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.

263402 lines
7.8MB

  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_Config.h *********/
  30. #ifndef __JUCE_CONFIG_JUCEHEADER__
  31. #define __JUCE_CONFIG_JUCEHEADER__
  32. /*
  33. This file contains macros that enable/disable various JUCE features.
  34. */
  35. /** The name of the namespace that all Juce classes and functions will be
  36. put inside. If this is not defined, no namespace will be used.
  37. */
  38. #ifndef JUCE_NAMESPACE
  39. #define JUCE_NAMESPACE juce
  40. #endif
  41. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  42. but if you define this value, you can override this can force it to be true or
  43. false.
  44. */
  45. #ifndef JUCE_FORCE_DEBUG
  46. //#define JUCE_FORCE_DEBUG 1
  47. #endif
  48. /** If this flag is enabled, the the jassert and jassertfalse macros will
  49. always use Logger::writeToLog() to write a message when an assertion happens.
  50. Enabling it will also leave this turned on in release builds. When it's disabled,
  51. however, the jassert and jassertfalse macros will not be compiled in a
  52. release build.
  53. @see jassert, jassertfalse, Logger
  54. */
  55. #ifndef JUCE_LOG_ASSERTIONS
  56. // #define JUCE_LOG_ASSERTIONS 1
  57. #endif
  58. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  59. which the ASIOAudioIODevice class can't be built. See the comments in the
  60. ASIOAudioIODevice class's header file for more info about this.
  61. (This only affects a Win32 build)
  62. */
  63. #ifndef JUCE_ASIO
  64. #define JUCE_ASIO 1
  65. #endif
  66. /** Comment out this macro to disable building of ALSA device support on Linux.
  67. */
  68. #ifndef JUCE_ALSA
  69. #define JUCE_ALSA 1
  70. #endif
  71. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  72. have the SDK installed.
  73. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  74. classes will be unavailable.
  75. On Windows, if you enable this, you'll need to have the QuickTime SDK
  76. installed, and its header files will need to be on your include path.
  77. */
  78. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  79. #define JUCE_QUICKTIME 1
  80. #endif
  81. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  82. have the appropriate headers and libraries available. If it's not enabled, the
  83. OpenGLComponent class will be unavailable.
  84. */
  85. #ifndef JUCE_OPENGL
  86. #define JUCE_OPENGL 1
  87. #endif
  88. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  89. If you're not going to need either of these formats, turn off the flags to
  90. avoid bloating your codebase with them.
  91. */
  92. #ifndef JUCE_USE_FLAC
  93. #define JUCE_USE_FLAC 1
  94. #endif
  95. #ifndef JUCE_USE_OGGVORBIS
  96. #define JUCE_USE_OGGVORBIS 1
  97. #endif
  98. /** This flag lets you enable support for CD-burning. You might want to disable
  99. it to build without the MS SDK under windows.
  100. */
  101. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  102. #define JUCE_USE_CDBURNER 1
  103. #endif
  104. /** Enabling this provides support for cameras, using the CameraDevice class
  105. */
  106. #if JUCE_QUICKTIME && ! defined (JUCE_USE_CAMERA)
  107. // #define JUCE_USE_CAMERA 1
  108. #endif
  109. /** Enabling this macro means that all regions that get repainted will have a coloured
  110. line drawn around them.
  111. This is handy if you're trying to optimise drawing, because it lets you easily see
  112. when anything is being repainted unnecessarily.
  113. */
  114. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  115. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  116. #endif
  117. /** Enable this under Linux to use Xinerama for multi-monitor support.
  118. */
  119. #ifndef JUCE_USE_XINERAMA
  120. #define JUCE_USE_XINERAMA 1
  121. #endif
  122. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  123. */
  124. #ifndef JUCE_USE_XSHM
  125. #define JUCE_USE_XSHM 1
  126. #endif
  127. /** Enabling this builds support for VST audio plugins.
  128. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  129. */
  130. #ifndef JUCE_PLUGINHOST_VST
  131. // #define JUCE_PLUGINHOST_VST 1
  132. #endif
  133. /** Enabling this builds support for AudioUnit audio plugins.
  134. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  135. */
  136. #ifndef JUCE_PLUGINHOST_AU
  137. // #define JUCE_PLUGINHOST_AU 1
  138. #endif
  139. /** Enabling this will avoid including any UI code in the build. This is handy for
  140. writing command-line utilities, e.g. on linux boxes which don't have some
  141. of the UI libraries installed.
  142. */
  143. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  144. //#define JUCE_ONLY_BUILD_CORE_LIBRARY 1
  145. #endif
  146. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  147. */
  148. #ifndef JUCE_WEB_BROWSER
  149. #define JUCE_WEB_BROWSER 1
  150. #endif
  151. /** Setting this allows the build to use old Carbon libraries that will be
  152. deprecated in newer versions of OSX. This is handy for some backwards-compatibility
  153. reasons.
  154. */
  155. #ifndef JUCE_SUPPORT_CARBON
  156. #define JUCE_SUPPORT_CARBON 1
  157. #endif
  158. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  159. codebase - you might need to use this if you're linking to some of these libraries
  160. yourself.
  161. */
  162. #ifndef JUCE_INCLUDE_ZLIB_CODE
  163. #define JUCE_INCLUDE_ZLIB_CODE 1
  164. #endif
  165. #ifndef JUCE_INCLUDE_FLAC_CODE
  166. #define JUCE_INCLUDE_FLAC_CODE 1
  167. #endif
  168. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  169. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  170. #endif
  171. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  172. #define JUCE_INCLUDE_PNGLIB_CODE 1
  173. #endif
  174. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  175. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  176. #endif
  177. /** Enable this to add extra memory-leak info to the new and delete operators.
  178. (Currently, this only affects Windows builds in debug mode).
  179. */
  180. #ifndef JUCE_CHECK_MEMORY_LEAKS
  181. #define JUCE_CHECK_MEMORY_LEAKS 1
  182. #endif
  183. /** Enable this to turn on juce's internal catching of exceptions.
  184. Turning it off will avoid any exception catching. With it on, all exceptions
  185. are passed to the JUCEApplication::unhandledException() callback for logging.
  186. */
  187. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  188. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  189. #endif
  190. /** If this macro is set, the Juce String class will use unicode as its
  191. internal representation. If it isn't set, it'll use ANSI.
  192. */
  193. #ifndef JUCE_STRINGS_ARE_UNICODE
  194. #define JUCE_STRINGS_ARE_UNICODE 1
  195. #endif
  196. #endif
  197. /********* End of inlined file: juce_Config.h *********/
  198. // FORCE_AMALGAMATOR_INCLUDE
  199. //==============================================================================
  200. #ifdef _WIN32
  201. /********* Start of inlined file: juce_win32_NativeIncludes.h *********/
  202. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  203. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  204. #ifndef STRICT
  205. #define STRICT 1
  206. #endif
  207. #undef WIN32_LEAN_AND_MEAN
  208. #define WIN32_LEAN_AND_MEAN 1
  209. #ifdef _MSC_VER
  210. #pragma warning (push)
  211. #pragma warning (disable : 4100 4201 4514 4312 4995)
  212. #endif
  213. #define _WIN32_WINNT 0x0500
  214. #define _UNICODE 1
  215. #define UNICODE 1
  216. #ifndef _WIN32_IE
  217. #define _WIN32_IE 0x0400
  218. #endif
  219. #include <windows.h>
  220. #include <windowsx.h>
  221. #include <commdlg.h>
  222. #include <shellapi.h>
  223. #include <mmsystem.h>
  224. #include <vfw.h>
  225. #include <tchar.h>
  226. #include <stddef.h>
  227. #include <ctime>
  228. #include <wininet.h>
  229. #include <nb30.h>
  230. #include <iphlpapi.h>
  231. #include <mapi.h>
  232. #include <float.h>
  233. #include <crtdbg.h>
  234. #include <process.h>
  235. #include <comutil.h>
  236. #include <Exdisp.h>
  237. #include <exdispid.h>
  238. #include <shlobj.h>
  239. #if JUCE_OPENGL
  240. #include <gl/gl.h>
  241. #endif
  242. #undef PACKED
  243. #if JUCE_ASIO
  244. /*
  245. This is very frustrating - we only need to use a handful of definitions from
  246. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  247. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  248. implementation...
  249. ..unfortunately that would break Steinberg's license agreement for use of
  250. their SDK, so I'm not allowed to do this.
  251. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  252. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  253. (see www.steinberg.net/Steinberg/Developers.asp).
  254. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  255. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  256. if you prefer). Make sure that your header search path will find the
  257. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  258. files are actually needed - so to simplify things, you could just copy
  259. these into your JUCE directory).
  260. If you're compiling and you get an error here because you don't have the
  261. ASIO SDK installed, you can disable ASIO support by commenting-out the
  262. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  263. */
  264. #include "iasiodrv.h"
  265. #endif
  266. #if JUCE_USE_CDBURNER
  267. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  268. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  269. flag in juce_Config.h to avoid these includes.
  270. */
  271. #include <imapi.h>
  272. #include <imapierror.h>
  273. #endif
  274. #if JUCE_USE_CAMERA
  275. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  276. Both of these files are provided in the normal Windows SDK, but some Microsoft plonker
  277. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK!
  278. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  279. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  280. .. which is a pathetic bodge, but a lot less hassle than installing the full DShow SDK.
  281. */
  282. #include <dshow.h>
  283. #include <qedit.h>
  284. #endif
  285. #if JUCE_QUICKTIME
  286. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  287. add its header directory to your include path.
  288. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  289. flag in juce_Config.h
  290. */
  291. #include <Movies.h>
  292. #include <QTML.h>
  293. #include <QuickTimeComponents.h>
  294. #include <MediaHandlers.h>
  295. #include <ImageCodec.h>
  296. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  297. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  298. your include search path to make these import statements work.
  299. */
  300. #import <QTOLibrary.dll>
  301. #import <QTOControl.dll>
  302. #endif
  303. #ifdef _MSC_VER
  304. #pragma warning (pop)
  305. #endif
  306. /** A simple COM smart pointer.
  307. Avoids having to include ATL just to get one of these.
  308. */
  309. template <class T>
  310. class ComSmartPtr
  311. {
  312. public:
  313. ComSmartPtr() throw() : p (0) {}
  314. ComSmartPtr (T* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  315. ComSmartPtr (const ComSmartPtr<T>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  316. ~ComSmartPtr() { if (p != 0) p->Release(); }
  317. operator T*() const throw() { return p; }
  318. T& operator*() const throw() { return *p; }
  319. T** operator&() throw() { return &p; }
  320. T* operator->() const throw() { return p; }
  321. T* operator= (T* const newP)
  322. {
  323. if (newP != 0)
  324. newP->AddRef();
  325. if (p != 0)
  326. p->Release();
  327. p = newP;
  328. return newP;
  329. }
  330. T* operator= (const ComSmartPtr<T>& newP) { return operator= (newP.p); }
  331. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext)
  332. {
  333. #ifndef __MINGW32__
  334. operator= (0);
  335. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof(T), (void**) &p);
  336. #else
  337. return S_FALSE;
  338. #endif
  339. }
  340. T* p;
  341. };
  342. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  343. /********* End of inlined file: juce_win32_NativeIncludes.h *********/
  344. #elif defined (LINUX)
  345. /********* Start of inlined file: juce_linux_NativeIncludes.h *********/
  346. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  347. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  348. /*
  349. This file wraps together all the linux-specific headers, so
  350. that we can include them all just once, and compile all our
  351. platform-specific stuff in one big lump, keeping it out of the
  352. way of the rest of the codebase.
  353. */
  354. #include <sched.h>
  355. #include <pthread.h>
  356. #include <sys/time.h>
  357. #include <errno.h>
  358. #include <sys/stat.h>
  359. #include <sys/dir.h>
  360. #include <sys/ptrace.h>
  361. #include <sys/vfs.h>
  362. #include <sys/wait.h>
  363. #include <fnmatch.h>
  364. #include <utime.h>
  365. #include <pwd.h>
  366. #include <fcntl.h>
  367. #include <dlfcn.h>
  368. #include <netdb.h>
  369. #include <arpa/inet.h>
  370. #include <netinet/in.h>
  371. #include <sys/types.h>
  372. #include <sys/ioctl.h>
  373. #include <sys/socket.h>
  374. #include <linux/if.h>
  375. #include <sys/sysinfo.h>
  376. #include <sys/file.h>
  377. #include <signal.h>
  378. /* Got a build error here? You'll need to install the freetype library...
  379. The name of the package to install is "libfreetype6-dev".
  380. */
  381. #include <ft2build.h>
  382. #include FT_FREETYPE_H
  383. #include <X11/Xlib.h>
  384. #include <X11/Xatom.h>
  385. #include <X11/Xresource.h>
  386. #include <X11/Xutil.h>
  387. #include <X11/Xmd.h>
  388. #include <X11/keysym.h>
  389. #include <X11/cursorfont.h>
  390. #if JUCE_USE_XINERAMA
  391. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  392. #include <X11/extensions/Xinerama.h>
  393. #endif
  394. #if JUCE_USE_XSHM
  395. #include <X11/extensions/XShm.h>
  396. #include <sys/shm.h>
  397. #include <sys/ipc.h>
  398. #endif
  399. #if JUCE_OPENGL
  400. /* Got an include error here?
  401. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  402. and "freeglut3-dev".
  403. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  404. want to disable it.
  405. */
  406. #include <GL/glx.h>
  407. #endif
  408. #undef KeyPress
  409. #if JUCE_ALSA
  410. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  411. not got your paths set up correctly to find its header files.
  412. The package you need to install to get ASLA support is "libasound2-dev".
  413. If you don't have the ALSA library and don't want to build Juce with audio support,
  414. just disable the JUCE_ALSA flag in juce_Config.h
  415. */
  416. #include <alsa/asoundlib.h>
  417. #endif
  418. #undef SIZEOF
  419. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  420. /********* End of inlined file: juce_linux_NativeIncludes.h *********/
  421. #else
  422. /********* Start of inlined file: juce_mac_NativeIncludes.h *********/
  423. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  424. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  425. /*
  426. This file wraps together all the mac-specific code, so that
  427. we can include all the native headers just once, and compile all our
  428. platform-specific stuff in one big lump, keeping it out of the way of
  429. the rest of the codebase.
  430. */
  431. #import <Cocoa/Cocoa.h>
  432. #import <CoreAudio/HostTime.h>
  433. #import <CoreAudio/AudioHardware.h>
  434. #import <CoreMIDI/MIDIServices.h>
  435. #import <QTKit/QTKit.h>
  436. #import <WebKit/WebKit.h>
  437. #import <DiscRecording/DiscRecording.h>
  438. #import <IOKit/IOKitLib.h>
  439. #import <IOKit/IOCFPlugIn.h>
  440. #import <IOKit/hid/IOHIDLib.h>
  441. #import <IOKit/hid/IOHIDKeys.h>
  442. #import <IOKit/network/IOEthernetInterface.h>
  443. #import <IOKit/network/IONetworkInterface.h>
  444. #import <IOKit/network/IOEthernetController.h>
  445. #import <IOKit/pwr_mgt/IOPMLib.h>
  446. #include <sys/sysctl.h>
  447. #include <sys/stat.h>
  448. #include <sys/dir.h>
  449. #include <sys/param.h>
  450. #include <sys/mount.h>
  451. #include <fnmatch.h>
  452. #include <utime.h>
  453. #include <dlfcn.h>
  454. #if MACOS_10_4_OR_EARLIER
  455. #include <GLUT/glut.h>
  456. typedef int NSInteger;
  457. typedef unsigned int NSUInteger;
  458. #endif
  459. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  460. /********* End of inlined file: juce_mac_NativeIncludes.h *********/
  461. #endif
  462. //==============================================================================
  463. #define DONT_SET_USING_JUCE_NAMESPACE 1
  464. #include "juce_amalgamated.h"
  465. #define NO_DUMMY_DECL
  466. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  467. #pragma warning (disable: 4309 4305)
  468. #endif
  469. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  470. BEGIN_JUCE_NAMESPACE
  471. /********* Start of inlined file: juce_mac_CarbonViewWrapperComponent.h *********/
  472. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  473. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  474. /**
  475. Creates a floating carbon window that can be used to hold a carbon UI.
  476. This is a handy class that's designed to be inlined where needed, e.g.
  477. in the audio plugin hosting code.
  478. */
  479. class CarbonViewWrapperComponent : public Component,
  480. public ComponentMovementWatcher,
  481. public Timer
  482. {
  483. public:
  484. CarbonViewWrapperComponent()
  485. : ComponentMovementWatcher (this),
  486. wrapperWindow (0),
  487. embeddedView (0),
  488. recursiveResize (false)
  489. {
  490. }
  491. virtual ~CarbonViewWrapperComponent()
  492. {
  493. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  494. }
  495. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  496. virtual void removeView (HIViewRef embeddedView) = 0;
  497. virtual void mouseDown (int x, int y) {}
  498. virtual void paint() {}
  499. virtual bool getEmbeddedViewSize (int& w, int& h)
  500. {
  501. if (embeddedView == 0)
  502. return false;
  503. HIRect bounds;
  504. HIViewGetBounds (embeddedView, &bounds);
  505. w = jmax (1, roundFloatToInt (bounds.size.width));
  506. h = jmax (1, roundFloatToInt (bounds.size.height));
  507. return true;
  508. }
  509. void createWindow()
  510. {
  511. if (wrapperWindow == 0)
  512. {
  513. Rect r;
  514. r.left = getScreenX();
  515. r.top = getScreenY();
  516. r.right = r.left + getWidth();
  517. r.bottom = r.top + getHeight();
  518. CreateNewWindow (kDocumentWindowClass,
  519. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  520. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  521. &r, &wrapperWindow);
  522. jassert (wrapperWindow != 0);
  523. if (wrapperWindow == 0)
  524. return;
  525. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  526. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  527. [ownerWindow addChildWindow: carbonWindow
  528. ordered: NSWindowAbove];
  529. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  530. EventTypeSpec windowEventTypes[] = { { kEventClassWindow, kEventWindowGetClickActivation },
  531. { kEventClassWindow, kEventWindowHandleDeactivate } };
  532. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  533. InstallWindowEventHandler (wrapperWindow, upp,
  534. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  535. windowEventTypes, this, &eventHandlerRef);
  536. setOurSizeToEmbeddedViewSize();
  537. setEmbeddedWindowToOurSize();
  538. creationTime = Time::getCurrentTime();
  539. }
  540. }
  541. void deleteWindow()
  542. {
  543. removeView (embeddedView);
  544. embeddedView = 0;
  545. if (wrapperWindow != 0)
  546. {
  547. RemoveEventHandler (eventHandlerRef);
  548. DisposeWindow (wrapperWindow);
  549. wrapperWindow = 0;
  550. }
  551. }
  552. void setOurSizeToEmbeddedViewSize()
  553. {
  554. int w, h;
  555. if (getEmbeddedViewSize (w, h))
  556. {
  557. if (w != getWidth() || h != getHeight())
  558. {
  559. startTimer (50);
  560. setSize (w, h);
  561. if (getParentComponent() != 0)
  562. getParentComponent()->setSize (w, h);
  563. }
  564. else
  565. {
  566. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  567. }
  568. }
  569. else
  570. {
  571. stopTimer();
  572. }
  573. }
  574. void setEmbeddedWindowToOurSize()
  575. {
  576. if (! recursiveResize)
  577. {
  578. recursiveResize = true;
  579. if (embeddedView != 0)
  580. {
  581. HIRect r;
  582. r.origin.x = 0;
  583. r.origin.y = 0;
  584. r.size.width = (float) getWidth();
  585. r.size.height = (float) getHeight();
  586. HIViewSetFrame (embeddedView, &r);
  587. }
  588. if (wrapperWindow != 0)
  589. {
  590. Rect wr;
  591. wr.left = getScreenX();
  592. wr.top = getScreenY();
  593. wr.right = wr.left + getWidth();
  594. wr.bottom = wr.top + getHeight();
  595. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  596. ShowWindow (wrapperWindow);
  597. }
  598. recursiveResize = false;
  599. }
  600. }
  601. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  602. {
  603. setEmbeddedWindowToOurSize();
  604. }
  605. void componentPeerChanged()
  606. {
  607. deleteWindow();
  608. createWindow();
  609. }
  610. void componentVisibilityChanged (Component&)
  611. {
  612. if (isShowing())
  613. createWindow();
  614. else
  615. deleteWindow();
  616. setEmbeddedWindowToOurSize();
  617. }
  618. void timerCallback()
  619. {
  620. setOurSizeToEmbeddedViewSize();
  621. // To avoid strange overpainting problems when the UI is first opened, we'll
  622. // repaint it a few times during the first second that it's on-screen..
  623. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  624. HIViewSetNeedsDisplay (embeddedView, true);
  625. }
  626. OSStatus carbonEventHandler (EventHandlerCallRef nextHandlerRef,
  627. EventRef event)
  628. {
  629. switch (GetEventKind (event))
  630. {
  631. case kEventWindowHandleDeactivate:
  632. ActivateWindow (wrapperWindow, TRUE);
  633. break;
  634. case kEventWindowGetClickActivation:
  635. {
  636. getTopLevelComponent()->toFront (false);
  637. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  638. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  639. sizeof (ClickActivationResult), &howToHandleClick);
  640. HIViewSetNeedsDisplay (embeddedView, true);
  641. }
  642. break;
  643. }
  644. return noErr;
  645. }
  646. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  647. EventRef event, void* userData)
  648. {
  649. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  650. }
  651. protected:
  652. WindowRef wrapperWindow;
  653. HIViewRef embeddedView;
  654. bool recursiveResize;
  655. Time creationTime;
  656. EventHandlerRef eventHandlerRef;
  657. };
  658. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  659. /********* End of inlined file: juce_mac_CarbonViewWrapperComponent.h *********/
  660. END_JUCE_NAMESPACE
  661. #endif
  662. #define JUCE_AMALGAMATED_TEMPLATE 1
  663. //==============================================================================
  664. /********* Start of inlined file: juce_FileLogger.cpp *********/
  665. BEGIN_JUCE_NAMESPACE
  666. FileLogger::FileLogger (const File& logFile_,
  667. const String& welcomeMessage,
  668. const int maxInitialFileSizeBytes)
  669. : logFile (logFile_)
  670. {
  671. if (maxInitialFileSizeBytes >= 0)
  672. trimFileSize (maxInitialFileSizeBytes);
  673. if (! logFile_.exists())
  674. {
  675. // do this so that the parent directories get created..
  676. logFile_.create();
  677. }
  678. logStream = logFile_.createOutputStream (256);
  679. jassert (logStream != 0);
  680. String welcome;
  681. welcome << "\r\n**********************************************************\r\n"
  682. << welcomeMessage
  683. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  684. << "\r\n";
  685. logMessage (welcome);
  686. }
  687. FileLogger::~FileLogger()
  688. {
  689. deleteAndZero (logStream);
  690. }
  691. void FileLogger::logMessage (const String& message)
  692. {
  693. if (logStream != 0)
  694. {
  695. Logger::outputDebugString (message);
  696. const ScopedLock sl (logLock);
  697. (*logStream) << message << T("\r\n");
  698. logStream->flush();
  699. }
  700. }
  701. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  702. {
  703. if (maxFileSizeBytes <= 0)
  704. {
  705. logFile.deleteFile();
  706. }
  707. else
  708. {
  709. const int64 fileSize = logFile.getSize();
  710. if (fileSize > maxFileSizeBytes)
  711. {
  712. FileInputStream* const in = logFile.createInputStream();
  713. jassert (in != 0);
  714. if (in != 0)
  715. {
  716. in->setPosition (fileSize - maxFileSizeBytes);
  717. String content;
  718. {
  719. MemoryBlock contentToSave;
  720. contentToSave.setSize (maxFileSizeBytes + 4);
  721. contentToSave.fillWith (0);
  722. in->read (contentToSave.getData(), maxFileSizeBytes);
  723. delete in;
  724. content = contentToSave.toString();
  725. }
  726. int newStart = 0;
  727. while (newStart < fileSize
  728. && content[newStart] != '\n'
  729. && content[newStart] != '\r')
  730. ++newStart;
  731. logFile.deleteFile();
  732. logFile.appendText (content.substring (newStart), false, false);
  733. }
  734. }
  735. }
  736. }
  737. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  738. const String& logFileName,
  739. const String& welcomeMessage,
  740. const int maxInitialFileSizeBytes)
  741. {
  742. #if JUCE_MAC
  743. File logFile ("~/Library/Logs");
  744. logFile = logFile.getChildFile (logFileName);
  745. #else
  746. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  747. if (logFile.isDirectory())
  748. {
  749. logFile = logFile.getChildFile (logFileSubDirectoryName)
  750. .getChildFile (logFileName);
  751. }
  752. #endif
  753. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  754. }
  755. END_JUCE_NAMESPACE
  756. /********* End of inlined file: juce_FileLogger.cpp *********/
  757. /********* Start of inlined file: juce_Logger.cpp *********/
  758. BEGIN_JUCE_NAMESPACE
  759. Logger::Logger()
  760. {
  761. }
  762. Logger::~Logger()
  763. {
  764. }
  765. static Logger* currentLogger = 0;
  766. void Logger::setCurrentLogger (Logger* const newLogger,
  767. const bool deleteOldLogger)
  768. {
  769. Logger* const oldLogger = currentLogger;
  770. currentLogger = newLogger;
  771. if (deleteOldLogger && (oldLogger != 0))
  772. delete oldLogger;
  773. }
  774. void Logger::writeToLog (const String& message)
  775. {
  776. if (currentLogger != 0)
  777. currentLogger->logMessage (message);
  778. else
  779. outputDebugString (message);
  780. }
  781. #if JUCE_LOG_ASSERTIONS
  782. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  783. {
  784. String m ("JUCE Assertion failure in ");
  785. m << filename << ", line " << lineNum;
  786. Logger::writeToLog (m);
  787. }
  788. #endif
  789. END_JUCE_NAMESPACE
  790. /********* End of inlined file: juce_Logger.cpp *********/
  791. /********* Start of inlined file: juce_Random.cpp *********/
  792. BEGIN_JUCE_NAMESPACE
  793. Random::Random (const int64 seedValue) throw()
  794. : seed (seedValue)
  795. {
  796. }
  797. Random::~Random() throw()
  798. {
  799. }
  800. void Random::setSeed (const int64 newSeed) throw()
  801. {
  802. seed = newSeed;
  803. }
  804. void Random::setSeedRandomly()
  805. {
  806. Random r1 (Time::getMillisecondCounter());
  807. Random r2 (Time::getHighResolutionTicks());
  808. Random r3 (Time::getHighResolutionTicksPerSecond());
  809. Random r4 (Time::currentTimeMillis());
  810. setSeed (nextInt64() ^ r1.nextInt64() ^ r2.nextInt64()
  811. ^ r3.nextInt64() ^ r4.nextInt64());
  812. }
  813. int Random::nextInt() throw()
  814. {
  815. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  816. return (int) (seed >> 16);
  817. }
  818. int Random::nextInt (const int maxValue) throw()
  819. {
  820. jassert (maxValue > 0);
  821. return (nextInt() & 0x7fffffff) % maxValue;
  822. }
  823. int64 Random::nextInt64() throw()
  824. {
  825. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  826. }
  827. bool Random::nextBool() throw()
  828. {
  829. return (nextInt() & 0x80000000) != 0;
  830. }
  831. float Random::nextFloat() throw()
  832. {
  833. return ((uint32) nextInt()) / (float) 0xffffffff;
  834. }
  835. double Random::nextDouble() throw()
  836. {
  837. return ((uint32) nextInt()) / (double) 0xffffffff;
  838. }
  839. const BitArray Random::nextLargeNumber (const BitArray& maximumValue) throw()
  840. {
  841. BitArray n;
  842. do
  843. {
  844. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  845. }
  846. while (n.compare (maximumValue) >= 0);
  847. return n;
  848. }
  849. void Random::fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw()
  850. {
  851. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  852. while ((startBit & 31) != 0 && numBits > 0)
  853. {
  854. arrayToChange.setBit (startBit++, nextBool());
  855. --numBits;
  856. }
  857. while (numBits >= 32)
  858. {
  859. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  860. startBit += 32;
  861. numBits -= 32;
  862. }
  863. while (--numBits >= 0)
  864. arrayToChange.setBit (startBit + numBits, nextBool());
  865. }
  866. Random& Random::getSystemRandom() throw()
  867. {
  868. static Random sysRand (1);
  869. return sysRand;
  870. }
  871. END_JUCE_NAMESPACE
  872. /********* End of inlined file: juce_Random.cpp *********/
  873. /********* Start of inlined file: juce_RelativeTime.cpp *********/
  874. BEGIN_JUCE_NAMESPACE
  875. RelativeTime::RelativeTime (const double seconds_) throw()
  876. : seconds (seconds_)
  877. {
  878. }
  879. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  880. : seconds (other.seconds)
  881. {
  882. }
  883. RelativeTime::~RelativeTime() throw()
  884. {
  885. }
  886. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  887. {
  888. return RelativeTime (milliseconds * 0.001);
  889. }
  890. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  891. {
  892. return RelativeTime (milliseconds * 0.001);
  893. }
  894. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  895. {
  896. return RelativeTime (numberOfMinutes * 60.0);
  897. }
  898. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  899. {
  900. return RelativeTime (numberOfHours * (60.0 * 60.0));
  901. }
  902. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  903. {
  904. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  905. }
  906. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  907. {
  908. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  909. }
  910. int64 RelativeTime::inMilliseconds() const throw()
  911. {
  912. return (int64)(seconds * 1000.0);
  913. }
  914. double RelativeTime::inMinutes() const throw()
  915. {
  916. return seconds / 60.0;
  917. }
  918. double RelativeTime::inHours() const throw()
  919. {
  920. return seconds / (60.0 * 60.0);
  921. }
  922. double RelativeTime::inDays() const throw()
  923. {
  924. return seconds / (60.0 * 60.0 * 24.0);
  925. }
  926. double RelativeTime::inWeeks() const throw()
  927. {
  928. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  929. }
  930. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  931. {
  932. if (seconds < 0.001 && seconds > -0.001)
  933. return returnValueForZeroTime;
  934. String result;
  935. if (seconds < 0)
  936. result = T("-");
  937. int fieldsShown = 0;
  938. int n = abs ((int) inWeeks());
  939. if (n > 0)
  940. {
  941. result << n << ((n == 1) ? TRANS(" week ")
  942. : TRANS(" weeks "));
  943. ++fieldsShown;
  944. }
  945. n = abs ((int) inDays()) % 7;
  946. if (n > 0)
  947. {
  948. result << n << ((n == 1) ? TRANS(" day ")
  949. : TRANS(" days "));
  950. ++fieldsShown;
  951. }
  952. if (fieldsShown < 2)
  953. {
  954. n = abs ((int) inHours()) % 24;
  955. if (n > 0)
  956. {
  957. result << n << ((n == 1) ? TRANS(" hr ")
  958. : TRANS(" hrs "));
  959. ++fieldsShown;
  960. }
  961. if (fieldsShown < 2)
  962. {
  963. n = abs ((int) inMinutes()) % 60;
  964. if (n > 0)
  965. {
  966. result << n << ((n == 1) ? TRANS(" min ")
  967. : TRANS(" mins "));
  968. ++fieldsShown;
  969. }
  970. if (fieldsShown < 2)
  971. {
  972. n = abs ((int) inSeconds()) % 60;
  973. if (n > 0)
  974. {
  975. result << n << ((n == 1) ? TRANS(" sec ")
  976. : TRANS(" secs "));
  977. ++fieldsShown;
  978. }
  979. if (fieldsShown < 1)
  980. {
  981. n = abs ((int) inMilliseconds()) % 1000;
  982. if (n > 0)
  983. {
  984. result << n << TRANS(" ms");
  985. ++fieldsShown;
  986. }
  987. }
  988. }
  989. }
  990. }
  991. return result.trimEnd();
  992. }
  993. const RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  994. {
  995. seconds = other.seconds;
  996. return *this;
  997. }
  998. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  999. {
  1000. return seconds == other.seconds;
  1001. }
  1002. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  1003. {
  1004. return seconds != other.seconds;
  1005. }
  1006. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  1007. {
  1008. return seconds > other.seconds;
  1009. }
  1010. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1011. {
  1012. return seconds < other.seconds;
  1013. }
  1014. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1015. {
  1016. return seconds >= other.seconds;
  1017. }
  1018. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1019. {
  1020. return seconds <= other.seconds;
  1021. }
  1022. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1023. {
  1024. return RelativeTime (seconds + timeToAdd.seconds);
  1025. }
  1026. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1027. {
  1028. return RelativeTime (seconds - timeToSubtract.seconds);
  1029. }
  1030. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1031. {
  1032. return RelativeTime (seconds + secondsToAdd);
  1033. }
  1034. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1035. {
  1036. return RelativeTime (seconds - secondsToSubtract);
  1037. }
  1038. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1039. {
  1040. seconds += timeToAdd.seconds;
  1041. return *this;
  1042. }
  1043. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1044. {
  1045. seconds -= timeToSubtract.seconds;
  1046. return *this;
  1047. }
  1048. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1049. {
  1050. seconds += secondsToAdd;
  1051. return *this;
  1052. }
  1053. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1054. {
  1055. seconds -= secondsToSubtract;
  1056. return *this;
  1057. }
  1058. END_JUCE_NAMESPACE
  1059. /********* End of inlined file: juce_RelativeTime.cpp *********/
  1060. /********* Start of inlined file: juce_SystemStats.cpp *********/
  1061. BEGIN_JUCE_NAMESPACE
  1062. void juce_initialiseStrings();
  1063. const String SystemStats::getJUCEVersion() throw()
  1064. {
  1065. return "JUCE v" + String (JUCE_MAJOR_VERSION) + "." + String (JUCE_MINOR_VERSION);
  1066. }
  1067. static bool juceInitialisedNonGUI = false;
  1068. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1069. {
  1070. if (! juceInitialisedNonGUI)
  1071. {
  1072. #if JUCE_MAC
  1073. const ScopedAutoReleasePool pool;
  1074. #endif
  1075. #ifdef JUCE_DEBUG
  1076. // Some simple test code to keep an eye on things and make sure these functions
  1077. // work ok on all platforms. Let me know if any of these assertions fail!
  1078. int n = 1;
  1079. atomicIncrement (n);
  1080. jassert (atomicIncrementAndReturn (n) == 3);
  1081. atomicDecrement (n);
  1082. jassert (atomicDecrementAndReturn (n) == 1);
  1083. jassert (swapByteOrder ((uint32) 0x11223344) == 0x44332211);
  1084. // quick test to make sure the run-time lib doesn't crash on freeing a null-pointer.
  1085. SystemStats* nullPointer = 0;
  1086. juce_free (nullPointer);
  1087. delete[] nullPointer;
  1088. delete nullPointer;
  1089. #endif
  1090. // Now the real initialisation..
  1091. juceInitialisedNonGUI = true;
  1092. DBG (SystemStats::getJUCEVersion());
  1093. Random::getSystemRandom().setSeedRandomly(); // (calling this more than once improves its randomness)
  1094. juce_initialiseStrings();
  1095. SystemStats::initialiseStats();
  1096. Random::getSystemRandom().setSeedRandomly(); // (calling this more than once improves its randomness)
  1097. }
  1098. }
  1099. #if JUCE_WIN32
  1100. // This is imported from the sockets code..
  1101. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  1102. extern juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib;
  1103. #endif
  1104. #if JUCE_DEBUG
  1105. extern void juce_CheckForDanglingStreams();
  1106. #endif
  1107. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1108. {
  1109. if (juceInitialisedNonGUI)
  1110. {
  1111. #if JUCE_MAC
  1112. const ScopedAutoReleasePool pool;
  1113. #endif
  1114. #if JUCE_WIN32
  1115. // need to shut down sockets if they were used..
  1116. if (juce_CloseWin32SocketLib != 0)
  1117. (*juce_CloseWin32SocketLib)();
  1118. #endif
  1119. LocalisedStrings::setCurrentMappings (0);
  1120. Thread::stopAllThreads (3000);
  1121. #if JUCE_DEBUG
  1122. juce_CheckForDanglingStreams();
  1123. #endif
  1124. juceInitialisedNonGUI = false;
  1125. }
  1126. }
  1127. #ifdef JUCE_DLL
  1128. void* juce_Malloc (const int size)
  1129. {
  1130. return malloc (size);
  1131. }
  1132. void* juce_Calloc (const int size)
  1133. {
  1134. return calloc (1, size);
  1135. }
  1136. void* juce_Realloc (void* const block, const int size)
  1137. {
  1138. return realloc (block, size);
  1139. }
  1140. void juce_Free (void* const block)
  1141. {
  1142. free (block);
  1143. }
  1144. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1145. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1146. {
  1147. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1148. }
  1149. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1150. {
  1151. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1152. }
  1153. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1154. {
  1155. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1156. }
  1157. void juce_DebugFree (void* const block)
  1158. {
  1159. _free_dbg (block, _NORMAL_BLOCK);
  1160. }
  1161. #endif
  1162. #endif
  1163. END_JUCE_NAMESPACE
  1164. /********* End of inlined file: juce_SystemStats.cpp *********/
  1165. /********* Start of inlined file: juce_Time.cpp *********/
  1166. #ifdef _MSC_VER
  1167. #pragma warning (disable: 4514)
  1168. #pragma warning (push)
  1169. #endif
  1170. #ifndef JUCE_WIN32
  1171. #include <sys/time.h>
  1172. #else
  1173. #include <ctime>
  1174. #endif
  1175. #include <sys/timeb.h>
  1176. BEGIN_JUCE_NAMESPACE
  1177. #ifdef _MSC_VER
  1178. #pragma warning (pop)
  1179. #ifdef _INC_TIME_INL
  1180. #define USE_NEW_SECURE_TIME_FNS
  1181. #endif
  1182. #endif
  1183. static void millisToLocal (const int64 millis, struct tm& result) throw()
  1184. {
  1185. const int64 seconds = millis / 1000;
  1186. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1187. {
  1188. // use extended maths for dates beyond 1970 to 2037..
  1189. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1190. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1191. const int days = (int) (jdm / literal64bit (86400));
  1192. const int a = 32044 + days;
  1193. const int b = (4 * a + 3) / 146097;
  1194. const int c = a - (b * 146097) / 4;
  1195. const int d = (4 * c + 3) / 1461;
  1196. const int e = c - (d * 1461) / 4;
  1197. const int m = (5 * e + 2) / 153;
  1198. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1199. result.tm_mon = m + 2 - 12 * (m / 10);
  1200. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1201. result.tm_wday = (days + 1) % 7;
  1202. result.tm_yday = -1;
  1203. int t = (int) (jdm % literal64bit (86400));
  1204. result.tm_hour = t / 3600;
  1205. t %= 3600;
  1206. result.tm_min = t / 60;
  1207. result.tm_sec = t % 60;
  1208. result.tm_isdst = -1;
  1209. }
  1210. else
  1211. {
  1212. time_t now = (time_t) (seconds);
  1213. #if JUCE_WIN32
  1214. #ifdef USE_NEW_SECURE_TIME_FNS
  1215. if (now >= 0 && now <= 0x793406fff)
  1216. localtime_s (&result, &now);
  1217. else
  1218. zeromem (&result, sizeof (result));
  1219. #else
  1220. result = *localtime (&now);
  1221. #endif
  1222. #else
  1223. // more thread-safe
  1224. localtime_r (&now, &result);
  1225. #endif
  1226. }
  1227. }
  1228. Time::Time() throw()
  1229. : millisSinceEpoch (0)
  1230. {
  1231. }
  1232. Time::Time (const Time& other) throw()
  1233. : millisSinceEpoch (other.millisSinceEpoch)
  1234. {
  1235. }
  1236. Time::Time (const int64 ms) throw()
  1237. : millisSinceEpoch (ms)
  1238. {
  1239. }
  1240. Time::Time (const int year,
  1241. const int month,
  1242. const int day,
  1243. const int hours,
  1244. const int minutes,
  1245. const int seconds,
  1246. const int milliseconds,
  1247. const bool useLocalTime) throw()
  1248. {
  1249. jassert (year > 100); // year must be a 4-digit version
  1250. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1251. {
  1252. // use extended maths for dates beyond 1970 to 2037..
  1253. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1254. : 0;
  1255. const int a = (13 - month) / 12;
  1256. const int y = year + 4800 - a;
  1257. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1258. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1259. - 32045;
  1260. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1261. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1262. + milliseconds;
  1263. }
  1264. else
  1265. {
  1266. struct tm t;
  1267. t.tm_year = year - 1900;
  1268. t.tm_mon = month;
  1269. t.tm_mday = day;
  1270. t.tm_hour = hours;
  1271. t.tm_min = minutes;
  1272. t.tm_sec = seconds;
  1273. t.tm_isdst = -1;
  1274. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1275. if (millisSinceEpoch < 0)
  1276. millisSinceEpoch = 0;
  1277. else
  1278. millisSinceEpoch += milliseconds;
  1279. }
  1280. }
  1281. Time::~Time() throw()
  1282. {
  1283. }
  1284. const Time& Time::operator= (const Time& other) throw()
  1285. {
  1286. millisSinceEpoch = other.millisSinceEpoch;
  1287. return *this;
  1288. }
  1289. int64 Time::currentTimeMillis() throw()
  1290. {
  1291. static uint32 lastCounterResult = 0xffffffff;
  1292. static int64 correction = 0;
  1293. const uint32 now = getMillisecondCounter();
  1294. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1295. if (now < lastCounterResult)
  1296. {
  1297. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1298. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1299. {
  1300. // get the time once using normal library calls, and store the difference needed to
  1301. // turn the millisecond counter into a real time.
  1302. #if JUCE_WIN32
  1303. struct _timeb t;
  1304. #ifdef USE_NEW_SECURE_TIME_FNS
  1305. _ftime_s (&t);
  1306. #else
  1307. _ftime (&t);
  1308. #endif
  1309. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1310. #else
  1311. struct timeval tv;
  1312. struct timezone tz;
  1313. gettimeofday (&tv, &tz);
  1314. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1315. #endif
  1316. }
  1317. }
  1318. lastCounterResult = now;
  1319. return correction + now;
  1320. }
  1321. uint32 juce_millisecondsSinceStartup() throw();
  1322. static uint32 lastMSCounterValue = 0;
  1323. uint32 Time::getMillisecondCounter() throw()
  1324. {
  1325. const uint32 now = juce_millisecondsSinceStartup();
  1326. if (now < lastMSCounterValue)
  1327. {
  1328. // in multi-threaded apps this might be called concurrently, so
  1329. // make sure that our last counter value only increases and doesn't
  1330. // go backwards..
  1331. if (now < lastMSCounterValue - 1000)
  1332. lastMSCounterValue = now;
  1333. }
  1334. else
  1335. {
  1336. lastMSCounterValue = now;
  1337. }
  1338. return now;
  1339. }
  1340. uint32 Time::getApproximateMillisecondCounter() throw()
  1341. {
  1342. jassert (lastMSCounterValue != 0);
  1343. return lastMSCounterValue;
  1344. }
  1345. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1346. {
  1347. for (;;)
  1348. {
  1349. const uint32 now = getMillisecondCounter();
  1350. if (now >= targetTime)
  1351. break;
  1352. const int toWait = targetTime - now;
  1353. if (toWait > 2)
  1354. {
  1355. Thread::sleep (jmin (20, toWait >> 1));
  1356. }
  1357. else
  1358. {
  1359. // xxx should consider using mutex_pause on the mac as it apparently
  1360. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1361. for (int i = 10; --i >= 0;)
  1362. Thread::yield();
  1363. }
  1364. }
  1365. }
  1366. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1367. {
  1368. return ticks / (double) getHighResolutionTicksPerSecond();
  1369. }
  1370. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1371. {
  1372. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1373. }
  1374. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1375. {
  1376. return Time (currentTimeMillis());
  1377. }
  1378. const String Time::toString (const bool includeDate,
  1379. const bool includeTime,
  1380. const bool includeSeconds,
  1381. const bool use24HourClock) const throw()
  1382. {
  1383. String result;
  1384. if (includeDate)
  1385. {
  1386. result << getDayOfMonth() << ' '
  1387. << getMonthName (true) << ' '
  1388. << getYear();
  1389. if (includeTime)
  1390. result << ' ';
  1391. }
  1392. if (includeTime)
  1393. {
  1394. if (includeSeconds)
  1395. {
  1396. result += String::formatted (T("%d:%02d:%02d "),
  1397. (use24HourClock) ? getHours()
  1398. : getHoursInAmPmFormat(),
  1399. getMinutes(),
  1400. getSeconds());
  1401. }
  1402. else
  1403. {
  1404. result += String::formatted (T("%d.%02d"),
  1405. (use24HourClock) ? getHours()
  1406. : getHoursInAmPmFormat(),
  1407. getMinutes());
  1408. }
  1409. if (! use24HourClock)
  1410. result << (isAfternoon() ? "pm" : "am");
  1411. }
  1412. return result.trimEnd();
  1413. }
  1414. const String Time::formatted (const tchar* const format) const throw()
  1415. {
  1416. tchar buffer[80];
  1417. struct tm t;
  1418. millisToLocal (millisSinceEpoch, t);
  1419. if (CharacterFunctions::ftime (buffer, 79, format, &t) <= 0)
  1420. {
  1421. int bufferSize = 128;
  1422. for (;;)
  1423. {
  1424. MemoryBlock mb (bufferSize * sizeof (tchar));
  1425. tchar* const b = (tchar*) mb.getData();
  1426. if (CharacterFunctions::ftime (b, bufferSize, format, &t) > 0)
  1427. return String (b);
  1428. bufferSize += 128;
  1429. }
  1430. }
  1431. return String (buffer);
  1432. }
  1433. int Time::getYear() const throw()
  1434. {
  1435. struct tm t;
  1436. millisToLocal (millisSinceEpoch, t);
  1437. return t.tm_year + 1900;
  1438. }
  1439. int Time::getMonth() const throw()
  1440. {
  1441. struct tm t;
  1442. millisToLocal (millisSinceEpoch, t);
  1443. return t.tm_mon;
  1444. }
  1445. int Time::getDayOfMonth() const throw()
  1446. {
  1447. struct tm t;
  1448. millisToLocal (millisSinceEpoch, t);
  1449. return t.tm_mday;
  1450. }
  1451. int Time::getDayOfWeek() const throw()
  1452. {
  1453. struct tm t;
  1454. millisToLocal (millisSinceEpoch, t);
  1455. return t.tm_wday;
  1456. }
  1457. int Time::getHours() const throw()
  1458. {
  1459. struct tm t;
  1460. millisToLocal (millisSinceEpoch, t);
  1461. return t.tm_hour;
  1462. }
  1463. int Time::getHoursInAmPmFormat() const throw()
  1464. {
  1465. const int hours = getHours();
  1466. if (hours == 0)
  1467. return 12;
  1468. else if (hours <= 12)
  1469. return hours;
  1470. else
  1471. return hours - 12;
  1472. }
  1473. bool Time::isAfternoon() const throw()
  1474. {
  1475. return getHours() >= 12;
  1476. }
  1477. static int extendedModulo (const int64 value, const int modulo) throw()
  1478. {
  1479. return (int) (value >= 0 ? (value % modulo)
  1480. : (value - ((value / modulo) + 1) * modulo));
  1481. }
  1482. int Time::getMinutes() const throw()
  1483. {
  1484. struct tm t;
  1485. millisToLocal (millisSinceEpoch, t);
  1486. return t.tm_min;
  1487. }
  1488. int Time::getSeconds() const throw()
  1489. {
  1490. return extendedModulo (millisSinceEpoch / 1000, 60);
  1491. }
  1492. int Time::getMilliseconds() const throw()
  1493. {
  1494. return extendedModulo (millisSinceEpoch, 1000);
  1495. }
  1496. bool Time::isDaylightSavingTime() const throw()
  1497. {
  1498. struct tm t;
  1499. millisToLocal (millisSinceEpoch, t);
  1500. return t.tm_isdst != 0;
  1501. }
  1502. const String Time::getTimeZone() const throw()
  1503. {
  1504. String zone[2];
  1505. #if JUCE_WIN32
  1506. _tzset();
  1507. #ifdef USE_NEW_SECURE_TIME_FNS
  1508. {
  1509. char name [128];
  1510. size_t length;
  1511. for (int i = 0; i < 2; ++i)
  1512. {
  1513. zeromem (name, sizeof (name));
  1514. _get_tzname (&length, name, 127, i);
  1515. zone[i] = name;
  1516. }
  1517. }
  1518. #else
  1519. const char** const zonePtr = (const char**) _tzname;
  1520. zone[0] = zonePtr[0];
  1521. zone[1] = zonePtr[1];
  1522. #endif
  1523. #else
  1524. tzset();
  1525. const char** const zonePtr = (const char**) tzname;
  1526. zone[0] = zonePtr[0];
  1527. zone[1] = zonePtr[1];
  1528. #endif
  1529. if (isDaylightSavingTime())
  1530. {
  1531. zone[0] = zone[1];
  1532. if (zone[0].length() > 3
  1533. && zone[0].containsIgnoreCase (T("daylight"))
  1534. && zone[0].contains (T("GMT")))
  1535. zone[0] = "BST";
  1536. }
  1537. return zone[0].substring (0, 3);
  1538. }
  1539. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1540. {
  1541. return getMonthName (getMonth(), threeLetterVersion);
  1542. }
  1543. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1544. {
  1545. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1546. }
  1547. const String Time::getMonthName (int monthNumber,
  1548. const bool threeLetterVersion) throw()
  1549. {
  1550. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1551. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1552. monthNumber %= 12;
  1553. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1554. : longMonthNames [monthNumber]);
  1555. }
  1556. const String Time::getWeekdayName (int day,
  1557. const bool threeLetterVersion) throw()
  1558. {
  1559. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1560. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1561. day %= 7;
  1562. return TRANS (threeLetterVersion ? shortDayNames [day]
  1563. : longDayNames [day]);
  1564. }
  1565. END_JUCE_NAMESPACE
  1566. /********* End of inlined file: juce_Time.cpp *********/
  1567. /********* Start of inlined file: juce_BitArray.cpp *********/
  1568. BEGIN_JUCE_NAMESPACE
  1569. BitArray::BitArray() throw()
  1570. : numValues (4),
  1571. highestBit (-1),
  1572. negative (false)
  1573. {
  1574. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1575. }
  1576. BitArray::BitArray (const int value) throw()
  1577. : numValues (4),
  1578. highestBit (31),
  1579. negative (value < 0)
  1580. {
  1581. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1582. values[0] = abs (value);
  1583. highestBit = getHighestBit();
  1584. }
  1585. BitArray::BitArray (int64 value) throw()
  1586. : numValues (4),
  1587. highestBit (63),
  1588. negative (value < 0)
  1589. {
  1590. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1591. if (value < 0)
  1592. value = -value;
  1593. values[0] = (unsigned int) value;
  1594. values[1] = (unsigned int) (value >> 32);
  1595. highestBit = getHighestBit();
  1596. }
  1597. BitArray::BitArray (const unsigned int value) throw()
  1598. : numValues (4),
  1599. highestBit (31),
  1600. negative (false)
  1601. {
  1602. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1603. values[0] = value;
  1604. highestBit = getHighestBit();
  1605. }
  1606. BitArray::BitArray (const BitArray& other) throw()
  1607. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1608. highestBit (other.getHighestBit()),
  1609. negative (other.negative)
  1610. {
  1611. const int bytes = sizeof (unsigned int) * (numValues + 1);
  1612. values = (unsigned int*) juce_malloc (bytes);
  1613. memcpy (values, other.values, bytes);
  1614. }
  1615. BitArray::~BitArray() throw()
  1616. {
  1617. juce_free (values);
  1618. }
  1619. const BitArray& BitArray::operator= (const BitArray& other) throw()
  1620. {
  1621. if (this != &other)
  1622. {
  1623. juce_free (values);
  1624. highestBit = other.getHighestBit();
  1625. numValues = jmax (4, (highestBit >> 5) + 1);
  1626. negative = other.negative;
  1627. const int memSize = sizeof (unsigned int) * (numValues + 1);
  1628. values = (unsigned int*)juce_malloc (memSize);
  1629. memcpy (values, other.values, memSize);
  1630. }
  1631. return *this;
  1632. }
  1633. // result == 0 = the same
  1634. // result < 0 = this number is smaller
  1635. // result > 0 = this number is bigger
  1636. int BitArray::compare (const BitArray& other) const throw()
  1637. {
  1638. if (isNegative() == other.isNegative())
  1639. {
  1640. const int absComp = compareAbsolute (other);
  1641. return isNegative() ? -absComp : absComp;
  1642. }
  1643. else
  1644. {
  1645. return isNegative() ? -1 : 1;
  1646. }
  1647. }
  1648. int BitArray::compareAbsolute (const BitArray& other) const throw()
  1649. {
  1650. const int h1 = getHighestBit();
  1651. const int h2 = other.getHighestBit();
  1652. if (h1 > h2)
  1653. return 1;
  1654. else if (h1 < h2)
  1655. return -1;
  1656. for (int i = (h1 >> 5) + 1; --i >= 0;)
  1657. if (values[i] != other.values[i])
  1658. return (values[i] > other.values[i]) ? 1 : -1;
  1659. return 0;
  1660. }
  1661. bool BitArray::operator== (const BitArray& other) const throw()
  1662. {
  1663. return compare (other) == 0;
  1664. }
  1665. bool BitArray::operator!= (const BitArray& other) const throw()
  1666. {
  1667. return compare (other) != 0;
  1668. }
  1669. bool BitArray::operator[] (const int bit) const throw()
  1670. {
  1671. return bit >= 0 && bit <= highestBit
  1672. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  1673. }
  1674. bool BitArray::isEmpty() const throw()
  1675. {
  1676. return getHighestBit() < 0;
  1677. }
  1678. void BitArray::clear() throw()
  1679. {
  1680. if (numValues > 16)
  1681. {
  1682. juce_free (values);
  1683. numValues = 4;
  1684. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1685. }
  1686. else
  1687. {
  1688. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  1689. }
  1690. highestBit = -1;
  1691. negative = false;
  1692. }
  1693. void BitArray::setBit (const int bit) throw()
  1694. {
  1695. if (bit >= 0)
  1696. {
  1697. if (bit > highestBit)
  1698. {
  1699. ensureSize (bit >> 5);
  1700. highestBit = bit;
  1701. }
  1702. values [bit >> 5] |= (1 << (bit & 31));
  1703. }
  1704. }
  1705. void BitArray::setBit (const int bit,
  1706. const bool shouldBeSet) throw()
  1707. {
  1708. if (shouldBeSet)
  1709. setBit (bit);
  1710. else
  1711. clearBit (bit);
  1712. }
  1713. void BitArray::clearBit (const int bit) throw()
  1714. {
  1715. if (bit >= 0 && bit <= highestBit)
  1716. values [bit >> 5] &= ~(1 << (bit & 31));
  1717. }
  1718. void BitArray::setRange (int startBit,
  1719. int numBits,
  1720. const bool shouldBeSet) throw()
  1721. {
  1722. while (--numBits >= 0)
  1723. setBit (startBit++, shouldBeSet);
  1724. }
  1725. void BitArray::insertBit (const int bit,
  1726. const bool shouldBeSet) throw()
  1727. {
  1728. if (bit >= 0)
  1729. shiftBits (1, bit);
  1730. setBit (bit, shouldBeSet);
  1731. }
  1732. void BitArray::andWith (const BitArray& other) throw()
  1733. {
  1734. // this operation will only work with the absolute values
  1735. jassert (isNegative() == other.isNegative());
  1736. int n = numValues;
  1737. while (n > other.numValues)
  1738. values[--n] = 0;
  1739. while (--n >= 0)
  1740. values[n] &= other.values[n];
  1741. if (other.highestBit < highestBit)
  1742. highestBit = other.highestBit;
  1743. highestBit = getHighestBit();
  1744. }
  1745. void BitArray::orWith (const BitArray& other) throw()
  1746. {
  1747. if (other.highestBit < 0)
  1748. return;
  1749. // this operation will only work with the absolute values
  1750. jassert (isNegative() == other.isNegative());
  1751. ensureSize (other.highestBit >> 5);
  1752. int n = (other.highestBit >> 5) + 1;
  1753. while (--n >= 0)
  1754. values[n] |= other.values[n];
  1755. if (other.highestBit > highestBit)
  1756. highestBit = other.highestBit;
  1757. highestBit = getHighestBit();
  1758. }
  1759. void BitArray::xorWith (const BitArray& other) throw()
  1760. {
  1761. if (other.highestBit < 0)
  1762. return;
  1763. // this operation will only work with the absolute values
  1764. jassert (isNegative() == other.isNegative());
  1765. ensureSize (other.highestBit >> 5);
  1766. int n = (other.highestBit >> 5) + 1;
  1767. while (--n >= 0)
  1768. values[n] ^= other.values[n];
  1769. if (other.highestBit > highestBit)
  1770. highestBit = other.highestBit;
  1771. highestBit = getHighestBit();
  1772. }
  1773. void BitArray::add (const BitArray& other) throw()
  1774. {
  1775. if (other.isNegative())
  1776. {
  1777. BitArray o (other);
  1778. o.negate();
  1779. subtract (o);
  1780. return;
  1781. }
  1782. if (isNegative())
  1783. {
  1784. if (compareAbsolute (other) < 0)
  1785. {
  1786. BitArray temp (*this);
  1787. temp.negate();
  1788. *this = other;
  1789. subtract (temp);
  1790. }
  1791. else
  1792. {
  1793. negate();
  1794. subtract (other);
  1795. negate();
  1796. }
  1797. return;
  1798. }
  1799. if (other.highestBit > highestBit)
  1800. highestBit = other.highestBit;
  1801. ++highestBit;
  1802. const int numInts = (highestBit >> 5) + 1;
  1803. ensureSize (numInts);
  1804. int64 remainder = 0;
  1805. for (int i = 0; i <= numInts; ++i)
  1806. {
  1807. if (i < numValues)
  1808. remainder += values[i];
  1809. if (i < other.numValues)
  1810. remainder += other.values[i];
  1811. values[i] = (unsigned int) remainder;
  1812. remainder >>= 32;
  1813. }
  1814. jassert (remainder == 0);
  1815. highestBit = getHighestBit();
  1816. }
  1817. void BitArray::subtract (const BitArray& other) throw()
  1818. {
  1819. if (other.isNegative())
  1820. {
  1821. BitArray o (other);
  1822. o.negate();
  1823. add (o);
  1824. return;
  1825. }
  1826. if (! isNegative())
  1827. {
  1828. if (compareAbsolute (other) < 0)
  1829. {
  1830. BitArray temp (*this);
  1831. *this = other;
  1832. subtract (temp);
  1833. negate();
  1834. return;
  1835. }
  1836. }
  1837. else
  1838. {
  1839. negate();
  1840. add (other);
  1841. negate();
  1842. return;
  1843. }
  1844. const int numInts = (highestBit >> 5) + 1;
  1845. const int maxOtherInts = (other.highestBit >> 5) + 1;
  1846. int64 amountToSubtract = 0;
  1847. for (int i = 0; i <= numInts; ++i)
  1848. {
  1849. if (i <= maxOtherInts)
  1850. amountToSubtract += (int64)other.values[i];
  1851. if (values[i] >= amountToSubtract)
  1852. {
  1853. values[i] = (unsigned int) (values[i] - amountToSubtract);
  1854. amountToSubtract = 0;
  1855. }
  1856. else
  1857. {
  1858. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  1859. values[i] = (unsigned int) n;
  1860. amountToSubtract = 1;
  1861. }
  1862. }
  1863. }
  1864. void BitArray::multiplyBy (const BitArray& other) throw()
  1865. {
  1866. BitArray total;
  1867. highestBit = getHighestBit();
  1868. const bool wasNegative = isNegative();
  1869. setNegative (false);
  1870. for (int i = 0; i <= highestBit; ++i)
  1871. {
  1872. if (operator[](i))
  1873. {
  1874. BitArray n (other);
  1875. n.setNegative (false);
  1876. n.shiftBits (i);
  1877. total.add (n);
  1878. }
  1879. }
  1880. *this = total;
  1881. negative = wasNegative ^ other.isNegative();
  1882. }
  1883. void BitArray::divideBy (const BitArray& divisor, BitArray& remainder) throw()
  1884. {
  1885. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  1886. const int divHB = divisor.getHighestBit();
  1887. const int ourHB = getHighestBit();
  1888. if (divHB < 0 || ourHB < 0)
  1889. {
  1890. // division by zero
  1891. remainder.clear();
  1892. clear();
  1893. }
  1894. else
  1895. {
  1896. remainder = *this;
  1897. remainder.setNegative (false);
  1898. const bool wasNegative = isNegative();
  1899. clear();
  1900. BitArray temp (divisor);
  1901. temp.setNegative (false);
  1902. int leftShift = ourHB - divHB;
  1903. temp.shiftBits (leftShift);
  1904. while (leftShift >= 0)
  1905. {
  1906. if (remainder.compareAbsolute (temp) >= 0)
  1907. {
  1908. remainder.subtract (temp);
  1909. setBit (leftShift);
  1910. }
  1911. if (--leftShift >= 0)
  1912. temp.shiftBits (-1);
  1913. }
  1914. negative = wasNegative ^ divisor.isNegative();
  1915. remainder.setNegative (wasNegative);
  1916. }
  1917. }
  1918. void BitArray::modulo (const BitArray& divisor) throw()
  1919. {
  1920. BitArray remainder;
  1921. divideBy (divisor, remainder);
  1922. *this = remainder;
  1923. }
  1924. static const BitArray simpleGCD (BitArray* m, BitArray* n) throw()
  1925. {
  1926. while (! m->isEmpty())
  1927. {
  1928. if (n->compareAbsolute (*m) > 0)
  1929. swapVariables (m, n);
  1930. m->subtract (*n);
  1931. }
  1932. return *n;
  1933. }
  1934. const BitArray BitArray::findGreatestCommonDivisor (BitArray n) const throw()
  1935. {
  1936. BitArray m (*this);
  1937. while (! n.isEmpty())
  1938. {
  1939. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  1940. return simpleGCD (&m, &n);
  1941. BitArray temp1 (m), temp2;
  1942. temp1.divideBy (n, temp2);
  1943. m = n;
  1944. n = temp2;
  1945. }
  1946. return m;
  1947. }
  1948. void BitArray::exponentModulo (const BitArray& exponent,
  1949. const BitArray& modulus) throw()
  1950. {
  1951. BitArray exp (exponent);
  1952. exp.modulo (modulus);
  1953. BitArray value (*this);
  1954. value.modulo (modulus);
  1955. clear();
  1956. setBit (0);
  1957. while (! exp.isEmpty())
  1958. {
  1959. if (exp [0])
  1960. {
  1961. multiplyBy (value);
  1962. this->modulo (modulus);
  1963. }
  1964. value.multiplyBy (value);
  1965. value.modulo (modulus);
  1966. exp.shiftBits (-1);
  1967. }
  1968. }
  1969. void BitArray::inverseModulo (const BitArray& modulus) throw()
  1970. {
  1971. const BitArray one (1);
  1972. if (modulus == one || modulus.isNegative())
  1973. {
  1974. clear();
  1975. return;
  1976. }
  1977. if (isNegative() || compareAbsolute (modulus) >= 0)
  1978. this->modulo (modulus);
  1979. if (*this == one)
  1980. return;
  1981. if (! (*this)[0])
  1982. {
  1983. // not invertible
  1984. clear();
  1985. return;
  1986. }
  1987. BitArray a1 (modulus);
  1988. BitArray a2 (*this);
  1989. BitArray b1 (modulus);
  1990. BitArray b2 (1);
  1991. while (a2 != one)
  1992. {
  1993. BitArray temp1, temp2, multiplier (a1);
  1994. multiplier.divideBy (a2, temp1);
  1995. temp1 = a2;
  1996. temp1.multiplyBy (multiplier);
  1997. temp2 = a1;
  1998. temp2.subtract (temp1);
  1999. a1 = a2;
  2000. a2 = temp2;
  2001. temp1 = b2;
  2002. temp1.multiplyBy (multiplier);
  2003. temp2 = b1;
  2004. temp2.subtract (temp1);
  2005. b1 = b2;
  2006. b2 = temp2;
  2007. }
  2008. while (b2.isNegative())
  2009. b2.add (modulus);
  2010. b2.modulo (modulus);
  2011. *this = b2;
  2012. }
  2013. void BitArray::shiftBits (int bits, const int startBit) throw()
  2014. {
  2015. if (highestBit < 0)
  2016. return;
  2017. if (startBit > 0)
  2018. {
  2019. if (bits < 0)
  2020. {
  2021. // right shift
  2022. for (int i = startBit; i <= highestBit; ++i)
  2023. setBit (i, operator[] (i - bits));
  2024. highestBit = getHighestBit();
  2025. }
  2026. else if (bits > 0)
  2027. {
  2028. // left shift
  2029. for (int i = highestBit + 1; --i >= startBit;)
  2030. setBit (i + bits, operator[] (i));
  2031. while (--bits >= 0)
  2032. clearBit (bits + startBit);
  2033. }
  2034. }
  2035. else
  2036. {
  2037. if (bits < 0)
  2038. {
  2039. // right shift
  2040. bits = -bits;
  2041. if (bits > highestBit)
  2042. {
  2043. clear();
  2044. }
  2045. else
  2046. {
  2047. const int wordsToMove = bits >> 5;
  2048. int top = 1 + (highestBit >> 5) - wordsToMove;
  2049. highestBit -= bits;
  2050. if (wordsToMove > 0)
  2051. {
  2052. int i;
  2053. for (i = 0; i < top; ++i)
  2054. values [i] = values [i + wordsToMove];
  2055. for (i = 0; i < wordsToMove; ++i)
  2056. values [top + i] = 0;
  2057. bits &= 31;
  2058. }
  2059. if (bits != 0)
  2060. {
  2061. const int invBits = 32 - bits;
  2062. --top;
  2063. for (int i = 0; i < top; ++i)
  2064. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2065. values[top] = (values[top] >> bits);
  2066. }
  2067. highestBit = getHighestBit();
  2068. }
  2069. }
  2070. else if (bits > 0)
  2071. {
  2072. // left shift
  2073. ensureSize (((highestBit + bits) >> 5) + 1);
  2074. const int wordsToMove = bits >> 5;
  2075. int top = 1 + (highestBit >> 5);
  2076. highestBit += bits;
  2077. if (wordsToMove > 0)
  2078. {
  2079. int i;
  2080. for (i = top; --i >= 0;)
  2081. values [i + wordsToMove] = values [i];
  2082. for (i = 0; i < wordsToMove; ++i)
  2083. values [i] = 0;
  2084. bits &= 31;
  2085. }
  2086. if (bits != 0)
  2087. {
  2088. const int invBits = 32 - bits;
  2089. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2090. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2091. values [wordsToMove] = values [wordsToMove] << bits;
  2092. }
  2093. highestBit = getHighestBit();
  2094. }
  2095. }
  2096. }
  2097. const BitArray BitArray::getBitRange (int startBit, int numBits) const throw()
  2098. {
  2099. BitArray r;
  2100. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2101. r.ensureSize (numBits >> 5);
  2102. r.highestBit = numBits;
  2103. int i = 0;
  2104. while (numBits > 0)
  2105. {
  2106. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2107. numBits -= 32;
  2108. startBit += 32;
  2109. }
  2110. r.highestBit = r.getHighestBit();
  2111. return r;
  2112. }
  2113. int BitArray::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2114. {
  2115. if (numBits > 32)
  2116. {
  2117. jassertfalse // use getBitRange() if you need more than 32 bits..
  2118. numBits = 32;
  2119. }
  2120. numBits = jmin (numBits, highestBit + 1 - startBit);
  2121. if (numBits <= 0)
  2122. return 0;
  2123. const int pos = startBit >> 5;
  2124. const int offset = startBit & 31;
  2125. const int endSpace = 32 - numBits;
  2126. uint32 n = ((uint32) values [pos]) >> offset;
  2127. if (offset > endSpace)
  2128. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2129. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2130. }
  2131. void BitArray::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet) throw()
  2132. {
  2133. if (numBits > 32)
  2134. {
  2135. jassertfalse
  2136. numBits = 32;
  2137. }
  2138. for (int i = 0; i < numBits; ++i)
  2139. {
  2140. setBit (startBit + i, (valueToSet & 1) != 0);
  2141. valueToSet >>= 1;
  2142. }
  2143. }
  2144. bool BitArray::isNegative() const throw()
  2145. {
  2146. return negative && ! isEmpty();
  2147. }
  2148. void BitArray::setNegative (const bool neg) throw()
  2149. {
  2150. negative = neg;
  2151. }
  2152. void BitArray::negate() throw()
  2153. {
  2154. negative = (! negative) && ! isEmpty();
  2155. }
  2156. int BitArray::countNumberOfSetBits() const throw()
  2157. {
  2158. int total = 0;
  2159. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2160. {
  2161. unsigned int n = values[i];
  2162. if (n == 0xffffffff)
  2163. {
  2164. total += 32;
  2165. }
  2166. else
  2167. {
  2168. while (n != 0)
  2169. {
  2170. total += (n & 1);
  2171. n >>= 1;
  2172. }
  2173. }
  2174. }
  2175. return total;
  2176. }
  2177. int BitArray::getHighestBit() const throw()
  2178. {
  2179. for (int i = highestBit + 1; --i >= 0;)
  2180. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2181. return i;
  2182. return -1;
  2183. }
  2184. int BitArray::findNextSetBit (int i) const throw()
  2185. {
  2186. for (; i <= highestBit; ++i)
  2187. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2188. return i;
  2189. return -1;
  2190. }
  2191. int BitArray::findNextClearBit (int i) const throw()
  2192. {
  2193. for (; i <= highestBit; ++i)
  2194. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2195. break;
  2196. return i;
  2197. }
  2198. void BitArray::ensureSize (const int numVals) throw()
  2199. {
  2200. if (numVals + 2 >= numValues)
  2201. {
  2202. int oldSize = numValues;
  2203. numValues = ((numVals + 2) * 3) / 2;
  2204. values = (unsigned int*) juce_realloc (values, sizeof (unsigned int) * numValues + 4);
  2205. while (oldSize < numValues)
  2206. values [oldSize++] = 0;
  2207. }
  2208. }
  2209. const String BitArray::toString (const int base, const int minimumNumCharacters) const throw()
  2210. {
  2211. String s;
  2212. BitArray v (*this);
  2213. if (base == 2 || base == 8 || base == 16)
  2214. {
  2215. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2216. static const tchar* const hexDigits = T("0123456789abcdef");
  2217. for (;;)
  2218. {
  2219. const int remainder = v.getBitRangeAsInt (0, bits);
  2220. v.shiftBits (-bits);
  2221. if (remainder == 0 && v.isEmpty())
  2222. break;
  2223. s = String::charToString (hexDigits [remainder]) + s;
  2224. }
  2225. }
  2226. else if (base == 10)
  2227. {
  2228. const BitArray ten (10);
  2229. BitArray remainder;
  2230. for (;;)
  2231. {
  2232. v.divideBy (ten, remainder);
  2233. if (remainder.isEmpty() && v.isEmpty())
  2234. break;
  2235. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2236. }
  2237. }
  2238. else
  2239. {
  2240. jassertfalse // can't do the specified base
  2241. return String::empty;
  2242. }
  2243. const int length = s.length();
  2244. if (length < minimumNumCharacters)
  2245. s = String::repeatedString (T("0"), minimumNumCharacters - length);
  2246. return isNegative() ? T("-") + s : s;
  2247. }
  2248. void BitArray::parseString (const String& text,
  2249. const int base) throw()
  2250. {
  2251. clear();
  2252. const tchar* t = (const tchar*) text;
  2253. if (base == 2 || base == 8 || base == 16)
  2254. {
  2255. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2256. for (;;)
  2257. {
  2258. const tchar c = *t++;
  2259. const int digit = CharacterFunctions::getHexDigitValue (c);
  2260. if (((unsigned int) digit) < (unsigned int) base)
  2261. {
  2262. shiftBits (bits);
  2263. add (digit);
  2264. }
  2265. else if (c == 0)
  2266. {
  2267. break;
  2268. }
  2269. }
  2270. }
  2271. else if (base == 10)
  2272. {
  2273. const BitArray ten ((unsigned int) 10);
  2274. for (;;)
  2275. {
  2276. const tchar c = *t++;
  2277. if (c >= T('0') && c <= T('9'))
  2278. {
  2279. multiplyBy (ten);
  2280. add ((int) (c - T('0')));
  2281. }
  2282. else if (c == 0)
  2283. {
  2284. break;
  2285. }
  2286. }
  2287. }
  2288. setNegative (text.trimStart().startsWithChar (T('-')));
  2289. }
  2290. const MemoryBlock BitArray::toMemoryBlock() const throw()
  2291. {
  2292. const int numBytes = (getHighestBit() + 8) >> 3;
  2293. MemoryBlock mb (numBytes);
  2294. for (int i = 0; i < numBytes; ++i)
  2295. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2296. return mb;
  2297. }
  2298. void BitArray::loadFromMemoryBlock (const MemoryBlock& data) throw()
  2299. {
  2300. clear();
  2301. for (int i = data.getSize(); --i >= 0;)
  2302. this->setBitRangeAsInt (i << 3, 8, data [i]);
  2303. }
  2304. END_JUCE_NAMESPACE
  2305. /********* End of inlined file: juce_BitArray.cpp *********/
  2306. /********* Start of inlined file: juce_MemoryBlock.cpp *********/
  2307. BEGIN_JUCE_NAMESPACE
  2308. MemoryBlock::MemoryBlock() throw()
  2309. : data (0),
  2310. size (0)
  2311. {
  2312. }
  2313. MemoryBlock::MemoryBlock (const int initialSize,
  2314. const bool initialiseToZero) throw()
  2315. {
  2316. if (initialSize > 0)
  2317. {
  2318. size = initialSize;
  2319. if (initialiseToZero)
  2320. data = (char*) juce_calloc (initialSize);
  2321. else
  2322. data = (char*) juce_malloc (initialSize);
  2323. }
  2324. else
  2325. {
  2326. data = 0;
  2327. size = 0;
  2328. }
  2329. }
  2330. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2331. : data (0),
  2332. size (other.size)
  2333. {
  2334. if (size > 0)
  2335. {
  2336. jassert (other.data != 0);
  2337. data = (char*) juce_malloc (size);
  2338. memcpy (data, other.data, size);
  2339. }
  2340. }
  2341. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2342. const int sizeInBytes) throw()
  2343. : data (0),
  2344. size (jmax (0, sizeInBytes))
  2345. {
  2346. jassert (sizeInBytes >= 0);
  2347. if (size > 0)
  2348. {
  2349. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2350. data = (char*) juce_malloc (size);
  2351. if (dataToInitialiseFrom != 0)
  2352. memcpy (data, dataToInitialiseFrom, size);
  2353. }
  2354. }
  2355. MemoryBlock::~MemoryBlock() throw()
  2356. {
  2357. jassert (size >= 0); // should never happen
  2358. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2359. juce_free (data);
  2360. }
  2361. const MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2362. {
  2363. if (this != &other)
  2364. {
  2365. setSize (other.size, false);
  2366. memcpy (data, other.data, size);
  2367. }
  2368. return *this;
  2369. }
  2370. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2371. {
  2372. return (size == other.size)
  2373. && (memcmp (data, other.data, size) == 0);
  2374. }
  2375. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2376. {
  2377. return ! operator== (other);
  2378. }
  2379. // this will resize the block to this size
  2380. void MemoryBlock::setSize (const int newSize,
  2381. const bool initialiseToZero) throw()
  2382. {
  2383. if (size != newSize)
  2384. {
  2385. if (newSize <= 0)
  2386. {
  2387. juce_free (data);
  2388. data = 0;
  2389. size = 0;
  2390. }
  2391. else
  2392. {
  2393. if (data != 0)
  2394. {
  2395. data = (char*) juce_realloc (data, newSize);
  2396. if (initialiseToZero && (newSize > size))
  2397. zeromem (data + size, newSize - size);
  2398. }
  2399. else
  2400. {
  2401. if (initialiseToZero)
  2402. data = (char*) juce_calloc (newSize);
  2403. else
  2404. data = (char*) juce_malloc (newSize);
  2405. }
  2406. size = newSize;
  2407. }
  2408. }
  2409. }
  2410. void MemoryBlock::ensureSize (const int minimumSize,
  2411. const bool initialiseToZero) throw()
  2412. {
  2413. if (size < minimumSize)
  2414. setSize (minimumSize, initialiseToZero);
  2415. }
  2416. void MemoryBlock::fillWith (const uint8 value) throw()
  2417. {
  2418. memset (data, (int) value, size);
  2419. }
  2420. void MemoryBlock::append (const void* const srcData,
  2421. const int numBytes) throw()
  2422. {
  2423. if (numBytes > 0)
  2424. {
  2425. const int oldSize = size;
  2426. setSize (size + numBytes);
  2427. memcpy (data + oldSize, srcData, numBytes);
  2428. }
  2429. }
  2430. void MemoryBlock::copyFrom (const void* const src, int offset, int num) throw()
  2431. {
  2432. const char* d = (const char*) src;
  2433. if (offset < 0)
  2434. {
  2435. d -= offset;
  2436. num -= offset;
  2437. offset = 0;
  2438. }
  2439. if (offset + num > size)
  2440. num = size - offset;
  2441. if (num > 0)
  2442. memcpy (data + offset, d, num);
  2443. }
  2444. void MemoryBlock::copyTo (void* const dst, int offset, int num) const throw()
  2445. {
  2446. char* d = (char*) dst;
  2447. if (offset < 0)
  2448. {
  2449. zeromem (d, -offset);
  2450. d -= offset;
  2451. num += offset;
  2452. offset = 0;
  2453. }
  2454. if (offset + num > size)
  2455. {
  2456. const int newNum = size - offset;
  2457. zeromem (d + newNum, num - newNum);
  2458. num = newNum;
  2459. }
  2460. if (num > 0)
  2461. memcpy (d, data + offset, num);
  2462. }
  2463. void MemoryBlock::removeSection (int startByte, int numBytesToRemove) throw()
  2464. {
  2465. if (startByte < 0)
  2466. {
  2467. numBytesToRemove += startByte;
  2468. startByte = 0;
  2469. }
  2470. if (startByte + numBytesToRemove >= size)
  2471. {
  2472. setSize (startByte);
  2473. }
  2474. else if (numBytesToRemove > 0)
  2475. {
  2476. memmove (data + startByte,
  2477. data + startByte + numBytesToRemove,
  2478. size - (startByte + numBytesToRemove));
  2479. setSize (size - numBytesToRemove);
  2480. }
  2481. }
  2482. const String MemoryBlock::toString() const throw()
  2483. {
  2484. return String (data, size);
  2485. }
  2486. int MemoryBlock::getBitRange (const int bitRangeStart, int numBits) const throw()
  2487. {
  2488. int res = 0;
  2489. int byte = bitRangeStart >> 3;
  2490. int offsetInByte = bitRangeStart & 7;
  2491. int bitsSoFar = 0;
  2492. while (numBits > 0 && byte < size)
  2493. {
  2494. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  2495. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2496. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2497. bitsSoFar += bitsThisTime;
  2498. numBits -= bitsThisTime;
  2499. ++byte;
  2500. offsetInByte = 0;
  2501. }
  2502. return res;
  2503. }
  2504. void MemoryBlock::setBitRange (const int bitRangeStart, int numBits, int bitsToSet) throw()
  2505. {
  2506. int byte = bitRangeStart >> 3;
  2507. int offsetInByte = bitRangeStart & 7;
  2508. unsigned int mask = ~((((unsigned int)0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2509. while (numBits > 0 && byte < size)
  2510. {
  2511. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  2512. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int)0xffffffff) >> offsetInByte) << offsetInByte);
  2513. const unsigned int tempBits = bitsToSet << offsetInByte;
  2514. data[byte] = (char)((data[byte] & tempMask) | tempBits);
  2515. ++byte;
  2516. numBits -= bitsThisTime;
  2517. bitsToSet >>= bitsThisTime;
  2518. mask >>= bitsThisTime;
  2519. offsetInByte = 0;
  2520. }
  2521. }
  2522. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2523. {
  2524. ensureSize (hex.length() >> 1);
  2525. char* dest = data;
  2526. int i = 0;
  2527. for (;;)
  2528. {
  2529. int byte = 0;
  2530. for (int loop = 2; --loop >= 0;)
  2531. {
  2532. byte <<= 4;
  2533. for (;;)
  2534. {
  2535. const tchar c = hex [i++];
  2536. if (c >= T('0') && c <= T('9'))
  2537. {
  2538. byte |= c - T('0');
  2539. break;
  2540. }
  2541. else if (c >= T('a') && c <= T('z'))
  2542. {
  2543. byte |= c - (T('a') - 10);
  2544. break;
  2545. }
  2546. else if (c >= T('A') && c <= T('Z'))
  2547. {
  2548. byte |= c - (T('A') - 10);
  2549. break;
  2550. }
  2551. else if (c == 0)
  2552. {
  2553. setSize ((int) (dest - data));
  2554. return;
  2555. }
  2556. }
  2557. }
  2558. *dest++ = (char) byte;
  2559. }
  2560. }
  2561. static const char* const encodingTable
  2562. = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2563. const String MemoryBlock::toBase64Encoding() const throw()
  2564. {
  2565. const int numChars = ((size << 3) + 5) / 6;
  2566. String destString (size); // store the length, followed by a '.', and then the data.
  2567. const int initialLen = destString.length();
  2568. destString.preallocateStorage (initialLen + 2 + numChars);
  2569. tchar* d = const_cast <tchar*> (((const tchar*) destString) + initialLen);
  2570. *d++ = T('.');
  2571. for (int i = 0; i < numChars; ++i)
  2572. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2573. *d++ = 0;
  2574. return destString;
  2575. }
  2576. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  2577. {
  2578. const int startPos = s.indexOfChar (T('.')) + 1;
  2579. if (startPos <= 0)
  2580. return false;
  2581. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2582. setSize (numBytesNeeded, true);
  2583. const int numChars = s.length() - startPos;
  2584. const tchar* const srcChars = ((const tchar*) s) + startPos;
  2585. for (int i = 0; i < numChars; ++i)
  2586. {
  2587. const char c = (char) srcChars[i];
  2588. for (int j = 0; j < 64; ++j)
  2589. {
  2590. if (encodingTable[j] == c)
  2591. {
  2592. setBitRange (i * 6, 6, j);
  2593. break;
  2594. }
  2595. }
  2596. }
  2597. return true;
  2598. }
  2599. END_JUCE_NAMESPACE
  2600. /********* End of inlined file: juce_MemoryBlock.cpp *********/
  2601. /********* Start of inlined file: juce_PropertySet.cpp *********/
  2602. BEGIN_JUCE_NAMESPACE
  2603. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2604. : properties (ignoreCaseOfKeyNames),
  2605. fallbackProperties (0),
  2606. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2607. {
  2608. }
  2609. PropertySet::PropertySet (const PropertySet& other) throw()
  2610. : properties (other.properties),
  2611. fallbackProperties (other.fallbackProperties),
  2612. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2613. {
  2614. }
  2615. const PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2616. {
  2617. properties = other.properties;
  2618. fallbackProperties = other.fallbackProperties;
  2619. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  2620. propertyChanged();
  2621. return *this;
  2622. }
  2623. PropertySet::~PropertySet()
  2624. {
  2625. }
  2626. void PropertySet::clear()
  2627. {
  2628. const ScopedLock sl (lock);
  2629. if (properties.size() > 0)
  2630. {
  2631. properties.clear();
  2632. propertyChanged();
  2633. }
  2634. }
  2635. const String PropertySet::getValue (const String& keyName,
  2636. const String& defaultValue) const throw()
  2637. {
  2638. const ScopedLock sl (lock);
  2639. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2640. if (index >= 0)
  2641. return properties.getAllValues() [index];
  2642. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  2643. : defaultValue;
  2644. }
  2645. int PropertySet::getIntValue (const String& keyName,
  2646. const int defaultValue) const throw()
  2647. {
  2648. const ScopedLock sl (lock);
  2649. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2650. if (index >= 0)
  2651. return properties.getAllValues() [index].getIntValue();
  2652. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  2653. : defaultValue;
  2654. }
  2655. double PropertySet::getDoubleValue (const String& keyName,
  2656. const double defaultValue) const throw()
  2657. {
  2658. const ScopedLock sl (lock);
  2659. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2660. if (index >= 0)
  2661. return properties.getAllValues()[index].getDoubleValue();
  2662. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  2663. : defaultValue;
  2664. }
  2665. bool PropertySet::getBoolValue (const String& keyName,
  2666. const bool defaultValue) const throw()
  2667. {
  2668. const ScopedLock sl (lock);
  2669. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2670. if (index >= 0)
  2671. return properties.getAllValues() [index].getIntValue() != 0;
  2672. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  2673. : defaultValue;
  2674. }
  2675. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  2676. {
  2677. XmlDocument doc (getValue (keyName));
  2678. return doc.getDocumentElement();
  2679. }
  2680. void PropertySet::setValue (const String& keyName,
  2681. const String& value) throw()
  2682. {
  2683. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  2684. if (keyName.isNotEmpty())
  2685. {
  2686. const ScopedLock sl (lock);
  2687. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2688. if (index < 0 || properties.getAllValues() [index] != value)
  2689. {
  2690. properties.set (keyName, value);
  2691. propertyChanged();
  2692. }
  2693. }
  2694. }
  2695. void PropertySet::removeValue (const String& keyName) throw()
  2696. {
  2697. if (keyName.isNotEmpty())
  2698. {
  2699. const ScopedLock sl (lock);
  2700. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2701. if (index >= 0)
  2702. {
  2703. properties.remove (keyName);
  2704. propertyChanged();
  2705. }
  2706. }
  2707. }
  2708. void PropertySet::setValue (const String& keyName, const tchar* const value) throw()
  2709. {
  2710. setValue (keyName, String (value));
  2711. }
  2712. void PropertySet::setValue (const String& keyName, const int value) throw()
  2713. {
  2714. setValue (keyName, String (value));
  2715. }
  2716. void PropertySet::setValue (const String& keyName, const double value) throw()
  2717. {
  2718. setValue (keyName, String (value));
  2719. }
  2720. void PropertySet::setValue (const String& keyName, const bool value) throw()
  2721. {
  2722. setValue (keyName, String ((value) ? T("1") : T("0")));
  2723. }
  2724. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  2725. {
  2726. setValue (keyName, (xml == 0) ? String::empty
  2727. : xml->createDocument (String::empty, true));
  2728. }
  2729. bool PropertySet::containsKey (const String& keyName) const throw()
  2730. {
  2731. const ScopedLock sl (lock);
  2732. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  2733. }
  2734. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  2735. {
  2736. const ScopedLock sl (lock);
  2737. fallbackProperties = fallbackProperties_;
  2738. }
  2739. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  2740. {
  2741. const ScopedLock sl (lock);
  2742. XmlElement* const xml = new XmlElement (nodeName);
  2743. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  2744. {
  2745. XmlElement* const e = new XmlElement (T("VALUE"));
  2746. e->setAttribute (T("name"), properties.getAllKeys()[i]);
  2747. e->setAttribute (T("val"), properties.getAllValues()[i]);
  2748. xml->addChildElement (e);
  2749. }
  2750. return xml;
  2751. }
  2752. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  2753. {
  2754. const ScopedLock sl (lock);
  2755. clear();
  2756. forEachXmlChildElementWithTagName (xml, e, T("VALUE"))
  2757. {
  2758. if (e->hasAttribute (T("name"))
  2759. && e->hasAttribute (T("val")))
  2760. {
  2761. properties.set (e->getStringAttribute (T("name")),
  2762. e->getStringAttribute (T("val")));
  2763. }
  2764. }
  2765. if (properties.size() > 0)
  2766. propertyChanged();
  2767. }
  2768. void PropertySet::propertyChanged()
  2769. {
  2770. }
  2771. END_JUCE_NAMESPACE
  2772. /********* End of inlined file: juce_PropertySet.cpp *********/
  2773. /********* Start of inlined file: juce_Variant.cpp *********/
  2774. BEGIN_JUCE_NAMESPACE
  2775. var::var() throw()
  2776. : type (voidType)
  2777. {
  2778. value.doubleValue = 0;
  2779. }
  2780. void var::releaseValue() throw()
  2781. {
  2782. if (type == stringType)
  2783. delete value.stringValue;
  2784. else if (type == objectType && value.objectValue != 0)
  2785. value.objectValue->decReferenceCount();
  2786. }
  2787. var::~var()
  2788. {
  2789. releaseValue();
  2790. }
  2791. var::var (const var& valueToCopy) throw()
  2792. : type (valueToCopy.type),
  2793. value (valueToCopy.value)
  2794. {
  2795. if (type == stringType)
  2796. value.stringValue = new String (*(value.stringValue));
  2797. else if (type == objectType && value.objectValue != 0)
  2798. value.objectValue->incReferenceCount();
  2799. }
  2800. var::var (const int value_) throw()
  2801. : type (intType)
  2802. {
  2803. value.intValue = value_;
  2804. }
  2805. var::var (const bool value_) throw()
  2806. : type (boolType)
  2807. {
  2808. value.boolValue = value_;
  2809. }
  2810. var::var (const double value_) throw()
  2811. : type (doubleType)
  2812. {
  2813. value.doubleValue = value_;
  2814. }
  2815. var::var (const String& value_) throw()
  2816. : type (stringType)
  2817. {
  2818. value.stringValue = new String (value_);
  2819. }
  2820. var::var (const char* const value_) throw()
  2821. : type (stringType)
  2822. {
  2823. value.stringValue = new String (value_);
  2824. }
  2825. var::var (const juce_wchar* const value_) throw()
  2826. : type (stringType)
  2827. {
  2828. value.stringValue = new String (value_);
  2829. }
  2830. var::var (DynamicObject* const object) throw()
  2831. : type (objectType)
  2832. {
  2833. value.objectValue = object;
  2834. if (object != 0)
  2835. object->incReferenceCount();
  2836. }
  2837. var::var (MethodFunction method_) throw()
  2838. : type (methodType)
  2839. {
  2840. value.methodValue = method_;
  2841. }
  2842. const var& var::operator= (const var& valueToCopy) throw()
  2843. {
  2844. if (this != &valueToCopy)
  2845. {
  2846. if (type == stringType)
  2847. delete value.stringValue;
  2848. DynamicObject* const oldObject = getObject();
  2849. type = valueToCopy.type;
  2850. value = valueToCopy.value;
  2851. if (type == stringType)
  2852. value.stringValue = new String (*(value.stringValue));
  2853. else if (type == objectType && value.objectValue != 0)
  2854. value.objectValue->incReferenceCount();
  2855. if (oldObject != 0)
  2856. oldObject->decReferenceCount();
  2857. }
  2858. return *this;
  2859. }
  2860. const var& var::operator= (const int value_) throw()
  2861. {
  2862. releaseValue();
  2863. type = intType;
  2864. value.intValue = value_;
  2865. return *this;
  2866. }
  2867. const var& var::operator= (const bool value_) throw()
  2868. {
  2869. releaseValue();
  2870. type = boolType;
  2871. value.boolValue = value_;
  2872. return *this;
  2873. }
  2874. const var& var::operator= (const double value_) throw()
  2875. {
  2876. releaseValue();
  2877. type = doubleType;
  2878. value.doubleValue = value_;
  2879. return *this;
  2880. }
  2881. const var& var::operator= (const char* const value_) throw()
  2882. {
  2883. releaseValue();
  2884. type = stringType;
  2885. value.stringValue = new String (value_);
  2886. return *this;
  2887. }
  2888. const var& var::operator= (const juce_wchar* const value_) throw()
  2889. {
  2890. releaseValue();
  2891. type = stringType;
  2892. value.stringValue = new String (value_);
  2893. return *this;
  2894. }
  2895. const var& var::operator= (const String& value_) throw()
  2896. {
  2897. releaseValue();
  2898. type = stringType;
  2899. value.stringValue = new String (value_);
  2900. return *this;
  2901. }
  2902. const var& var::operator= (DynamicObject* const value_) throw()
  2903. {
  2904. value_->incReferenceCount();
  2905. releaseValue();
  2906. type = objectType;
  2907. value.objectValue = value_;
  2908. return *this;
  2909. }
  2910. const var& var::operator= (MethodFunction method_) throw()
  2911. {
  2912. releaseValue();
  2913. type = doubleType;
  2914. value.methodValue = method_;
  2915. return *this;
  2916. }
  2917. var::operator int() const throw()
  2918. {
  2919. switch (type)
  2920. {
  2921. case voidType:
  2922. case objectType: break;
  2923. case intType: return value.intValue;
  2924. case boolType: return value.boolValue ? 1 : 0;
  2925. case doubleType: return (int) value.doubleValue;
  2926. case stringType: return value.stringValue->getIntValue();
  2927. default: jassertfalse; break;
  2928. }
  2929. return 0;
  2930. }
  2931. var::operator bool() const throw()
  2932. {
  2933. switch (type)
  2934. {
  2935. case voidType: break;
  2936. case objectType: return value.objectValue != 0;
  2937. case intType: return value.intValue != 0;
  2938. case boolType: return value.boolValue;
  2939. case doubleType: return value.doubleValue != 0;
  2940. case stringType: return value.stringValue->getIntValue() != 0
  2941. || value.stringValue->trim().equalsIgnoreCase (T("true"))
  2942. || value.stringValue->trim().equalsIgnoreCase (T("yes"));
  2943. default: jassertfalse; break;
  2944. }
  2945. return false;
  2946. }
  2947. var::operator double() const throw()
  2948. {
  2949. switch (type)
  2950. {
  2951. case voidType:
  2952. case objectType: break;
  2953. case intType: return value.intValue;
  2954. case boolType: return value.boolValue ? 1.0 : 0.0;
  2955. case doubleType: return value.doubleValue;
  2956. case stringType: return value.stringValue->getDoubleValue();
  2957. default: jassertfalse; break;
  2958. }
  2959. return 0;
  2960. }
  2961. const String var::toString() const throw()
  2962. {
  2963. switch (type)
  2964. {
  2965. case voidType:
  2966. case objectType: return "Object 0x" + String::toHexString ((int) (pointer_sized_int) value.objectValue);
  2967. case intType: return String (value.intValue);
  2968. case boolType: return value.boolValue ? T("1") : T("0");
  2969. case doubleType: return String (value.doubleValue);
  2970. case stringType: return *(value.stringValue);
  2971. default: jassertfalse; break;
  2972. }
  2973. return String::empty;
  2974. }
  2975. var::operator const String() const throw()
  2976. {
  2977. return toString();
  2978. }
  2979. DynamicObject* var::getObject() const throw()
  2980. {
  2981. return type == objectType ? value.objectValue : 0;
  2982. }
  2983. const var var::operator[] (const var::identifier& propertyName) const throw()
  2984. {
  2985. if (type == objectType && value.objectValue != 0)
  2986. return value.objectValue->getProperty (propertyName);
  2987. return var();
  2988. }
  2989. const var var::invoke (const var::identifier& method, const var* arguments, int numArguments) const
  2990. {
  2991. if (type == objectType && value.objectValue != 0)
  2992. return value.objectValue->invokeMethod (method, arguments, numArguments);
  2993. return var();
  2994. }
  2995. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  2996. {
  2997. if (isMethod())
  2998. {
  2999. DynamicObject* const target = targetObject.getObject();
  3000. if (target != 0)
  3001. return (target->*(value.methodValue)) (arguments, numArguments);
  3002. }
  3003. return var();
  3004. }
  3005. const var var::call (const var::identifier& method) const
  3006. {
  3007. return invoke (method, 0, 0);
  3008. }
  3009. const var var::call (const var::identifier& method, const var& arg1) const
  3010. {
  3011. return invoke (method, &arg1, 1);
  3012. }
  3013. const var var::call (const var::identifier& method, const var& arg1, const var& arg2) const
  3014. {
  3015. var args[] = { arg1, arg2 };
  3016. return invoke (method, args, 2);
  3017. }
  3018. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3019. {
  3020. var args[] = { arg1, arg2, arg3 };
  3021. return invoke (method, args, 3);
  3022. }
  3023. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3024. {
  3025. var args[] = { arg1, arg2, arg3, arg4 };
  3026. return invoke (method, args, 4);
  3027. }
  3028. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3029. {
  3030. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3031. return invoke (method, args, 5);
  3032. }
  3033. var::identifier::identifier (const String& name_) throw()
  3034. : name (name_),
  3035. hashCode (name_.hashCode())
  3036. {
  3037. }
  3038. var::identifier::identifier (const char* const name_) throw()
  3039. : name (name_),
  3040. hashCode (name.hashCode())
  3041. {
  3042. }
  3043. var::identifier::~identifier() throw()
  3044. {
  3045. }
  3046. DynamicObject::DynamicObject()
  3047. {
  3048. }
  3049. DynamicObject::~DynamicObject()
  3050. {
  3051. }
  3052. bool DynamicObject::hasProperty (const var::identifier& propertyName) const
  3053. {
  3054. const int index = propertyIds.indexOf (propertyName.hashCode);
  3055. return index >= 0 && ! propertyValues.getUnchecked (index)->isMethod();
  3056. }
  3057. const var DynamicObject::getProperty (const var::identifier& propertyName) const
  3058. {
  3059. const int index = propertyIds.indexOf (propertyName.hashCode);
  3060. if (index >= 0)
  3061. return *propertyValues.getUnchecked (index);
  3062. return var();
  3063. }
  3064. void DynamicObject::setProperty (const var::identifier& propertyName, const var& newValue)
  3065. {
  3066. const int index = propertyIds.indexOf (propertyName.hashCode);
  3067. if (index >= 0)
  3068. {
  3069. propertyValues.set (index, new var (newValue));
  3070. }
  3071. else
  3072. {
  3073. propertyIds.add (propertyName.hashCode);
  3074. propertyValues.add (new var (newValue));
  3075. }
  3076. }
  3077. void DynamicObject::removeProperty (const var::identifier& propertyName)
  3078. {
  3079. const int index = propertyIds.indexOf (propertyName.hashCode);
  3080. if (index >= 0)
  3081. {
  3082. propertyIds.remove (index);
  3083. propertyValues.remove (index);
  3084. }
  3085. }
  3086. bool DynamicObject::hasMethod (const var::identifier& methodName) const
  3087. {
  3088. return getProperty (methodName).isMethod();
  3089. }
  3090. const var DynamicObject::invokeMethod (const var::identifier& methodName,
  3091. const var* parameters,
  3092. int numParameters)
  3093. {
  3094. return getProperty (methodName).invoke (this, parameters, numParameters);
  3095. }
  3096. void DynamicObject::setMethod (const var::identifier& name,
  3097. var::MethodFunction methodFunction)
  3098. {
  3099. setProperty (name, methodFunction);
  3100. }
  3101. void DynamicObject::clear()
  3102. {
  3103. propertyIds.clear();
  3104. propertyValues.clear();
  3105. }
  3106. END_JUCE_NAMESPACE
  3107. /********* End of inlined file: juce_Variant.cpp *********/
  3108. /********* Start of inlined file: juce_BlowFish.cpp *********/
  3109. BEGIN_JUCE_NAMESPACE
  3110. static const uint32 initialPValues [18] =
  3111. {
  3112. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
  3113. 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3114. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
  3115. 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3116. 0x9216d5d9, 0x8979fb1b
  3117. };
  3118. static const uint32 initialSValues [4 * 256] =
  3119. {
  3120. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
  3121. 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3122. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
  3123. 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3124. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
  3125. 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3126. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
  3127. 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3128. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
  3129. 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3130. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
  3131. 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3132. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
  3133. 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3134. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
  3135. 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3136. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
  3137. 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3138. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
  3139. 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3140. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
  3141. 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3142. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
  3143. 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3144. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
  3145. 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3146. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
  3147. 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3148. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
  3149. 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3150. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
  3151. 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3152. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
  3153. 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3154. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
  3155. 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3156. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
  3157. 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3158. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
  3159. 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3160. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
  3161. 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3162. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
  3163. 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3164. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
  3165. 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3166. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
  3167. 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3168. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
  3169. 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3170. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
  3171. 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3172. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
  3173. 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3174. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
  3175. 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3176. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
  3177. 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3178. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
  3179. 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3180. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
  3181. 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3182. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
  3183. 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3184. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
  3185. 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3186. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
  3187. 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3188. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
  3189. 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3190. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
  3191. 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3192. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
  3193. 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3194. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
  3195. 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3196. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
  3197. 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3198. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
  3199. 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3200. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
  3201. 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3202. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
  3203. 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3204. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
  3205. 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3206. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
  3207. 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3208. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
  3209. 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3210. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
  3211. 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3212. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
  3213. 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3214. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
  3215. 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3216. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
  3217. 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3218. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
  3219. 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3220. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
  3221. 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3222. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
  3223. 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3224. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
  3225. 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3226. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
  3227. 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3228. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
  3229. 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3230. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
  3231. 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3232. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
  3233. 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3234. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
  3235. 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3236. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
  3237. 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3238. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
  3239. 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3240. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
  3241. 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3242. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
  3243. 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3244. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
  3245. 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3246. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
  3247. 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3248. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
  3249. 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3250. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
  3251. 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3252. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
  3253. 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3254. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
  3255. 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3256. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
  3257. 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3258. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
  3259. 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3260. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
  3261. 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3262. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
  3263. 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3264. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
  3265. 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3266. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
  3267. 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3268. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
  3269. 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3270. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
  3271. 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3272. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
  3273. 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3274. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
  3275. 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3276. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
  3277. 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3278. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
  3279. 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3280. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
  3281. 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3282. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
  3283. 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3284. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
  3285. 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3286. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
  3287. 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3288. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
  3289. 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3290. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
  3291. 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3292. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
  3293. 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3294. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
  3295. 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3296. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
  3297. 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3298. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
  3299. 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3300. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
  3301. 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3302. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
  3303. 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3304. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
  3305. 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3306. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
  3307. 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3308. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
  3309. 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3310. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
  3311. 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3312. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
  3313. 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3314. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
  3315. 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3316. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
  3317. 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3318. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
  3319. 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3320. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
  3321. 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3322. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
  3323. 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3324. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
  3325. 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3326. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
  3327. 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3328. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
  3329. 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3330. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
  3331. 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3332. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
  3333. 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3334. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
  3335. 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3336. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
  3337. 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3338. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
  3339. 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3340. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
  3341. 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3342. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
  3343. 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3344. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
  3345. 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3346. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
  3347. 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3348. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
  3349. 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3350. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
  3351. 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3352. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
  3353. 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3354. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
  3355. 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3356. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
  3357. 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3358. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
  3359. 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3360. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
  3361. 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3362. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
  3363. 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3364. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
  3365. 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3366. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
  3367. 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3368. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
  3369. 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3370. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
  3371. 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3372. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
  3373. 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3374. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
  3375. 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3376. };
  3377. BlowFish::BlowFish (const uint8* keyData, int keyBytes)
  3378. {
  3379. memcpy (p, initialPValues, sizeof (p));
  3380. int i, j;
  3381. for (i = 4; --i >= 0;)
  3382. {
  3383. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  3384. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3385. }
  3386. j = 0;
  3387. for (i = 0; i < 18; ++i)
  3388. {
  3389. uint32 d = 0;
  3390. for (int k = 0; k < 4; ++k)
  3391. {
  3392. d = (d << 8) | keyData[j];
  3393. if (++j >= keyBytes)
  3394. j = 0;
  3395. }
  3396. p[i] = initialPValues[i] ^ d;
  3397. }
  3398. uint32 l = 0, r = 0;
  3399. for (i = 0; i < 18; i += 2)
  3400. {
  3401. encrypt (l, r);
  3402. p[i] = l;
  3403. p[i + 1] = r;
  3404. }
  3405. for (i = 0; i < 4; ++i)
  3406. {
  3407. for (j = 0; j < 256; j += 2)
  3408. {
  3409. encrypt (l, r);
  3410. s[i][j] = l;
  3411. s[i][j + 1] = r;
  3412. }
  3413. }
  3414. }
  3415. BlowFish::BlowFish (const BlowFish& other)
  3416. {
  3417. for (int i = 4; --i >= 0;)
  3418. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  3419. operator= (other);
  3420. }
  3421. const BlowFish& BlowFish::operator= (const BlowFish& other)
  3422. {
  3423. memcpy (p, other.p, sizeof (p));
  3424. for (int i = 4; --i >= 0;)
  3425. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3426. return *this;
  3427. }
  3428. BlowFish::~BlowFish()
  3429. {
  3430. for (int i = 4; --i >= 0;)
  3431. juce_free (s[i]);
  3432. }
  3433. uint32 BlowFish::F (uint32 x) const
  3434. {
  3435. uint16 a, b, c, d;
  3436. uint32 y;
  3437. d = (uint16) (x & 0xff);
  3438. x >>= 8;
  3439. c = (uint16) (x & 0xff);
  3440. x >>= 8;
  3441. b = (uint16) (x & 0xff);
  3442. x >>= 8;
  3443. a = (uint16) (x & 0xff);
  3444. y = s[0][a] + s[1][b];
  3445. y = y ^ s[2][c];
  3446. y = y + s[3][d];
  3447. return y;
  3448. }
  3449. void BlowFish::encrypt (uint32& data1,
  3450. uint32& data2) const
  3451. {
  3452. uint32 l = data1;
  3453. uint32 r = data2;
  3454. for (int i = 0; i < 16; ++i)
  3455. {
  3456. l = l ^ p[i];
  3457. r = F (l) ^ r;
  3458. const uint32 temp = l;
  3459. l = r;
  3460. r = temp;
  3461. }
  3462. const uint32 temp = l;
  3463. l = r;
  3464. r = temp;
  3465. r = r ^ p[16];
  3466. l = l ^ p[17];
  3467. data1 = l;
  3468. data2 = r;
  3469. }
  3470. void BlowFish::decrypt (uint32& data1,
  3471. uint32& data2) const
  3472. {
  3473. uint32 l = data1;
  3474. uint32 r = data2;
  3475. for (int i = 17; i > 1; --i)
  3476. {
  3477. l =l ^ p[i];
  3478. r = F (l) ^ r;
  3479. const uint32 temp = l;
  3480. l = r;
  3481. r = temp;
  3482. }
  3483. const uint32 temp = l;
  3484. l = r;
  3485. r = temp;
  3486. r = r ^ p[1];
  3487. l = l ^ p[0];
  3488. data1 = l;
  3489. data2 = r;
  3490. }
  3491. END_JUCE_NAMESPACE
  3492. /********* End of inlined file: juce_BlowFish.cpp *********/
  3493. /********* Start of inlined file: juce_MD5.cpp *********/
  3494. BEGIN_JUCE_NAMESPACE
  3495. MD5::MD5()
  3496. {
  3497. zeromem (result, sizeof (result));
  3498. }
  3499. MD5::MD5 (const MD5& other)
  3500. {
  3501. memcpy (result, other.result, sizeof (result));
  3502. }
  3503. const MD5& MD5::operator= (const MD5& other)
  3504. {
  3505. memcpy (result, other.result, sizeof (result));
  3506. return *this;
  3507. }
  3508. MD5::MD5 (const MemoryBlock& data)
  3509. {
  3510. ProcessContext context;
  3511. context.processBlock ((const uint8*) data.getData(), data.getSize());
  3512. context.finish (result);
  3513. }
  3514. MD5::MD5 (const char* data, const int numBytes)
  3515. {
  3516. ProcessContext context;
  3517. context.processBlock ((const uint8*) data, numBytes);
  3518. context.finish (result);
  3519. }
  3520. MD5::MD5 (const String& text)
  3521. {
  3522. ProcessContext context;
  3523. const int len = text.length();
  3524. const juce_wchar* const t = text;
  3525. for (int i = 0; i < len; ++i)
  3526. {
  3527. // force the string into integer-sized unicode characters, to try to make it
  3528. // get the same results on all platforms + compilers.
  3529. uint32 unicodeChar = (uint32) t[i];
  3530. swapIfBigEndian (unicodeChar);
  3531. context.processBlock ((const uint8*) &unicodeChar,
  3532. sizeof (unicodeChar));
  3533. }
  3534. context.finish (result);
  3535. }
  3536. void MD5::processStream (InputStream& input, int numBytesToRead)
  3537. {
  3538. ProcessContext context;
  3539. if (numBytesToRead < 0)
  3540. numBytesToRead = INT_MAX;
  3541. while (numBytesToRead > 0)
  3542. {
  3543. char tempBuffer [512];
  3544. const int bytesRead = input.read (tempBuffer, jmin (numBytesToRead, sizeof (tempBuffer)));
  3545. if (bytesRead <= 0)
  3546. break;
  3547. numBytesToRead -= bytesRead;
  3548. context.processBlock ((const uint8*) tempBuffer, bytesRead);
  3549. }
  3550. context.finish (result);
  3551. }
  3552. MD5::MD5 (InputStream& input, int numBytesToRead)
  3553. {
  3554. processStream (input, numBytesToRead);
  3555. }
  3556. MD5::MD5 (const File& file)
  3557. {
  3558. FileInputStream* const fin = file.createInputStream();
  3559. if (fin != 0)
  3560. {
  3561. processStream (*fin, -1);
  3562. delete fin;
  3563. }
  3564. else
  3565. {
  3566. zeromem (result, sizeof (result));
  3567. }
  3568. }
  3569. MD5::~MD5()
  3570. {
  3571. }
  3572. MD5::ProcessContext::ProcessContext()
  3573. {
  3574. state[0] = 0x67452301;
  3575. state[1] = 0xefcdab89;
  3576. state[2] = 0x98badcfe;
  3577. state[3] = 0x10325476;
  3578. count[0] = 0;
  3579. count[1] = 0;
  3580. }
  3581. void MD5::ProcessContext::processBlock (const uint8* const data, int dataSize)
  3582. {
  3583. int bufferPos = ((count[0] >> 3) & 0x3F);
  3584. count[0] += (dataSize << 3);
  3585. if (count[0] < ((uint32) dataSize << 3))
  3586. count[1]++;
  3587. count[1] += (dataSize >> 29);
  3588. const int spaceLeft = 64 - bufferPos;
  3589. int i = 0;
  3590. if (dataSize >= spaceLeft)
  3591. {
  3592. memcpy (buffer + bufferPos, data, spaceLeft);
  3593. transform (buffer);
  3594. i = spaceLeft;
  3595. while (i < dataSize - 63)
  3596. {
  3597. transform (data + i);
  3598. i += 64;
  3599. }
  3600. bufferPos = 0;
  3601. }
  3602. memcpy (buffer + bufferPos, data + i, dataSize - i);
  3603. }
  3604. static void encode (uint8* const output,
  3605. const uint32* const input,
  3606. const int numBytes)
  3607. {
  3608. uint32* const o = (uint32*) output;
  3609. for (int i = 0; i < (numBytes >> 2); ++i)
  3610. o[i] = swapIfBigEndian (input [i]);
  3611. }
  3612. static void decode (uint32* const output,
  3613. const uint8* const input,
  3614. const int numBytes)
  3615. {
  3616. for (int i = 0; i < (numBytes >> 2); ++i)
  3617. output[i] = littleEndianInt ((const char*) input + (i << 2));
  3618. }
  3619. void MD5::ProcessContext::finish (uint8* const result)
  3620. {
  3621. unsigned char encodedLength[8];
  3622. encode (encodedLength, count, 8);
  3623. // Pad out to 56 mod 64.
  3624. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  3625. const int paddingLength = (index < 56) ? (56 - index)
  3626. : (120 - index);
  3627. uint8 paddingBuffer [64];
  3628. zeromem (paddingBuffer, paddingLength);
  3629. paddingBuffer [0] = 0x80;
  3630. processBlock (paddingBuffer, paddingLength);
  3631. processBlock (encodedLength, 8);
  3632. encode (result, state, 16);
  3633. zeromem (buffer, sizeof (buffer));
  3634. }
  3635. #define S11 7
  3636. #define S12 12
  3637. #define S13 17
  3638. #define S14 22
  3639. #define S21 5
  3640. #define S22 9
  3641. #define S23 14
  3642. #define S24 20
  3643. #define S31 4
  3644. #define S32 11
  3645. #define S33 16
  3646. #define S34 23
  3647. #define S41 6
  3648. #define S42 10
  3649. #define S43 15
  3650. #define S44 21
  3651. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) { return (x & y) | (~x & z); }
  3652. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) { return (x & z) | (y & ~z); }
  3653. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) { return x ^ y ^ z; }
  3654. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) { return y ^ (x | ~z); }
  3655. static inline uint32 rotateLeft (const uint32 x, const uint32 n) { return (x << n) | (x >> (32 - n)); }
  3656. static inline void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3657. {
  3658. a += F (b, c, d) + x + ac;
  3659. a = rotateLeft (a, s) + b;
  3660. }
  3661. static inline void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3662. {
  3663. a += G (b, c, d) + x + ac;
  3664. a = rotateLeft (a, s) + b;
  3665. }
  3666. static inline void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3667. {
  3668. a += H (b, c, d) + x + ac;
  3669. a = rotateLeft (a, s) + b;
  3670. }
  3671. static inline void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3672. {
  3673. a += I (b, c, d) + x + ac;
  3674. a = rotateLeft (a, s) + b;
  3675. }
  3676. void MD5::ProcessContext::transform (const uint8* const buffer)
  3677. {
  3678. uint32 a = state[0];
  3679. uint32 b = state[1];
  3680. uint32 c = state[2];
  3681. uint32 d = state[3];
  3682. uint32 x[16];
  3683. decode (x, buffer, 64);
  3684. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
  3685. FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
  3686. FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
  3687. FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
  3688. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
  3689. FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
  3690. FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
  3691. FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
  3692. FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
  3693. FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
  3694. FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
  3695. FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
  3696. FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
  3697. FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
  3698. FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
  3699. FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
  3700. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
  3701. GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
  3702. GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
  3703. GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
  3704. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
  3705. GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
  3706. GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
  3707. GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
  3708. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
  3709. GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
  3710. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
  3711. GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
  3712. GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
  3713. GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
  3714. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
  3715. GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
  3716. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
  3717. HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
  3718. HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
  3719. HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
  3720. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
  3721. HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
  3722. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
  3723. HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
  3724. HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
  3725. HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
  3726. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
  3727. HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
  3728. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
  3729. HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
  3730. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
  3731. HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
  3732. II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
  3733. II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
  3734. II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
  3735. II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
  3736. II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
  3737. II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
  3738. II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
  3739. II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
  3740. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
  3741. II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
  3742. II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
  3743. II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
  3744. II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
  3745. II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
  3746. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
  3747. II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
  3748. state[0] += a;
  3749. state[1] += b;
  3750. state[2] += c;
  3751. state[3] += d;
  3752. zeromem (x, sizeof (x));
  3753. }
  3754. const MemoryBlock MD5::getRawChecksumData() const
  3755. {
  3756. return MemoryBlock (result, 16);
  3757. }
  3758. const String MD5::toHexString() const
  3759. {
  3760. return String::toHexString (result, 16, 0);
  3761. }
  3762. bool MD5::operator== (const MD5& other) const
  3763. {
  3764. return memcmp (result, other.result, 16) == 0;
  3765. }
  3766. bool MD5::operator!= (const MD5& other) const
  3767. {
  3768. return ! operator== (other);
  3769. }
  3770. END_JUCE_NAMESPACE
  3771. /********* End of inlined file: juce_MD5.cpp *********/
  3772. /********* Start of inlined file: juce_Primes.cpp *********/
  3773. BEGIN_JUCE_NAMESPACE
  3774. static void createSmallSieve (const int numBits, BitArray& result) throw()
  3775. {
  3776. result.setBit (numBits);
  3777. result.clearBit (numBits); // to enlarge the array
  3778. result.setBit (0);
  3779. int n = 2;
  3780. do
  3781. {
  3782. for (int i = n + n; i < numBits; i += n)
  3783. result.setBit (i);
  3784. n = result.findNextClearBit (n + 1);
  3785. }
  3786. while (n <= (numBits >> 1));
  3787. }
  3788. static void bigSieve (const BitArray& base,
  3789. const int numBits,
  3790. BitArray& result,
  3791. const BitArray& smallSieve,
  3792. const int smallSieveSize) throw()
  3793. {
  3794. jassert (! base[0]); // must be even!
  3795. result.setBit (numBits);
  3796. result.clearBit (numBits); // to enlarge the array
  3797. int index = smallSieve.findNextClearBit (0);
  3798. do
  3799. {
  3800. const int prime = (index << 1) + 1;
  3801. BitArray r (base);
  3802. BitArray remainder;
  3803. r.divideBy (prime, remainder);
  3804. int i = prime - remainder.getBitRangeAsInt (0, 32);
  3805. if (r.isEmpty())
  3806. i += prime;
  3807. if ((i & 1) == 0)
  3808. i += prime;
  3809. i = (i - 1) >> 1;
  3810. while (i < numBits)
  3811. {
  3812. result.setBit (i);
  3813. i += prime;
  3814. }
  3815. index = smallSieve.findNextClearBit (index + 1);
  3816. }
  3817. while (index < smallSieveSize);
  3818. }
  3819. static bool findCandidate (const BitArray& base,
  3820. const BitArray& sieve,
  3821. const int numBits,
  3822. BitArray& result,
  3823. const int certainty) throw()
  3824. {
  3825. for (int i = 0; i < numBits; ++i)
  3826. {
  3827. if (! sieve[i])
  3828. {
  3829. result = base;
  3830. result.add (BitArray ((unsigned int) ((i << 1) + 1)));
  3831. if (Primes::isProbablyPrime (result, certainty))
  3832. return true;
  3833. }
  3834. }
  3835. return false;
  3836. }
  3837. const BitArray Primes::createProbablePrime (const int bitLength,
  3838. const int certainty,
  3839. const int* randomSeeds,
  3840. int numRandomSeeds) throw()
  3841. {
  3842. int defaultSeeds [16];
  3843. if (numRandomSeeds <= 0)
  3844. {
  3845. randomSeeds = defaultSeeds;
  3846. numRandomSeeds = numElementsInArray (defaultSeeds);
  3847. Random r (0);
  3848. for (int j = 10; --j >= 0;)
  3849. {
  3850. r.setSeedRandomly();
  3851. for (int i = numRandomSeeds; --i >= 0;)
  3852. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  3853. }
  3854. }
  3855. BitArray smallSieve;
  3856. const int smallSieveSize = 15000;
  3857. createSmallSieve (smallSieveSize, smallSieve);
  3858. BitArray p;
  3859. for (int i = numRandomSeeds; --i >= 0;)
  3860. {
  3861. BitArray p2;
  3862. Random r (randomSeeds[i]);
  3863. r.fillBitsRandomly (p2, 0, bitLength);
  3864. p.xorWith (p2);
  3865. }
  3866. p.setBit (bitLength - 1);
  3867. p.clearBit (0);
  3868. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  3869. while (p.getHighestBit() < bitLength)
  3870. {
  3871. p.add (2 * searchLen);
  3872. BitArray sieve;
  3873. bigSieve (p, searchLen, sieve,
  3874. smallSieve, smallSieveSize);
  3875. BitArray candidate;
  3876. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  3877. return candidate;
  3878. }
  3879. jassertfalse
  3880. return BitArray();
  3881. }
  3882. static bool passesMillerRabin (const BitArray& n, int iterations) throw()
  3883. {
  3884. const BitArray one (1);
  3885. const BitArray two (2);
  3886. BitArray nMinusOne (n);
  3887. nMinusOne.subtract (one);
  3888. BitArray d (nMinusOne);
  3889. const int s = d.findNextSetBit (0);
  3890. d.shiftBits (-s);
  3891. BitArray smallPrimes;
  3892. int numBitsInSmallPrimes = 0;
  3893. for (;;)
  3894. {
  3895. numBitsInSmallPrimes += 256;
  3896. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  3897. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  3898. if (numPrimesFound > iterations + 1)
  3899. break;
  3900. }
  3901. int smallPrime = 2;
  3902. while (--iterations >= 0)
  3903. {
  3904. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  3905. BitArray r (smallPrime);
  3906. //r.createRandomNumber (nMinusOne);
  3907. r.exponentModulo (d, n);
  3908. if (! (r == one || r == nMinusOne))
  3909. {
  3910. for (int j = 0; j < s; ++j)
  3911. {
  3912. r.exponentModulo (two, n);
  3913. if (r == nMinusOne)
  3914. break;
  3915. }
  3916. if (r != nMinusOne)
  3917. return false;
  3918. }
  3919. }
  3920. return true;
  3921. }
  3922. bool Primes::isProbablyPrime (const BitArray& number,
  3923. const int certainty) throw()
  3924. {
  3925. if (! number[0])
  3926. return false;
  3927. if (number.getHighestBit() <= 10)
  3928. {
  3929. const int num = number.getBitRangeAsInt (0, 10);
  3930. for (int i = num / 2; --i > 1;)
  3931. if (num % i == 0)
  3932. return false;
  3933. return true;
  3934. }
  3935. else
  3936. {
  3937. const BitArray screen (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23);
  3938. if (number.findGreatestCommonDivisor (screen) != BitArray (1))
  3939. return false;
  3940. return passesMillerRabin (number, certainty);
  3941. }
  3942. }
  3943. END_JUCE_NAMESPACE
  3944. /********* End of inlined file: juce_Primes.cpp *********/
  3945. /********* Start of inlined file: juce_RSAKey.cpp *********/
  3946. BEGIN_JUCE_NAMESPACE
  3947. RSAKey::RSAKey() throw()
  3948. {
  3949. }
  3950. RSAKey::RSAKey (const String& s) throw()
  3951. {
  3952. if (s.containsChar (T(',')))
  3953. {
  3954. part1.parseString (s.upToFirstOccurrenceOf (T(","), false, false), 16);
  3955. part2.parseString (s.fromFirstOccurrenceOf (T(","), false, false), 16);
  3956. }
  3957. else
  3958. {
  3959. // the string needs to be two hex numbers, comma-separated..
  3960. jassertfalse;
  3961. }
  3962. }
  3963. RSAKey::~RSAKey() throw()
  3964. {
  3965. }
  3966. const String RSAKey::toString() const throw()
  3967. {
  3968. return part1.toString (16) + T(",") + part2.toString (16);
  3969. }
  3970. bool RSAKey::applyToValue (BitArray& value) const throw()
  3971. {
  3972. if (part1.isEmpty() || part2.isEmpty()
  3973. || value.compare (0) <= 0)
  3974. {
  3975. jassertfalse // using an uninitialised key
  3976. value.clear();
  3977. return false;
  3978. }
  3979. BitArray result;
  3980. while (! value.isEmpty())
  3981. {
  3982. result.multiplyBy (part2);
  3983. BitArray remainder;
  3984. value.divideBy (part2, remainder);
  3985. remainder.exponentModulo (part1, part2);
  3986. result.add (remainder);
  3987. }
  3988. value = result;
  3989. return true;
  3990. }
  3991. static const BitArray findBestCommonDivisor (const BitArray& p,
  3992. const BitArray& q) throw()
  3993. {
  3994. const BitArray one (1);
  3995. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  3996. // are fast to divide + multiply
  3997. for (int i = 2; i <= 65536; i *= 2)
  3998. {
  3999. const BitArray e (1 + i);
  4000. if (e.findGreatestCommonDivisor (p) == one
  4001. && e.findGreatestCommonDivisor (q) == one)
  4002. {
  4003. return e;
  4004. }
  4005. }
  4006. BitArray e (4);
  4007. while (! (e.findGreatestCommonDivisor (p) == one
  4008. && e.findGreatestCommonDivisor (q) == one))
  4009. {
  4010. e.add (one);
  4011. }
  4012. return e;
  4013. }
  4014. void RSAKey::createKeyPair (RSAKey& publicKey,
  4015. RSAKey& privateKey,
  4016. const int numBits,
  4017. const int* randomSeeds,
  4018. const int numRandomSeeds) throw()
  4019. {
  4020. jassert (numBits > 16); // not much point using less than this..
  4021. BitArray p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds));
  4022. BitArray q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds, numRandomSeeds));
  4023. BitArray n (p);
  4024. n.multiplyBy (q); // n = pq
  4025. const BitArray one (1);
  4026. p.subtract (one);
  4027. q.subtract (one);
  4028. BitArray m (p);
  4029. m.multiplyBy (q); // m = (p - 1)(q - 1)
  4030. const BitArray e (findBestCommonDivisor (p, q));
  4031. BitArray d (e);
  4032. d.inverseModulo (m);
  4033. publicKey.part1 = e;
  4034. publicKey.part2 = n;
  4035. privateKey.part1 = d;
  4036. privateKey.part2 = n;
  4037. }
  4038. END_JUCE_NAMESPACE
  4039. /********* End of inlined file: juce_RSAKey.cpp *********/
  4040. /********* Start of inlined file: juce_InputStream.cpp *********/
  4041. BEGIN_JUCE_NAMESPACE
  4042. char InputStream::readByte()
  4043. {
  4044. char temp = 0;
  4045. read (&temp, 1);
  4046. return temp;
  4047. }
  4048. bool InputStream::readBool()
  4049. {
  4050. return readByte() != 0;
  4051. }
  4052. short InputStream::readShort()
  4053. {
  4054. char temp [2];
  4055. if (read (temp, 2) == 2)
  4056. return (short) littleEndianShort (temp);
  4057. else
  4058. return 0;
  4059. }
  4060. short InputStream::readShortBigEndian()
  4061. {
  4062. char temp [2];
  4063. if (read (temp, 2) == 2)
  4064. return (short) bigEndianShort (temp);
  4065. else
  4066. return 0;
  4067. }
  4068. int InputStream::readInt()
  4069. {
  4070. char temp [4];
  4071. if (read (temp, 4) == 4)
  4072. return (int) littleEndianInt (temp);
  4073. else
  4074. return 0;
  4075. }
  4076. int InputStream::readIntBigEndian()
  4077. {
  4078. char temp [4];
  4079. if (read (temp, 4) == 4)
  4080. return (int) bigEndianInt (temp);
  4081. else
  4082. return 0;
  4083. }
  4084. int InputStream::readCompressedInt()
  4085. {
  4086. int num = 0;
  4087. if (! isExhausted())
  4088. {
  4089. unsigned char numBytes = readByte();
  4090. const bool negative = (numBytes & 0x80) != 0;
  4091. numBytes &= 0x7f;
  4092. if (numBytes <= 4)
  4093. {
  4094. if (read (&num, numBytes) != numBytes)
  4095. return 0;
  4096. if (negative)
  4097. num = -num;
  4098. }
  4099. }
  4100. return num;
  4101. }
  4102. int64 InputStream::readInt64()
  4103. {
  4104. char temp [8];
  4105. if (read (temp, 8) == 8)
  4106. return (int64) swapIfBigEndian (*(uint64*)temp);
  4107. else
  4108. return 0;
  4109. }
  4110. int64 InputStream::readInt64BigEndian()
  4111. {
  4112. char temp [8];
  4113. if (read (temp, 8) == 8)
  4114. return (int64) swapIfLittleEndian (*(uint64*)temp);
  4115. else
  4116. return 0;
  4117. }
  4118. float InputStream::readFloat()
  4119. {
  4120. union { int asInt; float asFloat; } n;
  4121. n.asInt = readInt();
  4122. return n.asFloat;
  4123. }
  4124. float InputStream::readFloatBigEndian()
  4125. {
  4126. union { int asInt; float asFloat; } n;
  4127. n.asInt = readIntBigEndian();
  4128. return n.asFloat;
  4129. }
  4130. double InputStream::readDouble()
  4131. {
  4132. union { int64 asInt; double asDouble; } n;
  4133. n.asInt = readInt64();
  4134. return n.asDouble;
  4135. }
  4136. double InputStream::readDoubleBigEndian()
  4137. {
  4138. union { int64 asInt; double asDouble; } n;
  4139. n.asInt = readInt64BigEndian();
  4140. return n.asDouble;
  4141. }
  4142. const String InputStream::readString()
  4143. {
  4144. const int tempBufferSize = 256;
  4145. uint8 temp [tempBufferSize];
  4146. int i = 0;
  4147. while ((temp [i++] = readByte()) != 0)
  4148. {
  4149. if (i == tempBufferSize)
  4150. {
  4151. // too big for our quick buffer, so read it in blocks..
  4152. String result (String::fromUTF8 (temp, i));
  4153. i = 0;
  4154. for (;;)
  4155. {
  4156. if ((temp [i++] = readByte()) == 0)
  4157. {
  4158. result += String::fromUTF8 (temp, i - 1);
  4159. break;
  4160. }
  4161. else if (i == tempBufferSize)
  4162. {
  4163. result += String::fromUTF8 (temp, i);
  4164. i = 0;
  4165. }
  4166. }
  4167. return result;
  4168. }
  4169. }
  4170. return String::fromUTF8 (temp, i - 1);
  4171. }
  4172. const String InputStream::readNextLine()
  4173. {
  4174. String s;
  4175. const int maxChars = 256;
  4176. tchar buffer [maxChars];
  4177. int charsInBuffer = 0;
  4178. while (! isExhausted())
  4179. {
  4180. const uint8 c = readByte();
  4181. const int64 lastPos = getPosition();
  4182. if (c == '\n')
  4183. {
  4184. break;
  4185. }
  4186. else if (c == '\r')
  4187. {
  4188. if (readByte() != '\n')
  4189. setPosition (lastPos);
  4190. break;
  4191. }
  4192. buffer [charsInBuffer++] = c;
  4193. if (charsInBuffer == maxChars)
  4194. {
  4195. s.append (buffer, maxChars);
  4196. charsInBuffer = 0;
  4197. }
  4198. }
  4199. if (charsInBuffer > 0)
  4200. s.append (buffer, charsInBuffer);
  4201. return s;
  4202. }
  4203. int InputStream::readIntoMemoryBlock (MemoryBlock& block,
  4204. int numBytes)
  4205. {
  4206. const int64 totalLength = getTotalLength();
  4207. if (totalLength >= 0)
  4208. {
  4209. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  4210. totalLength - getPosition());
  4211. if (numBytes < 0)
  4212. numBytes = totalBytesRemaining;
  4213. else if (numBytes > 0)
  4214. numBytes = jmin (numBytes, totalBytesRemaining);
  4215. else
  4216. return 0;
  4217. }
  4218. const int originalBlockSize = block.getSize();
  4219. int totalBytesRead = 0;
  4220. if (numBytes > 0)
  4221. {
  4222. // know how many bytes we want, so we can resize the block first..
  4223. block.setSize (originalBlockSize + numBytes, false);
  4224. totalBytesRead = read (((char*) block.getData()) + originalBlockSize, numBytes);
  4225. }
  4226. else
  4227. {
  4228. // read until end of stram..
  4229. const int chunkSize = 32768;
  4230. for (;;)
  4231. {
  4232. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  4233. const int bytesJustIn = read (((char*) block.getData())
  4234. + originalBlockSize
  4235. + totalBytesRead,
  4236. chunkSize);
  4237. if (bytesJustIn == 0)
  4238. break;
  4239. totalBytesRead += bytesJustIn;
  4240. }
  4241. }
  4242. // trim off any excess left at the end
  4243. block.setSize (originalBlockSize + totalBytesRead, false);
  4244. return totalBytesRead;
  4245. }
  4246. const String InputStream::readEntireStreamAsString()
  4247. {
  4248. MemoryBlock mb;
  4249. const int size = readIntoMemoryBlock (mb);
  4250. return String::createStringFromData ((const char*) mb.getData(), size);
  4251. }
  4252. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4253. {
  4254. if (numBytesToSkip > 0)
  4255. {
  4256. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4257. MemoryBlock temp (skipBufferSize);
  4258. while ((numBytesToSkip > 0) && ! isExhausted())
  4259. {
  4260. numBytesToSkip -= read (temp.getData(), (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4261. }
  4262. }
  4263. }
  4264. END_JUCE_NAMESPACE
  4265. /********* End of inlined file: juce_InputStream.cpp *********/
  4266. /********* Start of inlined file: juce_OutputStream.cpp *********/
  4267. BEGIN_JUCE_NAMESPACE
  4268. #if JUCE_DEBUG
  4269. static CriticalSection activeStreamLock;
  4270. static VoidArray activeStreams;
  4271. void juce_CheckForDanglingStreams()
  4272. {
  4273. /*
  4274. It's always a bad idea to leak any object, but if you're leaking output
  4275. streams, then there's a good chance that you're failing to flush a file
  4276. to disk properly, which could result in corrupted data and other similar
  4277. nastiness..
  4278. */
  4279. jassert (activeStreams.size() == 0);
  4280. };
  4281. #endif
  4282. OutputStream::OutputStream() throw()
  4283. {
  4284. #if JUCE_DEBUG
  4285. activeStreamLock.enter();
  4286. activeStreams.add (this);
  4287. activeStreamLock.exit();
  4288. #endif
  4289. }
  4290. OutputStream::~OutputStream()
  4291. {
  4292. #if JUCE_DEBUG
  4293. activeStreamLock.enter();
  4294. activeStreams.removeValue (this);
  4295. activeStreamLock.exit();
  4296. #endif
  4297. }
  4298. void OutputStream::writeBool (bool b)
  4299. {
  4300. writeByte ((b) ? (char) 1
  4301. : (char) 0);
  4302. }
  4303. void OutputStream::writeByte (char byte)
  4304. {
  4305. write (&byte, 1);
  4306. }
  4307. void OutputStream::writeShort (short value)
  4308. {
  4309. const unsigned short v = swapIfBigEndian ((unsigned short) value);
  4310. write (&v, 2);
  4311. }
  4312. void OutputStream::writeShortBigEndian (short value)
  4313. {
  4314. const unsigned short v = swapIfLittleEndian ((unsigned short) value);
  4315. write (&v, 2);
  4316. }
  4317. void OutputStream::writeInt (int value)
  4318. {
  4319. const unsigned int v = swapIfBigEndian ((unsigned int) value);
  4320. write (&v, 4);
  4321. }
  4322. void OutputStream::writeIntBigEndian (int value)
  4323. {
  4324. const unsigned int v = swapIfLittleEndian ((unsigned int) value);
  4325. write (&v, 4);
  4326. }
  4327. void OutputStream::writeCompressedInt (int value)
  4328. {
  4329. unsigned int un = (value < 0) ? (unsigned int) -value
  4330. : (unsigned int) value;
  4331. unsigned int tn = un;
  4332. int numSigBytes = 0;
  4333. do
  4334. {
  4335. tn >>= 8;
  4336. numSigBytes++;
  4337. } while (tn & 0xff);
  4338. if (value < 0)
  4339. numSigBytes |= 0x80;
  4340. writeByte ((char) numSigBytes);
  4341. write (&un, numSigBytes);
  4342. }
  4343. void OutputStream::writeInt64 (int64 value)
  4344. {
  4345. const uint64 v = swapIfBigEndian ((uint64) value);
  4346. write (&v, 8);
  4347. }
  4348. void OutputStream::writeInt64BigEndian (int64 value)
  4349. {
  4350. const uint64 v = swapIfLittleEndian ((uint64) value);
  4351. write (&v, 8);
  4352. }
  4353. void OutputStream::writeFloat (float value)
  4354. {
  4355. union { int asInt; float asFloat; } n;
  4356. n.asFloat = value;
  4357. writeInt (n.asInt);
  4358. }
  4359. void OutputStream::writeFloatBigEndian (float value)
  4360. {
  4361. union { int asInt; float asFloat; } n;
  4362. n.asFloat = value;
  4363. writeIntBigEndian (n.asInt);
  4364. }
  4365. void OutputStream::writeDouble (double value)
  4366. {
  4367. union { int64 asInt; double asDouble; } n;
  4368. n.asDouble = value;
  4369. writeInt64 (n.asInt);
  4370. }
  4371. void OutputStream::writeDoubleBigEndian (double value)
  4372. {
  4373. union { int64 asInt; double asDouble; } n;
  4374. n.asDouble = value;
  4375. writeInt64BigEndian (n.asInt);
  4376. }
  4377. void OutputStream::writeString (const String& text)
  4378. {
  4379. const int numBytes = text.copyToUTF8 (0);
  4380. uint8* const temp = (uint8*) juce_malloc (numBytes);
  4381. text.copyToUTF8 (temp);
  4382. write (temp, numBytes); // (numBytes includes the terminating null).
  4383. juce_free (temp);
  4384. }
  4385. void OutputStream::printf (const char* pf, ...)
  4386. {
  4387. unsigned int bufSize = 256;
  4388. char* buf = (char*) juce_malloc (bufSize);
  4389. for (;;)
  4390. {
  4391. va_list list;
  4392. va_start (list, pf);
  4393. const int num = CharacterFunctions::vprintf (buf, bufSize, pf, list);
  4394. va_end (list);
  4395. if (num > 0)
  4396. {
  4397. write (buf, num);
  4398. break;
  4399. }
  4400. else if (num == 0)
  4401. {
  4402. break;
  4403. }
  4404. juce_free (buf);
  4405. bufSize += 256;
  4406. buf = (char*) juce_malloc (bufSize);
  4407. }
  4408. juce_free (buf);
  4409. }
  4410. OutputStream& OutputStream::operator<< (const int number)
  4411. {
  4412. const String s (number);
  4413. write ((const char*) s, s.length());
  4414. return *this;
  4415. }
  4416. OutputStream& OutputStream::operator<< (const double number)
  4417. {
  4418. const String s (number);
  4419. write ((const char*) s, s.length());
  4420. return *this;
  4421. }
  4422. OutputStream& OutputStream::operator<< (const char character)
  4423. {
  4424. writeByte (character);
  4425. return *this;
  4426. }
  4427. OutputStream& OutputStream::operator<< (const char* const text)
  4428. {
  4429. write (text, (int) strlen (text));
  4430. return *this;
  4431. }
  4432. OutputStream& OutputStream::operator<< (const juce_wchar* const text)
  4433. {
  4434. const String s (text);
  4435. write ((const char*) s, s.length());
  4436. return *this;
  4437. }
  4438. OutputStream& OutputStream::operator<< (const String& text)
  4439. {
  4440. write ((const char*) text,
  4441. text.length());
  4442. return *this;
  4443. }
  4444. void OutputStream::writeText (const String& text,
  4445. const bool asUnicode,
  4446. const bool writeUnicodeHeaderBytes)
  4447. {
  4448. if (asUnicode)
  4449. {
  4450. if (writeUnicodeHeaderBytes)
  4451. write ("\x0ff\x0fe", 2);
  4452. const juce_wchar* src = (const juce_wchar*) text;
  4453. bool lastCharWasReturn = false;
  4454. while (*src != 0)
  4455. {
  4456. if (*src == L'\n' && ! lastCharWasReturn)
  4457. writeShort ((short) L'\r');
  4458. lastCharWasReturn = (*src == L'\r');
  4459. writeShort ((short) *src++);
  4460. }
  4461. }
  4462. else
  4463. {
  4464. const char* src = (const char*) text;
  4465. const char* t = src;
  4466. for (;;)
  4467. {
  4468. if (*t == '\n')
  4469. {
  4470. if (t > src)
  4471. write (src, (int) (t - src));
  4472. write ("\r\n", 2);
  4473. src = t + 1;
  4474. }
  4475. else if (*t == '\r')
  4476. {
  4477. if (t[1] == '\n')
  4478. ++t;
  4479. }
  4480. else if (*t == 0)
  4481. {
  4482. if (t > src)
  4483. write (src, (int) (t - src));
  4484. break;
  4485. }
  4486. ++t;
  4487. }
  4488. }
  4489. }
  4490. int OutputStream::writeFromInputStream (InputStream& source,
  4491. int numBytesToWrite)
  4492. {
  4493. if (numBytesToWrite < 0)
  4494. numBytesToWrite = 0x7fffffff;
  4495. int numWritten = 0;
  4496. while (numBytesToWrite > 0 && ! source.isExhausted())
  4497. {
  4498. char buffer [8192];
  4499. const int num = source.read (buffer, jmin (numBytesToWrite, sizeof (buffer)));
  4500. if (num == 0)
  4501. break;
  4502. write (buffer, num);
  4503. numBytesToWrite -= num;
  4504. numWritten += num;
  4505. }
  4506. return numWritten;
  4507. }
  4508. END_JUCE_NAMESPACE
  4509. /********* End of inlined file: juce_OutputStream.cpp *********/
  4510. /********* Start of inlined file: juce_DirectoryIterator.cpp *********/
  4511. BEGIN_JUCE_NAMESPACE
  4512. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  4513. bool* isDirectory, bool* isHidden, int64* fileSize,
  4514. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4515. bool juce_findFileNext (void* handle, String& resultFile,
  4516. bool* isDirectory, bool* isHidden, int64* fileSize,
  4517. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4518. void juce_findFileClose (void* handle) throw();
  4519. DirectoryIterator::DirectoryIterator (const File& directory,
  4520. bool isRecursive,
  4521. const String& wc,
  4522. const int whatToLookFor_) throw()
  4523. : wildCard (wc),
  4524. index (-1),
  4525. whatToLookFor (whatToLookFor_),
  4526. subIterator (0)
  4527. {
  4528. // you have to specify the type of files you're looking for!
  4529. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4530. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4531. String path (directory.getFullPathName());
  4532. if (! path.endsWithChar (File::separator))
  4533. path += File::separator;
  4534. String filename;
  4535. bool isDirectory, isHidden;
  4536. void* const handle = juce_findFileStart (path,
  4537. isRecursive ? T("*") : wc,
  4538. filename, &isDirectory, &isHidden, 0, 0, 0, 0);
  4539. if (handle != 0)
  4540. {
  4541. do
  4542. {
  4543. if (! filename.containsOnly (T(".")))
  4544. {
  4545. bool addToList = false;
  4546. if (isDirectory)
  4547. {
  4548. if (isRecursive
  4549. && ((whatToLookFor_ & File::ignoreHiddenFiles) == 0
  4550. || ! isHidden))
  4551. {
  4552. dirsFound.add (new File (path + filename, 0));
  4553. }
  4554. addToList = (whatToLookFor_ & File::findDirectories) != 0;
  4555. }
  4556. else
  4557. {
  4558. addToList = (whatToLookFor_ & File::findFiles) != 0;
  4559. }
  4560. // if it's recursive, we're not relying on the OS iterator
  4561. // to do the wildcard match, so do it now..
  4562. if (isRecursive && addToList)
  4563. addToList = filename.matchesWildcard (wc, true);
  4564. if (addToList && (whatToLookFor_ & File::ignoreHiddenFiles) != 0)
  4565. addToList = ! isHidden;
  4566. if (addToList)
  4567. filesFound.add (new File (path + filename, 0));
  4568. }
  4569. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  4570. juce_findFileClose (handle);
  4571. }
  4572. }
  4573. DirectoryIterator::~DirectoryIterator() throw()
  4574. {
  4575. if (subIterator != 0)
  4576. delete subIterator;
  4577. }
  4578. bool DirectoryIterator::next() throw()
  4579. {
  4580. if (subIterator != 0)
  4581. {
  4582. if (subIterator->next())
  4583. return true;
  4584. deleteAndZero (subIterator);
  4585. }
  4586. if (index >= filesFound.size() + dirsFound.size() - 1)
  4587. return false;
  4588. ++index;
  4589. if (index >= filesFound.size())
  4590. {
  4591. subIterator = new DirectoryIterator (*(dirsFound [index - filesFound.size()]),
  4592. true, wildCard, whatToLookFor);
  4593. return next();
  4594. }
  4595. return true;
  4596. }
  4597. const File DirectoryIterator::getFile() const throw()
  4598. {
  4599. if (subIterator != 0)
  4600. return subIterator->getFile();
  4601. const File* const f = filesFound [index];
  4602. return (f != 0) ? *f
  4603. : File::nonexistent;
  4604. }
  4605. float DirectoryIterator::getEstimatedProgress() const throw()
  4606. {
  4607. if (filesFound.size() + dirsFound.size() == 0)
  4608. {
  4609. return 0.0f;
  4610. }
  4611. else
  4612. {
  4613. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4614. : (float) index;
  4615. return detailedIndex / (filesFound.size() + dirsFound.size());
  4616. }
  4617. }
  4618. END_JUCE_NAMESPACE
  4619. /********* End of inlined file: juce_DirectoryIterator.cpp *********/
  4620. /********* Start of inlined file: juce_File.cpp *********/
  4621. #ifdef _MSC_VER
  4622. #pragma warning (disable: 4514)
  4623. #pragma warning (push)
  4624. #endif
  4625. #ifndef JUCE_WIN32
  4626. #include <pwd.h>
  4627. #endif
  4628. BEGIN_JUCE_NAMESPACE
  4629. #ifdef _MSC_VER
  4630. #pragma warning (pop)
  4631. #endif
  4632. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4633. void juce_fileClose (void* handle) throw();
  4634. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  4635. int64 juce_fileGetPosition (void* handle) throw();
  4636. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4637. void juce_fileFlush (void* handle) throw();
  4638. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw();
  4639. bool juce_isDirectory (const String& fileName) throw();
  4640. int64 juce_getFileSize (const String& fileName) throw();
  4641. bool juce_canWriteToFile (const String& fileName) throw();
  4642. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw();
  4643. void juce_getFileTimes (const String& fileName, int64& modificationTime, int64& accessTime, int64& creationTime) throw();
  4644. bool juce_setFileTimes (const String& fileName, int64 modificationTime, int64 accessTime, int64 creationTime) throw();
  4645. bool juce_deleteFile (const String& fileName) throw();
  4646. bool juce_copyFile (const String& source, const String& dest) throw();
  4647. bool juce_moveFile (const String& source, const String& dest) throw();
  4648. // this must also create all paths involved in the directory.
  4649. void juce_createDirectory (const String& fileName) throw();
  4650. bool juce_launchFile (const String& fileName, const String& parameters) throw();
  4651. const StringArray juce_getFileSystemRoots() throw();
  4652. const String juce_getVolumeLabel (const String& filenameOnVolume, int& volumeSerialNumber) throw();
  4653. // starts a directory search operation with a wildcard, returning a handle for
  4654. // use in calls to juce_findFileNext.
  4655. // juce_firstResultFile gets the name of the file (not the whole pathname) and
  4656. // the other pointers, if non-null, are set based on the properties of the file.
  4657. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  4658. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  4659. Time* creationTime, bool* isReadOnly) throw();
  4660. // returns false when no more files are found
  4661. bool juce_findFileNext (void* handle, String& resultFile,
  4662. bool* isDirectory, bool* isHidden, int64* fileSize,
  4663. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4664. void juce_findFileClose (void* handle) throw();
  4665. static const String juce_addTrailingSeparator (const String& path) throw()
  4666. {
  4667. return path.endsWithChar (File::separator) ? path
  4668. : path + File::separator;
  4669. }
  4670. static const String parseAbsolutePath (String path) throw()
  4671. {
  4672. if (path.isEmpty())
  4673. return String::empty;
  4674. #if JUCE_WIN32
  4675. // Windows..
  4676. path = path.replaceCharacter (T('/'), T('\\'));
  4677. if (path.startsWithChar (File::separator))
  4678. {
  4679. if (path[1] != File::separator)
  4680. {
  4681. jassertfalse // using a filename that starts with a slash is a bit dodgy on
  4682. // Windows, because it needs a drive letter, which in this case
  4683. // we'll take from the CWD.. but this is a bit of an assumption that
  4684. // could be wrong..
  4685. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4686. }
  4687. }
  4688. else if (path.indexOfChar (T(':')) < 0)
  4689. {
  4690. if (path.isEmpty())
  4691. return String::empty;
  4692. jassertfalse // using a partial filename is a bad way to initialise a file, because
  4693. // we don't know what directory to put it in.
  4694. // Here we'll assume it's in the CWD, but this might not be what was
  4695. // intended..
  4696. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4697. }
  4698. #else
  4699. // Mac or Linux..
  4700. path = path.replaceCharacter (T('\\'), T('/'));
  4701. if (path.startsWithChar (T('~')))
  4702. {
  4703. const char* homeDir = 0;
  4704. if (path[1] == File::separator || path[1] == 0)
  4705. {
  4706. // expand a name of the form "~/abc"
  4707. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4708. + path.substring (1);
  4709. }
  4710. else
  4711. {
  4712. // expand a name of type "~dave/abc"
  4713. const String userName (path.substring (1)
  4714. .upToFirstOccurrenceOf (T("/"), false, false));
  4715. struct passwd* const pw = getpwnam (userName);
  4716. if (pw != 0)
  4717. {
  4718. String home (homeDir);
  4719. if (home.endsWithChar (File::separator))
  4720. home [home.length() - 1] = 0;
  4721. path = String (pw->pw_dir)
  4722. + path.substring (userName.length());
  4723. }
  4724. }
  4725. }
  4726. else if (! path.startsWithChar (File::separator))
  4727. {
  4728. while (path.startsWith (T("./")))
  4729. path = path.substring (2);
  4730. if (path.isEmpty())
  4731. return String::empty;
  4732. jassertfalse // using a partial filename is a bad way to initialise a file, because
  4733. // we don't know what directory to put it in.
  4734. // Here we'll assume it's in the CWD, but this might not be what was
  4735. // intended..
  4736. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4737. }
  4738. #endif
  4739. int len = path.length();
  4740. while (--len > 0 && path [len] == File::separator)
  4741. path [len] = 0;
  4742. return path;
  4743. }
  4744. const File File::nonexistent;
  4745. File::File (const String& fullPathName) throw()
  4746. : fullPath (parseAbsolutePath (fullPathName))
  4747. {
  4748. }
  4749. File::File (const String& path, int) throw()
  4750. : fullPath (path)
  4751. {
  4752. }
  4753. File::File (const File& other) throw()
  4754. : fullPath (other.fullPath)
  4755. {
  4756. }
  4757. const File& File::operator= (const String& newPath) throw()
  4758. {
  4759. fullPath = parseAbsolutePath (newPath);
  4760. return *this;
  4761. }
  4762. const File& File::operator= (const File& other) throw()
  4763. {
  4764. fullPath = other.fullPath;
  4765. return *this;
  4766. }
  4767. #if JUCE_LINUX
  4768. #define NAMES_ARE_CASE_SENSITIVE 1
  4769. #endif
  4770. bool File::areFileNamesCaseSensitive()
  4771. {
  4772. #if NAMES_ARE_CASE_SENSITIVE
  4773. return true;
  4774. #else
  4775. return false;
  4776. #endif
  4777. }
  4778. bool File::operator== (const File& other) const throw()
  4779. {
  4780. // case-insensitive on Windows, but not on linux.
  4781. #if NAMES_ARE_CASE_SENSITIVE
  4782. return fullPath == other.fullPath;
  4783. #else
  4784. return fullPath.equalsIgnoreCase (other.fullPath);
  4785. #endif
  4786. }
  4787. bool File::operator!= (const File& other) const throw()
  4788. {
  4789. return ! operator== (other);
  4790. }
  4791. bool File::exists() const throw()
  4792. {
  4793. return juce_fileExists (fullPath, false);
  4794. }
  4795. bool File::existsAsFile() const throw()
  4796. {
  4797. return juce_fileExists (fullPath, true);
  4798. }
  4799. bool File::isDirectory() const throw()
  4800. {
  4801. return juce_isDirectory (fullPath);
  4802. }
  4803. bool File::hasWriteAccess() const throw()
  4804. {
  4805. if (exists())
  4806. return juce_canWriteToFile (fullPath);
  4807. #ifndef JUCE_WIN32
  4808. else if ((! isDirectory()) && fullPath.containsChar (separator))
  4809. return getParentDirectory().hasWriteAccess();
  4810. else
  4811. return false;
  4812. #else
  4813. // on windows, it seems that even read-only directories can still be written into,
  4814. // so checking the parent directory's permissions would return the wrong result..
  4815. else
  4816. return true;
  4817. #endif
  4818. }
  4819. bool File::setReadOnly (const bool shouldBeReadOnly,
  4820. const bool applyRecursively) const throw()
  4821. {
  4822. bool worked = true;
  4823. if (applyRecursively && isDirectory())
  4824. {
  4825. OwnedArray <File> subFiles;
  4826. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4827. for (int i = subFiles.size(); --i >= 0;)
  4828. worked = subFiles[i]->setReadOnly (shouldBeReadOnly, true) && worked;
  4829. }
  4830. return juce_setFileReadOnly (fullPath, shouldBeReadOnly) && worked;
  4831. }
  4832. bool File::deleteFile() const throw()
  4833. {
  4834. return (! exists())
  4835. || juce_deleteFile (fullPath);
  4836. }
  4837. bool File::deleteRecursively() const throw()
  4838. {
  4839. bool worked = true;
  4840. if (isDirectory())
  4841. {
  4842. OwnedArray<File> subFiles;
  4843. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4844. for (int i = subFiles.size(); --i >= 0;)
  4845. worked = subFiles[i]->deleteRecursively() && worked;
  4846. }
  4847. return deleteFile() && worked;
  4848. }
  4849. bool File::moveFileTo (const File& newFile) const throw()
  4850. {
  4851. if (newFile.fullPath == fullPath)
  4852. return true;
  4853. #if ! NAMES_ARE_CASE_SENSITIVE
  4854. if (*this != newFile)
  4855. #endif
  4856. if (! newFile.deleteFile())
  4857. return false;
  4858. return juce_moveFile (fullPath, newFile.fullPath);
  4859. }
  4860. bool File::copyFileTo (const File& newFile) const throw()
  4861. {
  4862. if (*this == newFile)
  4863. return true;
  4864. if (! newFile.deleteFile())
  4865. return false;
  4866. return juce_copyFile (fullPath, newFile.fullPath);
  4867. }
  4868. bool File::copyDirectoryTo (const File& newDirectory) const throw()
  4869. {
  4870. if (isDirectory() && newDirectory.createDirectory())
  4871. {
  4872. OwnedArray<File> subFiles;
  4873. findChildFiles (subFiles, File::findFiles, false);
  4874. int i;
  4875. for (i = 0; i < subFiles.size(); ++i)
  4876. if (! subFiles[i]->copyFileTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  4877. return false;
  4878. subFiles.clear();
  4879. findChildFiles (subFiles, File::findDirectories, false);
  4880. for (i = 0; i < subFiles.size(); ++i)
  4881. if (! subFiles[i]->copyDirectoryTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  4882. return false;
  4883. return true;
  4884. }
  4885. return false;
  4886. }
  4887. const String File::getPathUpToLastSlash() const throw()
  4888. {
  4889. const int lastSlash = fullPath.lastIndexOfChar (separator);
  4890. if (lastSlash > 0)
  4891. return fullPath.substring (0, lastSlash);
  4892. else if (lastSlash == 0)
  4893. return separatorString;
  4894. else
  4895. return fullPath;
  4896. }
  4897. const File File::getParentDirectory() const throw()
  4898. {
  4899. return File (getPathUpToLastSlash());
  4900. }
  4901. const String File::getFileName() const throw()
  4902. {
  4903. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  4904. }
  4905. int File::hashCode() const throw()
  4906. {
  4907. return fullPath.hashCode();
  4908. }
  4909. int64 File::hashCode64() const throw()
  4910. {
  4911. return fullPath.hashCode64();
  4912. }
  4913. const String File::getFileNameWithoutExtension() const throw()
  4914. {
  4915. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  4916. const int lastDot = fullPath.lastIndexOfChar (T('.'));
  4917. if (lastDot > lastSlash)
  4918. return fullPath.substring (lastSlash, lastDot);
  4919. else
  4920. return fullPath.substring (lastSlash);
  4921. }
  4922. bool File::isAChildOf (const File& potentialParent) const throw()
  4923. {
  4924. const String ourPath (getPathUpToLastSlash());
  4925. #if NAMES_ARE_CASE_SENSITIVE
  4926. if (potentialParent.fullPath == ourPath)
  4927. #else
  4928. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  4929. #endif
  4930. {
  4931. return true;
  4932. }
  4933. else if (potentialParent.fullPath.length() >= ourPath.length())
  4934. {
  4935. return false;
  4936. }
  4937. else
  4938. {
  4939. return getParentDirectory().isAChildOf (potentialParent);
  4940. }
  4941. }
  4942. bool File::isAbsolutePath (const String& path) throw()
  4943. {
  4944. return path.startsWithChar (T('/')) || path.startsWithChar (T('\\'))
  4945. #if JUCE_WIN32
  4946. || (path.isNotEmpty() && ((const String&) path)[1] == T(':'));
  4947. #else
  4948. || path.startsWithChar (T('~'));
  4949. #endif
  4950. }
  4951. const File File::getChildFile (String relativePath) const throw()
  4952. {
  4953. if (isAbsolutePath (relativePath))
  4954. {
  4955. // the path is really absolute..
  4956. return File (relativePath);
  4957. }
  4958. else
  4959. {
  4960. // it's relative, so remove any ../ or ./ bits at the start.
  4961. String path (fullPath);
  4962. if (relativePath[0] == T('.'))
  4963. {
  4964. #if JUCE_WIN32
  4965. relativePath = relativePath.replaceCharacter (T('/'), T('\\')).trimStart();
  4966. #else
  4967. relativePath = relativePath.replaceCharacter (T('\\'), T('/')).trimStart();
  4968. #endif
  4969. while (relativePath[0] == T('.'))
  4970. {
  4971. if (relativePath[1] == T('.'))
  4972. {
  4973. if (relativePath [2] == 0 || relativePath[2] == separator)
  4974. {
  4975. const int lastSlash = path.lastIndexOfChar (separator);
  4976. if (lastSlash >= 0)
  4977. path = path.substring (0, lastSlash);
  4978. relativePath = relativePath.substring (3);
  4979. }
  4980. else
  4981. {
  4982. break;
  4983. }
  4984. }
  4985. else if (relativePath[1] == separator)
  4986. {
  4987. relativePath = relativePath.substring (2);
  4988. }
  4989. else
  4990. {
  4991. break;
  4992. }
  4993. }
  4994. }
  4995. return File (juce_addTrailingSeparator (path) + relativePath);
  4996. }
  4997. }
  4998. const File File::getSiblingFile (const String& fileName) const throw()
  4999. {
  5000. return getParentDirectory().getChildFile (fileName);
  5001. }
  5002. int64 File::getSize() const throw()
  5003. {
  5004. return juce_getFileSize (fullPath);
  5005. }
  5006. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5007. {
  5008. if (bytes == 1)
  5009. {
  5010. return "1 byte";
  5011. }
  5012. else if (bytes < 1024)
  5013. {
  5014. return String ((int) bytes) + " bytes";
  5015. }
  5016. else if (bytes < 1024 * 1024)
  5017. {
  5018. return String (bytes / 1024.0, 1) + " KB";
  5019. }
  5020. else if (bytes < 1024 * 1024 * 1024)
  5021. {
  5022. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5023. }
  5024. else
  5025. {
  5026. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5027. }
  5028. }
  5029. bool File::create() const throw()
  5030. {
  5031. if (! exists())
  5032. {
  5033. const File parentDir (getParentDirectory());
  5034. if (parentDir == *this || ! parentDir.createDirectory())
  5035. return false;
  5036. void* const fh = juce_fileOpen (fullPath, true);
  5037. if (fh == 0)
  5038. return false;
  5039. juce_fileClose (fh);
  5040. }
  5041. return true;
  5042. }
  5043. bool File::createDirectory() const throw()
  5044. {
  5045. if (! isDirectory())
  5046. {
  5047. const File parentDir (getParentDirectory());
  5048. if (parentDir == *this || ! parentDir.createDirectory())
  5049. return false;
  5050. String dir (fullPath);
  5051. while (dir.endsWithChar (separator))
  5052. dir [dir.length() - 1] = 0;
  5053. juce_createDirectory (dir);
  5054. return isDirectory();
  5055. }
  5056. return true;
  5057. }
  5058. const Time File::getCreationTime() const throw()
  5059. {
  5060. int64 m, a, c;
  5061. juce_getFileTimes (fullPath, m, a, c);
  5062. return Time (c);
  5063. }
  5064. bool File::setCreationTime (const Time& t) const throw()
  5065. {
  5066. return juce_setFileTimes (fullPath, 0, 0, t.toMilliseconds());
  5067. }
  5068. const Time File::getLastModificationTime() const throw()
  5069. {
  5070. int64 m, a, c;
  5071. juce_getFileTimes (fullPath, m, a, c);
  5072. return Time (m);
  5073. }
  5074. bool File::setLastModificationTime (const Time& t) const throw()
  5075. {
  5076. return juce_setFileTimes (fullPath, t.toMilliseconds(), 0, 0);
  5077. }
  5078. const Time File::getLastAccessTime() const throw()
  5079. {
  5080. int64 m, a, c;
  5081. juce_getFileTimes (fullPath, m, a, c);
  5082. return Time (a);
  5083. }
  5084. bool File::setLastAccessTime (const Time& t) const throw()
  5085. {
  5086. return juce_setFileTimes (fullPath, 0, t.toMilliseconds(), 0);
  5087. }
  5088. bool File::loadFileAsData (MemoryBlock& destBlock) const throw()
  5089. {
  5090. if (! existsAsFile())
  5091. return false;
  5092. FileInputStream in (*this);
  5093. return getSize() == in.readIntoMemoryBlock (destBlock);
  5094. }
  5095. const String File::loadFileAsString() const throw()
  5096. {
  5097. if (! existsAsFile())
  5098. return String::empty;
  5099. FileInputStream in (*this);
  5100. return in.readEntireStreamAsString();
  5101. }
  5102. static inline bool fileTypeMatches (const int whatToLookFor,
  5103. const bool isDir,
  5104. const bool isHidden)
  5105. {
  5106. return (whatToLookFor & (isDir ? File::findDirectories
  5107. : File::findFiles)) != 0
  5108. && ((! isHidden)
  5109. || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5110. }
  5111. int File::findChildFiles (OwnedArray<File>& results,
  5112. const int whatToLookFor,
  5113. const bool searchRecursively,
  5114. const String& wildCardPattern) const throw()
  5115. {
  5116. // you have to specify the type of files you're looking for!
  5117. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5118. int total = 0;
  5119. // find child files or directories in this directory first..
  5120. if (isDirectory())
  5121. {
  5122. const String path (juce_addTrailingSeparator (fullPath));
  5123. String filename;
  5124. bool isDirectory, isHidden;
  5125. void* const handle = juce_findFileStart (path,
  5126. wildCardPattern,
  5127. filename,
  5128. &isDirectory, &isHidden,
  5129. 0, 0, 0, 0);
  5130. if (handle != 0)
  5131. {
  5132. do
  5133. {
  5134. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  5135. && ! filename.containsOnly (T(".")))
  5136. {
  5137. results.add (new File (path + filename, 0));
  5138. ++total;
  5139. }
  5140. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5141. juce_findFileClose (handle);
  5142. }
  5143. }
  5144. else
  5145. {
  5146. // trying to search for files inside a non-directory?
  5147. //jassertfalse
  5148. }
  5149. // and recurse down if required.
  5150. if (searchRecursively)
  5151. {
  5152. OwnedArray <File> subDirectories;
  5153. findChildFiles (subDirectories, File::findDirectories, false);
  5154. for (int i = 0; i < subDirectories.size(); ++i)
  5155. {
  5156. total += subDirectories.getUnchecked(i)
  5157. ->findChildFiles (results,
  5158. whatToLookFor,
  5159. true,
  5160. wildCardPattern);
  5161. }
  5162. }
  5163. return total;
  5164. }
  5165. int File::getNumberOfChildFiles (const int whatToLookFor,
  5166. const String& wildCardPattern) const throw()
  5167. {
  5168. // you have to specify the type of files you're looking for!
  5169. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5170. int count = 0;
  5171. if (isDirectory())
  5172. {
  5173. String filename;
  5174. bool isDirectory, isHidden;
  5175. void* const handle = juce_findFileStart (fullPath,
  5176. wildCardPattern,
  5177. filename,
  5178. &isDirectory, &isHidden,
  5179. 0, 0, 0, 0);
  5180. if (handle != 0)
  5181. {
  5182. do
  5183. {
  5184. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  5185. && ! filename.containsOnly (T(".")))
  5186. {
  5187. ++count;
  5188. }
  5189. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5190. juce_findFileClose (handle);
  5191. }
  5192. }
  5193. else
  5194. {
  5195. // trying to search for files inside a non-directory?
  5196. jassertfalse
  5197. }
  5198. return count;
  5199. }
  5200. bool File::containsSubDirectories() const throw()
  5201. {
  5202. bool result = false;
  5203. if (isDirectory())
  5204. {
  5205. String filename;
  5206. bool isDirectory, isHidden;
  5207. void* const handle = juce_findFileStart (juce_addTrailingSeparator (fullPath),
  5208. T("*"), filename,
  5209. &isDirectory, &isHidden, 0, 0, 0, 0);
  5210. if (handle != 0)
  5211. {
  5212. do
  5213. {
  5214. if (isDirectory)
  5215. {
  5216. result = true;
  5217. break;
  5218. }
  5219. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5220. juce_findFileClose (handle);
  5221. }
  5222. }
  5223. return result;
  5224. }
  5225. const File File::getNonexistentChildFile (const String& prefix_,
  5226. const String& suffix,
  5227. bool putNumbersInBrackets) const throw()
  5228. {
  5229. File f (getChildFile (prefix_ + suffix));
  5230. if (f.exists())
  5231. {
  5232. int num = 2;
  5233. String prefix (prefix_);
  5234. // remove any bracketed numbers that may already be on the end..
  5235. if (prefix.trim().endsWithChar (T(')')))
  5236. {
  5237. putNumbersInBrackets = true;
  5238. const int openBracks = prefix.lastIndexOfChar (T('('));
  5239. const int closeBracks = prefix.lastIndexOfChar (T(')'));
  5240. if (openBracks > 0
  5241. && closeBracks > openBracks
  5242. && prefix.substring (openBracks + 1, closeBracks).containsOnly (T("0123456789")))
  5243. {
  5244. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5245. prefix = prefix.substring (0, openBracks);
  5246. }
  5247. }
  5248. // also use brackets if it ends in a digit.
  5249. putNumbersInBrackets = putNumbersInBrackets
  5250. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5251. do
  5252. {
  5253. if (putNumbersInBrackets)
  5254. f = getChildFile (prefix + T('(') + String (num++) + T(')') + suffix);
  5255. else
  5256. f = getChildFile (prefix + String (num++) + suffix);
  5257. } while (f.exists());
  5258. }
  5259. return f;
  5260. }
  5261. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const throw()
  5262. {
  5263. if (exists())
  5264. {
  5265. return getParentDirectory()
  5266. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5267. getFileExtension(),
  5268. putNumbersInBrackets);
  5269. }
  5270. else
  5271. {
  5272. return *this;
  5273. }
  5274. }
  5275. const String File::getFileExtension() const throw()
  5276. {
  5277. String ext;
  5278. if (! isDirectory())
  5279. {
  5280. const int indexOfDot = fullPath.lastIndexOfChar (T('.'));
  5281. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5282. ext = fullPath.substring (indexOfDot);
  5283. }
  5284. return ext;
  5285. }
  5286. bool File::hasFileExtension (const String& possibleSuffix) const throw()
  5287. {
  5288. if (possibleSuffix.isEmpty())
  5289. return fullPath.lastIndexOfChar (T('.')) <= fullPath.lastIndexOfChar (separator);
  5290. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5291. {
  5292. if (possibleSuffix.startsWithChar (T('.')))
  5293. return true;
  5294. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5295. if (dotPos >= 0)
  5296. return fullPath [dotPos] == T('.');
  5297. }
  5298. return false;
  5299. }
  5300. const File File::withFileExtension (const String& newExtension) const throw()
  5301. {
  5302. if (fullPath.isEmpty())
  5303. return File::nonexistent;
  5304. String filePart (getFileName());
  5305. int i = filePart.lastIndexOfChar (T('.'));
  5306. if (i < 0)
  5307. i = filePart.length();
  5308. String newExt (newExtension);
  5309. if (newExt.isNotEmpty() && ! newExt.startsWithChar (T('.')))
  5310. newExt = T(".") + newExt;
  5311. return getSiblingFile (filePart.substring (0, i) + newExt);
  5312. }
  5313. bool File::startAsProcess (const String& parameters) const throw()
  5314. {
  5315. return exists()
  5316. && juce_launchFile (fullPath, parameters);
  5317. }
  5318. FileInputStream* File::createInputStream() const throw()
  5319. {
  5320. if (existsAsFile())
  5321. return new FileInputStream (*this);
  5322. else
  5323. return 0;
  5324. }
  5325. FileOutputStream* File::createOutputStream (const int bufferSize) const throw()
  5326. {
  5327. FileOutputStream* const out = new FileOutputStream (*this, bufferSize);
  5328. if (out->failedToOpen())
  5329. {
  5330. delete out;
  5331. return 0;
  5332. }
  5333. else
  5334. {
  5335. return out;
  5336. }
  5337. }
  5338. bool File::appendData (const void* const dataToAppend,
  5339. const int numberOfBytes) const throw()
  5340. {
  5341. if (numberOfBytes > 0)
  5342. {
  5343. FileOutputStream* const out = createOutputStream();
  5344. if (out == 0)
  5345. return false;
  5346. out->write (dataToAppend, numberOfBytes);
  5347. delete out;
  5348. }
  5349. return true;
  5350. }
  5351. bool File::replaceWithData (const void* const dataToWrite,
  5352. const int numberOfBytes) const throw()
  5353. {
  5354. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5355. if (numberOfBytes <= 0)
  5356. return deleteFile();
  5357. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  5358. if (tempFile.appendData (dataToWrite, numberOfBytes)
  5359. && tempFile.moveFileTo (*this))
  5360. {
  5361. return true;
  5362. }
  5363. tempFile.deleteFile();
  5364. return false;
  5365. }
  5366. bool File::appendText (const String& text,
  5367. const bool asUnicode,
  5368. const bool writeUnicodeHeaderBytes) const throw()
  5369. {
  5370. FileOutputStream* const out = createOutputStream();
  5371. if (out != 0)
  5372. {
  5373. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5374. delete out;
  5375. return true;
  5376. }
  5377. return false;
  5378. }
  5379. bool File::printf (const tchar* pf, ...) const throw()
  5380. {
  5381. va_list list;
  5382. va_start (list, pf);
  5383. String text;
  5384. text.vprintf (pf, list);
  5385. return appendData ((const char*) text, text.length());
  5386. }
  5387. bool File::replaceWithText (const String& textToWrite,
  5388. const bool asUnicode,
  5389. const bool writeUnicodeHeaderBytes) const throw()
  5390. {
  5391. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  5392. if (tempFile.appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes)
  5393. && tempFile.moveFileTo (*this))
  5394. {
  5395. return true;
  5396. }
  5397. tempFile.deleteFile();
  5398. return false;
  5399. }
  5400. const String File::createLegalPathName (const String& original) throw()
  5401. {
  5402. String s (original);
  5403. String start;
  5404. if (s[1] == T(':'))
  5405. {
  5406. start = s.substring (0, 2);
  5407. s = s.substring (2);
  5408. }
  5409. return start + s.removeCharacters (T("\"#@,;:<>*^|?"))
  5410. .substring (0, 1024);
  5411. }
  5412. const String File::createLegalFileName (const String& original) throw()
  5413. {
  5414. String s (original.removeCharacters (T("\"#@,;:<>*^|?\\/")));
  5415. const int maxLength = 128; // only the length of the filename, not the whole path
  5416. const int len = s.length();
  5417. if (len > maxLength)
  5418. {
  5419. const int lastDot = s.lastIndexOfChar (T('.'));
  5420. if (lastDot > jmax (0, len - 12))
  5421. {
  5422. s = s.substring (0, maxLength - (len - lastDot))
  5423. + s.substring (lastDot);
  5424. }
  5425. else
  5426. {
  5427. s = s.substring (0, maxLength);
  5428. }
  5429. }
  5430. return s;
  5431. }
  5432. const String File::getRelativePathFrom (const File& dir) const throw()
  5433. {
  5434. String thisPath (fullPath);
  5435. {
  5436. int len = thisPath.length();
  5437. while (--len >= 0 && thisPath [len] == File::separator)
  5438. thisPath [len] = 0;
  5439. }
  5440. String dirPath (juce_addTrailingSeparator ((dir.existsAsFile()) ? dir.getParentDirectory().getFullPathName()
  5441. : dir.fullPath));
  5442. const int len = jmin (thisPath.length(), dirPath.length());
  5443. int commonBitLength = 0;
  5444. for (int i = 0; i < len; ++i)
  5445. {
  5446. #if NAMES_ARE_CASE_SENSITIVE
  5447. if (thisPath[i] != dirPath[i])
  5448. #else
  5449. if (CharacterFunctions::toLowerCase (thisPath[i])
  5450. != CharacterFunctions::toLowerCase (dirPath[i]))
  5451. #endif
  5452. {
  5453. break;
  5454. }
  5455. ++commonBitLength;
  5456. }
  5457. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5458. --commonBitLength;
  5459. // if the only common bit is the root, then just return the full path..
  5460. if (commonBitLength <= 0
  5461. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5462. return fullPath;
  5463. thisPath = thisPath.substring (commonBitLength);
  5464. dirPath = dirPath.substring (commonBitLength);
  5465. while (dirPath.isNotEmpty())
  5466. {
  5467. #if JUCE_WIN32
  5468. thisPath = T("..\\") + thisPath;
  5469. #else
  5470. thisPath = T("../") + thisPath;
  5471. #endif
  5472. const int sep = dirPath.indexOfChar (separator);
  5473. if (sep >= 0)
  5474. dirPath = dirPath.substring (sep + 1);
  5475. else
  5476. dirPath = String::empty;
  5477. }
  5478. return thisPath;
  5479. }
  5480. void File::findFileSystemRoots (OwnedArray<File>& destArray) throw()
  5481. {
  5482. const StringArray roots (juce_getFileSystemRoots());
  5483. for (int i = 0; i < roots.size(); ++i)
  5484. destArray.add (new File (roots[i]));
  5485. }
  5486. const String File::getVolumeLabel() const throw()
  5487. {
  5488. int serialNum;
  5489. return juce_getVolumeLabel (fullPath, serialNum);
  5490. }
  5491. int File::getVolumeSerialNumber() const throw()
  5492. {
  5493. int serialNum;
  5494. juce_getVolumeLabel (fullPath, serialNum);
  5495. return serialNum;
  5496. }
  5497. const File File::createTempFile (const String& fileNameEnding) throw()
  5498. {
  5499. String tempName (T("temp"));
  5500. static int tempNum = 0;
  5501. tempName << tempNum++ << fileNameEnding;
  5502. const File tempFile (getSpecialLocation (tempDirectory)
  5503. .getChildFile (tempName));
  5504. if (tempFile.exists())
  5505. return createTempFile (fileNameEnding);
  5506. else
  5507. return tempFile;
  5508. }
  5509. END_JUCE_NAMESPACE
  5510. /********* End of inlined file: juce_File.cpp *********/
  5511. /********* Start of inlined file: juce_FileInputStream.cpp *********/
  5512. BEGIN_JUCE_NAMESPACE
  5513. void* juce_fileOpen (const String& path, bool forWriting) throw();
  5514. void juce_fileClose (void* handle) throw();
  5515. int juce_fileRead (void* handle, void* buffer, int size) throw();
  5516. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  5517. FileInputStream::FileInputStream (const File& f)
  5518. : file (f),
  5519. currentPosition (0),
  5520. needToSeek (true)
  5521. {
  5522. totalSize = f.getSize();
  5523. fileHandle = juce_fileOpen (f.getFullPathName(), false);
  5524. }
  5525. FileInputStream::~FileInputStream()
  5526. {
  5527. juce_fileClose (fileHandle);
  5528. }
  5529. int64 FileInputStream::getTotalLength()
  5530. {
  5531. return totalSize;
  5532. }
  5533. int FileInputStream::read (void* buffer, int bytesToRead)
  5534. {
  5535. int num = 0;
  5536. if (needToSeek)
  5537. {
  5538. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5539. return 0;
  5540. needToSeek = false;
  5541. }
  5542. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5543. currentPosition += num;
  5544. return num;
  5545. }
  5546. bool FileInputStream::isExhausted()
  5547. {
  5548. return currentPosition >= totalSize;
  5549. }
  5550. int64 FileInputStream::getPosition()
  5551. {
  5552. return currentPosition;
  5553. }
  5554. bool FileInputStream::setPosition (int64 pos)
  5555. {
  5556. pos = jlimit ((int64) 0, totalSize, pos);
  5557. needToSeek |= (currentPosition != pos);
  5558. currentPosition = pos;
  5559. return true;
  5560. }
  5561. END_JUCE_NAMESPACE
  5562. /********* End of inlined file: juce_FileInputStream.cpp *********/
  5563. /********* Start of inlined file: juce_FileOutputStream.cpp *********/
  5564. BEGIN_JUCE_NAMESPACE
  5565. void* juce_fileOpen (const String& path, bool forWriting) throw();
  5566. void juce_fileClose (void* handle) throw();
  5567. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  5568. void juce_fileFlush (void* handle) throw();
  5569. int64 juce_fileGetPosition (void* handle) throw();
  5570. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  5571. FileOutputStream::FileOutputStream (const File& f,
  5572. const int bufferSize_)
  5573. : file (f),
  5574. bufferSize (bufferSize_),
  5575. bytesInBuffer (0)
  5576. {
  5577. fileHandle = juce_fileOpen (f.getFullPathName(), true);
  5578. if (fileHandle != 0)
  5579. {
  5580. currentPosition = juce_fileGetPosition (fileHandle);
  5581. if (currentPosition < 0)
  5582. {
  5583. jassertfalse
  5584. juce_fileClose (fileHandle);
  5585. fileHandle = 0;
  5586. }
  5587. }
  5588. buffer = (char*) juce_malloc (jmax (bufferSize_, 16));
  5589. }
  5590. FileOutputStream::~FileOutputStream()
  5591. {
  5592. flush();
  5593. juce_fileClose (fileHandle);
  5594. juce_free (buffer);
  5595. }
  5596. int64 FileOutputStream::getPosition()
  5597. {
  5598. return currentPosition;
  5599. }
  5600. bool FileOutputStream::setPosition (int64 newPosition)
  5601. {
  5602. if (newPosition != currentPosition)
  5603. {
  5604. flush();
  5605. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5606. }
  5607. return newPosition == currentPosition;
  5608. }
  5609. void FileOutputStream::flush()
  5610. {
  5611. if (bytesInBuffer > 0)
  5612. {
  5613. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5614. bytesInBuffer = 0;
  5615. }
  5616. juce_fileFlush (fileHandle);
  5617. }
  5618. bool FileOutputStream::write (const void* const src, const int numBytes)
  5619. {
  5620. if (bytesInBuffer + numBytes < bufferSize)
  5621. {
  5622. memcpy (buffer + bytesInBuffer, src, numBytes);
  5623. bytesInBuffer += numBytes;
  5624. currentPosition += numBytes;
  5625. }
  5626. else
  5627. {
  5628. if (bytesInBuffer > 0)
  5629. {
  5630. // flush the reservoir
  5631. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5632. bytesInBuffer = 0;
  5633. if (! wroteOk)
  5634. return false;
  5635. }
  5636. if (numBytes < bufferSize)
  5637. {
  5638. memcpy (buffer + bytesInBuffer, src, numBytes);
  5639. bytesInBuffer += numBytes;
  5640. currentPosition += numBytes;
  5641. }
  5642. else
  5643. {
  5644. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5645. currentPosition += bytesWritten;
  5646. return bytesWritten == numBytes;
  5647. }
  5648. }
  5649. return true;
  5650. }
  5651. END_JUCE_NAMESPACE
  5652. /********* End of inlined file: juce_FileOutputStream.cpp *********/
  5653. /********* Start of inlined file: juce_FileSearchPath.cpp *********/
  5654. BEGIN_JUCE_NAMESPACE
  5655. FileSearchPath::FileSearchPath()
  5656. {
  5657. }
  5658. FileSearchPath::FileSearchPath (const String& path)
  5659. {
  5660. init (path);
  5661. }
  5662. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5663. : directories (other.directories)
  5664. {
  5665. }
  5666. FileSearchPath::~FileSearchPath()
  5667. {
  5668. }
  5669. const FileSearchPath& FileSearchPath::operator= (const String& path)
  5670. {
  5671. init (path);
  5672. return *this;
  5673. }
  5674. void FileSearchPath::init (const String& path)
  5675. {
  5676. directories.clear();
  5677. directories.addTokens (path, T(";"), T("\""));
  5678. directories.trim();
  5679. directories.removeEmptyStrings();
  5680. for (int i = directories.size(); --i >= 0;)
  5681. directories.set (i, directories[i].unquoted());
  5682. }
  5683. int FileSearchPath::getNumPaths() const
  5684. {
  5685. return directories.size();
  5686. }
  5687. const File FileSearchPath::operator[] (const int index) const
  5688. {
  5689. return File (directories [index]);
  5690. }
  5691. const String FileSearchPath::toString() const
  5692. {
  5693. StringArray directories2 (directories);
  5694. for (int i = directories2.size(); --i >= 0;)
  5695. if (directories2[i].containsChar (T(';')))
  5696. directories2.set (i, directories2[i].quoted());
  5697. return directories2.joinIntoString (T(";"));
  5698. }
  5699. void FileSearchPath::add (const File& dir, const int insertIndex)
  5700. {
  5701. directories.insert (insertIndex, dir.getFullPathName());
  5702. }
  5703. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5704. {
  5705. for (int i = 0; i < directories.size(); ++i)
  5706. if (File (directories[i]) == dir)
  5707. return;
  5708. add (dir);
  5709. }
  5710. void FileSearchPath::remove (const int index)
  5711. {
  5712. directories.remove (index);
  5713. }
  5714. void FileSearchPath::addPath (const FileSearchPath& other)
  5715. {
  5716. for (int i = 0; i < other.getNumPaths(); ++i)
  5717. addIfNotAlreadyThere (other[i]);
  5718. }
  5719. void FileSearchPath::removeRedundantPaths()
  5720. {
  5721. for (int i = directories.size(); --i >= 0;)
  5722. {
  5723. const File d1 (directories[i]);
  5724. for (int j = directories.size(); --j >= 0;)
  5725. {
  5726. const File d2 (directories[j]);
  5727. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5728. {
  5729. directories.remove (i);
  5730. break;
  5731. }
  5732. }
  5733. }
  5734. }
  5735. void FileSearchPath::removeNonExistentPaths()
  5736. {
  5737. for (int i = directories.size(); --i >= 0;)
  5738. if (! File (directories[i]).isDirectory())
  5739. directories.remove (i);
  5740. }
  5741. int FileSearchPath::findChildFiles (OwnedArray<File>& results,
  5742. const int whatToLookFor,
  5743. const bool searchRecursively,
  5744. const String& wildCardPattern) const
  5745. {
  5746. int total = 0;
  5747. for (int i = 0; i < directories.size(); ++i)
  5748. total += operator[] (i).findChildFiles (results,
  5749. whatToLookFor,
  5750. searchRecursively,
  5751. wildCardPattern);
  5752. return total;
  5753. }
  5754. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5755. const bool checkRecursively) const
  5756. {
  5757. for (int i = directories.size(); --i >= 0;)
  5758. {
  5759. const File d (directories[i]);
  5760. if (checkRecursively)
  5761. {
  5762. if (fileToCheck.isAChildOf (d))
  5763. return true;
  5764. }
  5765. else
  5766. {
  5767. if (fileToCheck.getParentDirectory() == d)
  5768. return true;
  5769. }
  5770. }
  5771. return false;
  5772. }
  5773. END_JUCE_NAMESPACE
  5774. /********* End of inlined file: juce_FileSearchPath.cpp *********/
  5775. /********* Start of inlined file: juce_NamedPipe.cpp *********/
  5776. BEGIN_JUCE_NAMESPACE
  5777. NamedPipe::NamedPipe()
  5778. : internal (0)
  5779. {
  5780. }
  5781. NamedPipe::~NamedPipe()
  5782. {
  5783. close();
  5784. }
  5785. bool NamedPipe::openExisting (const String& pipeName)
  5786. {
  5787. currentPipeName = pipeName;
  5788. return openInternal (pipeName, false);
  5789. }
  5790. bool NamedPipe::createNewPipe (const String& pipeName)
  5791. {
  5792. currentPipeName = pipeName;
  5793. return openInternal (pipeName, true);
  5794. }
  5795. bool NamedPipe::isOpen() const throw()
  5796. {
  5797. return internal != 0;
  5798. }
  5799. const String NamedPipe::getName() const throw()
  5800. {
  5801. return currentPipeName;
  5802. }
  5803. // other methods for this class are implemented in the platform-specific files
  5804. END_JUCE_NAMESPACE
  5805. /********* End of inlined file: juce_NamedPipe.cpp *********/
  5806. /********* Start of inlined file: juce_Socket.cpp *********/
  5807. #ifdef _WIN32
  5808. #include <winsock2.h>
  5809. #ifdef _MSC_VER
  5810. #pragma warning (disable : 4127 4389 4018)
  5811. #endif
  5812. #else
  5813. #if defined (LINUX) || defined (__linux__)
  5814. #include <sys/types.h>
  5815. #include <sys/socket.h>
  5816. #include <sys/errno.h>
  5817. #include <unistd.h>
  5818. #include <netinet/in.h>
  5819. #else
  5820. #if MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4
  5821. #include <CoreServices/CoreServices.h>
  5822. #endif
  5823. #endif
  5824. #include <fcntl.h>
  5825. #include <netdb.h>
  5826. #include <arpa/inet.h>
  5827. #include <netinet/tcp.h>
  5828. #endif
  5829. BEGIN_JUCE_NAMESPACE
  5830. #if JUCE_WIN32
  5831. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  5832. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  5833. static void initWin32Sockets()
  5834. {
  5835. static CriticalSection lock;
  5836. const ScopedLock sl (lock);
  5837. if (juce_CloseWin32SocketLib == 0)
  5838. {
  5839. WSADATA wsaData;
  5840. const WORD wVersionRequested = MAKEWORD (1, 1);
  5841. WSAStartup (wVersionRequested, &wsaData);
  5842. juce_CloseWin32SocketLib = &WSACleanup;
  5843. }
  5844. }
  5845. #endif
  5846. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  5847. {
  5848. const int sndBufSize = 65536;
  5849. const int rcvBufSize = 65536;
  5850. const int one = 1;
  5851. return handle > 0
  5852. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  5853. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  5854. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  5855. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  5856. }
  5857. static bool bindSocketToPort (const int handle, const int port) throw()
  5858. {
  5859. if (handle <= 0 || port <= 0)
  5860. return false;
  5861. struct sockaddr_in servTmpAddr;
  5862. zerostruct (servTmpAddr);
  5863. servTmpAddr.sin_family = PF_INET;
  5864. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5865. servTmpAddr.sin_port = htons ((uint16) port);
  5866. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  5867. }
  5868. static int readSocket (const int handle,
  5869. void* const destBuffer, const int maxBytesToRead,
  5870. bool volatile& connected,
  5871. const bool blockUntilSpecifiedAmountHasArrived) throw()
  5872. {
  5873. int bytesRead = 0;
  5874. while (bytesRead < maxBytesToRead)
  5875. {
  5876. int bytesThisTime;
  5877. #if JUCE_WIN32
  5878. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  5879. #else
  5880. while ((bytesThisTime = ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  5881. && errno == EINTR
  5882. && connected)
  5883. {
  5884. }
  5885. #endif
  5886. if (bytesThisTime <= 0 || ! connected)
  5887. {
  5888. if (bytesRead == 0)
  5889. bytesRead = -1;
  5890. break;
  5891. }
  5892. bytesRead += bytesThisTime;
  5893. if (! blockUntilSpecifiedAmountHasArrived)
  5894. break;
  5895. }
  5896. return bytesRead;
  5897. }
  5898. static int waitForReadiness (const int handle, const bool forReading,
  5899. const int timeoutMsecs) throw()
  5900. {
  5901. struct timeval timeout;
  5902. struct timeval* timeoutp;
  5903. if (timeoutMsecs >= 0)
  5904. {
  5905. timeout.tv_sec = timeoutMsecs / 1000;
  5906. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  5907. timeoutp = &timeout;
  5908. }
  5909. else
  5910. {
  5911. timeoutp = 0;
  5912. }
  5913. fd_set rset, wset;
  5914. FD_ZERO (&rset);
  5915. FD_SET (handle, &rset);
  5916. FD_ZERO (&wset);
  5917. FD_SET (handle, &wset);
  5918. fd_set* const prset = forReading ? &rset : 0;
  5919. fd_set* const pwset = forReading ? 0 : &wset;
  5920. #if JUCE_WIN32
  5921. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  5922. return -1;
  5923. #else
  5924. {
  5925. int result;
  5926. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  5927. && errno == EINTR)
  5928. {
  5929. }
  5930. if (result < 0)
  5931. return -1;
  5932. }
  5933. #endif
  5934. {
  5935. int opt;
  5936. #if defined (JUCE_LINUX) || defined (JUCE_MAC)
  5937. socklen_t len = sizeof (opt);
  5938. #else
  5939. int len = sizeof (opt);
  5940. #endif
  5941. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  5942. || opt != 0)
  5943. return -1;
  5944. }
  5945. if ((forReading && FD_ISSET (handle, &rset))
  5946. || ((! forReading) && FD_ISSET (handle, &wset)))
  5947. return 1;
  5948. return 0;
  5949. }
  5950. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  5951. {
  5952. #if JUCE_WIN32
  5953. u_long nonBlocking = shouldBlock ? 0 : 1;
  5954. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  5955. return false;
  5956. #else
  5957. int socketFlags = fcntl (handle, F_GETFL, 0);
  5958. if (socketFlags == -1)
  5959. return false;
  5960. if (shouldBlock)
  5961. socketFlags &= ~O_NONBLOCK;
  5962. else
  5963. socketFlags |= O_NONBLOCK;
  5964. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  5965. return false;
  5966. #endif
  5967. return true;
  5968. }
  5969. static bool connectSocket (int volatile& handle,
  5970. const bool isDatagram,
  5971. void** serverAddress,
  5972. const String& hostName,
  5973. const int portNumber,
  5974. const int timeOutMillisecs) throw()
  5975. {
  5976. struct hostent* const hostEnt = gethostbyname (hostName);
  5977. if (hostEnt == 0)
  5978. return false;
  5979. struct in_addr targetAddress;
  5980. memcpy (&targetAddress.s_addr,
  5981. *(hostEnt->h_addr_list),
  5982. sizeof (targetAddress.s_addr));
  5983. struct sockaddr_in servTmpAddr;
  5984. zerostruct (servTmpAddr);
  5985. servTmpAddr.sin_family = PF_INET;
  5986. servTmpAddr.sin_addr = targetAddress;
  5987. servTmpAddr.sin_port = htons ((uint16) portNumber);
  5988. if (handle < 0)
  5989. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  5990. if (handle < 0)
  5991. return false;
  5992. if (isDatagram)
  5993. {
  5994. *serverAddress = new struct sockaddr_in();
  5995. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  5996. return true;
  5997. }
  5998. setSocketBlockingState (handle, false);
  5999. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6000. if (result < 0)
  6001. {
  6002. #if JUCE_WIN32
  6003. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6004. #else
  6005. if (errno == EINPROGRESS)
  6006. #endif
  6007. {
  6008. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6009. {
  6010. setSocketBlockingState (handle, true);
  6011. return false;
  6012. }
  6013. }
  6014. }
  6015. setSocketBlockingState (handle, true);
  6016. resetSocketOptions (handle, false, false);
  6017. return true;
  6018. }
  6019. StreamingSocket::StreamingSocket()
  6020. : portNumber (0),
  6021. handle (-1),
  6022. connected (false),
  6023. isListener (false)
  6024. {
  6025. #if JUCE_WIN32
  6026. initWin32Sockets();
  6027. #endif
  6028. }
  6029. StreamingSocket::StreamingSocket (const String& hostName_,
  6030. const int portNumber_,
  6031. const int handle_)
  6032. : hostName (hostName_),
  6033. portNumber (portNumber_),
  6034. handle (handle_),
  6035. connected (true),
  6036. isListener (false)
  6037. {
  6038. #if JUCE_WIN32
  6039. initWin32Sockets();
  6040. #endif
  6041. resetSocketOptions (handle_, false, false);
  6042. }
  6043. StreamingSocket::~StreamingSocket()
  6044. {
  6045. close();
  6046. }
  6047. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6048. {
  6049. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6050. : -1;
  6051. }
  6052. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6053. {
  6054. if (isListener || ! connected)
  6055. return -1;
  6056. #if JUCE_WIN32
  6057. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6058. #else
  6059. int result;
  6060. while ((result = ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6061. && errno == EINTR)
  6062. {
  6063. }
  6064. return result;
  6065. #endif
  6066. }
  6067. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6068. const int timeoutMsecs) const
  6069. {
  6070. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6071. : -1;
  6072. }
  6073. bool StreamingSocket::bindToPort (const int port)
  6074. {
  6075. return bindSocketToPort (handle, port);
  6076. }
  6077. bool StreamingSocket::connect (const String& remoteHostName,
  6078. const int remotePortNumber,
  6079. const int timeOutMillisecs)
  6080. {
  6081. if (isListener)
  6082. {
  6083. jassertfalse // a listener socket can't connect to another one!
  6084. return false;
  6085. }
  6086. if (connected)
  6087. close();
  6088. hostName = remoteHostName;
  6089. portNumber = remotePortNumber;
  6090. isListener = false;
  6091. connected = connectSocket (handle, false, 0, remoteHostName,
  6092. remotePortNumber, timeOutMillisecs);
  6093. if (! (connected && resetSocketOptions (handle, false, false)))
  6094. {
  6095. close();
  6096. return false;
  6097. }
  6098. return true;
  6099. }
  6100. void StreamingSocket::close()
  6101. {
  6102. #if JUCE_WIN32
  6103. closesocket (handle);
  6104. connected = false;
  6105. #else
  6106. if (connected)
  6107. {
  6108. connected = false;
  6109. if (isListener)
  6110. {
  6111. // need to do this to interrupt the accept() function..
  6112. StreamingSocket temp;
  6113. temp.connect ("localhost", portNumber, 1000);
  6114. }
  6115. }
  6116. ::close (handle);
  6117. #endif
  6118. hostName = String::empty;
  6119. portNumber = 0;
  6120. handle = -1;
  6121. isListener = false;
  6122. }
  6123. bool StreamingSocket::createListener (const int newPortNumber)
  6124. {
  6125. if (connected)
  6126. close();
  6127. hostName = "listener";
  6128. portNumber = newPortNumber;
  6129. isListener = true;
  6130. struct sockaddr_in servTmpAddr;
  6131. zerostruct (servTmpAddr);
  6132. servTmpAddr.sin_family = PF_INET;
  6133. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6134. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6135. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6136. if (handle < 0)
  6137. return false;
  6138. const int reuse = 1;
  6139. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6140. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6141. || listen (handle, SOMAXCONN) < 0)
  6142. {
  6143. close();
  6144. return false;
  6145. }
  6146. connected = true;
  6147. return true;
  6148. }
  6149. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6150. {
  6151. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6152. // prepare this socket as a listener.
  6153. if (connected && isListener)
  6154. {
  6155. struct sockaddr address;
  6156. #if defined (JUCE_LINUX) || defined (JUCE_MAC)
  6157. socklen_t len = sizeof (sockaddr);
  6158. #else
  6159. int len = sizeof (sockaddr);
  6160. #endif
  6161. const int newSocket = (int) accept (handle, &address, &len);
  6162. if (newSocket >= 0 && connected)
  6163. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6164. portNumber, newSocket);
  6165. }
  6166. return 0;
  6167. }
  6168. bool StreamingSocket::isLocal() const throw()
  6169. {
  6170. return hostName == T("127.0.0.1");
  6171. }
  6172. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6173. : portNumber (0),
  6174. handle (-1),
  6175. connected (true),
  6176. allowBroadcast (allowBroadcast_),
  6177. serverAddress (0)
  6178. {
  6179. #if JUCE_WIN32
  6180. initWin32Sockets();
  6181. #endif
  6182. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6183. bindToPort (localPortNumber);
  6184. }
  6185. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6186. const int handle_, const int localPortNumber)
  6187. : hostName (hostName_),
  6188. portNumber (portNumber_),
  6189. handle (handle_),
  6190. connected (true),
  6191. allowBroadcast (false),
  6192. serverAddress (0)
  6193. {
  6194. #if JUCE_WIN32
  6195. initWin32Sockets();
  6196. #endif
  6197. resetSocketOptions (handle_, true, allowBroadcast);
  6198. bindToPort (localPortNumber);
  6199. }
  6200. DatagramSocket::~DatagramSocket()
  6201. {
  6202. close();
  6203. delete ((struct sockaddr_in*) serverAddress);
  6204. serverAddress = 0;
  6205. }
  6206. void DatagramSocket::close()
  6207. {
  6208. #if JUCE_WIN32
  6209. closesocket (handle);
  6210. connected = false;
  6211. #else
  6212. connected = false;
  6213. ::close (handle);
  6214. #endif
  6215. hostName = String::empty;
  6216. portNumber = 0;
  6217. handle = -1;
  6218. }
  6219. bool DatagramSocket::bindToPort (const int port)
  6220. {
  6221. return bindSocketToPort (handle, port);
  6222. }
  6223. bool DatagramSocket::connect (const String& remoteHostName,
  6224. const int remotePortNumber,
  6225. const int timeOutMillisecs)
  6226. {
  6227. if (connected)
  6228. close();
  6229. hostName = remoteHostName;
  6230. portNumber = remotePortNumber;
  6231. connected = connectSocket (handle, true, &serverAddress,
  6232. remoteHostName, remotePortNumber,
  6233. timeOutMillisecs);
  6234. if (! (connected && resetSocketOptions (handle, true, allowBroadcast)))
  6235. {
  6236. close();
  6237. return false;
  6238. }
  6239. return true;
  6240. }
  6241. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6242. {
  6243. struct sockaddr address;
  6244. #if defined (JUCE_LINUX) || defined (JUCE_MAC)
  6245. socklen_t len = sizeof (sockaddr);
  6246. #else
  6247. int len = sizeof (sockaddr);
  6248. #endif
  6249. while (waitUntilReady (true, -1) == 1)
  6250. {
  6251. char buf[1];
  6252. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6253. {
  6254. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6255. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6256. -1, -1);
  6257. }
  6258. }
  6259. return 0;
  6260. }
  6261. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6262. const int timeoutMsecs) const
  6263. {
  6264. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6265. : -1;
  6266. }
  6267. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6268. {
  6269. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6270. : -1;
  6271. }
  6272. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6273. {
  6274. // You need to call connect() first to set the server address..
  6275. jassert (serverAddress != 0 && connected);
  6276. return connected ? sendto (handle, (const char*) sourceBuffer,
  6277. numBytesToWrite, 0,
  6278. (const struct sockaddr*) serverAddress,
  6279. sizeof (struct sockaddr_in))
  6280. : -1;
  6281. }
  6282. bool DatagramSocket::isLocal() const throw()
  6283. {
  6284. return hostName == T("127.0.0.1");
  6285. }
  6286. END_JUCE_NAMESPACE
  6287. /********* End of inlined file: juce_Socket.cpp *********/
  6288. /********* Start of inlined file: juce_URL.cpp *********/
  6289. BEGIN_JUCE_NAMESPACE
  6290. URL::URL() throw()
  6291. {
  6292. }
  6293. URL::URL (const String& url_)
  6294. : url (url_)
  6295. {
  6296. int i = url.indexOfChar (T('?'));
  6297. if (i >= 0)
  6298. {
  6299. do
  6300. {
  6301. const int nextAmp = url.indexOfChar (i + 1, T('&'));
  6302. const int equalsPos = url.indexOfChar (i + 1, T('='));
  6303. if (equalsPos > i + 1)
  6304. {
  6305. if (nextAmp < 0)
  6306. {
  6307. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6308. removeEscapeChars (url.substring (equalsPos + 1)));
  6309. }
  6310. else if (nextAmp > 0 && equalsPos < nextAmp)
  6311. {
  6312. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6313. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6314. }
  6315. }
  6316. i = nextAmp;
  6317. }
  6318. while (i >= 0);
  6319. url = url.upToFirstOccurrenceOf (T("?"), false, false);
  6320. }
  6321. }
  6322. URL::URL (const URL& other)
  6323. : url (other.url),
  6324. postData (other.postData),
  6325. parameters (other.parameters),
  6326. filesToUpload (other.filesToUpload),
  6327. mimeTypes (other.mimeTypes)
  6328. {
  6329. }
  6330. const URL& URL::operator= (const URL& other)
  6331. {
  6332. url = other.url;
  6333. postData = other.postData;
  6334. parameters = other.parameters;
  6335. filesToUpload = other.filesToUpload;
  6336. mimeTypes = other.mimeTypes;
  6337. return *this;
  6338. }
  6339. URL::~URL() throw()
  6340. {
  6341. }
  6342. static const String getMangledParameters (const StringPairArray& parameters)
  6343. {
  6344. String p;
  6345. for (int i = 0; i < parameters.size(); ++i)
  6346. {
  6347. if (i > 0)
  6348. p += T("&");
  6349. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6350. << T("=")
  6351. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6352. }
  6353. return p;
  6354. }
  6355. const String URL::toString (const bool includeGetParameters) const
  6356. {
  6357. if (includeGetParameters && parameters.size() > 0)
  6358. return url + T("?") + getMangledParameters (parameters);
  6359. else
  6360. return url;
  6361. }
  6362. bool URL::isWellFormed() const
  6363. {
  6364. //xxx TODO
  6365. return url.isNotEmpty();
  6366. }
  6367. static int findStartOfDomain (const String& url)
  6368. {
  6369. int i = 0;
  6370. while (CharacterFunctions::isLetterOrDigit (url[i])
  6371. || CharacterFunctions::indexOfChar (T("+-."), url[i], false) >= 0)
  6372. ++i;
  6373. return url[i] == T(':') ? i + 1 : 0;
  6374. }
  6375. const String URL::getDomain() const
  6376. {
  6377. int start = findStartOfDomain (url);
  6378. while (url[start] == T('/'))
  6379. ++start;
  6380. const int end1 = url.indexOfChar (start, T('/'));
  6381. const int end2 = url.indexOfChar (start, T(':'));
  6382. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6383. : jmin (end1, end2);
  6384. return url.substring (start, end);
  6385. }
  6386. const String URL::getSubPath() const
  6387. {
  6388. int start = findStartOfDomain (url);
  6389. while (url[start] == T('/'))
  6390. ++start;
  6391. const int startOfPath = url.indexOfChar (start, T('/')) + 1;
  6392. return startOfPath <= 0 ? String::empty
  6393. : url.substring (startOfPath);
  6394. }
  6395. const String URL::getScheme() const
  6396. {
  6397. return url.substring (0, findStartOfDomain (url) - 1);
  6398. }
  6399. const URL URL::withNewSubPath (const String& newPath) const
  6400. {
  6401. int start = findStartOfDomain (url);
  6402. while (url[start] == T('/'))
  6403. ++start;
  6404. const int startOfPath = url.indexOfChar (start, T('/')) + 1;
  6405. URL u (*this);
  6406. if (startOfPath > 0)
  6407. u.url = url.substring (0, startOfPath);
  6408. if (! u.url.endsWithChar (T('/')))
  6409. u.url << '/';
  6410. if (newPath.startsWithChar (T('/')))
  6411. u.url << newPath.substring (1);
  6412. else
  6413. u.url << newPath;
  6414. return u;
  6415. }
  6416. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6417. {
  6418. if (possibleURL.startsWithIgnoreCase (T("http:"))
  6419. || possibleURL.startsWithIgnoreCase (T("ftp:")))
  6420. return true;
  6421. if (possibleURL.startsWithIgnoreCase (T("file:"))
  6422. || possibleURL.containsChar (T('@'))
  6423. || possibleURL.endsWithChar (T('.'))
  6424. || (! possibleURL.containsChar (T('.'))))
  6425. return false;
  6426. if (possibleURL.startsWithIgnoreCase (T("www."))
  6427. && possibleURL.substring (5).containsChar (T('.')))
  6428. return true;
  6429. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6430. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6431. if ((possibleURL + T("/")).containsIgnoreCase (T(".") + String (commonTLDs[i]) + T("/")))
  6432. return true;
  6433. return false;
  6434. }
  6435. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6436. {
  6437. const int atSign = possibleEmailAddress.indexOfChar (T('@'));
  6438. return atSign > 0
  6439. && possibleEmailAddress.lastIndexOfChar (T('.')) > (atSign + 1)
  6440. && (! possibleEmailAddress.endsWithChar (T('.')));
  6441. }
  6442. void* juce_openInternetFile (const String& url,
  6443. const String& headers,
  6444. const MemoryBlock& optionalPostData,
  6445. const bool isPost,
  6446. URL::OpenStreamProgressCallback* callback,
  6447. void* callbackContext,
  6448. int timeOutMs);
  6449. void juce_closeInternetFile (void* handle);
  6450. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6451. int juce_seekInInternetFile (void* handle, int newPosition);
  6452. int64 juce_getInternetFileContentLength (void* handle);
  6453. class WebInputStream : public InputStream
  6454. {
  6455. public:
  6456. WebInputStream (const URL& url,
  6457. const bool isPost_,
  6458. URL::OpenStreamProgressCallback* const progressCallback_,
  6459. void* const progressCallbackContext_,
  6460. const String& extraHeaders,
  6461. int timeOutMs_)
  6462. : position (0),
  6463. finished (false),
  6464. isPost (isPost_),
  6465. progressCallback (progressCallback_),
  6466. progressCallbackContext (progressCallbackContext_),
  6467. timeOutMs (timeOutMs_)
  6468. {
  6469. server = url.toString (! isPost);
  6470. if (isPost_)
  6471. createHeadersAndPostData (url);
  6472. headers += extraHeaders;
  6473. if (! headers.endsWithChar (T('\n')))
  6474. headers << "\r\n";
  6475. handle = juce_openInternetFile (server, headers, postData, isPost,
  6476. progressCallback_, progressCallbackContext_,
  6477. timeOutMs);
  6478. }
  6479. ~WebInputStream()
  6480. {
  6481. juce_closeInternetFile (handle);
  6482. }
  6483. bool isError() const throw()
  6484. {
  6485. return handle == 0;
  6486. }
  6487. int64 getTotalLength()
  6488. {
  6489. return juce_getInternetFileContentLength (handle);
  6490. }
  6491. bool isExhausted()
  6492. {
  6493. return finished;
  6494. }
  6495. int read (void* dest, int bytes)
  6496. {
  6497. if (finished || isError())
  6498. {
  6499. return 0;
  6500. }
  6501. else
  6502. {
  6503. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6504. position += bytesRead;
  6505. if (bytesRead == 0)
  6506. finished = true;
  6507. return bytesRead;
  6508. }
  6509. }
  6510. int64 getPosition()
  6511. {
  6512. return position;
  6513. }
  6514. bool setPosition (int64 wantedPos)
  6515. {
  6516. if (wantedPos != position)
  6517. {
  6518. finished = false;
  6519. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6520. if (actualPos == wantedPos)
  6521. {
  6522. position = wantedPos;
  6523. }
  6524. else
  6525. {
  6526. if (wantedPos < position)
  6527. {
  6528. juce_closeInternetFile (handle);
  6529. position = 0;
  6530. finished = false;
  6531. handle = juce_openInternetFile (server, headers, postData, isPost,
  6532. progressCallback, progressCallbackContext,
  6533. timeOutMs);
  6534. }
  6535. skipNextBytes (wantedPos - position);
  6536. }
  6537. }
  6538. return true;
  6539. }
  6540. juce_UseDebuggingNewOperator
  6541. private:
  6542. String server, headers;
  6543. MemoryBlock postData;
  6544. int64 position;
  6545. bool finished;
  6546. const bool isPost;
  6547. void* handle;
  6548. URL::OpenStreamProgressCallback* const progressCallback;
  6549. void* const progressCallbackContext;
  6550. const int timeOutMs;
  6551. void createHeadersAndPostData (const URL& url)
  6552. {
  6553. if (url.getFilesToUpload().size() > 0)
  6554. {
  6555. // need to upload some files, so do it as multi-part...
  6556. String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6557. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6558. appendUTF8ToPostData ("--" + boundary);
  6559. int i;
  6560. for (i = 0; i < url.getParameters().size(); ++i)
  6561. {
  6562. String s;
  6563. s << "\r\nContent-Disposition: form-data; name=\""
  6564. << url.getParameters().getAllKeys() [i]
  6565. << "\"\r\n\r\n"
  6566. << url.getParameters().getAllValues() [i]
  6567. << "\r\n--"
  6568. << boundary;
  6569. appendUTF8ToPostData (s);
  6570. }
  6571. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6572. {
  6573. const File f (url.getFilesToUpload().getAllValues() [i]);
  6574. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6575. String s;
  6576. s << "\r\nContent-Disposition: form-data; name=\""
  6577. << paramName
  6578. << "\"; filename=\""
  6579. << f.getFileName()
  6580. << "\"\r\n";
  6581. const String mimeType (url.getMimeTypesOfUploadFiles()
  6582. .getValue (paramName, String::empty));
  6583. if (mimeType.isNotEmpty())
  6584. s << "Content-Type: " << mimeType << "\r\n";
  6585. s << "Content-Transfer-Encoding: binary\r\n\r\n";
  6586. appendUTF8ToPostData (s);
  6587. f.loadFileAsData (postData);
  6588. s = "\r\n--" + boundary;
  6589. appendUTF8ToPostData (s);
  6590. }
  6591. appendUTF8ToPostData ("--\r\n");
  6592. }
  6593. else
  6594. {
  6595. appendUTF8ToPostData (getMangledParameters (url.getParameters()));
  6596. appendUTF8ToPostData (url.getPostData());
  6597. // just a short text attachment, so use simple url encoding..
  6598. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6599. + String (postData.getSize())
  6600. + "\r\n";
  6601. }
  6602. }
  6603. void appendUTF8ToPostData (const String& text) throw()
  6604. {
  6605. postData.append (text.toUTF8(),
  6606. (int) strlen (text.toUTF8()));
  6607. }
  6608. WebInputStream (const WebInputStream&);
  6609. const WebInputStream& operator= (const WebInputStream&);
  6610. };
  6611. InputStream* URL::createInputStream (const bool usePostCommand,
  6612. OpenStreamProgressCallback* const progressCallback,
  6613. void* const progressCallbackContext,
  6614. const String& extraHeaders,
  6615. const int timeOutMs) const
  6616. {
  6617. WebInputStream* wi = new WebInputStream (*this, usePostCommand,
  6618. progressCallback, progressCallbackContext,
  6619. extraHeaders,
  6620. timeOutMs);
  6621. if (wi->isError())
  6622. {
  6623. delete wi;
  6624. wi = 0;
  6625. }
  6626. return wi;
  6627. }
  6628. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6629. const bool usePostCommand) const
  6630. {
  6631. InputStream* const in = createInputStream (usePostCommand);
  6632. if (in != 0)
  6633. {
  6634. in->readIntoMemoryBlock (destData, -1);
  6635. delete in;
  6636. return true;
  6637. }
  6638. return false;
  6639. }
  6640. const String URL::readEntireTextStream (const bool usePostCommand) const
  6641. {
  6642. String result;
  6643. InputStream* const in = createInputStream (usePostCommand);
  6644. if (in != 0)
  6645. {
  6646. result = in->readEntireStreamAsString();
  6647. delete in;
  6648. }
  6649. return result;
  6650. }
  6651. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6652. {
  6653. XmlDocument doc (readEntireTextStream (usePostCommand));
  6654. return doc.getDocumentElement();
  6655. }
  6656. const URL URL::withParameter (const String& parameterName,
  6657. const String& parameterValue) const
  6658. {
  6659. URL u (*this);
  6660. u.parameters.set (parameterName, parameterValue);
  6661. return u;
  6662. }
  6663. const URL URL::withFileToUpload (const String& parameterName,
  6664. const File& fileToUpload,
  6665. const String& mimeType) const
  6666. {
  6667. URL u (*this);
  6668. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6669. u.mimeTypes.set (parameterName, mimeType);
  6670. return u;
  6671. }
  6672. const URL URL::withPOSTData (const String& postData_) const
  6673. {
  6674. URL u (*this);
  6675. u.postData = postData_;
  6676. return u;
  6677. }
  6678. const StringPairArray& URL::getParameters() const throw()
  6679. {
  6680. return parameters;
  6681. }
  6682. const StringPairArray& URL::getFilesToUpload() const throw()
  6683. {
  6684. return filesToUpload;
  6685. }
  6686. const StringPairArray& URL::getMimeTypesOfUploadFiles() const throw()
  6687. {
  6688. return mimeTypes;
  6689. }
  6690. const String URL::removeEscapeChars (const String& s)
  6691. {
  6692. const int len = s.length();
  6693. uint8* const resultUTF8 = (uint8*) juce_calloc (len * 4);
  6694. uint8* r = resultUTF8;
  6695. for (int i = 0; i < len; ++i)
  6696. {
  6697. char c = (char) s[i];
  6698. if (c == 0)
  6699. break;
  6700. if (c == '+')
  6701. {
  6702. c = ' ';
  6703. }
  6704. else if (c == '%')
  6705. {
  6706. c = (char) s.substring (i + 1, i + 3).getHexValue32();
  6707. i += 2;
  6708. }
  6709. *r++ = c;
  6710. }
  6711. const String stringResult (String::fromUTF8 (resultUTF8));
  6712. juce_free (resultUTF8);
  6713. return stringResult;
  6714. }
  6715. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6716. {
  6717. String result;
  6718. result.preallocateStorage (s.length() + 8);
  6719. const char* utf8 = s.toUTF8();
  6720. const char* legalChars = isParameter ? "_-.*!'()"
  6721. : "_-$.*!'(),";
  6722. while (*utf8 != 0)
  6723. {
  6724. const char c = *utf8++;
  6725. if (CharacterFunctions::isLetterOrDigit (c)
  6726. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6727. {
  6728. result << c;
  6729. }
  6730. else
  6731. {
  6732. const int v = (int) (uint8) c;
  6733. if (v < 0x10)
  6734. result << T("%0");
  6735. else
  6736. result << T('%');
  6737. result << String::toHexString (v);
  6738. }
  6739. }
  6740. return result;
  6741. }
  6742. extern bool juce_launchFile (const String& fileName,
  6743. const String& parameters) throw();
  6744. bool URL::launchInDefaultBrowser() const
  6745. {
  6746. String u (toString (true));
  6747. if (u.contains (T("@")) && ! u.contains (T(":")))
  6748. u = "mailto:" + u;
  6749. return juce_launchFile (u, String::empty);
  6750. }
  6751. END_JUCE_NAMESPACE
  6752. /********* End of inlined file: juce_URL.cpp *********/
  6753. /********* Start of inlined file: juce_BufferedInputStream.cpp *********/
  6754. BEGIN_JUCE_NAMESPACE
  6755. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6756. const int bufferSize_,
  6757. const bool deleteSourceWhenDestroyed_) throw()
  6758. : source (source_),
  6759. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  6760. bufferSize (jmax (256, bufferSize_)),
  6761. position (source_->getPosition()),
  6762. lastReadPos (0),
  6763. bufferOverlap (128)
  6764. {
  6765. const int sourceSize = (int) source_->getTotalLength();
  6766. if (sourceSize >= 0)
  6767. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6768. bufferStart = position;
  6769. buffer = (char*) juce_malloc (bufferSize);
  6770. }
  6771. BufferedInputStream::~BufferedInputStream() throw()
  6772. {
  6773. if (deleteSourceWhenDestroyed)
  6774. delete source;
  6775. juce_free (buffer);
  6776. }
  6777. int64 BufferedInputStream::getTotalLength()
  6778. {
  6779. return source->getTotalLength();
  6780. }
  6781. int64 BufferedInputStream::getPosition()
  6782. {
  6783. return position;
  6784. }
  6785. bool BufferedInputStream::setPosition (int64 newPosition)
  6786. {
  6787. position = jmax ((int64) 0, newPosition);
  6788. return true;
  6789. }
  6790. bool BufferedInputStream::isExhausted()
  6791. {
  6792. return (position >= lastReadPos)
  6793. && source->isExhausted();
  6794. }
  6795. void BufferedInputStream::ensureBuffered()
  6796. {
  6797. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6798. if (position < bufferStart || position >= bufferEndOverlap)
  6799. {
  6800. int bytesRead;
  6801. if (position < lastReadPos
  6802. && position >= bufferEndOverlap
  6803. && position >= bufferStart)
  6804. {
  6805. const int bytesToKeep = (int) (lastReadPos - position);
  6806. memmove (buffer, buffer + position - bufferStart, bytesToKeep);
  6807. bufferStart = position;
  6808. bytesRead = source->read (buffer + bytesToKeep,
  6809. bufferSize - bytesToKeep);
  6810. lastReadPos += bytesRead;
  6811. bytesRead += bytesToKeep;
  6812. }
  6813. else
  6814. {
  6815. bufferStart = position;
  6816. source->setPosition (bufferStart);
  6817. bytesRead = source->read (buffer, bufferSize);
  6818. lastReadPos = bufferStart + bytesRead;
  6819. }
  6820. while (bytesRead < bufferSize)
  6821. buffer [bytesRead++] = 0;
  6822. }
  6823. }
  6824. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6825. {
  6826. if (position >= bufferStart
  6827. && position + maxBytesToRead <= lastReadPos)
  6828. {
  6829. memcpy (destBuffer, buffer + (position - bufferStart), maxBytesToRead);
  6830. position += maxBytesToRead;
  6831. return maxBytesToRead;
  6832. }
  6833. else
  6834. {
  6835. if (position < bufferStart || position >= lastReadPos)
  6836. ensureBuffered();
  6837. int bytesRead = 0;
  6838. while (maxBytesToRead > 0)
  6839. {
  6840. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6841. if (bytesAvailable > 0)
  6842. {
  6843. memcpy (destBuffer, buffer + (position - bufferStart), bytesAvailable);
  6844. maxBytesToRead -= bytesAvailable;
  6845. bytesRead += bytesAvailable;
  6846. position += bytesAvailable;
  6847. destBuffer = (void*) (((char*) destBuffer) + bytesAvailable);
  6848. }
  6849. const int64 oldLastReadPos = lastReadPos;
  6850. ensureBuffered();
  6851. if (oldLastReadPos == lastReadPos)
  6852. break; // if ensureBuffered() failed to read any more data, bail out
  6853. if (isExhausted())
  6854. break;
  6855. }
  6856. return bytesRead;
  6857. }
  6858. }
  6859. const String BufferedInputStream::readString()
  6860. {
  6861. if (position >= bufferStart
  6862. && position < lastReadPos)
  6863. {
  6864. const int maxChars = (int) (lastReadPos - position);
  6865. const char* const src = buffer + (position - bufferStart);
  6866. for (int i = 0; i < maxChars; ++i)
  6867. {
  6868. if (src[i] == 0)
  6869. {
  6870. position += i + 1;
  6871. return String::fromUTF8 ((const uint8*) src, i);
  6872. }
  6873. }
  6874. }
  6875. return InputStream::readString();
  6876. }
  6877. END_JUCE_NAMESPACE
  6878. /********* End of inlined file: juce_BufferedInputStream.cpp *********/
  6879. /********* Start of inlined file: juce_FileInputSource.cpp *********/
  6880. BEGIN_JUCE_NAMESPACE
  6881. FileInputSource::FileInputSource (const File& file_) throw()
  6882. : file (file_)
  6883. {
  6884. }
  6885. FileInputSource::~FileInputSource()
  6886. {
  6887. }
  6888. InputStream* FileInputSource::createInputStream()
  6889. {
  6890. return file.createInputStream();
  6891. }
  6892. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  6893. {
  6894. return file.getSiblingFile (relatedItemPath).createInputStream();
  6895. }
  6896. int64 FileInputSource::hashCode() const
  6897. {
  6898. return file.hashCode();
  6899. }
  6900. END_JUCE_NAMESPACE
  6901. /********* End of inlined file: juce_FileInputSource.cpp *********/
  6902. /********* Start of inlined file: juce_MemoryInputStream.cpp *********/
  6903. BEGIN_JUCE_NAMESPACE
  6904. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  6905. const int sourceDataSize,
  6906. const bool keepInternalCopy) throw()
  6907. : data ((const char*) sourceData),
  6908. dataSize (sourceDataSize),
  6909. position (0)
  6910. {
  6911. if (keepInternalCopy)
  6912. {
  6913. internalCopy.append (data, sourceDataSize);
  6914. data = (const char*) internalCopy.getData();
  6915. }
  6916. }
  6917. MemoryInputStream::~MemoryInputStream() throw()
  6918. {
  6919. }
  6920. int64 MemoryInputStream::getTotalLength()
  6921. {
  6922. return dataSize;
  6923. }
  6924. int MemoryInputStream::read (void* buffer, int howMany)
  6925. {
  6926. const int num = jmin (howMany, dataSize - position);
  6927. memcpy (buffer, data + position, num);
  6928. position += num;
  6929. return num;
  6930. }
  6931. bool MemoryInputStream::isExhausted()
  6932. {
  6933. return (position >= dataSize);
  6934. }
  6935. bool MemoryInputStream::setPosition (int64 pos)
  6936. {
  6937. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  6938. return true;
  6939. }
  6940. int64 MemoryInputStream::getPosition()
  6941. {
  6942. return position;
  6943. }
  6944. END_JUCE_NAMESPACE
  6945. /********* End of inlined file: juce_MemoryInputStream.cpp *********/
  6946. /********* Start of inlined file: juce_MemoryOutputStream.cpp *********/
  6947. BEGIN_JUCE_NAMESPACE
  6948. MemoryOutputStream::MemoryOutputStream (const int initialSize,
  6949. const int blockSizeToIncreaseBy,
  6950. MemoryBlock* const memoryBlockToWriteTo) throw()
  6951. : data (memoryBlockToWriteTo),
  6952. position (0),
  6953. size (0),
  6954. blockSize (jmax (16, blockSizeToIncreaseBy)),
  6955. ownsMemoryBlock (memoryBlockToWriteTo == 0)
  6956. {
  6957. if (memoryBlockToWriteTo == 0)
  6958. data = new MemoryBlock (initialSize);
  6959. else
  6960. memoryBlockToWriteTo->setSize (initialSize, false);
  6961. }
  6962. MemoryOutputStream::~MemoryOutputStream() throw()
  6963. {
  6964. if (ownsMemoryBlock)
  6965. delete data;
  6966. else
  6967. flush();
  6968. }
  6969. void MemoryOutputStream::flush()
  6970. {
  6971. if (! ownsMemoryBlock)
  6972. data->setSize (size, false);
  6973. }
  6974. void MemoryOutputStream::reset() throw()
  6975. {
  6976. position = 0;
  6977. size = 0;
  6978. }
  6979. bool MemoryOutputStream::write (const void* buffer, int howMany)
  6980. {
  6981. if (howMany > 0)
  6982. {
  6983. int storageNeeded = position + howMany;
  6984. if (storageNeeded >= data->getSize())
  6985. {
  6986. // if we need more space, increase the block by at least 10%..
  6987. storageNeeded += jmax (blockSize, storageNeeded / 10);
  6988. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  6989. data->ensureSize (storageNeeded);
  6990. }
  6991. data->copyFrom (buffer, position, howMany);
  6992. position += howMany;
  6993. size = jmax (size, position);
  6994. }
  6995. return true;
  6996. }
  6997. const char* MemoryOutputStream::getData() throw()
  6998. {
  6999. if (data->getSize() > size)
  7000. ((char*) data->getData()) [size] = 0;
  7001. return (const char*) data->getData();
  7002. }
  7003. int MemoryOutputStream::getDataSize() const throw()
  7004. {
  7005. return size;
  7006. }
  7007. int64 MemoryOutputStream::getPosition()
  7008. {
  7009. return position;
  7010. }
  7011. bool MemoryOutputStream::setPosition (int64 newPosition)
  7012. {
  7013. if (newPosition <= size)
  7014. {
  7015. // ok to seek backwards
  7016. position = jlimit (0, size, (int) newPosition);
  7017. return true;
  7018. }
  7019. else
  7020. {
  7021. // trying to make it bigger isn't a good thing to do..
  7022. return false;
  7023. }
  7024. }
  7025. END_JUCE_NAMESPACE
  7026. /********* End of inlined file: juce_MemoryOutputStream.cpp *********/
  7027. /********* Start of inlined file: juce_SubregionStream.cpp *********/
  7028. BEGIN_JUCE_NAMESPACE
  7029. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7030. const int64 startPositionInSourceStream_,
  7031. const int64 lengthOfSourceStream_,
  7032. const bool deleteSourceWhenDestroyed_) throw()
  7033. : source (sourceStream),
  7034. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  7035. startPositionInSourceStream (startPositionInSourceStream_),
  7036. lengthOfSourceStream (lengthOfSourceStream_)
  7037. {
  7038. setPosition (0);
  7039. }
  7040. SubregionStream::~SubregionStream() throw()
  7041. {
  7042. if (deleteSourceWhenDestroyed)
  7043. delete source;
  7044. }
  7045. int64 SubregionStream::getTotalLength()
  7046. {
  7047. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7048. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7049. : srcLen;
  7050. }
  7051. int64 SubregionStream::getPosition()
  7052. {
  7053. return source->getPosition() - startPositionInSourceStream;
  7054. }
  7055. bool SubregionStream::setPosition (int64 newPosition)
  7056. {
  7057. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7058. }
  7059. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7060. {
  7061. if (lengthOfSourceStream < 0)
  7062. {
  7063. return source->read (destBuffer, maxBytesToRead);
  7064. }
  7065. else
  7066. {
  7067. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7068. if (maxBytesToRead <= 0)
  7069. return 0;
  7070. return source->read (destBuffer, maxBytesToRead);
  7071. }
  7072. }
  7073. bool SubregionStream::isExhausted()
  7074. {
  7075. if (lengthOfSourceStream >= 0)
  7076. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7077. else
  7078. return source->isExhausted();
  7079. }
  7080. END_JUCE_NAMESPACE
  7081. /********* End of inlined file: juce_SubregionStream.cpp *********/
  7082. /********* Start of inlined file: juce_PerformanceCounter.cpp *********/
  7083. BEGIN_JUCE_NAMESPACE
  7084. PerformanceCounter::PerformanceCounter (const String& name_,
  7085. int runsPerPrintout,
  7086. const File& loggingFile)
  7087. : name (name_),
  7088. numRuns (0),
  7089. runsPerPrint (runsPerPrintout),
  7090. totalTime (0),
  7091. outputFile (loggingFile)
  7092. {
  7093. if (outputFile != File::nonexistent)
  7094. {
  7095. String s ("**** Counter for \"");
  7096. s << name_ << "\" started at: "
  7097. << Time::getCurrentTime().toString (true, true)
  7098. << "\r\n";
  7099. outputFile.appendText (s, false, false);
  7100. }
  7101. }
  7102. PerformanceCounter::~PerformanceCounter()
  7103. {
  7104. printStatistics();
  7105. }
  7106. void PerformanceCounter::start()
  7107. {
  7108. started = Time::getHighResolutionTicks();
  7109. }
  7110. void PerformanceCounter::stop()
  7111. {
  7112. const int64 now = Time::getHighResolutionTicks();
  7113. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7114. if (++numRuns == runsPerPrint)
  7115. printStatistics();
  7116. }
  7117. void PerformanceCounter::printStatistics()
  7118. {
  7119. if (numRuns > 0)
  7120. {
  7121. String s ("Performance count for \"");
  7122. s << name << "\" - average over " << numRuns << " run(s) = ";
  7123. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7124. if (micros > 10000)
  7125. s << (micros/1000) << " millisecs";
  7126. else
  7127. s << micros << " microsecs";
  7128. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7129. Logger::outputDebugString (s);
  7130. s << "\r\n";
  7131. if (outputFile != File::nonexistent)
  7132. outputFile.appendText (s, false, false);
  7133. numRuns = 0;
  7134. totalTime = 0;
  7135. }
  7136. }
  7137. END_JUCE_NAMESPACE
  7138. /********* End of inlined file: juce_PerformanceCounter.cpp *********/
  7139. /********* Start of inlined file: juce_Uuid.cpp *********/
  7140. BEGIN_JUCE_NAMESPACE
  7141. Uuid::Uuid()
  7142. {
  7143. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7144. // to make it very very unlikely that two UUIDs will ever be the same..
  7145. static int64 macAddresses[2];
  7146. static bool hasCheckedMacAddresses = false;
  7147. if (! hasCheckedMacAddresses)
  7148. {
  7149. hasCheckedMacAddresses = true;
  7150. SystemStats::getMACAddresses (macAddresses, 2);
  7151. }
  7152. value.asInt64[0] = macAddresses[0];
  7153. value.asInt64[1] = macAddresses[1];
  7154. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7155. // whose seed will carry over between calls to this method.
  7156. Random r (macAddresses[0] ^ macAddresses[1]
  7157. ^ Random::getSystemRandom().nextInt64());
  7158. for (int i = 4; --i >= 0;)
  7159. {
  7160. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7161. value.asInt[i] ^= r.nextInt();
  7162. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7163. }
  7164. }
  7165. Uuid::~Uuid() throw()
  7166. {
  7167. }
  7168. Uuid::Uuid (const Uuid& other)
  7169. : value (other.value)
  7170. {
  7171. }
  7172. Uuid& Uuid::operator= (const Uuid& other)
  7173. {
  7174. if (this != &other)
  7175. value = other.value;
  7176. return *this;
  7177. }
  7178. bool Uuid::operator== (const Uuid& other) const
  7179. {
  7180. return memcmp (value.asBytes, other.value.asBytes, 16) == 0;
  7181. }
  7182. bool Uuid::operator!= (const Uuid& other) const
  7183. {
  7184. return ! operator== (other);
  7185. }
  7186. bool Uuid::isNull() const throw()
  7187. {
  7188. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7189. }
  7190. const String Uuid::toString() const
  7191. {
  7192. return String::toHexString (value.asBytes, 16, 0);
  7193. }
  7194. Uuid::Uuid (const String& uuidString)
  7195. {
  7196. operator= (uuidString);
  7197. }
  7198. Uuid& Uuid::operator= (const String& uuidString)
  7199. {
  7200. int destIndex = 0;
  7201. int i = 0;
  7202. for (;;)
  7203. {
  7204. int byte = 0;
  7205. for (int loop = 2; --loop >= 0;)
  7206. {
  7207. byte <<= 4;
  7208. for (;;)
  7209. {
  7210. const tchar c = uuidString [i++];
  7211. if (c >= T('0') && c <= T('9'))
  7212. {
  7213. byte |= c - T('0');
  7214. break;
  7215. }
  7216. else if (c >= T('a') && c <= T('z'))
  7217. {
  7218. byte |= c - (T('a') - 10);
  7219. break;
  7220. }
  7221. else if (c >= T('A') && c <= T('Z'))
  7222. {
  7223. byte |= c - (T('A') - 10);
  7224. break;
  7225. }
  7226. else if (c == 0)
  7227. {
  7228. while (destIndex < 16)
  7229. value.asBytes [destIndex++] = 0;
  7230. return *this;
  7231. }
  7232. }
  7233. }
  7234. value.asBytes [destIndex++] = (uint8) byte;
  7235. }
  7236. }
  7237. Uuid::Uuid (const uint8* const rawData)
  7238. {
  7239. operator= (rawData);
  7240. }
  7241. Uuid& Uuid::operator= (const uint8* const rawData)
  7242. {
  7243. if (rawData != 0)
  7244. memcpy (value.asBytes, rawData, 16);
  7245. else
  7246. zeromem (value.asBytes, 16);
  7247. return *this;
  7248. }
  7249. END_JUCE_NAMESPACE
  7250. /********* End of inlined file: juce_Uuid.cpp *********/
  7251. /********* Start of inlined file: juce_ZipFile.cpp *********/
  7252. BEGIN_JUCE_NAMESPACE
  7253. struct ZipEntryInfo
  7254. {
  7255. ZipFile::ZipEntry entry;
  7256. int streamOffset;
  7257. int compressedSize;
  7258. bool compressed;
  7259. };
  7260. class ZipInputStream : public InputStream
  7261. {
  7262. public:
  7263. ZipInputStream (ZipFile& file_,
  7264. ZipEntryInfo& zei) throw()
  7265. : file (file_),
  7266. zipEntryInfo (zei),
  7267. pos (0),
  7268. headerSize (0),
  7269. inputStream (0)
  7270. {
  7271. inputStream = file_.inputStream;
  7272. if (file_.inputSource != 0)
  7273. {
  7274. inputStream = file.inputSource->createInputStream();
  7275. }
  7276. else
  7277. {
  7278. #ifdef JUCE_DEBUG
  7279. file_.numOpenStreams++;
  7280. #endif
  7281. }
  7282. char buffer [30];
  7283. if (inputStream != 0
  7284. && inputStream->setPosition (zei.streamOffset)
  7285. && inputStream->read (buffer, 30) == 30
  7286. && littleEndianInt (buffer) == 0x04034b50)
  7287. {
  7288. headerSize = 30 + littleEndianShort (buffer + 26)
  7289. + littleEndianShort (buffer + 28);
  7290. }
  7291. }
  7292. ~ZipInputStream() throw()
  7293. {
  7294. #ifdef JUCE_DEBUG
  7295. if (inputStream != 0 && inputStream == file.inputStream)
  7296. file.numOpenStreams--;
  7297. #endif
  7298. if (inputStream != file.inputStream)
  7299. delete inputStream;
  7300. }
  7301. int64 getTotalLength() throw()
  7302. {
  7303. return zipEntryInfo.compressedSize;
  7304. }
  7305. int read (void* buffer, int howMany) throw()
  7306. {
  7307. if (headerSize <= 0)
  7308. return 0;
  7309. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7310. if (inputStream == 0)
  7311. return 0;
  7312. int num;
  7313. if (inputStream == file.inputStream)
  7314. {
  7315. const ScopedLock sl (file.lock);
  7316. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7317. num = inputStream->read (buffer, howMany);
  7318. }
  7319. else
  7320. {
  7321. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7322. num = inputStream->read (buffer, howMany);
  7323. }
  7324. pos += num;
  7325. return num;
  7326. }
  7327. bool isExhausted() throw()
  7328. {
  7329. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7330. }
  7331. int64 getPosition() throw()
  7332. {
  7333. return pos;
  7334. }
  7335. bool setPosition (int64 newPos) throw()
  7336. {
  7337. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7338. return true;
  7339. }
  7340. private:
  7341. ZipFile& file;
  7342. ZipEntryInfo zipEntryInfo;
  7343. int64 pos;
  7344. int headerSize;
  7345. InputStream* inputStream;
  7346. ZipInputStream (const ZipInputStream&);
  7347. const ZipInputStream& operator= (const ZipInputStream&);
  7348. };
  7349. ZipFile::ZipFile (InputStream* const source_,
  7350. const bool deleteStreamWhenDestroyed_) throw()
  7351. : inputStream (source_),
  7352. inputSource (0),
  7353. deleteStreamWhenDestroyed (deleteStreamWhenDestroyed_)
  7354. #ifdef JUCE_DEBUG
  7355. , numOpenStreams (0)
  7356. #endif
  7357. {
  7358. init();
  7359. }
  7360. ZipFile::ZipFile (const File& file)
  7361. : inputStream (0),
  7362. deleteStreamWhenDestroyed (false)
  7363. #ifdef JUCE_DEBUG
  7364. , numOpenStreams (0)
  7365. #endif
  7366. {
  7367. inputSource = new FileInputSource (file);
  7368. init();
  7369. }
  7370. ZipFile::ZipFile (InputSource* const inputSource_)
  7371. : inputStream (0),
  7372. inputSource (inputSource_),
  7373. deleteStreamWhenDestroyed (false)
  7374. #ifdef JUCE_DEBUG
  7375. , numOpenStreams (0)
  7376. #endif
  7377. {
  7378. init();
  7379. }
  7380. ZipFile::~ZipFile() throw()
  7381. {
  7382. for (int i = entries.size(); --i >= 0;)
  7383. {
  7384. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [i];
  7385. delete zei;
  7386. }
  7387. if (deleteStreamWhenDestroyed)
  7388. delete inputStream;
  7389. delete inputSource;
  7390. #ifdef JUCE_DEBUG
  7391. // If you hit this assertion, it means you've created a stream to read
  7392. // one of the items in the zipfile, but you've forgotten to delete that
  7393. // stream object before deleting the file.. Streams can't be kept open
  7394. // after the file is deleted because they need to share the input
  7395. // stream that the file uses to read itself.
  7396. jassert (numOpenStreams == 0);
  7397. #endif
  7398. }
  7399. int ZipFile::getNumEntries() const throw()
  7400. {
  7401. return entries.size();
  7402. }
  7403. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7404. {
  7405. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [index];
  7406. return (zei != 0) ? &(zei->entry)
  7407. : 0;
  7408. }
  7409. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7410. {
  7411. for (int i = 0; i < entries.size(); ++i)
  7412. if (((ZipEntryInfo*) entries.getUnchecked (i))->entry.filename == fileName)
  7413. return i;
  7414. return -1;
  7415. }
  7416. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7417. {
  7418. return getEntry (getIndexOfFileName (fileName));
  7419. }
  7420. InputStream* ZipFile::createStreamForEntry (const int index)
  7421. {
  7422. ZipEntryInfo* const zei = (ZipEntryInfo*) entries[index];
  7423. InputStream* stream = 0;
  7424. if (zei != 0)
  7425. {
  7426. stream = new ZipInputStream (*this, *zei);
  7427. if (zei->compressed)
  7428. {
  7429. stream = new GZIPDecompressorInputStream (stream, true, true,
  7430. zei->entry.uncompressedSize);
  7431. // (much faster to unzip in big blocks using a buffer..)
  7432. stream = new BufferedInputStream (stream, 32768, true);
  7433. }
  7434. }
  7435. return stream;
  7436. }
  7437. class ZipFilenameComparator
  7438. {
  7439. public:
  7440. static int compareElements (const void* const first, const void* const second) throw()
  7441. {
  7442. return ((const ZipEntryInfo*) first)->entry.filename
  7443. .compare (((const ZipEntryInfo*) second)->entry.filename);
  7444. }
  7445. };
  7446. void ZipFile::sortEntriesByFilename()
  7447. {
  7448. ZipFilenameComparator sorter;
  7449. entries.sort (sorter);
  7450. }
  7451. void ZipFile::init()
  7452. {
  7453. InputStream* in = inputStream;
  7454. bool deleteInput = false;
  7455. if (inputSource != 0)
  7456. {
  7457. deleteInput = true;
  7458. in = inputSource->createInputStream();
  7459. }
  7460. if (in != 0)
  7461. {
  7462. numEntries = 0;
  7463. int pos = findEndOfZipEntryTable (in);
  7464. if (pos >= 0 && pos < in->getTotalLength())
  7465. {
  7466. const int size = (int) (in->getTotalLength() - pos);
  7467. in->setPosition (pos);
  7468. MemoryBlock headerData;
  7469. if (in->readIntoMemoryBlock (headerData, size) == size)
  7470. {
  7471. pos = 0;
  7472. for (int i = 0; i < numEntries; ++i)
  7473. {
  7474. if (pos + 46 > size)
  7475. break;
  7476. const char* const buffer = ((const char*) headerData.getData()) + pos;
  7477. const int fileNameLen = littleEndianShort (buffer + 28);
  7478. if (pos + 46 + fileNameLen > size)
  7479. break;
  7480. ZipEntryInfo* const zei = new ZipEntryInfo();
  7481. zei->entry.filename = String (buffer + 46, fileNameLen);
  7482. const int time = littleEndianShort (buffer + 12);
  7483. const int date = littleEndianShort (buffer + 14);
  7484. const int year = 1980 + (date >> 9);
  7485. const int month = ((date >> 5) & 15) - 1;
  7486. const int day = date & 31;
  7487. const int hours = time >> 11;
  7488. const int minutes = (time >> 5) & 63;
  7489. const int seconds = (time & 31) << 1;
  7490. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7491. zei->compressed = littleEndianShort (buffer + 10) != 0;
  7492. zei->compressedSize = littleEndianInt (buffer + 20);
  7493. zei->entry.uncompressedSize = littleEndianInt (buffer + 24);
  7494. zei->streamOffset = littleEndianInt (buffer + 42);
  7495. entries.add (zei);
  7496. pos += 46 + fileNameLen
  7497. + littleEndianShort (buffer + 30)
  7498. + littleEndianShort (buffer + 32);
  7499. }
  7500. }
  7501. }
  7502. if (deleteInput)
  7503. delete in;
  7504. }
  7505. }
  7506. int ZipFile::findEndOfZipEntryTable (InputStream* input)
  7507. {
  7508. BufferedInputStream in (input, 8192, false);
  7509. in.setPosition (in.getTotalLength());
  7510. int64 pos = in.getPosition();
  7511. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7512. char buffer [32];
  7513. zeromem (buffer, sizeof (buffer));
  7514. while (pos > lowestPos)
  7515. {
  7516. in.setPosition (pos - 22);
  7517. pos = in.getPosition();
  7518. memcpy (buffer + 22, buffer, 4);
  7519. if (in.read (buffer, 22) != 22)
  7520. return 0;
  7521. for (int i = 0; i < 22; ++i)
  7522. {
  7523. if (littleEndianInt (buffer + i) == 0x06054b50)
  7524. {
  7525. in.setPosition (pos + i);
  7526. in.read (buffer, 22);
  7527. numEntries = littleEndianShort (buffer + 10);
  7528. return littleEndianInt (buffer + 16);
  7529. }
  7530. }
  7531. }
  7532. return 0;
  7533. }
  7534. void ZipFile::uncompressTo (const File& targetDirectory,
  7535. const bool shouldOverwriteFiles)
  7536. {
  7537. for (int i = 0; i < entries.size(); ++i)
  7538. {
  7539. const ZipEntryInfo& zei = *(ZipEntryInfo*) entries[i];
  7540. const File targetFile (targetDirectory.getChildFile (zei.entry.filename));
  7541. if (zei.entry.filename.endsWithChar (T('/')))
  7542. {
  7543. targetFile.createDirectory(); // (entry is a directory, not a file)
  7544. }
  7545. else
  7546. {
  7547. InputStream* const in = createStreamForEntry (i);
  7548. if (in != 0)
  7549. {
  7550. if (shouldOverwriteFiles)
  7551. targetFile.deleteFile();
  7552. if ((! targetFile.exists())
  7553. && targetFile.getParentDirectory().createDirectory())
  7554. {
  7555. FileOutputStream* const out = targetFile.createOutputStream();
  7556. if (out != 0)
  7557. {
  7558. out->writeFromInputStream (*in, -1);
  7559. delete out;
  7560. targetFile.setCreationTime (zei.entry.fileTime);
  7561. targetFile.setLastModificationTime (zei.entry.fileTime);
  7562. targetFile.setLastAccessTime (zei.entry.fileTime);
  7563. }
  7564. }
  7565. delete in;
  7566. }
  7567. }
  7568. }
  7569. }
  7570. END_JUCE_NAMESPACE
  7571. /********* End of inlined file: juce_ZipFile.cpp *********/
  7572. /********* Start of inlined file: juce_CharacterFunctions.cpp *********/
  7573. #ifdef _MSC_VER
  7574. #pragma warning (disable: 4514 4996)
  7575. #pragma warning (push)
  7576. #endif
  7577. #include <cwctype>
  7578. #include <cctype>
  7579. #include <ctime>
  7580. #ifdef _MSC_VER
  7581. #pragma warning (pop)
  7582. #endif
  7583. BEGIN_JUCE_NAMESPACE
  7584. int CharacterFunctions::length (const char* const s) throw()
  7585. {
  7586. return (int) strlen (s);
  7587. }
  7588. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7589. {
  7590. return (int) wcslen (s);
  7591. }
  7592. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7593. {
  7594. strncpy (dest, src, maxChars);
  7595. }
  7596. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7597. {
  7598. wcsncpy (dest, src, maxChars);
  7599. }
  7600. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7601. {
  7602. mbstowcs (dest, src, maxChars);
  7603. }
  7604. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7605. {
  7606. wcstombs (dest, src, maxChars);
  7607. }
  7608. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7609. {
  7610. return (int) wcstombs (0, src, 0);
  7611. }
  7612. void CharacterFunctions::append (char* dest, const char* src) throw()
  7613. {
  7614. strcat (dest, src);
  7615. }
  7616. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7617. {
  7618. wcscat (dest, src);
  7619. }
  7620. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7621. {
  7622. return strcmp (s1, s2);
  7623. }
  7624. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7625. {
  7626. jassert (s1 != 0 && s2 != 0);
  7627. return wcscmp (s1, s2);
  7628. }
  7629. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7630. {
  7631. jassert (s1 != 0 && s2 != 0);
  7632. return strncmp (s1, s2, maxChars);
  7633. }
  7634. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7635. {
  7636. jassert (s1 != 0 && s2 != 0);
  7637. return wcsncmp (s1, s2, maxChars);
  7638. }
  7639. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7640. {
  7641. jassert (s1 != 0 && s2 != 0);
  7642. #if JUCE_WIN32
  7643. return stricmp (s1, s2);
  7644. #else
  7645. return strcasecmp (s1, s2);
  7646. #endif
  7647. }
  7648. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7649. {
  7650. jassert (s1 != 0 && s2 != 0);
  7651. #if JUCE_WIN32
  7652. return _wcsicmp (s1, s2);
  7653. #else
  7654. for (;;)
  7655. {
  7656. if (*s1 != *s2)
  7657. {
  7658. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7659. if (diff != 0)
  7660. return diff < 0 ? -1 : 1;
  7661. }
  7662. else if (*s1 == 0)
  7663. break;
  7664. ++s1;
  7665. ++s2;
  7666. }
  7667. return 0;
  7668. #endif
  7669. }
  7670. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7671. {
  7672. jassert (s1 != 0 && s2 != 0);
  7673. #if JUCE_WIN32
  7674. return strnicmp (s1, s2, maxChars);
  7675. #else
  7676. return strncasecmp (s1, s2, maxChars);
  7677. #endif
  7678. }
  7679. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7680. {
  7681. jassert (s1 != 0 && s2 != 0);
  7682. #if JUCE_WIN32
  7683. return _wcsnicmp (s1, s2, maxChars);
  7684. #else
  7685. while (--maxChars >= 0)
  7686. {
  7687. if (*s1 != *s2)
  7688. {
  7689. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7690. if (diff != 0)
  7691. return diff < 0 ? -1 : 1;
  7692. }
  7693. else if (*s1 == 0)
  7694. break;
  7695. ++s1;
  7696. ++s2;
  7697. }
  7698. return 0;
  7699. #endif
  7700. }
  7701. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7702. {
  7703. return strstr (haystack, needle);
  7704. }
  7705. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7706. {
  7707. return wcsstr (haystack, needle);
  7708. }
  7709. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7710. {
  7711. if (haystack != 0)
  7712. {
  7713. int i = 0;
  7714. if (ignoreCase)
  7715. {
  7716. const char n1 = toLowerCase (needle);
  7717. const char n2 = toUpperCase (needle);
  7718. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7719. {
  7720. while (haystack[i] != 0)
  7721. {
  7722. if (haystack[i] == n1 || haystack[i] == n2)
  7723. return i;
  7724. ++i;
  7725. }
  7726. return -1;
  7727. }
  7728. jassert (n1 == needle);
  7729. }
  7730. while (haystack[i] != 0)
  7731. {
  7732. if (haystack[i] == needle)
  7733. return i;
  7734. ++i;
  7735. }
  7736. }
  7737. return -1;
  7738. }
  7739. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7740. {
  7741. if (haystack != 0)
  7742. {
  7743. int i = 0;
  7744. if (ignoreCase)
  7745. {
  7746. const juce_wchar n1 = toLowerCase (needle);
  7747. const juce_wchar n2 = toUpperCase (needle);
  7748. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7749. {
  7750. while (haystack[i] != 0)
  7751. {
  7752. if (haystack[i] == n1 || haystack[i] == n2)
  7753. return i;
  7754. ++i;
  7755. }
  7756. return -1;
  7757. }
  7758. jassert (n1 == needle);
  7759. }
  7760. while (haystack[i] != 0)
  7761. {
  7762. if (haystack[i] == needle)
  7763. return i;
  7764. ++i;
  7765. }
  7766. }
  7767. return -1;
  7768. }
  7769. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7770. {
  7771. jassert (haystack != 0);
  7772. int i = 0;
  7773. while (haystack[i] != 0)
  7774. {
  7775. if (haystack[i] == needle)
  7776. return i;
  7777. ++i;
  7778. }
  7779. return -1;
  7780. }
  7781. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7782. {
  7783. jassert (haystack != 0);
  7784. int i = 0;
  7785. while (haystack[i] != 0)
  7786. {
  7787. if (haystack[i] == needle)
  7788. return i;
  7789. ++i;
  7790. }
  7791. return -1;
  7792. }
  7793. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7794. {
  7795. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7796. }
  7797. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7798. {
  7799. if (allowedChars == 0)
  7800. return 0;
  7801. int i = 0;
  7802. for (;;)
  7803. {
  7804. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7805. break;
  7806. ++i;
  7807. }
  7808. return i;
  7809. }
  7810. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7811. {
  7812. return (int) strftime (dest, maxChars, format, tm);
  7813. }
  7814. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7815. {
  7816. return (int) wcsftime (dest, maxChars, format, tm);
  7817. }
  7818. int CharacterFunctions::getIntValue (const char* const s) throw()
  7819. {
  7820. return atoi (s);
  7821. }
  7822. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7823. {
  7824. #if JUCE_WIN32
  7825. return _wtoi (s);
  7826. #else
  7827. int v = 0;
  7828. while (isWhitespace (*s))
  7829. ++s;
  7830. const bool isNeg = *s == T('-');
  7831. if (isNeg)
  7832. ++s;
  7833. for (;;)
  7834. {
  7835. const wchar_t c = *s++;
  7836. if (c >= T('0') && c <= T('9'))
  7837. v = v * 10 + (int) (c - T('0'));
  7838. else
  7839. break;
  7840. }
  7841. return isNeg ? -v : v;
  7842. #endif
  7843. }
  7844. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  7845. {
  7846. #if JUCE_LINUX
  7847. return atoll (s);
  7848. #elif defined (JUCE_WIN32)
  7849. return _atoi64 (s);
  7850. #else
  7851. int64 v = 0;
  7852. while (isWhitespace (*s))
  7853. ++s;
  7854. const bool isNeg = *s == T('-');
  7855. if (isNeg)
  7856. ++s;
  7857. for (;;)
  7858. {
  7859. const char c = *s++;
  7860. if (c >= '0' && c <= '9')
  7861. v = v * 10 + (int64) (c - '0');
  7862. else
  7863. break;
  7864. }
  7865. return isNeg ? -v : v;
  7866. #endif
  7867. }
  7868. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  7869. {
  7870. #if JUCE_WIN32
  7871. return _wtoi64 (s);
  7872. #else
  7873. int64 v = 0;
  7874. while (isWhitespace (*s))
  7875. ++s;
  7876. const bool isNeg = *s == T('-');
  7877. if (isNeg)
  7878. ++s;
  7879. for (;;)
  7880. {
  7881. const juce_wchar c = *s++;
  7882. if (c >= T('0') && c <= T('9'))
  7883. v = v * 10 + (int64) (c - T('0'));
  7884. else
  7885. break;
  7886. }
  7887. return isNeg ? -v : v;
  7888. #endif
  7889. }
  7890. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  7891. {
  7892. return atof (s);
  7893. }
  7894. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  7895. {
  7896. wchar_t* endChar;
  7897. return wcstod (s, &endChar);
  7898. }
  7899. char CharacterFunctions::toUpperCase (const char character) throw()
  7900. {
  7901. return (char) toupper (character);
  7902. }
  7903. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  7904. {
  7905. return towupper (character);
  7906. }
  7907. void CharacterFunctions::toUpperCase (char* s) throw()
  7908. {
  7909. #if JUCE_WIN32
  7910. strupr (s);
  7911. #else
  7912. while (*s != 0)
  7913. {
  7914. *s = toUpperCase (*s);
  7915. ++s;
  7916. }
  7917. #endif
  7918. }
  7919. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  7920. {
  7921. #if JUCE_WIN32
  7922. _wcsupr (s);
  7923. #else
  7924. while (*s != 0)
  7925. {
  7926. *s = toUpperCase (*s);
  7927. ++s;
  7928. }
  7929. #endif
  7930. }
  7931. bool CharacterFunctions::isUpperCase (const char character) throw()
  7932. {
  7933. return isupper (character) != 0;
  7934. }
  7935. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  7936. {
  7937. #if JUCE_WIN32
  7938. return iswupper (character) != 0;
  7939. #else
  7940. return toLowerCase (character) != character;
  7941. #endif
  7942. }
  7943. char CharacterFunctions::toLowerCase (const char character) throw()
  7944. {
  7945. return (char) tolower (character);
  7946. }
  7947. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  7948. {
  7949. return towlower (character);
  7950. }
  7951. void CharacterFunctions::toLowerCase (char* s) throw()
  7952. {
  7953. #if JUCE_WIN32
  7954. strlwr (s);
  7955. #else
  7956. while (*s != 0)
  7957. {
  7958. *s = toLowerCase (*s);
  7959. ++s;
  7960. }
  7961. #endif
  7962. }
  7963. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  7964. {
  7965. #if JUCE_WIN32
  7966. _wcslwr (s);
  7967. #else
  7968. while (*s != 0)
  7969. {
  7970. *s = toLowerCase (*s);
  7971. ++s;
  7972. }
  7973. #endif
  7974. }
  7975. bool CharacterFunctions::isLowerCase (const char character) throw()
  7976. {
  7977. return islower (character) != 0;
  7978. }
  7979. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  7980. {
  7981. #if JUCE_WIN32
  7982. return iswlower (character) != 0;
  7983. #else
  7984. return toUpperCase (character) != character;
  7985. #endif
  7986. }
  7987. bool CharacterFunctions::isWhitespace (const char character) throw()
  7988. {
  7989. return character == T(' ') || (character <= 13 && character >= 9);
  7990. }
  7991. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  7992. {
  7993. return iswspace (character) != 0;
  7994. }
  7995. bool CharacterFunctions::isDigit (const char character) throw()
  7996. {
  7997. return (character >= '0' && character <= '9');
  7998. }
  7999. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8000. {
  8001. return iswdigit (character) != 0;
  8002. }
  8003. bool CharacterFunctions::isLetter (const char character) throw()
  8004. {
  8005. return (character >= 'a' && character <= 'z')
  8006. || (character >= 'A' && character <= 'Z');
  8007. }
  8008. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8009. {
  8010. return iswalpha (character) != 0;
  8011. }
  8012. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8013. {
  8014. return (character >= 'a' && character <= 'z')
  8015. || (character >= 'A' && character <= 'Z')
  8016. || (character >= '0' && character <= '9');
  8017. }
  8018. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8019. {
  8020. return iswalnum (character) != 0;
  8021. }
  8022. int CharacterFunctions::getHexDigitValue (const tchar digit) throw()
  8023. {
  8024. if (digit >= T('0') && digit <= T('9'))
  8025. return digit - T('0');
  8026. else if (digit >= T('a') && digit <= T('f'))
  8027. return digit - (T('a') - 10);
  8028. else if (digit >= T('A') && digit <= T('F'))
  8029. return digit - (T('A') - 10);
  8030. return -1;
  8031. }
  8032. int CharacterFunctions::printf (char* const dest, const int maxLength, const char* const format, ...) throw()
  8033. {
  8034. va_list list;
  8035. va_start (list, format);
  8036. return vprintf (dest, maxLength, format, list);
  8037. }
  8038. int CharacterFunctions::printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw()
  8039. {
  8040. va_list list;
  8041. va_start (list, format);
  8042. return vprintf (dest, maxLength, format, list);
  8043. }
  8044. int CharacterFunctions::vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw()
  8045. {
  8046. #if JUCE_WIN32
  8047. return (int) _vsnprintf (dest, maxLength, format, args);
  8048. #else
  8049. return (int) vsnprintf (dest, maxLength, format, args);
  8050. #endif
  8051. }
  8052. int CharacterFunctions::vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw()
  8053. {
  8054. #if MACOS_10_3_OR_EARLIER
  8055. const String formatTemp (format);
  8056. size_t num = vprintf ((char*) dest, maxLength, formatTemp, args);
  8057. String temp ((char*) dest);
  8058. temp.copyToBuffer (dest, num);
  8059. dest [num] = 0;
  8060. return (int) num;
  8061. #elif defined (JUCE_WIN32)
  8062. return (int) _vsnwprintf (dest, maxLength, format, args);
  8063. #else
  8064. return (int) vswprintf (dest, maxLength, format, args);
  8065. #endif
  8066. }
  8067. END_JUCE_NAMESPACE
  8068. /********* End of inlined file: juce_CharacterFunctions.cpp *********/
  8069. /********* Start of inlined file: juce_LocalisedStrings.cpp *********/
  8070. BEGIN_JUCE_NAMESPACE
  8071. LocalisedStrings::LocalisedStrings (const String& fileContents) throw()
  8072. {
  8073. loadFromText (fileContents);
  8074. }
  8075. LocalisedStrings::LocalisedStrings (const File& fileToLoad) throw()
  8076. {
  8077. loadFromText (fileToLoad.loadFileAsString());
  8078. }
  8079. LocalisedStrings::~LocalisedStrings() throw()
  8080. {
  8081. }
  8082. const String LocalisedStrings::translate (const String& text) const throw()
  8083. {
  8084. return translations.getValue (text, text);
  8085. }
  8086. static int findCloseQuote (const String& text, int startPos) throw()
  8087. {
  8088. tchar lastChar = 0;
  8089. for (;;)
  8090. {
  8091. const tchar c = text [startPos];
  8092. if (c == 0 || (c == T('"') && lastChar != T('\\')))
  8093. break;
  8094. lastChar = c;
  8095. ++startPos;
  8096. }
  8097. return startPos;
  8098. }
  8099. static const String unescapeString (const String& s) throw()
  8100. {
  8101. return s.replace (T("\\\""), T("\""))
  8102. .replace (T("\\\'"), T("\'"))
  8103. .replace (T("\\t"), T("\t"))
  8104. .replace (T("\\r"), T("\r"))
  8105. .replace (T("\\n"), T("\n"));
  8106. }
  8107. void LocalisedStrings::loadFromText (const String& fileContents) throw()
  8108. {
  8109. StringArray lines;
  8110. lines.addLines (fileContents);
  8111. for (int i = 0; i < lines.size(); ++i)
  8112. {
  8113. String line (lines[i].trim());
  8114. if (line.startsWithChar (T('"')))
  8115. {
  8116. int closeQuote = findCloseQuote (line, 1);
  8117. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8118. if (originalText.isNotEmpty())
  8119. {
  8120. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8121. closeQuote = findCloseQuote (line, openingQuote + 1);
  8122. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8123. if (newText.isNotEmpty())
  8124. translations.set (originalText, newText);
  8125. }
  8126. }
  8127. else if (line.startsWithIgnoreCase (T("language:")))
  8128. {
  8129. languageName = line.substring (9).trim();
  8130. }
  8131. else if (line.startsWithIgnoreCase (T("countries:")))
  8132. {
  8133. countryCodes.addTokens (line.substring (10).trim(), true);
  8134. countryCodes.trim();
  8135. countryCodes.removeEmptyStrings();
  8136. }
  8137. }
  8138. }
  8139. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase) throw()
  8140. {
  8141. translations.setIgnoresCase (shouldIgnoreCase);
  8142. }
  8143. static CriticalSection currentMappingsLock;
  8144. static LocalisedStrings* currentMappings = 0;
  8145. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations) throw()
  8146. {
  8147. const ScopedLock sl (currentMappingsLock);
  8148. delete currentMappings;
  8149. currentMappings = newTranslations;
  8150. }
  8151. LocalisedStrings* LocalisedStrings::getCurrentMappings() throw()
  8152. {
  8153. return currentMappings;
  8154. }
  8155. const String LocalisedStrings::translateWithCurrentMappings (const String& text) throw()
  8156. {
  8157. const ScopedLock sl (currentMappingsLock);
  8158. if (currentMappings != 0)
  8159. return currentMappings->translate (text);
  8160. return text;
  8161. }
  8162. const String LocalisedStrings::translateWithCurrentMappings (const char* text) throw()
  8163. {
  8164. return translateWithCurrentMappings (String (text));
  8165. }
  8166. END_JUCE_NAMESPACE
  8167. /********* End of inlined file: juce_LocalisedStrings.cpp *********/
  8168. /********* Start of inlined file: juce_String.cpp *********/
  8169. #ifdef _MSC_VER
  8170. #pragma warning (disable: 4514)
  8171. #pragma warning (push)
  8172. #endif
  8173. #include <locale>
  8174. #if JUCE_MSVC
  8175. #include <float.h>
  8176. #endif
  8177. BEGIN_JUCE_NAMESPACE
  8178. #ifdef _MSC_VER
  8179. #pragma warning (pop)
  8180. #endif
  8181. static const char* const emptyCharString = "\0\0\0\0JUCE";
  8182. static const int safeEmptyStringRefCount = 0x3fffffff;
  8183. String::InternalRefCountedStringHolder String::emptyString = { safeEmptyStringRefCount, 0, { 0 } };
  8184. static tchar decimalPoint = T('.');
  8185. void juce_initialiseStrings()
  8186. {
  8187. decimalPoint = String::fromUTF8 ((const uint8*) localeconv()->decimal_point) [0];
  8188. }
  8189. void String::deleteInternal() throw()
  8190. {
  8191. if (atomicDecrementAndReturn (text->refCount) == 0)
  8192. juce_free (text);
  8193. }
  8194. void String::createInternal (const int numChars) throw()
  8195. {
  8196. jassert (numChars > 0);
  8197. text = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8198. + numChars * sizeof (tchar));
  8199. text->refCount = 1;
  8200. text->allocatedNumChars = numChars;
  8201. text->text[0] = 0;
  8202. }
  8203. void String::createInternal (const tchar* const t, const tchar* const textEnd) throw()
  8204. {
  8205. jassert (*(textEnd - 1) == 0); // must have a null terminator
  8206. const int numChars = (int) (textEnd - t);
  8207. createInternal (numChars - 1);
  8208. memcpy (text->text, t, numChars * sizeof (tchar));
  8209. }
  8210. void String::appendInternal (const tchar* const newText,
  8211. const int numExtraChars) throw()
  8212. {
  8213. if (numExtraChars > 0)
  8214. {
  8215. const int oldLen = CharacterFunctions::length (text->text);
  8216. const int newTotalLen = oldLen + numExtraChars;
  8217. if (text->refCount > 1)
  8218. {
  8219. // it's in use by other strings as well, so we need to make a private copy before messing with it..
  8220. InternalRefCountedStringHolder* const newTextHolder
  8221. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8222. + newTotalLen * sizeof (tchar));
  8223. newTextHolder->refCount = 1;
  8224. newTextHolder->allocatedNumChars = newTotalLen;
  8225. memcpy (newTextHolder->text, text->text, oldLen * sizeof (tchar));
  8226. memcpy (newTextHolder->text + oldLen, newText, numExtraChars * sizeof (tchar));
  8227. InternalRefCountedStringHolder* const old = text;
  8228. text = newTextHolder;
  8229. if (atomicDecrementAndReturn (old->refCount) == 0)
  8230. juce_free (old);
  8231. }
  8232. else
  8233. {
  8234. // no other strings using it, so just expand it if needed..
  8235. if (newTotalLen > text->allocatedNumChars)
  8236. {
  8237. text = (InternalRefCountedStringHolder*)
  8238. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8239. + newTotalLen * sizeof (tchar));
  8240. text->allocatedNumChars = newTotalLen;
  8241. }
  8242. memcpy (text->text + oldLen, newText, numExtraChars * sizeof (tchar));
  8243. }
  8244. text->text [newTotalLen] = 0;
  8245. }
  8246. }
  8247. void String::dupeInternalIfMultiplyReferenced() throw()
  8248. {
  8249. if (text->refCount > 1)
  8250. {
  8251. InternalRefCountedStringHolder* const old = text;
  8252. const int len = old->allocatedNumChars;
  8253. InternalRefCountedStringHolder* const newTextHolder
  8254. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8255. + len * sizeof (tchar));
  8256. newTextHolder->refCount = 1;
  8257. newTextHolder->allocatedNumChars = len;
  8258. memcpy (newTextHolder->text, old->text, (len + 1) * sizeof (tchar));
  8259. text = newTextHolder;
  8260. if (atomicDecrementAndReturn (old->refCount) == 0)
  8261. juce_free (old);
  8262. }
  8263. }
  8264. const String String::empty;
  8265. String::String() throw()
  8266. : text (&emptyString)
  8267. {
  8268. }
  8269. String::String (const String& other) throw()
  8270. : text (other.text)
  8271. {
  8272. atomicIncrement (text->refCount);
  8273. }
  8274. String::String (const int numChars,
  8275. const int /*dummyVariable*/) throw()
  8276. {
  8277. createInternal (numChars);
  8278. }
  8279. String::String (const char* const t) throw()
  8280. {
  8281. if (t != 0 && *t != 0)
  8282. {
  8283. const int len = CharacterFunctions::length (t);
  8284. createInternal (len);
  8285. #if JUCE_STRINGS_ARE_UNICODE
  8286. CharacterFunctions::copy (text->text, t, len + 1);
  8287. #else
  8288. memcpy (text->text, t, len + 1);
  8289. #endif
  8290. }
  8291. else
  8292. {
  8293. text = &emptyString;
  8294. emptyString.refCount = safeEmptyStringRefCount;
  8295. }
  8296. }
  8297. String::String (const juce_wchar* const t) throw()
  8298. {
  8299. if (t != 0 && *t != 0)
  8300. {
  8301. #if JUCE_STRINGS_ARE_UNICODE
  8302. const int len = CharacterFunctions::length (t);
  8303. createInternal (len);
  8304. memcpy (text->text, t, (len + 1) * sizeof (tchar));
  8305. #else
  8306. const int len = CharacterFunctions::bytesRequiredForCopy (t);
  8307. createInternal (len);
  8308. CharacterFunctions::copy (text->text, t, len + 1);
  8309. #endif
  8310. }
  8311. else
  8312. {
  8313. text = &emptyString;
  8314. emptyString.refCount = safeEmptyStringRefCount;
  8315. }
  8316. }
  8317. String::String (const char* const t,
  8318. const int maxChars) throw()
  8319. {
  8320. int i;
  8321. for (i = 0; i < maxChars; ++i)
  8322. if (t[i] == 0)
  8323. break;
  8324. if (i > 0)
  8325. {
  8326. createInternal (i);
  8327. #if JUCE_STRINGS_ARE_UNICODE
  8328. CharacterFunctions::copy (text->text, t, i);
  8329. #else
  8330. memcpy (text->text, t, i);
  8331. #endif
  8332. text->text [i] = 0;
  8333. }
  8334. else
  8335. {
  8336. text = &emptyString;
  8337. emptyString.refCount = safeEmptyStringRefCount;
  8338. }
  8339. }
  8340. String::String (const juce_wchar* const t,
  8341. const int maxChars) throw()
  8342. {
  8343. int i;
  8344. for (i = 0; i < maxChars; ++i)
  8345. if (t[i] == 0)
  8346. break;
  8347. if (i > 0)
  8348. {
  8349. createInternal (i);
  8350. #if JUCE_STRINGS_ARE_UNICODE
  8351. memcpy (text->text, t, i * sizeof (tchar));
  8352. #else
  8353. CharacterFunctions::copy (text->text, t, i);
  8354. #endif
  8355. text->text [i] = 0;
  8356. }
  8357. else
  8358. {
  8359. text = &emptyString;
  8360. emptyString.refCount = safeEmptyStringRefCount;
  8361. }
  8362. }
  8363. const String String::charToString (const tchar character) throw()
  8364. {
  8365. tchar temp[2];
  8366. temp[0] = character;
  8367. temp[1] = 0;
  8368. return String (temp);
  8369. }
  8370. // pass in a pointer to the END of a buffer..
  8371. static tchar* int64ToCharString (tchar* t, const int64 n) throw()
  8372. {
  8373. *--t = 0;
  8374. int64 v = (n >= 0) ? n : -n;
  8375. do
  8376. {
  8377. *--t = (tchar) (T('0') + (int) (v % 10));
  8378. v /= 10;
  8379. } while (v > 0);
  8380. if (n < 0)
  8381. *--t = T('-');
  8382. return t;
  8383. }
  8384. static tchar* intToCharString (tchar* t, const int n) throw()
  8385. {
  8386. if (n == (int) 0x80000000) // (would cause an overflow)
  8387. return int64ToCharString (t, n);
  8388. *--t = 0;
  8389. int v = abs (n);
  8390. do
  8391. {
  8392. *--t = (tchar) (T('0') + (v % 10));
  8393. v /= 10;
  8394. } while (v > 0);
  8395. if (n < 0)
  8396. *--t = T('-');
  8397. return t;
  8398. }
  8399. static tchar* uintToCharString (tchar* t, unsigned int v) throw()
  8400. {
  8401. *--t = 0;
  8402. do
  8403. {
  8404. *--t = (tchar) (T('0') + (v % 10));
  8405. v /= 10;
  8406. } while (v > 0);
  8407. return t;
  8408. }
  8409. String::String (const int number) throw()
  8410. {
  8411. tchar buffer [16];
  8412. tchar* const end = buffer + 16;
  8413. createInternal (intToCharString (end, number), end);
  8414. }
  8415. String::String (const unsigned int number) throw()
  8416. {
  8417. tchar buffer [16];
  8418. tchar* const end = buffer + 16;
  8419. createInternal (uintToCharString (end, number), end);
  8420. }
  8421. String::String (const short number) throw()
  8422. {
  8423. tchar buffer [16];
  8424. tchar* const end = buffer + 16;
  8425. createInternal (intToCharString (end, (int) number), end);
  8426. }
  8427. String::String (const unsigned short number) throw()
  8428. {
  8429. tchar buffer [16];
  8430. tchar* const end = buffer + 16;
  8431. createInternal (uintToCharString (end, (unsigned int) number), end);
  8432. }
  8433. String::String (const int64 number) throw()
  8434. {
  8435. tchar buffer [32];
  8436. tchar* const end = buffer + 32;
  8437. createInternal (int64ToCharString (end, number), end);
  8438. }
  8439. String::String (const uint64 number) throw()
  8440. {
  8441. tchar buffer [32];
  8442. tchar* const end = buffer + 32;
  8443. tchar* t = end;
  8444. *--t = 0;
  8445. int64 v = number;
  8446. do
  8447. {
  8448. *--t = (tchar) (T('0') + (int) (v % 10));
  8449. v /= 10;
  8450. } while (v > 0);
  8451. createInternal (t, end);
  8452. }
  8453. // a double-to-string routine that actually uses the number of dec. places you asked for
  8454. // without resorting to exponent notation if the number's too big or small (which is what printf does).
  8455. void String::doubleToStringWithDecPlaces (double n, int numDecPlaces) throw()
  8456. {
  8457. const int bufSize = 80;
  8458. tchar buffer [bufSize];
  8459. int len;
  8460. tchar* t;
  8461. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8462. {
  8463. int64 v = (int64) (pow (10.0, numDecPlaces) * fabs (n) + 0.5);
  8464. t = buffer + bufSize;
  8465. *--t = (tchar) 0;
  8466. while (numDecPlaces >= 0 || v > 0)
  8467. {
  8468. if (numDecPlaces == 0)
  8469. *--t = decimalPoint;
  8470. *--t = (tchar) (T('0') + (v % 10));
  8471. v /= 10;
  8472. --numDecPlaces;
  8473. }
  8474. if (n < 0)
  8475. *--t = T('-');
  8476. len = (int) ((buffer + bufSize) - t);
  8477. }
  8478. else
  8479. {
  8480. len = CharacterFunctions::printf (buffer, bufSize, T("%.9g"), n) + 1;
  8481. t = buffer;
  8482. }
  8483. if (len > 1)
  8484. {
  8485. jassert (len < numElementsInArray (buffer));
  8486. createInternal (len - 1);
  8487. memcpy (text->text, t, len * sizeof (tchar));
  8488. }
  8489. else
  8490. {
  8491. jassert (*t == 0);
  8492. text = &emptyString;
  8493. emptyString.refCount = safeEmptyStringRefCount;
  8494. }
  8495. }
  8496. String::String (const float number,
  8497. const int numberOfDecimalPlaces) throw()
  8498. {
  8499. doubleToStringWithDecPlaces ((double) number,
  8500. numberOfDecimalPlaces);
  8501. }
  8502. String::String (const double number,
  8503. const int numberOfDecimalPlaces) throw()
  8504. {
  8505. doubleToStringWithDecPlaces (number,
  8506. numberOfDecimalPlaces);
  8507. }
  8508. String::~String() throw()
  8509. {
  8510. emptyString.refCount = safeEmptyStringRefCount;
  8511. if (atomicDecrementAndReturn (text->refCount) == 0)
  8512. juce_free (text);
  8513. }
  8514. void String::preallocateStorage (const int numChars) throw()
  8515. {
  8516. if (numChars > text->allocatedNumChars)
  8517. {
  8518. dupeInternalIfMultiplyReferenced();
  8519. text = (InternalRefCountedStringHolder*) juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8520. + numChars * sizeof (tchar));
  8521. text->allocatedNumChars = numChars;
  8522. }
  8523. }
  8524. #if JUCE_STRINGS_ARE_UNICODE
  8525. String::operator const char*() const throw()
  8526. {
  8527. if (isEmpty())
  8528. {
  8529. return (const char*) emptyCharString;
  8530. }
  8531. else
  8532. {
  8533. String* const mutableThis = const_cast <String*> (this);
  8534. mutableThis->dupeInternalIfMultiplyReferenced();
  8535. int len = CharacterFunctions::bytesRequiredForCopy (text->text) + 1;
  8536. mutableThis->text = (InternalRefCountedStringHolder*)
  8537. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8538. + (len * sizeof (juce_wchar) + len));
  8539. char* otherCopy = (char*) (text->text + len);
  8540. --len;
  8541. CharacterFunctions::copy (otherCopy, text->text, len);
  8542. otherCopy [len] = 0;
  8543. return otherCopy;
  8544. }
  8545. }
  8546. #else
  8547. String::operator const juce_wchar*() const throw()
  8548. {
  8549. if (isEmpty())
  8550. {
  8551. return (const juce_wchar*) emptyCharString;
  8552. }
  8553. else
  8554. {
  8555. String* const mutableThis = const_cast <String*> (this);
  8556. mutableThis->dupeInternalIfMultiplyReferenced();
  8557. int len = CharacterFunctions::length (text->text) + 1;
  8558. mutableThis->text = (InternalRefCountedStringHolder*)
  8559. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8560. + (len * sizeof (juce_wchar) + len));
  8561. juce_wchar* otherCopy = (juce_wchar*) (text->text + len);
  8562. --len;
  8563. CharacterFunctions::copy (otherCopy, text->text, len);
  8564. otherCopy [len] = 0;
  8565. return otherCopy;
  8566. }
  8567. }
  8568. #endif
  8569. void String::copyToBuffer (char* const destBuffer,
  8570. const int bufferSizeBytes) const throw()
  8571. {
  8572. #if JUCE_STRINGS_ARE_UNICODE
  8573. const int len = jmin (bufferSizeBytes, CharacterFunctions::bytesRequiredForCopy (text->text));
  8574. CharacterFunctions::copy (destBuffer, text->text, len);
  8575. #else
  8576. const int len = jmin (bufferSizeBytes, length());
  8577. memcpy (destBuffer, text->text, len * sizeof (tchar));
  8578. #endif
  8579. destBuffer [len] = 0;
  8580. }
  8581. void String::copyToBuffer (juce_wchar* const destBuffer,
  8582. const int maxCharsToCopy) const throw()
  8583. {
  8584. const int len = jmin (maxCharsToCopy, length());
  8585. #if JUCE_STRINGS_ARE_UNICODE
  8586. memcpy (destBuffer, text->text, len * sizeof (juce_wchar));
  8587. #else
  8588. CharacterFunctions::copy (destBuffer, text->text, len);
  8589. #endif
  8590. destBuffer [len] = 0;
  8591. }
  8592. int String::length() const throw()
  8593. {
  8594. return CharacterFunctions::length (text->text);
  8595. }
  8596. int String::hashCode() const throw()
  8597. {
  8598. const tchar* t = text->text;
  8599. int result = 0;
  8600. while (*t != (tchar) 0)
  8601. result = 31 * result + *t++;
  8602. return result;
  8603. }
  8604. int64 String::hashCode64() const throw()
  8605. {
  8606. const tchar* t = text->text;
  8607. int64 result = 0;
  8608. while (*t != (tchar) 0)
  8609. result = 101 * result + *t++;
  8610. return result;
  8611. }
  8612. const String& String::operator= (const tchar* const otherText) throw()
  8613. {
  8614. if (otherText != 0 && *otherText != 0)
  8615. {
  8616. const int otherLen = CharacterFunctions::length (otherText);
  8617. if (otherLen > 0)
  8618. {
  8619. // avoid resizing the memory block if the string is
  8620. // shrinking..
  8621. if (text->refCount > 1
  8622. || otherLen > text->allocatedNumChars
  8623. || otherLen <= (text->allocatedNumChars >> 1))
  8624. {
  8625. deleteInternal();
  8626. createInternal (otherLen);
  8627. }
  8628. memcpy (text->text, otherText, (otherLen + 1) * sizeof (tchar));
  8629. return *this;
  8630. }
  8631. }
  8632. deleteInternal();
  8633. text = &emptyString;
  8634. emptyString.refCount = safeEmptyStringRefCount;
  8635. return *this;
  8636. }
  8637. const String& String::operator= (const String& other) throw()
  8638. {
  8639. if (this != &other)
  8640. {
  8641. atomicIncrement (other.text->refCount);
  8642. if (atomicDecrementAndReturn (text->refCount) == 0)
  8643. juce_free (text);
  8644. text = other.text;
  8645. }
  8646. return *this;
  8647. }
  8648. bool String::operator== (const String& other) const throw()
  8649. {
  8650. return text == other.text
  8651. || CharacterFunctions::compare (text->text, other.text->text) == 0;
  8652. }
  8653. bool String::operator== (const tchar* const t) const throw()
  8654. {
  8655. return t != 0 ? CharacterFunctions::compare (text->text, t) == 0
  8656. : isEmpty();
  8657. }
  8658. bool String::equalsIgnoreCase (const tchar* t) const throw()
  8659. {
  8660. return t != 0 ? CharacterFunctions::compareIgnoreCase (text->text, t) == 0
  8661. : isEmpty();
  8662. }
  8663. bool String::equalsIgnoreCase (const String& other) const throw()
  8664. {
  8665. return text == other.text
  8666. || CharacterFunctions::compareIgnoreCase (text->text, other.text->text) == 0;
  8667. }
  8668. bool String::operator!= (const String& other) const throw()
  8669. {
  8670. return text != other.text
  8671. && CharacterFunctions::compare (text->text, other.text->text) != 0;
  8672. }
  8673. bool String::operator!= (const tchar* const t) const throw()
  8674. {
  8675. return t != 0 ? (CharacterFunctions::compare (text->text, t) != 0)
  8676. : isNotEmpty();
  8677. }
  8678. bool String::operator> (const String& other) const throw()
  8679. {
  8680. return compare (other) > 0;
  8681. }
  8682. bool String::operator< (const tchar* const other) const throw()
  8683. {
  8684. return compare (other) < 0;
  8685. }
  8686. bool String::operator>= (const String& other) const throw()
  8687. {
  8688. return compare (other) >= 0;
  8689. }
  8690. bool String::operator<= (const tchar* const other) const throw()
  8691. {
  8692. return compare (other) <= 0;
  8693. }
  8694. int String::compare (const tchar* const other) const throw()
  8695. {
  8696. return other != 0 ? CharacterFunctions::compare (text->text, other)
  8697. : isEmpty();
  8698. }
  8699. int String::compareIgnoreCase (const tchar* const other) const throw()
  8700. {
  8701. return other != 0 ? CharacterFunctions::compareIgnoreCase (text->text, other)
  8702. : isEmpty();
  8703. }
  8704. int String::compareLexicographically (const tchar* other) const throw()
  8705. {
  8706. if (other == 0)
  8707. return isEmpty();
  8708. const tchar* s1 = text->text;
  8709. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8710. ++s1;
  8711. while (*other != 0 && ! CharacterFunctions::isLetterOrDigit (*other))
  8712. ++other;
  8713. return CharacterFunctions::compareIgnoreCase (s1, other);
  8714. }
  8715. const String String::operator+ (const String& other) const throw()
  8716. {
  8717. if (*(other.text->text) == 0)
  8718. return *this;
  8719. if (isEmpty())
  8720. return other;
  8721. const int len = CharacterFunctions::length (text->text);
  8722. const int otherLen = CharacterFunctions::length (other.text->text);
  8723. String result (len + otherLen, (int) 0);
  8724. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8725. memcpy (result.text->text + len, other.text->text, otherLen * sizeof (tchar));
  8726. result.text->text [len + otherLen] = 0;
  8727. return result;
  8728. }
  8729. const String String::operator+ (const tchar* const textToAppend) const throw()
  8730. {
  8731. if (textToAppend == 0 || *textToAppend == 0)
  8732. return *this;
  8733. const int len = CharacterFunctions::length (text->text);
  8734. const int otherLen = CharacterFunctions::length (textToAppend);
  8735. String result (len + otherLen, (int) 0);
  8736. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8737. memcpy (result.text->text + len, textToAppend, otherLen * sizeof (tchar));
  8738. result.text->text [len + otherLen] = 0;
  8739. return result;
  8740. }
  8741. const String String::operator+ (const tchar characterToAppend) const throw()
  8742. {
  8743. if (characterToAppend == 0)
  8744. return *this;
  8745. const int len = CharacterFunctions::length (text->text);
  8746. String result ((int) (len + 1), (int) 0);
  8747. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8748. result.text->text[len] = characterToAppend;
  8749. result.text->text[len + 1] = 0;
  8750. return result;
  8751. }
  8752. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  8753. const String& string2) throw()
  8754. {
  8755. String s (string1);
  8756. s += string2;
  8757. return s;
  8758. }
  8759. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  8760. const String& string2) throw()
  8761. {
  8762. String s (string1);
  8763. s += string2;
  8764. return s;
  8765. }
  8766. const String& String::operator+= (const tchar* const t) throw()
  8767. {
  8768. if (t != 0)
  8769. appendInternal (t, CharacterFunctions::length (t));
  8770. return *this;
  8771. }
  8772. const String& String::operator+= (const String& other) throw()
  8773. {
  8774. if (isEmpty())
  8775. operator= (other);
  8776. else
  8777. appendInternal (other.text->text,
  8778. CharacterFunctions::length (other.text->text));
  8779. return *this;
  8780. }
  8781. const String& String::operator+= (const char ch) throw()
  8782. {
  8783. char asString[2];
  8784. asString[0] = ch;
  8785. asString[1] = 0;
  8786. #if JUCE_STRINGS_ARE_UNICODE
  8787. operator+= (String (asString));
  8788. #else
  8789. appendInternal (asString, 1);
  8790. #endif
  8791. return *this;
  8792. }
  8793. const String& String::operator+= (const juce_wchar ch) throw()
  8794. {
  8795. juce_wchar asString[2];
  8796. asString[0] = ch;
  8797. asString[1] = 0;
  8798. #if JUCE_STRINGS_ARE_UNICODE
  8799. appendInternal (asString, 1);
  8800. #else
  8801. operator+= (String (asString));
  8802. #endif
  8803. return *this;
  8804. }
  8805. void String::append (const tchar* const other,
  8806. const int howMany) throw()
  8807. {
  8808. if (howMany > 0)
  8809. {
  8810. int i;
  8811. for (i = 0; i < howMany; ++i)
  8812. if (other[i] == 0)
  8813. break;
  8814. appendInternal (other, i);
  8815. }
  8816. }
  8817. String& String::operator<< (const int number) throw()
  8818. {
  8819. tchar buffer [64];
  8820. tchar* const end = buffer + 64;
  8821. const tchar* const t = intToCharString (end, number);
  8822. appendInternal (t, (int) (end - t) - 1);
  8823. return *this;
  8824. }
  8825. String& String::operator<< (const unsigned int number) throw()
  8826. {
  8827. tchar buffer [64];
  8828. tchar* const end = buffer + 64;
  8829. const tchar* const t = uintToCharString (end, number);
  8830. appendInternal (t, (int) (end - t) - 1);
  8831. return *this;
  8832. }
  8833. String& String::operator<< (const short number) throw()
  8834. {
  8835. tchar buffer [64];
  8836. tchar* const end = buffer + 64;
  8837. const tchar* const t = intToCharString (end, (int) number);
  8838. appendInternal (t, (int) (end - t) - 1);
  8839. return *this;
  8840. }
  8841. String& String::operator<< (const double number) throw()
  8842. {
  8843. operator+= (String (number));
  8844. return *this;
  8845. }
  8846. String& String::operator<< (const float number) throw()
  8847. {
  8848. operator+= (String (number));
  8849. return *this;
  8850. }
  8851. String& String::operator<< (const char character) throw()
  8852. {
  8853. operator+= (character);
  8854. return *this;
  8855. }
  8856. String& String::operator<< (const juce_wchar character) throw()
  8857. {
  8858. operator+= (character);
  8859. return *this;
  8860. }
  8861. String& String::operator<< (const char* const t) throw()
  8862. {
  8863. #if JUCE_STRINGS_ARE_UNICODE
  8864. operator+= (String (t));
  8865. #else
  8866. operator+= (t);
  8867. #endif
  8868. return *this;
  8869. }
  8870. String& String::operator<< (const juce_wchar* const t) throw()
  8871. {
  8872. #if JUCE_STRINGS_ARE_UNICODE
  8873. operator+= (t);
  8874. #else
  8875. operator+= (String (t));
  8876. #endif
  8877. return *this;
  8878. }
  8879. String& String::operator<< (const String& t) throw()
  8880. {
  8881. operator+= (t);
  8882. return *this;
  8883. }
  8884. int String::indexOfChar (const tchar character) const throw()
  8885. {
  8886. const tchar* t = text->text;
  8887. for (;;)
  8888. {
  8889. if (*t == character)
  8890. return (int) (t - text->text);
  8891. if (*t++ == 0)
  8892. return -1;
  8893. }
  8894. }
  8895. int String::lastIndexOfChar (const tchar character) const throw()
  8896. {
  8897. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  8898. if (text->text[i] == character)
  8899. return i;
  8900. return -1;
  8901. }
  8902. int String::indexOf (const tchar* const t) const throw()
  8903. {
  8904. const tchar* const r = CharacterFunctions::find (text->text, t);
  8905. return (r == 0) ? -1
  8906. : (int) (r - text->text);
  8907. }
  8908. int String::indexOfChar (const int startIndex,
  8909. const tchar character) const throw()
  8910. {
  8911. if (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text))
  8912. return -1;
  8913. const tchar* t = text->text + jmax (0, startIndex);
  8914. for (;;)
  8915. {
  8916. if (*t == character)
  8917. return (int) (t - text->text);
  8918. if (*t++ == 0)
  8919. return -1;
  8920. }
  8921. }
  8922. int String::indexOfAnyOf (const tchar* const charactersToLookFor,
  8923. const int startIndex,
  8924. const bool ignoreCase) const throw()
  8925. {
  8926. if (charactersToLookFor == 0
  8927. || (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text)))
  8928. return -1;
  8929. const tchar* t = text->text + jmax (0, startIndex);
  8930. while (*t != 0)
  8931. {
  8932. if (CharacterFunctions::indexOfChar (charactersToLookFor, *t, ignoreCase) >= 0)
  8933. return (int) (t - text->text);
  8934. ++t;
  8935. }
  8936. return -1;
  8937. }
  8938. int String::indexOf (const int startIndex,
  8939. const tchar* const other) const throw()
  8940. {
  8941. if (other == 0 || startIndex >= CharacterFunctions::length (text->text))
  8942. return -1;
  8943. const tchar* const found = CharacterFunctions::find (text->text + jmax (0, startIndex),
  8944. other);
  8945. return (found == 0) ? -1
  8946. : (int) (found - text->text);
  8947. }
  8948. int String::indexOfIgnoreCase (const tchar* const other) const throw()
  8949. {
  8950. if (other != 0 && *other != 0)
  8951. {
  8952. const int len = CharacterFunctions::length (other);
  8953. const int end = CharacterFunctions::length (text->text) - len;
  8954. for (int i = 0; i <= end; ++i)
  8955. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  8956. return i;
  8957. }
  8958. return -1;
  8959. }
  8960. int String::indexOfIgnoreCase (const int startIndex,
  8961. const tchar* const other) const throw()
  8962. {
  8963. if (other != 0 && *other != 0)
  8964. {
  8965. const int len = CharacterFunctions::length (other);
  8966. const int end = length() - len;
  8967. for (int i = jmax (0, startIndex); i <= end; ++i)
  8968. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  8969. return i;
  8970. }
  8971. return -1;
  8972. }
  8973. int String::lastIndexOf (const tchar* const other) const throw()
  8974. {
  8975. if (other != 0 && *other != 0)
  8976. {
  8977. const int len = CharacterFunctions::length (other);
  8978. int i = length() - len;
  8979. if (i >= 0)
  8980. {
  8981. const tchar* n = text->text + i;
  8982. while (i >= 0)
  8983. {
  8984. if (CharacterFunctions::compare (n--, other, len) == 0)
  8985. return i;
  8986. --i;
  8987. }
  8988. }
  8989. }
  8990. return -1;
  8991. }
  8992. int String::lastIndexOfIgnoreCase (const tchar* const other) const throw()
  8993. {
  8994. if (other != 0 && *other != 0)
  8995. {
  8996. const int len = CharacterFunctions::length (other);
  8997. int i = length() - len;
  8998. if (i >= 0)
  8999. {
  9000. const tchar* n = text->text + i;
  9001. while (i >= 0)
  9002. {
  9003. if (CharacterFunctions::compareIgnoreCase (n--, other, len) == 0)
  9004. return i;
  9005. --i;
  9006. }
  9007. }
  9008. }
  9009. return -1;
  9010. }
  9011. int String::lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  9012. const bool ignoreCase) const throw()
  9013. {
  9014. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  9015. if (CharacterFunctions::indexOfChar (charactersToLookFor, text->text [i], ignoreCase) >= 0)
  9016. return i;
  9017. return -1;
  9018. }
  9019. bool String::contains (const tchar* const other) const throw()
  9020. {
  9021. return indexOf (other) >= 0;
  9022. }
  9023. bool String::containsChar (const tchar character) const throw()
  9024. {
  9025. return indexOfChar (character) >= 0;
  9026. }
  9027. bool String::containsIgnoreCase (const tchar* const t) const throw()
  9028. {
  9029. return indexOfIgnoreCase (t) >= 0;
  9030. }
  9031. int String::indexOfWholeWord (const tchar* const word) const throw()
  9032. {
  9033. if (word != 0 && *word != 0)
  9034. {
  9035. const int wordLen = CharacterFunctions::length (word);
  9036. const int end = length() - wordLen;
  9037. const tchar* t = text->text;
  9038. for (int i = 0; i <= end; ++i)
  9039. {
  9040. if (CharacterFunctions::compare (t, word, wordLen) == 0
  9041. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9042. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9043. {
  9044. return i;
  9045. }
  9046. ++t;
  9047. }
  9048. }
  9049. return -1;
  9050. }
  9051. int String::indexOfWholeWordIgnoreCase (const tchar* const word) const throw()
  9052. {
  9053. if (word != 0 && *word != 0)
  9054. {
  9055. const int wordLen = CharacterFunctions::length (word);
  9056. const int end = length() - wordLen;
  9057. const tchar* t = text->text;
  9058. for (int i = 0; i <= end; ++i)
  9059. {
  9060. if (CharacterFunctions::compareIgnoreCase (t, word, wordLen) == 0
  9061. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9062. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9063. {
  9064. return i;
  9065. }
  9066. ++t;
  9067. }
  9068. }
  9069. return -1;
  9070. }
  9071. bool String::containsWholeWord (const tchar* const wordToLookFor) const throw()
  9072. {
  9073. return indexOfWholeWord (wordToLookFor) >= 0;
  9074. }
  9075. bool String::containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw()
  9076. {
  9077. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9078. }
  9079. static int indexOfMatch (const tchar* const wildcard,
  9080. const tchar* const test,
  9081. const bool ignoreCase) throw()
  9082. {
  9083. int start = 0;
  9084. while (test [start] != 0)
  9085. {
  9086. int i = 0;
  9087. for (;;)
  9088. {
  9089. const tchar wc = wildcard [i];
  9090. const tchar c = test [i + start];
  9091. if (wc == c
  9092. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9093. || (wc == T('?') && c != 0))
  9094. {
  9095. if (wc == 0)
  9096. return start;
  9097. ++i;
  9098. }
  9099. else
  9100. {
  9101. if (wc == T('*') && (wildcard [i + 1] == 0
  9102. || indexOfMatch (wildcard + i + 1,
  9103. test + start + i,
  9104. ignoreCase) >= 0))
  9105. {
  9106. return start;
  9107. }
  9108. break;
  9109. }
  9110. }
  9111. ++start;
  9112. }
  9113. return -1;
  9114. }
  9115. bool String::matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw()
  9116. {
  9117. int i = 0;
  9118. for (;;)
  9119. {
  9120. const tchar wc = wildcard [i];
  9121. const tchar c = text->text [i];
  9122. if (wc == c
  9123. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9124. || (wc == T('?') && c != 0))
  9125. {
  9126. if (wc == 0)
  9127. return true;
  9128. ++i;
  9129. }
  9130. else
  9131. {
  9132. return wc == T('*') && (wildcard [i + 1] == 0
  9133. || indexOfMatch (wildcard + i + 1,
  9134. text->text + i,
  9135. ignoreCase) >= 0);
  9136. }
  9137. }
  9138. }
  9139. void String::printf (const tchar* const pf, ...) throw()
  9140. {
  9141. va_list list;
  9142. va_start (list, pf);
  9143. vprintf (pf, list);
  9144. }
  9145. const String String::formatted (const tchar* const pf, ...) throw()
  9146. {
  9147. va_list list;
  9148. va_start (list, pf);
  9149. String result;
  9150. result.vprintf (pf, list);
  9151. return result;
  9152. }
  9153. void String::vprintf (const tchar* const pf, va_list& args) throw()
  9154. {
  9155. tchar stackBuf [256];
  9156. unsigned int bufSize = 256;
  9157. tchar* buf = stackBuf;
  9158. deleteInternal();
  9159. do
  9160. {
  9161. #if JUCE_LINUX && JUCE_64BIT
  9162. va_list tempArgs;
  9163. va_copy (tempArgs, args);
  9164. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, tempArgs);
  9165. va_end (tempArgs);
  9166. #else
  9167. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, args);
  9168. #endif
  9169. if (num > 0)
  9170. {
  9171. createInternal (num);
  9172. memcpy (text->text, buf, (num + 1) * sizeof (tchar));
  9173. break;
  9174. }
  9175. else if (num == 0)
  9176. {
  9177. text = &emptyString;
  9178. emptyString.refCount = safeEmptyStringRefCount;
  9179. break;
  9180. }
  9181. if (buf != stackBuf)
  9182. juce_free (buf);
  9183. bufSize += 256;
  9184. buf = (tchar*) juce_malloc (bufSize * sizeof (tchar));
  9185. }
  9186. while (bufSize < 65536); // this is a sanity check to avoid situations where vprintf repeatedly
  9187. // returns -1 because of an error rather than because it needs more space.
  9188. if (buf != stackBuf)
  9189. juce_free (buf);
  9190. }
  9191. const String String::repeatedString (const tchar* const stringToRepeat,
  9192. int numberOfTimesToRepeat) throw()
  9193. {
  9194. const int len = CharacterFunctions::length (stringToRepeat);
  9195. String result ((int) (len * numberOfTimesToRepeat + 1), (int) 0);
  9196. tchar* n = result.text->text;
  9197. n[0] = 0;
  9198. while (--numberOfTimesToRepeat >= 0)
  9199. {
  9200. CharacterFunctions::append (n, stringToRepeat);
  9201. n += len;
  9202. }
  9203. return result;
  9204. }
  9205. const String String::replaceSection (int index,
  9206. int numCharsToReplace,
  9207. const tchar* const stringToInsert) const throw()
  9208. {
  9209. if (index < 0)
  9210. {
  9211. // a negative index to replace from?
  9212. jassertfalse
  9213. index = 0;
  9214. }
  9215. if (numCharsToReplace < 0)
  9216. {
  9217. // replacing a negative number of characters?
  9218. numCharsToReplace = 0;
  9219. jassertfalse;
  9220. }
  9221. const int len = length();
  9222. if (index + numCharsToReplace > len)
  9223. {
  9224. if (index > len)
  9225. {
  9226. // replacing beyond the end of the string?
  9227. index = len;
  9228. jassertfalse
  9229. }
  9230. numCharsToReplace = len - index;
  9231. }
  9232. const int newStringLen = (stringToInsert != 0) ? CharacterFunctions::length (stringToInsert) : 0;
  9233. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9234. if (newTotalLen <= 0)
  9235. return String::empty;
  9236. String result (newTotalLen, (int) 0);
  9237. memcpy (result.text->text,
  9238. text->text,
  9239. index * sizeof (tchar));
  9240. if (newStringLen > 0)
  9241. memcpy (result.text->text + index,
  9242. stringToInsert,
  9243. newStringLen * sizeof (tchar));
  9244. const int endStringLen = newTotalLen - (index + newStringLen);
  9245. if (endStringLen > 0)
  9246. memcpy (result.text->text + (index + newStringLen),
  9247. text->text + (index + numCharsToReplace),
  9248. endStringLen * sizeof (tchar));
  9249. result.text->text [newTotalLen] = 0;
  9250. return result;
  9251. }
  9252. const String String::replace (const tchar* const stringToReplace,
  9253. const tchar* const stringToInsert,
  9254. const bool ignoreCase) const throw()
  9255. {
  9256. const int stringToReplaceLen = CharacterFunctions::length (stringToReplace);
  9257. const int stringToInsertLen = CharacterFunctions::length (stringToInsert);
  9258. int i = 0;
  9259. String result (*this);
  9260. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9261. : result.indexOf (i, stringToReplace))) >= 0)
  9262. {
  9263. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9264. i += stringToInsertLen;
  9265. }
  9266. return result;
  9267. }
  9268. const String String::replaceCharacter (const tchar charToReplace,
  9269. const tchar charToInsert) const throw()
  9270. {
  9271. const int index = indexOfChar (charToReplace);
  9272. if (index < 0)
  9273. return *this;
  9274. String result (*this);
  9275. result.dupeInternalIfMultiplyReferenced();
  9276. tchar* t = result.text->text + index;
  9277. while (*t != 0)
  9278. {
  9279. if (*t == charToReplace)
  9280. *t = charToInsert;
  9281. ++t;
  9282. }
  9283. return result;
  9284. }
  9285. const String String::replaceCharacters (const String& charactersToReplace,
  9286. const tchar* const charactersToInsertInstead) const throw()
  9287. {
  9288. String result (*this);
  9289. result.dupeInternalIfMultiplyReferenced();
  9290. tchar* t = result.text->text;
  9291. const int len2 = CharacterFunctions::length (charactersToInsertInstead);
  9292. // the two strings passed in are supposed to be the same length!
  9293. jassert (len2 == charactersToReplace.length());
  9294. while (*t != 0)
  9295. {
  9296. const int index = charactersToReplace.indexOfChar (*t);
  9297. if (((unsigned int) index) < (unsigned int) len2)
  9298. *t = charactersToInsertInstead [index];
  9299. ++t;
  9300. }
  9301. return result;
  9302. }
  9303. bool String::startsWith (const tchar* const other) const throw()
  9304. {
  9305. return other != 0
  9306. && CharacterFunctions::compare (text->text, other, CharacterFunctions::length (other)) == 0;
  9307. }
  9308. bool String::startsWithIgnoreCase (const tchar* const other) const throw()
  9309. {
  9310. return other != 0
  9311. && CharacterFunctions::compareIgnoreCase (text->text, other, CharacterFunctions::length (other)) == 0;
  9312. }
  9313. bool String::startsWithChar (const tchar character) const throw()
  9314. {
  9315. jassert (character != 0); // strings can't contain a null character!
  9316. return text->text[0] == character;
  9317. }
  9318. bool String::endsWithChar (const tchar character) const throw()
  9319. {
  9320. jassert (character != 0); // strings can't contain a null character!
  9321. return text->text[0] != 0
  9322. && text->text [length() - 1] == character;
  9323. }
  9324. bool String::endsWith (const tchar* const other) const throw()
  9325. {
  9326. if (other == 0)
  9327. return false;
  9328. const int thisLen = length();
  9329. const int otherLen = CharacterFunctions::length (other);
  9330. return thisLen >= otherLen
  9331. && CharacterFunctions::compare (text->text + thisLen - otherLen, other) == 0;
  9332. }
  9333. bool String::endsWithIgnoreCase (const tchar* const other) const throw()
  9334. {
  9335. if (other == 0)
  9336. return false;
  9337. const int thisLen = length();
  9338. const int otherLen = CharacterFunctions::length (other);
  9339. return thisLen >= otherLen
  9340. && CharacterFunctions::compareIgnoreCase (text->text + thisLen - otherLen, other) == 0;
  9341. }
  9342. const String String::toUpperCase() const throw()
  9343. {
  9344. String result (*this);
  9345. result.dupeInternalIfMultiplyReferenced();
  9346. CharacterFunctions::toUpperCase (result.text->text);
  9347. return result;
  9348. }
  9349. const String String::toLowerCase() const throw()
  9350. {
  9351. String result (*this);
  9352. result.dupeInternalIfMultiplyReferenced();
  9353. CharacterFunctions::toLowerCase (result.text->text);
  9354. return result;
  9355. }
  9356. tchar& String::operator[] (const int index) throw()
  9357. {
  9358. jassert (((unsigned int) index) <= (unsigned int) length());
  9359. dupeInternalIfMultiplyReferenced();
  9360. return text->text [index];
  9361. }
  9362. tchar String::getLastCharacter() const throw()
  9363. {
  9364. return (isEmpty()) ? ((tchar) 0)
  9365. : text->text [CharacterFunctions::length (text->text) - 1];
  9366. }
  9367. const String String::substring (int start, int end) const throw()
  9368. {
  9369. if (start < 0)
  9370. start = 0;
  9371. else if (end <= start)
  9372. return empty;
  9373. int len = 0;
  9374. const tchar* const t = text->text;
  9375. while (len <= end && t [len] != 0)
  9376. ++len;
  9377. if (end >= len)
  9378. {
  9379. if (start == 0)
  9380. return *this;
  9381. end = len;
  9382. }
  9383. return String (text->text + start,
  9384. end - start);
  9385. }
  9386. const String String::substring (const int start) const throw()
  9387. {
  9388. if (start <= 0)
  9389. return *this;
  9390. const int len = CharacterFunctions::length (text->text);
  9391. if (start >= len)
  9392. return empty;
  9393. else
  9394. return String (text->text + start,
  9395. len - start);
  9396. }
  9397. const String String::dropLastCharacters (const int numberToDrop) const throw()
  9398. {
  9399. return String (text->text,
  9400. jmax (0, CharacterFunctions::length (text->text) - numberToDrop));
  9401. }
  9402. const String String::fromFirstOccurrenceOf (const tchar* const sub,
  9403. const bool includeSubString,
  9404. const bool ignoreCase) const throw()
  9405. {
  9406. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9407. : indexOf (sub);
  9408. if (i < 0)
  9409. return empty;
  9410. else
  9411. return substring (includeSubString ? i : i + CharacterFunctions::length (sub));
  9412. }
  9413. const String String::fromLastOccurrenceOf (const tchar* const sub,
  9414. const bool includeSubString,
  9415. const bool ignoreCase) const throw()
  9416. {
  9417. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9418. : lastIndexOf (sub);
  9419. if (i < 0)
  9420. return *this;
  9421. else
  9422. return substring (includeSubString ? i : i + CharacterFunctions::length (sub));
  9423. }
  9424. const String String::upToFirstOccurrenceOf (const tchar* const sub,
  9425. const bool includeSubString,
  9426. const bool ignoreCase) const throw()
  9427. {
  9428. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9429. : indexOf (sub);
  9430. if (i < 0)
  9431. return *this;
  9432. else
  9433. return substring (0, includeSubString ? i + CharacterFunctions::length (sub) : i);
  9434. }
  9435. const String String::upToLastOccurrenceOf (const tchar* const sub,
  9436. const bool includeSubString,
  9437. const bool ignoreCase) const throw()
  9438. {
  9439. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9440. : lastIndexOf (sub);
  9441. if (i < 0)
  9442. return *this;
  9443. return substring (0, includeSubString ? i + CharacterFunctions::length (sub) : i);
  9444. }
  9445. bool String::isQuotedString() const throw()
  9446. {
  9447. const String trimmed (trimStart());
  9448. return trimmed[0] == T('"')
  9449. || trimmed[0] == T('\'');
  9450. }
  9451. const String String::unquoted() const throw()
  9452. {
  9453. String s (*this);
  9454. if (s[0] == T('"') || s[0] == T('\''))
  9455. s = s.substring (1);
  9456. const int lastCharIndex = s.length() - 1;
  9457. if (lastCharIndex >= 0
  9458. && (s [lastCharIndex] == T('"') || s[lastCharIndex] == T('\'')))
  9459. s [lastCharIndex] = 0;
  9460. return s;
  9461. }
  9462. const String String::quoted (const tchar quoteCharacter) const throw()
  9463. {
  9464. if (isEmpty())
  9465. return charToString (quoteCharacter) + quoteCharacter;
  9466. String t (*this);
  9467. if (! t.startsWithChar (quoteCharacter))
  9468. t = charToString (quoteCharacter) + t;
  9469. if (! t.endsWithChar (quoteCharacter))
  9470. t += quoteCharacter;
  9471. return t;
  9472. }
  9473. const String String::trim() const throw()
  9474. {
  9475. if (isEmpty())
  9476. return empty;
  9477. int start = 0;
  9478. while (CharacterFunctions::isWhitespace (text->text [start]))
  9479. ++start;
  9480. const int len = CharacterFunctions::length (text->text);
  9481. int end = len - 1;
  9482. while ((end >= start) && CharacterFunctions::isWhitespace (text->text [end]))
  9483. --end;
  9484. ++end;
  9485. if (end <= start)
  9486. return empty;
  9487. else if (start > 0 || end < len)
  9488. return String (text->text + start, end - start);
  9489. else
  9490. return *this;
  9491. }
  9492. const String String::trimStart() const throw()
  9493. {
  9494. if (isEmpty())
  9495. return empty;
  9496. const tchar* t = text->text;
  9497. while (CharacterFunctions::isWhitespace (*t))
  9498. ++t;
  9499. if (t == text->text)
  9500. return *this;
  9501. else
  9502. return String (t);
  9503. }
  9504. const String String::trimEnd() const throw()
  9505. {
  9506. if (isEmpty())
  9507. return empty;
  9508. const tchar* endT = text->text + (CharacterFunctions::length (text->text) - 1);
  9509. while ((endT >= text->text) && CharacterFunctions::isWhitespace (*endT))
  9510. --endT;
  9511. return String (text->text, (int) (++endT - text->text));
  9512. }
  9513. const String String::retainCharacters (const tchar* const charactersToRetain) const throw()
  9514. {
  9515. jassert (charactersToRetain != 0);
  9516. if (isEmpty())
  9517. return empty;
  9518. String result (text->allocatedNumChars, (int) 0);
  9519. tchar* dst = result.text->text;
  9520. const tchar* src = text->text;
  9521. while (*src != 0)
  9522. {
  9523. if (CharacterFunctions::indexOfCharFast (charactersToRetain, *src) >= 0)
  9524. *dst++ = *src;
  9525. ++src;
  9526. }
  9527. *dst = 0;
  9528. return result;
  9529. }
  9530. const String String::removeCharacters (const tchar* const charactersToRemove) const throw()
  9531. {
  9532. jassert (charactersToRemove != 0);
  9533. if (isEmpty())
  9534. return empty;
  9535. String result (text->allocatedNumChars, (int) 0);
  9536. tchar* dst = result.text->text;
  9537. const tchar* src = text->text;
  9538. while (*src != 0)
  9539. {
  9540. if (CharacterFunctions::indexOfCharFast (charactersToRemove, *src) < 0)
  9541. *dst++ = *src;
  9542. ++src;
  9543. }
  9544. *dst = 0;
  9545. return result;
  9546. }
  9547. const String String::initialSectionContainingOnly (const tchar* const permittedCharacters) const throw()
  9548. {
  9549. return substring (0, CharacterFunctions::getIntialSectionContainingOnly (text->text, permittedCharacters));
  9550. }
  9551. const String String::initialSectionNotContaining (const tchar* const charactersToStopAt) const throw()
  9552. {
  9553. jassert (charactersToStopAt != 0);
  9554. const tchar* const t = text->text;
  9555. int i = 0;
  9556. while (t[i] != 0)
  9557. {
  9558. if (CharacterFunctions::indexOfCharFast (charactersToStopAt, t[i]) >= 0)
  9559. return String (text->text, i);
  9560. ++i;
  9561. }
  9562. return empty;
  9563. }
  9564. bool String::containsOnly (const tchar* const chars) const throw()
  9565. {
  9566. jassert (chars != 0);
  9567. const tchar* t = text->text;
  9568. while (*t != 0)
  9569. if (CharacterFunctions::indexOfCharFast (chars, *t++) < 0)
  9570. return false;
  9571. return true;
  9572. }
  9573. bool String::containsAnyOf (const tchar* const chars) const throw()
  9574. {
  9575. jassert (chars != 0);
  9576. const tchar* t = text->text;
  9577. while (*t != 0)
  9578. if (CharacterFunctions::indexOfCharFast (chars, *t++) >= 0)
  9579. return true;
  9580. return false;
  9581. }
  9582. bool String::containsNonWhitespaceChars() const throw()
  9583. {
  9584. const tchar* t = text->text;
  9585. while (*t != 0)
  9586. if (! CharacterFunctions::isWhitespace (*t++))
  9587. return true;
  9588. return false;
  9589. }
  9590. int String::getIntValue() const throw()
  9591. {
  9592. return CharacterFunctions::getIntValue (text->text);
  9593. }
  9594. int String::getTrailingIntValue() const throw()
  9595. {
  9596. int n = 0;
  9597. int mult = 1;
  9598. const tchar* t = text->text + length();
  9599. while (--t >= text->text)
  9600. {
  9601. const tchar c = *t;
  9602. if (! CharacterFunctions::isDigit (c))
  9603. {
  9604. if (c == T('-'))
  9605. n = -n;
  9606. break;
  9607. }
  9608. n += mult * (c - T('0'));
  9609. mult *= 10;
  9610. }
  9611. return n;
  9612. }
  9613. int64 String::getLargeIntValue() const throw()
  9614. {
  9615. return CharacterFunctions::getInt64Value (text->text);
  9616. }
  9617. float String::getFloatValue() const throw()
  9618. {
  9619. return (float) CharacterFunctions::getDoubleValue (text->text);
  9620. }
  9621. double String::getDoubleValue() const throw()
  9622. {
  9623. return CharacterFunctions::getDoubleValue (text->text);
  9624. }
  9625. static const tchar* const hexDigits = T("0123456789abcdef");
  9626. const String String::toHexString (const int number) throw()
  9627. {
  9628. tchar buffer[32];
  9629. tchar* const end = buffer + 32;
  9630. tchar* t = end;
  9631. *--t = 0;
  9632. unsigned int v = (unsigned int) number;
  9633. do
  9634. {
  9635. *--t = hexDigits [v & 15];
  9636. v >>= 4;
  9637. } while (v != 0);
  9638. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9639. }
  9640. const String String::toHexString (const int64 number) throw()
  9641. {
  9642. tchar buffer[32];
  9643. tchar* const end = buffer + 32;
  9644. tchar* t = end;
  9645. *--t = 0;
  9646. uint64 v = (uint64) number;
  9647. do
  9648. {
  9649. *--t = hexDigits [(int) (v & 15)];
  9650. v >>= 4;
  9651. } while (v != 0);
  9652. return String (t, (int) (((char*) end) - (char*) t));
  9653. }
  9654. const String String::toHexString (const short number) throw()
  9655. {
  9656. return toHexString ((int) (unsigned short) number);
  9657. }
  9658. const String String::toHexString (const unsigned char* data,
  9659. const int size,
  9660. const int groupSize) throw()
  9661. {
  9662. if (size <= 0)
  9663. return empty;
  9664. int numChars = (size * 2) + 2;
  9665. if (groupSize > 0)
  9666. numChars += size / groupSize;
  9667. String s (numChars, (int) 0);
  9668. tchar* d = s.text->text;
  9669. for (int i = 0; i < size; ++i)
  9670. {
  9671. *d++ = hexDigits [(*data) >> 4];
  9672. *d++ = hexDigits [(*data) & 0xf];
  9673. ++data;
  9674. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9675. *d++ = T(' ');
  9676. }
  9677. *d = 0;
  9678. return s;
  9679. }
  9680. int String::getHexValue32() const throw()
  9681. {
  9682. int result = 0;
  9683. const tchar* c = text->text;
  9684. for (;;)
  9685. {
  9686. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9687. if (hexValue >= 0)
  9688. result = (result << 4) | hexValue;
  9689. else if (*c == 0)
  9690. break;
  9691. ++c;
  9692. }
  9693. return result;
  9694. }
  9695. int64 String::getHexValue64() const throw()
  9696. {
  9697. int64 result = 0;
  9698. const tchar* c = text->text;
  9699. for (;;)
  9700. {
  9701. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9702. if (hexValue >= 0)
  9703. result = (result << 4) | hexValue;
  9704. else if (*c == 0)
  9705. break;
  9706. ++c;
  9707. }
  9708. return result;
  9709. }
  9710. const String String::createStringFromData (const void* const data_,
  9711. const int size) throw()
  9712. {
  9713. const char* const data = (const char*) data_;
  9714. if (size <= 0 || data == 0)
  9715. {
  9716. return empty;
  9717. }
  9718. else if (size < 2)
  9719. {
  9720. return charToString (data[0]);
  9721. }
  9722. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9723. || (data[0] == (char)-1 && data[1] == (char)-2))
  9724. {
  9725. // assume it's 16-bit unicode
  9726. const bool bigEndian = (data[0] == (char)-2);
  9727. const int numChars = size / 2 - 1;
  9728. String result;
  9729. result.preallocateStorage (numChars + 2);
  9730. const uint16* const src = (const uint16*) (data + 2);
  9731. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  9732. if (bigEndian)
  9733. {
  9734. for (int i = 0; i < numChars; ++i)
  9735. dst[i] = (tchar) swapIfLittleEndian (src[i]);
  9736. }
  9737. else
  9738. {
  9739. for (int i = 0; i < numChars; ++i)
  9740. dst[i] = (tchar) swapIfBigEndian (src[i]);
  9741. }
  9742. dst [numChars] = 0;
  9743. return result;
  9744. }
  9745. else
  9746. {
  9747. return String::fromUTF8 ((const uint8*) data, size);
  9748. }
  9749. }
  9750. const char* String::toUTF8() const throw()
  9751. {
  9752. if (isEmpty())
  9753. {
  9754. return (const char*) emptyCharString;
  9755. }
  9756. else
  9757. {
  9758. String* const mutableThis = const_cast <String*> (this);
  9759. mutableThis->dupeInternalIfMultiplyReferenced();
  9760. const int currentLen = CharacterFunctions::length (text->text) + 1;
  9761. const int utf8BytesNeeded = copyToUTF8 (0);
  9762. mutableThis->text = (InternalRefCountedStringHolder*)
  9763. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  9764. + (currentLen * sizeof (juce_wchar) + utf8BytesNeeded));
  9765. char* const otherCopy = (char*) (text->text + currentLen);
  9766. copyToUTF8 ((uint8*) otherCopy);
  9767. return otherCopy;
  9768. }
  9769. }
  9770. int String::copyToUTF8 (uint8* const buffer, const int maxBufferSizeBytes) const throw()
  9771. {
  9772. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  9773. #if JUCE_STRINGS_ARE_UNICODE
  9774. int num = 0, index = 0;
  9775. for (;;)
  9776. {
  9777. const uint32 c = (uint32) text->text [index++];
  9778. if (c >= 0x80)
  9779. {
  9780. int numExtraBytes = 1;
  9781. if (c >= 0x800)
  9782. {
  9783. ++numExtraBytes;
  9784. if (c >= 0x10000)
  9785. {
  9786. ++numExtraBytes;
  9787. if (c >= 0x200000)
  9788. {
  9789. ++numExtraBytes;
  9790. if (c >= 0x4000000)
  9791. ++numExtraBytes;
  9792. }
  9793. }
  9794. }
  9795. if (buffer != 0)
  9796. {
  9797. if (num + numExtraBytes >= maxBufferSizeBytes)
  9798. {
  9799. buffer [num++] = 0;
  9800. break;
  9801. }
  9802. else
  9803. {
  9804. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9805. while (--numExtraBytes >= 0)
  9806. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9807. }
  9808. }
  9809. else
  9810. {
  9811. num += numExtraBytes + 1;
  9812. }
  9813. }
  9814. else
  9815. {
  9816. if (buffer != 0)
  9817. {
  9818. if (num + 1 >= maxBufferSizeBytes)
  9819. {
  9820. buffer [num++] = 0;
  9821. break;
  9822. }
  9823. buffer [num] = (uint8) c;
  9824. }
  9825. ++num;
  9826. }
  9827. if (c == 0)
  9828. break;
  9829. }
  9830. return num;
  9831. #else
  9832. const int numBytes = jmin (maxBufferSizeBytes, length() + 1);
  9833. if (buffer != 0)
  9834. copyToBuffer ((char*) buffer, maxBufferSizeBytes);
  9835. return numBytes;
  9836. #endif
  9837. }
  9838. const String String::fromUTF8 (const uint8* const buffer, int bufferSizeBytes) throw()
  9839. {
  9840. if (buffer == 0)
  9841. return empty;
  9842. if (bufferSizeBytes < 0)
  9843. bufferSizeBytes = INT_MAX;
  9844. int numBytes;
  9845. for (numBytes = 0; numBytes < bufferSizeBytes; ++numBytes)
  9846. if (buffer [numBytes] == 0)
  9847. break;
  9848. String result (numBytes + 1, 0);
  9849. tchar* dest = result.text->text;
  9850. int i = 0;
  9851. while (i < numBytes)
  9852. {
  9853. const uint8 c = buffer [i++];
  9854. if ((c & 0x80) != 0)
  9855. {
  9856. int mask = 0x7f;
  9857. int bit = 0x40;
  9858. int numExtraValues = 0;
  9859. while (bit != 0 && (c & bit) != 0)
  9860. {
  9861. bit >>= 1;
  9862. mask >>= 1;
  9863. ++numExtraValues;
  9864. }
  9865. int n = (c & mask);
  9866. while (--numExtraValues >= 0 && i < bufferSizeBytes)
  9867. {
  9868. const uint8 c = buffer[i];
  9869. if ((c & 0xc0) != 0x80)
  9870. break;
  9871. n <<= 6;
  9872. n |= (c & 0x3f);
  9873. ++i;
  9874. }
  9875. *dest++ = (tchar) n;
  9876. }
  9877. else
  9878. {
  9879. *dest++ = (tchar) c;
  9880. }
  9881. }
  9882. *dest = 0;
  9883. return result;
  9884. }
  9885. END_JUCE_NAMESPACE
  9886. /********* End of inlined file: juce_String.cpp *********/
  9887. /********* Start of inlined file: juce_StringArray.cpp *********/
  9888. BEGIN_JUCE_NAMESPACE
  9889. StringArray::StringArray() throw()
  9890. {
  9891. }
  9892. StringArray::StringArray (const StringArray& other) throw()
  9893. {
  9894. addArray (other);
  9895. }
  9896. StringArray::StringArray (const juce_wchar** const strings,
  9897. const int numberOfStrings) throw()
  9898. {
  9899. for (int i = 0; i < numberOfStrings; ++i)
  9900. add (strings [i]);
  9901. }
  9902. StringArray::StringArray (const char** const strings,
  9903. const int numberOfStrings) throw()
  9904. {
  9905. for (int i = 0; i < numberOfStrings; ++i)
  9906. add (strings [i]);
  9907. }
  9908. StringArray::StringArray (const juce_wchar** const strings) throw()
  9909. {
  9910. int i = 0;
  9911. while (strings[i] != 0)
  9912. add (strings [i++]);
  9913. }
  9914. StringArray::StringArray (const char** const strings) throw()
  9915. {
  9916. int i = 0;
  9917. while (strings[i] != 0)
  9918. add (strings [i++]);
  9919. }
  9920. const StringArray& StringArray::operator= (const StringArray& other) throw()
  9921. {
  9922. if (this != &other)
  9923. {
  9924. clear();
  9925. addArray (other);
  9926. }
  9927. return *this;
  9928. }
  9929. StringArray::~StringArray() throw()
  9930. {
  9931. clear();
  9932. }
  9933. bool StringArray::operator== (const StringArray& other) const throw()
  9934. {
  9935. if (other.size() != size())
  9936. return false;
  9937. for (int i = size(); --i >= 0;)
  9938. {
  9939. if (*(String*) other.strings.getUnchecked(i)
  9940. != *(String*) strings.getUnchecked(i))
  9941. {
  9942. return false;
  9943. }
  9944. }
  9945. return true;
  9946. }
  9947. bool StringArray::operator!= (const StringArray& other) const throw()
  9948. {
  9949. return ! operator== (other);
  9950. }
  9951. void StringArray::clear() throw()
  9952. {
  9953. for (int i = size(); --i >= 0;)
  9954. {
  9955. String* const s = (String*) strings.getUnchecked(i);
  9956. delete s;
  9957. }
  9958. strings.clear();
  9959. }
  9960. const String& StringArray::operator[] (const int index) const throw()
  9961. {
  9962. if (((unsigned int) index) < (unsigned int) strings.size())
  9963. return *(const String*) (strings.getUnchecked (index));
  9964. return String::empty;
  9965. }
  9966. void StringArray::add (const String& newString) throw()
  9967. {
  9968. strings.add (new String (newString));
  9969. }
  9970. void StringArray::insert (const int index,
  9971. const String& newString) throw()
  9972. {
  9973. strings.insert (index, new String (newString));
  9974. }
  9975. void StringArray::addIfNotAlreadyThere (const String& newString,
  9976. const bool ignoreCase) throw()
  9977. {
  9978. if (! contains (newString, ignoreCase))
  9979. add (newString);
  9980. }
  9981. void StringArray::addArray (const StringArray& otherArray,
  9982. int startIndex,
  9983. int numElementsToAdd) throw()
  9984. {
  9985. if (startIndex < 0)
  9986. {
  9987. jassertfalse
  9988. startIndex = 0;
  9989. }
  9990. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  9991. numElementsToAdd = otherArray.size() - startIndex;
  9992. while (--numElementsToAdd >= 0)
  9993. strings.add (new String (*(const String*) otherArray.strings.getUnchecked (startIndex++)));
  9994. }
  9995. void StringArray::set (const int index,
  9996. const String& newString) throw()
  9997. {
  9998. String* const s = (String*) strings [index];
  9999. if (s != 0)
  10000. {
  10001. *s = newString;
  10002. }
  10003. else if (index >= 0)
  10004. {
  10005. add (newString);
  10006. }
  10007. }
  10008. bool StringArray::contains (const String& stringToLookFor,
  10009. const bool ignoreCase) const throw()
  10010. {
  10011. if (ignoreCase)
  10012. {
  10013. for (int i = size(); --i >= 0;)
  10014. if (stringToLookFor.equalsIgnoreCase (*(const String*)(strings.getUnchecked(i))))
  10015. return true;
  10016. }
  10017. else
  10018. {
  10019. for (int i = size(); --i >= 0;)
  10020. if (stringToLookFor == *(const String*)(strings.getUnchecked(i)))
  10021. return true;
  10022. }
  10023. return false;
  10024. }
  10025. int StringArray::indexOf (const String& stringToLookFor,
  10026. const bool ignoreCase,
  10027. int i) const throw()
  10028. {
  10029. if (i < 0)
  10030. i = 0;
  10031. const int numElements = size();
  10032. if (ignoreCase)
  10033. {
  10034. while (i < numElements)
  10035. {
  10036. if (stringToLookFor.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  10037. return i;
  10038. ++i;
  10039. }
  10040. }
  10041. else
  10042. {
  10043. while (i < numElements)
  10044. {
  10045. if (stringToLookFor == *(const String*) strings.getUnchecked (i))
  10046. return i;
  10047. ++i;
  10048. }
  10049. }
  10050. return -1;
  10051. }
  10052. void StringArray::remove (const int index) throw()
  10053. {
  10054. String* const s = (String*) strings [index];
  10055. if (s != 0)
  10056. {
  10057. strings.remove (index);
  10058. delete s;
  10059. }
  10060. }
  10061. void StringArray::removeString (const String& stringToRemove,
  10062. const bool ignoreCase) throw()
  10063. {
  10064. if (ignoreCase)
  10065. {
  10066. for (int i = size(); --i >= 0;)
  10067. if (stringToRemove.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  10068. remove (i);
  10069. }
  10070. else
  10071. {
  10072. for (int i = size(); --i >= 0;)
  10073. if (stringToRemove == *(const String*) strings.getUnchecked (i))
  10074. remove (i);
  10075. }
  10076. }
  10077. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings) throw()
  10078. {
  10079. if (removeWhitespaceStrings)
  10080. {
  10081. for (int i = size(); --i >= 0;)
  10082. if (! ((const String*) strings.getUnchecked(i))->containsNonWhitespaceChars())
  10083. remove (i);
  10084. }
  10085. else
  10086. {
  10087. for (int i = size(); --i >= 0;)
  10088. if (((const String*) strings.getUnchecked(i))->isEmpty())
  10089. remove (i);
  10090. }
  10091. }
  10092. void StringArray::trim() throw()
  10093. {
  10094. for (int i = size(); --i >= 0;)
  10095. {
  10096. String& s = *(String*) strings.getUnchecked(i);
  10097. s = s.trim();
  10098. }
  10099. }
  10100. class InternalStringArrayComparator
  10101. {
  10102. public:
  10103. static int compareElements (void* const first, void* const second) throw()
  10104. {
  10105. return ((const String*) first)->compare (*(const String*) second);
  10106. }
  10107. };
  10108. class InsensitiveInternalStringArrayComparator
  10109. {
  10110. public:
  10111. static int compareElements (void* const first, void* const second) throw()
  10112. {
  10113. return ((const String*) first)->compareIgnoreCase (*(const String*) second);
  10114. }
  10115. };
  10116. void StringArray::sort (const bool ignoreCase) throw()
  10117. {
  10118. if (ignoreCase)
  10119. {
  10120. InsensitiveInternalStringArrayComparator comp;
  10121. strings.sort (comp);
  10122. }
  10123. else
  10124. {
  10125. InternalStringArrayComparator comp;
  10126. strings.sort (comp);
  10127. }
  10128. }
  10129. void StringArray::move (const int currentIndex, int newIndex) throw()
  10130. {
  10131. strings.move (currentIndex, newIndex);
  10132. }
  10133. const String StringArray::joinIntoString (const String& separator,
  10134. int start,
  10135. int numberToJoin) const throw()
  10136. {
  10137. const int last = (numberToJoin < 0) ? size()
  10138. : jmin (size(), start + numberToJoin);
  10139. if (start < 0)
  10140. start = 0;
  10141. if (start >= last)
  10142. return String::empty;
  10143. if (start == last - 1)
  10144. return *(const String*) strings.getUnchecked (start);
  10145. const int separatorLen = separator.length();
  10146. int charsNeeded = separatorLen * (last - start - 1);
  10147. for (int i = start; i < last; ++i)
  10148. charsNeeded += ((const String*) strings.getUnchecked(i))->length();
  10149. String result;
  10150. result.preallocateStorage (charsNeeded);
  10151. tchar* dest = (tchar*) (const tchar*) result;
  10152. while (start < last)
  10153. {
  10154. const String& s = *(const String*) strings.getUnchecked (start);
  10155. const int len = s.length();
  10156. if (len > 0)
  10157. {
  10158. s.copyToBuffer (dest, len);
  10159. dest += len;
  10160. }
  10161. if (++start < last && separatorLen > 0)
  10162. {
  10163. separator.copyToBuffer (dest, separatorLen);
  10164. dest += separatorLen;
  10165. }
  10166. }
  10167. *dest = 0;
  10168. return result;
  10169. }
  10170. int StringArray::addTokens (const tchar* const text,
  10171. const bool preserveQuotedStrings) throw()
  10172. {
  10173. return addTokens (text,
  10174. T(" \n\r\t"),
  10175. preserveQuotedStrings ? T("\"") : 0);
  10176. }
  10177. int StringArray::addTokens (const tchar* const text,
  10178. const tchar* breakCharacters,
  10179. const tchar* quoteCharacters) throw()
  10180. {
  10181. int num = 0;
  10182. if (text != 0 && *text != 0)
  10183. {
  10184. if (breakCharacters == 0)
  10185. breakCharacters = T("");
  10186. if (quoteCharacters == 0)
  10187. quoteCharacters = T("");
  10188. bool insideQuotes = false;
  10189. tchar currentQuoteChar = 0;
  10190. int i = 0;
  10191. int tokenStart = 0;
  10192. for (;;)
  10193. {
  10194. const tchar c = text[i];
  10195. bool isBreak = (c == 0);
  10196. if (! (insideQuotes || isBreak))
  10197. {
  10198. const tchar* b = breakCharacters;
  10199. while (*b != 0)
  10200. {
  10201. if (*b++ == c)
  10202. {
  10203. isBreak = true;
  10204. break;
  10205. }
  10206. }
  10207. }
  10208. if (! isBreak)
  10209. {
  10210. bool isQuote = false;
  10211. const tchar* q = quoteCharacters;
  10212. while (*q != 0)
  10213. {
  10214. if (*q++ == c)
  10215. {
  10216. isQuote = true;
  10217. break;
  10218. }
  10219. }
  10220. if (isQuote)
  10221. {
  10222. if (insideQuotes)
  10223. {
  10224. // only break out of quotes-mode if we find a matching quote to the
  10225. // one that we opened with..
  10226. if (currentQuoteChar == c)
  10227. insideQuotes = false;
  10228. }
  10229. else
  10230. {
  10231. insideQuotes = true;
  10232. currentQuoteChar = c;
  10233. }
  10234. }
  10235. }
  10236. else
  10237. {
  10238. add (String (text + tokenStart, i - tokenStart));
  10239. ++num;
  10240. tokenStart = i + 1;
  10241. }
  10242. if (c == 0)
  10243. break;
  10244. ++i;
  10245. }
  10246. }
  10247. return num;
  10248. }
  10249. int StringArray::addLines (const tchar* text) throw()
  10250. {
  10251. int numLines = 0;
  10252. if (text != 0)
  10253. {
  10254. while (*text != 0)
  10255. {
  10256. const tchar* const startOfLine = text;
  10257. while (*text != 0)
  10258. {
  10259. if (*text == T('\r'))
  10260. {
  10261. ++text;
  10262. if (*text == T('\n'))
  10263. ++text;
  10264. break;
  10265. }
  10266. if (*text == T('\n'))
  10267. {
  10268. ++text;
  10269. break;
  10270. }
  10271. ++text;
  10272. }
  10273. const tchar* endOfLine = text;
  10274. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  10275. --endOfLine;
  10276. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  10277. --endOfLine;
  10278. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10279. ++numLines;
  10280. }
  10281. }
  10282. return numLines;
  10283. }
  10284. void StringArray::removeDuplicates (const bool ignoreCase) throw()
  10285. {
  10286. for (int i = 0; i < size() - 1; ++i)
  10287. {
  10288. const String& s = *(String*) strings.getUnchecked(i);
  10289. int nextIndex = i + 1;
  10290. for (;;)
  10291. {
  10292. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10293. if (nextIndex < 0)
  10294. break;
  10295. remove (nextIndex);
  10296. }
  10297. }
  10298. }
  10299. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10300. const bool appendNumberToFirstInstance,
  10301. const tchar* const preNumberString,
  10302. const tchar* const postNumberString) throw()
  10303. {
  10304. for (int i = 0; i < size() - 1; ++i)
  10305. {
  10306. String& s = *(String*) strings.getUnchecked(i);
  10307. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10308. if (nextIndex >= 0)
  10309. {
  10310. const String original (s);
  10311. int number = 0;
  10312. if (appendNumberToFirstInstance)
  10313. s = original + preNumberString + String (++number) + postNumberString;
  10314. else
  10315. ++number;
  10316. while (nextIndex >= 0)
  10317. {
  10318. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10319. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10320. }
  10321. }
  10322. }
  10323. }
  10324. void StringArray::minimiseStorageOverheads() throw()
  10325. {
  10326. strings.minimiseStorageOverheads();
  10327. }
  10328. END_JUCE_NAMESPACE
  10329. /********* End of inlined file: juce_StringArray.cpp *********/
  10330. /********* Start of inlined file: juce_StringPairArray.cpp *********/
  10331. BEGIN_JUCE_NAMESPACE
  10332. StringPairArray::StringPairArray (const bool ignoreCase_) throw()
  10333. : ignoreCase (ignoreCase_)
  10334. {
  10335. }
  10336. StringPairArray::StringPairArray (const StringPairArray& other) throw()
  10337. : keys (other.keys),
  10338. values (other.values),
  10339. ignoreCase (other.ignoreCase)
  10340. {
  10341. }
  10342. StringPairArray::~StringPairArray() throw()
  10343. {
  10344. }
  10345. const StringPairArray& StringPairArray::operator= (const StringPairArray& other) throw()
  10346. {
  10347. keys = other.keys;
  10348. values = other.values;
  10349. return *this;
  10350. }
  10351. bool StringPairArray::operator== (const StringPairArray& other) const throw()
  10352. {
  10353. for (int i = keys.size(); --i >= 0;)
  10354. if (other [keys[i]] != values[i])
  10355. return false;
  10356. return true;
  10357. }
  10358. bool StringPairArray::operator!= (const StringPairArray& other) const throw()
  10359. {
  10360. return ! operator== (other);
  10361. }
  10362. const String& StringPairArray::operator[] (const String& key) const throw()
  10363. {
  10364. return values [keys.indexOf (key, ignoreCase)];
  10365. }
  10366. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10367. {
  10368. const int i = keys.indexOf (key, ignoreCase);
  10369. if (i >= 0)
  10370. return values[i];
  10371. return defaultReturnValue;
  10372. }
  10373. void StringPairArray::set (const String& key,
  10374. const String& value) throw()
  10375. {
  10376. const int i = keys.indexOf (key, ignoreCase);
  10377. if (i >= 0)
  10378. {
  10379. values.set (i, value);
  10380. }
  10381. else
  10382. {
  10383. keys.add (key);
  10384. values.add (value);
  10385. }
  10386. }
  10387. void StringPairArray::addArray (const StringPairArray& other)
  10388. {
  10389. for (int i = 0; i < other.size(); ++i)
  10390. set (other.keys[i], other.values[i]);
  10391. }
  10392. void StringPairArray::clear() throw()
  10393. {
  10394. keys.clear();
  10395. values.clear();
  10396. }
  10397. void StringPairArray::remove (const String& key) throw()
  10398. {
  10399. remove (keys.indexOf (key, ignoreCase));
  10400. }
  10401. void StringPairArray::remove (const int index) throw()
  10402. {
  10403. keys.remove (index);
  10404. values.remove (index);
  10405. }
  10406. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase) throw()
  10407. {
  10408. ignoreCase = shouldIgnoreCase;
  10409. }
  10410. const String StringPairArray::getDescription() const
  10411. {
  10412. String s;
  10413. for (int i = 0; i < keys.size(); ++i)
  10414. {
  10415. s << keys[i] << T(" = ") << values[i];
  10416. if (i < keys.size())
  10417. s << T(", ");
  10418. }
  10419. return s;
  10420. }
  10421. void StringPairArray::minimiseStorageOverheads() throw()
  10422. {
  10423. keys.minimiseStorageOverheads();
  10424. values.minimiseStorageOverheads();
  10425. }
  10426. END_JUCE_NAMESPACE
  10427. /********* End of inlined file: juce_StringPairArray.cpp *********/
  10428. /********* Start of inlined file: juce_XmlDocument.cpp *********/
  10429. BEGIN_JUCE_NAMESPACE
  10430. static bool isXmlIdentifierChar_Slow (const tchar c) throw()
  10431. {
  10432. return CharacterFunctions::isLetterOrDigit (c)
  10433. || c == T('_')
  10434. || c == T('-')
  10435. || c == T(':')
  10436. || c == T('.');
  10437. }
  10438. #define isXmlIdentifierChar(c) \
  10439. ((c > 0 && c <= 127) ? identifierLookupTable [(int) c] : isXmlIdentifierChar_Slow (c))
  10440. XmlDocument::XmlDocument (const String& documentText) throw()
  10441. : originalText (documentText),
  10442. ignoreEmptyTextElements (true),
  10443. inputSource (0)
  10444. {
  10445. }
  10446. XmlDocument::XmlDocument (const File& file)
  10447. {
  10448. inputSource = new FileInputSource (file);
  10449. }
  10450. XmlDocument::~XmlDocument() throw()
  10451. {
  10452. delete inputSource;
  10453. }
  10454. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10455. {
  10456. if (inputSource != newSource)
  10457. {
  10458. delete inputSource;
  10459. inputSource = newSource;
  10460. }
  10461. }
  10462. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10463. {
  10464. ignoreEmptyTextElements = shouldBeIgnored;
  10465. }
  10466. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10467. {
  10468. String textToParse (originalText);
  10469. if (textToParse.isEmpty() && inputSource != 0)
  10470. {
  10471. InputStream* const in = inputSource->createInputStream();
  10472. if (in != 0)
  10473. {
  10474. MemoryBlock data;
  10475. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  10476. delete in;
  10477. if (data.getSize() >= 2
  10478. && ((data[0] == (char)-2 && data[1] == (char)-1)
  10479. || (data[0] == (char)-1 && data[1] == (char)-2)))
  10480. {
  10481. textToParse = String::createStringFromData ((const char*) data.getData(), data.getSize());
  10482. }
  10483. else
  10484. {
  10485. textToParse = String::fromUTF8 ((const uint8*) data.getData(), data.getSize());
  10486. }
  10487. if (! onlyReadOuterDocumentElement)
  10488. originalText = textToParse;
  10489. }
  10490. }
  10491. input = textToParse;
  10492. lastError = String::empty;
  10493. errorOccurred = false;
  10494. outOfData = false;
  10495. needToLoadDTD = true;
  10496. for (int i = 0; i < 128; ++i)
  10497. identifierLookupTable[i] = isXmlIdentifierChar_Slow ((tchar) i);
  10498. if (textToParse.isEmpty())
  10499. {
  10500. lastError = "not enough input";
  10501. }
  10502. else
  10503. {
  10504. skipHeader();
  10505. if (input != 0)
  10506. {
  10507. XmlElement* const result = readNextElement (! onlyReadOuterDocumentElement);
  10508. if (errorOccurred)
  10509. delete result;
  10510. else
  10511. return result;
  10512. }
  10513. else
  10514. {
  10515. lastError = "incorrect xml header";
  10516. }
  10517. }
  10518. return 0;
  10519. }
  10520. const String& XmlDocument::getLastParseError() const throw()
  10521. {
  10522. return lastError;
  10523. }
  10524. void XmlDocument::setLastError (const String& desc, const bool carryOn) throw()
  10525. {
  10526. lastError = desc;
  10527. errorOccurred = ! carryOn;
  10528. }
  10529. const String XmlDocument::getFileContents (const String& filename) const
  10530. {
  10531. String result;
  10532. if (inputSource != 0)
  10533. {
  10534. InputStream* const in = inputSource->createInputStreamFor (filename.trim().unquoted());
  10535. if (in != 0)
  10536. {
  10537. result = in->readEntireStreamAsString();
  10538. delete in;
  10539. }
  10540. }
  10541. return result;
  10542. }
  10543. tchar XmlDocument::readNextChar() throw()
  10544. {
  10545. if (*input != 0)
  10546. {
  10547. return *input++;
  10548. }
  10549. else
  10550. {
  10551. outOfData = true;
  10552. return 0;
  10553. }
  10554. }
  10555. int XmlDocument::findNextTokenLength() throw()
  10556. {
  10557. int len = 0;
  10558. tchar c = *input;
  10559. while (isXmlIdentifierChar (c))
  10560. c = input [++len];
  10561. return len;
  10562. }
  10563. void XmlDocument::skipHeader() throw()
  10564. {
  10565. const tchar* const found = CharacterFunctions::find (input, T("<?xml"));
  10566. if (found != 0)
  10567. {
  10568. input = found;
  10569. input = CharacterFunctions::find (input, T("?>"));
  10570. if (input == 0)
  10571. return;
  10572. input += 2;
  10573. }
  10574. skipNextWhiteSpace();
  10575. const tchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  10576. if (docType == 0)
  10577. return;
  10578. input = docType + 9;
  10579. int n = 1;
  10580. while (n > 0)
  10581. {
  10582. const tchar c = readNextChar();
  10583. if (outOfData)
  10584. return;
  10585. if (c == T('<'))
  10586. ++n;
  10587. else if (c == T('>'))
  10588. --n;
  10589. }
  10590. docType += 9;
  10591. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10592. }
  10593. void XmlDocument::skipNextWhiteSpace() throw()
  10594. {
  10595. for (;;)
  10596. {
  10597. tchar c = *input;
  10598. while (CharacterFunctions::isWhitespace (c))
  10599. c = *++input;
  10600. if (c == 0)
  10601. {
  10602. outOfData = true;
  10603. break;
  10604. }
  10605. else if (c == T('<'))
  10606. {
  10607. if (input[1] == T('!')
  10608. && input[2] == T('-')
  10609. && input[3] == T('-'))
  10610. {
  10611. const tchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  10612. if (closeComment == 0)
  10613. {
  10614. outOfData = true;
  10615. break;
  10616. }
  10617. input = closeComment + 3;
  10618. continue;
  10619. }
  10620. else if (input[1] == T('?'))
  10621. {
  10622. const tchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  10623. if (closeBracket == 0)
  10624. {
  10625. outOfData = true;
  10626. break;
  10627. }
  10628. input = closeBracket + 2;
  10629. continue;
  10630. }
  10631. }
  10632. break;
  10633. }
  10634. }
  10635. void XmlDocument::readQuotedString (String& result) throw()
  10636. {
  10637. const tchar quote = readNextChar();
  10638. while (! outOfData)
  10639. {
  10640. const tchar character = readNextChar();
  10641. if (character == quote)
  10642. break;
  10643. if (character == T('&'))
  10644. {
  10645. --input;
  10646. readEntity (result);
  10647. }
  10648. else
  10649. {
  10650. --input;
  10651. const tchar* const start = input;
  10652. for (;;)
  10653. {
  10654. const tchar character = *input;
  10655. if (character == quote)
  10656. {
  10657. result.append (start, (int) (input - start));
  10658. ++input;
  10659. return;
  10660. }
  10661. else if (character == T('&'))
  10662. {
  10663. result.append (start, (int) (input - start));
  10664. break;
  10665. }
  10666. else if (character == 0)
  10667. {
  10668. outOfData = true;
  10669. setLastError ("unmatched quotes", false);
  10670. break;
  10671. }
  10672. ++input;
  10673. }
  10674. }
  10675. }
  10676. }
  10677. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements) throw()
  10678. {
  10679. XmlElement* node = 0;
  10680. skipNextWhiteSpace();
  10681. if (outOfData)
  10682. return 0;
  10683. input = CharacterFunctions::find (input, T("<"));
  10684. if (input != 0)
  10685. {
  10686. ++input;
  10687. int tagLen = findNextTokenLength();
  10688. if (tagLen == 0)
  10689. {
  10690. // no tag name - but allow for a gap after the '<' before giving an error
  10691. skipNextWhiteSpace();
  10692. tagLen = findNextTokenLength();
  10693. if (tagLen == 0)
  10694. {
  10695. setLastError ("tag name missing", false);
  10696. return node;
  10697. }
  10698. }
  10699. node = new XmlElement (input, tagLen);
  10700. input += tagLen;
  10701. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10702. // look for attributes
  10703. for (;;)
  10704. {
  10705. skipNextWhiteSpace();
  10706. const tchar c = *input;
  10707. // empty tag..
  10708. if (c == T('/') && input[1] == T('>'))
  10709. {
  10710. input += 2;
  10711. break;
  10712. }
  10713. // parse the guts of the element..
  10714. if (c == T('>'))
  10715. {
  10716. ++input;
  10717. skipNextWhiteSpace();
  10718. if (alsoParseSubElements)
  10719. readChildElements (node);
  10720. break;
  10721. }
  10722. // get an attribute..
  10723. if (isXmlIdentifierChar (c))
  10724. {
  10725. const int attNameLen = findNextTokenLength();
  10726. if (attNameLen > 0)
  10727. {
  10728. const tchar* attNameStart = input;
  10729. input += attNameLen;
  10730. skipNextWhiteSpace();
  10731. if (readNextChar() == T('='))
  10732. {
  10733. skipNextWhiteSpace();
  10734. const tchar c = *input;
  10735. if (c == T('"') || c == T('\''))
  10736. {
  10737. XmlElement::XmlAttributeNode* const newAtt
  10738. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10739. String::empty);
  10740. readQuotedString (newAtt->value);
  10741. if (lastAttribute == 0)
  10742. node->attributes = newAtt;
  10743. else
  10744. lastAttribute->next = newAtt;
  10745. lastAttribute = newAtt;
  10746. continue;
  10747. }
  10748. }
  10749. }
  10750. }
  10751. else
  10752. {
  10753. if (! outOfData)
  10754. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10755. }
  10756. break;
  10757. }
  10758. }
  10759. return node;
  10760. }
  10761. void XmlDocument::readChildElements (XmlElement* parent) throw()
  10762. {
  10763. XmlElement* lastChildNode = 0;
  10764. for (;;)
  10765. {
  10766. skipNextWhiteSpace();
  10767. if (outOfData)
  10768. {
  10769. setLastError ("unmatched tags", false);
  10770. break;
  10771. }
  10772. if (*input == T('<'))
  10773. {
  10774. if (input[1] == T('/'))
  10775. {
  10776. // our close tag..
  10777. input = CharacterFunctions::find (input, T(">"));
  10778. ++input;
  10779. break;
  10780. }
  10781. else if (input[1] == T('!')
  10782. && input[2] == T('[')
  10783. && input[3] == T('C')
  10784. && input[4] == T('D')
  10785. && input[5] == T('A')
  10786. && input[6] == T('T')
  10787. && input[7] == T('A')
  10788. && input[8] == T('['))
  10789. {
  10790. input += 9;
  10791. const tchar* const inputStart = input;
  10792. int len = 0;
  10793. for (;;)
  10794. {
  10795. if (*input == 0)
  10796. {
  10797. setLastError ("unterminated CDATA section", false);
  10798. outOfData = true;
  10799. break;
  10800. }
  10801. else if (input[0] == T(']')
  10802. && input[1] == T(']')
  10803. && input[2] == T('>'))
  10804. {
  10805. input += 3;
  10806. break;
  10807. }
  10808. ++input;
  10809. ++len;
  10810. }
  10811. XmlElement* const e = new XmlElement ((int) 0);
  10812. e->setText (String (inputStart, len));
  10813. if (lastChildNode != 0)
  10814. lastChildNode->nextElement = e;
  10815. else
  10816. parent->addChildElement (e);
  10817. lastChildNode = e;
  10818. }
  10819. else
  10820. {
  10821. // this is some other element, so parse and add it..
  10822. XmlElement* const n = readNextElement (true);
  10823. if (n != 0)
  10824. {
  10825. if (lastChildNode == 0)
  10826. parent->addChildElement (n);
  10827. else
  10828. lastChildNode->nextElement = n;
  10829. lastChildNode = n;
  10830. }
  10831. else
  10832. {
  10833. return;
  10834. }
  10835. }
  10836. }
  10837. else
  10838. {
  10839. // read character block..
  10840. XmlElement* const e = new XmlElement ((int)0);
  10841. if (lastChildNode != 0)
  10842. lastChildNode->nextElement = e;
  10843. else
  10844. parent->addChildElement (e);
  10845. lastChildNode = e;
  10846. String textElementContent;
  10847. for (;;)
  10848. {
  10849. const tchar c = *input;
  10850. if (c == T('<'))
  10851. break;
  10852. if (c == 0)
  10853. {
  10854. setLastError ("unmatched tags", false);
  10855. outOfData = true;
  10856. return;
  10857. }
  10858. if (c == T('&'))
  10859. {
  10860. String entity;
  10861. readEntity (entity);
  10862. if (entity.startsWithChar (T('<')) && entity [1] != 0)
  10863. {
  10864. const tchar* const oldInput = input;
  10865. const bool oldOutOfData = outOfData;
  10866. input = (const tchar*) entity;
  10867. outOfData = false;
  10868. for (;;)
  10869. {
  10870. XmlElement* const n = readNextElement (true);
  10871. if (n == 0)
  10872. break;
  10873. if (lastChildNode == 0)
  10874. parent->addChildElement (n);
  10875. else
  10876. lastChildNode->nextElement = n;
  10877. lastChildNode = n;
  10878. }
  10879. input = oldInput;
  10880. outOfData = oldOutOfData;
  10881. }
  10882. else
  10883. {
  10884. textElementContent += entity;
  10885. }
  10886. }
  10887. else
  10888. {
  10889. const tchar* start = input;
  10890. int len = 0;
  10891. for (;;)
  10892. {
  10893. const tchar c = *input;
  10894. if (c == T('<') || c == T('&'))
  10895. {
  10896. break;
  10897. }
  10898. else if (c == 0)
  10899. {
  10900. setLastError ("unmatched tags", false);
  10901. outOfData = true;
  10902. return;
  10903. }
  10904. ++input;
  10905. ++len;
  10906. }
  10907. textElementContent.append (start, len);
  10908. }
  10909. }
  10910. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  10911. : textElementContent.isNotEmpty())
  10912. e->setText (textElementContent);
  10913. }
  10914. }
  10915. }
  10916. void XmlDocument::readEntity (String& result) throw()
  10917. {
  10918. // skip over the ampersand
  10919. ++input;
  10920. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  10921. {
  10922. input += 4;
  10923. result += T("&");
  10924. }
  10925. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  10926. {
  10927. input += 5;
  10928. result += T("\"");
  10929. }
  10930. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  10931. {
  10932. input += 5;
  10933. result += T("\'");
  10934. }
  10935. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  10936. {
  10937. input += 3;
  10938. result += T("<");
  10939. }
  10940. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  10941. {
  10942. input += 3;
  10943. result += T(">");
  10944. }
  10945. else if (*input == T('#'))
  10946. {
  10947. int charCode = 0;
  10948. ++input;
  10949. if (*input == T('x') || *input == T('X'))
  10950. {
  10951. ++input;
  10952. int numChars = 0;
  10953. while (input[0] != T(';'))
  10954. {
  10955. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  10956. if (hexValue < 0 || ++numChars > 8)
  10957. {
  10958. setLastError ("illegal escape sequence", true);
  10959. break;
  10960. }
  10961. charCode = (charCode << 4) | hexValue;
  10962. ++input;
  10963. }
  10964. ++input;
  10965. }
  10966. else if (input[0] >= T('0') && input[0] <= T('9'))
  10967. {
  10968. int numChars = 0;
  10969. while (input[0] != T(';'))
  10970. {
  10971. if (++numChars > 12)
  10972. {
  10973. setLastError ("illegal escape sequence", true);
  10974. break;
  10975. }
  10976. charCode = charCode * 10 + (input[0] - T('0'));
  10977. ++input;
  10978. }
  10979. ++input;
  10980. }
  10981. else
  10982. {
  10983. setLastError ("illegal escape sequence", true);
  10984. result += T("&");
  10985. return;
  10986. }
  10987. result << (tchar) charCode;
  10988. }
  10989. else
  10990. {
  10991. const tchar* const entityNameStart = input;
  10992. const tchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  10993. if (closingSemiColon == 0)
  10994. {
  10995. outOfData = true;
  10996. result += T("&");
  10997. }
  10998. else
  10999. {
  11000. input = closingSemiColon + 1;
  11001. result += expandExternalEntity (String (entityNameStart,
  11002. (int) (closingSemiColon - entityNameStart)));
  11003. }
  11004. }
  11005. }
  11006. const String XmlDocument::expandEntity (const String& ent)
  11007. {
  11008. if (ent.equalsIgnoreCase (T("amp")))
  11009. {
  11010. return T("&");
  11011. }
  11012. else if (ent.equalsIgnoreCase (T("quot")))
  11013. {
  11014. return T("\"");
  11015. }
  11016. else if (ent.equalsIgnoreCase (T("apos")))
  11017. {
  11018. return T("\'");
  11019. }
  11020. else if (ent.equalsIgnoreCase (T("lt")))
  11021. {
  11022. return T("<");
  11023. }
  11024. else if (ent.equalsIgnoreCase (T("gt")))
  11025. {
  11026. return T(">");
  11027. }
  11028. else if (ent[0] == T('#'))
  11029. {
  11030. if (ent[1] == T('x') || ent[1] == T('X'))
  11031. {
  11032. return String::charToString ((tchar) ent.substring (2).getHexValue32());
  11033. }
  11034. else if (ent[1] >= T('0') && ent[1] <= T('9'))
  11035. {
  11036. return String::charToString ((tchar) ent.substring (1).getIntValue());
  11037. }
  11038. setLastError ("illegal escape sequence", false);
  11039. return T("&");
  11040. }
  11041. else
  11042. {
  11043. return expandExternalEntity (ent);
  11044. }
  11045. }
  11046. const String XmlDocument::expandExternalEntity (const String& entity)
  11047. {
  11048. if (needToLoadDTD)
  11049. {
  11050. if (dtdText.isNotEmpty())
  11051. {
  11052. while (dtdText.endsWithChar (T('>')))
  11053. dtdText = dtdText.dropLastCharacters (1);
  11054. tokenisedDTD.addTokens (dtdText, true);
  11055. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase (T("system"))
  11056. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11057. {
  11058. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11059. tokenisedDTD.clear();
  11060. tokenisedDTD.addTokens (getFileContents (fn), true);
  11061. }
  11062. else
  11063. {
  11064. tokenisedDTD.clear();
  11065. const int openBracket = dtdText.indexOfChar (T('['));
  11066. if (openBracket > 0)
  11067. {
  11068. const int closeBracket = dtdText.lastIndexOfChar (T(']'));
  11069. if (closeBracket > openBracket)
  11070. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11071. closeBracket), true);
  11072. }
  11073. }
  11074. for (int i = tokenisedDTD.size(); --i >= 0;)
  11075. {
  11076. if (tokenisedDTD[i].startsWithChar (T('%'))
  11077. && tokenisedDTD[i].endsWithChar (T(';')))
  11078. {
  11079. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11080. StringArray newToks;
  11081. newToks.addTokens (parsed, true);
  11082. tokenisedDTD.remove (i);
  11083. for (int j = newToks.size(); --j >= 0;)
  11084. tokenisedDTD.insert (i, newToks[j]);
  11085. }
  11086. }
  11087. }
  11088. needToLoadDTD = false;
  11089. }
  11090. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11091. {
  11092. if (tokenisedDTD[i] == entity)
  11093. {
  11094. if (tokenisedDTD[i - 1].equalsIgnoreCase (T("<!entity")))
  11095. {
  11096. String ent (tokenisedDTD [i + 1]);
  11097. while (ent.endsWithChar (T('>')))
  11098. ent = ent.dropLastCharacters (1);
  11099. ent = ent.trim().unquoted();
  11100. // check for sub-entities..
  11101. int ampersand = ent.indexOfChar (T('&'));
  11102. while (ampersand >= 0)
  11103. {
  11104. const int semiColon = ent.indexOf (i + 1, T(";"));
  11105. if (semiColon < 0)
  11106. {
  11107. setLastError ("entity without terminating semi-colon", false);
  11108. break;
  11109. }
  11110. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11111. ent = ent.substring (0, ampersand)
  11112. + resolved
  11113. + ent.substring (semiColon + 1);
  11114. ampersand = ent.indexOfChar (semiColon + 1, T('&'));
  11115. }
  11116. return ent;
  11117. }
  11118. }
  11119. }
  11120. setLastError ("unknown entity", true);
  11121. return entity;
  11122. }
  11123. const String XmlDocument::getParameterEntity (const String& entity)
  11124. {
  11125. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11126. {
  11127. if (tokenisedDTD[i] == entity)
  11128. {
  11129. if (tokenisedDTD [i - 1] == T("%")
  11130. && tokenisedDTD [i - 2].equalsIgnoreCase (T("<!entity")))
  11131. {
  11132. String ent (tokenisedDTD [i + 1]);
  11133. while (ent.endsWithChar (T('>')))
  11134. ent = ent.dropLastCharacters (1);
  11135. if (ent.equalsIgnoreCase (T("system")))
  11136. {
  11137. String filename (tokenisedDTD [i + 2]);
  11138. while (filename.endsWithChar (T('>')))
  11139. filename = filename.dropLastCharacters (1);
  11140. return getFileContents (filename);
  11141. }
  11142. else
  11143. {
  11144. return ent.trim().unquoted();
  11145. }
  11146. }
  11147. }
  11148. }
  11149. return entity;
  11150. }
  11151. END_JUCE_NAMESPACE
  11152. /********* End of inlined file: juce_XmlDocument.cpp *********/
  11153. /********* Start of inlined file: juce_XmlElement.cpp *********/
  11154. BEGIN_JUCE_NAMESPACE
  11155. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11156. : name (other.name),
  11157. value (other.value),
  11158. next (0)
  11159. {
  11160. }
  11161. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_,
  11162. const String& value_) throw()
  11163. : name (name_),
  11164. value (value_),
  11165. next (0)
  11166. {
  11167. }
  11168. XmlElement::XmlElement (const String& tagName_) throw()
  11169. : tagName (tagName_),
  11170. firstChildElement (0),
  11171. nextElement (0),
  11172. attributes (0)
  11173. {
  11174. // the tag name mustn't be empty, or it'll look like a text element!
  11175. jassert (tagName_.containsNonWhitespaceChars())
  11176. }
  11177. XmlElement::XmlElement (int /*dummy*/) throw()
  11178. : firstChildElement (0),
  11179. nextElement (0),
  11180. attributes (0)
  11181. {
  11182. }
  11183. XmlElement::XmlElement (const tchar* const tagName_,
  11184. const int nameLen) throw()
  11185. : tagName (tagName_, nameLen),
  11186. firstChildElement (0),
  11187. nextElement (0),
  11188. attributes (0)
  11189. {
  11190. }
  11191. XmlElement::XmlElement (const XmlElement& other) throw()
  11192. : tagName (other.tagName),
  11193. firstChildElement (0),
  11194. nextElement (0),
  11195. attributes (0)
  11196. {
  11197. copyChildrenAndAttributesFrom (other);
  11198. }
  11199. const XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  11200. {
  11201. if (this != &other)
  11202. {
  11203. removeAllAttributes();
  11204. deleteAllChildElements();
  11205. tagName = other.tagName;
  11206. copyChildrenAndAttributesFrom (other);
  11207. }
  11208. return *this;
  11209. }
  11210. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  11211. {
  11212. XmlElement* child = other.firstChildElement;
  11213. XmlElement* lastChild = 0;
  11214. while (child != 0)
  11215. {
  11216. XmlElement* const copiedChild = new XmlElement (*child);
  11217. if (lastChild != 0)
  11218. lastChild->nextElement = copiedChild;
  11219. else
  11220. firstChildElement = copiedChild;
  11221. lastChild = copiedChild;
  11222. child = child->nextElement;
  11223. }
  11224. const XmlAttributeNode* att = other.attributes;
  11225. XmlAttributeNode* lastAtt = 0;
  11226. while (att != 0)
  11227. {
  11228. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11229. if (lastAtt != 0)
  11230. lastAtt->next = newAtt;
  11231. else
  11232. attributes = newAtt;
  11233. lastAtt = newAtt;
  11234. att = att->next;
  11235. }
  11236. }
  11237. XmlElement::~XmlElement() throw()
  11238. {
  11239. XmlElement* child = firstChildElement;
  11240. while (child != 0)
  11241. {
  11242. XmlElement* const nextChild = child->nextElement;
  11243. delete child;
  11244. child = nextChild;
  11245. }
  11246. XmlAttributeNode* att = attributes;
  11247. while (att != 0)
  11248. {
  11249. XmlAttributeNode* const nextAtt = att->next;
  11250. delete att;
  11251. att = nextAtt;
  11252. }
  11253. }
  11254. static bool isLegalXmlChar (const juce_wchar character)
  11255. {
  11256. if ((character >= 'a' && character <= 'z')
  11257. || (character >= 'A' && character <= 'Z')
  11258. || (character >= '0' && character <= '9'))
  11259. return true;
  11260. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  11261. do
  11262. {
  11263. if (((juce_wchar) (uint8) *t) == character)
  11264. return true;
  11265. }
  11266. while (*++t != 0);
  11267. return false;
  11268. }
  11269. static void escapeIllegalXmlChars (OutputStream& outputStream,
  11270. const String& text,
  11271. const bool changeNewLines) throw()
  11272. {
  11273. const juce_wchar* t = (const juce_wchar*) text;
  11274. for (;;)
  11275. {
  11276. const juce_wchar character = *t++;
  11277. if (character == 0)
  11278. {
  11279. break;
  11280. }
  11281. else if (isLegalXmlChar (character))
  11282. {
  11283. outputStream.writeByte ((char) character);
  11284. }
  11285. else
  11286. {
  11287. switch (character)
  11288. {
  11289. case '&':
  11290. outputStream.write ("&amp;", 5);
  11291. break;
  11292. case '"':
  11293. outputStream.write ("&quot;", 6);
  11294. break;
  11295. case '>':
  11296. outputStream.write ("&gt;", 4);
  11297. break;
  11298. case '<':
  11299. outputStream.write ("&lt;", 4);
  11300. break;
  11301. case '\n':
  11302. if (changeNewLines)
  11303. outputStream.write ("&#10;", 5);
  11304. else
  11305. outputStream.writeByte ((char) character);
  11306. break;
  11307. case '\r':
  11308. if (changeNewLines)
  11309. outputStream.write ("&#13;", 5);
  11310. else
  11311. outputStream.writeByte ((char) character);
  11312. break;
  11313. default:
  11314. {
  11315. String encoded (T("&#"));
  11316. encoded << String ((int) (unsigned int) character).trim()
  11317. << T(';');
  11318. outputStream.write ((const char*) encoded, encoded.length());
  11319. }
  11320. }
  11321. }
  11322. }
  11323. }
  11324. static void writeSpaces (OutputStream& out, int numSpaces) throw()
  11325. {
  11326. if (numSpaces > 0)
  11327. {
  11328. const char* const blanks = " ";
  11329. const int blankSize = (int) sizeof (blanks) - 1;
  11330. while (numSpaces > blankSize)
  11331. {
  11332. out.write (blanks, blankSize);
  11333. numSpaces -= blankSize;
  11334. }
  11335. out.write (blanks, numSpaces);
  11336. }
  11337. }
  11338. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11339. const int indentationLevel,
  11340. const int lineWrapLength) const throw()
  11341. {
  11342. writeSpaces (outputStream, indentationLevel);
  11343. if (! isTextElement())
  11344. {
  11345. outputStream.writeByte ('<');
  11346. const int nameLen = tagName.length();
  11347. outputStream.write ((const char*) tagName, nameLen);
  11348. const int attIndent = indentationLevel + nameLen + 1;
  11349. int lineLen = 0;
  11350. const XmlAttributeNode* att = attributes;
  11351. while (att != 0)
  11352. {
  11353. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11354. {
  11355. outputStream.write ("\r\n", 2);
  11356. writeSpaces (outputStream, attIndent);
  11357. lineLen = 0;
  11358. }
  11359. const int attNameLen = att->name.length();
  11360. outputStream.writeByte (' ');
  11361. outputStream.write ((const char*) (att->name), attNameLen);
  11362. outputStream.write ("=\"", 2);
  11363. escapeIllegalXmlChars (outputStream, att->value, true);
  11364. outputStream.writeByte ('"');
  11365. lineLen += 4 + attNameLen + att->value.length();
  11366. att = att->next;
  11367. }
  11368. if (firstChildElement != 0)
  11369. {
  11370. XmlElement* child = firstChildElement;
  11371. if (child->nextElement == 0 && child->isTextElement())
  11372. {
  11373. outputStream.writeByte ('>');
  11374. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11375. }
  11376. else
  11377. {
  11378. if (indentationLevel >= 0)
  11379. outputStream.write (">\r\n", 3);
  11380. else
  11381. outputStream.writeByte ('>');
  11382. bool lastWasTextNode = false;
  11383. while (child != 0)
  11384. {
  11385. if (child->isTextElement())
  11386. {
  11387. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11388. writeSpaces (outputStream, indentationLevel + 2);
  11389. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11390. lastWasTextNode = true;
  11391. }
  11392. else
  11393. {
  11394. if (indentationLevel >= 0)
  11395. {
  11396. if (lastWasTextNode)
  11397. outputStream.write ("\r\n", 2);
  11398. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11399. }
  11400. else
  11401. {
  11402. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11403. }
  11404. lastWasTextNode = false;
  11405. }
  11406. child = child->nextElement;
  11407. }
  11408. if (indentationLevel >= 0)
  11409. {
  11410. if (lastWasTextNode)
  11411. outputStream.write ("\r\n", 2);
  11412. writeSpaces (outputStream, indentationLevel);
  11413. }
  11414. }
  11415. outputStream.write ("</", 2);
  11416. outputStream.write ((const char*) tagName, nameLen);
  11417. if (indentationLevel >= 0)
  11418. outputStream.write (">\r\n", 3);
  11419. else
  11420. outputStream.writeByte ('>');
  11421. }
  11422. else
  11423. {
  11424. if (indentationLevel >= 0)
  11425. outputStream.write ("/>\r\n", 4);
  11426. else
  11427. outputStream.write ("/>", 2);
  11428. }
  11429. }
  11430. else
  11431. {
  11432. if (indentationLevel >= 0)
  11433. writeSpaces (outputStream, indentationLevel + 2);
  11434. escapeIllegalXmlChars (outputStream, getText(), false);
  11435. }
  11436. }
  11437. const String XmlElement::createDocument (const String& dtd,
  11438. const bool allOnOneLine,
  11439. const bool includeXmlHeader,
  11440. const tchar* const encoding,
  11441. const int lineWrapLength) const throw()
  11442. {
  11443. String doc;
  11444. doc.preallocateStorage (1024);
  11445. if (includeXmlHeader)
  11446. {
  11447. doc << "<?xml version=\"1.0\" encoding=\""
  11448. << encoding;
  11449. if (allOnOneLine)
  11450. doc += "\"?> ";
  11451. else
  11452. doc += "\"?>\n\n";
  11453. }
  11454. if (dtd.isNotEmpty())
  11455. {
  11456. if (allOnOneLine)
  11457. doc << dtd << " ";
  11458. else
  11459. doc << dtd << "\r\n";
  11460. }
  11461. MemoryOutputStream mem (2048, 4096);
  11462. writeElementAsText (mem, allOnOneLine ? -1 : 0, lineWrapLength);
  11463. return doc + String (mem.getData(),
  11464. mem.getDataSize());
  11465. }
  11466. bool XmlElement::writeToFile (const File& f,
  11467. const String& dtd,
  11468. const tchar* const encoding,
  11469. const int lineWrapLength) const throw()
  11470. {
  11471. if (f.hasWriteAccess())
  11472. {
  11473. const File tempFile (f.getNonexistentSibling());
  11474. FileOutputStream* const out = tempFile.createOutputStream();
  11475. if (out != 0)
  11476. {
  11477. *out << "<?xml version=\"1.0\" encoding=\"" << encoding << "\"?>\r\n\r\n"
  11478. << dtd << "\r\n";
  11479. writeElementAsText (*out, 0, lineWrapLength);
  11480. delete out;
  11481. if (tempFile.moveFileTo (f))
  11482. return true;
  11483. tempFile.deleteFile();
  11484. }
  11485. }
  11486. return false;
  11487. }
  11488. bool XmlElement::hasTagName (const tchar* const tagNameWanted) const throw()
  11489. {
  11490. #ifdef JUCE_DEBUG
  11491. // if debugging, check that the case is actually the same, because
  11492. // valid xml is case-sensitive, and although this lets it pass, it's
  11493. // better not to..
  11494. if (tagName.equalsIgnoreCase (tagNameWanted))
  11495. {
  11496. jassert (tagName == tagNameWanted);
  11497. return true;
  11498. }
  11499. else
  11500. {
  11501. return false;
  11502. }
  11503. #else
  11504. return tagName.equalsIgnoreCase (tagNameWanted);
  11505. #endif
  11506. }
  11507. XmlElement* XmlElement::getNextElementWithTagName (const tchar* const requiredTagName) const
  11508. {
  11509. XmlElement* e = nextElement;
  11510. while (e != 0 && ! e->hasTagName (requiredTagName))
  11511. e = e->nextElement;
  11512. return e;
  11513. }
  11514. int XmlElement::getNumAttributes() const throw()
  11515. {
  11516. const XmlAttributeNode* att = attributes;
  11517. int count = 0;
  11518. while (att != 0)
  11519. {
  11520. att = att->next;
  11521. ++count;
  11522. }
  11523. return count;
  11524. }
  11525. const String& XmlElement::getAttributeName (const int index) const throw()
  11526. {
  11527. const XmlAttributeNode* att = attributes;
  11528. int count = 0;
  11529. while (att != 0)
  11530. {
  11531. if (count == index)
  11532. return att->name;
  11533. att = att->next;
  11534. ++count;
  11535. }
  11536. return String::empty;
  11537. }
  11538. const String& XmlElement::getAttributeValue (const int index) const throw()
  11539. {
  11540. const XmlAttributeNode* att = attributes;
  11541. int count = 0;
  11542. while (att != 0)
  11543. {
  11544. if (count == index)
  11545. return att->value;
  11546. att = att->next;
  11547. ++count;
  11548. }
  11549. return String::empty;
  11550. }
  11551. bool XmlElement::hasAttribute (const tchar* const attributeName) const throw()
  11552. {
  11553. const XmlAttributeNode* att = attributes;
  11554. while (att != 0)
  11555. {
  11556. if (att->name.equalsIgnoreCase (attributeName))
  11557. return true;
  11558. att = att->next;
  11559. }
  11560. return false;
  11561. }
  11562. const String XmlElement::getStringAttribute (const tchar* const attributeName,
  11563. const tchar* const defaultReturnValue) const throw()
  11564. {
  11565. const XmlAttributeNode* att = attributes;
  11566. while (att != 0)
  11567. {
  11568. if (att->name.equalsIgnoreCase (attributeName))
  11569. return att->value;
  11570. att = att->next;
  11571. }
  11572. return defaultReturnValue;
  11573. }
  11574. int XmlElement::getIntAttribute (const tchar* const attributeName,
  11575. const int defaultReturnValue) const throw()
  11576. {
  11577. const XmlAttributeNode* att = attributes;
  11578. while (att != 0)
  11579. {
  11580. if (att->name.equalsIgnoreCase (attributeName))
  11581. return att->value.getIntValue();
  11582. att = att->next;
  11583. }
  11584. return defaultReturnValue;
  11585. }
  11586. double XmlElement::getDoubleAttribute (const tchar* const attributeName,
  11587. const double defaultReturnValue) const throw()
  11588. {
  11589. const XmlAttributeNode* att = attributes;
  11590. while (att != 0)
  11591. {
  11592. if (att->name.equalsIgnoreCase (attributeName))
  11593. return att->value.getDoubleValue();
  11594. att = att->next;
  11595. }
  11596. return defaultReturnValue;
  11597. }
  11598. bool XmlElement::getBoolAttribute (const tchar* const attributeName,
  11599. const bool defaultReturnValue) const throw()
  11600. {
  11601. const XmlAttributeNode* att = attributes;
  11602. while (att != 0)
  11603. {
  11604. if (att->name.equalsIgnoreCase (attributeName))
  11605. {
  11606. tchar firstChar = att->value[0];
  11607. if (CharacterFunctions::isWhitespace (firstChar))
  11608. firstChar = att->value.trimStart() [0];
  11609. return firstChar == T('1')
  11610. || firstChar == T('t')
  11611. || firstChar == T('y')
  11612. || firstChar == T('T')
  11613. || firstChar == T('Y');
  11614. }
  11615. att = att->next;
  11616. }
  11617. return defaultReturnValue;
  11618. }
  11619. bool XmlElement::compareAttribute (const tchar* const attributeName,
  11620. const tchar* const stringToCompareAgainst,
  11621. const bool ignoreCase) const throw()
  11622. {
  11623. const XmlAttributeNode* att = attributes;
  11624. while (att != 0)
  11625. {
  11626. if (att->name.equalsIgnoreCase (attributeName))
  11627. {
  11628. if (ignoreCase)
  11629. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11630. else
  11631. return att->value == stringToCompareAgainst;
  11632. }
  11633. att = att->next;
  11634. }
  11635. return false;
  11636. }
  11637. void XmlElement::setAttribute (const tchar* const attributeName,
  11638. const String& value) throw()
  11639. {
  11640. #ifdef JUCE_DEBUG
  11641. // check the identifier being passed in is legal..
  11642. const tchar* t = attributeName;
  11643. while (*t != 0)
  11644. {
  11645. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11646. || *t == T('_')
  11647. || *t == T('-')
  11648. || *t == T(':'));
  11649. ++t;
  11650. }
  11651. #endif
  11652. if (attributes == 0)
  11653. {
  11654. attributes = new XmlAttributeNode (attributeName, value);
  11655. }
  11656. else
  11657. {
  11658. XmlAttributeNode* att = attributes;
  11659. for (;;)
  11660. {
  11661. if (att->name.equalsIgnoreCase (attributeName))
  11662. {
  11663. att->value = value;
  11664. break;
  11665. }
  11666. else if (att->next == 0)
  11667. {
  11668. att->next = new XmlAttributeNode (attributeName, value);
  11669. break;
  11670. }
  11671. att = att->next;
  11672. }
  11673. }
  11674. }
  11675. void XmlElement::setAttribute (const tchar* const attributeName,
  11676. const tchar* const text) throw()
  11677. {
  11678. setAttribute (attributeName, String (text));
  11679. }
  11680. void XmlElement::setAttribute (const tchar* const attributeName,
  11681. const int number) throw()
  11682. {
  11683. setAttribute (attributeName, String (number));
  11684. }
  11685. void XmlElement::setAttribute (const tchar* const attributeName,
  11686. const double number) throw()
  11687. {
  11688. tchar buffer [40];
  11689. CharacterFunctions::printf (buffer, numElementsInArray (buffer), T("%.9g"), number);
  11690. setAttribute (attributeName, buffer);
  11691. }
  11692. void XmlElement::removeAttribute (const tchar* const attributeName) throw()
  11693. {
  11694. XmlAttributeNode* att = attributes;
  11695. XmlAttributeNode* lastAtt = 0;
  11696. while (att != 0)
  11697. {
  11698. if (att->name.equalsIgnoreCase (attributeName))
  11699. {
  11700. if (lastAtt == 0)
  11701. attributes = att->next;
  11702. else
  11703. lastAtt->next = att->next;
  11704. delete att;
  11705. break;
  11706. }
  11707. lastAtt = att;
  11708. att = att->next;
  11709. }
  11710. }
  11711. void XmlElement::removeAllAttributes() throw()
  11712. {
  11713. while (attributes != 0)
  11714. {
  11715. XmlAttributeNode* const nextAtt = attributes->next;
  11716. delete attributes;
  11717. attributes = nextAtt;
  11718. }
  11719. }
  11720. int XmlElement::getNumChildElements() const throw()
  11721. {
  11722. int count = 0;
  11723. const XmlElement* child = firstChildElement;
  11724. while (child != 0)
  11725. {
  11726. ++count;
  11727. child = child->nextElement;
  11728. }
  11729. return count;
  11730. }
  11731. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11732. {
  11733. int count = 0;
  11734. XmlElement* child = firstChildElement;
  11735. while (child != 0 && count < index)
  11736. {
  11737. child = child->nextElement;
  11738. ++count;
  11739. }
  11740. return child;
  11741. }
  11742. XmlElement* XmlElement::getChildByName (const tchar* const childName) const throw()
  11743. {
  11744. XmlElement* child = firstChildElement;
  11745. while (child != 0)
  11746. {
  11747. if (child->hasTagName (childName))
  11748. break;
  11749. child = child->nextElement;
  11750. }
  11751. return child;
  11752. }
  11753. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11754. {
  11755. if (newNode != 0)
  11756. {
  11757. if (firstChildElement == 0)
  11758. {
  11759. firstChildElement = newNode;
  11760. }
  11761. else
  11762. {
  11763. XmlElement* child = firstChildElement;
  11764. while (child->nextElement != 0)
  11765. child = child->nextElement;
  11766. child->nextElement = newNode;
  11767. // if this is non-zero, then something's probably
  11768. // gone wrong..
  11769. jassert (newNode->nextElement == 0);
  11770. }
  11771. }
  11772. }
  11773. void XmlElement::insertChildElement (XmlElement* const newNode,
  11774. int indexToInsertAt) throw()
  11775. {
  11776. if (newNode != 0)
  11777. {
  11778. removeChildElement (newNode, false);
  11779. if (indexToInsertAt == 0)
  11780. {
  11781. newNode->nextElement = firstChildElement;
  11782. firstChildElement = newNode;
  11783. }
  11784. else
  11785. {
  11786. if (firstChildElement == 0)
  11787. {
  11788. firstChildElement = newNode;
  11789. }
  11790. else
  11791. {
  11792. if (indexToInsertAt < 0)
  11793. indexToInsertAt = INT_MAX;
  11794. XmlElement* child = firstChildElement;
  11795. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11796. child = child->nextElement;
  11797. newNode->nextElement = child->nextElement;
  11798. child->nextElement = newNode;
  11799. }
  11800. }
  11801. }
  11802. }
  11803. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11804. XmlElement* const newNode) throw()
  11805. {
  11806. if (newNode != 0)
  11807. {
  11808. XmlElement* child = firstChildElement;
  11809. XmlElement* previousNode = 0;
  11810. while (child != 0)
  11811. {
  11812. if (child == currentChildElement)
  11813. {
  11814. if (child != newNode)
  11815. {
  11816. if (previousNode == 0)
  11817. firstChildElement = newNode;
  11818. else
  11819. previousNode->nextElement = newNode;
  11820. newNode->nextElement = child->nextElement;
  11821. delete child;
  11822. }
  11823. return true;
  11824. }
  11825. previousNode = child;
  11826. child = child->nextElement;
  11827. }
  11828. }
  11829. return false;
  11830. }
  11831. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  11832. const bool shouldDeleteTheChild) throw()
  11833. {
  11834. if (childToRemove != 0)
  11835. {
  11836. if (firstChildElement == childToRemove)
  11837. {
  11838. firstChildElement = childToRemove->nextElement;
  11839. childToRemove->nextElement = 0;
  11840. }
  11841. else
  11842. {
  11843. XmlElement* child = firstChildElement;
  11844. XmlElement* last = 0;
  11845. while (child != 0)
  11846. {
  11847. if (child == childToRemove)
  11848. {
  11849. if (last == 0)
  11850. firstChildElement = child->nextElement;
  11851. else
  11852. last->nextElement = child->nextElement;
  11853. childToRemove->nextElement = 0;
  11854. break;
  11855. }
  11856. last = child;
  11857. child = child->nextElement;
  11858. }
  11859. }
  11860. if (shouldDeleteTheChild)
  11861. delete childToRemove;
  11862. }
  11863. }
  11864. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  11865. const bool ignoreOrderOfAttributes) const throw()
  11866. {
  11867. if (this != other)
  11868. {
  11869. if (other == 0 || tagName != other->tagName)
  11870. {
  11871. return false;
  11872. }
  11873. if (ignoreOrderOfAttributes)
  11874. {
  11875. int totalAtts = 0;
  11876. const XmlAttributeNode* att = attributes;
  11877. while (att != 0)
  11878. {
  11879. if (! other->compareAttribute (att->name, att->value))
  11880. return false;
  11881. att = att->next;
  11882. ++totalAtts;
  11883. }
  11884. if (totalAtts != other->getNumAttributes())
  11885. return false;
  11886. }
  11887. else
  11888. {
  11889. const XmlAttributeNode* thisAtt = attributes;
  11890. const XmlAttributeNode* otherAtt = other->attributes;
  11891. for (;;)
  11892. {
  11893. if (thisAtt == 0 || otherAtt == 0)
  11894. {
  11895. if (thisAtt == otherAtt) // both 0, so it's a match
  11896. break;
  11897. return false;
  11898. }
  11899. if (thisAtt->name != otherAtt->name
  11900. || thisAtt->value != otherAtt->value)
  11901. {
  11902. return false;
  11903. }
  11904. thisAtt = thisAtt->next;
  11905. otherAtt = otherAtt->next;
  11906. }
  11907. }
  11908. const XmlElement* thisChild = firstChildElement;
  11909. const XmlElement* otherChild = other->firstChildElement;
  11910. for (;;)
  11911. {
  11912. if (thisChild == 0 || otherChild == 0)
  11913. {
  11914. if (thisChild == otherChild) // both 0, so it's a match
  11915. break;
  11916. return false;
  11917. }
  11918. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  11919. return false;
  11920. thisChild = thisChild->nextElement;
  11921. otherChild = otherChild->nextElement;
  11922. }
  11923. }
  11924. return true;
  11925. }
  11926. void XmlElement::deleteAllChildElements() throw()
  11927. {
  11928. while (firstChildElement != 0)
  11929. {
  11930. XmlElement* const nextChild = firstChildElement->nextElement;
  11931. delete firstChildElement;
  11932. firstChildElement = nextChild;
  11933. }
  11934. }
  11935. void XmlElement::deleteAllChildElementsWithTagName (const tchar* const name) throw()
  11936. {
  11937. XmlElement* child = firstChildElement;
  11938. while (child != 0)
  11939. {
  11940. if (child->hasTagName (name))
  11941. {
  11942. XmlElement* const nextChild = child->nextElement;
  11943. removeChildElement (child, true);
  11944. child = nextChild;
  11945. }
  11946. else
  11947. {
  11948. child = child->nextElement;
  11949. }
  11950. }
  11951. }
  11952. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  11953. {
  11954. const XmlElement* child = firstChildElement;
  11955. while (child != 0)
  11956. {
  11957. if (child == possibleChild)
  11958. return true;
  11959. child = child->nextElement;
  11960. }
  11961. return false;
  11962. }
  11963. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  11964. {
  11965. if (this == elementToLookFor || elementToLookFor == 0)
  11966. return 0;
  11967. XmlElement* child = firstChildElement;
  11968. while (child != 0)
  11969. {
  11970. if (elementToLookFor == child)
  11971. return this;
  11972. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  11973. if (found != 0)
  11974. return found;
  11975. child = child->nextElement;
  11976. }
  11977. return 0;
  11978. }
  11979. XmlElement** XmlElement::getChildElementsAsArray (const int num) const throw()
  11980. {
  11981. XmlElement** const elems = new XmlElement* [num];
  11982. XmlElement* e = firstChildElement;
  11983. int i = 0;
  11984. while (e != 0)
  11985. {
  11986. elems [i++] = e;
  11987. e = e->nextElement;
  11988. }
  11989. return elems;
  11990. }
  11991. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  11992. {
  11993. XmlElement* e = firstChildElement = elems[0];
  11994. for (int i = 1; i < num; ++i)
  11995. {
  11996. e->nextElement = elems[i];
  11997. e = e->nextElement;
  11998. }
  11999. e->nextElement = 0;
  12000. }
  12001. bool XmlElement::isTextElement() const throw()
  12002. {
  12003. return tagName.isEmpty();
  12004. }
  12005. static const tchar* const juce_xmltextContentAttributeName = T("text");
  12006. const String XmlElement::getText() const throw()
  12007. {
  12008. jassert (isTextElement()); // you're trying to get the text from an element that
  12009. // isn't actually a text element.. If this contains text sub-nodes, you
  12010. // can use getAllSubText instead to
  12011. return getStringAttribute (juce_xmltextContentAttributeName);
  12012. }
  12013. void XmlElement::setText (const String& newText) throw()
  12014. {
  12015. if (isTextElement())
  12016. {
  12017. setAttribute (juce_xmltextContentAttributeName, newText);
  12018. }
  12019. else
  12020. {
  12021. jassertfalse // you can only change the text in a text element, not a normal one.
  12022. }
  12023. }
  12024. const String XmlElement::getAllSubText() const throw()
  12025. {
  12026. String result;
  12027. const XmlElement* child = firstChildElement;
  12028. while (child != 0)
  12029. {
  12030. if (child->isTextElement())
  12031. result += child->getText();
  12032. child = child->nextElement;
  12033. }
  12034. return result;
  12035. }
  12036. const String XmlElement::getChildElementAllSubText (const tchar* const childTagName,
  12037. const String& defaultReturnValue) const throw()
  12038. {
  12039. const XmlElement* const child = getChildByName (childTagName);
  12040. if (child != 0)
  12041. return child->getAllSubText();
  12042. return defaultReturnValue;
  12043. }
  12044. XmlElement* XmlElement::createTextElement (const String& text) throw()
  12045. {
  12046. XmlElement* const e = new XmlElement ((int) 0);
  12047. e->setAttribute (juce_xmltextContentAttributeName, text);
  12048. return e;
  12049. }
  12050. void XmlElement::addTextElement (const String& text) throw()
  12051. {
  12052. addChildElement (createTextElement (text));
  12053. }
  12054. void XmlElement::deleteAllTextElements() throw()
  12055. {
  12056. XmlElement* child = firstChildElement;
  12057. while (child != 0)
  12058. {
  12059. XmlElement* const next = child->nextElement;
  12060. if (child->isTextElement())
  12061. removeChildElement (child, true);
  12062. child = next;
  12063. }
  12064. }
  12065. END_JUCE_NAMESPACE
  12066. /********* End of inlined file: juce_XmlElement.cpp *********/
  12067. /********* Start of inlined file: juce_InterProcessLock.cpp *********/
  12068. BEGIN_JUCE_NAMESPACE
  12069. // (implemented in the platform-specific code files)
  12070. END_JUCE_NAMESPACE
  12071. /********* End of inlined file: juce_InterProcessLock.cpp *********/
  12072. /********* Start of inlined file: juce_ReadWriteLock.cpp *********/
  12073. BEGIN_JUCE_NAMESPACE
  12074. ReadWriteLock::ReadWriteLock() throw()
  12075. : numWaitingWriters (0),
  12076. numWriters (0),
  12077. writerThreadId (0)
  12078. {
  12079. }
  12080. ReadWriteLock::~ReadWriteLock() throw()
  12081. {
  12082. jassert (readerThreads.size() == 0);
  12083. jassert (numWriters == 0);
  12084. }
  12085. void ReadWriteLock::enterRead() const throw()
  12086. {
  12087. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12088. const ScopedLock sl (accessLock);
  12089. for (;;)
  12090. {
  12091. jassert (readerThreads.size() % 2 == 0);
  12092. int i;
  12093. for (i = 0; i < readerThreads.size(); i += 2)
  12094. if (readerThreads.getUnchecked(i) == threadId)
  12095. break;
  12096. if (i < readerThreads.size()
  12097. || numWriters + numWaitingWriters == 0
  12098. || (threadId == writerThreadId && numWriters > 0))
  12099. {
  12100. if (i < readerThreads.size())
  12101. {
  12102. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12103. }
  12104. else
  12105. {
  12106. readerThreads.add (threadId);
  12107. readerThreads.add ((Thread::ThreadID) 1);
  12108. }
  12109. return;
  12110. }
  12111. const ScopedUnlock ul (accessLock);
  12112. waitEvent.wait (100);
  12113. }
  12114. }
  12115. void ReadWriteLock::exitRead() const throw()
  12116. {
  12117. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12118. const ScopedLock sl (accessLock);
  12119. for (int i = 0; i < readerThreads.size(); i += 2)
  12120. {
  12121. if (readerThreads.getUnchecked(i) == threadId)
  12122. {
  12123. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12124. if (newCount == 0)
  12125. {
  12126. readerThreads.removeRange (i, 2);
  12127. waitEvent.signal();
  12128. }
  12129. else
  12130. {
  12131. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12132. }
  12133. return;
  12134. }
  12135. }
  12136. jassertfalse // unlocking a lock that wasn't locked..
  12137. }
  12138. void ReadWriteLock::enterWrite() const throw()
  12139. {
  12140. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12141. const ScopedLock sl (accessLock);
  12142. for (;;)
  12143. {
  12144. if (readerThreads.size() + numWriters == 0
  12145. || threadId == writerThreadId
  12146. || (readerThreads.size() == 2
  12147. && readerThreads.getUnchecked(0) == threadId))
  12148. {
  12149. writerThreadId = threadId;
  12150. ++numWriters;
  12151. break;
  12152. }
  12153. ++numWaitingWriters;
  12154. accessLock.exit();
  12155. waitEvent.wait (100);
  12156. accessLock.enter();
  12157. --numWaitingWriters;
  12158. }
  12159. }
  12160. bool ReadWriteLock::tryEnterWrite() const throw()
  12161. {
  12162. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12163. const ScopedLock sl (accessLock);
  12164. if (readerThreads.size() + numWriters == 0
  12165. || threadId == writerThreadId
  12166. || (readerThreads.size() == 2
  12167. && readerThreads.getUnchecked(0) == threadId))
  12168. {
  12169. writerThreadId = threadId;
  12170. ++numWriters;
  12171. return true;
  12172. }
  12173. return false;
  12174. }
  12175. void ReadWriteLock::exitWrite() const throw()
  12176. {
  12177. const ScopedLock sl (accessLock);
  12178. // check this thread actually had the lock..
  12179. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12180. if (--numWriters == 0)
  12181. {
  12182. writerThreadId = 0;
  12183. waitEvent.signal();
  12184. }
  12185. }
  12186. END_JUCE_NAMESPACE
  12187. /********* End of inlined file: juce_ReadWriteLock.cpp *********/
  12188. /********* Start of inlined file: juce_Thread.cpp *********/
  12189. BEGIN_JUCE_NAMESPACE
  12190. // these functions are implemented in the platform-specific code.
  12191. void* juce_createThread (void* userData) throw();
  12192. void juce_killThread (void* handle) throw();
  12193. bool juce_setThreadPriority (void* handle, int priority) throw();
  12194. void juce_setCurrentThreadName (const String& name) throw();
  12195. #if JUCE_WIN32
  12196. void juce_CloseThreadHandle (void* handle) throw();
  12197. #endif
  12198. static VoidArray runningThreads (4);
  12199. static CriticalSection runningThreadsLock;
  12200. void Thread::threadEntryPoint (Thread* const thread) throw()
  12201. {
  12202. {
  12203. const ScopedLock sl (runningThreadsLock);
  12204. runningThreads.add (thread);
  12205. }
  12206. JUCE_TRY
  12207. {
  12208. thread->threadId_ = Thread::getCurrentThreadId();
  12209. if (thread->threadName_.isNotEmpty())
  12210. juce_setCurrentThreadName (thread->threadName_);
  12211. if (thread->startSuspensionEvent_.wait (10000))
  12212. {
  12213. if (thread->affinityMask_ != 0)
  12214. setCurrentThreadAffinityMask (thread->affinityMask_);
  12215. thread->run();
  12216. }
  12217. }
  12218. JUCE_CATCH_ALL_ASSERT
  12219. {
  12220. const ScopedLock sl (runningThreadsLock);
  12221. jassert (runningThreads.contains (thread));
  12222. runningThreads.removeValue (thread);
  12223. }
  12224. #if JUCE_WIN32
  12225. juce_CloseThreadHandle (thread->threadHandle_);
  12226. #endif
  12227. thread->threadHandle_ = 0;
  12228. thread->threadId_ = 0;
  12229. }
  12230. // used to wrap the incoming call from the platform-specific code
  12231. void JUCE_API juce_threadEntryPoint (void* userData)
  12232. {
  12233. Thread::threadEntryPoint ((Thread*) userData);
  12234. }
  12235. Thread::Thread (const String& threadName)
  12236. : threadName_ (threadName),
  12237. threadHandle_ (0),
  12238. threadPriority_ (5),
  12239. threadId_ (0),
  12240. affinityMask_ (0),
  12241. threadShouldExit_ (false)
  12242. {
  12243. }
  12244. Thread::~Thread()
  12245. {
  12246. stopThread (100);
  12247. }
  12248. void Thread::startThread() throw()
  12249. {
  12250. const ScopedLock sl (startStopLock);
  12251. threadShouldExit_ = false;
  12252. if (threadHandle_ == 0)
  12253. {
  12254. threadHandle_ = juce_createThread ((void*) this);
  12255. juce_setThreadPriority (threadHandle_, threadPriority_);
  12256. startSuspensionEvent_.signal();
  12257. }
  12258. }
  12259. void Thread::startThread (const int priority) throw()
  12260. {
  12261. const ScopedLock sl (startStopLock);
  12262. if (threadHandle_ == 0)
  12263. {
  12264. threadPriority_ = priority;
  12265. startThread();
  12266. }
  12267. else
  12268. {
  12269. setPriority (priority);
  12270. }
  12271. }
  12272. bool Thread::isThreadRunning() const throw()
  12273. {
  12274. return threadHandle_ != 0;
  12275. }
  12276. void Thread::signalThreadShouldExit() throw()
  12277. {
  12278. threadShouldExit_ = true;
  12279. }
  12280. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const throw()
  12281. {
  12282. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12283. jassert (getThreadId() != getCurrentThreadId());
  12284. const int sleepMsPerIteration = 5;
  12285. int count = timeOutMilliseconds / sleepMsPerIteration;
  12286. while (isThreadRunning())
  12287. {
  12288. if (timeOutMilliseconds > 0 && --count < 0)
  12289. return false;
  12290. sleep (sleepMsPerIteration);
  12291. }
  12292. return true;
  12293. }
  12294. void Thread::stopThread (const int timeOutMilliseconds) throw()
  12295. {
  12296. // agh! You can't stop the thread that's calling this method! How on earth
  12297. // would that work??
  12298. jassert (getCurrentThreadId() != getThreadId());
  12299. const ScopedLock sl (startStopLock);
  12300. if (isThreadRunning())
  12301. {
  12302. signalThreadShouldExit();
  12303. notify();
  12304. if (timeOutMilliseconds != 0)
  12305. waitForThreadToExit (timeOutMilliseconds);
  12306. if (isThreadRunning())
  12307. {
  12308. // very bad karma if this point is reached, as
  12309. // there are bound to be locks and events left in
  12310. // silly states when a thread is killed by force..
  12311. jassertfalse
  12312. Logger::writeToLog ("!! killing thread by force !!");
  12313. juce_killThread (threadHandle_);
  12314. threadHandle_ = 0;
  12315. threadId_ = 0;
  12316. const ScopedLock sl (runningThreadsLock);
  12317. runningThreads.removeValue (this);
  12318. }
  12319. }
  12320. }
  12321. bool Thread::setPriority (const int priority) throw()
  12322. {
  12323. const ScopedLock sl (startStopLock);
  12324. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12325. if (worked)
  12326. threadPriority_ = priority;
  12327. return worked;
  12328. }
  12329. bool Thread::setCurrentThreadPriority (const int priority) throw()
  12330. {
  12331. return juce_setThreadPriority (0, priority);
  12332. }
  12333. void Thread::setAffinityMask (const uint32 affinityMask) throw()
  12334. {
  12335. affinityMask_ = affinityMask;
  12336. }
  12337. Thread::ThreadID Thread::getThreadId() const throw()
  12338. {
  12339. return threadId_;
  12340. }
  12341. bool Thread::wait (const int timeOutMilliseconds) const throw()
  12342. {
  12343. return defaultEvent_.wait (timeOutMilliseconds);
  12344. }
  12345. void Thread::notify() const throw()
  12346. {
  12347. defaultEvent_.signal();
  12348. }
  12349. int Thread::getNumRunningThreads() throw()
  12350. {
  12351. return runningThreads.size();
  12352. }
  12353. Thread* Thread::getCurrentThread() throw()
  12354. {
  12355. const ThreadID thisId = getCurrentThreadId();
  12356. const ScopedLock sl (runningThreadsLock);
  12357. for (int i = runningThreads.size(); --i >= 0;)
  12358. {
  12359. Thread* const t = (Thread*) (runningThreads.getUnchecked(i));
  12360. if (t->threadId_ == thisId)
  12361. return t;
  12362. }
  12363. return 0;
  12364. }
  12365. void Thread::stopAllThreads (const int timeOutMilliseconds) throw()
  12366. {
  12367. {
  12368. const ScopedLock sl (runningThreadsLock);
  12369. for (int i = runningThreads.size(); --i >= 0;)
  12370. ((Thread*) runningThreads.getUnchecked(i))->signalThreadShouldExit();
  12371. }
  12372. for (;;)
  12373. {
  12374. runningThreadsLock.enter();
  12375. Thread* const t = (Thread*) runningThreads[0];
  12376. runningThreadsLock.exit();
  12377. if (t == 0)
  12378. break;
  12379. t->stopThread (timeOutMilliseconds);
  12380. }
  12381. }
  12382. END_JUCE_NAMESPACE
  12383. /********* End of inlined file: juce_Thread.cpp *********/
  12384. /********* Start of inlined file: juce_ThreadPool.cpp *********/
  12385. BEGIN_JUCE_NAMESPACE
  12386. ThreadPoolJob::ThreadPoolJob (const String& name)
  12387. : jobName (name),
  12388. pool (0),
  12389. shouldStop (false),
  12390. isActive (false),
  12391. shouldBeDeleted (false)
  12392. {
  12393. }
  12394. ThreadPoolJob::~ThreadPoolJob()
  12395. {
  12396. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12397. // to remove it first!
  12398. jassert (pool == 0 || ! pool->contains (this));
  12399. }
  12400. const String ThreadPoolJob::getJobName() const
  12401. {
  12402. return jobName;
  12403. }
  12404. void ThreadPoolJob::setJobName (const String& newName)
  12405. {
  12406. jobName = newName;
  12407. }
  12408. void ThreadPoolJob::signalJobShouldExit()
  12409. {
  12410. shouldStop = true;
  12411. }
  12412. class ThreadPoolThread : public Thread
  12413. {
  12414. ThreadPool& pool;
  12415. bool volatile busy;
  12416. ThreadPoolThread (const ThreadPoolThread&);
  12417. const ThreadPoolThread& operator= (const ThreadPoolThread&);
  12418. public:
  12419. ThreadPoolThread (ThreadPool& pool_)
  12420. : Thread (T("Pool")),
  12421. pool (pool_),
  12422. busy (false)
  12423. {
  12424. }
  12425. ~ThreadPoolThread()
  12426. {
  12427. }
  12428. void run()
  12429. {
  12430. while (! threadShouldExit())
  12431. {
  12432. if (! pool.runNextJob())
  12433. wait (500);
  12434. }
  12435. }
  12436. };
  12437. ThreadPool::ThreadPool (const int numThreads_,
  12438. const bool startThreadsOnlyWhenNeeded,
  12439. const int stopThreadsWhenNotUsedTimeoutMs)
  12440. : numThreads (jmax (1, numThreads_)),
  12441. threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12442. priority (5)
  12443. {
  12444. jassert (numThreads_ > 0); // not much point having one of these with no threads in it.
  12445. threads = (Thread**) juce_calloc (sizeof (Thread*) * numThreads);
  12446. for (int i = numThreads; --i >= 0;)
  12447. {
  12448. threads[i] = new ThreadPoolThread (*this);
  12449. if (! startThreadsOnlyWhenNeeded)
  12450. threads[i]->startThread (priority);
  12451. }
  12452. }
  12453. ThreadPool::~ThreadPool()
  12454. {
  12455. removeAllJobs (true, 4000);
  12456. int i;
  12457. for (i = numThreads; --i >= 0;)
  12458. threads[i]->signalThreadShouldExit();
  12459. for (i = numThreads; --i >= 0;)
  12460. {
  12461. threads[i]->stopThread (500);
  12462. delete threads[i];
  12463. }
  12464. juce_free (threads);
  12465. }
  12466. void ThreadPool::addJob (ThreadPoolJob* const job)
  12467. {
  12468. jassert (job->pool == 0);
  12469. if (job->pool == 0)
  12470. {
  12471. job->pool = this;
  12472. job->shouldStop = false;
  12473. job->isActive = false;
  12474. lock.enter();
  12475. jobs.add (job);
  12476. int numRunning = 0;
  12477. int i;
  12478. for (i = numThreads; --i >= 0;)
  12479. if (threads[i]->isThreadRunning() && ! threads[i]->threadShouldExit())
  12480. ++numRunning;
  12481. if (numRunning < numThreads)
  12482. {
  12483. bool startedOne = false;
  12484. int n = 1000;
  12485. while (--n >= 0 && ! startedOne)
  12486. {
  12487. for (int i = numThreads; --i >= 0;)
  12488. {
  12489. if (! threads[i]->isThreadRunning())
  12490. {
  12491. threads[i]->startThread (priority);
  12492. startedOne = true;
  12493. }
  12494. }
  12495. if (! startedOne)
  12496. Thread::sleep (5);
  12497. }
  12498. }
  12499. lock.exit();
  12500. for (i = numThreads; --i >= 0;)
  12501. threads[i]->notify();
  12502. }
  12503. }
  12504. int ThreadPool::getNumJobs() const throw()
  12505. {
  12506. return jobs.size();
  12507. }
  12508. ThreadPoolJob* ThreadPool::getJob (const int index) const
  12509. {
  12510. const ScopedLock sl (lock);
  12511. return (ThreadPoolJob*) jobs [index];
  12512. }
  12513. bool ThreadPool::contains (const ThreadPoolJob* const job) const throw()
  12514. {
  12515. const ScopedLock sl (lock);
  12516. return jobs.contains ((void*) job);
  12517. }
  12518. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12519. {
  12520. const ScopedLock sl (lock);
  12521. return jobs.contains ((void*) job) && job->isActive;
  12522. }
  12523. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12524. const int timeOutMs) const
  12525. {
  12526. if (job != 0)
  12527. {
  12528. const uint32 start = Time::getMillisecondCounter();
  12529. while (contains (job))
  12530. {
  12531. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12532. return false;
  12533. Thread::sleep (2);
  12534. }
  12535. }
  12536. return true;
  12537. }
  12538. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12539. const bool interruptIfRunning,
  12540. const int timeOutMs)
  12541. {
  12542. if (job != 0)
  12543. {
  12544. lock.enter();
  12545. if (jobs.contains (job))
  12546. {
  12547. if (job->isActive)
  12548. {
  12549. if (interruptIfRunning)
  12550. job->signalJobShouldExit();
  12551. lock.exit();
  12552. return waitForJobToFinish (job, timeOutMs);
  12553. }
  12554. else
  12555. {
  12556. jobs.removeValue (job);
  12557. }
  12558. }
  12559. lock.exit();
  12560. }
  12561. return true;
  12562. }
  12563. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12564. const int timeOutMs,
  12565. const bool deleteInactiveJobs)
  12566. {
  12567. lock.enter();
  12568. for (int i = jobs.size(); --i >= 0;)
  12569. {
  12570. ThreadPoolJob* const job = (ThreadPoolJob*) jobs.getUnchecked(i);
  12571. if (job->isActive)
  12572. {
  12573. if (interruptRunningJobs)
  12574. job->signalJobShouldExit();
  12575. }
  12576. else
  12577. {
  12578. jobs.remove (i);
  12579. if (deleteInactiveJobs)
  12580. delete job;
  12581. }
  12582. }
  12583. lock.exit();
  12584. const uint32 start = Time::getMillisecondCounter();
  12585. while (jobs.size() > 0)
  12586. {
  12587. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12588. return false;
  12589. Thread::sleep (2);
  12590. }
  12591. return true;
  12592. }
  12593. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  12594. {
  12595. StringArray s;
  12596. const ScopedLock sl (lock);
  12597. for (int i = 0; i < jobs.size(); ++i)
  12598. {
  12599. const ThreadPoolJob* const job = (const ThreadPoolJob*) jobs.getUnchecked(i);
  12600. if (job->isActive || ! onlyReturnActiveJobs)
  12601. s.add (job->getJobName());
  12602. }
  12603. return s;
  12604. }
  12605. bool ThreadPool::setThreadPriorities (const int newPriority)
  12606. {
  12607. bool ok = true;
  12608. if (priority != newPriority)
  12609. {
  12610. priority = newPriority;
  12611. for (int i = numThreads; --i >= 0;)
  12612. if (! threads[i]->setPriority (newPriority))
  12613. ok = false;
  12614. }
  12615. return ok;
  12616. }
  12617. bool ThreadPool::runNextJob()
  12618. {
  12619. lock.enter();
  12620. ThreadPoolJob* job = 0;
  12621. for (int i = 0; i < jobs.size(); ++i)
  12622. {
  12623. job = (ThreadPoolJob*) jobs [i];
  12624. if (job != 0 && ! (job->isActive || job->shouldStop))
  12625. break;
  12626. job = 0;
  12627. }
  12628. if (job != 0)
  12629. {
  12630. job->isActive = true;
  12631. lock.exit();
  12632. JUCE_TRY
  12633. {
  12634. ThreadPoolJob::JobStatus result = job->runJob();
  12635. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12636. const ScopedLock sl (lock);
  12637. if (jobs.contains (job))
  12638. {
  12639. job->isActive = false;
  12640. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12641. {
  12642. job->pool = 0;
  12643. job->shouldStop = true;
  12644. jobs.removeValue (job);
  12645. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12646. delete job;
  12647. }
  12648. else
  12649. {
  12650. // move the job to the end of the queue if it wants another go
  12651. jobs.move (jobs.indexOf (job), -1);
  12652. }
  12653. }
  12654. }
  12655. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12656. catch (...)
  12657. {
  12658. lock.enter();
  12659. jobs.removeValue (job);
  12660. lock.exit();
  12661. }
  12662. #endif
  12663. }
  12664. else
  12665. {
  12666. lock.exit();
  12667. if (threadStopTimeout > 0
  12668. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12669. {
  12670. lock.enter();
  12671. if (jobs.size() == 0)
  12672. {
  12673. for (int i = numThreads; --i >= 0;)
  12674. threads[i]->signalThreadShouldExit();
  12675. }
  12676. lock.exit();
  12677. }
  12678. else
  12679. {
  12680. return false;
  12681. }
  12682. }
  12683. return true;
  12684. }
  12685. END_JUCE_NAMESPACE
  12686. /********* End of inlined file: juce_ThreadPool.cpp *********/
  12687. /********* Start of inlined file: juce_TimeSliceThread.cpp *********/
  12688. BEGIN_JUCE_NAMESPACE
  12689. TimeSliceThread::TimeSliceThread (const String& threadName)
  12690. : Thread (threadName),
  12691. index (0),
  12692. clientBeingCalled (0),
  12693. clientsChanged (false)
  12694. {
  12695. }
  12696. TimeSliceThread::~TimeSliceThread()
  12697. {
  12698. stopThread (2000);
  12699. }
  12700. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12701. {
  12702. const ScopedLock sl (listLock);
  12703. clients.addIfNotAlreadyThere (client);
  12704. clientsChanged = true;
  12705. notify();
  12706. }
  12707. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12708. {
  12709. const ScopedLock sl1 (listLock);
  12710. clientsChanged = true;
  12711. // if there's a chance we're in the middle of calling this client, we need to
  12712. // also lock the outer lock..
  12713. if (clientBeingCalled == client)
  12714. {
  12715. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12716. const ScopedLock sl1 (callbackLock);
  12717. const ScopedLock sl2 (listLock);
  12718. clients.removeValue (client);
  12719. }
  12720. else
  12721. {
  12722. clients.removeValue (client);
  12723. }
  12724. }
  12725. int TimeSliceThread::getNumClients() const throw()
  12726. {
  12727. return clients.size();
  12728. }
  12729. TimeSliceClient* TimeSliceThread::getClient (const int index) const throw()
  12730. {
  12731. const ScopedLock sl (listLock);
  12732. return clients [index];
  12733. }
  12734. void TimeSliceThread::run()
  12735. {
  12736. int numCallsSinceBusy = 0;
  12737. while (! threadShouldExit())
  12738. {
  12739. int timeToWait = 500;
  12740. {
  12741. const ScopedLock sl (callbackLock);
  12742. {
  12743. const ScopedLock sl (listLock);
  12744. if (clients.size() > 0)
  12745. {
  12746. index = (index + 1) % clients.size();
  12747. clientBeingCalled = clients [index];
  12748. }
  12749. else
  12750. {
  12751. index = 0;
  12752. clientBeingCalled = 0;
  12753. }
  12754. if (clientsChanged)
  12755. {
  12756. clientsChanged = false;
  12757. numCallsSinceBusy = 0;
  12758. }
  12759. }
  12760. if (clientBeingCalled != 0)
  12761. {
  12762. if (clientBeingCalled->useTimeSlice())
  12763. numCallsSinceBusy = 0;
  12764. else
  12765. ++numCallsSinceBusy;
  12766. if (numCallsSinceBusy >= clients.size())
  12767. timeToWait = 500;
  12768. else if (index == 0)
  12769. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12770. else
  12771. timeToWait = 0;
  12772. }
  12773. }
  12774. if (timeToWait > 0)
  12775. wait (timeToWait);
  12776. }
  12777. }
  12778. END_JUCE_NAMESPACE
  12779. /********* End of inlined file: juce_TimeSliceThread.cpp *********/
  12780. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  12781. /********* Start of inlined file: juce_Application.cpp *********/
  12782. #if JUCE_MSVC
  12783. #pragma warning (push)
  12784. #pragma warning (disable: 4245 4514 4100)
  12785. #include <crtdbg.h>
  12786. #pragma warning (pop)
  12787. #endif
  12788. BEGIN_JUCE_NAMESPACE
  12789. void juce_setCurrentThreadName (const String& name) throw();
  12790. static JUCEApplication* appInstance = 0;
  12791. JUCEApplication::JUCEApplication()
  12792. : appReturnValue (0),
  12793. stillInitialising (true)
  12794. {
  12795. }
  12796. JUCEApplication::~JUCEApplication()
  12797. {
  12798. }
  12799. JUCEApplication* JUCEApplication::getInstance() throw()
  12800. {
  12801. return appInstance;
  12802. }
  12803. bool JUCEApplication::isInitialising() const throw()
  12804. {
  12805. return stillInitialising;
  12806. }
  12807. const String JUCEApplication::getApplicationVersion()
  12808. {
  12809. return String::empty;
  12810. }
  12811. bool JUCEApplication::moreThanOneInstanceAllowed()
  12812. {
  12813. return true;
  12814. }
  12815. void JUCEApplication::anotherInstanceStarted (const String&)
  12816. {
  12817. }
  12818. void JUCEApplication::systemRequestedQuit()
  12819. {
  12820. quit();
  12821. }
  12822. void JUCEApplication::quit()
  12823. {
  12824. MessageManager::getInstance()->stopDispatchLoop();
  12825. }
  12826. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  12827. {
  12828. appReturnValue = newReturnValue;
  12829. }
  12830. void JUCEApplication::unhandledException (const std::exception*,
  12831. const String&,
  12832. const int)
  12833. {
  12834. jassertfalse
  12835. }
  12836. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  12837. const char* const sourceFile,
  12838. const int lineNumber)
  12839. {
  12840. if (appInstance != 0)
  12841. appInstance->unhandledException (e, sourceFile, lineNumber);
  12842. }
  12843. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  12844. {
  12845. return 0;
  12846. }
  12847. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  12848. {
  12849. commands.add (StandardApplicationCommandIDs::quit);
  12850. }
  12851. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  12852. {
  12853. if (commandID == StandardApplicationCommandIDs::quit)
  12854. {
  12855. result.setInfo ("Quit",
  12856. "Quits the application",
  12857. "Application",
  12858. 0);
  12859. result.defaultKeypresses.add (KeyPress (T('q'), ModifierKeys::commandModifier, 0));
  12860. }
  12861. }
  12862. bool JUCEApplication::perform (const InvocationInfo& info)
  12863. {
  12864. if (info.commandID == StandardApplicationCommandIDs::quit)
  12865. {
  12866. systemRequestedQuit();
  12867. return true;
  12868. }
  12869. return false;
  12870. }
  12871. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  12872. {
  12873. jassert (appInstance == 0);
  12874. appInstance = app;
  12875. app->commandLineParameters = commandLine.trim();
  12876. commandLine = String::empty;
  12877. initialiseJuce_GUI();
  12878. InterProcessLock* appLock = 0;
  12879. if (! app->moreThanOneInstanceAllowed())
  12880. {
  12881. appLock = new InterProcessLock ("juceAppLock_" + app->getApplicationName());
  12882. if (! appLock->enter(0))
  12883. {
  12884. MessageManager::broadcastMessage (app->getApplicationName() + "/" + app->commandLineParameters);
  12885. delete appInstance;
  12886. appInstance = 0;
  12887. DBG ("Another instance is running - quitting...");
  12888. return 0;
  12889. }
  12890. }
  12891. JUCE_TRY
  12892. {
  12893. juce_setCurrentThreadName ("Juce Message Thread");
  12894. // let the app do its setting-up..
  12895. app->initialise (app->commandLineParameters);
  12896. // register for broadcast new app messages
  12897. MessageManager::getInstance()->registerBroadcastListener (app);
  12898. app->stillInitialising = false;
  12899. // now loop until a quit message is received..
  12900. MessageManager::getInstance()->runDispatchLoop();
  12901. MessageManager::getInstance()->deregisterBroadcastListener (app);
  12902. if (appLock != 0)
  12903. {
  12904. appLock->exit();
  12905. delete appLock;
  12906. }
  12907. }
  12908. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12909. catch (const std::exception& e)
  12910. {
  12911. app->unhandledException (&e, __FILE__, __LINE__);
  12912. }
  12913. catch (...)
  12914. {
  12915. app->unhandledException (0, __FILE__, __LINE__);
  12916. }
  12917. #endif
  12918. return shutdownAppAndClearUp();
  12919. }
  12920. int JUCEApplication::shutdownAppAndClearUp()
  12921. {
  12922. jassert (appInstance != 0);
  12923. JUCEApplication* const app = appInstance;
  12924. int returnValue = 0;
  12925. static bool reentrancyCheck = false;
  12926. if (! reentrancyCheck)
  12927. {
  12928. reentrancyCheck = true;
  12929. JUCE_TRY
  12930. {
  12931. // give the app a chance to clean up..
  12932. app->shutdown();
  12933. }
  12934. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12935. catch (const std::exception& e)
  12936. {
  12937. app->unhandledException (&e, __FILE__, __LINE__);
  12938. }
  12939. catch (...)
  12940. {
  12941. app->unhandledException (0, __FILE__, __LINE__);
  12942. }
  12943. #endif
  12944. JUCE_TRY
  12945. {
  12946. shutdownJuce_GUI();
  12947. returnValue = app->getApplicationReturnValue();
  12948. appInstance = 0;
  12949. delete app;
  12950. }
  12951. JUCE_CATCH_ALL_ASSERT
  12952. reentrancyCheck = false;
  12953. }
  12954. return returnValue;
  12955. }
  12956. int JUCEApplication::main (int argc, char* argv[],
  12957. JUCEApplication* const newApp)
  12958. {
  12959. #if JUCE_MAC
  12960. const ScopedAutoReleasePool pool;
  12961. #endif
  12962. String cmd;
  12963. for (int i = 1; i < argc; ++i)
  12964. cmd << String::fromUTF8 ((const uint8*) argv[i]) << T(' ');
  12965. return JUCEApplication::main (cmd, newApp);
  12966. }
  12967. void JUCEApplication::actionListenerCallback (const String& message)
  12968. {
  12969. if (message.startsWith (getApplicationName() + "/"))
  12970. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  12971. }
  12972. static bool juceInitialisedGUI = false;
  12973. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  12974. {
  12975. if (! juceInitialisedGUI)
  12976. {
  12977. #if JUCE_MAC
  12978. const ScopedAutoReleasePool pool;
  12979. #endif
  12980. juceInitialisedGUI = true;
  12981. initialiseJuce_NonGUI();
  12982. MessageManager::getInstance();
  12983. LookAndFeel::setDefaultLookAndFeel (0);
  12984. #if JUCE_WIN32 && JUCE_DEBUG
  12985. // This section is just for catching people who mess up their project settings and
  12986. // turn RTTI off..
  12987. try
  12988. {
  12989. TextButton tb (String::empty);
  12990. Component* c = &tb;
  12991. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  12992. c = dynamic_cast <Button*> (c);
  12993. }
  12994. catch (...)
  12995. {
  12996. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  12997. // got as far as this catch statement, then why haven't you got exception catching
  12998. // turned on in the debugger???
  12999. jassertfalse
  13000. }
  13001. #endif
  13002. }
  13003. }
  13004. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  13005. {
  13006. if (juceInitialisedGUI)
  13007. {
  13008. #if JUCE_MAC
  13009. const ScopedAutoReleasePool pool;
  13010. #endif
  13011. {
  13012. DeletedAtShutdown::deleteAll();
  13013. LookAndFeel::clearDefaultLookAndFeel();
  13014. }
  13015. delete MessageManager::getInstance();
  13016. shutdownJuce_NonGUI();
  13017. juceInitialisedGUI = false;
  13018. }
  13019. }
  13020. END_JUCE_NAMESPACE
  13021. /********* End of inlined file: juce_Application.cpp *********/
  13022. /********* Start of inlined file: juce_ApplicationCommandInfo.cpp *********/
  13023. BEGIN_JUCE_NAMESPACE
  13024. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  13025. : commandID (commandID_),
  13026. flags (0)
  13027. {
  13028. }
  13029. void ApplicationCommandInfo::setInfo (const String& shortName_,
  13030. const String& description_,
  13031. const String& categoryName_,
  13032. const int flags_) throw()
  13033. {
  13034. shortName = shortName_;
  13035. description = description_;
  13036. categoryName = categoryName_;
  13037. flags = flags_;
  13038. }
  13039. void ApplicationCommandInfo::setActive (const bool b) throw()
  13040. {
  13041. if (b)
  13042. flags &= ~isDisabled;
  13043. else
  13044. flags |= isDisabled;
  13045. }
  13046. void ApplicationCommandInfo::setTicked (const bool b) throw()
  13047. {
  13048. if (b)
  13049. flags |= isTicked;
  13050. else
  13051. flags &= ~isTicked;
  13052. }
  13053. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  13054. {
  13055. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  13056. }
  13057. END_JUCE_NAMESPACE
  13058. /********* End of inlined file: juce_ApplicationCommandInfo.cpp *********/
  13059. /********* Start of inlined file: juce_ApplicationCommandManager.cpp *********/
  13060. BEGIN_JUCE_NAMESPACE
  13061. ApplicationCommandManager::ApplicationCommandManager()
  13062. : listeners (8),
  13063. firstTarget (0)
  13064. {
  13065. keyMappings = new KeyPressMappingSet (this);
  13066. Desktop::getInstance().addFocusChangeListener (this);
  13067. }
  13068. ApplicationCommandManager::~ApplicationCommandManager()
  13069. {
  13070. Desktop::getInstance().removeFocusChangeListener (this);
  13071. deleteAndZero (keyMappings);
  13072. }
  13073. void ApplicationCommandManager::clearCommands()
  13074. {
  13075. commands.clear();
  13076. keyMappings->clearAllKeyPresses();
  13077. triggerAsyncUpdate();
  13078. }
  13079. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  13080. {
  13081. // zero isn't a valid command ID!
  13082. jassert (newCommand.commandID != 0);
  13083. // the name isn't optional!
  13084. jassert (newCommand.shortName.isNotEmpty());
  13085. if (getCommandForID (newCommand.commandID) == 0)
  13086. {
  13087. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  13088. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  13089. commands.add (newInfo);
  13090. keyMappings->resetToDefaultMapping (newCommand.commandID);
  13091. triggerAsyncUpdate();
  13092. }
  13093. else
  13094. {
  13095. // trying to re-register the same command with different parameters?
  13096. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  13097. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  13098. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  13099. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  13100. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  13101. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  13102. }
  13103. }
  13104. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  13105. {
  13106. if (target != 0)
  13107. {
  13108. Array <CommandID> commandIDs;
  13109. target->getAllCommands (commandIDs);
  13110. for (int i = 0; i < commandIDs.size(); ++i)
  13111. {
  13112. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  13113. target->getCommandInfo (info.commandID, info);
  13114. registerCommand (info);
  13115. }
  13116. }
  13117. }
  13118. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  13119. {
  13120. for (int i = commands.size(); --i >= 0;)
  13121. {
  13122. if (commands.getUnchecked (i)->commandID == commandID)
  13123. {
  13124. commands.remove (i);
  13125. triggerAsyncUpdate();
  13126. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  13127. for (int j = keys.size(); --j >= 0;)
  13128. keyMappings->removeKeyPress (keys.getReference (j));
  13129. }
  13130. }
  13131. }
  13132. void ApplicationCommandManager::commandStatusChanged()
  13133. {
  13134. triggerAsyncUpdate();
  13135. }
  13136. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  13137. {
  13138. for (int i = commands.size(); --i >= 0;)
  13139. if (commands.getUnchecked(i)->commandID == commandID)
  13140. return commands.getUnchecked(i);
  13141. return 0;
  13142. }
  13143. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  13144. {
  13145. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13146. return (ci != 0) ? ci->shortName : String::empty;
  13147. }
  13148. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  13149. {
  13150. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13151. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  13152. : String::empty;
  13153. }
  13154. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  13155. {
  13156. StringArray s;
  13157. for (int i = 0; i < commands.size(); ++i)
  13158. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  13159. return s;
  13160. }
  13161. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  13162. {
  13163. Array <CommandID> results (4);
  13164. for (int i = 0; i < commands.size(); ++i)
  13165. if (commands.getUnchecked(i)->categoryName == categoryName)
  13166. results.add (commands.getUnchecked(i)->commandID);
  13167. return results;
  13168. }
  13169. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  13170. {
  13171. ApplicationCommandTarget::InvocationInfo info (commandID);
  13172. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  13173. return invoke (info, asynchronously);
  13174. }
  13175. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  13176. {
  13177. // This call isn't thread-safe for use from a non-UI thread without locking the message
  13178. // manager first..
  13179. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  13180. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  13181. if (target == 0)
  13182. return false;
  13183. ApplicationCommandInfo commandInfo (0);
  13184. target->getCommandInfo (info_.commandID, commandInfo);
  13185. ApplicationCommandTarget::InvocationInfo info (info_);
  13186. info.commandFlags = commandInfo.flags;
  13187. sendListenerInvokeCallback (info);
  13188. const bool ok = target->invoke (info, asynchronously);
  13189. commandStatusChanged();
  13190. return ok;
  13191. }
  13192. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  13193. {
  13194. return firstTarget != 0 ? firstTarget
  13195. : findDefaultComponentTarget();
  13196. }
  13197. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  13198. {
  13199. firstTarget = newTarget;
  13200. }
  13201. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  13202. ApplicationCommandInfo& upToDateInfo)
  13203. {
  13204. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  13205. if (target == 0)
  13206. target = JUCEApplication::getInstance();
  13207. if (target != 0)
  13208. target = target->getTargetForCommand (commandID);
  13209. if (target != 0)
  13210. target->getCommandInfo (commandID, upToDateInfo);
  13211. return target;
  13212. }
  13213. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  13214. {
  13215. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  13216. if (target == 0 && c != 0)
  13217. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  13218. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  13219. return target;
  13220. }
  13221. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  13222. {
  13223. Component* c = Component::getCurrentlyFocusedComponent();
  13224. if (c == 0)
  13225. {
  13226. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  13227. if (activeWindow != 0)
  13228. {
  13229. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  13230. if (c == 0)
  13231. c = activeWindow;
  13232. }
  13233. }
  13234. if (c == 0 && Process::isForegroundProcess())
  13235. {
  13236. // getting a bit desperate now - try all desktop comps..
  13237. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  13238. {
  13239. ApplicationCommandTarget* const target
  13240. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  13241. ->getPeer()->getLastFocusedSubcomponent());
  13242. if (target != 0)
  13243. return target;
  13244. }
  13245. }
  13246. if (c != 0)
  13247. {
  13248. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  13249. // if we're focused on a ResizableWindow, chances are that it's the content
  13250. // component that really should get the event. And if not, the event will
  13251. // still be passed up to the top level window anyway, so let's send it to the
  13252. // content comp.
  13253. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  13254. c = resizableWindow->getContentComponent();
  13255. ApplicationCommandTarget* const target = findTargetForComponent (c);
  13256. if (target != 0)
  13257. return target;
  13258. }
  13259. return JUCEApplication::getInstance();
  13260. }
  13261. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  13262. {
  13263. jassert (listener != 0);
  13264. if (listener != 0)
  13265. listeners.add (listener);
  13266. }
  13267. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  13268. {
  13269. listeners.removeValue (listener);
  13270. }
  13271. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const
  13272. {
  13273. for (int i = listeners.size(); --i >= 0;)
  13274. {
  13275. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandInvoked (info);
  13276. i = jmin (i, listeners.size());
  13277. }
  13278. }
  13279. void ApplicationCommandManager::handleAsyncUpdate()
  13280. {
  13281. for (int i = listeners.size(); --i >= 0;)
  13282. {
  13283. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandListChanged();
  13284. i = jmin (i, listeners.size());
  13285. }
  13286. }
  13287. void ApplicationCommandManager::globalFocusChanged (Component*)
  13288. {
  13289. commandStatusChanged();
  13290. }
  13291. END_JUCE_NAMESPACE
  13292. /********* End of inlined file: juce_ApplicationCommandManager.cpp *********/
  13293. /********* Start of inlined file: juce_ApplicationCommandTarget.cpp *********/
  13294. BEGIN_JUCE_NAMESPACE
  13295. ApplicationCommandTarget::ApplicationCommandTarget()
  13296. : messageInvoker (0)
  13297. {
  13298. }
  13299. ApplicationCommandTarget::~ApplicationCommandTarget()
  13300. {
  13301. deleteAndZero (messageInvoker);
  13302. }
  13303. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  13304. {
  13305. if (isCommandActive (info.commandID))
  13306. {
  13307. if (async)
  13308. {
  13309. if (messageInvoker == 0)
  13310. messageInvoker = new CommandTargetMessageInvoker (this);
  13311. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  13312. return true;
  13313. }
  13314. else
  13315. {
  13316. const bool success = perform (info);
  13317. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  13318. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  13319. // returns the command's info.
  13320. return success;
  13321. }
  13322. }
  13323. return false;
  13324. }
  13325. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  13326. {
  13327. Component* c = dynamic_cast <Component*> (this);
  13328. if (c != 0)
  13329. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  13330. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  13331. return 0;
  13332. }
  13333. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  13334. {
  13335. ApplicationCommandTarget* target = this;
  13336. int depth = 0;
  13337. while (target != 0)
  13338. {
  13339. Array <CommandID> commandIDs;
  13340. target->getAllCommands (commandIDs);
  13341. if (commandIDs.contains (commandID))
  13342. return target;
  13343. target = target->getNextCommandTarget();
  13344. ++depth;
  13345. jassert (depth < 100); // could be a recursive command chain??
  13346. jassert (target != this); // definitely a recursive command chain!
  13347. if (depth > 100 || target == this)
  13348. break;
  13349. }
  13350. if (target == 0)
  13351. {
  13352. target = JUCEApplication::getInstance();
  13353. if (target != 0)
  13354. {
  13355. Array <CommandID> commandIDs;
  13356. target->getAllCommands (commandIDs);
  13357. if (commandIDs.contains (commandID))
  13358. return target;
  13359. }
  13360. }
  13361. return 0;
  13362. }
  13363. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  13364. {
  13365. ApplicationCommandInfo info (commandID);
  13366. info.flags = ApplicationCommandInfo::isDisabled;
  13367. getCommandInfo (commandID, info);
  13368. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  13369. }
  13370. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  13371. {
  13372. ApplicationCommandTarget* target = this;
  13373. int depth = 0;
  13374. while (target != 0)
  13375. {
  13376. if (target->tryToInvoke (info, async))
  13377. return true;
  13378. target = target->getNextCommandTarget();
  13379. ++depth;
  13380. jassert (depth < 100); // could be a recursive command chain??
  13381. jassert (target != this); // definitely a recursive command chain!
  13382. if (depth > 100 || target == this)
  13383. break;
  13384. }
  13385. if (target == 0)
  13386. {
  13387. target = JUCEApplication::getInstance();
  13388. if (target != 0)
  13389. return target->tryToInvoke (info, async);
  13390. }
  13391. return false;
  13392. }
  13393. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  13394. {
  13395. ApplicationCommandTarget::InvocationInfo info (commandID);
  13396. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  13397. return invoke (info, asynchronously);
  13398. }
  13399. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  13400. : commandID (commandID_),
  13401. commandFlags (0),
  13402. invocationMethod (direct),
  13403. originatingComponent (0),
  13404. isKeyDown (false),
  13405. millisecsSinceKeyPressed (0)
  13406. {
  13407. }
  13408. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  13409. : owner (owner_)
  13410. {
  13411. }
  13412. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  13413. {
  13414. }
  13415. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  13416. {
  13417. InvocationInfo* const info = (InvocationInfo*) message.pointerParameter;
  13418. owner->tryToInvoke (*info, false);
  13419. delete info;
  13420. }
  13421. END_JUCE_NAMESPACE
  13422. /********* End of inlined file: juce_ApplicationCommandTarget.cpp *********/
  13423. /********* Start of inlined file: juce_ApplicationProperties.cpp *********/
  13424. BEGIN_JUCE_NAMESPACE
  13425. juce_ImplementSingleton (ApplicationProperties)
  13426. ApplicationProperties::ApplicationProperties() throw()
  13427. : userProps (0),
  13428. commonProps (0),
  13429. msBeforeSaving (3000),
  13430. options (PropertiesFile::storeAsBinary),
  13431. commonSettingsAreReadOnly (0)
  13432. {
  13433. }
  13434. ApplicationProperties::~ApplicationProperties()
  13435. {
  13436. closeFiles();
  13437. clearSingletonInstance();
  13438. }
  13439. void ApplicationProperties::setStorageParameters (const String& applicationName,
  13440. const String& fileNameSuffix,
  13441. const String& folderName_,
  13442. const int millisecondsBeforeSaving,
  13443. const int propertiesFileOptions) throw()
  13444. {
  13445. appName = applicationName;
  13446. fileSuffix = fileNameSuffix;
  13447. folderName = folderName_;
  13448. msBeforeSaving = millisecondsBeforeSaving;
  13449. options = propertiesFileOptions;
  13450. }
  13451. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  13452. const bool testCommonSettings,
  13453. const bool showWarningDialogOnFailure)
  13454. {
  13455. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  13456. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  13457. if (! (userOk && commonOk))
  13458. {
  13459. if (showWarningDialogOnFailure)
  13460. {
  13461. String filenames;
  13462. if (userProps != 0 && ! userOk)
  13463. filenames << '\n' << userProps->getFile().getFullPathName();
  13464. if (commonProps != 0 && ! commonOk)
  13465. filenames << '\n' << commonProps->getFile().getFullPathName();
  13466. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  13467. appName + TRANS(" - Unable to save settings"),
  13468. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  13469. + appName + TRANS(" needs to be able to write to the following files:\n")
  13470. + filenames
  13471. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  13472. }
  13473. return false;
  13474. }
  13475. return true;
  13476. }
  13477. void ApplicationProperties::openFiles() throw()
  13478. {
  13479. // You need to call setStorageParameters() before trying to get hold of the
  13480. // properties!
  13481. jassert (appName.isNotEmpty());
  13482. if (appName.isNotEmpty())
  13483. {
  13484. if (userProps == 0)
  13485. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  13486. false, msBeforeSaving, options);
  13487. if (commonProps == 0)
  13488. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  13489. true, msBeforeSaving, options);
  13490. userProps->setFallbackPropertySet (commonProps);
  13491. }
  13492. }
  13493. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  13494. {
  13495. if (userProps == 0)
  13496. openFiles();
  13497. return userProps;
  13498. }
  13499. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  13500. {
  13501. if (commonProps == 0)
  13502. openFiles();
  13503. if (returnUserPropsIfReadOnly)
  13504. {
  13505. if (commonSettingsAreReadOnly == 0)
  13506. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  13507. if (commonSettingsAreReadOnly > 0)
  13508. return userProps;
  13509. }
  13510. return commonProps;
  13511. }
  13512. bool ApplicationProperties::saveIfNeeded()
  13513. {
  13514. return (userProps == 0 || userProps->saveIfNeeded())
  13515. && (commonProps == 0 || commonProps->saveIfNeeded());
  13516. }
  13517. void ApplicationProperties::closeFiles()
  13518. {
  13519. deleteAndZero (userProps);
  13520. deleteAndZero (commonProps);
  13521. }
  13522. END_JUCE_NAMESPACE
  13523. /********* End of inlined file: juce_ApplicationProperties.cpp *********/
  13524. /********* Start of inlined file: juce_DeletedAtShutdown.cpp *********/
  13525. BEGIN_JUCE_NAMESPACE
  13526. static VoidArray objectsToDelete (16);
  13527. static CriticalSection lock;
  13528. DeletedAtShutdown::DeletedAtShutdown() throw()
  13529. {
  13530. const ScopedLock sl (lock);
  13531. objectsToDelete.add (this);
  13532. }
  13533. DeletedAtShutdown::~DeletedAtShutdown()
  13534. {
  13535. const ScopedLock sl (lock);
  13536. objectsToDelete.removeValue (this);
  13537. }
  13538. void DeletedAtShutdown::deleteAll()
  13539. {
  13540. // make a local copy of the array, so it can't get into a loop if something
  13541. // creates another DeletedAtShutdown object during its destructor.
  13542. lock.enter();
  13543. const VoidArray localCopy (objectsToDelete);
  13544. lock.exit();
  13545. for (int i = localCopy.size(); --i >= 0;)
  13546. {
  13547. JUCE_TRY
  13548. {
  13549. DeletedAtShutdown* const deletee = (DeletedAtShutdown*) localCopy.getUnchecked(i);
  13550. // double-check that it's not already been deleted during another object's destructor.
  13551. lock.enter();
  13552. const bool okToDelete = objectsToDelete.contains (deletee);
  13553. lock.exit();
  13554. if (okToDelete)
  13555. delete deletee;
  13556. }
  13557. JUCE_CATCH_EXCEPTION
  13558. }
  13559. // if no objects got re-created during shutdown, this should have been emptied by their
  13560. // destructors
  13561. jassert (objectsToDelete.size() == 0);
  13562. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  13563. }
  13564. END_JUCE_NAMESPACE
  13565. /********* End of inlined file: juce_DeletedAtShutdown.cpp *********/
  13566. /********* Start of inlined file: juce_PropertiesFile.cpp *********/
  13567. BEGIN_JUCE_NAMESPACE
  13568. static const int propFileMagicNumber = ((int) littleEndianInt ("PROP"));
  13569. static const int propFileMagicNumberCompressed = ((int) littleEndianInt ("CPRP"));
  13570. static const tchar* const propertyFileXmlTag = T("PROPERTIES");
  13571. static const tchar* const propertyTagName = T("VALUE");
  13572. PropertiesFile::PropertiesFile (const File& f,
  13573. const int millisecondsBeforeSaving,
  13574. const int options_) throw()
  13575. : PropertySet (ignoreCaseOfKeyNames),
  13576. file (f),
  13577. timerInterval (millisecondsBeforeSaving),
  13578. options (options_),
  13579. needsWriting (false)
  13580. {
  13581. // You need to correctly specify just one storage format for the file
  13582. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  13583. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  13584. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  13585. InputStream* fileStream = f.createInputStream();
  13586. if (fileStream != 0)
  13587. {
  13588. int magicNumber = fileStream->readInt();
  13589. if (magicNumber == propFileMagicNumberCompressed)
  13590. {
  13591. fileStream = new SubregionStream (fileStream, 4, -1, true);
  13592. fileStream = new GZIPDecompressorInputStream (fileStream, true);
  13593. magicNumber = propFileMagicNumber;
  13594. }
  13595. if (magicNumber == propFileMagicNumber)
  13596. {
  13597. BufferedInputStream in (fileStream, 2048, true);
  13598. int numValues = in.readInt();
  13599. while (--numValues >= 0 && ! in.isExhausted())
  13600. {
  13601. const String key (in.readString());
  13602. const String value (in.readString());
  13603. jassert (key.isNotEmpty());
  13604. if (key.isNotEmpty())
  13605. getAllProperties().set (key, value);
  13606. }
  13607. }
  13608. else
  13609. {
  13610. // Not a binary props file - let's see if it's XML..
  13611. delete fileStream;
  13612. XmlDocument parser (f);
  13613. XmlElement* doc = parser.getDocumentElement (true);
  13614. if (doc != 0 && doc->hasTagName (propertyFileXmlTag))
  13615. {
  13616. delete doc;
  13617. doc = parser.getDocumentElement();
  13618. if (doc != 0)
  13619. {
  13620. forEachXmlChildElementWithTagName (*doc, e, propertyTagName)
  13621. {
  13622. const String name (e->getStringAttribute (T("name")));
  13623. if (name.isNotEmpty())
  13624. {
  13625. getAllProperties().set (name,
  13626. e->getFirstChildElement() != 0
  13627. ? e->getFirstChildElement()->createDocument (String::empty, true)
  13628. : e->getStringAttribute (T("val")));
  13629. }
  13630. }
  13631. }
  13632. else
  13633. {
  13634. // must be a pretty broken XML file we're trying to parse here!
  13635. jassertfalse
  13636. }
  13637. delete doc;
  13638. }
  13639. }
  13640. }
  13641. }
  13642. PropertiesFile::~PropertiesFile()
  13643. {
  13644. saveIfNeeded();
  13645. }
  13646. bool PropertiesFile::saveIfNeeded()
  13647. {
  13648. const ScopedLock sl (getLock());
  13649. return (! needsWriting) || save();
  13650. }
  13651. bool PropertiesFile::needsToBeSaved() const throw()
  13652. {
  13653. const ScopedLock sl (getLock());
  13654. return needsWriting;
  13655. }
  13656. bool PropertiesFile::save()
  13657. {
  13658. const ScopedLock sl (getLock());
  13659. stopTimer();
  13660. if (file == File::nonexistent
  13661. || file.isDirectory()
  13662. || ! file.getParentDirectory().createDirectory())
  13663. return false;
  13664. if ((options & storeAsXML) != 0)
  13665. {
  13666. XmlElement* const doc = new XmlElement (propertyFileXmlTag);
  13667. for (int i = 0; i < getAllProperties().size(); ++i)
  13668. {
  13669. XmlElement* const e = new XmlElement (propertyTagName);
  13670. e->setAttribute (T("name"), getAllProperties().getAllKeys() [i]);
  13671. // if the value seems to contain xml, store it as such..
  13672. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  13673. XmlElement* const childElement = xmlContent.getDocumentElement();
  13674. if (childElement != 0)
  13675. e->addChildElement (childElement);
  13676. else
  13677. e->setAttribute (T("val"), getAllProperties().getAllValues() [i]);
  13678. doc->addChildElement (e);
  13679. }
  13680. const bool ok = doc->writeToFile (file, String::empty);
  13681. delete doc;
  13682. return ok;
  13683. }
  13684. else
  13685. {
  13686. const File tempFile (file.getNonexistentSibling (false));
  13687. OutputStream* out = tempFile.createOutputStream();
  13688. if (out != 0)
  13689. {
  13690. if ((options & storeAsCompressedBinary) != 0)
  13691. {
  13692. out->writeInt (propFileMagicNumberCompressed);
  13693. out->flush();
  13694. out = new GZIPCompressorOutputStream (out, 9, true);
  13695. }
  13696. else
  13697. {
  13698. // have you set up the storage option flags correctly?
  13699. jassert ((options & storeAsBinary) != 0);
  13700. out->writeInt (propFileMagicNumber);
  13701. }
  13702. const int numProperties = getAllProperties().size();
  13703. out->writeInt (numProperties);
  13704. for (int i = 0; i < numProperties; ++i)
  13705. {
  13706. out->writeString (getAllProperties().getAllKeys() [i]);
  13707. out->writeString (getAllProperties().getAllValues() [i]);
  13708. }
  13709. out->flush();
  13710. delete out;
  13711. if (tempFile.moveFileTo (file))
  13712. {
  13713. needsWriting = false;
  13714. return true;
  13715. }
  13716. tempFile.deleteFile();
  13717. }
  13718. }
  13719. return false;
  13720. }
  13721. void PropertiesFile::timerCallback()
  13722. {
  13723. saveIfNeeded();
  13724. }
  13725. void PropertiesFile::propertyChanged()
  13726. {
  13727. sendChangeMessage (this);
  13728. needsWriting = true;
  13729. if (timerInterval > 0)
  13730. startTimer (timerInterval);
  13731. else if (timerInterval == 0)
  13732. saveIfNeeded();
  13733. }
  13734. const File PropertiesFile::getFile() const throw()
  13735. {
  13736. return file;
  13737. }
  13738. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  13739. const String& fileNameSuffix,
  13740. const String& folderName,
  13741. const bool commonToAllUsers)
  13742. {
  13743. // mustn't have illegal characters in this name..
  13744. jassert (applicationName == File::createLegalFileName (applicationName));
  13745. #if JUCE_MAC
  13746. File dir (commonToAllUsers ? "/Library/Preferences"
  13747. : "~/Library/Preferences");
  13748. if (folderName.isNotEmpty())
  13749. dir = dir.getChildFile (folderName);
  13750. #endif
  13751. #ifdef JUCE_LINUX
  13752. const File dir ((commonToAllUsers ? T("/var/") : T("~/"))
  13753. + (folderName.isNotEmpty() ? folderName
  13754. : (T(".") + applicationName)));
  13755. #endif
  13756. #if JUCE_WIN32
  13757. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  13758. : File::userApplicationDataDirectory));
  13759. if (dir == File::nonexistent)
  13760. return File::nonexistent;
  13761. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  13762. : applicationName);
  13763. #endif
  13764. return dir.getChildFile (applicationName)
  13765. .withFileExtension (fileNameSuffix);
  13766. }
  13767. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  13768. const String& fileNameSuffix,
  13769. const String& folderName,
  13770. const bool commonToAllUsers,
  13771. const int millisecondsBeforeSaving,
  13772. const int propertiesFileOptions)
  13773. {
  13774. const File file (getDefaultAppSettingsFile (applicationName,
  13775. fileNameSuffix,
  13776. folderName,
  13777. commonToAllUsers));
  13778. jassert (file != File::nonexistent);
  13779. if (file == File::nonexistent)
  13780. return 0;
  13781. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions);
  13782. }
  13783. END_JUCE_NAMESPACE
  13784. /********* End of inlined file: juce_PropertiesFile.cpp *********/
  13785. /********* Start of inlined file: juce_FileBasedDocument.cpp *********/
  13786. BEGIN_JUCE_NAMESPACE
  13787. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  13788. const String& fileWildcard_,
  13789. const String& openFileDialogTitle_,
  13790. const String& saveFileDialogTitle_)
  13791. : changedSinceSave (false),
  13792. fileExtension (fileExtension_),
  13793. fileWildcard (fileWildcard_),
  13794. openFileDialogTitle (openFileDialogTitle_),
  13795. saveFileDialogTitle (saveFileDialogTitle_)
  13796. {
  13797. }
  13798. FileBasedDocument::~FileBasedDocument()
  13799. {
  13800. }
  13801. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  13802. {
  13803. changedSinceSave = hasChanged;
  13804. }
  13805. void FileBasedDocument::changed()
  13806. {
  13807. changedSinceSave = true;
  13808. sendChangeMessage (this);
  13809. }
  13810. void FileBasedDocument::setFile (const File& newFile)
  13811. {
  13812. if (documentFile != newFile)
  13813. {
  13814. documentFile = newFile;
  13815. changedSinceSave = true;
  13816. }
  13817. }
  13818. bool FileBasedDocument::loadFrom (const File& newFile,
  13819. const bool showMessageOnFailure)
  13820. {
  13821. MouseCursor::showWaitCursor();
  13822. const File oldFile (documentFile);
  13823. documentFile = newFile;
  13824. String error;
  13825. if (newFile.existsAsFile())
  13826. {
  13827. error = loadDocument (newFile);
  13828. if (error.isEmpty())
  13829. {
  13830. setChangedFlag (false);
  13831. MouseCursor::hideWaitCursor();
  13832. setLastDocumentOpened (newFile);
  13833. return true;
  13834. }
  13835. }
  13836. else
  13837. {
  13838. error = "The file doesn't exist";
  13839. }
  13840. documentFile = oldFile;
  13841. MouseCursor::hideWaitCursor();
  13842. if (showMessageOnFailure)
  13843. {
  13844. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  13845. TRANS("Failed to open file..."),
  13846. TRANS("There was an error while trying to load the file:\n\n")
  13847. + newFile.getFullPathName()
  13848. + T("\n\n")
  13849. + error);
  13850. }
  13851. return false;
  13852. }
  13853. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  13854. {
  13855. FileChooser fc (openFileDialogTitle,
  13856. getLastDocumentOpened(),
  13857. fileWildcard);
  13858. if (fc.browseForFileToOpen())
  13859. return loadFrom (fc.getResult(), showMessageOnFailure);
  13860. return false;
  13861. }
  13862. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  13863. const bool showMessageOnFailure)
  13864. {
  13865. return saveAs (documentFile,
  13866. false,
  13867. askUserForFileIfNotSpecified,
  13868. showMessageOnFailure);
  13869. }
  13870. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  13871. const bool warnAboutOverwritingExistingFiles,
  13872. const bool askUserForFileIfNotSpecified,
  13873. const bool showMessageOnFailure)
  13874. {
  13875. if (newFile == File::nonexistent)
  13876. {
  13877. if (askUserForFileIfNotSpecified)
  13878. {
  13879. return saveAsInteractive (true);
  13880. }
  13881. else
  13882. {
  13883. // can't save to an unspecified file
  13884. jassertfalse
  13885. return failedToWriteToFile;
  13886. }
  13887. }
  13888. if (warnAboutOverwritingExistingFiles && newFile.exists())
  13889. {
  13890. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  13891. TRANS("File already exists"),
  13892. TRANS("There's already a file called:\n\n")
  13893. + newFile.getFullPathName()
  13894. + TRANS("\n\nAre you sure you want to overwrite it?"),
  13895. TRANS("overwrite"),
  13896. TRANS("cancel")))
  13897. {
  13898. return userCancelledSave;
  13899. }
  13900. }
  13901. MouseCursor::showWaitCursor();
  13902. const File oldFile (documentFile);
  13903. documentFile = newFile;
  13904. String error (saveDocument (newFile));
  13905. if (error.isEmpty())
  13906. {
  13907. setChangedFlag (false);
  13908. MouseCursor::hideWaitCursor();
  13909. return savedOk;
  13910. }
  13911. documentFile = oldFile;
  13912. MouseCursor::hideWaitCursor();
  13913. if (showMessageOnFailure)
  13914. {
  13915. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  13916. TRANS("Error writing to file..."),
  13917. TRANS("An error occurred while trying to save \"")
  13918. + getDocumentTitle()
  13919. + TRANS("\" to the file:\n\n")
  13920. + newFile.getFullPathName()
  13921. + T("\n\n")
  13922. + error);
  13923. }
  13924. return failedToWriteToFile;
  13925. }
  13926. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  13927. {
  13928. if (! hasChangedSinceSaved())
  13929. return savedOk;
  13930. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  13931. TRANS("Closing document..."),
  13932. TRANS("Do you want to save the changes to \"")
  13933. + getDocumentTitle() + T("\"?"),
  13934. TRANS("save"),
  13935. TRANS("discard changes"),
  13936. TRANS("cancel"));
  13937. if (r == 1)
  13938. {
  13939. // save changes
  13940. return save (true, true);
  13941. }
  13942. else if (r == 2)
  13943. {
  13944. // discard changes
  13945. return savedOk;
  13946. }
  13947. return userCancelledSave;
  13948. }
  13949. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  13950. {
  13951. File f;
  13952. if (documentFile.existsAsFile())
  13953. f = documentFile;
  13954. else
  13955. f = getLastDocumentOpened();
  13956. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  13957. if (legalFilename.isEmpty())
  13958. legalFilename = "unnamed";
  13959. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  13960. f = f.getSiblingFile (legalFilename);
  13961. else
  13962. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  13963. f = f.withFileExtension (fileExtension)
  13964. .getNonexistentSibling (true);
  13965. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  13966. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  13967. {
  13968. setLastDocumentOpened (fc.getResult());
  13969. File chosen (fc.getResult());
  13970. if (chosen.getFileExtension().isEmpty())
  13971. chosen = chosen.withFileExtension (fileExtension);
  13972. return saveAs (chosen, false, false, true);
  13973. }
  13974. return userCancelledSave;
  13975. }
  13976. END_JUCE_NAMESPACE
  13977. /********* End of inlined file: juce_FileBasedDocument.cpp *********/
  13978. /********* Start of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  13979. BEGIN_JUCE_NAMESPACE
  13980. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  13981. : maxNumberOfItems (10)
  13982. {
  13983. }
  13984. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  13985. {
  13986. }
  13987. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  13988. {
  13989. maxNumberOfItems = jmax (1, newMaxNumber);
  13990. while (getNumFiles() > maxNumberOfItems)
  13991. files.remove (getNumFiles() - 1);
  13992. }
  13993. int RecentlyOpenedFilesList::getNumFiles() const
  13994. {
  13995. return files.size();
  13996. }
  13997. const File RecentlyOpenedFilesList::getFile (const int index) const
  13998. {
  13999. return File (files [index]);
  14000. }
  14001. void RecentlyOpenedFilesList::clear()
  14002. {
  14003. files.clear();
  14004. }
  14005. void RecentlyOpenedFilesList::addFile (const File& file)
  14006. {
  14007. const String path (file.getFullPathName());
  14008. files.removeString (path, true);
  14009. files.insert (0, path);
  14010. setMaxNumberOfItems (maxNumberOfItems);
  14011. }
  14012. void RecentlyOpenedFilesList::removeNonExistentFiles()
  14013. {
  14014. for (int i = getNumFiles(); --i >= 0;)
  14015. if (! getFile(i).exists())
  14016. files.remove (i);
  14017. }
  14018. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  14019. const int baseItemId,
  14020. const bool showFullPaths,
  14021. const bool dontAddNonExistentFiles,
  14022. const File** filesToAvoid)
  14023. {
  14024. int num = 0;
  14025. for (int i = 0; i < getNumFiles(); ++i)
  14026. {
  14027. const File f (getFile(i));
  14028. if ((! dontAddNonExistentFiles) || f.exists())
  14029. {
  14030. bool needsAvoiding = false;
  14031. if (filesToAvoid != 0)
  14032. {
  14033. const File** files = filesToAvoid;
  14034. while (*files != 0)
  14035. {
  14036. if (f == **files)
  14037. {
  14038. needsAvoiding = true;
  14039. break;
  14040. }
  14041. ++files;
  14042. }
  14043. }
  14044. if (! needsAvoiding)
  14045. {
  14046. menuToAddTo.addItem (baseItemId + i,
  14047. showFullPaths ? f.getFullPathName()
  14048. : f.getFileName());
  14049. ++num;
  14050. }
  14051. }
  14052. }
  14053. return num;
  14054. }
  14055. const String RecentlyOpenedFilesList::toString() const
  14056. {
  14057. return files.joinIntoString (T("\n"));
  14058. }
  14059. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  14060. {
  14061. clear();
  14062. files.addLines (stringifiedVersion);
  14063. setMaxNumberOfItems (maxNumberOfItems);
  14064. }
  14065. END_JUCE_NAMESPACE
  14066. /********* End of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  14067. /********* Start of inlined file: juce_UndoManager.cpp *********/
  14068. BEGIN_JUCE_NAMESPACE
  14069. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  14070. const int minimumTransactions)
  14071. : totalUnitsStored (0),
  14072. nextIndex (0),
  14073. newTransaction (true),
  14074. reentrancyCheck (false)
  14075. {
  14076. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  14077. minimumTransactions);
  14078. }
  14079. UndoManager::~UndoManager()
  14080. {
  14081. clearUndoHistory();
  14082. }
  14083. void UndoManager::clearUndoHistory()
  14084. {
  14085. transactions.clear();
  14086. transactionNames.clear();
  14087. totalUnitsStored = 0;
  14088. nextIndex = 0;
  14089. sendChangeMessage (this);
  14090. }
  14091. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  14092. {
  14093. return totalUnitsStored;
  14094. }
  14095. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  14096. const int minimumTransactions)
  14097. {
  14098. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  14099. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  14100. }
  14101. bool UndoManager::perform (UndoableAction* const command, const String& actionName)
  14102. {
  14103. if (command != 0)
  14104. {
  14105. if (actionName.isNotEmpty())
  14106. currentTransactionName = actionName;
  14107. if (reentrancyCheck)
  14108. {
  14109. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  14110. // undo() methods, or else these actions won't actually get done.
  14111. return false;
  14112. }
  14113. else
  14114. {
  14115. bool success = false;
  14116. JUCE_TRY
  14117. {
  14118. success = command->perform();
  14119. }
  14120. JUCE_CATCH_EXCEPTION
  14121. jassert (success);
  14122. if (success)
  14123. {
  14124. if (nextIndex > 0 && ! newTransaction)
  14125. {
  14126. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  14127. jassert (commandSet != 0);
  14128. if (commandSet == 0)
  14129. return false;
  14130. commandSet->add (command);
  14131. }
  14132. else
  14133. {
  14134. OwnedArray<UndoableAction>* commandSet = new OwnedArray<UndoableAction>();
  14135. commandSet->add (command);
  14136. transactions.insert (nextIndex, commandSet);
  14137. transactionNames.insert (nextIndex, currentTransactionName);
  14138. ++nextIndex;
  14139. }
  14140. totalUnitsStored += command->getSizeInUnits();
  14141. newTransaction = false;
  14142. }
  14143. while (nextIndex < transactions.size())
  14144. {
  14145. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  14146. for (int i = lastSet->size(); --i >= 0;)
  14147. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  14148. transactions.removeLast();
  14149. transactionNames.remove (transactionNames.size() - 1);
  14150. }
  14151. while (nextIndex > 0
  14152. && totalUnitsStored > maxNumUnitsToKeep
  14153. && transactions.size() > minimumTransactionsToKeep)
  14154. {
  14155. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  14156. for (int i = firstSet->size(); --i >= 0;)
  14157. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  14158. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  14159. transactions.remove (0);
  14160. transactionNames.remove (0);
  14161. --nextIndex;
  14162. }
  14163. sendChangeMessage (this);
  14164. return success;
  14165. }
  14166. }
  14167. return false;
  14168. }
  14169. void UndoManager::beginNewTransaction (const String& actionName)
  14170. {
  14171. newTransaction = true;
  14172. currentTransactionName = actionName;
  14173. }
  14174. void UndoManager::setCurrentTransactionName (const String& newName)
  14175. {
  14176. currentTransactionName = newName;
  14177. }
  14178. bool UndoManager::canUndo() const
  14179. {
  14180. return nextIndex > 0;
  14181. }
  14182. bool UndoManager::canRedo() const
  14183. {
  14184. return nextIndex < transactions.size();
  14185. }
  14186. const String UndoManager::getUndoDescription() const
  14187. {
  14188. return transactionNames [nextIndex - 1];
  14189. }
  14190. const String UndoManager::getRedoDescription() const
  14191. {
  14192. return transactionNames [nextIndex];
  14193. }
  14194. bool UndoManager::undo()
  14195. {
  14196. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  14197. if (commandSet == 0)
  14198. return false;
  14199. reentrancyCheck = true;
  14200. bool failed = false;
  14201. for (int i = commandSet->size(); --i >= 0;)
  14202. {
  14203. if (! commandSet->getUnchecked(i)->undo())
  14204. {
  14205. jassertfalse
  14206. failed = true;
  14207. break;
  14208. }
  14209. }
  14210. reentrancyCheck = false;
  14211. if (failed)
  14212. {
  14213. clearUndoHistory();
  14214. }
  14215. else
  14216. {
  14217. --nextIndex;
  14218. }
  14219. beginNewTransaction();
  14220. sendChangeMessage (this);
  14221. return true;
  14222. }
  14223. bool UndoManager::redo()
  14224. {
  14225. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  14226. if (commandSet == 0)
  14227. return false;
  14228. reentrancyCheck = true;
  14229. bool failed = false;
  14230. for (int i = 0; i < commandSet->size(); ++i)
  14231. {
  14232. if (! commandSet->getUnchecked(i)->perform())
  14233. {
  14234. jassertfalse
  14235. failed = true;
  14236. break;
  14237. }
  14238. }
  14239. reentrancyCheck = false;
  14240. if (failed)
  14241. {
  14242. clearUndoHistory();
  14243. }
  14244. else
  14245. {
  14246. ++nextIndex;
  14247. }
  14248. beginNewTransaction();
  14249. sendChangeMessage (this);
  14250. return true;
  14251. }
  14252. bool UndoManager::undoCurrentTransactionOnly()
  14253. {
  14254. return newTransaction ? false
  14255. : undo();
  14256. }
  14257. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  14258. {
  14259. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  14260. if (commandSet != 0 && ! newTransaction)
  14261. {
  14262. for (int i = 0; i < commandSet->size(); ++i)
  14263. actionsFound.add (commandSet->getUnchecked(i));
  14264. }
  14265. }
  14266. END_JUCE_NAMESPACE
  14267. /********* End of inlined file: juce_UndoManager.cpp *********/
  14268. /********* Start of inlined file: juce_AiffAudioFormat.cpp *********/
  14269. BEGIN_JUCE_NAMESPACE
  14270. #undef chunkName
  14271. #define chunkName(a) (int)littleEndianInt(a)
  14272. #define aiffFormatName TRANS("AIFF file")
  14273. static const tchar* const aiffExtensions[] = { T(".aiff"), T(".aif"), 0 };
  14274. class AiffAudioFormatReader : public AudioFormatReader
  14275. {
  14276. public:
  14277. int bytesPerFrame;
  14278. int64 dataChunkStart;
  14279. bool littleEndian;
  14280. AiffAudioFormatReader (InputStream* in)
  14281. : AudioFormatReader (in, aiffFormatName)
  14282. {
  14283. if (input->readInt() == chunkName ("FORM"))
  14284. {
  14285. const int len = input->readIntBigEndian();
  14286. const int64 end = input->getPosition() + len;
  14287. const int nextType = input->readInt();
  14288. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  14289. {
  14290. bool hasGotVer = false;
  14291. bool hasGotData = false;
  14292. bool hasGotType = false;
  14293. while (input->getPosition() < end)
  14294. {
  14295. const int type = input->readInt();
  14296. const uint32 length = (uint32) input->readIntBigEndian();
  14297. const int64 chunkEnd = input->getPosition() + length;
  14298. if (type == chunkName ("FVER"))
  14299. {
  14300. hasGotVer = true;
  14301. const int ver = input->readIntBigEndian();
  14302. if (ver != 0 && ver != (int)0xa2805140)
  14303. break;
  14304. }
  14305. else if (type == chunkName ("COMM"))
  14306. {
  14307. hasGotType = true;
  14308. numChannels = (unsigned int)input->readShortBigEndian();
  14309. lengthInSamples = input->readIntBigEndian();
  14310. bitsPerSample = input->readShortBigEndian();
  14311. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  14312. unsigned char sampleRateBytes[10];
  14313. input->read (sampleRateBytes, 10);
  14314. const int byte0 = sampleRateBytes[0];
  14315. if ((byte0 & 0x80) != 0
  14316. || byte0 <= 0x3F || byte0 > 0x40
  14317. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  14318. break;
  14319. unsigned int sampRate = bigEndianInt ((char*) sampleRateBytes + 2);
  14320. sampRate >>= (16414 - bigEndianShort ((char*) sampleRateBytes));
  14321. sampleRate = (int)sampRate;
  14322. if (length <= 18)
  14323. {
  14324. // some types don't have a chunk large enough to include a compression
  14325. // type, so assume it's just big-endian pcm
  14326. littleEndian = false;
  14327. }
  14328. else
  14329. {
  14330. const int compType = input->readInt();
  14331. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  14332. {
  14333. littleEndian = false;
  14334. }
  14335. else if (compType == chunkName ("sowt"))
  14336. {
  14337. littleEndian = true;
  14338. }
  14339. else
  14340. {
  14341. sampleRate = 0;
  14342. break;
  14343. }
  14344. }
  14345. }
  14346. else if (type == chunkName ("SSND"))
  14347. {
  14348. hasGotData = true;
  14349. const int offset = input->readIntBigEndian();
  14350. dataChunkStart = input->getPosition() + 4 + offset;
  14351. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  14352. }
  14353. else if ((hasGotVer && hasGotData && hasGotType)
  14354. || chunkEnd < input->getPosition()
  14355. || input->isExhausted())
  14356. {
  14357. break;
  14358. }
  14359. input->setPosition (chunkEnd);
  14360. }
  14361. }
  14362. }
  14363. }
  14364. ~AiffAudioFormatReader()
  14365. {
  14366. }
  14367. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  14368. int64 startSampleInFile, int numSamples)
  14369. {
  14370. numSamples = (int) jmin ((int64) numSamples, lengthInSamples - startSampleInFile);
  14371. if (numSamples <= 0)
  14372. return true;
  14373. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  14374. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  14375. char tempBuffer [tempBufSize];
  14376. while (numSamples > 0)
  14377. {
  14378. int* left = destSamples[0];
  14379. if (left != 0)
  14380. left += startOffsetInDestBuffer;
  14381. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  14382. if (right != 0)
  14383. right += startOffsetInDestBuffer;
  14384. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  14385. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  14386. if (bytesRead < numThisTime * bytesPerFrame)
  14387. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  14388. if (bitsPerSample == 16)
  14389. {
  14390. if (littleEndian)
  14391. {
  14392. const short* src = (const short*) tempBuffer;
  14393. if (numChannels > 1)
  14394. {
  14395. if (left == 0)
  14396. {
  14397. for (int i = numThisTime; --i >= 0;)
  14398. {
  14399. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14400. ++src;
  14401. }
  14402. }
  14403. else if (right == 0)
  14404. {
  14405. for (int i = numThisTime; --i >= 0;)
  14406. {
  14407. ++src;
  14408. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14409. }
  14410. }
  14411. else
  14412. {
  14413. for (int i = numThisTime; --i >= 0;)
  14414. {
  14415. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14416. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14417. }
  14418. }
  14419. }
  14420. else
  14421. {
  14422. for (int i = numThisTime; --i >= 0;)
  14423. {
  14424. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14425. }
  14426. }
  14427. }
  14428. else
  14429. {
  14430. const char* src = (const char*) tempBuffer;
  14431. if (numChannels > 1)
  14432. {
  14433. if (left == 0)
  14434. {
  14435. for (int i = numThisTime; --i >= 0;)
  14436. {
  14437. *right++ = bigEndianShort (src) << 16;
  14438. src += 4;
  14439. }
  14440. }
  14441. else if (right == 0)
  14442. {
  14443. for (int i = numThisTime; --i >= 0;)
  14444. {
  14445. src += 2;
  14446. *left++ = bigEndianShort (src) << 16;
  14447. src += 2;
  14448. }
  14449. }
  14450. else
  14451. {
  14452. for (int i = numThisTime; --i >= 0;)
  14453. {
  14454. *left++ = bigEndianShort (src) << 16;
  14455. src += 2;
  14456. *right++ = bigEndianShort (src) << 16;
  14457. src += 2;
  14458. }
  14459. }
  14460. }
  14461. else
  14462. {
  14463. for (int i = numThisTime; --i >= 0;)
  14464. {
  14465. *left++ = bigEndianShort (src) << 16;
  14466. src += 2;
  14467. }
  14468. }
  14469. }
  14470. }
  14471. else if (bitsPerSample == 24)
  14472. {
  14473. const char* src = (const char*)tempBuffer;
  14474. if (littleEndian)
  14475. {
  14476. if (numChannels > 1)
  14477. {
  14478. if (left == 0)
  14479. {
  14480. for (int i = numThisTime; --i >= 0;)
  14481. {
  14482. *right++ = littleEndian24Bit (src) << 8;
  14483. src += 6;
  14484. }
  14485. }
  14486. else if (right == 0)
  14487. {
  14488. for (int i = numThisTime; --i >= 0;)
  14489. {
  14490. src += 3;
  14491. *left++ = littleEndian24Bit (src) << 8;
  14492. src += 3;
  14493. }
  14494. }
  14495. else
  14496. {
  14497. for (int i = numThisTime; --i >= 0;)
  14498. {
  14499. *left++ = littleEndian24Bit (src) << 8;
  14500. src += 3;
  14501. *right++ = littleEndian24Bit (src) << 8;
  14502. src += 3;
  14503. }
  14504. }
  14505. }
  14506. else
  14507. {
  14508. for (int i = numThisTime; --i >= 0;)
  14509. {
  14510. *left++ = littleEndian24Bit (src) << 8;
  14511. src += 3;
  14512. }
  14513. }
  14514. }
  14515. else
  14516. {
  14517. if (numChannels > 1)
  14518. {
  14519. if (left == 0)
  14520. {
  14521. for (int i = numThisTime; --i >= 0;)
  14522. {
  14523. *right++ = bigEndian24Bit (src) << 8;
  14524. src += 6;
  14525. }
  14526. }
  14527. else if (right == 0)
  14528. {
  14529. for (int i = numThisTime; --i >= 0;)
  14530. {
  14531. src += 3;
  14532. *left++ = bigEndian24Bit (src) << 8;
  14533. src += 3;
  14534. }
  14535. }
  14536. else
  14537. {
  14538. for (int i = numThisTime; --i >= 0;)
  14539. {
  14540. *left++ = bigEndian24Bit (src) << 8;
  14541. src += 3;
  14542. *right++ = bigEndian24Bit (src) << 8;
  14543. src += 3;
  14544. }
  14545. }
  14546. }
  14547. else
  14548. {
  14549. for (int i = numThisTime; --i >= 0;)
  14550. {
  14551. *left++ = bigEndian24Bit (src) << 8;
  14552. src += 3;
  14553. }
  14554. }
  14555. }
  14556. }
  14557. else if (bitsPerSample == 32)
  14558. {
  14559. const unsigned int* src = (const unsigned int*) tempBuffer;
  14560. unsigned int* l = (unsigned int*) left;
  14561. unsigned int* r = (unsigned int*) right;
  14562. if (littleEndian)
  14563. {
  14564. if (numChannels > 1)
  14565. {
  14566. if (l == 0)
  14567. {
  14568. for (int i = numThisTime; --i >= 0;)
  14569. {
  14570. ++src;
  14571. *r++ = swapIfBigEndian (*src++);
  14572. }
  14573. }
  14574. else if (r == 0)
  14575. {
  14576. for (int i = numThisTime; --i >= 0;)
  14577. {
  14578. *l++ = swapIfBigEndian (*src++);
  14579. ++src;
  14580. }
  14581. }
  14582. else
  14583. {
  14584. for (int i = numThisTime; --i >= 0;)
  14585. {
  14586. *l++ = swapIfBigEndian (*src++);
  14587. *r++ = swapIfBigEndian (*src++);
  14588. }
  14589. }
  14590. }
  14591. else
  14592. {
  14593. for (int i = numThisTime; --i >= 0;)
  14594. {
  14595. *l++ = swapIfBigEndian (*src++);
  14596. }
  14597. }
  14598. }
  14599. else
  14600. {
  14601. if (numChannels > 1)
  14602. {
  14603. if (l == 0)
  14604. {
  14605. for (int i = numThisTime; --i >= 0;)
  14606. {
  14607. ++src;
  14608. *r++ = swapIfLittleEndian (*src++);
  14609. }
  14610. }
  14611. else if (r == 0)
  14612. {
  14613. for (int i = numThisTime; --i >= 0;)
  14614. {
  14615. *l++ = swapIfLittleEndian (*src++);
  14616. ++src;
  14617. }
  14618. }
  14619. else
  14620. {
  14621. for (int i = numThisTime; --i >= 0;)
  14622. {
  14623. *l++ = swapIfLittleEndian (*src++);
  14624. *r++ = swapIfLittleEndian (*src++);
  14625. }
  14626. }
  14627. }
  14628. else
  14629. {
  14630. for (int i = numThisTime; --i >= 0;)
  14631. {
  14632. *l++ = swapIfLittleEndian (*src++);
  14633. }
  14634. }
  14635. }
  14636. left = (int*) l;
  14637. right = (int*) r;
  14638. }
  14639. else if (bitsPerSample == 8)
  14640. {
  14641. const char* src = (const char*) tempBuffer;
  14642. if (numChannels > 1)
  14643. {
  14644. if (left == 0)
  14645. {
  14646. for (int i = numThisTime; --i >= 0;)
  14647. {
  14648. *right++ = ((int) *src++) << 24;
  14649. ++src;
  14650. }
  14651. }
  14652. else if (right == 0)
  14653. {
  14654. for (int i = numThisTime; --i >= 0;)
  14655. {
  14656. ++src;
  14657. *left++ = ((int) *src++) << 24;
  14658. }
  14659. }
  14660. else
  14661. {
  14662. for (int i = numThisTime; --i >= 0;)
  14663. {
  14664. *left++ = ((int) *src++) << 24;
  14665. *right++ = ((int) *src++) << 24;
  14666. }
  14667. }
  14668. }
  14669. else
  14670. {
  14671. for (int i = numThisTime; --i >= 0;)
  14672. {
  14673. *left++ = ((int) *src++) << 24;
  14674. }
  14675. }
  14676. }
  14677. startOffsetInDestBuffer += numThisTime;
  14678. numSamples -= numThisTime;
  14679. }
  14680. if (numSamples > 0)
  14681. {
  14682. for (int i = numDestChannels; --i >= 0;)
  14683. if (destSamples[i] != 0)
  14684. zeromem (destSamples[i] + startOffsetInDestBuffer,
  14685. sizeof (int) * numSamples);
  14686. }
  14687. return true;
  14688. }
  14689. juce_UseDebuggingNewOperator
  14690. private:
  14691. AiffAudioFormatReader (const AiffAudioFormatReader&);
  14692. const AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  14693. };
  14694. class AiffAudioFormatWriter : public AudioFormatWriter
  14695. {
  14696. MemoryBlock tempBlock;
  14697. uint32 lengthInSamples, bytesWritten;
  14698. int64 headerPosition;
  14699. bool writeFailed;
  14700. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  14701. const AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  14702. void writeHeader()
  14703. {
  14704. const bool couldSeekOk = output->setPosition (headerPosition);
  14705. (void) couldSeekOk;
  14706. // if this fails, you've given it an output stream that can't seek! It needs
  14707. // to be able to seek back to write the header
  14708. jassert (couldSeekOk);
  14709. const int headerLen = 54;
  14710. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  14711. audioBytes += (audioBytes & 1);
  14712. output->writeInt (chunkName ("FORM"));
  14713. output->writeIntBigEndian (headerLen + audioBytes - 8);
  14714. output->writeInt (chunkName ("AIFF"));
  14715. output->writeInt (chunkName ("COMM"));
  14716. output->writeIntBigEndian (18);
  14717. output->writeShortBigEndian ((short) numChannels);
  14718. output->writeIntBigEndian (lengthInSamples);
  14719. output->writeShortBigEndian ((short) bitsPerSample);
  14720. uint8 sampleRateBytes[10];
  14721. zeromem (sampleRateBytes, 10);
  14722. if (sampleRate <= 1)
  14723. {
  14724. sampleRateBytes[0] = 0x3f;
  14725. sampleRateBytes[1] = 0xff;
  14726. sampleRateBytes[2] = 0x80;
  14727. }
  14728. else
  14729. {
  14730. int mask = 0x40000000;
  14731. sampleRateBytes[0] = 0x40;
  14732. if (sampleRate >= mask)
  14733. {
  14734. jassertfalse
  14735. sampleRateBytes[1] = 0x1d;
  14736. }
  14737. else
  14738. {
  14739. int n = (int) sampleRate;
  14740. int i;
  14741. for (i = 0; i <= 32 ; ++i)
  14742. {
  14743. if ((n & mask) != 0)
  14744. break;
  14745. mask >>= 1;
  14746. }
  14747. n = n << (i + 1);
  14748. sampleRateBytes[1] = (uint8) (29 - i);
  14749. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  14750. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  14751. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  14752. sampleRateBytes[5] = (uint8) (n & 0xff);
  14753. }
  14754. }
  14755. output->write (sampleRateBytes, 10);
  14756. output->writeInt (chunkName ("SSND"));
  14757. output->writeIntBigEndian (audioBytes + 8);
  14758. output->writeInt (0);
  14759. output->writeInt (0);
  14760. jassert (output->getPosition() == headerLen);
  14761. }
  14762. public:
  14763. AiffAudioFormatWriter (OutputStream* out,
  14764. const double sampleRate_,
  14765. const unsigned int chans,
  14766. const int bits)
  14767. : AudioFormatWriter (out,
  14768. aiffFormatName,
  14769. sampleRate_,
  14770. chans,
  14771. bits),
  14772. lengthInSamples (0),
  14773. bytesWritten (0),
  14774. writeFailed (false)
  14775. {
  14776. headerPosition = out->getPosition();
  14777. writeHeader();
  14778. }
  14779. ~AiffAudioFormatWriter()
  14780. {
  14781. if ((bytesWritten & 1) != 0)
  14782. output->writeByte (0);
  14783. writeHeader();
  14784. }
  14785. bool write (const int** data, int numSamples)
  14786. {
  14787. if (writeFailed)
  14788. return false;
  14789. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  14790. tempBlock.ensureSize (bytes, false);
  14791. char* buffer = (char*) tempBlock.getData();
  14792. const int* left = data[0];
  14793. const int* right = data[1];
  14794. if (right == 0)
  14795. right = left;
  14796. if (bitsPerSample == 16)
  14797. {
  14798. short* b = (short*) buffer;
  14799. if (numChannels > 1)
  14800. {
  14801. for (int i = numSamples; --i >= 0;)
  14802. {
  14803. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  14804. *b++ = (short) swapIfLittleEndian ((unsigned short) (*right++ >> 16));
  14805. }
  14806. }
  14807. else
  14808. {
  14809. for (int i = numSamples; --i >= 0;)
  14810. {
  14811. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  14812. }
  14813. }
  14814. }
  14815. else if (bitsPerSample == 24)
  14816. {
  14817. char* b = (char*) buffer;
  14818. if (numChannels > 1)
  14819. {
  14820. for (int i = numSamples; --i >= 0;)
  14821. {
  14822. bigEndian24BitToChars (*left++ >> 8, b);
  14823. b += 3;
  14824. bigEndian24BitToChars (*right++ >> 8, b);
  14825. b += 3;
  14826. }
  14827. }
  14828. else
  14829. {
  14830. for (int i = numSamples; --i >= 0;)
  14831. {
  14832. bigEndian24BitToChars (*left++ >> 8, b);
  14833. b += 3;
  14834. }
  14835. }
  14836. }
  14837. else if (bitsPerSample == 32)
  14838. {
  14839. unsigned int* b = (unsigned int*) buffer;
  14840. if (numChannels > 1)
  14841. {
  14842. for (int i = numSamples; --i >= 0;)
  14843. {
  14844. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  14845. *b++ = swapIfLittleEndian ((unsigned int) *right++);
  14846. }
  14847. }
  14848. else
  14849. {
  14850. for (int i = numSamples; --i >= 0;)
  14851. {
  14852. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  14853. }
  14854. }
  14855. }
  14856. else if (bitsPerSample == 8)
  14857. {
  14858. char* b = (char*)buffer;
  14859. if (numChannels > 1)
  14860. {
  14861. for (int i = numSamples; --i >= 0;)
  14862. {
  14863. *b++ = (char) (*left++ >> 24);
  14864. *b++ = (char) (*right++ >> 24);
  14865. }
  14866. }
  14867. else
  14868. {
  14869. for (int i = numSamples; --i >= 0;)
  14870. {
  14871. *b++ = (char) (*left++ >> 24);
  14872. }
  14873. }
  14874. }
  14875. if (bytesWritten + bytes >= (uint32) 0xfff00000
  14876. || ! output->write (buffer, bytes))
  14877. {
  14878. // failed to write to disk, so let's try writing the header.
  14879. // If it's just run out of disk space, then if it does manage
  14880. // to write the header, we'll still have a useable file..
  14881. writeHeader();
  14882. writeFailed = true;
  14883. return false;
  14884. }
  14885. else
  14886. {
  14887. bytesWritten += bytes;
  14888. lengthInSamples += numSamples;
  14889. return true;
  14890. }
  14891. }
  14892. juce_UseDebuggingNewOperator
  14893. };
  14894. AiffAudioFormat::AiffAudioFormat()
  14895. : AudioFormat (aiffFormatName, (const tchar**) aiffExtensions)
  14896. {
  14897. }
  14898. AiffAudioFormat::~AiffAudioFormat()
  14899. {
  14900. }
  14901. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  14902. {
  14903. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  14904. return Array <int> (rates);
  14905. }
  14906. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  14907. {
  14908. const int depths[] = { 8, 16, 24, 0 };
  14909. return Array <int> (depths);
  14910. }
  14911. bool AiffAudioFormat::canDoStereo()
  14912. {
  14913. return true;
  14914. }
  14915. bool AiffAudioFormat::canDoMono()
  14916. {
  14917. return true;
  14918. }
  14919. #if JUCE_MAC
  14920. bool AiffAudioFormat::canHandleFile (const File& f)
  14921. {
  14922. if (AudioFormat::canHandleFile (f))
  14923. return true;
  14924. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  14925. return type == 'AIFF' || type == 'AIFC'
  14926. || type == 'aiff' || type == 'aifc';
  14927. }
  14928. #endif
  14929. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  14930. const bool deleteStreamIfOpeningFails)
  14931. {
  14932. AiffAudioFormatReader* w = new AiffAudioFormatReader (sourceStream);
  14933. if (w->sampleRate == 0)
  14934. {
  14935. if (! deleteStreamIfOpeningFails)
  14936. w->input = 0;
  14937. deleteAndZero (w);
  14938. }
  14939. return w;
  14940. }
  14941. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  14942. double sampleRate,
  14943. unsigned int chans,
  14944. int bitsPerSample,
  14945. const StringPairArray& /*metadataValues*/,
  14946. int /*qualityOptionIndex*/)
  14947. {
  14948. if (getPossibleBitDepths().contains (bitsPerSample))
  14949. {
  14950. return new AiffAudioFormatWriter (out,
  14951. sampleRate,
  14952. chans,
  14953. bitsPerSample);
  14954. }
  14955. return 0;
  14956. }
  14957. END_JUCE_NAMESPACE
  14958. /********* End of inlined file: juce_AiffAudioFormat.cpp *********/
  14959. /********* Start of inlined file: juce_AudioCDReader.cpp *********/
  14960. BEGIN_JUCE_NAMESPACE
  14961. #if JUCE_MAC
  14962. // Mac version doesn't need any native code because it's all done with files..
  14963. // Windows + Linux versions are in the platform-dependent code sections.
  14964. static void findCDs (OwnedArray<File>& cds)
  14965. {
  14966. File volumes ("/Volumes");
  14967. volumes.findChildFiles (cds, File::findDirectories, false);
  14968. for (int i = cds.size(); --i >= 0;)
  14969. if (! cds[i]->getChildFile (".TOC.plist").exists())
  14970. cds.remove (i);
  14971. }
  14972. const StringArray AudioCDReader::getAvailableCDNames()
  14973. {
  14974. OwnedArray<File> cds;
  14975. findCDs (cds);
  14976. StringArray names;
  14977. for (int i = 0; i < cds.size(); ++i)
  14978. names.add (cds[i]->getFileName());
  14979. return names;
  14980. }
  14981. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  14982. {
  14983. OwnedArray<File> cds;
  14984. findCDs (cds);
  14985. if (cds[index] != 0)
  14986. return new AudioCDReader (*cds[index]);
  14987. else
  14988. return 0;
  14989. }
  14990. AudioCDReader::AudioCDReader (const File& volume)
  14991. : AudioFormatReader (0, "CD Audio"),
  14992. volumeDir (volume),
  14993. currentReaderTrack (-1),
  14994. reader (0)
  14995. {
  14996. sampleRate = 44100.0;
  14997. bitsPerSample = 16;
  14998. numChannels = 2;
  14999. usesFloatingPointData = false;
  15000. refreshTrackLengths();
  15001. }
  15002. AudioCDReader::~AudioCDReader()
  15003. {
  15004. if (reader != 0)
  15005. delete reader;
  15006. }
  15007. static int getTrackNumber (const File& file)
  15008. {
  15009. return file.getFileName()
  15010. .initialSectionContainingOnly (T("0123456789"))
  15011. .getIntValue();
  15012. }
  15013. int AudioCDReader::compareElements (const File* const first, const File* const second) throw()
  15014. {
  15015. const int firstTrack = getTrackNumber (*first);
  15016. const int secondTrack = getTrackNumber (*second);
  15017. jassert (firstTrack > 0 && secondTrack > 0);
  15018. return firstTrack - secondTrack;
  15019. }
  15020. void AudioCDReader::refreshTrackLengths()
  15021. {
  15022. tracks.clear();
  15023. trackStartSamples.clear();
  15024. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, T("*.aiff"));
  15025. tracks.sort (*this);
  15026. AiffAudioFormat format;
  15027. int sample = 0;
  15028. for (int i = 0; i < tracks.size(); ++i)
  15029. {
  15030. trackStartSamples.add (sample);
  15031. FileInputStream* const in = tracks[i]->createInputStream();
  15032. if (in != 0)
  15033. {
  15034. AudioFormatReader* const r = format.createReaderFor (in, true);
  15035. if (r != 0)
  15036. {
  15037. sample += r->lengthInSamples;
  15038. delete r;
  15039. }
  15040. }
  15041. }
  15042. trackStartSamples.add (sample);
  15043. lengthInSamples = sample;
  15044. }
  15045. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15046. int64 startSampleInFile, int numSamples)
  15047. {
  15048. while (numSamples > 0)
  15049. {
  15050. int track = -1;
  15051. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  15052. {
  15053. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  15054. {
  15055. track = i;
  15056. break;
  15057. }
  15058. }
  15059. if (track < 0)
  15060. return false;
  15061. if (track != currentReaderTrack)
  15062. {
  15063. deleteAndZero (reader);
  15064. if (tracks [track] != 0)
  15065. {
  15066. FileInputStream* const in = tracks [track]->createInputStream();
  15067. if (in != 0)
  15068. {
  15069. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  15070. AiffAudioFormat format;
  15071. reader = format.createReaderFor (bin, true);
  15072. if (reader == 0)
  15073. currentReaderTrack = -1;
  15074. else
  15075. currentReaderTrack = track;
  15076. }
  15077. }
  15078. }
  15079. if (reader == 0)
  15080. return false;
  15081. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  15082. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  15083. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  15084. numSamples -= numAvailable;
  15085. startSampleInFile += numAvailable;
  15086. }
  15087. return true;
  15088. }
  15089. bool AudioCDReader::isCDStillPresent() const
  15090. {
  15091. return volumeDir.exists();
  15092. }
  15093. int AudioCDReader::getNumTracks() const
  15094. {
  15095. return tracks.size();
  15096. }
  15097. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  15098. {
  15099. return trackStartSamples [trackNum];
  15100. }
  15101. bool AudioCDReader::isTrackAudio (int trackNum) const
  15102. {
  15103. return tracks [trackNum] != 0;
  15104. }
  15105. void AudioCDReader::enableIndexScanning (bool b)
  15106. {
  15107. // any way to do this on a Mac??
  15108. }
  15109. int AudioCDReader::getLastIndex() const
  15110. {
  15111. return 0;
  15112. }
  15113. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  15114. {
  15115. return Array <int>();
  15116. }
  15117. int AudioCDReader::getCDDBId()
  15118. {
  15119. return 0; //xxx
  15120. }
  15121. #endif
  15122. END_JUCE_NAMESPACE
  15123. /********* End of inlined file: juce_AudioCDReader.cpp *********/
  15124. /********* Start of inlined file: juce_AudioFormat.cpp *********/
  15125. BEGIN_JUCE_NAMESPACE
  15126. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15127. const String& formatName_)
  15128. : sampleRate (0),
  15129. bitsPerSample (0),
  15130. lengthInSamples (0),
  15131. numChannels (0),
  15132. usesFloatingPointData (false),
  15133. input (in),
  15134. formatName (formatName_)
  15135. {
  15136. }
  15137. AudioFormatReader::~AudioFormatReader()
  15138. {
  15139. delete input;
  15140. }
  15141. bool AudioFormatReader::read (int** destSamples,
  15142. int numDestChannels,
  15143. int64 startSampleInSource,
  15144. int numSamplesToRead,
  15145. const bool fillLeftoverChannelsWithCopies)
  15146. {
  15147. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15148. int startOffsetInDestBuffer = 0;
  15149. if (startSampleInSource < 0)
  15150. {
  15151. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15152. for (int i = numDestChannels; --i >= 0;)
  15153. if (destSamples[i] != 0)
  15154. zeromem (destSamples[i], sizeof (int) * silence);
  15155. startOffsetInDestBuffer += silence;
  15156. numSamplesToRead -= silence;
  15157. startSampleInSource = 0;
  15158. }
  15159. if (numSamplesToRead <= 0)
  15160. return true;
  15161. if (! readSamples (destSamples, jmin (numChannels, numDestChannels), startOffsetInDestBuffer,
  15162. startSampleInSource, numSamplesToRead))
  15163. return false;
  15164. if (numDestChannels > (int) numChannels)
  15165. {
  15166. if (fillLeftoverChannelsWithCopies)
  15167. {
  15168. int* lastFullChannel = destSamples[0];
  15169. for (int i = numDestChannels; --i > 0;)
  15170. {
  15171. if (destSamples[i] != 0)
  15172. {
  15173. lastFullChannel = destSamples[i];
  15174. break;
  15175. }
  15176. }
  15177. if (lastFullChannel != 0)
  15178. for (int i = numChannels; i < numDestChannels; ++i)
  15179. if (destSamples[i] != 0)
  15180. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  15181. }
  15182. else
  15183. {
  15184. for (int i = numChannels; i < numDestChannels; ++i)
  15185. if (destSamples[i] != 0)
  15186. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  15187. }
  15188. }
  15189. return true;
  15190. }
  15191. static void findMaxMin (const float* src, const int num,
  15192. float& maxVal, float& minVal)
  15193. {
  15194. float mn = src[0];
  15195. float mx = mn;
  15196. for (int i = 1; i < num; ++i)
  15197. {
  15198. const float s = src[i];
  15199. if (s > mx)
  15200. mx = s;
  15201. if (s < mn)
  15202. mn = s;
  15203. }
  15204. maxVal = mx;
  15205. minVal = mn;
  15206. }
  15207. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  15208. int64 numSamples,
  15209. float& lowestLeft, float& highestLeft,
  15210. float& lowestRight, float& highestRight)
  15211. {
  15212. if (numSamples <= 0)
  15213. {
  15214. lowestLeft = 0;
  15215. lowestRight = 0;
  15216. highestLeft = 0;
  15217. highestRight = 0;
  15218. return;
  15219. }
  15220. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  15221. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  15222. int* tempBuffer[3];
  15223. tempBuffer[0] = (int*) tempSpace.getData();
  15224. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  15225. tempBuffer[2] = 0;
  15226. if (usesFloatingPointData)
  15227. {
  15228. float lmin = 1.0e6;
  15229. float lmax = -lmin;
  15230. float rmin = lmin;
  15231. float rmax = lmax;
  15232. while (numSamples > 0)
  15233. {
  15234. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  15235. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  15236. numSamples -= numToDo;
  15237. float bufmin, bufmax;
  15238. findMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  15239. lmin = jmin (lmin, bufmin);
  15240. lmax = jmax (lmax, bufmax);
  15241. if (numChannels > 1)
  15242. {
  15243. findMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  15244. rmin = jmin (rmin, bufmin);
  15245. rmax = jmax (rmax, bufmax);
  15246. }
  15247. }
  15248. if (numChannels <= 1)
  15249. {
  15250. rmax = lmax;
  15251. rmin = lmin;
  15252. }
  15253. lowestLeft = lmin;
  15254. highestLeft = lmax;
  15255. lowestRight = rmin;
  15256. highestRight = rmax;
  15257. }
  15258. else
  15259. {
  15260. int lmax = INT_MIN;
  15261. int lmin = INT_MAX;
  15262. int rmax = INT_MIN;
  15263. int rmin = INT_MAX;
  15264. while (numSamples > 0)
  15265. {
  15266. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  15267. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  15268. numSamples -= numToDo;
  15269. for (int j = numChannels; --j >= 0;)
  15270. {
  15271. int bufMax = INT_MIN;
  15272. int bufMin = INT_MAX;
  15273. const int* const b = tempBuffer[j];
  15274. for (int i = 0; i < numToDo; ++i)
  15275. {
  15276. const int samp = b[i];
  15277. if (samp < bufMin)
  15278. bufMin = samp;
  15279. if (samp > bufMax)
  15280. bufMax = samp;
  15281. }
  15282. if (j == 0)
  15283. {
  15284. lmax = jmax (lmax, bufMax);
  15285. lmin = jmin (lmin, bufMin);
  15286. }
  15287. else
  15288. {
  15289. rmax = jmax (rmax, bufMax);
  15290. rmin = jmin (rmin, bufMin);
  15291. }
  15292. }
  15293. }
  15294. if (numChannels <= 1)
  15295. {
  15296. rmax = lmax;
  15297. rmin = lmin;
  15298. }
  15299. lowestLeft = lmin / (float)INT_MAX;
  15300. highestLeft = lmax / (float)INT_MAX;
  15301. lowestRight = rmin / (float)INT_MAX;
  15302. highestRight = rmax / (float)INT_MAX;
  15303. }
  15304. }
  15305. int64 AudioFormatReader::searchForLevel (int64 startSample,
  15306. int64 numSamplesToSearch,
  15307. const double magnitudeRangeMinimum,
  15308. const double magnitudeRangeMaximum,
  15309. const int minimumConsecutiveSamples)
  15310. {
  15311. if (numSamplesToSearch == 0)
  15312. return -1;
  15313. const int bufferSize = 4096;
  15314. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  15315. int* tempBuffer[3];
  15316. tempBuffer[0] = (int*) tempSpace.getData();
  15317. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  15318. tempBuffer[2] = 0;
  15319. int consecutive = 0;
  15320. int64 firstMatchPos = -1;
  15321. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  15322. const double doubleMin = jlimit (0.0, (double) INT_MAX, magnitudeRangeMinimum * INT_MAX);
  15323. const double doubleMax = jlimit (doubleMin, (double) INT_MAX, magnitudeRangeMaximum * INT_MAX);
  15324. const int intMagnitudeRangeMinimum = roundDoubleToInt (doubleMin);
  15325. const int intMagnitudeRangeMaximum = roundDoubleToInt (doubleMax);
  15326. while (numSamplesToSearch != 0)
  15327. {
  15328. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  15329. int64 bufferStart = startSample;
  15330. if (numSamplesToSearch < 0)
  15331. bufferStart -= numThisTime;
  15332. if (bufferStart >= (int) lengthInSamples)
  15333. break;
  15334. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  15335. int num = numThisTime;
  15336. while (--num >= 0)
  15337. {
  15338. if (numSamplesToSearch < 0)
  15339. --startSample;
  15340. bool matches = false;
  15341. const int index = (int) (startSample - bufferStart);
  15342. if (usesFloatingPointData)
  15343. {
  15344. const float sample1 = fabsf (((float*) tempBuffer[0]) [index]);
  15345. if (sample1 >= magnitudeRangeMinimum
  15346. && sample1 <= magnitudeRangeMaximum)
  15347. {
  15348. matches = true;
  15349. }
  15350. else if (numChannels > 1)
  15351. {
  15352. const float sample2 = fabsf (((float*) tempBuffer[1]) [index]);
  15353. matches = (sample2 >= magnitudeRangeMinimum
  15354. && sample2 <= magnitudeRangeMaximum);
  15355. }
  15356. }
  15357. else
  15358. {
  15359. const int sample1 = abs (tempBuffer[0] [index]);
  15360. if (sample1 >= intMagnitudeRangeMinimum
  15361. && sample1 <= intMagnitudeRangeMaximum)
  15362. {
  15363. matches = true;
  15364. }
  15365. else if (numChannels > 1)
  15366. {
  15367. const int sample2 = abs (tempBuffer[1][index]);
  15368. matches = (sample2 >= intMagnitudeRangeMinimum
  15369. && sample2 <= intMagnitudeRangeMaximum);
  15370. }
  15371. }
  15372. if (matches)
  15373. {
  15374. if (firstMatchPos < 0)
  15375. firstMatchPos = startSample;
  15376. if (++consecutive >= minimumConsecutiveSamples)
  15377. {
  15378. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  15379. return -1;
  15380. return firstMatchPos;
  15381. }
  15382. }
  15383. else
  15384. {
  15385. consecutive = 0;
  15386. firstMatchPos = -1;
  15387. }
  15388. if (numSamplesToSearch > 0)
  15389. ++startSample;
  15390. }
  15391. if (numSamplesToSearch > 0)
  15392. numSamplesToSearch -= numThisTime;
  15393. else
  15394. numSamplesToSearch += numThisTime;
  15395. }
  15396. return -1;
  15397. }
  15398. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  15399. const String& formatName_,
  15400. const double rate,
  15401. const unsigned int numChannels_,
  15402. const unsigned int bitsPerSample_)
  15403. : sampleRate (rate),
  15404. numChannels (numChannels_),
  15405. bitsPerSample (bitsPerSample_),
  15406. usesFloatingPointData (false),
  15407. output (out),
  15408. formatName (formatName_)
  15409. {
  15410. }
  15411. AudioFormatWriter::~AudioFormatWriter()
  15412. {
  15413. delete output;
  15414. }
  15415. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  15416. int64 startSample,
  15417. int64 numSamplesToRead)
  15418. {
  15419. const int bufferSize = 16384;
  15420. const int maxChans = 128;
  15421. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  15422. int* buffers [maxChans];
  15423. for (int i = maxChans; --i >= 0;)
  15424. buffers[i] = 0;
  15425. if (numSamplesToRead < 0)
  15426. numSamplesToRead = reader.lengthInSamples;
  15427. while (numSamplesToRead > 0)
  15428. {
  15429. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  15430. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  15431. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  15432. if (! reader.read (buffers, maxChans, startSample, numToDo, false))
  15433. return false;
  15434. if (reader.usesFloatingPointData != isFloatingPoint())
  15435. {
  15436. int** bufferChan = buffers;
  15437. while (*bufferChan != 0)
  15438. {
  15439. int* b = *bufferChan++;
  15440. if (isFloatingPoint())
  15441. {
  15442. // int -> float
  15443. const double factor = 1.0 / INT_MAX;
  15444. for (int i = 0; i < numToDo; ++i)
  15445. ((float*)b)[i] = (float) (factor * b[i]);
  15446. }
  15447. else
  15448. {
  15449. // float -> int
  15450. for (int i = 0; i < numToDo; ++i)
  15451. {
  15452. const double samp = *(const float*) b;
  15453. if (samp <= -1.0)
  15454. *b++ = INT_MIN;
  15455. else if (samp >= 1.0)
  15456. *b++ = INT_MAX;
  15457. else
  15458. *b++ = roundDoubleToInt (INT_MAX * samp);
  15459. }
  15460. }
  15461. }
  15462. }
  15463. if (! write ((const int**) buffers, numToDo))
  15464. return false;
  15465. numSamplesToRead -= numToDo;
  15466. startSample += numToDo;
  15467. }
  15468. return true;
  15469. }
  15470. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  15471. int numSamplesToRead,
  15472. const int samplesPerBlock)
  15473. {
  15474. const int maxChans = 128;
  15475. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  15476. int* buffers [maxChans];
  15477. while (numSamplesToRead > 0)
  15478. {
  15479. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  15480. AudioSourceChannelInfo info;
  15481. info.buffer = &tempBuffer;
  15482. info.startSample = 0;
  15483. info.numSamples = numToDo;
  15484. info.clearActiveBufferRegion();
  15485. source.getNextAudioBlock (info);
  15486. int i;
  15487. for (i = maxChans; --i >= 0;)
  15488. buffers[i] = 0;
  15489. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  15490. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  15491. if (! isFloatingPoint())
  15492. {
  15493. int** bufferChan = buffers;
  15494. while (*bufferChan != 0)
  15495. {
  15496. int* b = *bufferChan++;
  15497. // float -> int
  15498. for (int j = numToDo; --j >= 0;)
  15499. {
  15500. const double samp = *(const float*) b;
  15501. if (samp <= -1.0)
  15502. *b++ = INT_MIN;
  15503. else if (samp >= 1.0)
  15504. *b++ = INT_MAX;
  15505. else
  15506. *b++ = roundDoubleToInt (INT_MAX * samp);
  15507. }
  15508. }
  15509. }
  15510. if (! write ((const int**) buffers, numToDo))
  15511. return false;
  15512. numSamplesToRead -= numToDo;
  15513. }
  15514. return true;
  15515. }
  15516. AudioFormat::AudioFormat (const String& name,
  15517. const tchar** const extensions)
  15518. : formatName (name),
  15519. fileExtensions (extensions)
  15520. {
  15521. }
  15522. AudioFormat::~AudioFormat()
  15523. {
  15524. }
  15525. const String& AudioFormat::getFormatName() const
  15526. {
  15527. return formatName;
  15528. }
  15529. const StringArray& AudioFormat::getFileExtensions() const
  15530. {
  15531. return fileExtensions;
  15532. }
  15533. bool AudioFormat::canHandleFile (const File& f)
  15534. {
  15535. for (int i = 0; i < fileExtensions.size(); ++i)
  15536. if (f.hasFileExtension (fileExtensions[i]))
  15537. return true;
  15538. return false;
  15539. }
  15540. bool AudioFormat::isCompressed()
  15541. {
  15542. return false;
  15543. }
  15544. const StringArray AudioFormat::getQualityOptions()
  15545. {
  15546. return StringArray();
  15547. }
  15548. END_JUCE_NAMESPACE
  15549. /********* End of inlined file: juce_AudioFormat.cpp *********/
  15550. /********* Start of inlined file: juce_AudioFormatManager.cpp *********/
  15551. BEGIN_JUCE_NAMESPACE
  15552. AudioFormatManager::AudioFormatManager()
  15553. : knownFormats (4),
  15554. defaultFormatIndex (0)
  15555. {
  15556. }
  15557. AudioFormatManager::~AudioFormatManager()
  15558. {
  15559. clearFormats();
  15560. clearSingletonInstance();
  15561. }
  15562. juce_ImplementSingleton (AudioFormatManager);
  15563. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  15564. const bool makeThisTheDefaultFormat)
  15565. {
  15566. jassert (newFormat != 0);
  15567. if (newFormat != 0)
  15568. {
  15569. #ifdef JUCE_DEBUG
  15570. for (int i = getNumKnownFormats(); --i >= 0;)
  15571. {
  15572. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  15573. {
  15574. jassertfalse // trying to add the same format twice!
  15575. }
  15576. }
  15577. #endif
  15578. if (makeThisTheDefaultFormat)
  15579. defaultFormatIndex = knownFormats.size();
  15580. knownFormats.add (newFormat);
  15581. }
  15582. }
  15583. void AudioFormatManager::registerBasicFormats()
  15584. {
  15585. #if JUCE_MAC
  15586. registerFormat (new AiffAudioFormat(), true);
  15587. registerFormat (new WavAudioFormat(), false);
  15588. #else
  15589. registerFormat (new WavAudioFormat(), true);
  15590. registerFormat (new AiffAudioFormat(), false);
  15591. #endif
  15592. #if JUCE_USE_FLAC
  15593. registerFormat (new FlacAudioFormat(), false);
  15594. #endif
  15595. #if JUCE_USE_OGGVORBIS
  15596. registerFormat (new OggVorbisAudioFormat(), false);
  15597. #endif
  15598. }
  15599. void AudioFormatManager::clearFormats()
  15600. {
  15601. for (int i = getNumKnownFormats(); --i >= 0;)
  15602. {
  15603. AudioFormat* const af = getKnownFormat(i);
  15604. delete af;
  15605. }
  15606. knownFormats.clear();
  15607. defaultFormatIndex = 0;
  15608. }
  15609. int AudioFormatManager::getNumKnownFormats() const
  15610. {
  15611. return knownFormats.size();
  15612. }
  15613. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  15614. {
  15615. return (AudioFormat*) knownFormats [index];
  15616. }
  15617. AudioFormat* AudioFormatManager::getDefaultFormat() const
  15618. {
  15619. return getKnownFormat (defaultFormatIndex);
  15620. }
  15621. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  15622. {
  15623. String e (fileExtension);
  15624. if (! e.startsWithChar (T('.')))
  15625. e = T(".") + e;
  15626. for (int i = 0; i < getNumKnownFormats(); ++i)
  15627. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  15628. return getKnownFormat(i);
  15629. return 0;
  15630. }
  15631. const String AudioFormatManager::getWildcardForAllFormats() const
  15632. {
  15633. StringArray allExtensions;
  15634. int i;
  15635. for (i = 0; i < getNumKnownFormats(); ++i)
  15636. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  15637. allExtensions.trim();
  15638. allExtensions.removeEmptyStrings();
  15639. String s;
  15640. for (i = 0; i < allExtensions.size(); ++i)
  15641. {
  15642. s << T('*');
  15643. if (! allExtensions[i].startsWithChar (T('.')))
  15644. s << T('.');
  15645. s << allExtensions[i];
  15646. if (i < allExtensions.size() - 1)
  15647. s << T(';');
  15648. }
  15649. return s;
  15650. }
  15651. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  15652. {
  15653. // you need to actually register some formats before the manager can
  15654. // use them to open a file!
  15655. jassert (knownFormats.size() > 0);
  15656. for (int i = 0; i < getNumKnownFormats(); ++i)
  15657. {
  15658. AudioFormat* const af = getKnownFormat(i);
  15659. if (af->canHandleFile (file))
  15660. {
  15661. InputStream* const in = file.createInputStream();
  15662. if (in != 0)
  15663. {
  15664. AudioFormatReader* const r = af->createReaderFor (in, true);
  15665. if (r != 0)
  15666. return r;
  15667. }
  15668. }
  15669. }
  15670. return 0;
  15671. }
  15672. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* in)
  15673. {
  15674. // you need to actually register some formats before the manager can
  15675. // use them to open a file!
  15676. jassert (knownFormats.size() > 0);
  15677. if (in != 0)
  15678. {
  15679. const int64 originalStreamPos = in->getPosition();
  15680. for (int i = 0; i < getNumKnownFormats(); ++i)
  15681. {
  15682. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  15683. if (r != 0)
  15684. return r;
  15685. in->setPosition (originalStreamPos);
  15686. // the stream that is passed-in must be capable of being repositioned so
  15687. // that all the formats can have a go at opening it.
  15688. jassert (in->getPosition() == originalStreamPos);
  15689. }
  15690. delete in;
  15691. }
  15692. return 0;
  15693. }
  15694. END_JUCE_NAMESPACE
  15695. /********* End of inlined file: juce_AudioFormatManager.cpp *********/
  15696. /********* Start of inlined file: juce_AudioSubsectionReader.cpp *********/
  15697. BEGIN_JUCE_NAMESPACE
  15698. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  15699. const int64 startSample_,
  15700. const int64 length_,
  15701. const bool deleteSourceWhenDeleted_)
  15702. : AudioFormatReader (0, source_->getFormatName()),
  15703. source (source_),
  15704. startSample (startSample_),
  15705. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  15706. {
  15707. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  15708. sampleRate = source->sampleRate;
  15709. bitsPerSample = source->bitsPerSample;
  15710. lengthInSamples = length;
  15711. numChannels = source->numChannels;
  15712. usesFloatingPointData = source->usesFloatingPointData;
  15713. }
  15714. AudioSubsectionReader::~AudioSubsectionReader()
  15715. {
  15716. if (deleteSourceWhenDeleted)
  15717. delete source;
  15718. }
  15719. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15720. int64 startSampleInFile, int numSamples)
  15721. {
  15722. if (startSampleInFile + numSamples > length)
  15723. {
  15724. for (int i = numDestChannels; --i >= 0;)
  15725. if (destSamples[i] != 0)
  15726. zeromem (destSamples[i], sizeof (int) * numSamples);
  15727. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  15728. if (numSamples <= 0)
  15729. return true;
  15730. }
  15731. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  15732. startSampleInFile + startSample, numSamples);
  15733. }
  15734. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  15735. int64 numSamples,
  15736. float& lowestLeft,
  15737. float& highestLeft,
  15738. float& lowestRight,
  15739. float& highestRight)
  15740. {
  15741. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  15742. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  15743. source->readMaxLevels (startSampleInFile + startSample,
  15744. numSamples,
  15745. lowestLeft,
  15746. highestLeft,
  15747. lowestRight,
  15748. highestRight);
  15749. }
  15750. END_JUCE_NAMESPACE
  15751. /********* End of inlined file: juce_AudioSubsectionReader.cpp *********/
  15752. /********* Start of inlined file: juce_AudioThumbnail.cpp *********/
  15753. BEGIN_JUCE_NAMESPACE
  15754. const int timeBeforeDeletingReader = 2000;
  15755. struct AudioThumbnailDataFormat
  15756. {
  15757. char thumbnailMagic[4];
  15758. int samplesPerThumbSample;
  15759. int64 totalSamples; // source samples
  15760. int64 numFinishedSamples; // source samples
  15761. int numThumbnailSamples;
  15762. int numChannels;
  15763. int sampleRate;
  15764. char future[16];
  15765. char data[1];
  15766. };
  15767. #if JUCE_BIG_ENDIAN
  15768. static void swap (int& n) { n = (int) swapByteOrder ((uint32) n); }
  15769. static void swap (int64& n) { n = (int64) swapByteOrder ((uint64) n); }
  15770. #endif
  15771. static void swapEndiannessIfNeeded (AudioThumbnailDataFormat* const d)
  15772. {
  15773. (void) d;
  15774. #if JUCE_BIG_ENDIAN
  15775. swap (d->samplesPerThumbSample);
  15776. swap (d->totalSamples);
  15777. swap (d->numFinishedSamples);
  15778. swap (d->numThumbnailSamples);
  15779. swap (d->numChannels);
  15780. swap (d->sampleRate);
  15781. #endif
  15782. }
  15783. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  15784. AudioFormatManager& formatManagerToUse_,
  15785. AudioThumbnailCache& cacheToUse)
  15786. : formatManagerToUse (formatManagerToUse_),
  15787. cache (cacheToUse),
  15788. source (0),
  15789. reader (0),
  15790. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  15791. {
  15792. clear();
  15793. }
  15794. AudioThumbnail::~AudioThumbnail()
  15795. {
  15796. cache.removeThumbnail (this);
  15797. const ScopedLock sl (readerLock);
  15798. deleteAndZero (reader);
  15799. delete source;
  15800. }
  15801. void AudioThumbnail::setSource (InputSource* const newSource)
  15802. {
  15803. cache.removeThumbnail (this);
  15804. timerCallback(); // stops the timer and deletes the reader
  15805. delete source;
  15806. source = newSource;
  15807. clear();
  15808. if (newSource != 0
  15809. && ! (cache.loadThumb (*this, newSource->hashCode())
  15810. && isFullyLoaded()))
  15811. {
  15812. {
  15813. const ScopedLock sl (readerLock);
  15814. reader = createReader();
  15815. }
  15816. if (reader != 0)
  15817. {
  15818. initialiseFromAudioFile (*reader);
  15819. cache.addThumbnail (this);
  15820. }
  15821. }
  15822. sendChangeMessage (this);
  15823. }
  15824. bool AudioThumbnail::useTimeSlice()
  15825. {
  15826. const ScopedLock sl (readerLock);
  15827. if (isFullyLoaded())
  15828. {
  15829. if (reader != 0)
  15830. startTimer (timeBeforeDeletingReader);
  15831. cache.removeThumbnail (this);
  15832. return false;
  15833. }
  15834. if (reader == 0)
  15835. reader = createReader();
  15836. if (reader != 0)
  15837. {
  15838. readNextBlockFromAudioFile (*reader);
  15839. stopTimer();
  15840. sendChangeMessage (this);
  15841. const bool justFinished = isFullyLoaded();
  15842. if (justFinished)
  15843. cache.storeThumb (*this, source->hashCode());
  15844. return ! justFinished;
  15845. }
  15846. return false;
  15847. }
  15848. AudioFormatReader* AudioThumbnail::createReader() const
  15849. {
  15850. if (source != 0)
  15851. {
  15852. InputStream* const audioFileStream = source->createInputStream();
  15853. if (audioFileStream != 0)
  15854. return formatManagerToUse.createReaderFor (audioFileStream);
  15855. }
  15856. return 0;
  15857. }
  15858. void AudioThumbnail::timerCallback()
  15859. {
  15860. stopTimer();
  15861. const ScopedLock sl (readerLock);
  15862. deleteAndZero (reader);
  15863. }
  15864. void AudioThumbnail::clear()
  15865. {
  15866. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  15867. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  15868. d->thumbnailMagic[0] = 'j';
  15869. d->thumbnailMagic[1] = 'a';
  15870. d->thumbnailMagic[2] = 't';
  15871. d->thumbnailMagic[3] = 'm';
  15872. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  15873. d->totalSamples = 0;
  15874. d->numFinishedSamples = 0;
  15875. d->numThumbnailSamples = 0;
  15876. d->numChannels = 0;
  15877. d->sampleRate = 0;
  15878. numSamplesCached = 0;
  15879. cacheNeedsRefilling = true;
  15880. }
  15881. void AudioThumbnail::loadFrom (InputStream& input)
  15882. {
  15883. data.setSize (0);
  15884. input.readIntoMemoryBlock (data);
  15885. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  15886. swapEndiannessIfNeeded (d);
  15887. if (! (d->thumbnailMagic[0] == 'j'
  15888. && d->thumbnailMagic[1] == 'a'
  15889. && d->thumbnailMagic[2] == 't'
  15890. && d->thumbnailMagic[3] == 'm'))
  15891. {
  15892. clear();
  15893. }
  15894. numSamplesCached = 0;
  15895. cacheNeedsRefilling = true;
  15896. }
  15897. void AudioThumbnail::saveTo (OutputStream& output) const
  15898. {
  15899. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  15900. swapEndiannessIfNeeded (d);
  15901. output.write (data.getData(), data.getSize());
  15902. swapEndiannessIfNeeded (d);
  15903. }
  15904. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& reader)
  15905. {
  15906. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  15907. d->totalSamples = reader.lengthInSamples;
  15908. d->numChannels = jmin (2, reader.numChannels);
  15909. d->numFinishedSamples = 0;
  15910. d->sampleRate = roundDoubleToInt (reader.sampleRate);
  15911. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  15912. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  15913. d = (AudioThumbnailDataFormat*) data.getData();
  15914. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  15915. return d->totalSamples > 0;
  15916. }
  15917. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& reader)
  15918. {
  15919. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  15920. if (d->numFinishedSamples < d->totalSamples)
  15921. {
  15922. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  15923. generateSection (reader,
  15924. d->numFinishedSamples,
  15925. numToDo);
  15926. d->numFinishedSamples += numToDo;
  15927. }
  15928. cacheNeedsRefilling = true;
  15929. return (d->numFinishedSamples < d->totalSamples);
  15930. }
  15931. int AudioThumbnail::getNumChannels() const throw()
  15932. {
  15933. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  15934. jassert (d != 0);
  15935. return d->numChannels;
  15936. }
  15937. double AudioThumbnail::getTotalLength() const throw()
  15938. {
  15939. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  15940. jassert (d != 0);
  15941. if (d->sampleRate > 0)
  15942. return d->totalSamples / (double)d->sampleRate;
  15943. else
  15944. return 0.0;
  15945. }
  15946. void AudioThumbnail::generateSection (AudioFormatReader& reader,
  15947. int64 startSample,
  15948. int numSamples)
  15949. {
  15950. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  15951. jassert (d != 0);
  15952. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  15953. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  15954. char* l = getChannelData (0);
  15955. char* r = getChannelData (1);
  15956. for (int i = firstDataPos; i < lastDataPos; ++i)
  15957. {
  15958. const int sourceStart = i * d->samplesPerThumbSample;
  15959. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  15960. float lowestLeft, highestLeft, lowestRight, highestRight;
  15961. reader.readMaxLevels (sourceStart,
  15962. sourceEnd - sourceStart,
  15963. lowestLeft,
  15964. highestLeft,
  15965. lowestRight,
  15966. highestRight);
  15967. int n = i * 2;
  15968. if (r != 0)
  15969. {
  15970. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  15971. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  15972. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  15973. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  15974. }
  15975. else
  15976. {
  15977. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  15978. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  15979. }
  15980. }
  15981. }
  15982. char* AudioThumbnail::getChannelData (int channel) const
  15983. {
  15984. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  15985. jassert (d != 0);
  15986. if (channel >= 0 && channel < d->numChannels)
  15987. return d->data + (channel * 2 * d->numThumbnailSamples);
  15988. return 0;
  15989. }
  15990. bool AudioThumbnail::isFullyLoaded() const throw()
  15991. {
  15992. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  15993. jassert (d != 0);
  15994. return d->numFinishedSamples >= d->totalSamples;
  15995. }
  15996. void AudioThumbnail::refillCache (const int numSamples,
  15997. double startTime,
  15998. const double timePerPixel)
  15999. {
  16000. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16001. jassert (d != 0);
  16002. if (numSamples <= 0
  16003. || timePerPixel <= 0.0
  16004. || d->sampleRate <= 0)
  16005. {
  16006. numSamplesCached = 0;
  16007. cacheNeedsRefilling = true;
  16008. return;
  16009. }
  16010. if (numSamples == numSamplesCached
  16011. && numChannelsCached == d->numChannels
  16012. && startTime == cachedStart
  16013. && timePerPixel == cachedTimePerPixel
  16014. && ! cacheNeedsRefilling)
  16015. {
  16016. return;
  16017. }
  16018. numSamplesCached = numSamples;
  16019. numChannelsCached = d->numChannels;
  16020. cachedStart = startTime;
  16021. cachedTimePerPixel = timePerPixel;
  16022. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16023. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16024. const ScopedLock sl (readerLock);
  16025. cacheNeedsRefilling = false;
  16026. if (needExtraDetail && reader == 0)
  16027. reader = createReader();
  16028. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16029. {
  16030. startTimer (timeBeforeDeletingReader);
  16031. char* cacheData = (char*) cachedLevels.getData();
  16032. int sample = roundDoubleToInt (startTime * d->sampleRate);
  16033. for (int i = numSamples; --i >= 0;)
  16034. {
  16035. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * d->sampleRate);
  16036. if (sample >= 0)
  16037. {
  16038. if (sample >= reader->lengthInSamples)
  16039. break;
  16040. float lmin, lmax, rmin, rmax;
  16041. reader->readMaxLevels (sample,
  16042. jmax (1, nextSample - sample),
  16043. lmin, lmax, rmin, rmax);
  16044. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16045. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16046. if (numChannelsCached > 1)
  16047. {
  16048. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16049. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16050. }
  16051. cacheData += 2 * numChannelsCached;
  16052. }
  16053. startTime += timePerPixel;
  16054. sample = nextSample;
  16055. }
  16056. }
  16057. else
  16058. {
  16059. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16060. {
  16061. char* const data = getChannelData (channelNum);
  16062. char* cacheData = ((char*) cachedLevels.getData()) + channelNum * 2;
  16063. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16064. startTime = cachedStart;
  16065. int sample = roundDoubleToInt (startTime * timeToThumbSampleFactor);
  16066. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16067. for (int i = numSamples; --i >= 0;)
  16068. {
  16069. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16070. if (sample >= 0 && data != 0)
  16071. {
  16072. char mx = -128;
  16073. char mn = 127;
  16074. while (sample <= nextSample)
  16075. {
  16076. if (sample >= numFinished)
  16077. break;
  16078. const int n = sample << 1;
  16079. const char sampMin = data [n];
  16080. const char sampMax = data [n + 1];
  16081. if (sampMin < mn)
  16082. mn = sampMin;
  16083. if (sampMax > mx)
  16084. mx = sampMax;
  16085. ++sample;
  16086. }
  16087. if (mn <= mx)
  16088. {
  16089. cacheData[0] = mn;
  16090. cacheData[1] = mx;
  16091. }
  16092. else
  16093. {
  16094. cacheData[0] = 1;
  16095. cacheData[1] = 0;
  16096. }
  16097. }
  16098. else
  16099. {
  16100. cacheData[0] = 1;
  16101. cacheData[1] = 0;
  16102. }
  16103. cacheData += numChannelsCached * 2;
  16104. startTime += timePerPixel;
  16105. sample = nextSample;
  16106. }
  16107. }
  16108. }
  16109. }
  16110. void AudioThumbnail::drawChannel (Graphics& g,
  16111. int x, int y, int w, int h,
  16112. double startTime,
  16113. double endTime,
  16114. int channelNum,
  16115. const float verticalZoomFactor)
  16116. {
  16117. refillCache (w, startTime, (endTime - startTime) / w);
  16118. if (numSamplesCached >= w
  16119. && channelNum >= 0
  16120. && channelNum < numChannelsCached)
  16121. {
  16122. const float topY = (float) y;
  16123. const float bottomY = topY + h;
  16124. const float midY = topY + h * 0.5f;
  16125. const float vscale = verticalZoomFactor * h / 256.0f;
  16126. const Rectangle clip (g.getClipBounds());
  16127. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16128. w -= skipLeft;
  16129. x += skipLeft;
  16130. const char* cacheData = ((const char*) cachedLevels.getData())
  16131. + (channelNum << 1)
  16132. + skipLeft * (numChannelsCached << 1);
  16133. while (--w >= 0)
  16134. {
  16135. const char mn = cacheData[0];
  16136. const char mx = cacheData[1];
  16137. cacheData += numChannelsCached << 1;
  16138. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16139. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16140. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16141. ++x;
  16142. if (x >= clip.getRight())
  16143. break;
  16144. }
  16145. }
  16146. }
  16147. END_JUCE_NAMESPACE
  16148. /********* End of inlined file: juce_AudioThumbnail.cpp *********/
  16149. /********* Start of inlined file: juce_AudioThumbnailCache.cpp *********/
  16150. BEGIN_JUCE_NAMESPACE
  16151. struct ThumbnailCacheEntry
  16152. {
  16153. int64 hash;
  16154. uint32 lastUsed;
  16155. MemoryBlock data;
  16156. juce_UseDebuggingNewOperator
  16157. };
  16158. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16159. : TimeSliceThread (T("thumb cache")),
  16160. maxNumThumbsToStore (maxNumThumbsToStore_)
  16161. {
  16162. startThread (2);
  16163. }
  16164. AudioThumbnailCache::~AudioThumbnailCache()
  16165. {
  16166. }
  16167. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16168. {
  16169. for (int i = thumbs.size(); --i >= 0;)
  16170. {
  16171. if (thumbs[i]->hash == hashCode)
  16172. {
  16173. MemoryInputStream in ((const char*) thumbs[i]->data.getData(),
  16174. thumbs[i]->data.getSize(),
  16175. false);
  16176. thumb.loadFrom (in);
  16177. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  16178. return true;
  16179. }
  16180. }
  16181. return false;
  16182. }
  16183. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  16184. const int64 hashCode)
  16185. {
  16186. MemoryOutputStream out;
  16187. thumb.saveTo (out);
  16188. ThumbnailCacheEntry* te = 0;
  16189. for (int i = thumbs.size(); --i >= 0;)
  16190. {
  16191. if (thumbs[i]->hash == hashCode)
  16192. {
  16193. te = thumbs[i];
  16194. break;
  16195. }
  16196. }
  16197. if (te == 0)
  16198. {
  16199. te = new ThumbnailCacheEntry();
  16200. te->hash = hashCode;
  16201. if (thumbs.size() < maxNumThumbsToStore)
  16202. {
  16203. thumbs.add (te);
  16204. }
  16205. else
  16206. {
  16207. int oldest = 0;
  16208. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  16209. int i;
  16210. for (i = thumbs.size(); --i >= 0;)
  16211. if (thumbs[i]->lastUsed < oldestTime)
  16212. oldest = i;
  16213. thumbs.set (i, te);
  16214. }
  16215. }
  16216. te->lastUsed = Time::getMillisecondCounter();
  16217. te->data.setSize (0);
  16218. te->data.append (out.getData(), out.getDataSize());
  16219. }
  16220. void AudioThumbnailCache::clear()
  16221. {
  16222. thumbs.clear();
  16223. }
  16224. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  16225. {
  16226. addTimeSliceClient (thumb);
  16227. }
  16228. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  16229. {
  16230. removeTimeSliceClient (thumb);
  16231. }
  16232. END_JUCE_NAMESPACE
  16233. /********* End of inlined file: juce_AudioThumbnailCache.cpp *********/
  16234. /********* Start of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  16235. #if JUCE_QUICKTIME
  16236. #if ! defined (_WIN32)
  16237. #include <QuickTime/Movies.h>
  16238. #include <QuickTime/QTML.h>
  16239. #include <QuickTime/QuickTimeComponents.h>
  16240. #include <QuickTime/MediaHandlers.h>
  16241. #include <QuickTime/ImageCodec.h>
  16242. #else
  16243. #ifdef _MSC_VER
  16244. #pragma warning (push)
  16245. #pragma warning (disable : 4100)
  16246. #endif
  16247. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  16248. add its header directory to your include path.
  16249. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  16250. flag in juce_Config.h
  16251. */
  16252. #include <Movies.h>
  16253. #include <QTML.h>
  16254. #include <QuickTimeComponents.h>
  16255. #include <MediaHandlers.h>
  16256. #include <ImageCodec.h>
  16257. #ifdef _MSC_VER
  16258. #pragma warning (pop)
  16259. #endif
  16260. #endif
  16261. #if ! (JUCE_MAC && JUCE_64BIT)
  16262. BEGIN_JUCE_NAMESPACE
  16263. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  16264. #define quickTimeFormatName TRANS("QuickTime file")
  16265. static const tchar* const quickTimeExtensions[] = { T(".mov"), T(".mp3"), T(".mp4"), 0 };
  16266. class QTAudioReader : public AudioFormatReader
  16267. {
  16268. public:
  16269. QTAudioReader (InputStream* const input_, const int trackNum_)
  16270. : AudioFormatReader (input_, quickTimeFormatName),
  16271. ok (false),
  16272. movie (0),
  16273. trackNum (trackNum_),
  16274. extractor (0),
  16275. lastSampleRead (0),
  16276. lastThreadId (0),
  16277. dataHandle (0)
  16278. {
  16279. bufferList = (AudioBufferList*) juce_calloc (256);
  16280. #ifdef WIN32
  16281. if (InitializeQTML (0) != noErr)
  16282. return;
  16283. #endif
  16284. if (EnterMovies() != noErr)
  16285. return;
  16286. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  16287. if (! opened)
  16288. return;
  16289. {
  16290. const int numTracks = GetMovieTrackCount (movie);
  16291. int trackCount = 0;
  16292. for (int i = 1; i <= numTracks; ++i)
  16293. {
  16294. track = GetMovieIndTrack (movie, i);
  16295. media = GetTrackMedia (track);
  16296. OSType mediaType;
  16297. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  16298. if (mediaType == SoundMediaType
  16299. && trackCount++ == trackNum_)
  16300. {
  16301. ok = true;
  16302. break;
  16303. }
  16304. }
  16305. }
  16306. if (! ok)
  16307. return;
  16308. ok = false;
  16309. lengthInSamples = GetMediaDecodeDuration (media);
  16310. usesFloatingPointData = false;
  16311. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  16312. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  16313. / GetMediaTimeScale (media);
  16314. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  16315. unsigned long output_layout_size;
  16316. err = MovieAudioExtractionGetPropertyInfo (extractor,
  16317. kQTPropertyClass_MovieAudioExtraction_Audio,
  16318. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16319. 0, &output_layout_size, 0);
  16320. if (err != noErr)
  16321. return;
  16322. AudioChannelLayout* const qt_audio_channel_layout
  16323. = (AudioChannelLayout*) juce_calloc (output_layout_size);
  16324. err = MovieAudioExtractionGetProperty (extractor,
  16325. kQTPropertyClass_MovieAudioExtraction_Audio,
  16326. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16327. output_layout_size, qt_audio_channel_layout, 0);
  16328. qt_audio_channel_layout->mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  16329. err = MovieAudioExtractionSetProperty (extractor,
  16330. kQTPropertyClass_MovieAudioExtraction_Audio,
  16331. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16332. sizeof (qt_audio_channel_layout),
  16333. qt_audio_channel_layout);
  16334. juce_free (qt_audio_channel_layout);
  16335. err = MovieAudioExtractionGetProperty (extractor,
  16336. kQTPropertyClass_MovieAudioExtraction_Audio,
  16337. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  16338. sizeof (inputStreamDesc),
  16339. &inputStreamDesc, 0);
  16340. if (err != noErr)
  16341. return;
  16342. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  16343. | kAudioFormatFlagIsPacked
  16344. | kAudioFormatFlagsNativeEndian;
  16345. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  16346. inputStreamDesc.mChannelsPerFrame = jmin (2, inputStreamDesc.mChannelsPerFrame);
  16347. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  16348. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  16349. err = MovieAudioExtractionSetProperty (extractor,
  16350. kQTPropertyClass_MovieAudioExtraction_Audio,
  16351. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  16352. sizeof (inputStreamDesc),
  16353. &inputStreamDesc);
  16354. if (err != noErr)
  16355. return;
  16356. Boolean allChannelsDiscrete = false;
  16357. err = MovieAudioExtractionSetProperty (extractor,
  16358. kQTPropertyClass_MovieAudioExtraction_Movie,
  16359. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  16360. sizeof (allChannelsDiscrete),
  16361. &allChannelsDiscrete);
  16362. if (err != noErr)
  16363. return;
  16364. bufferList->mNumberBuffers = 1;
  16365. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  16366. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  16367. bufferList->mBuffers[0].mData = malloc (bufferList->mBuffers[0].mDataByteSize);
  16368. sampleRate = inputStreamDesc.mSampleRate;
  16369. bitsPerSample = 16;
  16370. numChannels = inputStreamDesc.mChannelsPerFrame;
  16371. detachThread();
  16372. ok = true;
  16373. }
  16374. ~QTAudioReader()
  16375. {
  16376. if (dataHandle != 0)
  16377. DisposeHandle (dataHandle);
  16378. if (extractor != 0)
  16379. {
  16380. MovieAudioExtractionEnd (extractor);
  16381. extractor = 0;
  16382. }
  16383. checkThreadIsAttached();
  16384. DisposeMovie (movie);
  16385. juce_free (bufferList->mBuffers[0].mData);
  16386. juce_free (bufferList);
  16387. #if JUCE_MAC
  16388. ExitMoviesOnThread ();
  16389. #endif
  16390. }
  16391. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16392. int64 startSampleInFile, int numSamples)
  16393. {
  16394. checkThreadIsAttached();
  16395. while (numSamples > 0)
  16396. {
  16397. if (! loadFrame ((int) startSampleInFile))
  16398. return false;
  16399. const int numToDo = jmin (numSamples, samplesPerFrame);
  16400. for (int j = numDestChannels; --j >= 0;)
  16401. {
  16402. if (destSamples[j] != 0)
  16403. {
  16404. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  16405. for (int i = 0; i < numToDo; ++i)
  16406. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  16407. }
  16408. }
  16409. startOffsetInDestBuffer += numToDo;
  16410. startSampleInFile += numToDo;
  16411. numSamples -= numToDo;
  16412. }
  16413. detachThread();
  16414. return true;
  16415. }
  16416. bool loadFrame (const int sampleNum)
  16417. {
  16418. if (lastSampleRead != sampleNum)
  16419. {
  16420. TimeRecord time;
  16421. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  16422. time.base = 0;
  16423. time.value.hi = 0;
  16424. time.value.lo = (UInt32) sampleNum;
  16425. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  16426. kQTPropertyClass_MovieAudioExtraction_Movie,
  16427. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  16428. sizeof (time), &time);
  16429. if (err != noErr)
  16430. return false;
  16431. }
  16432. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  16433. UInt32 outFlags = 0;
  16434. UInt32 actualNumSamples = samplesPerFrame;
  16435. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  16436. bufferList, &outFlags);
  16437. lastSampleRead = sampleNum + samplesPerFrame;
  16438. return err == noErr;
  16439. }
  16440. juce_UseDebuggingNewOperator
  16441. bool ok;
  16442. private:
  16443. Movie movie;
  16444. Media media;
  16445. Track track;
  16446. const int trackNum;
  16447. double trackUnitsPerFrame;
  16448. int samplesPerFrame;
  16449. int lastSampleRead;
  16450. Thread::ThreadID lastThreadId;
  16451. MovieAudioExtractionRef extractor;
  16452. AudioStreamBasicDescription inputStreamDesc;
  16453. AudioBufferList* bufferList;
  16454. Handle dataHandle;
  16455. /*OSErr readMovieStream (long offset, long size, void* dataPtr)
  16456. {
  16457. input->setPosition (offset);
  16458. input->read (dataPtr, size);
  16459. return noErr;
  16460. }
  16461. static OSErr readMovieStreamProc (long offset, long size, void* dataPtr, void* userRef)
  16462. {
  16463. return ((QTAudioReader*) userRef)->readMovieStream (offset, size, dataPtr);
  16464. }*/
  16465. void checkThreadIsAttached()
  16466. {
  16467. #if JUCE_MAC
  16468. if (Thread::getCurrentThreadId() != lastThreadId)
  16469. EnterMoviesOnThread (0);
  16470. AttachMovieToCurrentThread (movie);
  16471. #endif
  16472. }
  16473. void detachThread()
  16474. {
  16475. #if JUCE_MAC
  16476. DetachMovieFromCurrentThread (movie);
  16477. #endif
  16478. }
  16479. };
  16480. QuickTimeAudioFormat::QuickTimeAudioFormat()
  16481. : AudioFormat (quickTimeFormatName, (const tchar**) quickTimeExtensions)
  16482. {
  16483. }
  16484. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  16485. {
  16486. }
  16487. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  16488. {
  16489. return Array<int>();
  16490. }
  16491. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  16492. {
  16493. return Array<int>();
  16494. }
  16495. bool QuickTimeAudioFormat::canDoStereo()
  16496. {
  16497. return true;
  16498. }
  16499. bool QuickTimeAudioFormat::canDoMono()
  16500. {
  16501. return true;
  16502. }
  16503. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  16504. const bool deleteStreamIfOpeningFails)
  16505. {
  16506. QTAudioReader* r = new QTAudioReader (sourceStream, 0);
  16507. if (! r->ok)
  16508. {
  16509. if (! deleteStreamIfOpeningFails)
  16510. r->input = 0;
  16511. deleteAndZero (r);
  16512. }
  16513. return r;
  16514. }
  16515. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  16516. double /*sampleRateToUse*/,
  16517. unsigned int /*numberOfChannels*/,
  16518. int /*bitsPerSample*/,
  16519. const StringPairArray& /*metadataValues*/,
  16520. int /*qualityOptionIndex*/)
  16521. {
  16522. jassertfalse // not yet implemented!
  16523. return 0;
  16524. }
  16525. END_JUCE_NAMESPACE
  16526. #endif
  16527. #endif
  16528. /********* End of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  16529. /********* Start of inlined file: juce_WavAudioFormat.cpp *********/
  16530. BEGIN_JUCE_NAMESPACE
  16531. #define wavFormatName TRANS("WAV file")
  16532. static const tchar* const wavExtensions[] = { T(".wav"), T(".bwf"), 0 };
  16533. const tchar* const WavAudioFormat::bwavDescription = T("bwav description");
  16534. const tchar* const WavAudioFormat::bwavOriginator = T("bwav originator");
  16535. const tchar* const WavAudioFormat::bwavOriginatorRef = T("bwav originator ref");
  16536. const tchar* const WavAudioFormat::bwavOriginationDate = T("bwav origination date");
  16537. const tchar* const WavAudioFormat::bwavOriginationTime = T("bwav origination time");
  16538. const tchar* const WavAudioFormat::bwavTimeReference = T("bwav time reference");
  16539. const tchar* const WavAudioFormat::bwavCodingHistory = T("bwav coding history");
  16540. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  16541. const String& originator,
  16542. const String& originatorRef,
  16543. const Time& date,
  16544. const int64 timeReferenceSamples,
  16545. const String& codingHistory)
  16546. {
  16547. StringPairArray m;
  16548. m.set (bwavDescription, description);
  16549. m.set (bwavOriginator, originator);
  16550. m.set (bwavOriginatorRef, originatorRef);
  16551. m.set (bwavOriginationDate, date.formatted (T("%Y-%m-%d")));
  16552. m.set (bwavOriginationTime, date.formatted (T("%H:%M:%S")));
  16553. m.set (bwavTimeReference, String (timeReferenceSamples));
  16554. m.set (bwavCodingHistory, codingHistory);
  16555. return m;
  16556. }
  16557. #if JUCE_MSVC
  16558. #pragma pack (push, 1)
  16559. #define PACKED
  16560. #elif defined (JUCE_GCC)
  16561. #define PACKED __attribute__((packed))
  16562. #else
  16563. #define PACKED
  16564. #endif
  16565. struct BWAVChunk
  16566. {
  16567. uint8 description [256];
  16568. uint8 originator [32];
  16569. uint8 originatorRef [32];
  16570. uint8 originationDate [10];
  16571. uint8 originationTime [8];
  16572. uint32 timeRefLow;
  16573. uint32 timeRefHigh;
  16574. uint16 version;
  16575. uint8 umid[64];
  16576. uint8 reserved[190];
  16577. uint8 codingHistory[1];
  16578. void copyTo (StringPairArray& values) const
  16579. {
  16580. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  16581. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  16582. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  16583. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  16584. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  16585. const uint32 timeLow = swapIfBigEndian (timeRefLow);
  16586. const uint32 timeHigh = swapIfBigEndian (timeRefHigh);
  16587. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  16588. values.set (WavAudioFormat::bwavTimeReference, String (time));
  16589. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  16590. }
  16591. static MemoryBlock createFrom (const StringPairArray& values)
  16592. {
  16593. const int sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (0) - 1;
  16594. MemoryBlock data ((sizeNeeded + 3) & ~3);
  16595. data.fillWith (0);
  16596. BWAVChunk* b = (BWAVChunk*) data.getData();
  16597. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  16598. // as they get called in the right order..
  16599. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  16600. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  16601. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  16602. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  16603. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  16604. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  16605. b->timeRefLow = swapIfBigEndian ((uint32) (time & 0xffffffff));
  16606. b->timeRefHigh = swapIfBigEndian ((uint32) (time >> 32));
  16607. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory);
  16608. if (b->description[0] != 0
  16609. || b->originator[0] != 0
  16610. || b->originationDate[0] != 0
  16611. || b->originationTime[0] != 0
  16612. || b->codingHistory[0] != 0
  16613. || time != 0)
  16614. {
  16615. return data;
  16616. }
  16617. return MemoryBlock();
  16618. }
  16619. } PACKED;
  16620. struct SMPLChunk
  16621. {
  16622. struct SampleLoop
  16623. {
  16624. uint32 identifier;
  16625. uint32 type;
  16626. uint32 start;
  16627. uint32 end;
  16628. uint32 fraction;
  16629. uint32 playCount;
  16630. } PACKED;
  16631. uint32 manufacturer;
  16632. uint32 product;
  16633. uint32 samplePeriod;
  16634. uint32 midiUnityNote;
  16635. uint32 midiPitchFraction;
  16636. uint32 smpteFormat;
  16637. uint32 smpteOffset;
  16638. uint32 numSampleLoops;
  16639. uint32 samplerData;
  16640. SampleLoop loops[1];
  16641. void copyTo (StringPairArray& values, const int totalSize) const
  16642. {
  16643. values.set (T("Manufacturer"), String (swapIfBigEndian (manufacturer)));
  16644. values.set (T("Product"), String (swapIfBigEndian (product)));
  16645. values.set (T("SamplePeriod"), String (swapIfBigEndian (samplePeriod)));
  16646. values.set (T("MidiUnityNote"), String (swapIfBigEndian (midiUnityNote)));
  16647. values.set (T("MidiPitchFraction"), String (swapIfBigEndian (midiPitchFraction)));
  16648. values.set (T("SmpteFormat"), String (swapIfBigEndian (smpteFormat)));
  16649. values.set (T("SmpteOffset"), String (swapIfBigEndian (smpteOffset)));
  16650. values.set (T("NumSampleLoops"), String (swapIfBigEndian (numSampleLoops)));
  16651. values.set (T("SamplerData"), String (swapIfBigEndian (samplerData)));
  16652. for (uint32 i = 0; i < numSampleLoops; ++i)
  16653. {
  16654. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  16655. break;
  16656. values.set (String::formatted (T("Loop%dIdentifier"), i), String (swapIfBigEndian (loops[i].identifier)));
  16657. values.set (String::formatted (T("Loop%dType"), i), String (swapIfBigEndian (loops[i].type)));
  16658. values.set (String::formatted (T("Loop%dStart"), i), String (swapIfBigEndian (loops[i].start)));
  16659. values.set (String::formatted (T("Loop%dEnd"), i), String (swapIfBigEndian (loops[i].end)));
  16660. values.set (String::formatted (T("Loop%dFraction"), i), String (swapIfBigEndian (loops[i].fraction)));
  16661. values.set (String::formatted (T("Loop%dPlayCount"), i), String (swapIfBigEndian (loops[i].playCount)));
  16662. }
  16663. }
  16664. } PACKED;
  16665. #if JUCE_MSVC
  16666. #pragma pack (pop)
  16667. #endif
  16668. #undef PACKED
  16669. #undef chunkName
  16670. #define chunkName(a) ((int) littleEndianInt(a))
  16671. class WavAudioFormatReader : public AudioFormatReader
  16672. {
  16673. int bytesPerFrame;
  16674. int64 dataChunkStart, dataLength;
  16675. WavAudioFormatReader (const WavAudioFormatReader&);
  16676. const WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  16677. public:
  16678. int64 bwavChunkStart, bwavSize;
  16679. WavAudioFormatReader (InputStream* const in)
  16680. : AudioFormatReader (in, wavFormatName),
  16681. dataLength (0),
  16682. bwavChunkStart (0),
  16683. bwavSize (0)
  16684. {
  16685. if (input->readInt() == chunkName ("RIFF"))
  16686. {
  16687. const uint32 len = (uint32) input->readInt();
  16688. const int64 end = input->getPosition() + len;
  16689. bool hasGotType = false;
  16690. bool hasGotData = false;
  16691. if (input->readInt() == chunkName ("WAVE"))
  16692. {
  16693. while (input->getPosition() < end
  16694. && ! input->isExhausted())
  16695. {
  16696. const int chunkType = input->readInt();
  16697. uint32 length = (uint32) input->readInt();
  16698. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  16699. if (chunkType == chunkName ("fmt "))
  16700. {
  16701. // read the format chunk
  16702. const short format = input->readShort();
  16703. const short numChans = input->readShort();
  16704. sampleRate = input->readInt();
  16705. const int bytesPerSec = input->readInt();
  16706. numChannels = numChans;
  16707. bytesPerFrame = bytesPerSec / (int)sampleRate;
  16708. bitsPerSample = 8 * bytesPerFrame / numChans;
  16709. if (format == 3)
  16710. usesFloatingPointData = true;
  16711. else if (format != 1)
  16712. bytesPerFrame = 0;
  16713. hasGotType = true;
  16714. }
  16715. else if (chunkType == chunkName ("data"))
  16716. {
  16717. // get the data chunk's position
  16718. dataLength = length;
  16719. dataChunkStart = input->getPosition();
  16720. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  16721. hasGotData = true;
  16722. }
  16723. else if (chunkType == chunkName ("bext"))
  16724. {
  16725. bwavChunkStart = input->getPosition();
  16726. bwavSize = length;
  16727. // Broadcast-wav extension chunk..
  16728. BWAVChunk* const bwav = (BWAVChunk*) juce_calloc (jmax (length + 1, (int) sizeof (BWAVChunk)));
  16729. input->read (bwav, length);
  16730. bwav->copyTo (metadataValues);
  16731. juce_free (bwav);
  16732. }
  16733. else if (chunkType == chunkName ("smpl"))
  16734. {
  16735. SMPLChunk* const smpl = (SMPLChunk*) juce_calloc (jmax (length + 1, (int) sizeof (SMPLChunk)));
  16736. input->read (smpl, length);
  16737. smpl->copyTo (metadataValues, length);
  16738. juce_free (smpl);
  16739. }
  16740. else if (chunkEnd <= input->getPosition())
  16741. {
  16742. break;
  16743. }
  16744. input->setPosition (chunkEnd);
  16745. }
  16746. }
  16747. }
  16748. }
  16749. ~WavAudioFormatReader()
  16750. {
  16751. }
  16752. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16753. int64 startSampleInFile, int numSamples)
  16754. {
  16755. numSamples = (int) jmin ((int64) numSamples, lengthInSamples - startSampleInFile);
  16756. if (numSamples <= 0)
  16757. return true;
  16758. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16759. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16760. char tempBuffer [tempBufSize];
  16761. while (numSamples > 0)
  16762. {
  16763. int* left = destSamples[0];
  16764. if (left != 0)
  16765. left += startOffsetInDestBuffer;
  16766. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  16767. if (right != 0)
  16768. right += startOffsetInDestBuffer;
  16769. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16770. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16771. if (bytesRead < numThisTime * bytesPerFrame)
  16772. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16773. if (bitsPerSample == 16)
  16774. {
  16775. const short* src = (const short*) tempBuffer;
  16776. if (numChannels > 1)
  16777. {
  16778. if (left == 0)
  16779. {
  16780. for (int i = numThisTime; --i >= 0;)
  16781. {
  16782. ++src;
  16783. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16784. }
  16785. }
  16786. else if (right == 0)
  16787. {
  16788. for (int i = numThisTime; --i >= 0;)
  16789. {
  16790. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16791. ++src;
  16792. }
  16793. }
  16794. else
  16795. {
  16796. for (int i = numThisTime; --i >= 0;)
  16797. {
  16798. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16799. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16800. }
  16801. }
  16802. }
  16803. else
  16804. {
  16805. for (int i = numThisTime; --i >= 0;)
  16806. {
  16807. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16808. }
  16809. }
  16810. }
  16811. else if (bitsPerSample == 24)
  16812. {
  16813. const char* src = (const char*) tempBuffer;
  16814. if (numChannels > 1)
  16815. {
  16816. if (left == 0)
  16817. {
  16818. for (int i = numThisTime; --i >= 0;)
  16819. {
  16820. src += 3;
  16821. *right++ = littleEndian24Bit (src) << 8;
  16822. src += 3;
  16823. }
  16824. }
  16825. else if (right == 0)
  16826. {
  16827. for (int i = numThisTime; --i >= 0;)
  16828. {
  16829. *left++ = littleEndian24Bit (src) << 8;
  16830. src += 6;
  16831. }
  16832. }
  16833. else
  16834. {
  16835. for (int i = 0; i < numThisTime; ++i)
  16836. {
  16837. *left++ = littleEndian24Bit (src) << 8;
  16838. src += 3;
  16839. *right++ = littleEndian24Bit (src) << 8;
  16840. src += 3;
  16841. }
  16842. }
  16843. }
  16844. else
  16845. {
  16846. for (int i = 0; i < numThisTime; ++i)
  16847. {
  16848. *left++ = littleEndian24Bit (src) << 8;
  16849. src += 3;
  16850. }
  16851. }
  16852. }
  16853. else if (bitsPerSample == 32)
  16854. {
  16855. const unsigned int* src = (const unsigned int*) tempBuffer;
  16856. unsigned int* l = (unsigned int*) left;
  16857. unsigned int* r = (unsigned int*) right;
  16858. if (numChannels > 1)
  16859. {
  16860. if (l == 0)
  16861. {
  16862. for (int i = numThisTime; --i >= 0;)
  16863. {
  16864. ++src;
  16865. *r++ = swapIfBigEndian (*src++);
  16866. }
  16867. }
  16868. else if (r == 0)
  16869. {
  16870. for (int i = numThisTime; --i >= 0;)
  16871. {
  16872. *l++ = swapIfBigEndian (*src++);
  16873. ++src;
  16874. }
  16875. }
  16876. else
  16877. {
  16878. for (int i = numThisTime; --i >= 0;)
  16879. {
  16880. *l++ = swapIfBigEndian (*src++);
  16881. *r++ = swapIfBigEndian (*src++);
  16882. }
  16883. }
  16884. }
  16885. else
  16886. {
  16887. for (int i = numThisTime; --i >= 0;)
  16888. {
  16889. *l++ = swapIfBigEndian (*src++);
  16890. }
  16891. }
  16892. left = (int*)l;
  16893. right = (int*)r;
  16894. }
  16895. else if (bitsPerSample == 8)
  16896. {
  16897. const unsigned char* src = (const unsigned char*) tempBuffer;
  16898. if (numChannels > 1)
  16899. {
  16900. if (left == 0)
  16901. {
  16902. for (int i = numThisTime; --i >= 0;)
  16903. {
  16904. ++src;
  16905. *right++ = ((int) *src++ - 128) << 24;
  16906. }
  16907. }
  16908. else if (right == 0)
  16909. {
  16910. for (int i = numThisTime; --i >= 0;)
  16911. {
  16912. *left++ = ((int) *src++ - 128) << 24;
  16913. ++src;
  16914. }
  16915. }
  16916. else
  16917. {
  16918. for (int i = numThisTime; --i >= 0;)
  16919. {
  16920. *left++ = ((int) *src++ - 128) << 24;
  16921. *right++ = ((int) *src++ - 128) << 24;
  16922. }
  16923. }
  16924. }
  16925. else
  16926. {
  16927. for (int i = numThisTime; --i >= 0;)
  16928. {
  16929. *left++ = ((int)*src++ - 128) << 24;
  16930. }
  16931. }
  16932. }
  16933. startOffsetInDestBuffer += numThisTime;
  16934. numSamples -= numThisTime;
  16935. }
  16936. if (numSamples > 0)
  16937. {
  16938. for (int i = numDestChannels; --i >= 0;)
  16939. if (destSamples[i] != 0)
  16940. zeromem (destSamples[i] + startOffsetInDestBuffer,
  16941. sizeof (int) * numSamples);
  16942. }
  16943. return true;
  16944. }
  16945. juce_UseDebuggingNewOperator
  16946. };
  16947. class WavAudioFormatWriter : public AudioFormatWriter
  16948. {
  16949. MemoryBlock tempBlock, bwavChunk;
  16950. uint32 lengthInSamples, bytesWritten;
  16951. int64 headerPosition;
  16952. bool writeFailed;
  16953. WavAudioFormatWriter (const WavAudioFormatWriter&);
  16954. const WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  16955. void writeHeader()
  16956. {
  16957. const bool seekedOk = output->setPosition (headerPosition);
  16958. (void) seekedOk;
  16959. // if this fails, you've given it an output stream that can't seek! It needs
  16960. // to be able to seek back to write the header
  16961. jassert (seekedOk);
  16962. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  16963. output->writeInt (chunkName ("RIFF"));
  16964. output->writeInt (lengthInSamples * bytesPerFrame
  16965. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36));
  16966. output->writeInt (chunkName ("WAVE"));
  16967. output->writeInt (chunkName ("fmt "));
  16968. output->writeInt (16);
  16969. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  16970. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  16971. output->writeShort ((short) numChannels);
  16972. output->writeInt ((int) sampleRate);
  16973. output->writeInt (bytesPerFrame * (int) sampleRate);
  16974. output->writeShort ((short) bytesPerFrame);
  16975. output->writeShort ((short) bitsPerSample);
  16976. if (bwavChunk.getSize() > 0)
  16977. {
  16978. output->writeInt (chunkName ("bext"));
  16979. output->writeInt (bwavChunk.getSize());
  16980. output->write (bwavChunk.getData(), bwavChunk.getSize());
  16981. }
  16982. output->writeInt (chunkName ("data"));
  16983. output->writeInt (lengthInSamples * bytesPerFrame);
  16984. usesFloatingPointData = (bitsPerSample == 32);
  16985. }
  16986. public:
  16987. WavAudioFormatWriter (OutputStream* const out,
  16988. const double sampleRate,
  16989. const unsigned int numChannels_,
  16990. const int bits,
  16991. const StringPairArray& metadataValues)
  16992. : AudioFormatWriter (out,
  16993. wavFormatName,
  16994. sampleRate,
  16995. numChannels_,
  16996. bits),
  16997. lengthInSamples (0),
  16998. bytesWritten (0),
  16999. writeFailed (false)
  17000. {
  17001. if (metadataValues.size() > 0)
  17002. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17003. headerPosition = out->getPosition();
  17004. writeHeader();
  17005. }
  17006. ~WavAudioFormatWriter()
  17007. {
  17008. writeHeader();
  17009. }
  17010. bool write (const int** data, int numSamples)
  17011. {
  17012. if (writeFailed)
  17013. return false;
  17014. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17015. tempBlock.ensureSize (bytes, false);
  17016. char* buffer = (char*) tempBlock.getData();
  17017. const int* left = data[0];
  17018. const int* right = data[1];
  17019. if (right == 0)
  17020. right = left;
  17021. if (bitsPerSample == 16)
  17022. {
  17023. short* b = (short*) buffer;
  17024. if (numChannels > 1)
  17025. {
  17026. for (int i = numSamples; --i >= 0;)
  17027. {
  17028. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17029. *b++ = (short) swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17030. }
  17031. }
  17032. else
  17033. {
  17034. for (int i = numSamples; --i >= 0;)
  17035. {
  17036. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17037. }
  17038. }
  17039. }
  17040. else if (bitsPerSample == 24)
  17041. {
  17042. char* b = (char*) buffer;
  17043. if (numChannels > 1)
  17044. {
  17045. for (int i = numSamples; --i >= 0;)
  17046. {
  17047. littleEndian24BitToChars ((*left++) >> 8, b);
  17048. b += 3;
  17049. littleEndian24BitToChars ((*right++) >> 8, b);
  17050. b += 3;
  17051. }
  17052. }
  17053. else
  17054. {
  17055. for (int i = numSamples; --i >= 0;)
  17056. {
  17057. littleEndian24BitToChars ((*left++) >> 8, b);
  17058. b += 3;
  17059. }
  17060. }
  17061. }
  17062. else if (bitsPerSample == 32)
  17063. {
  17064. unsigned int* b = (unsigned int*) buffer;
  17065. if (numChannels > 1)
  17066. {
  17067. for (int i = numSamples; --i >= 0;)
  17068. {
  17069. *b++ = swapIfBigEndian ((unsigned int) *left++);
  17070. *b++ = swapIfBigEndian ((unsigned int) *right++);
  17071. }
  17072. }
  17073. else
  17074. {
  17075. for (int i = numSamples; --i >= 0;)
  17076. {
  17077. *b++ = swapIfBigEndian ((unsigned int) *left++);
  17078. }
  17079. }
  17080. }
  17081. else if (bitsPerSample == 8)
  17082. {
  17083. unsigned char* b = (unsigned char*) buffer;
  17084. if (numChannels > 1)
  17085. {
  17086. for (int i = numSamples; --i >= 0;)
  17087. {
  17088. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17089. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17090. }
  17091. }
  17092. else
  17093. {
  17094. for (int i = numSamples; --i >= 0;)
  17095. {
  17096. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17097. }
  17098. }
  17099. }
  17100. if (bytesWritten + bytes >= (uint32) 0xfff00000
  17101. || ! output->write (buffer, bytes))
  17102. {
  17103. // failed to write to disk, so let's try writing the header.
  17104. // If it's just run out of disk space, then if it does manage
  17105. // to write the header, we'll still have a useable file..
  17106. writeHeader();
  17107. writeFailed = true;
  17108. return false;
  17109. }
  17110. else
  17111. {
  17112. bytesWritten += bytes;
  17113. lengthInSamples += numSamples;
  17114. return true;
  17115. }
  17116. }
  17117. juce_UseDebuggingNewOperator
  17118. };
  17119. WavAudioFormat::WavAudioFormat()
  17120. : AudioFormat (wavFormatName, (const tchar**) wavExtensions)
  17121. {
  17122. }
  17123. WavAudioFormat::~WavAudioFormat()
  17124. {
  17125. }
  17126. const Array <int> WavAudioFormat::getPossibleSampleRates()
  17127. {
  17128. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  17129. return Array <int> (rates);
  17130. }
  17131. const Array <int> WavAudioFormat::getPossibleBitDepths()
  17132. {
  17133. const int depths[] = { 8, 16, 24, 32, 0 };
  17134. return Array <int> (depths);
  17135. }
  17136. bool WavAudioFormat::canDoStereo()
  17137. {
  17138. return true;
  17139. }
  17140. bool WavAudioFormat::canDoMono()
  17141. {
  17142. return true;
  17143. }
  17144. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  17145. const bool deleteStreamIfOpeningFails)
  17146. {
  17147. WavAudioFormatReader* r = new WavAudioFormatReader (sourceStream);
  17148. if (r->sampleRate == 0)
  17149. {
  17150. if (! deleteStreamIfOpeningFails)
  17151. r->input = 0;
  17152. deleteAndZero (r);
  17153. }
  17154. return r;
  17155. }
  17156. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  17157. double sampleRate,
  17158. unsigned int numChannels,
  17159. int bitsPerSample,
  17160. const StringPairArray& metadataValues,
  17161. int /*qualityOptionIndex*/)
  17162. {
  17163. if (getPossibleBitDepths().contains (bitsPerSample))
  17164. {
  17165. return new WavAudioFormatWriter (out,
  17166. sampleRate,
  17167. numChannels,
  17168. bitsPerSample,
  17169. metadataValues);
  17170. }
  17171. return 0;
  17172. }
  17173. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  17174. {
  17175. bool ok = false;
  17176. WavAudioFormat wav;
  17177. const File dest (file.getNonexistentSibling());
  17178. OutputStream* outStream = dest.createOutputStream();
  17179. if (outStream != 0)
  17180. {
  17181. AudioFormatReader* reader = wav.createReaderFor (file.createInputStream(), true);
  17182. if (reader != 0)
  17183. {
  17184. AudioFormatWriter* writer = wav.createWriterFor (outStream, reader->sampleRate,
  17185. reader->numChannels, reader->bitsPerSample,
  17186. metadata, 0);
  17187. if (writer != 0)
  17188. {
  17189. ok = writer->writeFromAudioReader (*reader, 0, -1);
  17190. outStream = 0;
  17191. delete writer;
  17192. }
  17193. delete reader;
  17194. }
  17195. delete outStream;
  17196. }
  17197. if (ok)
  17198. ok = dest.moveFileTo (file);
  17199. if (! ok)
  17200. dest.deleteFile();
  17201. return ok;
  17202. }
  17203. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  17204. {
  17205. WavAudioFormatReader* reader = (WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true);
  17206. if (reader != 0)
  17207. {
  17208. const int64 bwavPos = reader->bwavChunkStart;
  17209. const int64 bwavSize = reader->bwavSize;
  17210. delete reader;
  17211. if (bwavSize > 0)
  17212. {
  17213. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  17214. if (chunk.getSize() <= bwavSize)
  17215. {
  17216. // the new one will fit in the space available, so write it directly..
  17217. const int64 oldSize = wavFile.getSize();
  17218. FileOutputStream* out = wavFile.createOutputStream();
  17219. out->setPosition (bwavPos);
  17220. out->write (chunk.getData(), chunk.getSize());
  17221. out->setPosition (oldSize);
  17222. delete out;
  17223. jassert (wavFile.getSize() == oldSize);
  17224. return true;
  17225. }
  17226. }
  17227. }
  17228. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  17229. }
  17230. END_JUCE_NAMESPACE
  17231. /********* End of inlined file: juce_WavAudioFormat.cpp *********/
  17232. /********* Start of inlined file: juce_AudioFormatReaderSource.cpp *********/
  17233. BEGIN_JUCE_NAMESPACE
  17234. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  17235. const bool deleteReaderWhenThisIsDeleted)
  17236. : reader (reader_),
  17237. deleteReader (deleteReaderWhenThisIsDeleted),
  17238. nextPlayPos (0),
  17239. looping (false)
  17240. {
  17241. jassert (reader != 0);
  17242. }
  17243. AudioFormatReaderSource::~AudioFormatReaderSource()
  17244. {
  17245. releaseResources();
  17246. if (deleteReader)
  17247. delete reader;
  17248. }
  17249. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  17250. {
  17251. nextPlayPos = newPosition;
  17252. }
  17253. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  17254. {
  17255. looping = shouldLoop;
  17256. }
  17257. int AudioFormatReaderSource::getNextReadPosition() const
  17258. {
  17259. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  17260. : nextPlayPos;
  17261. }
  17262. int AudioFormatReaderSource::getTotalLength() const
  17263. {
  17264. return (int) reader->lengthInSamples;
  17265. }
  17266. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  17267. double /*sampleRate*/)
  17268. {
  17269. }
  17270. void AudioFormatReaderSource::releaseResources()
  17271. {
  17272. }
  17273. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17274. {
  17275. if (info.numSamples > 0)
  17276. {
  17277. const int start = nextPlayPos;
  17278. if (looping)
  17279. {
  17280. const int newStart = start % (int) reader->lengthInSamples;
  17281. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  17282. if (newEnd > newStart)
  17283. {
  17284. info.buffer->readFromAudioReader (reader,
  17285. info.startSample,
  17286. newEnd - newStart,
  17287. newStart,
  17288. true, true);
  17289. }
  17290. else
  17291. {
  17292. const int endSamps = (int) reader->lengthInSamples - newStart;
  17293. info.buffer->readFromAudioReader (reader,
  17294. info.startSample,
  17295. endSamps,
  17296. newStart,
  17297. true, true);
  17298. info.buffer->readFromAudioReader (reader,
  17299. info.startSample + endSamps,
  17300. newEnd,
  17301. 0,
  17302. true, true);
  17303. }
  17304. nextPlayPos = newEnd;
  17305. }
  17306. else
  17307. {
  17308. info.buffer->readFromAudioReader (reader,
  17309. info.startSample,
  17310. info.numSamples,
  17311. start,
  17312. true, true);
  17313. nextPlayPos += info.numSamples;
  17314. }
  17315. }
  17316. }
  17317. END_JUCE_NAMESPACE
  17318. /********* End of inlined file: juce_AudioFormatReaderSource.cpp *********/
  17319. /********* Start of inlined file: juce_AudioSourcePlayer.cpp *********/
  17320. BEGIN_JUCE_NAMESPACE
  17321. AudioSourcePlayer::AudioSourcePlayer()
  17322. : source (0),
  17323. sampleRate (0),
  17324. bufferSize (0),
  17325. tempBuffer (2, 8),
  17326. lastGain (1.0f),
  17327. gain (1.0f)
  17328. {
  17329. }
  17330. AudioSourcePlayer::~AudioSourcePlayer()
  17331. {
  17332. setSource (0);
  17333. }
  17334. void AudioSourcePlayer::setSource (AudioSource* newSource)
  17335. {
  17336. if (source != newSource)
  17337. {
  17338. AudioSource* const oldSource = source;
  17339. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  17340. newSource->prepareToPlay (bufferSize, sampleRate);
  17341. {
  17342. const ScopedLock sl (readLock);
  17343. source = newSource;
  17344. }
  17345. if (oldSource != 0)
  17346. oldSource->releaseResources();
  17347. }
  17348. }
  17349. void AudioSourcePlayer::setGain (const float newGain) throw()
  17350. {
  17351. gain = newGain;
  17352. }
  17353. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  17354. int totalNumInputChannels,
  17355. float** outputChannelData,
  17356. int totalNumOutputChannels,
  17357. int numSamples)
  17358. {
  17359. // these should have been prepared by audioDeviceAboutToStart()...
  17360. jassert (sampleRate > 0 && bufferSize > 0);
  17361. const ScopedLock sl (readLock);
  17362. if (source != 0)
  17363. {
  17364. AudioSourceChannelInfo info;
  17365. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  17366. // messy stuff needed to compact the channels down into an array
  17367. // of non-zero pointers..
  17368. for (i = 0; i < totalNumInputChannels; ++i)
  17369. {
  17370. if (inputChannelData[i] != 0)
  17371. {
  17372. inputChans [numInputs++] = inputChannelData[i];
  17373. if (numInputs >= numElementsInArray (inputChans))
  17374. break;
  17375. }
  17376. }
  17377. for (i = 0; i < totalNumOutputChannels; ++i)
  17378. {
  17379. if (outputChannelData[i] != 0)
  17380. {
  17381. outputChans [numOutputs++] = outputChannelData[i];
  17382. if (numOutputs >= numElementsInArray (outputChans))
  17383. break;
  17384. }
  17385. }
  17386. if (numInputs > numOutputs)
  17387. {
  17388. // if there aren't enough output channels for the number of
  17389. // inputs, we need to create some temporary extra ones (can't
  17390. // use the input data in case it gets written to)
  17391. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  17392. false, false, true);
  17393. for (i = 0; i < numOutputs; ++i)
  17394. {
  17395. channels[numActiveChans] = outputChans[i];
  17396. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17397. ++numActiveChans;
  17398. }
  17399. for (i = numOutputs; i < numInputs; ++i)
  17400. {
  17401. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  17402. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17403. ++numActiveChans;
  17404. }
  17405. }
  17406. else
  17407. {
  17408. for (i = 0; i < numInputs; ++i)
  17409. {
  17410. channels[numActiveChans] = outputChans[i];
  17411. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17412. ++numActiveChans;
  17413. }
  17414. for (i = numInputs; i < numOutputs; ++i)
  17415. {
  17416. channels[numActiveChans] = outputChans[i];
  17417. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  17418. ++numActiveChans;
  17419. }
  17420. }
  17421. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  17422. info.buffer = &buffer;
  17423. info.startSample = 0;
  17424. info.numSamples = numSamples;
  17425. source->getNextAudioBlock (info);
  17426. for (i = info.buffer->getNumChannels(); --i >= 0;)
  17427. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  17428. lastGain = gain;
  17429. }
  17430. else
  17431. {
  17432. for (int i = 0; i < totalNumOutputChannels; ++i)
  17433. if (outputChannelData[i] != 0)
  17434. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  17435. }
  17436. }
  17437. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  17438. {
  17439. sampleRate = device->getCurrentSampleRate();
  17440. bufferSize = device->getCurrentBufferSizeSamples();
  17441. zeromem (channels, sizeof (channels));
  17442. if (source != 0)
  17443. source->prepareToPlay (bufferSize, sampleRate);
  17444. }
  17445. void AudioSourcePlayer::audioDeviceStopped()
  17446. {
  17447. if (source != 0)
  17448. source->releaseResources();
  17449. sampleRate = 0.0;
  17450. bufferSize = 0;
  17451. tempBuffer.setSize (2, 8);
  17452. }
  17453. END_JUCE_NAMESPACE
  17454. /********* End of inlined file: juce_AudioSourcePlayer.cpp *********/
  17455. /********* Start of inlined file: juce_AudioTransportSource.cpp *********/
  17456. BEGIN_JUCE_NAMESPACE
  17457. AudioTransportSource::AudioTransportSource()
  17458. : source (0),
  17459. resamplerSource (0),
  17460. bufferingSource (0),
  17461. positionableSource (0),
  17462. masterSource (0),
  17463. gain (1.0f),
  17464. lastGain (1.0f),
  17465. playing (false),
  17466. stopped (true),
  17467. sampleRate (44100.0),
  17468. sourceSampleRate (0.0),
  17469. blockSize (128),
  17470. readAheadBufferSize (0),
  17471. isPrepared (false),
  17472. inputStreamEOF (false)
  17473. {
  17474. }
  17475. AudioTransportSource::~AudioTransportSource()
  17476. {
  17477. setSource (0);
  17478. releaseResources();
  17479. }
  17480. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  17481. int readAheadBufferSize_,
  17482. double sourceSampleRateToCorrectFor)
  17483. {
  17484. if (source == newSource)
  17485. {
  17486. if (source == 0)
  17487. return;
  17488. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  17489. }
  17490. readAheadBufferSize = readAheadBufferSize_;
  17491. sourceSampleRate = sourceSampleRateToCorrectFor;
  17492. ResamplingAudioSource* newResamplerSource = 0;
  17493. BufferingAudioSource* newBufferingSource = 0;
  17494. PositionableAudioSource* newPositionableSource = 0;
  17495. AudioSource* newMasterSource = 0;
  17496. ResamplingAudioSource* oldResamplerSource = resamplerSource;
  17497. BufferingAudioSource* oldBufferingSource = bufferingSource;
  17498. AudioSource* oldMasterSource = masterSource;
  17499. if (newSource != 0)
  17500. {
  17501. newPositionableSource = newSource;
  17502. if (readAheadBufferSize_ > 0)
  17503. newPositionableSource = newBufferingSource
  17504. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  17505. newPositionableSource->setNextReadPosition (0);
  17506. if (sourceSampleRateToCorrectFor != 0)
  17507. newMasterSource = newResamplerSource
  17508. = new ResamplingAudioSource (newPositionableSource, false);
  17509. else
  17510. newMasterSource = newPositionableSource;
  17511. if (isPrepared)
  17512. {
  17513. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  17514. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  17515. newMasterSource->prepareToPlay (blockSize, sampleRate);
  17516. }
  17517. }
  17518. {
  17519. const ScopedLock sl (callbackLock);
  17520. source = newSource;
  17521. resamplerSource = newResamplerSource;
  17522. bufferingSource = newBufferingSource;
  17523. masterSource = newMasterSource;
  17524. positionableSource = newPositionableSource;
  17525. playing = false;
  17526. }
  17527. if (oldMasterSource != 0)
  17528. oldMasterSource->releaseResources();
  17529. delete oldResamplerSource;
  17530. delete oldBufferingSource;
  17531. }
  17532. void AudioTransportSource::start()
  17533. {
  17534. if ((! playing) && masterSource != 0)
  17535. {
  17536. callbackLock.enter();
  17537. playing = true;
  17538. stopped = false;
  17539. inputStreamEOF = false;
  17540. callbackLock.exit();
  17541. sendChangeMessage (this);
  17542. }
  17543. }
  17544. void AudioTransportSource::stop()
  17545. {
  17546. if (playing)
  17547. {
  17548. callbackLock.enter();
  17549. playing = false;
  17550. callbackLock.exit();
  17551. int n = 500;
  17552. while (--n >= 0 && ! stopped)
  17553. Thread::sleep (2);
  17554. sendChangeMessage (this);
  17555. }
  17556. }
  17557. void AudioTransportSource::setPosition (double newPosition)
  17558. {
  17559. if (sampleRate > 0.0)
  17560. setNextReadPosition (roundDoubleToInt (newPosition * sampleRate));
  17561. }
  17562. double AudioTransportSource::getCurrentPosition() const
  17563. {
  17564. if (sampleRate > 0.0)
  17565. return getNextReadPosition() / sampleRate;
  17566. else
  17567. return 0.0;
  17568. }
  17569. void AudioTransportSource::setNextReadPosition (int newPosition)
  17570. {
  17571. if (positionableSource != 0)
  17572. {
  17573. if (sampleRate > 0 && sourceSampleRate > 0)
  17574. newPosition = roundDoubleToInt (newPosition * sourceSampleRate / sampleRate);
  17575. positionableSource->setNextReadPosition (newPosition);
  17576. }
  17577. }
  17578. int AudioTransportSource::getNextReadPosition() const
  17579. {
  17580. if (positionableSource != 0)
  17581. {
  17582. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  17583. return roundDoubleToInt (positionableSource->getNextReadPosition() * ratio);
  17584. }
  17585. return 0;
  17586. }
  17587. int AudioTransportSource::getTotalLength() const
  17588. {
  17589. const ScopedLock sl (callbackLock);
  17590. if (positionableSource != 0)
  17591. {
  17592. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  17593. return roundDoubleToInt (positionableSource->getTotalLength() * ratio);
  17594. }
  17595. return 0;
  17596. }
  17597. bool AudioTransportSource::isLooping() const
  17598. {
  17599. const ScopedLock sl (callbackLock);
  17600. return positionableSource != 0
  17601. && positionableSource->isLooping();
  17602. }
  17603. void AudioTransportSource::setGain (const float newGain) throw()
  17604. {
  17605. gain = newGain;
  17606. }
  17607. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  17608. double sampleRate_)
  17609. {
  17610. const ScopedLock sl (callbackLock);
  17611. sampleRate = sampleRate_;
  17612. blockSize = samplesPerBlockExpected;
  17613. if (masterSource != 0)
  17614. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  17615. if (resamplerSource != 0 && sourceSampleRate != 0)
  17616. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  17617. isPrepared = true;
  17618. }
  17619. void AudioTransportSource::releaseResources()
  17620. {
  17621. const ScopedLock sl (callbackLock);
  17622. if (masterSource != 0)
  17623. masterSource->releaseResources();
  17624. isPrepared = false;
  17625. }
  17626. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17627. {
  17628. const ScopedLock sl (callbackLock);
  17629. inputStreamEOF = false;
  17630. if (masterSource != 0 && ! stopped)
  17631. {
  17632. masterSource->getNextAudioBlock (info);
  17633. if (! playing)
  17634. {
  17635. // just stopped playing, so fade out the last block..
  17636. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  17637. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  17638. if (info.numSamples > 256)
  17639. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  17640. }
  17641. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  17642. && ! positionableSource->isLooping())
  17643. {
  17644. playing = false;
  17645. inputStreamEOF = true;
  17646. sendChangeMessage (this);
  17647. }
  17648. stopped = ! playing;
  17649. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  17650. {
  17651. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  17652. lastGain, gain);
  17653. }
  17654. }
  17655. else
  17656. {
  17657. info.clearActiveBufferRegion();
  17658. stopped = true;
  17659. }
  17660. lastGain = gain;
  17661. }
  17662. END_JUCE_NAMESPACE
  17663. /********* End of inlined file: juce_AudioTransportSource.cpp *********/
  17664. /********* Start of inlined file: juce_BufferingAudioSource.cpp *********/
  17665. BEGIN_JUCE_NAMESPACE
  17666. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  17667. public Thread,
  17668. private Timer
  17669. {
  17670. public:
  17671. SharedBufferingAudioSourceThread()
  17672. : Thread ("Audio Buffer"),
  17673. sources (8)
  17674. {
  17675. }
  17676. ~SharedBufferingAudioSourceThread()
  17677. {
  17678. stopThread (10000);
  17679. clearSingletonInstance();
  17680. }
  17681. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  17682. void addSource (BufferingAudioSource* source)
  17683. {
  17684. const ScopedLock sl (lock);
  17685. if (! sources.contains ((void*) source))
  17686. {
  17687. sources.add ((void*) source);
  17688. startThread();
  17689. stopTimer();
  17690. }
  17691. notify();
  17692. }
  17693. void removeSource (BufferingAudioSource* source)
  17694. {
  17695. const ScopedLock sl (lock);
  17696. sources.removeValue ((void*) source);
  17697. if (sources.size() == 0)
  17698. startTimer (5000);
  17699. }
  17700. private:
  17701. VoidArray sources;
  17702. CriticalSection lock;
  17703. void run()
  17704. {
  17705. while (! threadShouldExit())
  17706. {
  17707. bool busy = false;
  17708. for (int i = sources.size(); --i >= 0;)
  17709. {
  17710. if (threadShouldExit())
  17711. return;
  17712. const ScopedLock sl (lock);
  17713. BufferingAudioSource* const b = (BufferingAudioSource*) sources[i];
  17714. if (b != 0 && b->readNextBufferChunk())
  17715. busy = true;
  17716. }
  17717. if (! busy)
  17718. wait (500);
  17719. }
  17720. }
  17721. void timerCallback()
  17722. {
  17723. stopTimer();
  17724. if (sources.size() == 0)
  17725. deleteInstance();
  17726. }
  17727. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  17728. const SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  17729. };
  17730. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  17731. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  17732. const bool deleteSourceWhenDeleted_,
  17733. int numberOfSamplesToBuffer_)
  17734. : source (source_),
  17735. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  17736. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  17737. buffer (2, 0),
  17738. bufferValidStart (0),
  17739. bufferValidEnd (0),
  17740. nextPlayPos (0),
  17741. wasSourceLooping (false)
  17742. {
  17743. jassert (source_ != 0);
  17744. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  17745. // not using a larger buffer..
  17746. }
  17747. BufferingAudioSource::~BufferingAudioSource()
  17748. {
  17749. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17750. if (thread != 0)
  17751. thread->removeSource (this);
  17752. if (deleteSourceWhenDeleted)
  17753. delete source;
  17754. }
  17755. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  17756. {
  17757. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  17758. sampleRate = sampleRate_;
  17759. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  17760. buffer.clear();
  17761. bufferValidStart = 0;
  17762. bufferValidEnd = 0;
  17763. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  17764. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  17765. buffer.getNumSamples() / 2))
  17766. {
  17767. SharedBufferingAudioSourceThread::getInstance()->notify();
  17768. Thread::sleep (5);
  17769. }
  17770. }
  17771. void BufferingAudioSource::releaseResources()
  17772. {
  17773. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17774. if (thread != 0)
  17775. thread->removeSource (this);
  17776. buffer.setSize (2, 0);
  17777. source->releaseResources();
  17778. }
  17779. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17780. {
  17781. const ScopedLock sl (bufferStartPosLock);
  17782. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  17783. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  17784. if (validStart == validEnd)
  17785. {
  17786. // total cache miss
  17787. info.clearActiveBufferRegion();
  17788. }
  17789. else
  17790. {
  17791. if (validStart > 0)
  17792. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  17793. if (validEnd < info.numSamples)
  17794. info.buffer->clear (info.startSample + validEnd,
  17795. info.numSamples - validEnd); // partial cache miss at end
  17796. if (validStart < validEnd)
  17797. {
  17798. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  17799. {
  17800. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  17801. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  17802. if (startBufferIndex < endBufferIndex)
  17803. {
  17804. info.buffer->copyFrom (chan, info.startSample + validStart,
  17805. buffer,
  17806. chan, startBufferIndex,
  17807. validEnd - validStart);
  17808. }
  17809. else
  17810. {
  17811. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  17812. info.buffer->copyFrom (chan, info.startSample + validStart,
  17813. buffer,
  17814. chan, startBufferIndex,
  17815. initialSize);
  17816. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  17817. buffer,
  17818. chan, 0,
  17819. (validEnd - validStart) - initialSize);
  17820. }
  17821. }
  17822. }
  17823. nextPlayPos += info.numSamples;
  17824. if (source->isLooping() && nextPlayPos > 0)
  17825. nextPlayPos %= source->getTotalLength();
  17826. }
  17827. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17828. if (thread != 0)
  17829. thread->notify();
  17830. }
  17831. int BufferingAudioSource::getNextReadPosition() const
  17832. {
  17833. return (source->isLooping() && nextPlayPos > 0)
  17834. ? nextPlayPos % source->getTotalLength()
  17835. : nextPlayPos;
  17836. }
  17837. void BufferingAudioSource::setNextReadPosition (int newPosition)
  17838. {
  17839. const ScopedLock sl (bufferStartPosLock);
  17840. nextPlayPos = newPosition;
  17841. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17842. if (thread != 0)
  17843. thread->notify();
  17844. }
  17845. bool BufferingAudioSource::readNextBufferChunk()
  17846. {
  17847. bufferStartPosLock.enter();
  17848. if (wasSourceLooping != isLooping())
  17849. {
  17850. wasSourceLooping = isLooping();
  17851. bufferValidStart = 0;
  17852. bufferValidEnd = 0;
  17853. }
  17854. int newBVS = jmax (0, nextPlayPos);
  17855. int newBVE = newBVS + buffer.getNumSamples() - 4;
  17856. int sectionToReadStart = 0;
  17857. int sectionToReadEnd = 0;
  17858. const int maxChunkSize = 2048;
  17859. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  17860. {
  17861. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  17862. sectionToReadStart = newBVS;
  17863. sectionToReadEnd = newBVE;
  17864. bufferValidStart = 0;
  17865. bufferValidEnd = 0;
  17866. }
  17867. else if (abs (newBVS - bufferValidStart) > 512
  17868. || abs (newBVE - bufferValidEnd) > 512)
  17869. {
  17870. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  17871. sectionToReadStart = bufferValidEnd;
  17872. sectionToReadEnd = newBVE;
  17873. bufferValidStart = newBVS;
  17874. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  17875. }
  17876. bufferStartPosLock.exit();
  17877. if (sectionToReadStart != sectionToReadEnd)
  17878. {
  17879. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  17880. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  17881. if (bufferIndexStart < bufferIndexEnd)
  17882. {
  17883. readBufferSection (sectionToReadStart,
  17884. sectionToReadEnd - sectionToReadStart,
  17885. bufferIndexStart);
  17886. }
  17887. else
  17888. {
  17889. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  17890. readBufferSection (sectionToReadStart,
  17891. initialSize,
  17892. bufferIndexStart);
  17893. readBufferSection (sectionToReadStart + initialSize,
  17894. (sectionToReadEnd - sectionToReadStart) - initialSize,
  17895. 0);
  17896. }
  17897. const ScopedLock sl2 (bufferStartPosLock);
  17898. bufferValidStart = newBVS;
  17899. bufferValidEnd = newBVE;
  17900. return true;
  17901. }
  17902. else
  17903. {
  17904. return false;
  17905. }
  17906. }
  17907. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  17908. {
  17909. if (source->getNextReadPosition() != start)
  17910. source->setNextReadPosition (start);
  17911. AudioSourceChannelInfo info;
  17912. info.buffer = &buffer;
  17913. info.startSample = bufferOffset;
  17914. info.numSamples = length;
  17915. source->getNextAudioBlock (info);
  17916. }
  17917. END_JUCE_NAMESPACE
  17918. /********* End of inlined file: juce_BufferingAudioSource.cpp *********/
  17919. /********* Start of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  17920. BEGIN_JUCE_NAMESPACE
  17921. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  17922. const bool deleteSourceWhenDeleted_)
  17923. : requiredNumberOfChannels (2),
  17924. source (source_),
  17925. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  17926. buffer (2, 16)
  17927. {
  17928. remappedInfo.buffer = &buffer;
  17929. remappedInfo.startSample = 0;
  17930. }
  17931. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  17932. {
  17933. if (deleteSourceWhenDeleted)
  17934. delete source;
  17935. }
  17936. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  17937. {
  17938. const ScopedLock sl (lock);
  17939. requiredNumberOfChannels = requiredNumberOfChannels_;
  17940. }
  17941. void ChannelRemappingAudioSource::clearAllMappings() throw()
  17942. {
  17943. const ScopedLock sl (lock);
  17944. remappedInputs.clear();
  17945. remappedOutputs.clear();
  17946. }
  17947. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  17948. {
  17949. const ScopedLock sl (lock);
  17950. while (remappedInputs.size() < destIndex)
  17951. remappedInputs.add (-1);
  17952. remappedInputs.set (destIndex, sourceIndex);
  17953. }
  17954. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  17955. {
  17956. const ScopedLock sl (lock);
  17957. while (remappedOutputs.size() < sourceIndex)
  17958. remappedOutputs.add (-1);
  17959. remappedOutputs.set (sourceIndex, destIndex);
  17960. }
  17961. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  17962. {
  17963. const ScopedLock sl (lock);
  17964. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  17965. return remappedInputs.getUnchecked (inputChannelIndex);
  17966. return -1;
  17967. }
  17968. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  17969. {
  17970. const ScopedLock sl (lock);
  17971. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  17972. return remappedOutputs .getUnchecked (outputChannelIndex);
  17973. return -1;
  17974. }
  17975. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  17976. {
  17977. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  17978. }
  17979. void ChannelRemappingAudioSource::releaseResources()
  17980. {
  17981. source->releaseResources();
  17982. }
  17983. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  17984. {
  17985. const ScopedLock sl (lock);
  17986. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  17987. const int numChans = bufferToFill.buffer->getNumChannels();
  17988. int i;
  17989. for (i = 0; i < buffer.getNumChannels(); ++i)
  17990. {
  17991. const int remappedChan = getRemappedInputChannel (i);
  17992. if (remappedChan >= 0 && remappedChan < numChans)
  17993. {
  17994. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  17995. remappedChan,
  17996. bufferToFill.startSample,
  17997. bufferToFill.numSamples);
  17998. }
  17999. else
  18000. {
  18001. buffer.clear (i, 0, bufferToFill.numSamples);
  18002. }
  18003. }
  18004. remappedInfo.numSamples = bufferToFill.numSamples;
  18005. source->getNextAudioBlock (remappedInfo);
  18006. bufferToFill.clearActiveBufferRegion();
  18007. for (i = 0; i < requiredNumberOfChannels; ++i)
  18008. {
  18009. const int remappedChan = getRemappedOutputChannel (i);
  18010. if (remappedChan >= 0 && remappedChan < numChans)
  18011. {
  18012. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18013. buffer, i, 0, bufferToFill.numSamples);
  18014. }
  18015. }
  18016. }
  18017. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18018. {
  18019. XmlElement* e = new XmlElement (T("MAPPINGS"));
  18020. String ins, outs;
  18021. int i;
  18022. const ScopedLock sl (lock);
  18023. for (i = 0; i < remappedInputs.size(); ++i)
  18024. ins << remappedInputs.getUnchecked(i) << T(' ');
  18025. for (i = 0; i < remappedOutputs.size(); ++i)
  18026. outs << remappedOutputs.getUnchecked(i) << T(' ');
  18027. e->setAttribute (T("inputs"), ins.trimEnd());
  18028. e->setAttribute (T("outputs"), outs.trimEnd());
  18029. return e;
  18030. }
  18031. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18032. {
  18033. if (e.hasTagName (T("MAPPINGS")))
  18034. {
  18035. const ScopedLock sl (lock);
  18036. clearAllMappings();
  18037. StringArray ins, outs;
  18038. ins.addTokens (e.getStringAttribute (T("inputs")), false);
  18039. outs.addTokens (e.getStringAttribute (T("outputs")), false);
  18040. int i;
  18041. for (i = 0; i < ins.size(); ++i)
  18042. remappedInputs.add (ins[i].getIntValue());
  18043. for (i = 0; i < outs.size(); ++i)
  18044. remappedOutputs.add (outs[i].getIntValue());
  18045. }
  18046. }
  18047. END_JUCE_NAMESPACE
  18048. /********* End of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  18049. /********* Start of inlined file: juce_IIRFilterAudioSource.cpp *********/
  18050. BEGIN_JUCE_NAMESPACE
  18051. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18052. const bool deleteInputWhenDeleted_)
  18053. : input (inputSource),
  18054. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18055. {
  18056. jassert (inputSource != 0);
  18057. for (int i = 2; --i >= 0;)
  18058. iirFilters.add (new IIRFilter());
  18059. }
  18060. IIRFilterAudioSource::~IIRFilterAudioSource()
  18061. {
  18062. if (deleteInputWhenDeleted)
  18063. delete input;
  18064. }
  18065. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18066. {
  18067. for (int i = iirFilters.size(); --i >= 0;)
  18068. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18069. }
  18070. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18071. {
  18072. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18073. for (int i = iirFilters.size(); --i >= 0;)
  18074. iirFilters.getUnchecked(i)->reset();
  18075. }
  18076. void IIRFilterAudioSource::releaseResources()
  18077. {
  18078. input->releaseResources();
  18079. }
  18080. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18081. {
  18082. input->getNextAudioBlock (bufferToFill);
  18083. const int numChannels = bufferToFill.buffer->getNumChannels();
  18084. while (numChannels > iirFilters.size())
  18085. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18086. for (int i = 0; i < numChannels; ++i)
  18087. iirFilters.getUnchecked(i)
  18088. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18089. bufferToFill.numSamples);
  18090. }
  18091. END_JUCE_NAMESPACE
  18092. /********* End of inlined file: juce_IIRFilterAudioSource.cpp *********/
  18093. /********* Start of inlined file: juce_MixerAudioSource.cpp *********/
  18094. BEGIN_JUCE_NAMESPACE
  18095. MixerAudioSource::MixerAudioSource()
  18096. : tempBuffer (2, 0),
  18097. currentSampleRate (0.0),
  18098. bufferSizeExpected (0)
  18099. {
  18100. }
  18101. MixerAudioSource::~MixerAudioSource()
  18102. {
  18103. removeAllInputs();
  18104. }
  18105. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  18106. {
  18107. if (input != 0 && ! inputs.contains (input))
  18108. {
  18109. lock.enter();
  18110. double localRate = currentSampleRate;
  18111. int localBufferSize = bufferSizeExpected;
  18112. lock.exit();
  18113. if (localRate != 0.0)
  18114. input->prepareToPlay (localBufferSize, localRate);
  18115. const ScopedLock sl (lock);
  18116. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  18117. inputs.add (input);
  18118. }
  18119. }
  18120. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  18121. {
  18122. if (input != 0)
  18123. {
  18124. lock.enter();
  18125. const int index = inputs.indexOf ((void*) input);
  18126. if (index >= 0)
  18127. {
  18128. inputsToDelete.shiftBits (index, 1);
  18129. inputs.remove (index);
  18130. }
  18131. lock.exit();
  18132. if (index >= 0)
  18133. {
  18134. input->releaseResources();
  18135. if (deleteInput)
  18136. delete input;
  18137. }
  18138. }
  18139. }
  18140. void MixerAudioSource::removeAllInputs()
  18141. {
  18142. lock.enter();
  18143. VoidArray inputsCopy (inputs);
  18144. BitArray inputsToDeleteCopy (inputsToDelete);
  18145. inputs.clear();
  18146. lock.exit();
  18147. for (int i = inputsCopy.size(); --i >= 0;)
  18148. if (inputsToDeleteCopy[i])
  18149. delete (AudioSource*) inputsCopy[i];
  18150. }
  18151. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18152. {
  18153. tempBuffer.setSize (2, samplesPerBlockExpected);
  18154. const ScopedLock sl (lock);
  18155. currentSampleRate = sampleRate;
  18156. bufferSizeExpected = samplesPerBlockExpected;
  18157. for (int i = inputs.size(); --i >= 0;)
  18158. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  18159. sampleRate);
  18160. }
  18161. void MixerAudioSource::releaseResources()
  18162. {
  18163. const ScopedLock sl (lock);
  18164. for (int i = inputs.size(); --i >= 0;)
  18165. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  18166. tempBuffer.setSize (2, 0);
  18167. currentSampleRate = 0;
  18168. bufferSizeExpected = 0;
  18169. }
  18170. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18171. {
  18172. const ScopedLock sl (lock);
  18173. if (inputs.size() > 0)
  18174. {
  18175. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  18176. if (inputs.size() > 1)
  18177. {
  18178. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  18179. info.buffer->getNumSamples());
  18180. AudioSourceChannelInfo info2;
  18181. info2.buffer = &tempBuffer;
  18182. info2.numSamples = info.numSamples;
  18183. info2.startSample = 0;
  18184. for (int i = 1; i < inputs.size(); ++i)
  18185. {
  18186. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  18187. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  18188. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  18189. }
  18190. }
  18191. }
  18192. else
  18193. {
  18194. info.clearActiveBufferRegion();
  18195. }
  18196. }
  18197. END_JUCE_NAMESPACE
  18198. /********* End of inlined file: juce_MixerAudioSource.cpp *********/
  18199. /********* Start of inlined file: juce_ResamplingAudioSource.cpp *********/
  18200. BEGIN_JUCE_NAMESPACE
  18201. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  18202. const bool deleteInputWhenDeleted_)
  18203. : input (inputSource),
  18204. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  18205. ratio (1.0),
  18206. lastRatio (1.0),
  18207. buffer (2, 0),
  18208. sampsInBuffer (0)
  18209. {
  18210. jassert (input != 0);
  18211. }
  18212. ResamplingAudioSource::~ResamplingAudioSource()
  18213. {
  18214. if (deleteInputWhenDeleted)
  18215. delete input;
  18216. }
  18217. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  18218. {
  18219. jassert (samplesInPerOutputSample > 0);
  18220. const ScopedLock sl (ratioLock);
  18221. ratio = jmax (0.0, samplesInPerOutputSample);
  18222. }
  18223. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  18224. double sampleRate)
  18225. {
  18226. const ScopedLock sl (ratioLock);
  18227. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18228. buffer.setSize (2, roundDoubleToInt (samplesPerBlockExpected * ratio) + 32);
  18229. buffer.clear();
  18230. sampsInBuffer = 0;
  18231. bufferPos = 0;
  18232. subSampleOffset = 0.0;
  18233. createLowPass (ratio);
  18234. resetFilters();
  18235. }
  18236. void ResamplingAudioSource::releaseResources()
  18237. {
  18238. input->releaseResources();
  18239. buffer.setSize (2, 0);
  18240. }
  18241. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18242. {
  18243. const ScopedLock sl (ratioLock);
  18244. if (lastRatio != ratio)
  18245. {
  18246. createLowPass (ratio);
  18247. lastRatio = ratio;
  18248. }
  18249. const int sampsNeeded = roundDoubleToInt (info.numSamples * ratio) + 2;
  18250. int bufferSize = buffer.getNumSamples();
  18251. if (bufferSize < sampsNeeded + 8)
  18252. {
  18253. bufferPos %= bufferSize;
  18254. bufferSize = sampsNeeded + 32;
  18255. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  18256. }
  18257. bufferPos %= bufferSize;
  18258. int endOfBufferPos = bufferPos + sampsInBuffer;
  18259. while (sampsNeeded > sampsInBuffer)
  18260. {
  18261. endOfBufferPos %= bufferSize;
  18262. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  18263. bufferSize - endOfBufferPos);
  18264. AudioSourceChannelInfo readInfo;
  18265. readInfo.buffer = &buffer;
  18266. readInfo.numSamples = numToDo;
  18267. readInfo.startSample = endOfBufferPos;
  18268. input->getNextAudioBlock (readInfo);
  18269. if (ratio > 1.0001)
  18270. {
  18271. // for down-sampling, pre-apply the filter..
  18272. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18273. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  18274. }
  18275. sampsInBuffer += numToDo;
  18276. endOfBufferPos += numToDo;
  18277. }
  18278. float* dl = info.buffer->getSampleData (0, info.startSample);
  18279. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  18280. const float* const bl = buffer.getSampleData (0, 0);
  18281. const float* const br = buffer.getSampleData (1, 0);
  18282. int nextPos = (bufferPos + 1) % bufferSize;
  18283. for (int m = info.numSamples; --m >= 0;)
  18284. {
  18285. const float alpha = (float) subSampleOffset;
  18286. const float invAlpha = 1.0f - alpha;
  18287. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  18288. if (dr != 0)
  18289. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  18290. subSampleOffset += ratio;
  18291. jassert (sampsInBuffer > 0);
  18292. while (subSampleOffset >= 1.0)
  18293. {
  18294. if (++bufferPos >= bufferSize)
  18295. bufferPos = 0;
  18296. --sampsInBuffer;
  18297. nextPos = (bufferPos + 1) % bufferSize;
  18298. subSampleOffset -= 1.0;
  18299. }
  18300. }
  18301. if (ratio < 0.9999)
  18302. {
  18303. // for up-sampling, apply the filter after transposing..
  18304. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18305. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  18306. }
  18307. else if (ratio <= 1.0001)
  18308. {
  18309. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  18310. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18311. {
  18312. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  18313. FilterState& fs = filterStates[i];
  18314. if (info.numSamples > 1)
  18315. {
  18316. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  18317. }
  18318. else
  18319. {
  18320. fs.y2 = fs.y1;
  18321. fs.x2 = fs.x1;
  18322. }
  18323. fs.y1 = fs.x1 = *endOfBuffer;
  18324. }
  18325. }
  18326. jassert (sampsInBuffer >= 0);
  18327. }
  18328. void ResamplingAudioSource::createLowPass (const double ratio)
  18329. {
  18330. const double proportionalRate = (ratio > 1.0) ? 0.5 / ratio
  18331. : 0.5 * ratio;
  18332. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  18333. const double nSquared = n * n;
  18334. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18335. setFilterCoefficients (c1,
  18336. c1 * 2.0f,
  18337. c1,
  18338. 1.0,
  18339. c1 * 2.0 * (1.0 - nSquared),
  18340. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18341. }
  18342. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  18343. {
  18344. const double a = 1.0 / c4;
  18345. c1 *= a;
  18346. c2 *= a;
  18347. c3 *= a;
  18348. c5 *= a;
  18349. c6 *= a;
  18350. coefficients[0] = c1;
  18351. coefficients[1] = c2;
  18352. coefficients[2] = c3;
  18353. coefficients[3] = c4;
  18354. coefficients[4] = c5;
  18355. coefficients[5] = c6;
  18356. }
  18357. void ResamplingAudioSource::resetFilters()
  18358. {
  18359. zeromem (filterStates, sizeof (filterStates));
  18360. }
  18361. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  18362. {
  18363. while (--num >= 0)
  18364. {
  18365. const double in = *samples;
  18366. double out = coefficients[0] * in
  18367. + coefficients[1] * fs.x1
  18368. + coefficients[2] * fs.x2
  18369. - coefficients[4] * fs.y1
  18370. - coefficients[5] * fs.y2;
  18371. #if JUCE_INTEL
  18372. if (! (out < -1.0e-8 || out > 1.0e-8))
  18373. out = 0;
  18374. #endif
  18375. fs.x2 = fs.x1;
  18376. fs.x1 = in;
  18377. fs.y2 = fs.y1;
  18378. fs.y1 = out;
  18379. *samples++ = (float) out;
  18380. }
  18381. }
  18382. END_JUCE_NAMESPACE
  18383. /********* End of inlined file: juce_ResamplingAudioSource.cpp *********/
  18384. /********* Start of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  18385. BEGIN_JUCE_NAMESPACE
  18386. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  18387. : frequency (1000.0),
  18388. sampleRate (44100.0),
  18389. currentPhase (0.0),
  18390. phasePerSample (0.0),
  18391. amplitude (0.5f)
  18392. {
  18393. }
  18394. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  18395. {
  18396. }
  18397. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  18398. {
  18399. amplitude = newAmplitude;
  18400. }
  18401. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  18402. {
  18403. frequency = newFrequencyHz;
  18404. phasePerSample = 0.0;
  18405. }
  18406. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18407. double sampleRate_)
  18408. {
  18409. currentPhase = 0.0;
  18410. phasePerSample = 0.0;
  18411. sampleRate = sampleRate_;
  18412. }
  18413. void ToneGeneratorAudioSource::releaseResources()
  18414. {
  18415. }
  18416. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18417. {
  18418. if (phasePerSample == 0.0)
  18419. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  18420. for (int i = 0; i < info.numSamples; ++i)
  18421. {
  18422. const float sample = amplitude * (float) sin (currentPhase);
  18423. currentPhase += phasePerSample;
  18424. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  18425. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  18426. }
  18427. }
  18428. END_JUCE_NAMESPACE
  18429. /********* End of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  18430. /********* Start of inlined file: juce_AudioDeviceManager.cpp *********/
  18431. BEGIN_JUCE_NAMESPACE
  18432. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  18433. : sampleRate (0),
  18434. bufferSize (0),
  18435. useDefaultInputChannels (true),
  18436. useDefaultOutputChannels (true)
  18437. {
  18438. }
  18439. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  18440. {
  18441. return outputDeviceName == other.outputDeviceName
  18442. && inputDeviceName == other.inputDeviceName
  18443. && sampleRate == other.sampleRate
  18444. && bufferSize == other.bufferSize
  18445. && inputChannels == other.inputChannels
  18446. && useDefaultInputChannels == other.useDefaultInputChannels
  18447. && outputChannels == other.outputChannels
  18448. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  18449. }
  18450. AudioDeviceManager::AudioDeviceManager()
  18451. : currentAudioDevice (0),
  18452. numInputChansNeeded (0),
  18453. numOutputChansNeeded (2),
  18454. lastExplicitSettings (0),
  18455. listNeedsScanning (true),
  18456. useInputNames (false),
  18457. inputLevelMeasurementEnabledCount (0),
  18458. inputLevel (0),
  18459. testSound (0),
  18460. tempBuffer (2, 2),
  18461. enabledMidiInputs (4),
  18462. midiCallbacks (4),
  18463. midiCallbackDevices (4),
  18464. defaultMidiOutput (0),
  18465. cpuUsageMs (0),
  18466. timeToCpuScale (0)
  18467. {
  18468. callbackHandler.owner = this;
  18469. }
  18470. AudioDeviceManager::~AudioDeviceManager()
  18471. {
  18472. deleteAndZero (currentAudioDevice);
  18473. deleteAndZero (defaultMidiOutput);
  18474. delete lastExplicitSettings;
  18475. delete testSound;
  18476. }
  18477. void AudioDeviceManager::createDeviceTypesIfNeeded()
  18478. {
  18479. if (availableDeviceTypes.size() == 0)
  18480. {
  18481. createAudioDeviceTypes (availableDeviceTypes);
  18482. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  18483. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  18484. if (availableDeviceTypes.size() > 0)
  18485. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  18486. }
  18487. }
  18488. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  18489. {
  18490. scanDevicesIfNeeded();
  18491. return availableDeviceTypes;
  18492. }
  18493. extern AudioIODeviceType* juce_createDefaultAudioIODeviceType();
  18494. #if JUCE_WIN32 && JUCE_ASIO
  18495. extern AudioIODeviceType* juce_createASIOAudioIODeviceType();
  18496. #endif
  18497. #if JUCE_WIN32 && JUCE_WDM_AUDIO
  18498. extern AudioIODeviceType* juce_createWDMAudioIODeviceType();
  18499. #endif
  18500. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  18501. {
  18502. AudioIODeviceType* const defaultDeviceType = juce_createDefaultAudioIODeviceType();
  18503. if (defaultDeviceType != 0)
  18504. list.add (defaultDeviceType);
  18505. #if JUCE_WIN32 && JUCE_ASIO
  18506. list.add (juce_createASIOAudioIODeviceType());
  18507. #endif
  18508. #if JUCE_WIN32 && JUCE_WDM_AUDIO
  18509. list.add (juce_createWDMAudioIODeviceType());
  18510. #endif
  18511. }
  18512. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  18513. const int numOutputChannelsNeeded,
  18514. const XmlElement* const e,
  18515. const bool selectDefaultDeviceOnFailure,
  18516. const String& preferredDefaultDeviceName,
  18517. const AudioDeviceSetup* preferredSetupOptions)
  18518. {
  18519. scanDevicesIfNeeded();
  18520. numInputChansNeeded = numInputChannelsNeeded;
  18521. numOutputChansNeeded = numOutputChannelsNeeded;
  18522. if (e != 0 && e->hasTagName (T("DEVICESETUP")))
  18523. {
  18524. delete lastExplicitSettings;
  18525. lastExplicitSettings = new XmlElement (*e);
  18526. String error;
  18527. AudioDeviceSetup setup;
  18528. if (preferredSetupOptions != 0)
  18529. setup = *preferredSetupOptions;
  18530. if (e->getStringAttribute (T("audioDeviceName")).isNotEmpty())
  18531. {
  18532. setup.inputDeviceName = setup.outputDeviceName
  18533. = e->getStringAttribute (T("audioDeviceName"));
  18534. }
  18535. else
  18536. {
  18537. setup.inputDeviceName = e->getStringAttribute (T("audioInputDeviceName"));
  18538. setup.outputDeviceName = e->getStringAttribute (T("audioOutputDeviceName"));
  18539. }
  18540. currentDeviceType = e->getStringAttribute (T("deviceType"));
  18541. if (currentDeviceType.isEmpty())
  18542. {
  18543. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  18544. if (type != 0)
  18545. currentDeviceType = type->getTypeName();
  18546. else if (availableDeviceTypes.size() > 0)
  18547. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  18548. }
  18549. setup.bufferSize = e->getIntAttribute (T("audioDeviceBufferSize"));
  18550. setup.sampleRate = e->getDoubleAttribute (T("audioDeviceRate"));
  18551. setup.inputChannels.parseString (e->getStringAttribute (T("audioDeviceInChans"), T("11")), 2);
  18552. setup.outputChannels.parseString (e->getStringAttribute (T("audioDeviceOutChans"), T("11")), 2);
  18553. setup.useDefaultInputChannels = ! e->hasAttribute (T("audioDeviceInChans"));
  18554. setup.useDefaultOutputChannels = ! e->hasAttribute (T("audioDeviceOutChans"));
  18555. error = setAudioDeviceSetup (setup, true);
  18556. midiInsFromXml.clear();
  18557. forEachXmlChildElementWithTagName (*e, c, T("MIDIINPUT"))
  18558. midiInsFromXml.add (c->getStringAttribute (T("name")));
  18559. const StringArray allMidiIns (MidiInput::getDevices());
  18560. for (int i = allMidiIns.size(); --i >= 0;)
  18561. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  18562. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  18563. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  18564. false, preferredDefaultDeviceName);
  18565. setDefaultMidiOutput (e->getStringAttribute (T("defaultMidiOutput")));
  18566. return error;
  18567. }
  18568. else
  18569. {
  18570. AudioDeviceSetup setup;
  18571. if (preferredSetupOptions != 0)
  18572. {
  18573. setup = *preferredSetupOptions;
  18574. }
  18575. else if (preferredDefaultDeviceName.isNotEmpty())
  18576. {
  18577. for (int j = availableDeviceTypes.size(); --j >= 0;)
  18578. {
  18579. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  18580. StringArray outs (type->getDeviceNames (false));
  18581. int i;
  18582. for (i = 0; i < outs.size(); ++i)
  18583. {
  18584. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  18585. {
  18586. setup.outputDeviceName = outs[i];
  18587. break;
  18588. }
  18589. }
  18590. StringArray ins (type->getDeviceNames (true));
  18591. for (i = 0; i < ins.size(); ++i)
  18592. {
  18593. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  18594. {
  18595. setup.inputDeviceName = ins[i];
  18596. break;
  18597. }
  18598. }
  18599. }
  18600. }
  18601. insertDefaultDeviceNames (setup);
  18602. return setAudioDeviceSetup (setup, false);
  18603. }
  18604. }
  18605. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  18606. {
  18607. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  18608. if (type != 0)
  18609. {
  18610. if (setup.outputDeviceName.isEmpty())
  18611. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  18612. if (setup.inputDeviceName.isEmpty())
  18613. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  18614. }
  18615. }
  18616. XmlElement* AudioDeviceManager::createStateXml() const
  18617. {
  18618. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  18619. }
  18620. void AudioDeviceManager::scanDevicesIfNeeded()
  18621. {
  18622. if (listNeedsScanning)
  18623. {
  18624. listNeedsScanning = false;
  18625. createDeviceTypesIfNeeded();
  18626. for (int i = availableDeviceTypes.size(); --i >= 0;)
  18627. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  18628. }
  18629. }
  18630. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  18631. {
  18632. scanDevicesIfNeeded();
  18633. for (int i = availableDeviceTypes.size(); --i >= 0;)
  18634. {
  18635. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  18636. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  18637. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  18638. {
  18639. return type;
  18640. }
  18641. }
  18642. return 0;
  18643. }
  18644. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  18645. {
  18646. setup = currentSetup;
  18647. }
  18648. void AudioDeviceManager::deleteCurrentDevice()
  18649. {
  18650. deleteAndZero (currentAudioDevice);
  18651. currentSetup.inputDeviceName = String::empty;
  18652. currentSetup.outputDeviceName = String::empty;
  18653. }
  18654. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  18655. const bool treatAsChosenDevice)
  18656. {
  18657. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18658. {
  18659. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  18660. && currentDeviceType != type)
  18661. {
  18662. currentDeviceType = type;
  18663. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  18664. insertDefaultDeviceNames (s);
  18665. setAudioDeviceSetup (s, treatAsChosenDevice);
  18666. sendChangeMessage (this);
  18667. break;
  18668. }
  18669. }
  18670. }
  18671. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  18672. {
  18673. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18674. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  18675. return availableDeviceTypes[i];
  18676. return availableDeviceTypes[0];
  18677. }
  18678. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  18679. const bool treatAsChosenDevice)
  18680. {
  18681. jassert (&newSetup != &currentSetup); // this will have no effect
  18682. if (newSetup == currentSetup && currentAudioDevice != 0)
  18683. return String::empty;
  18684. if (! (newSetup == currentSetup))
  18685. sendChangeMessage (this);
  18686. stopDevice();
  18687. String error;
  18688. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  18689. if (type == 0 || (newSetup.inputDeviceName.isEmpty()
  18690. && newSetup.outputDeviceName.isEmpty()))
  18691. {
  18692. deleteCurrentDevice();
  18693. if (treatAsChosenDevice)
  18694. updateXml();
  18695. return String::empty;
  18696. }
  18697. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  18698. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  18699. if (currentSetup.inputDeviceName != newInputDeviceName
  18700. || currentSetup.outputDeviceName != newOutputDeviceName
  18701. || currentAudioDevice == 0)
  18702. {
  18703. deleteCurrentDevice();
  18704. scanDevicesIfNeeded();
  18705. if (newOutputDeviceName.isNotEmpty()
  18706. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  18707. {
  18708. return "No such device: " + newOutputDeviceName;
  18709. }
  18710. if (newInputDeviceName.isNotEmpty()
  18711. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  18712. {
  18713. return "No such device: " + newInputDeviceName;
  18714. }
  18715. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  18716. if (currentAudioDevice == 0)
  18717. 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!";
  18718. else
  18719. error = currentAudioDevice->getLastError();
  18720. if (error.isNotEmpty())
  18721. {
  18722. deleteCurrentDevice();
  18723. return error;
  18724. }
  18725. if (newSetup.useDefaultInputChannels)
  18726. {
  18727. inputChannels.clear();
  18728. inputChannels.setRange (0, numInputChansNeeded, true);
  18729. }
  18730. if (newSetup.useDefaultOutputChannels)
  18731. {
  18732. outputChannels.clear();
  18733. outputChannels.setRange (0, numOutputChansNeeded, true);
  18734. }
  18735. if (newInputDeviceName.isEmpty())
  18736. inputChannels.clear();
  18737. if (newOutputDeviceName.isEmpty())
  18738. outputChannels.clear();
  18739. }
  18740. if (! newSetup.useDefaultInputChannels)
  18741. inputChannels = newSetup.inputChannels;
  18742. if (! newSetup.useDefaultOutputChannels)
  18743. outputChannels = newSetup.outputChannels;
  18744. currentSetup = newSetup;
  18745. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  18746. error = currentAudioDevice->open (inputChannels,
  18747. outputChannels,
  18748. currentSetup.sampleRate,
  18749. currentSetup.bufferSize);
  18750. if (error.isEmpty())
  18751. {
  18752. currentDeviceType = currentAudioDevice->getTypeName();
  18753. currentAudioDevice->start (&callbackHandler);
  18754. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  18755. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  18756. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  18757. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  18758. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18759. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  18760. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  18761. if (treatAsChosenDevice)
  18762. updateXml();
  18763. }
  18764. else
  18765. {
  18766. deleteCurrentDevice();
  18767. }
  18768. return error;
  18769. }
  18770. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  18771. {
  18772. jassert (currentAudioDevice != 0);
  18773. if (rate > 0)
  18774. {
  18775. bool ok = false;
  18776. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  18777. {
  18778. const double sr = currentAudioDevice->getSampleRate (i);
  18779. if (sr == rate)
  18780. ok = true;
  18781. }
  18782. if (! ok)
  18783. rate = 0;
  18784. }
  18785. if (rate == 0)
  18786. {
  18787. double lowestAbove44 = 0.0;
  18788. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  18789. {
  18790. const double sr = currentAudioDevice->getSampleRate (i);
  18791. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  18792. lowestAbove44 = sr;
  18793. }
  18794. if (lowestAbove44 == 0.0)
  18795. rate = currentAudioDevice->getSampleRate (0);
  18796. else
  18797. rate = lowestAbove44;
  18798. }
  18799. return rate;
  18800. }
  18801. void AudioDeviceManager::stopDevice()
  18802. {
  18803. if (currentAudioDevice != 0)
  18804. currentAudioDevice->stop();
  18805. }
  18806. void AudioDeviceManager::closeAudioDevice()
  18807. {
  18808. stopDevice();
  18809. deleteAndZero (currentAudioDevice);
  18810. }
  18811. void AudioDeviceManager::restartLastAudioDevice()
  18812. {
  18813. if (currentAudioDevice == 0)
  18814. {
  18815. if (currentSetup.inputDeviceName.isEmpty()
  18816. && currentSetup.outputDeviceName.isEmpty())
  18817. {
  18818. // This method will only reload the last device that was running
  18819. // before closeAudioDevice() was called - you need to actually open
  18820. // one first, with setAudioDevice().
  18821. jassertfalse
  18822. return;
  18823. }
  18824. AudioDeviceSetup s (currentSetup);
  18825. setAudioDeviceSetup (s, false);
  18826. }
  18827. }
  18828. void AudioDeviceManager::updateXml()
  18829. {
  18830. delete lastExplicitSettings;
  18831. lastExplicitSettings = new XmlElement (T("DEVICESETUP"));
  18832. lastExplicitSettings->setAttribute (T("deviceType"), currentDeviceType);
  18833. lastExplicitSettings->setAttribute (T("audioOutputDeviceName"), currentSetup.outputDeviceName);
  18834. lastExplicitSettings->setAttribute (T("audioInputDeviceName"), currentSetup.inputDeviceName);
  18835. if (currentAudioDevice != 0)
  18836. {
  18837. lastExplicitSettings->setAttribute (T("audioDeviceRate"), currentAudioDevice->getCurrentSampleRate());
  18838. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  18839. lastExplicitSettings->setAttribute (T("audioDeviceBufferSize"), currentAudioDevice->getCurrentBufferSizeSamples());
  18840. if (! currentSetup.useDefaultInputChannels)
  18841. lastExplicitSettings->setAttribute (T("audioDeviceInChans"), currentSetup.inputChannels.toString (2));
  18842. if (! currentSetup.useDefaultOutputChannels)
  18843. lastExplicitSettings->setAttribute (T("audioDeviceOutChans"), currentSetup.outputChannels.toString (2));
  18844. }
  18845. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  18846. {
  18847. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  18848. m->setAttribute (T("name"), enabledMidiInputs[i]->getName());
  18849. lastExplicitSettings->addChildElement (m);
  18850. }
  18851. if (midiInsFromXml.size() > 0)
  18852. {
  18853. // Add any midi devices that have been enabled before, but which aren't currently
  18854. // open because the device has been disconnected.
  18855. const StringArray availableMidiDevices (MidiInput::getDevices());
  18856. for (int i = 0; i < midiInsFromXml.size(); ++i)
  18857. {
  18858. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  18859. {
  18860. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  18861. m->setAttribute (T("name"), midiInsFromXml[i]);
  18862. lastExplicitSettings->addChildElement (m);
  18863. }
  18864. }
  18865. }
  18866. if (defaultMidiOutputName.isNotEmpty())
  18867. lastExplicitSettings->setAttribute (T("defaultMidiOutput"), defaultMidiOutputName);
  18868. }
  18869. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  18870. {
  18871. {
  18872. const ScopedLock sl (audioCallbackLock);
  18873. if (callbacks.contains (newCallback))
  18874. return;
  18875. }
  18876. if (currentAudioDevice != 0 && newCallback != 0)
  18877. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  18878. const ScopedLock sl (audioCallbackLock);
  18879. callbacks.add (newCallback);
  18880. }
  18881. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  18882. {
  18883. if (callback != 0)
  18884. {
  18885. bool needsDeinitialising = currentAudioDevice != 0;
  18886. {
  18887. const ScopedLock sl (audioCallbackLock);
  18888. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  18889. callbacks.removeValue (callback);
  18890. }
  18891. if (needsDeinitialising)
  18892. callback->audioDeviceStopped();
  18893. }
  18894. }
  18895. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  18896. int numInputChannels,
  18897. float** outputChannelData,
  18898. int numOutputChannels,
  18899. int numSamples)
  18900. {
  18901. const ScopedLock sl (audioCallbackLock);
  18902. if (inputLevelMeasurementEnabledCount > 0)
  18903. {
  18904. for (int j = 0; j < numSamples; ++j)
  18905. {
  18906. float s = 0;
  18907. for (int i = 0; i < numInputChannels; ++i)
  18908. s += fabsf (inputChannelData[i][j]);
  18909. s /= numInputChannels;
  18910. const double decayFactor = 0.99992;
  18911. if (s > inputLevel)
  18912. inputLevel = s;
  18913. else if (inputLevel > 0.001f)
  18914. inputLevel *= decayFactor;
  18915. else
  18916. inputLevel = 0;
  18917. }
  18918. }
  18919. if (callbacks.size() > 0)
  18920. {
  18921. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  18922. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  18923. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  18924. outputChannelData, numOutputChannels, numSamples);
  18925. float** const tempChans = tempBuffer.getArrayOfChannels();
  18926. for (int i = callbacks.size(); --i > 0;)
  18927. {
  18928. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  18929. tempChans, numOutputChannels, numSamples);
  18930. for (int chan = 0; chan < numOutputChannels; ++chan)
  18931. {
  18932. const float* const src = tempChans [chan];
  18933. float* const dst = outputChannelData [chan];
  18934. if (src != 0 && dst != 0)
  18935. for (int j = 0; j < numSamples; ++j)
  18936. dst[j] += src[j];
  18937. }
  18938. }
  18939. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  18940. const double filterAmount = 0.2;
  18941. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  18942. }
  18943. else
  18944. {
  18945. for (int i = 0; i < numOutputChannels; ++i)
  18946. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18947. }
  18948. if (testSound != 0)
  18949. {
  18950. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  18951. const float* const src = testSound->getSampleData (0, testSoundPosition);
  18952. for (int i = 0; i < numOutputChannels; ++i)
  18953. for (int j = 0; j < numSamps; ++j)
  18954. outputChannelData [i][j] += src[j];
  18955. testSoundPosition += numSamps;
  18956. if (testSoundPosition >= testSound->getNumSamples())
  18957. {
  18958. delete testSound;
  18959. testSound = 0;
  18960. }
  18961. }
  18962. }
  18963. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  18964. {
  18965. cpuUsageMs = 0;
  18966. const double sampleRate = device->getCurrentSampleRate();
  18967. const int blockSize = device->getCurrentBufferSizeSamples();
  18968. if (sampleRate > 0.0 && blockSize > 0)
  18969. {
  18970. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  18971. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  18972. }
  18973. {
  18974. const ScopedLock sl (audioCallbackLock);
  18975. for (int i = callbacks.size(); --i >= 0;)
  18976. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  18977. }
  18978. sendChangeMessage (this);
  18979. }
  18980. void AudioDeviceManager::audioDeviceStoppedInt()
  18981. {
  18982. cpuUsageMs = 0;
  18983. timeToCpuScale = 0;
  18984. sendChangeMessage (this);
  18985. const ScopedLock sl (audioCallbackLock);
  18986. for (int i = callbacks.size(); --i >= 0;)
  18987. callbacks.getUnchecked(i)->audioDeviceStopped();
  18988. }
  18989. double AudioDeviceManager::getCpuUsage() const
  18990. {
  18991. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  18992. }
  18993. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  18994. const bool enabled)
  18995. {
  18996. if (enabled != isMidiInputEnabled (name))
  18997. {
  18998. if (enabled)
  18999. {
  19000. const int index = MidiInput::getDevices().indexOf (name);
  19001. if (index >= 0)
  19002. {
  19003. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19004. if (min != 0)
  19005. {
  19006. enabledMidiInputs.add (min);
  19007. min->start();
  19008. }
  19009. }
  19010. }
  19011. else
  19012. {
  19013. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19014. if (enabledMidiInputs[i]->getName() == name)
  19015. enabledMidiInputs.remove (i);
  19016. }
  19017. updateXml();
  19018. sendChangeMessage (this);
  19019. }
  19020. }
  19021. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19022. {
  19023. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19024. if (enabledMidiInputs[i]->getName() == name)
  19025. return true;
  19026. return false;
  19027. }
  19028. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19029. MidiInputCallback* callback)
  19030. {
  19031. removeMidiInputCallback (name, callback);
  19032. if (name.isEmpty())
  19033. {
  19034. midiCallbacks.add (callback);
  19035. midiCallbackDevices.add (0);
  19036. }
  19037. else
  19038. {
  19039. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19040. {
  19041. if (enabledMidiInputs[i]->getName() == name)
  19042. {
  19043. const ScopedLock sl (midiCallbackLock);
  19044. midiCallbacks.add (callback);
  19045. midiCallbackDevices.add (enabledMidiInputs[i]);
  19046. break;
  19047. }
  19048. }
  19049. }
  19050. }
  19051. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19052. MidiInputCallback* /*callback*/)
  19053. {
  19054. const ScopedLock sl (midiCallbackLock);
  19055. for (int i = midiCallbacks.size(); --i >= 0;)
  19056. {
  19057. String devName;
  19058. if (midiCallbackDevices.getUnchecked(i) != 0)
  19059. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19060. if (devName == name)
  19061. {
  19062. midiCallbacks.remove (i);
  19063. midiCallbackDevices.remove (i);
  19064. }
  19065. }
  19066. }
  19067. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19068. const MidiMessage& message)
  19069. {
  19070. if (! message.isActiveSense())
  19071. {
  19072. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19073. const ScopedLock sl (midiCallbackLock);
  19074. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19075. {
  19076. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19077. if (md == source || (md == 0 && isDefaultSource))
  19078. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19079. }
  19080. }
  19081. }
  19082. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19083. {
  19084. if (defaultMidiOutputName != deviceName)
  19085. {
  19086. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19087. {
  19088. const ScopedLock sl (audioCallbackLock);
  19089. oldCallbacks = callbacks;
  19090. callbacks.clear();
  19091. }
  19092. if (currentAudioDevice != 0)
  19093. for (int i = oldCallbacks.size(); --i >= 0;)
  19094. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19095. deleteAndZero (defaultMidiOutput);
  19096. defaultMidiOutputName = deviceName;
  19097. if (deviceName.isNotEmpty())
  19098. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  19099. if (currentAudioDevice != 0)
  19100. for (int i = oldCallbacks.size(); --i >= 0;)
  19101. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  19102. {
  19103. const ScopedLock sl (audioCallbackLock);
  19104. callbacks = oldCallbacks;
  19105. }
  19106. updateXml();
  19107. sendChangeMessage (this);
  19108. }
  19109. }
  19110. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  19111. int numInputChannels,
  19112. float** outputChannelData,
  19113. int numOutputChannels,
  19114. int numSamples)
  19115. {
  19116. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  19117. }
  19118. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  19119. {
  19120. owner->audioDeviceAboutToStartInt (device);
  19121. }
  19122. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  19123. {
  19124. owner->audioDeviceStoppedInt();
  19125. }
  19126. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  19127. {
  19128. owner->handleIncomingMidiMessageInt (source, message);
  19129. }
  19130. void AudioDeviceManager::playTestSound()
  19131. {
  19132. audioCallbackLock.enter();
  19133. AudioSampleBuffer* oldSound = testSound;
  19134. testSound = 0;
  19135. audioCallbackLock.exit();
  19136. delete oldSound;
  19137. testSoundPosition = 0;
  19138. if (currentAudioDevice != 0)
  19139. {
  19140. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  19141. const int soundLength = (int) sampleRate;
  19142. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  19143. float* samples = newSound->getSampleData (0);
  19144. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  19145. const float amplitude = 0.5f;
  19146. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19147. for (int i = 0; i < soundLength; ++i)
  19148. samples[i] = amplitude * (float) sin (i * phasePerSample);
  19149. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  19150. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  19151. const ScopedLock sl (audioCallbackLock);
  19152. testSound = newSound;
  19153. }
  19154. }
  19155. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  19156. {
  19157. const ScopedLock sl (audioCallbackLock);
  19158. if (enableMeasurement)
  19159. ++inputLevelMeasurementEnabledCount;
  19160. else
  19161. --inputLevelMeasurementEnabledCount;
  19162. inputLevel = 0;
  19163. }
  19164. double AudioDeviceManager::getCurrentInputLevel() const
  19165. {
  19166. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  19167. return inputLevel;
  19168. }
  19169. END_JUCE_NAMESPACE
  19170. /********* End of inlined file: juce_AudioDeviceManager.cpp *********/
  19171. /********* Start of inlined file: juce_AudioIODevice.cpp *********/
  19172. BEGIN_JUCE_NAMESPACE
  19173. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  19174. : name (deviceName),
  19175. typeName (typeName_)
  19176. {
  19177. }
  19178. AudioIODevice::~AudioIODevice()
  19179. {
  19180. }
  19181. bool AudioIODevice::hasControlPanel() const
  19182. {
  19183. return false;
  19184. }
  19185. bool AudioIODevice::showControlPanel()
  19186. {
  19187. jassertfalse // this should only be called for devices which return true from
  19188. // their hasControlPanel() method.
  19189. return false;
  19190. }
  19191. END_JUCE_NAMESPACE
  19192. /********* End of inlined file: juce_AudioIODevice.cpp *********/
  19193. /********* Start of inlined file: juce_AudioIODeviceType.cpp *********/
  19194. BEGIN_JUCE_NAMESPACE
  19195. AudioIODeviceType::AudioIODeviceType (const tchar* const name)
  19196. : typeName (name)
  19197. {
  19198. }
  19199. AudioIODeviceType::~AudioIODeviceType()
  19200. {
  19201. }
  19202. END_JUCE_NAMESPACE
  19203. /********* End of inlined file: juce_AudioIODeviceType.cpp *********/
  19204. /********* Start of inlined file: juce_MidiOutput.cpp *********/
  19205. BEGIN_JUCE_NAMESPACE
  19206. MidiOutput::MidiOutput() throw()
  19207. : Thread ("midi out"),
  19208. internal (0),
  19209. firstMessage (0)
  19210. {
  19211. }
  19212. MidiOutput::PendingMessage::PendingMessage (const uint8* const data,
  19213. const int len,
  19214. const double sampleNumber) throw()
  19215. : message (data, len, sampleNumber)
  19216. {
  19217. }
  19218. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  19219. const double millisecondCounterToStartAt,
  19220. double samplesPerSecondForBuffer) throw()
  19221. {
  19222. // You've got to call startBackgroundThread() for this to actually work..
  19223. jassert (isThreadRunning());
  19224. // this needs to be a value in the future - RTFM for this method!
  19225. jassert (millisecondCounterToStartAt > 0);
  19226. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  19227. MidiBuffer::Iterator i (buffer);
  19228. const uint8* data;
  19229. int len, time;
  19230. while (i.getNextEvent (data, len, time))
  19231. {
  19232. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  19233. PendingMessage* const m
  19234. = new PendingMessage (data, len, eventTime);
  19235. const ScopedLock sl (lock);
  19236. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  19237. {
  19238. m->next = firstMessage;
  19239. firstMessage = m;
  19240. }
  19241. else
  19242. {
  19243. PendingMessage* mm = firstMessage;
  19244. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  19245. mm = mm->next;
  19246. m->next = mm->next;
  19247. mm->next = m;
  19248. }
  19249. }
  19250. notify();
  19251. }
  19252. void MidiOutput::clearAllPendingMessages() throw()
  19253. {
  19254. const ScopedLock sl (lock);
  19255. while (firstMessage != 0)
  19256. {
  19257. PendingMessage* const m = firstMessage;
  19258. firstMessage = firstMessage->next;
  19259. delete m;
  19260. }
  19261. }
  19262. void MidiOutput::startBackgroundThread() throw()
  19263. {
  19264. startThread (9);
  19265. }
  19266. void MidiOutput::stopBackgroundThread() throw()
  19267. {
  19268. stopThread (5000);
  19269. }
  19270. void MidiOutput::run()
  19271. {
  19272. while (! threadShouldExit())
  19273. {
  19274. uint32 now = Time::getMillisecondCounter();
  19275. uint32 eventTime = 0;
  19276. uint32 timeToWait = 500;
  19277. lock.enter();
  19278. PendingMessage* message = firstMessage;
  19279. if (message != 0)
  19280. {
  19281. eventTime = roundDoubleToInt (message->message.getTimeStamp());
  19282. if (eventTime > now + 20)
  19283. {
  19284. timeToWait = jmax (10, eventTime - now - 100);
  19285. message = 0;
  19286. }
  19287. else
  19288. {
  19289. firstMessage = message->next;
  19290. }
  19291. }
  19292. lock.exit();
  19293. if (message != 0)
  19294. {
  19295. if (eventTime > now)
  19296. {
  19297. Time::waitForMillisecondCounter (eventTime);
  19298. if (threadShouldExit())
  19299. break;
  19300. }
  19301. if (eventTime > now - 200)
  19302. sendMessageNow (message->message);
  19303. delete message;
  19304. }
  19305. else
  19306. {
  19307. jassert (timeToWait < 1000 * 30);
  19308. wait (timeToWait);
  19309. }
  19310. }
  19311. clearAllPendingMessages();
  19312. }
  19313. END_JUCE_NAMESPACE
  19314. /********* End of inlined file: juce_MidiOutput.cpp *********/
  19315. /********* Start of inlined file: juce_AudioDataConverters.cpp *********/
  19316. BEGIN_JUCE_NAMESPACE
  19317. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19318. {
  19319. const double maxVal = (double) 0x7fff;
  19320. char* intData = (char*) dest;
  19321. if (dest != (void*) source || destBytesPerSample <= 4)
  19322. {
  19323. for (int i = 0; i < numSamples; ++i)
  19324. {
  19325. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19326. intData += destBytesPerSample;
  19327. }
  19328. }
  19329. else
  19330. {
  19331. intData += destBytesPerSample * numSamples;
  19332. for (int i = numSamples; --i >= 0;)
  19333. {
  19334. intData -= destBytesPerSample;
  19335. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19336. }
  19337. }
  19338. }
  19339. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19340. {
  19341. const double maxVal = (double) 0x7fff;
  19342. char* intData = (char*) dest;
  19343. if (dest != (void*) source || destBytesPerSample <= 4)
  19344. {
  19345. for (int i = 0; i < numSamples; ++i)
  19346. {
  19347. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19348. intData += destBytesPerSample;
  19349. }
  19350. }
  19351. else
  19352. {
  19353. intData += destBytesPerSample * numSamples;
  19354. for (int i = numSamples; --i >= 0;)
  19355. {
  19356. intData -= destBytesPerSample;
  19357. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19358. }
  19359. }
  19360. }
  19361. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19362. {
  19363. const double maxVal = (double) 0x7fffff;
  19364. char* intData = (char*) dest;
  19365. if (dest != (void*) source || destBytesPerSample <= 4)
  19366. {
  19367. for (int i = 0; i < numSamples; ++i)
  19368. {
  19369. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19370. intData += destBytesPerSample;
  19371. }
  19372. }
  19373. else
  19374. {
  19375. intData += destBytesPerSample * numSamples;
  19376. for (int i = numSamples; --i >= 0;)
  19377. {
  19378. intData -= destBytesPerSample;
  19379. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19380. }
  19381. }
  19382. }
  19383. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19384. {
  19385. const double maxVal = (double) 0x7fffff;
  19386. char* intData = (char*) dest;
  19387. if (dest != (void*) source || destBytesPerSample <= 4)
  19388. {
  19389. for (int i = 0; i < numSamples; ++i)
  19390. {
  19391. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19392. intData += destBytesPerSample;
  19393. }
  19394. }
  19395. else
  19396. {
  19397. intData += destBytesPerSample * numSamples;
  19398. for (int i = numSamples; --i >= 0;)
  19399. {
  19400. intData -= destBytesPerSample;
  19401. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19402. }
  19403. }
  19404. }
  19405. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19406. {
  19407. const double maxVal = (double) 0x7fffffff;
  19408. char* intData = (char*) dest;
  19409. if (dest != (void*) source || destBytesPerSample <= 4)
  19410. {
  19411. for (int i = 0; i < numSamples; ++i)
  19412. {
  19413. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19414. intData += destBytesPerSample;
  19415. }
  19416. }
  19417. else
  19418. {
  19419. intData += destBytesPerSample * numSamples;
  19420. for (int i = numSamples; --i >= 0;)
  19421. {
  19422. intData -= destBytesPerSample;
  19423. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19424. }
  19425. }
  19426. }
  19427. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19428. {
  19429. const double maxVal = (double) 0x7fffffff;
  19430. char* intData = (char*) dest;
  19431. if (dest != (void*) source || destBytesPerSample <= 4)
  19432. {
  19433. for (int i = 0; i < numSamples; ++i)
  19434. {
  19435. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19436. intData += destBytesPerSample;
  19437. }
  19438. }
  19439. else
  19440. {
  19441. intData += destBytesPerSample * numSamples;
  19442. for (int i = numSamples; --i >= 0;)
  19443. {
  19444. intData -= destBytesPerSample;
  19445. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19446. }
  19447. }
  19448. }
  19449. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19450. {
  19451. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  19452. char* d = (char*) dest;
  19453. for (int i = 0; i < numSamples; ++i)
  19454. {
  19455. *(float*)d = source[i];
  19456. #if JUCE_BIG_ENDIAN
  19457. *(uint32*)d = swapByteOrder (*(uint32*)d);
  19458. #endif
  19459. d += destBytesPerSample;
  19460. }
  19461. }
  19462. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19463. {
  19464. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  19465. char* d = (char*) dest;
  19466. for (int i = 0; i < numSamples; ++i)
  19467. {
  19468. *(float*)d = source[i];
  19469. #if JUCE_LITTLE_ENDIAN
  19470. *(uint32*)d = swapByteOrder (*(uint32*)d);
  19471. #endif
  19472. d += destBytesPerSample;
  19473. }
  19474. }
  19475. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19476. {
  19477. const float scale = 1.0f / 0x7fff;
  19478. const char* intData = (const char*) source;
  19479. if (source != (void*) dest || srcBytesPerSample >= 4)
  19480. {
  19481. for (int i = 0; i < numSamples; ++i)
  19482. {
  19483. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  19484. intData += srcBytesPerSample;
  19485. }
  19486. }
  19487. else
  19488. {
  19489. intData += srcBytesPerSample * numSamples;
  19490. for (int i = numSamples; --i >= 0;)
  19491. {
  19492. intData -= srcBytesPerSample;
  19493. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  19494. }
  19495. }
  19496. }
  19497. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19498. {
  19499. const float scale = 1.0f / 0x7fff;
  19500. const char* intData = (const char*) source;
  19501. if (source != (void*) dest || srcBytesPerSample >= 4)
  19502. {
  19503. for (int i = 0; i < numSamples; ++i)
  19504. {
  19505. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  19506. intData += srcBytesPerSample;
  19507. }
  19508. }
  19509. else
  19510. {
  19511. intData += srcBytesPerSample * numSamples;
  19512. for (int i = numSamples; --i >= 0;)
  19513. {
  19514. intData -= srcBytesPerSample;
  19515. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  19516. }
  19517. }
  19518. }
  19519. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19520. {
  19521. const float scale = 1.0f / 0x7fffff;
  19522. const char* intData = (const char*) source;
  19523. if (source != (void*) dest || srcBytesPerSample >= 4)
  19524. {
  19525. for (int i = 0; i < numSamples; ++i)
  19526. {
  19527. dest[i] = scale * (short) littleEndian24Bit (intData);
  19528. intData += srcBytesPerSample;
  19529. }
  19530. }
  19531. else
  19532. {
  19533. intData += srcBytesPerSample * numSamples;
  19534. for (int i = numSamples; --i >= 0;)
  19535. {
  19536. intData -= srcBytesPerSample;
  19537. dest[i] = scale * (short) littleEndian24Bit (intData);
  19538. }
  19539. }
  19540. }
  19541. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19542. {
  19543. const float scale = 1.0f / 0x7fffff;
  19544. const char* intData = (const char*) source;
  19545. if (source != (void*) dest || srcBytesPerSample >= 4)
  19546. {
  19547. for (int i = 0; i < numSamples; ++i)
  19548. {
  19549. dest[i] = scale * (short) bigEndian24Bit (intData);
  19550. intData += srcBytesPerSample;
  19551. }
  19552. }
  19553. else
  19554. {
  19555. intData += srcBytesPerSample * numSamples;
  19556. for (int i = numSamples; --i >= 0;)
  19557. {
  19558. intData -= srcBytesPerSample;
  19559. dest[i] = scale * (short) bigEndian24Bit (intData);
  19560. }
  19561. }
  19562. }
  19563. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19564. {
  19565. const float scale = 1.0f / 0x7fffffff;
  19566. const char* intData = (const char*) source;
  19567. if (source != (void*) dest || srcBytesPerSample >= 4)
  19568. {
  19569. for (int i = 0; i < numSamples; ++i)
  19570. {
  19571. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  19572. intData += srcBytesPerSample;
  19573. }
  19574. }
  19575. else
  19576. {
  19577. intData += srcBytesPerSample * numSamples;
  19578. for (int i = numSamples; --i >= 0;)
  19579. {
  19580. intData -= srcBytesPerSample;
  19581. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  19582. }
  19583. }
  19584. }
  19585. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19586. {
  19587. const float scale = 1.0f / 0x7fffffff;
  19588. const char* intData = (const char*) source;
  19589. if (source != (void*) dest || srcBytesPerSample >= 4)
  19590. {
  19591. for (int i = 0; i < numSamples; ++i)
  19592. {
  19593. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  19594. intData += srcBytesPerSample;
  19595. }
  19596. }
  19597. else
  19598. {
  19599. intData += srcBytesPerSample * numSamples;
  19600. for (int i = numSamples; --i >= 0;)
  19601. {
  19602. intData -= srcBytesPerSample;
  19603. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  19604. }
  19605. }
  19606. }
  19607. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19608. {
  19609. const char* s = (const char*) source;
  19610. for (int i = 0; i < numSamples; ++i)
  19611. {
  19612. dest[i] = *(float*)s;
  19613. #if JUCE_BIG_ENDIAN
  19614. uint32* const d = (uint32*) (dest + i);
  19615. *d = swapByteOrder (*d);
  19616. #endif
  19617. s += srcBytesPerSample;
  19618. }
  19619. }
  19620. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19621. {
  19622. const char* s = (const char*) source;
  19623. for (int i = 0; i < numSamples; ++i)
  19624. {
  19625. dest[i] = *(float*)s;
  19626. #if JUCE_LITTLE_ENDIAN
  19627. uint32* const d = (uint32*) (dest + i);
  19628. *d = swapByteOrder (*d);
  19629. #endif
  19630. s += srcBytesPerSample;
  19631. }
  19632. }
  19633. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  19634. const float* const source,
  19635. void* const dest,
  19636. const int numSamples)
  19637. {
  19638. switch (destFormat)
  19639. {
  19640. case int16LE:
  19641. convertFloatToInt16LE (source, dest, numSamples);
  19642. break;
  19643. case int16BE:
  19644. convertFloatToInt16BE (source, dest, numSamples);
  19645. break;
  19646. case int24LE:
  19647. convertFloatToInt24LE (source, dest, numSamples);
  19648. break;
  19649. case int24BE:
  19650. convertFloatToInt24BE (source, dest, numSamples);
  19651. break;
  19652. case int32LE:
  19653. convertFloatToInt32LE (source, dest, numSamples);
  19654. break;
  19655. case int32BE:
  19656. convertFloatToInt32BE (source, dest, numSamples);
  19657. break;
  19658. case float32LE:
  19659. convertFloatToFloat32LE (source, dest, numSamples);
  19660. break;
  19661. case float32BE:
  19662. convertFloatToFloat32BE (source, dest, numSamples);
  19663. break;
  19664. default:
  19665. jassertfalse
  19666. break;
  19667. }
  19668. }
  19669. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  19670. const void* const source,
  19671. float* const dest,
  19672. const int numSamples)
  19673. {
  19674. switch (sourceFormat)
  19675. {
  19676. case int16LE:
  19677. convertInt16LEToFloat (source, dest, numSamples);
  19678. break;
  19679. case int16BE:
  19680. convertInt16BEToFloat (source, dest, numSamples);
  19681. break;
  19682. case int24LE:
  19683. convertInt24LEToFloat (source, dest, numSamples);
  19684. break;
  19685. case int24BE:
  19686. convertInt24BEToFloat (source, dest, numSamples);
  19687. break;
  19688. case int32LE:
  19689. convertInt32LEToFloat (source, dest, numSamples);
  19690. break;
  19691. case int32BE:
  19692. convertInt32BEToFloat (source, dest, numSamples);
  19693. break;
  19694. case float32LE:
  19695. convertFloat32LEToFloat (source, dest, numSamples);
  19696. break;
  19697. case float32BE:
  19698. convertFloat32BEToFloat (source, dest, numSamples);
  19699. break;
  19700. default:
  19701. jassertfalse
  19702. break;
  19703. }
  19704. }
  19705. void AudioDataConverters::interleaveSamples (const float** const source,
  19706. float* const dest,
  19707. const int numSamples,
  19708. const int numChannels)
  19709. {
  19710. for (int chan = 0; chan < numChannels; ++chan)
  19711. {
  19712. int i = chan;
  19713. const float* src = source [chan];
  19714. for (int j = 0; j < numSamples; ++j)
  19715. {
  19716. dest [i] = src [j];
  19717. i += numChannels;
  19718. }
  19719. }
  19720. }
  19721. void AudioDataConverters::deinterleaveSamples (const float* const source,
  19722. float** const dest,
  19723. const int numSamples,
  19724. const int numChannels)
  19725. {
  19726. for (int chan = 0; chan < numChannels; ++chan)
  19727. {
  19728. int i = chan;
  19729. float* dst = dest [chan];
  19730. for (int j = 0; j < numSamples; ++j)
  19731. {
  19732. dst [j] = source [i];
  19733. i += numChannels;
  19734. }
  19735. }
  19736. }
  19737. END_JUCE_NAMESPACE
  19738. /********* End of inlined file: juce_AudioDataConverters.cpp *********/
  19739. /********* Start of inlined file: juce_AudioSampleBuffer.cpp *********/
  19740. BEGIN_JUCE_NAMESPACE
  19741. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  19742. const int numSamples) throw()
  19743. : numChannels (numChannels_),
  19744. size (numSamples)
  19745. {
  19746. jassert (numSamples >= 0);
  19747. jassert (numChannels_ > 0);
  19748. allocatedBytes = numChannels * numSamples * sizeof (float) + 32;
  19749. allocatedData = (float*) juce_malloc (allocatedBytes);
  19750. channels = (float**) juce_malloc ((numChannels_ + 1) * sizeof (float*));
  19751. float* chan = allocatedData;
  19752. for (int i = 0; i < numChannels_; ++i)
  19753. {
  19754. channels[i] = chan;
  19755. chan += numSamples;
  19756. }
  19757. channels [numChannels_] = 0;
  19758. }
  19759. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  19760. const int numChannels_,
  19761. const int numSamples) throw()
  19762. : numChannels (numChannels_),
  19763. size (numSamples),
  19764. allocatedBytes (0),
  19765. allocatedData (0)
  19766. {
  19767. jassert (numChannels_ > 0);
  19768. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  19769. if (numChannels_ < numElementsInArray (preallocatedChannelSpace))
  19770. channels = (float**) preallocatedChannelSpace;
  19771. else
  19772. channels = (float**) juce_malloc ((numChannels_ + 1) * sizeof (float*));
  19773. for (int i = 0; i < numChannels_; ++i)
  19774. {
  19775. // you have to pass in the same number of valid pointers as numChannels
  19776. jassert (dataToReferTo[i] != 0);
  19777. channels[i] = dataToReferTo[i];
  19778. }
  19779. channels [numChannels_] = 0;
  19780. }
  19781. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  19782. const int numChannels_,
  19783. const int numSamples) throw()
  19784. {
  19785. jassert (numChannels_ > 0);
  19786. juce_free (allocatedData);
  19787. allocatedData = 0;
  19788. allocatedBytes = 0;
  19789. if (numChannels_ > numChannels)
  19790. channels = (float**) juce_realloc (channels, (numChannels_ + 1) * sizeof (float*));
  19791. numChannels = numChannels_;
  19792. size = numSamples;
  19793. for (int i = 0; i < numChannels_; ++i)
  19794. {
  19795. // you have to pass in the same number of valid pointers as numChannels
  19796. jassert (dataToReferTo[i] != 0);
  19797. channels[i] = dataToReferTo[i];
  19798. }
  19799. channels [numChannels_] = 0;
  19800. }
  19801. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  19802. : numChannels (other.numChannels),
  19803. size (other.size)
  19804. {
  19805. channels = (float**) juce_malloc ((other.numChannels + 1) * sizeof (float*));
  19806. if (other.allocatedData != 0)
  19807. {
  19808. allocatedBytes = numChannels * size * sizeof (float) + 32;
  19809. allocatedData = (float*) juce_malloc (allocatedBytes);
  19810. memcpy (allocatedData, other.allocatedData, allocatedBytes);
  19811. float* chan = allocatedData;
  19812. for (int i = 0; i < numChannels; ++i)
  19813. {
  19814. channels[i] = chan;
  19815. chan += size;
  19816. }
  19817. channels [numChannels] = 0;
  19818. }
  19819. else
  19820. {
  19821. allocatedData = 0;
  19822. allocatedBytes = 0;
  19823. memcpy (channels, other.channels, sizeof (channels));
  19824. }
  19825. }
  19826. const AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  19827. {
  19828. if (this != &other)
  19829. {
  19830. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  19831. const int numBytes = size * sizeof (float);
  19832. for (int i = 0; i < numChannels; ++i)
  19833. memcpy (channels[i], other.channels[i], numBytes);
  19834. }
  19835. return *this;
  19836. }
  19837. AudioSampleBuffer::~AudioSampleBuffer() throw()
  19838. {
  19839. juce_free (allocatedData);
  19840. if (channels != (float**) preallocatedChannelSpace)
  19841. juce_free (channels);
  19842. }
  19843. void AudioSampleBuffer::setSize (const int newNumChannels,
  19844. const int newNumSamples,
  19845. const bool keepExistingContent,
  19846. const bool clearExtraSpace,
  19847. const bool avoidReallocating) throw()
  19848. {
  19849. jassert (newNumChannels > 0);
  19850. if (newNumSamples != size || newNumChannels != numChannels)
  19851. {
  19852. const int newTotalBytes = newNumChannels * newNumSamples * sizeof (float) + 32;
  19853. if (keepExistingContent)
  19854. {
  19855. float* const newData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  19856. : (float*) juce_malloc (newTotalBytes);
  19857. const int sizeToCopy = sizeof (float) * jmin (newNumSamples, size);
  19858. for (int i = jmin (newNumChannels, numChannels); --i >= 0;)
  19859. {
  19860. memcpy (newData + i * newNumSamples,
  19861. channels[i],
  19862. sizeToCopy);
  19863. }
  19864. juce_free (allocatedData);
  19865. allocatedData = newData;
  19866. allocatedBytes = newTotalBytes;
  19867. }
  19868. else
  19869. {
  19870. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  19871. {
  19872. if (clearExtraSpace)
  19873. zeromem (allocatedData, newTotalBytes);
  19874. }
  19875. else
  19876. {
  19877. juce_free (allocatedData);
  19878. allocatedData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  19879. : (float*) juce_malloc (newTotalBytes);
  19880. allocatedBytes = newTotalBytes;
  19881. }
  19882. }
  19883. size = newNumSamples;
  19884. if (newNumChannels > numChannels)
  19885. channels = (float**) juce_realloc (channels, (newNumChannels + 1) * sizeof (float*));
  19886. numChannels = newNumChannels;
  19887. float* chan = allocatedData;
  19888. for (int i = 0; i < newNumChannels; ++i)
  19889. {
  19890. channels[i] = chan;
  19891. chan += size;
  19892. }
  19893. channels [newNumChannels] = 0;
  19894. }
  19895. }
  19896. void AudioSampleBuffer::clear() throw()
  19897. {
  19898. for (int i = 0; i < numChannels; ++i)
  19899. zeromem (channels[i], size * sizeof (float));
  19900. }
  19901. void AudioSampleBuffer::clear (const int startSample,
  19902. const int numSamples) throw()
  19903. {
  19904. jassert (startSample >= 0 && startSample + numSamples <= size);
  19905. for (int i = 0; i < numChannels; ++i)
  19906. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  19907. }
  19908. void AudioSampleBuffer::clear (const int channel,
  19909. const int startSample,
  19910. const int numSamples) throw()
  19911. {
  19912. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  19913. jassert (startSample >= 0 && startSample + numSamples <= size);
  19914. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  19915. }
  19916. void AudioSampleBuffer::applyGain (const int channel,
  19917. const int startSample,
  19918. int numSamples,
  19919. const float gain) throw()
  19920. {
  19921. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  19922. jassert (startSample >= 0 && startSample + numSamples <= size);
  19923. if (gain != 1.0f)
  19924. {
  19925. float* d = channels [channel] + startSample;
  19926. if (gain == 0.0f)
  19927. {
  19928. zeromem (d, sizeof (float) * numSamples);
  19929. }
  19930. else
  19931. {
  19932. while (--numSamples >= 0)
  19933. *d++ *= gain;
  19934. }
  19935. }
  19936. }
  19937. void AudioSampleBuffer::applyGainRamp (const int channel,
  19938. const int startSample,
  19939. int numSamples,
  19940. float startGain,
  19941. float endGain) throw()
  19942. {
  19943. if (startGain == endGain)
  19944. {
  19945. applyGain (channel, startSample, numSamples, startGain);
  19946. }
  19947. else
  19948. {
  19949. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  19950. jassert (startSample >= 0 && startSample + numSamples <= size);
  19951. const float increment = (endGain - startGain) / numSamples;
  19952. float* d = channels [channel] + startSample;
  19953. while (--numSamples >= 0)
  19954. {
  19955. *d++ *= startGain;
  19956. startGain += increment;
  19957. }
  19958. }
  19959. }
  19960. void AudioSampleBuffer::applyGain (const int startSample,
  19961. const int numSamples,
  19962. const float gain) throw()
  19963. {
  19964. for (int i = 0; i < numChannels; ++i)
  19965. applyGain (i, startSample, numSamples, gain);
  19966. }
  19967. void AudioSampleBuffer::addFrom (const int destChannel,
  19968. const int destStartSample,
  19969. const AudioSampleBuffer& source,
  19970. const int sourceChannel,
  19971. const int sourceStartSample,
  19972. int numSamples,
  19973. const float gain) throw()
  19974. {
  19975. jassert (&source != this || sourceChannel != destChannel);
  19976. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  19977. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  19978. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  19979. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  19980. if (gain != 0.0f && numSamples > 0)
  19981. {
  19982. float* d = channels [destChannel] + destStartSample;
  19983. const float* s = source.channels [sourceChannel] + sourceStartSample;
  19984. if (gain != 1.0f)
  19985. {
  19986. while (--numSamples >= 0)
  19987. *d++ += gain * *s++;
  19988. }
  19989. else
  19990. {
  19991. while (--numSamples >= 0)
  19992. *d++ += *s++;
  19993. }
  19994. }
  19995. }
  19996. void AudioSampleBuffer::addFrom (const int destChannel,
  19997. const int destStartSample,
  19998. const float* source,
  19999. int numSamples,
  20000. const float gain) throw()
  20001. {
  20002. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20003. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20004. jassert (source != 0);
  20005. if (gain != 0.0f && numSamples > 0)
  20006. {
  20007. float* d = channels [destChannel] + destStartSample;
  20008. if (gain != 1.0f)
  20009. {
  20010. while (--numSamples >= 0)
  20011. *d++ += gain * *source++;
  20012. }
  20013. else
  20014. {
  20015. while (--numSamples >= 0)
  20016. *d++ += *source++;
  20017. }
  20018. }
  20019. }
  20020. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20021. const int destStartSample,
  20022. const float* source,
  20023. int numSamples,
  20024. float startGain,
  20025. const float endGain) throw()
  20026. {
  20027. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20028. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20029. jassert (source != 0);
  20030. if (startGain == endGain)
  20031. {
  20032. addFrom (destChannel,
  20033. destStartSample,
  20034. source,
  20035. numSamples,
  20036. startGain);
  20037. }
  20038. else
  20039. {
  20040. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20041. {
  20042. const float increment = (endGain - startGain) / numSamples;
  20043. float* d = channels [destChannel] + destStartSample;
  20044. while (--numSamples >= 0)
  20045. {
  20046. *d++ += startGain * *source++;
  20047. startGain += increment;
  20048. }
  20049. }
  20050. }
  20051. }
  20052. void AudioSampleBuffer::copyFrom (const int destChannel,
  20053. const int destStartSample,
  20054. const AudioSampleBuffer& source,
  20055. const int sourceChannel,
  20056. const int sourceStartSample,
  20057. int numSamples) throw()
  20058. {
  20059. jassert (&source != this || sourceChannel != destChannel);
  20060. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20061. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20062. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20063. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20064. if (numSamples > 0)
  20065. {
  20066. memcpy (channels [destChannel] + destStartSample,
  20067. source.channels [sourceChannel] + sourceStartSample,
  20068. sizeof (float) * numSamples);
  20069. }
  20070. }
  20071. void AudioSampleBuffer::copyFrom (const int destChannel,
  20072. const int destStartSample,
  20073. const float* source,
  20074. int numSamples) throw()
  20075. {
  20076. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20077. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20078. jassert (source != 0);
  20079. if (numSamples > 0)
  20080. {
  20081. memcpy (channels [destChannel] + destStartSample,
  20082. source,
  20083. sizeof (float) * numSamples);
  20084. }
  20085. }
  20086. void AudioSampleBuffer::copyFrom (const int destChannel,
  20087. const int destStartSample,
  20088. const float* source,
  20089. int numSamples,
  20090. const float gain) throw()
  20091. {
  20092. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20093. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20094. jassert (source != 0);
  20095. if (numSamples > 0 && gain != 0)
  20096. {
  20097. float* d = channels [destChannel] + destStartSample;
  20098. if (gain != 1.0f)
  20099. {
  20100. while (--numSamples >= 0)
  20101. *d++ = gain * *source++;
  20102. }
  20103. else
  20104. {
  20105. memcpy (d, source, sizeof (float) * numSamples);
  20106. }
  20107. }
  20108. }
  20109. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  20110. const int destStartSample,
  20111. const float* source,
  20112. int numSamples,
  20113. float startGain,
  20114. float endGain) throw()
  20115. {
  20116. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20117. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20118. jassert (source != 0);
  20119. if (startGain == endGain)
  20120. {
  20121. copyFrom (destChannel,
  20122. destStartSample,
  20123. source,
  20124. numSamples,
  20125. startGain);
  20126. }
  20127. else
  20128. {
  20129. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20130. {
  20131. const float increment = (endGain - startGain) / numSamples;
  20132. float* d = channels [destChannel] + destStartSample;
  20133. while (--numSamples >= 0)
  20134. {
  20135. *d++ = startGain * *source++;
  20136. startGain += increment;
  20137. }
  20138. }
  20139. }
  20140. }
  20141. void AudioSampleBuffer::findMinMax (const int channel,
  20142. const int startSample,
  20143. int numSamples,
  20144. float& minVal,
  20145. float& maxVal) const throw()
  20146. {
  20147. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20148. jassert (startSample >= 0 && startSample + numSamples <= size);
  20149. if (numSamples <= 0)
  20150. {
  20151. minVal = 0.0f;
  20152. maxVal = 0.0f;
  20153. }
  20154. else
  20155. {
  20156. const float* d = channels [channel] + startSample;
  20157. float mn = *d++;
  20158. float mx = mn;
  20159. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  20160. {
  20161. const float samp = *d++;
  20162. if (samp > mx)
  20163. mx = samp;
  20164. if (samp < mn)
  20165. mn = samp;
  20166. }
  20167. maxVal = mx;
  20168. minVal = mn;
  20169. }
  20170. }
  20171. float AudioSampleBuffer::getMagnitude (const int channel,
  20172. const int startSample,
  20173. const int numSamples) const throw()
  20174. {
  20175. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20176. jassert (startSample >= 0 && startSample + numSamples <= size);
  20177. float mn, mx;
  20178. findMinMax (channel, startSample, numSamples, mn, mx);
  20179. return jmax (mn, -mn, mx, -mx);
  20180. }
  20181. float AudioSampleBuffer::getMagnitude (const int startSample,
  20182. const int numSamples) const throw()
  20183. {
  20184. float mag = 0.0f;
  20185. for (int i = 0; i < numChannels; ++i)
  20186. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  20187. return mag;
  20188. }
  20189. float AudioSampleBuffer::getRMSLevel (const int channel,
  20190. const int startSample,
  20191. const int numSamples) const throw()
  20192. {
  20193. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20194. jassert (startSample >= 0 && startSample + numSamples <= size);
  20195. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  20196. return 0.0f;
  20197. const float* const data = channels [channel] + startSample;
  20198. double sum = 0.0;
  20199. for (int i = 0; i < numSamples; ++i)
  20200. {
  20201. const float sample = data [i];
  20202. sum += sample * sample;
  20203. }
  20204. return (float) sqrt (sum / numSamples);
  20205. }
  20206. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  20207. const int startSample,
  20208. const int numSamples,
  20209. const int readerStartSample,
  20210. const bool useLeftChan,
  20211. const bool useRightChan) throw()
  20212. {
  20213. jassert (reader != 0);
  20214. jassert (startSample >= 0 && startSample + numSamples <= size);
  20215. if (numSamples > 0)
  20216. {
  20217. int* chans[3];
  20218. if (useLeftChan == useRightChan)
  20219. {
  20220. chans[0] = (int*) getSampleData (0, startSample);
  20221. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  20222. }
  20223. else if (useLeftChan || (reader->numChannels == 1))
  20224. {
  20225. chans[0] = (int*) getSampleData (0, startSample);
  20226. chans[1] = 0;
  20227. }
  20228. else if (useRightChan)
  20229. {
  20230. chans[0] = 0;
  20231. chans[1] = (int*) getSampleData (0, startSample);
  20232. }
  20233. chans[2] = 0;
  20234. reader->read (chans, 2, readerStartSample, numSamples, true);
  20235. if (! reader->usesFloatingPointData)
  20236. {
  20237. for (int j = 0; j < 2; ++j)
  20238. {
  20239. float* const d = (float*) (chans[j]);
  20240. if (d != 0)
  20241. {
  20242. const float multiplier = 1.0f / 0x7fffffff;
  20243. for (int i = 0; i < numSamples; ++i)
  20244. d[i] = *(int*)(d + i) * multiplier;
  20245. }
  20246. }
  20247. }
  20248. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  20249. {
  20250. // if this is a stereo buffer and the source was mono, dupe the first channel..
  20251. memcpy (getSampleData (1, startSample),
  20252. getSampleData (0, startSample),
  20253. sizeof (float) * numSamples);
  20254. }
  20255. }
  20256. }
  20257. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  20258. const int startSample,
  20259. const int numSamples) const throw()
  20260. {
  20261. jassert (startSample >= 0 && startSample + numSamples <= size);
  20262. if (numSamples > 0)
  20263. {
  20264. int* chans [3];
  20265. if (writer->isFloatingPoint())
  20266. {
  20267. chans[0] = (int*) getSampleData (0, startSample);
  20268. if (numChannels > 1)
  20269. chans[1] = (int*) getSampleData (1, startSample);
  20270. else
  20271. chans[1] = 0;
  20272. chans[2] = 0;
  20273. writer->write ((const int**) chans, numSamples);
  20274. }
  20275. else
  20276. {
  20277. chans[0] = (int*) juce_malloc (sizeof (int) * numSamples * 2);
  20278. if (numChannels > 1)
  20279. chans[1] = chans[0] + numSamples;
  20280. else
  20281. chans[1] = 0;
  20282. chans[2] = 0;
  20283. for (int j = 0; j < 2; ++j)
  20284. {
  20285. int* const dest = chans[j];
  20286. if (dest != 0)
  20287. {
  20288. const float* const src = channels [j] + startSample;
  20289. for (int i = 0; i < numSamples; ++i)
  20290. {
  20291. const double samp = src[i];
  20292. if (samp <= -1.0)
  20293. dest[i] = INT_MIN;
  20294. else if (samp >= 1.0)
  20295. dest[i] = INT_MAX;
  20296. else
  20297. dest[i] = roundDoubleToInt (INT_MAX * samp);
  20298. }
  20299. }
  20300. }
  20301. writer->write ((const int**) chans, numSamples);
  20302. juce_free (chans[0]);
  20303. }
  20304. }
  20305. }
  20306. END_JUCE_NAMESPACE
  20307. /********* End of inlined file: juce_AudioSampleBuffer.cpp *********/
  20308. /********* Start of inlined file: juce_IIRFilter.cpp *********/
  20309. BEGIN_JUCE_NAMESPACE
  20310. IIRFilter::IIRFilter() throw()
  20311. : active (false)
  20312. {
  20313. reset();
  20314. }
  20315. IIRFilter::IIRFilter (const IIRFilter& other) throw()
  20316. : active (other.active)
  20317. {
  20318. const ScopedLock sl (other.processLock);
  20319. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  20320. reset();
  20321. }
  20322. IIRFilter::~IIRFilter() throw()
  20323. {
  20324. }
  20325. void IIRFilter::reset() throw()
  20326. {
  20327. const ScopedLock sl (processLock);
  20328. x1 = 0;
  20329. x2 = 0;
  20330. y1 = 0;
  20331. y2 = 0;
  20332. }
  20333. float IIRFilter::processSingleSampleRaw (const float in) throw()
  20334. {
  20335. float out = coefficients[0] * in
  20336. + coefficients[1] * x1
  20337. + coefficients[2] * x2
  20338. - coefficients[4] * y1
  20339. - coefficients[5] * y2;
  20340. #if JUCE_INTEL
  20341. if (! (out < -1.0e-8 || out > 1.0e-8))
  20342. out = 0;
  20343. #endif
  20344. x2 = x1;
  20345. x1 = in;
  20346. y2 = y1;
  20347. y1 = out;
  20348. return out;
  20349. }
  20350. void IIRFilter::processSamples (float* const samples,
  20351. const int numSamples) throw()
  20352. {
  20353. const ScopedLock sl (processLock);
  20354. if (active)
  20355. {
  20356. for (int i = 0; i < numSamples; ++i)
  20357. {
  20358. const float in = samples[i];
  20359. float out = coefficients[0] * in
  20360. + coefficients[1] * x1
  20361. + coefficients[2] * x2
  20362. - coefficients[4] * y1
  20363. - coefficients[5] * y2;
  20364. #if JUCE_INTEL
  20365. if (! (out < -1.0e-8 || out > 1.0e-8))
  20366. out = 0;
  20367. #endif
  20368. x2 = x1;
  20369. x1 = in;
  20370. y2 = y1;
  20371. y1 = out;
  20372. samples[i] = out;
  20373. }
  20374. }
  20375. }
  20376. void IIRFilter::makeLowPass (const double sampleRate,
  20377. const double frequency) throw()
  20378. {
  20379. jassert (sampleRate > 0);
  20380. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  20381. const double nSquared = n * n;
  20382. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  20383. setCoefficients (c1,
  20384. c1 * 2.0f,
  20385. c1,
  20386. 1.0,
  20387. c1 * 2.0 * (1.0 - nSquared),
  20388. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  20389. }
  20390. void IIRFilter::makeHighPass (const double sampleRate,
  20391. const double frequency) throw()
  20392. {
  20393. const double n = tan (double_Pi * frequency / sampleRate);
  20394. const double nSquared = n * n;
  20395. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  20396. setCoefficients (c1,
  20397. c1 * -2.0f,
  20398. c1,
  20399. 1.0,
  20400. c1 * 2.0 * (nSquared - 1.0),
  20401. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  20402. }
  20403. void IIRFilter::makeLowShelf (const double sampleRate,
  20404. const double cutOffFrequency,
  20405. const double Q,
  20406. const float gainFactor) throw()
  20407. {
  20408. jassert (sampleRate > 0);
  20409. jassert (Q > 0);
  20410. const double A = jmax (0.0f, gainFactor);
  20411. const double aminus1 = A - 1.0;
  20412. const double aplus1 = A + 1.0;
  20413. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  20414. const double coso = cos (omega);
  20415. const double beta = sin (omega) * sqrt (A) / Q;
  20416. const double aminus1TimesCoso = aminus1 * coso;
  20417. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  20418. A * 2.0 * (aminus1 - aplus1 * coso),
  20419. A * (aplus1 - aminus1TimesCoso - beta),
  20420. aplus1 + aminus1TimesCoso + beta,
  20421. -2.0 * (aminus1 + aplus1 * coso),
  20422. aplus1 + aminus1TimesCoso - beta);
  20423. }
  20424. void IIRFilter::makeHighShelf (const double sampleRate,
  20425. const double cutOffFrequency,
  20426. const double Q,
  20427. const float gainFactor) throw()
  20428. {
  20429. jassert (sampleRate > 0);
  20430. jassert (Q > 0);
  20431. const double A = jmax (0.0f, gainFactor);
  20432. const double aminus1 = A - 1.0;
  20433. const double aplus1 = A + 1.0;
  20434. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  20435. const double coso = cos (omega);
  20436. const double beta = sin (omega) * sqrt (A) / Q;
  20437. const double aminus1TimesCoso = aminus1 * coso;
  20438. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  20439. A * -2.0 * (aminus1 + aplus1 * coso),
  20440. A * (aplus1 + aminus1TimesCoso - beta),
  20441. aplus1 - aminus1TimesCoso + beta,
  20442. 2.0 * (aminus1 - aplus1 * coso),
  20443. aplus1 - aminus1TimesCoso - beta);
  20444. }
  20445. void IIRFilter::makeBandPass (const double sampleRate,
  20446. const double centreFrequency,
  20447. const double Q,
  20448. const float gainFactor) throw()
  20449. {
  20450. jassert (sampleRate > 0);
  20451. jassert (Q > 0);
  20452. const double A = jmax (0.0f, gainFactor);
  20453. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  20454. const double alpha = 0.5 * sin (omega) / Q;
  20455. const double c2 = -2.0 * cos (omega);
  20456. const double alphaTimesA = alpha * A;
  20457. const double alphaOverA = alpha / A;
  20458. setCoefficients (1.0 + alphaTimesA,
  20459. c2,
  20460. 1.0 - alphaTimesA,
  20461. 1.0 + alphaOverA,
  20462. c2,
  20463. 1.0 - alphaOverA);
  20464. }
  20465. void IIRFilter::makeInactive() throw()
  20466. {
  20467. const ScopedLock sl (processLock);
  20468. active = false;
  20469. }
  20470. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  20471. {
  20472. const ScopedLock sl (processLock);
  20473. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  20474. active = other.active;
  20475. }
  20476. void IIRFilter::setCoefficients (double c1,
  20477. double c2,
  20478. double c3,
  20479. double c4,
  20480. double c5,
  20481. double c6) throw()
  20482. {
  20483. const double a = 1.0 / c4;
  20484. c1 *= a;
  20485. c2 *= a;
  20486. c3 *= a;
  20487. c5 *= a;
  20488. c6 *= a;
  20489. const ScopedLock sl (processLock);
  20490. coefficients[0] = (float) c1;
  20491. coefficients[1] = (float) c2;
  20492. coefficients[2] = (float) c3;
  20493. coefficients[3] = (float) c4;
  20494. coefficients[4] = (float) c5;
  20495. coefficients[5] = (float) c6;
  20496. active = true;
  20497. }
  20498. END_JUCE_NAMESPACE
  20499. /********* End of inlined file: juce_IIRFilter.cpp *********/
  20500. /********* Start of inlined file: juce_MidiBuffer.cpp *********/
  20501. BEGIN_JUCE_NAMESPACE
  20502. MidiBuffer::MidiBuffer() throw()
  20503. : ArrayAllocationBase <uint8> (32),
  20504. bytesUsed (0)
  20505. {
  20506. }
  20507. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  20508. : ArrayAllocationBase <uint8> (32),
  20509. bytesUsed (0)
  20510. {
  20511. addEvent (message, 0);
  20512. }
  20513. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  20514. : ArrayAllocationBase <uint8> (32),
  20515. bytesUsed (other.bytesUsed)
  20516. {
  20517. ensureAllocatedSize (bytesUsed);
  20518. memcpy (elements, other.elements, bytesUsed);
  20519. }
  20520. const MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  20521. {
  20522. if (this != &other)
  20523. {
  20524. bytesUsed = other.bytesUsed;
  20525. ensureAllocatedSize (bytesUsed);
  20526. if (bytesUsed > 0)
  20527. memcpy (elements, other.elements, bytesUsed);
  20528. }
  20529. return *this;
  20530. }
  20531. void MidiBuffer::swap (MidiBuffer& other)
  20532. {
  20533. swapVariables <uint8*> (this->elements, other.elements);
  20534. swapVariables <int> (this->numAllocated, other.numAllocated);
  20535. swapVariables <int> (this->bytesUsed, other.bytesUsed);
  20536. }
  20537. MidiBuffer::~MidiBuffer() throw()
  20538. {
  20539. }
  20540. void MidiBuffer::clear() throw()
  20541. {
  20542. bytesUsed = 0;
  20543. }
  20544. void MidiBuffer::clear (const int startSample,
  20545. const int numSamples) throw()
  20546. {
  20547. uint8* const start = findEventAfter (elements, startSample - 1);
  20548. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  20549. if (end > start)
  20550. {
  20551. const size_t bytesToMove = (size_t) (bytesUsed - (end - elements));
  20552. if (bytesToMove > 0)
  20553. memmove (start, end, bytesToMove);
  20554. bytesUsed -= (int) (end - start);
  20555. }
  20556. }
  20557. void MidiBuffer::addEvent (const MidiMessage& m,
  20558. const int sampleNumber) throw()
  20559. {
  20560. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  20561. }
  20562. static int findActualEventLength (const uint8* const data,
  20563. const int maxBytes) throw()
  20564. {
  20565. unsigned int byte = (unsigned int) *data;
  20566. int size = 0;
  20567. if (byte == 0xf0 || byte == 0xf7)
  20568. {
  20569. const uint8* d = data + 1;
  20570. while (d < data + maxBytes)
  20571. if (*d++ == 0xf7)
  20572. break;
  20573. size = (int) (d - data);
  20574. }
  20575. else if (byte == 0xff)
  20576. {
  20577. int n;
  20578. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  20579. size = jmin (maxBytes, n + 2 + bytesLeft);
  20580. }
  20581. else if (byte >= 0x80)
  20582. {
  20583. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  20584. }
  20585. return size;
  20586. }
  20587. void MidiBuffer::addEvent (const uint8* const newData,
  20588. const int maxBytes,
  20589. const int sampleNumber) throw()
  20590. {
  20591. const int numBytes = findActualEventLength (newData, maxBytes);
  20592. if (numBytes > 0)
  20593. {
  20594. ensureAllocatedSize (bytesUsed + numBytes + 6);
  20595. uint8* d = findEventAfter (elements, sampleNumber);
  20596. const size_t bytesToMove = (size_t) (bytesUsed - (d - elements));
  20597. if (bytesToMove > 0)
  20598. memmove (d + numBytes + 6,
  20599. d,
  20600. bytesToMove);
  20601. *(int*) d = sampleNumber;
  20602. d += 4;
  20603. *(uint16*) d = (uint16) numBytes;
  20604. d += 2;
  20605. memcpy (d, newData, numBytes);
  20606. bytesUsed += numBytes + 6;
  20607. }
  20608. }
  20609. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  20610. const int startSample,
  20611. const int numSamples,
  20612. const int sampleDeltaToAdd) throw()
  20613. {
  20614. Iterator i (otherBuffer);
  20615. i.setNextSamplePosition (startSample);
  20616. const uint8* data;
  20617. int size, position;
  20618. while (i.getNextEvent (data, size, position)
  20619. && (position < startSample + numSamples || numSamples < 0))
  20620. {
  20621. addEvent (data, size, position + sampleDeltaToAdd);
  20622. }
  20623. }
  20624. bool MidiBuffer::isEmpty() const throw()
  20625. {
  20626. return bytesUsed == 0;
  20627. }
  20628. int MidiBuffer::getNumEvents() const throw()
  20629. {
  20630. int n = 0;
  20631. const uint8* d = elements;
  20632. const uint8* const end = elements + bytesUsed;
  20633. while (d < end)
  20634. {
  20635. d += 4;
  20636. d += 2 + *(const uint16*) d;
  20637. ++n;
  20638. }
  20639. return n;
  20640. }
  20641. int MidiBuffer::getFirstEventTime() const throw()
  20642. {
  20643. return (bytesUsed > 0) ? *(const int*) elements : 0;
  20644. }
  20645. int MidiBuffer::getLastEventTime() const throw()
  20646. {
  20647. if (bytesUsed == 0)
  20648. return 0;
  20649. const uint8* d = elements;
  20650. const uint8* const endData = d + bytesUsed;
  20651. for (;;)
  20652. {
  20653. const uint8* nextOne = d + 6 + * (const uint16*) (d + 4);
  20654. if (nextOne >= endData)
  20655. return *(const int*) d;
  20656. d = nextOne;
  20657. }
  20658. }
  20659. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  20660. {
  20661. const uint8* const endData = elements + bytesUsed;
  20662. while (d < endData && *(int*) d <= samplePosition)
  20663. {
  20664. d += 4;
  20665. d += 2 + *(uint16*) d;
  20666. }
  20667. return d;
  20668. }
  20669. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer) throw()
  20670. : buffer (buffer),
  20671. data (buffer.elements)
  20672. {
  20673. }
  20674. MidiBuffer::Iterator::~Iterator() throw()
  20675. {
  20676. }
  20677. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  20678. {
  20679. data = buffer.elements;
  20680. const uint8* dataEnd = buffer.elements + buffer.bytesUsed;
  20681. while (data < dataEnd && *(int*) data < samplePosition)
  20682. {
  20683. data += 4;
  20684. data += 2 + *(uint16*) data;
  20685. }
  20686. }
  20687. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData,
  20688. int& numBytes,
  20689. int& samplePosition) throw()
  20690. {
  20691. if (data >= buffer.elements + buffer.bytesUsed)
  20692. return false;
  20693. samplePosition = *(int*) data;
  20694. data += 4;
  20695. numBytes = *(uint16*) data;
  20696. data += 2;
  20697. midiData = data;
  20698. data += numBytes;
  20699. return true;
  20700. }
  20701. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result,
  20702. int& samplePosition) throw()
  20703. {
  20704. if (data >= buffer.elements + buffer.bytesUsed)
  20705. return false;
  20706. samplePosition = *(int*) data;
  20707. data += 4;
  20708. const int numBytes = *(uint16*) data;
  20709. data += 2;
  20710. result = MidiMessage (data, numBytes, samplePosition);
  20711. data += numBytes;
  20712. return true;
  20713. }
  20714. END_JUCE_NAMESPACE
  20715. /********* End of inlined file: juce_MidiBuffer.cpp *********/
  20716. /********* Start of inlined file: juce_MidiFile.cpp *********/
  20717. BEGIN_JUCE_NAMESPACE
  20718. struct TempoInfo
  20719. {
  20720. double bpm, timestamp;
  20721. };
  20722. struct TimeSigInfo
  20723. {
  20724. int numerator, denominator;
  20725. double timestamp;
  20726. };
  20727. MidiFile::MidiFile() throw()
  20728. : numTracks (0),
  20729. timeFormat ((short)(unsigned short)0xe728)
  20730. {
  20731. }
  20732. MidiFile::~MidiFile() throw()
  20733. {
  20734. clear();
  20735. }
  20736. void MidiFile::clear() throw()
  20737. {
  20738. while (numTracks > 0)
  20739. delete tracks [--numTracks];
  20740. }
  20741. int MidiFile::getNumTracks() const throw()
  20742. {
  20743. return numTracks;
  20744. }
  20745. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  20746. {
  20747. return (((unsigned int) index) < (unsigned int) numTracks) ? tracks[index] : 0;
  20748. }
  20749. void MidiFile::addTrack (const MidiMessageSequence& trackSequence) throw()
  20750. {
  20751. jassert (numTracks < numElementsInArray (tracks));
  20752. if (numTracks < numElementsInArray (tracks))
  20753. tracks [numTracks++] = new MidiMessageSequence (trackSequence);
  20754. }
  20755. short MidiFile::getTimeFormat() const throw()
  20756. {
  20757. return timeFormat;
  20758. }
  20759. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  20760. {
  20761. timeFormat = (short)ticks;
  20762. }
  20763. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  20764. const int subframeResolution) throw()
  20765. {
  20766. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  20767. }
  20768. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  20769. {
  20770. for (int i = numTracks; --i >= 0;)
  20771. {
  20772. const int numEvents = tracks[i]->getNumEvents();
  20773. for (int j = 0; j < numEvents; ++j)
  20774. {
  20775. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  20776. if (m.isTempoMetaEvent())
  20777. tempoChangeEvents.addEvent (m);
  20778. }
  20779. }
  20780. }
  20781. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  20782. {
  20783. for (int i = numTracks; --i >= 0;)
  20784. {
  20785. const int numEvents = tracks[i]->getNumEvents();
  20786. for (int j = 0; j < numEvents; ++j)
  20787. {
  20788. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  20789. if (m.isTimeSignatureMetaEvent())
  20790. timeSigEvents.addEvent (m);
  20791. }
  20792. }
  20793. }
  20794. double MidiFile::getLastTimestamp() const
  20795. {
  20796. double t = 0.0;
  20797. for (int i = numTracks; --i >= 0;)
  20798. t = jmax (t, tracks[i]->getEndTime());
  20799. return t;
  20800. }
  20801. static bool parseMidiHeader (const char* &data,
  20802. short& timeFormat,
  20803. short& fileType,
  20804. short& numberOfTracks)
  20805. {
  20806. unsigned int ch = (int) bigEndianInt (data);
  20807. data += 4;
  20808. if (ch != bigEndianInt ("MThd"))
  20809. {
  20810. bool ok = false;
  20811. if (ch == bigEndianInt ("RIFF"))
  20812. {
  20813. for (int i = 0; i < 8; ++i)
  20814. {
  20815. ch = bigEndianInt (data);
  20816. data += 4;
  20817. if (ch == bigEndianInt ("MThd"))
  20818. {
  20819. ok = true;
  20820. break;
  20821. }
  20822. }
  20823. }
  20824. if (! ok)
  20825. return false;
  20826. }
  20827. unsigned int bytesRemaining = bigEndianInt (data);
  20828. data += 4;
  20829. fileType = (short)bigEndianShort (data);
  20830. data += 2;
  20831. numberOfTracks = (short)bigEndianShort (data);
  20832. data += 2;
  20833. timeFormat = (short)bigEndianShort (data);
  20834. data += 2;
  20835. bytesRemaining -= 6;
  20836. data += bytesRemaining;
  20837. return true;
  20838. }
  20839. bool MidiFile::readFrom (InputStream& sourceStream)
  20840. {
  20841. clear();
  20842. MemoryBlock data;
  20843. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  20844. // (put a sanity-check on the file size, as midi files are generally small)
  20845. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  20846. {
  20847. int size = data.getSize();
  20848. const char* d = (char*) data.getData();
  20849. short fileType, expectedTracks;
  20850. if (size > 16 && parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  20851. {
  20852. size -= (int) (d - (char*) data.getData());
  20853. int track = 0;
  20854. while (size > 0 && track < expectedTracks)
  20855. {
  20856. const int chunkType = (int)bigEndianInt (d);
  20857. d += 4;
  20858. const int chunkSize = (int)bigEndianInt (d);
  20859. d += 4;
  20860. if (chunkSize <= 0)
  20861. break;
  20862. if (size < 0)
  20863. return false;
  20864. if (chunkType == (int)bigEndianInt ("MTrk"))
  20865. {
  20866. readNextTrack (d, chunkSize);
  20867. }
  20868. size -= chunkSize + 8;
  20869. d += chunkSize;
  20870. ++track;
  20871. }
  20872. return true;
  20873. }
  20874. }
  20875. return false;
  20876. }
  20877. // a comparator that puts all the note-offs before note-ons that have the same time
  20878. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  20879. const MidiMessageSequence::MidiEventHolder* const second) throw()
  20880. {
  20881. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  20882. if (diff == 0)
  20883. {
  20884. if (first->message.isNoteOff() && second->message.isNoteOn())
  20885. return -1;
  20886. else if (first->message.isNoteOn() && second->message.isNoteOff())
  20887. return 1;
  20888. else
  20889. return 0;
  20890. }
  20891. else
  20892. {
  20893. return (diff > 0) ? 1 : -1;
  20894. }
  20895. }
  20896. void MidiFile::readNextTrack (const char* data, int size)
  20897. {
  20898. double time = 0;
  20899. char lastStatusByte = 0;
  20900. MidiMessageSequence result;
  20901. while (size > 0)
  20902. {
  20903. int bytesUsed;
  20904. const int delay = MidiMessage::readVariableLengthVal ((const uint8*) data, bytesUsed);
  20905. data += bytesUsed;
  20906. size -= bytesUsed;
  20907. time += delay;
  20908. int messSize = 0;
  20909. const MidiMessage mm ((const uint8*) data, size, messSize, lastStatusByte, time);
  20910. if (messSize <= 0)
  20911. break;
  20912. size -= messSize;
  20913. data += messSize;
  20914. result.addEvent (mm);
  20915. const char firstByte = *(mm.getRawData());
  20916. if ((firstByte & 0xf0) != 0xf0)
  20917. lastStatusByte = firstByte;
  20918. }
  20919. // use a sort that puts all the note-offs before note-ons that have the same time
  20920. result.list.sort (*this, true);
  20921. result.updateMatchedPairs();
  20922. addTrack (result);
  20923. }
  20924. static double convertTicksToSeconds (const double time,
  20925. const MidiMessageSequence& tempoEvents,
  20926. const int timeFormat)
  20927. {
  20928. if (timeFormat > 0)
  20929. {
  20930. int numer = 4, denom = 4;
  20931. double tempoTime = 0.0, correctedTempoTime = 0.0;
  20932. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  20933. double secsPerTick = 0.5 * tickLen;
  20934. const int numEvents = tempoEvents.getNumEvents();
  20935. for (int i = 0; i < numEvents; ++i)
  20936. {
  20937. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  20938. if (time <= m.getTimeStamp())
  20939. break;
  20940. if (timeFormat > 0)
  20941. {
  20942. correctedTempoTime = correctedTempoTime
  20943. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  20944. }
  20945. else
  20946. {
  20947. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  20948. }
  20949. tempoTime = m.getTimeStamp();
  20950. if (m.isTempoMetaEvent())
  20951. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  20952. else if (m.isTimeSignatureMetaEvent())
  20953. m.getTimeSignatureInfo (numer, denom);
  20954. while (i + 1 < numEvents)
  20955. {
  20956. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  20957. if (m2.getTimeStamp() == tempoTime)
  20958. {
  20959. ++i;
  20960. if (m2.isTempoMetaEvent())
  20961. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  20962. else if (m2.isTimeSignatureMetaEvent())
  20963. m2.getTimeSignatureInfo (numer, denom);
  20964. }
  20965. else
  20966. {
  20967. break;
  20968. }
  20969. }
  20970. }
  20971. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  20972. }
  20973. else
  20974. {
  20975. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  20976. }
  20977. }
  20978. void MidiFile::convertTimestampTicksToSeconds()
  20979. {
  20980. MidiMessageSequence tempoEvents;
  20981. findAllTempoEvents (tempoEvents);
  20982. findAllTimeSigEvents (tempoEvents);
  20983. for (int i = 0; i < numTracks; ++i)
  20984. {
  20985. MidiMessageSequence& ms = *tracks[i];
  20986. for (int j = ms.getNumEvents(); --j >= 0;)
  20987. {
  20988. MidiMessage& m = ms.getEventPointer(j)->message;
  20989. m.setTimeStamp (convertTicksToSeconds (m.getTimeStamp(),
  20990. tempoEvents,
  20991. timeFormat));
  20992. }
  20993. }
  20994. }
  20995. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  20996. {
  20997. unsigned int buffer = v & 0x7F;
  20998. while ((v >>= 7) != 0)
  20999. {
  21000. buffer <<= 8;
  21001. buffer |= ((v & 0x7F) | 0x80);
  21002. }
  21003. for (;;)
  21004. {
  21005. out.writeByte ((char) buffer);
  21006. if (buffer & 0x80)
  21007. buffer >>= 8;
  21008. else
  21009. break;
  21010. }
  21011. }
  21012. bool MidiFile::writeTo (OutputStream& out)
  21013. {
  21014. out.writeIntBigEndian ((int) bigEndianInt ("MThd"));
  21015. out.writeIntBigEndian (6);
  21016. out.writeShortBigEndian (1); // type
  21017. out.writeShortBigEndian (numTracks);
  21018. out.writeShortBigEndian (timeFormat);
  21019. for (int i = 0; i < numTracks; ++i)
  21020. writeTrack (out, i);
  21021. out.flush();
  21022. return true;
  21023. }
  21024. void MidiFile::writeTrack (OutputStream& mainOut,
  21025. const int trackNum)
  21026. {
  21027. MemoryOutputStream out;
  21028. const MidiMessageSequence& ms = *tracks[trackNum];
  21029. int lastTick = 0;
  21030. char lastStatusByte = 0;
  21031. for (int i = 0; i < ms.getNumEvents(); ++i)
  21032. {
  21033. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21034. const int tick = roundDoubleToInt (mm.getTimeStamp());
  21035. const int delta = jmax (0, tick - lastTick);
  21036. writeVariableLengthInt (out, delta);
  21037. lastTick = tick;
  21038. const char statusByte = *(mm.getRawData());
  21039. if ((statusByte == lastStatusByte)
  21040. && ((statusByte & 0xf0) != 0xf0)
  21041. && i > 0
  21042. && mm.getRawDataSize() > 1)
  21043. {
  21044. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21045. }
  21046. else
  21047. {
  21048. out.write (mm.getRawData(), mm.getRawDataSize());
  21049. }
  21050. lastStatusByte = statusByte;
  21051. }
  21052. out.writeByte (0);
  21053. const MidiMessage m (MidiMessage::endOfTrack());
  21054. out.write (m.getRawData(),
  21055. m.getRawDataSize());
  21056. mainOut.writeIntBigEndian ((int)bigEndianInt ("MTrk"));
  21057. mainOut.writeIntBigEndian (out.getDataSize());
  21058. mainOut.write (out.getData(), out.getDataSize());
  21059. }
  21060. END_JUCE_NAMESPACE
  21061. /********* End of inlined file: juce_MidiFile.cpp *********/
  21062. /********* Start of inlined file: juce_MidiKeyboardState.cpp *********/
  21063. BEGIN_JUCE_NAMESPACE
  21064. MidiKeyboardState::MidiKeyboardState()
  21065. : listeners (2)
  21066. {
  21067. zeromem (noteStates, sizeof (noteStates));
  21068. }
  21069. MidiKeyboardState::~MidiKeyboardState()
  21070. {
  21071. }
  21072. void MidiKeyboardState::reset()
  21073. {
  21074. const ScopedLock sl (lock);
  21075. zeromem (noteStates, sizeof (noteStates));
  21076. eventsToAdd.clear();
  21077. }
  21078. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21079. {
  21080. jassert (midiChannel >= 0 && midiChannel <= 16);
  21081. return ((unsigned int) n) < 128
  21082. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21083. }
  21084. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21085. {
  21086. return ((unsigned int) n) < 128
  21087. && (noteStates[n] & midiChannelMask) != 0;
  21088. }
  21089. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21090. {
  21091. jassert (midiChannel >= 0 && midiChannel <= 16);
  21092. jassert (((unsigned int) midiNoteNumber) < 128);
  21093. const ScopedLock sl (lock);
  21094. if (((unsigned int) midiNoteNumber) < 128)
  21095. {
  21096. const int timeNow = (int) Time::getMillisecondCounter();
  21097. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21098. eventsToAdd.clear (0, timeNow - 500);
  21099. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21100. }
  21101. }
  21102. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21103. {
  21104. if (((unsigned int) midiNoteNumber) < 128)
  21105. {
  21106. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21107. for (int i = listeners.size(); --i >= 0;)
  21108. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  21109. ->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21110. }
  21111. }
  21112. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21113. {
  21114. const ScopedLock sl (lock);
  21115. if (isNoteOn (midiChannel, midiNoteNumber))
  21116. {
  21117. const int timeNow = (int) Time::getMillisecondCounter();
  21118. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21119. eventsToAdd.clear (0, timeNow - 500);
  21120. noteOffInternal (midiChannel, midiNoteNumber);
  21121. }
  21122. }
  21123. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  21124. {
  21125. if (isNoteOn (midiChannel, midiNoteNumber))
  21126. {
  21127. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  21128. for (int i = listeners.size(); --i >= 0;)
  21129. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  21130. ->handleNoteOff (this, midiChannel, midiNoteNumber);
  21131. }
  21132. }
  21133. void MidiKeyboardState::allNotesOff (const int midiChannel)
  21134. {
  21135. const ScopedLock sl (lock);
  21136. if (midiChannel <= 0)
  21137. {
  21138. for (int i = 1; i <= 16; ++i)
  21139. allNotesOff (i);
  21140. }
  21141. else
  21142. {
  21143. for (int i = 0; i < 128; ++i)
  21144. noteOff (midiChannel, i);
  21145. }
  21146. }
  21147. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  21148. {
  21149. if (message.isNoteOn())
  21150. {
  21151. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  21152. }
  21153. else if (message.isNoteOff())
  21154. {
  21155. noteOffInternal (message.getChannel(), message.getNoteNumber());
  21156. }
  21157. else if (message.isAllNotesOff())
  21158. {
  21159. for (int i = 0; i < 128; ++i)
  21160. noteOffInternal (message.getChannel(), i);
  21161. }
  21162. }
  21163. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  21164. const int startSample,
  21165. const int numSamples,
  21166. const bool injectIndirectEvents)
  21167. {
  21168. MidiBuffer::Iterator i (buffer);
  21169. MidiMessage message (0xf4, 0.0);
  21170. int time;
  21171. const ScopedLock sl (lock);
  21172. while (i.getNextEvent (message, time))
  21173. processNextMidiEvent (message);
  21174. if (injectIndirectEvents)
  21175. {
  21176. MidiBuffer::Iterator i2 (eventsToAdd);
  21177. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  21178. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  21179. while (i2.getNextEvent (message, time))
  21180. {
  21181. const int pos = jlimit (0, numSamples - 1, roundDoubleToInt ((time - firstEventToAdd) * scaleFactor));
  21182. buffer.addEvent (message, startSample + pos);
  21183. }
  21184. }
  21185. eventsToAdd.clear();
  21186. }
  21187. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  21188. {
  21189. const ScopedLock sl (lock);
  21190. listeners.addIfNotAlreadyThere (listener);
  21191. }
  21192. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  21193. {
  21194. const ScopedLock sl (lock);
  21195. listeners.removeValue (listener);
  21196. }
  21197. END_JUCE_NAMESPACE
  21198. /********* End of inlined file: juce_MidiKeyboardState.cpp *********/
  21199. /********* Start of inlined file: juce_MidiMessage.cpp *********/
  21200. BEGIN_JUCE_NAMESPACE
  21201. int MidiMessage::readVariableLengthVal (const uint8* data,
  21202. int& numBytesUsed) throw()
  21203. {
  21204. numBytesUsed = 0;
  21205. int v = 0;
  21206. int i;
  21207. do
  21208. {
  21209. i = (int) *data++;
  21210. if (++numBytesUsed > 6)
  21211. break;
  21212. v = (v << 7) + (i & 0x7f);
  21213. } while (i & 0x80);
  21214. return v;
  21215. }
  21216. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  21217. {
  21218. // this method only works for valid starting bytes of a short midi message
  21219. jassert (firstByte >= 0x80
  21220. && firstByte != 0xf0
  21221. && firstByte != 0xf7);
  21222. static const char messageLengths[] =
  21223. {
  21224. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21225. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21226. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21227. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21228. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  21229. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  21230. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21231. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  21232. };
  21233. return messageLengths [firstByte & 0x7f];
  21234. }
  21235. MidiMessage::MidiMessage (const uint8* const d,
  21236. const int dataSize,
  21237. const double t) throw()
  21238. : timeStamp (t),
  21239. message (0),
  21240. size (dataSize)
  21241. {
  21242. jassert (dataSize > 0);
  21243. if (dataSize <= 4)
  21244. data = (uint8*) &message;
  21245. else
  21246. data = (uint8*) juce_malloc (dataSize);
  21247. memcpy (data, d, dataSize);
  21248. // check that the length matches the data..
  21249. jassert (size > 3 || *d >= 0xf0 || getMessageLengthFromFirstByte (*d) == size);
  21250. }
  21251. MidiMessage::MidiMessage (const int byte1,
  21252. const double t) throw()
  21253. : timeStamp (t),
  21254. data ((uint8*) &message),
  21255. size (1)
  21256. {
  21257. data[0] = (uint8) byte1;
  21258. // check that the length matches the data..
  21259. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  21260. }
  21261. MidiMessage::MidiMessage (const int byte1,
  21262. const int byte2,
  21263. const double t) throw()
  21264. : timeStamp (t),
  21265. data ((uint8*) &message),
  21266. size (2)
  21267. {
  21268. data[0] = (uint8) byte1;
  21269. data[1] = (uint8) byte2;
  21270. // check that the length matches the data..
  21271. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  21272. }
  21273. MidiMessage::MidiMessage (const int byte1,
  21274. const int byte2,
  21275. const int byte3,
  21276. const double t) throw()
  21277. : timeStamp (t),
  21278. data ((uint8*) &message),
  21279. size (3)
  21280. {
  21281. data[0] = (uint8) byte1;
  21282. data[1] = (uint8) byte2;
  21283. data[2] = (uint8) byte3;
  21284. // check that the length matches the data..
  21285. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  21286. }
  21287. MidiMessage::MidiMessage (const MidiMessage& other) throw()
  21288. : timeStamp (other.timeStamp),
  21289. message (other.message),
  21290. size (other.size)
  21291. {
  21292. if (other.data != (uint8*) &other.message)
  21293. {
  21294. data = (uint8*) juce_malloc (size);
  21295. memcpy (data, other.data, size);
  21296. }
  21297. else
  21298. {
  21299. data = (uint8*) &message;
  21300. }
  21301. }
  21302. MidiMessage::MidiMessage (const MidiMessage& other,
  21303. const double newTimeStamp) throw()
  21304. : timeStamp (newTimeStamp),
  21305. message (other.message),
  21306. size (other.size)
  21307. {
  21308. if (other.data != (uint8*) &other.message)
  21309. {
  21310. data = (uint8*) juce_malloc (size);
  21311. memcpy (data, other.data, size);
  21312. }
  21313. else
  21314. {
  21315. data = (uint8*) &message;
  21316. }
  21317. }
  21318. MidiMessage::MidiMessage (const uint8* src,
  21319. int sz,
  21320. int& numBytesUsed,
  21321. const uint8 lastStatusByte,
  21322. double t) throw()
  21323. : timeStamp (t),
  21324. data ((uint8*) &message),
  21325. message (0)
  21326. {
  21327. unsigned int byte = (unsigned int) *src;
  21328. if (byte < 0x80)
  21329. {
  21330. byte = (unsigned int) (uint8) lastStatusByte;
  21331. numBytesUsed = -1;
  21332. }
  21333. else
  21334. {
  21335. numBytesUsed = 0;
  21336. --sz;
  21337. ++src;
  21338. }
  21339. if (byte >= 0x80)
  21340. {
  21341. if (byte == 0xf0)
  21342. {
  21343. const uint8* d = (const uint8*) src;
  21344. while (d < src + sz)
  21345. {
  21346. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  21347. {
  21348. if (*d == 0xf7) // include an 0xf7 if we hit one
  21349. ++d;
  21350. break;
  21351. }
  21352. ++d;
  21353. }
  21354. size = 1 + (int) (d - src);
  21355. data = (uint8*) juce_malloc (size);
  21356. *data = (uint8) byte;
  21357. memcpy (data + 1, src, size - 1);
  21358. }
  21359. else if (byte == 0xff)
  21360. {
  21361. int n;
  21362. const int bytesLeft = readVariableLengthVal (src + 1, n);
  21363. size = jmin (sz + 1, n + 2 + bytesLeft);
  21364. data = (uint8*) juce_malloc (size);
  21365. *data = (uint8) byte;
  21366. memcpy (data + 1, src, size - 1);
  21367. }
  21368. else
  21369. {
  21370. size = getMessageLengthFromFirstByte ((uint8) byte);
  21371. *data = (uint8) byte;
  21372. if (size > 1)
  21373. {
  21374. data[1] = src[0];
  21375. if (size > 2)
  21376. data[2] = src[1];
  21377. }
  21378. }
  21379. numBytesUsed += size;
  21380. }
  21381. else
  21382. {
  21383. message = 0;
  21384. size = 0;
  21385. }
  21386. }
  21387. const MidiMessage& MidiMessage::operator= (const MidiMessage& other) throw()
  21388. {
  21389. if (this == &other)
  21390. return *this;
  21391. timeStamp = other.timeStamp;
  21392. size = other.size;
  21393. message = other.message;
  21394. if (data != (uint8*) &message)
  21395. juce_free (data);
  21396. if (other.data != (uint8*) &other.message)
  21397. {
  21398. data = (uint8*) juce_malloc (size);
  21399. memcpy (data, other.data, size);
  21400. }
  21401. else
  21402. {
  21403. data = (uint8*) &message;
  21404. }
  21405. return *this;
  21406. }
  21407. MidiMessage::~MidiMessage() throw()
  21408. {
  21409. if (data != (uint8*) &message)
  21410. juce_free (data);
  21411. }
  21412. int MidiMessage::getChannel() const throw()
  21413. {
  21414. if ((data[0] & 0xf0) != 0xf0)
  21415. return (data[0] & 0xf) + 1;
  21416. else
  21417. return 0;
  21418. }
  21419. bool MidiMessage::isForChannel (const int channel) const throw()
  21420. {
  21421. return ((data[0] & 0xf) == channel - 1)
  21422. && ((data[0] & 0xf0) != 0xf0);
  21423. }
  21424. void MidiMessage::setChannel (const int channel) throw()
  21425. {
  21426. if ((data[0] & 0xf0) != (uint8) 0xf0)
  21427. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  21428. | (uint8)(channel - 1));
  21429. }
  21430. bool MidiMessage::isNoteOn() const throw()
  21431. {
  21432. return ((data[0] & 0xf0) == 0x90)
  21433. && (data[2] != 0);
  21434. }
  21435. bool MidiMessage::isNoteOff() const throw()
  21436. {
  21437. return ((data[0] & 0xf0) == 0x80)
  21438. || ((data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  21439. }
  21440. bool MidiMessage::isNoteOnOrOff() const throw()
  21441. {
  21442. const int d = data[0] & 0xf0;
  21443. return (d == 0x90) || (d == 0x80);
  21444. }
  21445. int MidiMessage::getNoteNumber() const throw()
  21446. {
  21447. return data[1];
  21448. }
  21449. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  21450. {
  21451. if (isNoteOnOrOff())
  21452. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  21453. }
  21454. uint8 MidiMessage::getVelocity() const throw()
  21455. {
  21456. if (isNoteOnOrOff())
  21457. return data[2];
  21458. else
  21459. return 0;
  21460. }
  21461. float MidiMessage::getFloatVelocity() const throw()
  21462. {
  21463. return getVelocity() * (1.0f / 127.0f);
  21464. }
  21465. void MidiMessage::setVelocity (const float newVelocity) throw()
  21466. {
  21467. if (isNoteOnOrOff())
  21468. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (newVelocity * 127.0f));
  21469. }
  21470. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  21471. {
  21472. if (isNoteOnOrOff())
  21473. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (scaleFactor * data[2]));
  21474. }
  21475. bool MidiMessage::isAftertouch() const throw()
  21476. {
  21477. return (data[0] & 0xf0) == 0xa0;
  21478. }
  21479. int MidiMessage::getAfterTouchValue() const throw()
  21480. {
  21481. return data[2];
  21482. }
  21483. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  21484. const int noteNum,
  21485. const int aftertouchValue) throw()
  21486. {
  21487. jassert (channel > 0 && channel <= 16);
  21488. jassert (((unsigned int) noteNum) <= 127);
  21489. jassert (((unsigned int) aftertouchValue) <= 127);
  21490. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  21491. noteNum & 0x7f,
  21492. aftertouchValue & 0x7f);
  21493. }
  21494. bool MidiMessage::isChannelPressure() const throw()
  21495. {
  21496. return (data[0] & 0xf0) == 0xd0;
  21497. }
  21498. int MidiMessage::getChannelPressureValue() const throw()
  21499. {
  21500. jassert (isChannelPressure());
  21501. return data[1];
  21502. }
  21503. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  21504. const int pressure) throw()
  21505. {
  21506. jassert (channel > 0 && channel <= 16);
  21507. jassert (((unsigned int) pressure) <= 127);
  21508. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  21509. pressure & 0x7f);
  21510. }
  21511. bool MidiMessage::isProgramChange() const throw()
  21512. {
  21513. return (data[0] & 0xf0) == 0xc0;
  21514. }
  21515. int MidiMessage::getProgramChangeNumber() const throw()
  21516. {
  21517. return data[1];
  21518. }
  21519. const MidiMessage MidiMessage::programChange (const int channel,
  21520. const int programNumber) throw()
  21521. {
  21522. jassert (channel > 0 && channel <= 16);
  21523. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  21524. programNumber & 0x7f);
  21525. }
  21526. bool MidiMessage::isPitchWheel() const throw()
  21527. {
  21528. return (data[0] & 0xf0) == 0xe0;
  21529. }
  21530. int MidiMessage::getPitchWheelValue() const throw()
  21531. {
  21532. return data[1] | (data[2] << 7);
  21533. }
  21534. const MidiMessage MidiMessage::pitchWheel (const int channel,
  21535. const int position) throw()
  21536. {
  21537. jassert (channel > 0 && channel <= 16);
  21538. jassert (((unsigned int) position) <= 0x3fff);
  21539. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  21540. position & 127,
  21541. (position >> 7) & 127);
  21542. }
  21543. bool MidiMessage::isController() const throw()
  21544. {
  21545. return (data[0] & 0xf0) == 0xb0;
  21546. }
  21547. int MidiMessage::getControllerNumber() const throw()
  21548. {
  21549. jassert (isController());
  21550. return data[1];
  21551. }
  21552. int MidiMessage::getControllerValue() const throw()
  21553. {
  21554. jassert (isController());
  21555. return data[2];
  21556. }
  21557. const MidiMessage MidiMessage::controllerEvent (const int channel,
  21558. const int controllerType,
  21559. const int value) throw()
  21560. {
  21561. // the channel must be between 1 and 16 inclusive
  21562. jassert (channel > 0 && channel <= 16);
  21563. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  21564. controllerType & 127,
  21565. value & 127);
  21566. }
  21567. const MidiMessage MidiMessage::noteOn (const int channel,
  21568. const int noteNumber,
  21569. const float velocity) throw()
  21570. {
  21571. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  21572. }
  21573. const MidiMessage MidiMessage::noteOn (const int channel,
  21574. const int noteNumber,
  21575. const uint8 velocity) throw()
  21576. {
  21577. jassert (channel > 0 && channel <= 16);
  21578. jassert (((unsigned int) noteNumber) <= 127);
  21579. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  21580. noteNumber & 127,
  21581. jlimit (0, 127, roundFloatToInt (velocity)));
  21582. }
  21583. const MidiMessage MidiMessage::noteOff (const int channel,
  21584. const int noteNumber) throw()
  21585. {
  21586. jassert (channel > 0 && channel <= 16);
  21587. jassert (((unsigned int) noteNumber) <= 127);
  21588. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  21589. }
  21590. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  21591. {
  21592. jassert (channel > 0 && channel <= 16);
  21593. return controllerEvent (channel, 123, 0);
  21594. }
  21595. bool MidiMessage::isAllNotesOff() const throw()
  21596. {
  21597. return (data[0] & 0xf0) == 0xb0
  21598. && data[1] == 123;
  21599. }
  21600. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  21601. {
  21602. return controllerEvent (channel, 120, 0);
  21603. }
  21604. bool MidiMessage::isAllSoundOff() const throw()
  21605. {
  21606. return (data[0] & 0xf0) == 0xb0
  21607. && data[1] == 120;
  21608. }
  21609. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  21610. {
  21611. return controllerEvent (channel, 121, 0);
  21612. }
  21613. const MidiMessage MidiMessage::masterVolume (const float volume) throw()
  21614. {
  21615. const int vol = jlimit (0, 0x3fff, roundFloatToInt (volume * 0x4000));
  21616. uint8 buf[8];
  21617. buf[0] = 0xf0;
  21618. buf[1] = 0x7f;
  21619. buf[2] = 0x7f;
  21620. buf[3] = 0x04;
  21621. buf[4] = 0x01;
  21622. buf[5] = (uint8) (vol & 0x7f);
  21623. buf[6] = (uint8) (vol >> 7);
  21624. buf[7] = 0xf7;
  21625. return MidiMessage (buf, 8);
  21626. }
  21627. bool MidiMessage::isSysEx() const throw()
  21628. {
  21629. return *data == 0xf0;
  21630. }
  21631. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData,
  21632. const int dataSize) throw()
  21633. {
  21634. MemoryBlock mm (dataSize + 2);
  21635. uint8* const m = (uint8*) mm.getData();
  21636. m[0] = 0xf0;
  21637. memcpy (m + 1, sysexData, dataSize);
  21638. m[dataSize + 1] = 0xf7;
  21639. return MidiMessage (m, dataSize + 2);
  21640. }
  21641. const uint8* MidiMessage::getSysExData() const throw()
  21642. {
  21643. return (isSysEx()) ? getRawData() + 1
  21644. : 0;
  21645. }
  21646. int MidiMessage::getSysExDataSize() const throw()
  21647. {
  21648. return (isSysEx()) ? size - 2
  21649. : 0;
  21650. }
  21651. bool MidiMessage::isMetaEvent() const throw()
  21652. {
  21653. return *data == 0xff;
  21654. }
  21655. bool MidiMessage::isActiveSense() const throw()
  21656. {
  21657. return *data == 0xfe;
  21658. }
  21659. int MidiMessage::getMetaEventType() const throw()
  21660. {
  21661. if (*data != 0xff)
  21662. return -1;
  21663. else
  21664. return data[1];
  21665. }
  21666. int MidiMessage::getMetaEventLength() const throw()
  21667. {
  21668. if (*data == 0xff)
  21669. {
  21670. int n;
  21671. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  21672. }
  21673. return 0;
  21674. }
  21675. const uint8* MidiMessage::getMetaEventData() const throw()
  21676. {
  21677. int n;
  21678. const uint8* d = data + 2;
  21679. readVariableLengthVal (d, n);
  21680. return d + n;
  21681. }
  21682. bool MidiMessage::isTrackMetaEvent() const throw()
  21683. {
  21684. return getMetaEventType() == 0;
  21685. }
  21686. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  21687. {
  21688. return getMetaEventType() == 47;
  21689. }
  21690. bool MidiMessage::isTextMetaEvent() const throw()
  21691. {
  21692. const int t = getMetaEventType();
  21693. return t > 0 && t < 16;
  21694. }
  21695. const String MidiMessage::getTextFromTextMetaEvent() const throw()
  21696. {
  21697. return String ((const char*) getMetaEventData(),
  21698. getMetaEventLength());
  21699. }
  21700. bool MidiMessage::isTrackNameEvent() const throw()
  21701. {
  21702. return (data[1] == 3)
  21703. && (*data == 0xff);
  21704. }
  21705. bool MidiMessage::isTempoMetaEvent() const throw()
  21706. {
  21707. return (data[1] == 81)
  21708. && (*data == 0xff);
  21709. }
  21710. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  21711. {
  21712. return (data[1] == 0x20)
  21713. && (*data == 0xff)
  21714. && (data[2] == 1);
  21715. }
  21716. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  21717. {
  21718. return data[3] + 1;
  21719. }
  21720. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  21721. {
  21722. if (! isTempoMetaEvent())
  21723. return 0.0;
  21724. const uint8* const d = getMetaEventData();
  21725. return (((unsigned int) d[0] << 16)
  21726. | ((unsigned int) d[1] << 8)
  21727. | d[2])
  21728. / 1000000.0;
  21729. }
  21730. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  21731. {
  21732. if (timeFormat > 0)
  21733. {
  21734. if (! isTempoMetaEvent())
  21735. return 0.5 / timeFormat;
  21736. return getTempoSecondsPerQuarterNote() / timeFormat;
  21737. }
  21738. else
  21739. {
  21740. const int frameCode = (-timeFormat) >> 8;
  21741. double framesPerSecond;
  21742. switch (frameCode)
  21743. {
  21744. case 24: framesPerSecond = 24.0; break;
  21745. case 25: framesPerSecond = 25.0; break;
  21746. case 29: framesPerSecond = 29.97; break;
  21747. case 30: framesPerSecond = 30.0; break;
  21748. default: framesPerSecond = 30.0; break;
  21749. }
  21750. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  21751. }
  21752. }
  21753. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  21754. {
  21755. uint8 d[8];
  21756. d[0] = 0xff;
  21757. d[1] = 81;
  21758. d[2] = 3;
  21759. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  21760. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  21761. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  21762. return MidiMessage (d, 6, 0.0);
  21763. }
  21764. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  21765. {
  21766. return (data[1] == 0x58)
  21767. && (*data == (uint8) 0xff);
  21768. }
  21769. void MidiMessage::getTimeSignatureInfo (int& numerator,
  21770. int& denominator) const throw()
  21771. {
  21772. if (isTimeSignatureMetaEvent())
  21773. {
  21774. const uint8* const d = getMetaEventData();
  21775. numerator = d[0];
  21776. denominator = 1 << d[1];
  21777. }
  21778. else
  21779. {
  21780. numerator = 4;
  21781. denominator = 4;
  21782. }
  21783. }
  21784. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator,
  21785. const int denominator) throw()
  21786. {
  21787. uint8 d[8];
  21788. d[0] = 0xff;
  21789. d[1] = 0x58;
  21790. d[2] = 0x04;
  21791. d[3] = (uint8) numerator;
  21792. int n = 1;
  21793. int powerOfTwo = 0;
  21794. while (n < denominator)
  21795. {
  21796. n <<= 1;
  21797. ++powerOfTwo;
  21798. }
  21799. d[4] = (uint8) powerOfTwo;
  21800. d[5] = 0x01;
  21801. d[6] = 96;
  21802. return MidiMessage (d, 7, 0.0);
  21803. }
  21804. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  21805. {
  21806. uint8 d[8];
  21807. d[0] = 0xff;
  21808. d[1] = 0x20;
  21809. d[2] = 0x01;
  21810. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  21811. return MidiMessage (d, 4, 0.0);
  21812. }
  21813. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  21814. {
  21815. return getMetaEventType() == 89;
  21816. }
  21817. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  21818. {
  21819. return (int) *getMetaEventData();
  21820. }
  21821. const MidiMessage MidiMessage::endOfTrack() throw()
  21822. {
  21823. return MidiMessage (0xff, 0x2f, 0, 0.0);
  21824. }
  21825. bool MidiMessage::isSongPositionPointer() const throw()
  21826. {
  21827. return *data == 0xf2;
  21828. }
  21829. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  21830. {
  21831. return data[1] | (data[2] << 7);
  21832. }
  21833. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  21834. {
  21835. return MidiMessage (0xf2,
  21836. positionInMidiBeats & 127,
  21837. (positionInMidiBeats >> 7) & 127);
  21838. }
  21839. bool MidiMessage::isMidiStart() const throw()
  21840. {
  21841. return *data == 0xfa;
  21842. }
  21843. const MidiMessage MidiMessage::midiStart() throw()
  21844. {
  21845. return MidiMessage (0xfa);
  21846. }
  21847. bool MidiMessage::isMidiContinue() const throw()
  21848. {
  21849. return *data == 0xfb;
  21850. }
  21851. const MidiMessage MidiMessage::midiContinue() throw()
  21852. {
  21853. return MidiMessage (0xfb);
  21854. }
  21855. bool MidiMessage::isMidiStop() const throw()
  21856. {
  21857. return *data == 0xfc;
  21858. }
  21859. const MidiMessage MidiMessage::midiStop() throw()
  21860. {
  21861. return MidiMessage (0xfc);
  21862. }
  21863. bool MidiMessage::isMidiClock() const throw()
  21864. {
  21865. return *data == 0xf8;
  21866. }
  21867. const MidiMessage MidiMessage::midiClock() throw()
  21868. {
  21869. return MidiMessage (0xf8);
  21870. }
  21871. bool MidiMessage::isQuarterFrame() const throw()
  21872. {
  21873. return *data == 0xf1;
  21874. }
  21875. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  21876. {
  21877. return ((int) data[1]) >> 4;
  21878. }
  21879. int MidiMessage::getQuarterFrameValue() const throw()
  21880. {
  21881. return ((int) data[1]) & 0x0f;
  21882. }
  21883. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  21884. const int value) throw()
  21885. {
  21886. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  21887. }
  21888. bool MidiMessage::isFullFrame() const throw()
  21889. {
  21890. return data[0] == 0xf0
  21891. && data[1] == 0x7f
  21892. && size >= 10
  21893. && data[3] == 0x01
  21894. && data[4] == 0x01;
  21895. }
  21896. void MidiMessage::getFullFrameParameters (int& hours,
  21897. int& minutes,
  21898. int& seconds,
  21899. int& frames,
  21900. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  21901. {
  21902. jassert (isFullFrame());
  21903. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  21904. hours = data[5] & 0x1f;
  21905. minutes = data[6];
  21906. seconds = data[7];
  21907. frames = data[8];
  21908. }
  21909. const MidiMessage MidiMessage::fullFrame (const int hours,
  21910. const int minutes,
  21911. const int seconds,
  21912. const int frames,
  21913. MidiMessage::SmpteTimecodeType timecodeType)
  21914. {
  21915. uint8 d[10];
  21916. d[0] = 0xf0;
  21917. d[1] = 0x7f;
  21918. d[2] = 0x7f;
  21919. d[3] = 0x01;
  21920. d[4] = 0x01;
  21921. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  21922. d[6] = (uint8) minutes;
  21923. d[7] = (uint8) seconds;
  21924. d[8] = (uint8) frames;
  21925. d[9] = 0xf7;
  21926. return MidiMessage (d, 10, 0.0);
  21927. }
  21928. bool MidiMessage::isMidiMachineControlMessage() const throw()
  21929. {
  21930. return data[0] == 0xf0
  21931. && data[1] == 0x7f
  21932. && data[3] == 0x06
  21933. && size > 5;
  21934. }
  21935. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  21936. {
  21937. jassert (isMidiMachineControlMessage());
  21938. return (MidiMachineControlCommand) data[4];
  21939. }
  21940. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  21941. {
  21942. uint8 d[6];
  21943. d[0] = 0xf0;
  21944. d[1] = 0x7f;
  21945. d[2] = 0x00;
  21946. d[3] = 0x06;
  21947. d[4] = (uint8) command;
  21948. d[5] = 0xf7;
  21949. return MidiMessage (d, 6, 0.0);
  21950. }
  21951. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  21952. int& minutes,
  21953. int& seconds,
  21954. int& frames) const throw()
  21955. {
  21956. if (size >= 12
  21957. && data[0] == 0xf0
  21958. && data[1] == 0x7f
  21959. && data[3] == 0x06
  21960. && data[4] == 0x44
  21961. && data[5] == 0x06
  21962. && data[6] == 0x01)
  21963. {
  21964. hours = data[7] % 24; // (that some machines send out hours > 24)
  21965. minutes = data[8];
  21966. seconds = data[9];
  21967. frames = data[10];
  21968. return true;
  21969. }
  21970. return false;
  21971. }
  21972. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  21973. int minutes,
  21974. int seconds,
  21975. int frames)
  21976. {
  21977. uint8 d[12];
  21978. d[0] = 0xf0;
  21979. d[1] = 0x7f;
  21980. d[2] = 0x00;
  21981. d[3] = 0x06;
  21982. d[4] = 0x44;
  21983. d[5] = 0x06;
  21984. d[6] = 0x01;
  21985. d[7] = (uint8) hours;
  21986. d[8] = (uint8) minutes;
  21987. d[9] = (uint8) seconds;
  21988. d[10] = (uint8) frames;
  21989. d[11] = 0xf7;
  21990. return MidiMessage (d, 12, 0.0);
  21991. }
  21992. const String MidiMessage::getMidiNoteName (int note,
  21993. bool useSharps,
  21994. bool includeOctaveNumber,
  21995. int octaveNumForMiddleC) throw()
  21996. {
  21997. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  21998. "F", "F#", "G", "G#", "A",
  21999. "A#", "B" };
  22000. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22001. "F", "Gb", "G", "Ab", "A",
  22002. "Bb", "B" };
  22003. if (((unsigned int) note) < 128)
  22004. {
  22005. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22006. : flatNoteNames [note % 12]);
  22007. if (includeOctaveNumber)
  22008. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22009. else
  22010. return s;
  22011. }
  22012. return String::empty;
  22013. }
  22014. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22015. {
  22016. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22017. return 440.0 * pow (2.0, noteNumber / 12.0);
  22018. }
  22019. const String MidiMessage::getGMInstrumentName (int n) throw()
  22020. {
  22021. const char *names[] =
  22022. {
  22023. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22024. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22025. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22026. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22027. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22028. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22029. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22030. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22031. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22032. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22033. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22034. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22035. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22036. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22037. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22038. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22039. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22040. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22041. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22042. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22043. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22044. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22045. "Applause", "Gunshot"
  22046. };
  22047. return (((unsigned int) n) < 128) ? names[n]
  22048. : (const char*)0;
  22049. }
  22050. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22051. {
  22052. const char* names[] =
  22053. {
  22054. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22055. "Bass", "Strings", "Ensemble", "Brass",
  22056. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22057. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22058. };
  22059. return (((unsigned int) n) <= 15) ? names[n]
  22060. : (const char*)0;
  22061. }
  22062. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22063. {
  22064. const char* names[] =
  22065. {
  22066. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22067. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22068. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22069. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22070. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22071. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22072. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22073. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22074. "Mute Triangle", "Open Triangle"
  22075. };
  22076. return (n >= 35 && n <= 81) ? names [n - 35]
  22077. : (const char*)0;
  22078. }
  22079. const String MidiMessage::getControllerName (int n) throw()
  22080. {
  22081. const char* names[] =
  22082. {
  22083. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22084. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22085. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22086. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22087. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22088. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22089. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22090. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22091. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22092. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22093. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22094. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22095. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22096. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22097. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22098. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22099. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22100. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22101. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22103. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22104. "Poly Operation"
  22105. };
  22106. return (((unsigned int) n) < 128) ? names[n]
  22107. : (const char*)0;
  22108. }
  22109. END_JUCE_NAMESPACE
  22110. /********* End of inlined file: juce_MidiMessage.cpp *********/
  22111. /********* Start of inlined file: juce_MidiMessageCollector.cpp *********/
  22112. BEGIN_JUCE_NAMESPACE
  22113. MidiMessageCollector::MidiMessageCollector()
  22114. : lastCallbackTime (0),
  22115. sampleRate (44100.0001)
  22116. {
  22117. }
  22118. MidiMessageCollector::~MidiMessageCollector()
  22119. {
  22120. }
  22121. void MidiMessageCollector::reset (const double sampleRate_)
  22122. {
  22123. jassert (sampleRate_ > 0);
  22124. const ScopedLock sl (midiCallbackLock);
  22125. sampleRate = sampleRate_;
  22126. incomingMessages.clear();
  22127. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22128. }
  22129. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22130. {
  22131. // you need to call reset() to set the correct sample rate before using this object
  22132. jassert (sampleRate != 44100.0001);
  22133. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22134. // for details of what the number should be.
  22135. jassert (message.getTimeStamp() != 0);
  22136. const ScopedLock sl (midiCallbackLock);
  22137. const int sampleNumber
  22138. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22139. incomingMessages.addEvent (message, sampleNumber);
  22140. // if the messages don't get used for over a second, we'd better
  22141. // get rid of any old ones to avoid the queue getting too big
  22142. if (sampleNumber > sampleRate)
  22143. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  22144. }
  22145. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  22146. const int numSamples)
  22147. {
  22148. // you need to call reset() to set the correct sample rate before using this object
  22149. jassert (sampleRate != 44100.0001);
  22150. const double timeNow = Time::getMillisecondCounterHiRes();
  22151. const double msElapsed = timeNow - lastCallbackTime;
  22152. const ScopedLock sl (midiCallbackLock);
  22153. lastCallbackTime = timeNow;
  22154. if (! incomingMessages.isEmpty())
  22155. {
  22156. int numSourceSamples = jmax (1, roundDoubleToInt (msElapsed * 0.001 * sampleRate));
  22157. int startSample = 0;
  22158. int scale = 1 << 16;
  22159. const uint8* midiData;
  22160. int numBytes, samplePosition;
  22161. MidiBuffer::Iterator iter (incomingMessages);
  22162. if (numSourceSamples > numSamples)
  22163. {
  22164. // if our list of events is longer than the buffer we're being
  22165. // asked for, scale them down to squeeze them all in..
  22166. const int maxBlockLengthToUse = numSamples << 5;
  22167. if (numSourceSamples > maxBlockLengthToUse)
  22168. {
  22169. startSample = numSourceSamples - maxBlockLengthToUse;
  22170. numSourceSamples = maxBlockLengthToUse;
  22171. iter.setNextSamplePosition (startSample);
  22172. }
  22173. scale = (numSamples << 10) / numSourceSamples;
  22174. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22175. {
  22176. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  22177. destBuffer.addEvent (midiData, numBytes,
  22178. jlimit (0, numSamples - 1, samplePosition));
  22179. }
  22180. }
  22181. else
  22182. {
  22183. // if our event list is shorter than the number we need, put them
  22184. // towards the end of the buffer
  22185. startSample = numSamples - numSourceSamples;
  22186. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22187. {
  22188. destBuffer.addEvent (midiData, numBytes,
  22189. jlimit (0, numSamples - 1, samplePosition + startSample));
  22190. }
  22191. }
  22192. incomingMessages.clear();
  22193. }
  22194. }
  22195. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  22196. {
  22197. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  22198. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  22199. addMessageToQueue (m);
  22200. }
  22201. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  22202. {
  22203. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  22204. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  22205. addMessageToQueue (m);
  22206. }
  22207. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  22208. {
  22209. addMessageToQueue (message);
  22210. }
  22211. END_JUCE_NAMESPACE
  22212. /********* End of inlined file: juce_MidiMessageCollector.cpp *********/
  22213. /********* Start of inlined file: juce_MidiMessageSequence.cpp *********/
  22214. BEGIN_JUCE_NAMESPACE
  22215. MidiMessageSequence::MidiMessageSequence()
  22216. {
  22217. }
  22218. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  22219. {
  22220. list.ensureStorageAllocated (other.list.size());
  22221. for (int i = 0; i < other.list.size(); ++i)
  22222. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  22223. }
  22224. const MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  22225. {
  22226. if (this != &other)
  22227. {
  22228. clear();
  22229. for (int i = 0; i < other.list.size(); ++i)
  22230. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  22231. }
  22232. return *this;
  22233. }
  22234. MidiMessageSequence::~MidiMessageSequence()
  22235. {
  22236. }
  22237. void MidiMessageSequence::clear()
  22238. {
  22239. list.clear();
  22240. }
  22241. int MidiMessageSequence::getNumEvents() const
  22242. {
  22243. return list.size();
  22244. }
  22245. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  22246. {
  22247. return list [index];
  22248. }
  22249. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  22250. {
  22251. const MidiEventHolder* const meh = list [index];
  22252. if (meh != 0 && meh->noteOffObject != 0)
  22253. return meh->noteOffObject->message.getTimeStamp();
  22254. else
  22255. return 0.0;
  22256. }
  22257. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  22258. {
  22259. const MidiEventHolder* const meh = list [index];
  22260. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  22261. }
  22262. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  22263. {
  22264. return list.indexOf (event);
  22265. }
  22266. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  22267. {
  22268. const int numEvents = list.size();
  22269. int i;
  22270. for (i = 0; i < numEvents; ++i)
  22271. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  22272. break;
  22273. return i;
  22274. }
  22275. double MidiMessageSequence::getStartTime() const
  22276. {
  22277. if (list.size() > 0)
  22278. return list.getUnchecked(0)->message.getTimeStamp();
  22279. else
  22280. return 0;
  22281. }
  22282. double MidiMessageSequence::getEndTime() const
  22283. {
  22284. if (list.size() > 0)
  22285. return list.getLast()->message.getTimeStamp();
  22286. else
  22287. return 0;
  22288. }
  22289. double MidiMessageSequence::getEventTime (const int index) const
  22290. {
  22291. if (((unsigned int) index) < (unsigned int) list.size())
  22292. return list.getUnchecked (index)->message.getTimeStamp();
  22293. return 0.0;
  22294. }
  22295. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  22296. double timeAdjustment)
  22297. {
  22298. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  22299. timeAdjustment += newMessage.getTimeStamp();
  22300. newOne->message.setTimeStamp (timeAdjustment);
  22301. int i;
  22302. for (i = list.size(); --i >= 0;)
  22303. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  22304. break;
  22305. list.insert (i + 1, newOne);
  22306. }
  22307. void MidiMessageSequence::deleteEvent (const int index,
  22308. const bool deleteMatchingNoteUp)
  22309. {
  22310. if (((unsigned int) index) < (unsigned int) list.size())
  22311. {
  22312. if (deleteMatchingNoteUp)
  22313. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  22314. list.remove (index);
  22315. }
  22316. }
  22317. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  22318. double timeAdjustment,
  22319. double firstAllowableTime,
  22320. double endOfAllowableDestTimes)
  22321. {
  22322. firstAllowableTime -= timeAdjustment;
  22323. endOfAllowableDestTimes -= timeAdjustment;
  22324. for (int i = 0; i < other.list.size(); ++i)
  22325. {
  22326. const MidiMessage& m = other.list.getUnchecked(i)->message;
  22327. const double t = m.getTimeStamp();
  22328. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  22329. {
  22330. MidiEventHolder* const newOne = new MidiEventHolder (m);
  22331. newOne->message.setTimeStamp (timeAdjustment + t);
  22332. list.add (newOne);
  22333. }
  22334. }
  22335. sort();
  22336. }
  22337. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22338. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22339. {
  22340. const double diff = first->message.getTimeStamp()
  22341. - second->message.getTimeStamp();
  22342. return (diff > 0) - (diff < 0);
  22343. }
  22344. void MidiMessageSequence::sort()
  22345. {
  22346. list.sort (*this, true);
  22347. }
  22348. void MidiMessageSequence::updateMatchedPairs()
  22349. {
  22350. for (int i = 0; i < list.size(); ++i)
  22351. {
  22352. const MidiMessage& m1 = list.getUnchecked(i)->message;
  22353. if (m1.isNoteOn())
  22354. {
  22355. list.getUnchecked(i)->noteOffObject = 0;
  22356. const int note = m1.getNoteNumber();
  22357. const int chan = m1.getChannel();
  22358. const int len = list.size();
  22359. for (int j = i + 1; j < len; ++j)
  22360. {
  22361. const MidiMessage& m = list.getUnchecked(j)->message;
  22362. if (m.getNoteNumber() == note && m.getChannel() == chan)
  22363. {
  22364. if (m.isNoteOff())
  22365. {
  22366. list.getUnchecked(i)->noteOffObject = list[j];
  22367. break;
  22368. }
  22369. else if (m.isNoteOn())
  22370. {
  22371. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  22372. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  22373. list.getUnchecked(i)->noteOffObject = list[j];
  22374. break;
  22375. }
  22376. }
  22377. }
  22378. }
  22379. }
  22380. }
  22381. void MidiMessageSequence::addTimeToMessages (const double delta)
  22382. {
  22383. for (int i = list.size(); --i >= 0;)
  22384. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  22385. + delta);
  22386. }
  22387. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  22388. MidiMessageSequence& destSequence,
  22389. const bool alsoIncludeMetaEvents) const
  22390. {
  22391. for (int i = 0; i < list.size(); ++i)
  22392. {
  22393. const MidiMessage& mm = list.getUnchecked(i)->message;
  22394. if (mm.isForChannel (channelNumberToExtract)
  22395. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  22396. {
  22397. destSequence.addEvent (mm);
  22398. }
  22399. }
  22400. }
  22401. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  22402. {
  22403. for (int i = 0; i < list.size(); ++i)
  22404. {
  22405. const MidiMessage& mm = list.getUnchecked(i)->message;
  22406. if (mm.isSysEx())
  22407. destSequence.addEvent (mm);
  22408. }
  22409. }
  22410. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  22411. {
  22412. for (int i = list.size(); --i >= 0;)
  22413. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  22414. list.remove(i);
  22415. }
  22416. void MidiMessageSequence::deleteSysExMessages()
  22417. {
  22418. for (int i = list.size(); --i >= 0;)
  22419. if (list.getUnchecked(i)->message.isSysEx())
  22420. list.remove(i);
  22421. }
  22422. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  22423. const double time,
  22424. OwnedArray<MidiMessage>& dest)
  22425. {
  22426. bool doneProg = false;
  22427. bool donePitchWheel = false;
  22428. Array <int> doneControllers (32);
  22429. for (int i = list.size(); --i >= 0;)
  22430. {
  22431. const MidiMessage& mm = list.getUnchecked(i)->message;
  22432. if (mm.isForChannel (channelNumber)
  22433. && mm.getTimeStamp() <= time)
  22434. {
  22435. if (mm.isProgramChange())
  22436. {
  22437. if (! doneProg)
  22438. {
  22439. dest.add (new MidiMessage (mm, 0.0));
  22440. doneProg = true;
  22441. }
  22442. }
  22443. else if (mm.isController())
  22444. {
  22445. if (! doneControllers.contains (mm.getControllerNumber()))
  22446. {
  22447. dest.add (new MidiMessage (mm, 0.0));
  22448. doneControllers.add (mm.getControllerNumber());
  22449. }
  22450. }
  22451. else if (mm.isPitchWheel())
  22452. {
  22453. if (! donePitchWheel)
  22454. {
  22455. dest.add (new MidiMessage (mm, 0.0));
  22456. donePitchWheel = true;
  22457. }
  22458. }
  22459. }
  22460. }
  22461. }
  22462. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  22463. : message (message_),
  22464. noteOffObject (0)
  22465. {
  22466. }
  22467. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  22468. {
  22469. }
  22470. END_JUCE_NAMESPACE
  22471. /********* End of inlined file: juce_MidiMessageSequence.cpp *********/
  22472. /********* Start of inlined file: juce_AudioPluginFormat.cpp *********/
  22473. BEGIN_JUCE_NAMESPACE
  22474. AudioPluginFormat::AudioPluginFormat() throw()
  22475. {
  22476. }
  22477. AudioPluginFormat::~AudioPluginFormat()
  22478. {
  22479. }
  22480. END_JUCE_NAMESPACE
  22481. /********* End of inlined file: juce_AudioPluginFormat.cpp *********/
  22482. /********* Start of inlined file: juce_AudioPluginFormatManager.cpp *********/
  22483. BEGIN_JUCE_NAMESPACE
  22484. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  22485. {
  22486. }
  22487. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  22488. {
  22489. clearSingletonInstance();
  22490. }
  22491. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  22492. void AudioPluginFormatManager::addDefaultFormats()
  22493. {
  22494. #ifdef JUCE_DEBUG
  22495. // you should only call this method once!
  22496. for (int i = formats.size(); --i >= 0;)
  22497. {
  22498. #if JUCE_PLUGINHOST_VST
  22499. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  22500. #endif
  22501. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  22502. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  22503. #endif
  22504. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  22505. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  22506. #endif
  22507. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  22508. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  22509. #endif
  22510. }
  22511. #endif
  22512. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  22513. formats.add (new AudioUnitPluginFormat());
  22514. #endif
  22515. #if JUCE_PLUGINHOST_VST
  22516. formats.add (new VSTPluginFormat());
  22517. #endif
  22518. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  22519. formats.add (new DirectXPluginFormat());
  22520. #endif
  22521. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  22522. formats.add (new LADSPAPluginFormat());
  22523. #endif
  22524. }
  22525. int AudioPluginFormatManager::getNumFormats() throw()
  22526. {
  22527. return formats.size();
  22528. }
  22529. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  22530. {
  22531. return formats [index];
  22532. }
  22533. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  22534. {
  22535. formats.add (format);
  22536. }
  22537. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  22538. String& errorMessage) const
  22539. {
  22540. AudioPluginInstance* result = 0;
  22541. for (int i = 0; i < formats.size(); ++i)
  22542. {
  22543. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  22544. if (result != 0)
  22545. break;
  22546. }
  22547. if (result == 0)
  22548. {
  22549. if (! doesPluginStillExist (description))
  22550. errorMessage = TRANS ("This plug-in file no longer exists");
  22551. else
  22552. errorMessage = TRANS ("This plug-in failed to load correctly");
  22553. }
  22554. return result;
  22555. }
  22556. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  22557. {
  22558. for (int i = 0; i < formats.size(); ++i)
  22559. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  22560. return formats.getUnchecked(i)->doesPluginStillExist (description);
  22561. return false;
  22562. }
  22563. END_JUCE_NAMESPACE
  22564. /********* End of inlined file: juce_AudioPluginFormatManager.cpp *********/
  22565. /********* Start of inlined file: juce_AudioPluginInstance.cpp *********/
  22566. #define JUCE_PLUGIN_HOST 1
  22567. BEGIN_JUCE_NAMESPACE
  22568. AudioPluginInstance::AudioPluginInstance()
  22569. {
  22570. }
  22571. AudioPluginInstance::~AudioPluginInstance()
  22572. {
  22573. }
  22574. END_JUCE_NAMESPACE
  22575. /********* End of inlined file: juce_AudioPluginInstance.cpp *********/
  22576. /********* Start of inlined file: juce_KnownPluginList.cpp *********/
  22577. BEGIN_JUCE_NAMESPACE
  22578. KnownPluginList::KnownPluginList()
  22579. {
  22580. }
  22581. KnownPluginList::~KnownPluginList()
  22582. {
  22583. }
  22584. void KnownPluginList::clear()
  22585. {
  22586. if (types.size() > 0)
  22587. {
  22588. types.clear();
  22589. sendChangeMessage (this);
  22590. }
  22591. }
  22592. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  22593. {
  22594. for (int i = 0; i < types.size(); ++i)
  22595. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  22596. return types.getUnchecked(i);
  22597. return 0;
  22598. }
  22599. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  22600. {
  22601. for (int i = 0; i < types.size(); ++i)
  22602. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  22603. return types.getUnchecked(i);
  22604. return 0;
  22605. }
  22606. bool KnownPluginList::addType (const PluginDescription& type)
  22607. {
  22608. for (int i = types.size(); --i >= 0;)
  22609. {
  22610. if (types.getUnchecked(i)->isDuplicateOf (type))
  22611. {
  22612. // strange - found a duplicate plugin with different info..
  22613. jassert (types.getUnchecked(i)->name == type.name);
  22614. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  22615. *types.getUnchecked(i) = type;
  22616. return false;
  22617. }
  22618. }
  22619. types.add (new PluginDescription (type));
  22620. sendChangeMessage (this);
  22621. return true;
  22622. }
  22623. void KnownPluginList::removeType (const int index) throw()
  22624. {
  22625. types.remove (index);
  22626. sendChangeMessage (this);
  22627. }
  22628. static Time getFileModTime (const String& fileOrIdentifier) throw()
  22629. {
  22630. if (fileOrIdentifier.startsWithChar (T('/'))
  22631. || fileOrIdentifier[1] == T(':'))
  22632. {
  22633. return File (fileOrIdentifier).getLastModificationTime();
  22634. }
  22635. return Time (0);
  22636. }
  22637. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  22638. {
  22639. return t1 != t2 || t1 == Time (0);
  22640. }
  22641. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  22642. {
  22643. if (getTypeForFile (fileOrIdentifier) == 0)
  22644. return false;
  22645. for (int i = types.size(); --i >= 0;)
  22646. {
  22647. const PluginDescription* const d = types.getUnchecked(i);
  22648. if (d->fileOrIdentifier == fileOrIdentifier
  22649. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  22650. {
  22651. return false;
  22652. }
  22653. }
  22654. return true;
  22655. }
  22656. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  22657. const bool dontRescanIfAlreadyInList,
  22658. OwnedArray <PluginDescription>& typesFound,
  22659. AudioPluginFormat& format)
  22660. {
  22661. bool addedOne = false;
  22662. if (dontRescanIfAlreadyInList
  22663. && getTypeForFile (fileOrIdentifier) != 0)
  22664. {
  22665. bool needsRescanning = false;
  22666. for (int i = types.size(); --i >= 0;)
  22667. {
  22668. const PluginDescription* const d = types.getUnchecked(i);
  22669. if (d->fileOrIdentifier == fileOrIdentifier)
  22670. {
  22671. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  22672. needsRescanning = true;
  22673. else
  22674. typesFound.add (new PluginDescription (*d));
  22675. }
  22676. }
  22677. if (! needsRescanning)
  22678. return false;
  22679. }
  22680. OwnedArray <PluginDescription> found;
  22681. format.findAllTypesForFile (found, fileOrIdentifier);
  22682. for (int i = 0; i < found.size(); ++i)
  22683. {
  22684. PluginDescription* const desc = found.getUnchecked(i);
  22685. jassert (desc != 0);
  22686. if (addType (*desc))
  22687. addedOne = true;
  22688. typesFound.add (new PluginDescription (*desc));
  22689. }
  22690. return addedOne;
  22691. }
  22692. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  22693. OwnedArray <PluginDescription>& typesFound)
  22694. {
  22695. for (int i = 0; i < files.size(); ++i)
  22696. {
  22697. bool loaded = false;
  22698. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  22699. {
  22700. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  22701. if (scanAndAddFile (files[i], true, typesFound, *format))
  22702. loaded = true;
  22703. }
  22704. if (! loaded)
  22705. {
  22706. const File f (files[i]);
  22707. if (f.isDirectory())
  22708. {
  22709. StringArray s;
  22710. {
  22711. OwnedArray <File> subFiles;
  22712. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  22713. for (int j = 0; j < subFiles.size(); ++j)
  22714. s.add (subFiles.getUnchecked (j)->getFullPathName());
  22715. }
  22716. scanAndAddDragAndDroppedFiles (s, typesFound);
  22717. }
  22718. }
  22719. }
  22720. }
  22721. class PluginSorter
  22722. {
  22723. public:
  22724. KnownPluginList::SortMethod method;
  22725. PluginSorter() throw() {}
  22726. int compareElements (const PluginDescription* const first,
  22727. const PluginDescription* const second) const throw()
  22728. {
  22729. int diff = 0;
  22730. if (method == KnownPluginList::sortByCategory)
  22731. diff = first->category.compareLexicographically (second->category);
  22732. else if (method == KnownPluginList::sortByManufacturer)
  22733. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  22734. else if (method == KnownPluginList::sortByFileSystemLocation)
  22735. diff = first->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  22736. .upToLastOccurrenceOf (T("/"), false, false)
  22737. .compare (second->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  22738. .upToLastOccurrenceOf (T("/"), false, false));
  22739. if (diff == 0)
  22740. diff = first->name.compareLexicographically (second->name);
  22741. return diff;
  22742. }
  22743. };
  22744. void KnownPluginList::sort (const SortMethod method)
  22745. {
  22746. if (method != defaultOrder)
  22747. {
  22748. PluginSorter sorter;
  22749. sorter.method = method;
  22750. types.sort (sorter, true);
  22751. sendChangeMessage (this);
  22752. }
  22753. }
  22754. XmlElement* KnownPluginList::createXml() const
  22755. {
  22756. XmlElement* const e = new XmlElement (T("KNOWNPLUGINS"));
  22757. for (int i = 0; i < types.size(); ++i)
  22758. e->addChildElement (types.getUnchecked(i)->createXml());
  22759. return e;
  22760. }
  22761. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  22762. {
  22763. clear();
  22764. if (xml.hasTagName (T("KNOWNPLUGINS")))
  22765. {
  22766. forEachXmlChildElement (xml, e)
  22767. {
  22768. PluginDescription info;
  22769. if (info.loadFromXml (*e))
  22770. addType (info);
  22771. }
  22772. }
  22773. }
  22774. const int menuIdBase = 0x324503f4;
  22775. // This is used to turn a bunch of paths into a nested menu structure.
  22776. struct PluginFilesystemTree
  22777. {
  22778. private:
  22779. String folder;
  22780. OwnedArray <PluginFilesystemTree> subFolders;
  22781. Array <PluginDescription*> plugins;
  22782. void addPlugin (PluginDescription* const pd, const String& path)
  22783. {
  22784. if (path.isEmpty())
  22785. {
  22786. plugins.add (pd);
  22787. }
  22788. else
  22789. {
  22790. const String firstSubFolder (path.upToFirstOccurrenceOf (T("/"), false, false));
  22791. const String remainingPath (path.fromFirstOccurrenceOf (T("/"), false, false));
  22792. for (int i = subFolders.size(); --i >= 0;)
  22793. {
  22794. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  22795. {
  22796. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  22797. return;
  22798. }
  22799. }
  22800. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  22801. newFolder->folder = firstSubFolder;
  22802. subFolders.add (newFolder);
  22803. newFolder->addPlugin (pd, remainingPath);
  22804. }
  22805. }
  22806. // removes any deeply nested folders that don't contain any actual plugins
  22807. void optimise()
  22808. {
  22809. for (int i = subFolders.size(); --i >= 0;)
  22810. {
  22811. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  22812. sub->optimise();
  22813. if (sub->plugins.size() == 0)
  22814. {
  22815. for (int j = 0; j < sub->subFolders.size(); ++j)
  22816. subFolders.add (sub->subFolders.getUnchecked(j));
  22817. sub->subFolders.clear (false);
  22818. subFolders.remove (i);
  22819. }
  22820. }
  22821. }
  22822. public:
  22823. void buildTree (const Array <PluginDescription*>& allPlugins)
  22824. {
  22825. for (int i = 0; i < allPlugins.size(); ++i)
  22826. {
  22827. String path (allPlugins.getUnchecked(i)
  22828. ->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  22829. .upToLastOccurrenceOf (T("/"), false, false));
  22830. if (path.substring (1, 2) == T(":"))
  22831. path = path.substring (2);
  22832. addPlugin (allPlugins.getUnchecked(i), path);
  22833. }
  22834. optimise();
  22835. }
  22836. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  22837. {
  22838. int i;
  22839. for (i = 0; i < subFolders.size(); ++i)
  22840. {
  22841. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  22842. PopupMenu subMenu;
  22843. sub->addToMenu (subMenu, allPlugins);
  22844. #if JUCE_MAC
  22845. // avoid the special AU formatting nonsense on Mac..
  22846. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (T(":"), false, false), subMenu);
  22847. #else
  22848. m.addSubMenu (sub->folder, subMenu);
  22849. #endif
  22850. }
  22851. for (i = 0; i < plugins.size(); ++i)
  22852. {
  22853. PluginDescription* const plugin = plugins.getUnchecked(i);
  22854. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  22855. plugin->name, true, false);
  22856. }
  22857. }
  22858. };
  22859. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  22860. {
  22861. Array <PluginDescription*> sorted;
  22862. {
  22863. PluginSorter sorter;
  22864. sorter.method = sortMethod;
  22865. for (int i = 0; i < types.size(); ++i)
  22866. sorted.addSorted (sorter, types.getUnchecked(i));
  22867. }
  22868. if (sortMethod == sortByCategory
  22869. || sortMethod == sortByManufacturer)
  22870. {
  22871. String lastSubMenuName;
  22872. PopupMenu sub;
  22873. for (int i = 0; i < sorted.size(); ++i)
  22874. {
  22875. const PluginDescription* const pd = sorted.getUnchecked(i);
  22876. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  22877. : pd->manufacturerName);
  22878. if (! thisSubMenuName.containsNonWhitespaceChars())
  22879. thisSubMenuName = T("Other");
  22880. if (thisSubMenuName != lastSubMenuName)
  22881. {
  22882. if (sub.getNumItems() > 0)
  22883. {
  22884. menu.addSubMenu (lastSubMenuName, sub);
  22885. sub.clear();
  22886. }
  22887. lastSubMenuName = thisSubMenuName;
  22888. }
  22889. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  22890. }
  22891. if (sub.getNumItems() > 0)
  22892. menu.addSubMenu (lastSubMenuName, sub);
  22893. }
  22894. else if (sortMethod == sortByFileSystemLocation)
  22895. {
  22896. PluginFilesystemTree root;
  22897. root.buildTree (sorted);
  22898. root.addToMenu (menu, types);
  22899. }
  22900. else
  22901. {
  22902. for (int i = 0; i < sorted.size(); ++i)
  22903. {
  22904. const PluginDescription* const pd = sorted.getUnchecked(i);
  22905. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  22906. }
  22907. }
  22908. }
  22909. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  22910. {
  22911. const int i = menuResultCode - menuIdBase;
  22912. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  22913. }
  22914. END_JUCE_NAMESPACE
  22915. /********* End of inlined file: juce_KnownPluginList.cpp *********/
  22916. /********* Start of inlined file: juce_PluginDescription.cpp *********/
  22917. BEGIN_JUCE_NAMESPACE
  22918. PluginDescription::PluginDescription() throw()
  22919. : uid (0),
  22920. isInstrument (false),
  22921. numInputChannels (0),
  22922. numOutputChannels (0)
  22923. {
  22924. }
  22925. PluginDescription::~PluginDescription() throw()
  22926. {
  22927. }
  22928. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  22929. : name (other.name),
  22930. pluginFormatName (other.pluginFormatName),
  22931. category (other.category),
  22932. manufacturerName (other.manufacturerName),
  22933. version (other.version),
  22934. fileOrIdentifier (other.fileOrIdentifier),
  22935. lastFileModTime (other.lastFileModTime),
  22936. uid (other.uid),
  22937. isInstrument (other.isInstrument),
  22938. numInputChannels (other.numInputChannels),
  22939. numOutputChannels (other.numOutputChannels)
  22940. {
  22941. }
  22942. const PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  22943. {
  22944. name = other.name;
  22945. pluginFormatName = other.pluginFormatName;
  22946. category = other.category;
  22947. manufacturerName = other.manufacturerName;
  22948. version = other.version;
  22949. fileOrIdentifier = other.fileOrIdentifier;
  22950. uid = other.uid;
  22951. isInstrument = other.isInstrument;
  22952. lastFileModTime = other.lastFileModTime;
  22953. numInputChannels = other.numInputChannels;
  22954. numOutputChannels = other.numOutputChannels;
  22955. return *this;
  22956. }
  22957. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  22958. {
  22959. return fileOrIdentifier == other.fileOrIdentifier
  22960. && uid == other.uid;
  22961. }
  22962. const String PluginDescription::createIdentifierString() const throw()
  22963. {
  22964. return pluginFormatName
  22965. + T("-") + name
  22966. + T("-") + String::toHexString (fileOrIdentifier.hashCode())
  22967. + T("-") + String::toHexString (uid);
  22968. }
  22969. XmlElement* PluginDescription::createXml() const
  22970. {
  22971. XmlElement* const e = new XmlElement (T("PLUGIN"));
  22972. e->setAttribute (T("name"), name);
  22973. e->setAttribute (T("format"), pluginFormatName);
  22974. e->setAttribute (T("category"), category);
  22975. e->setAttribute (T("manufacturer"), manufacturerName);
  22976. e->setAttribute (T("version"), version);
  22977. e->setAttribute (T("file"), fileOrIdentifier);
  22978. e->setAttribute (T("uid"), String::toHexString (uid));
  22979. e->setAttribute (T("isInstrument"), isInstrument);
  22980. e->setAttribute (T("fileTime"), String::toHexString (lastFileModTime.toMilliseconds()));
  22981. e->setAttribute (T("numInputs"), numInputChannels);
  22982. e->setAttribute (T("numOutputs"), numOutputChannels);
  22983. return e;
  22984. }
  22985. bool PluginDescription::loadFromXml (const XmlElement& xml)
  22986. {
  22987. if (xml.hasTagName (T("PLUGIN")))
  22988. {
  22989. name = xml.getStringAttribute (T("name"));
  22990. pluginFormatName = xml.getStringAttribute (T("format"));
  22991. category = xml.getStringAttribute (T("category"));
  22992. manufacturerName = xml.getStringAttribute (T("manufacturer"));
  22993. version = xml.getStringAttribute (T("version"));
  22994. fileOrIdentifier = xml.getStringAttribute (T("file"));
  22995. uid = xml.getStringAttribute (T("uid")).getHexValue32();
  22996. isInstrument = xml.getBoolAttribute (T("isInstrument"), false);
  22997. lastFileModTime = Time (xml.getStringAttribute (T("fileTime")).getHexValue64());
  22998. numInputChannels = xml.getIntAttribute (T("numInputs"));
  22999. numOutputChannels = xml.getIntAttribute (T("numOutputs"));
  23000. return true;
  23001. }
  23002. return false;
  23003. }
  23004. END_JUCE_NAMESPACE
  23005. /********* End of inlined file: juce_PluginDescription.cpp *********/
  23006. /********* Start of inlined file: juce_PluginDirectoryScanner.cpp *********/
  23007. BEGIN_JUCE_NAMESPACE
  23008. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23009. AudioPluginFormat& formatToLookFor,
  23010. FileSearchPath directoriesToSearch,
  23011. const bool recursive,
  23012. const File& deadMansPedalFile_)
  23013. : list (listToAddTo),
  23014. format (formatToLookFor),
  23015. deadMansPedalFile (deadMansPedalFile_),
  23016. nextIndex (0),
  23017. progress (0)
  23018. {
  23019. directoriesToSearch.removeRedundantPaths();
  23020. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23021. // If any plugins have crashed recently when being loaded, move them to the
  23022. // end of the list to give the others a chance to load correctly..
  23023. const StringArray crashedPlugins (getDeadMansPedalFile());
  23024. for (int i = 0; i < crashedPlugins.size(); ++i)
  23025. {
  23026. const String f = crashedPlugins[i];
  23027. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23028. if (f == filesOrIdentifiersToScan[j])
  23029. filesOrIdentifiersToScan.move (j, -1);
  23030. }
  23031. }
  23032. PluginDirectoryScanner::~PluginDirectoryScanner()
  23033. {
  23034. }
  23035. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23036. {
  23037. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23038. }
  23039. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23040. {
  23041. String file (filesOrIdentifiersToScan [nextIndex]);
  23042. if (file.isNotEmpty())
  23043. {
  23044. if (! list.isListingUpToDate (file))
  23045. {
  23046. OwnedArray <PluginDescription> typesFound;
  23047. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23048. StringArray crashedPlugins (getDeadMansPedalFile());
  23049. crashedPlugins.removeString (file);
  23050. crashedPlugins.add (file);
  23051. setDeadMansPedalFile (crashedPlugins);
  23052. list.scanAndAddFile (file,
  23053. dontRescanIfAlreadyInList,
  23054. typesFound,
  23055. format);
  23056. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23057. crashedPlugins.removeString (file);
  23058. setDeadMansPedalFile (crashedPlugins);
  23059. if (typesFound.size() == 0)
  23060. failedFiles.add (file);
  23061. }
  23062. ++nextIndex;
  23063. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23064. }
  23065. return nextIndex < filesOrIdentifiersToScan.size();
  23066. }
  23067. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23068. {
  23069. StringArray lines;
  23070. if (deadMansPedalFile != File::nonexistent)
  23071. {
  23072. lines.addLines (deadMansPedalFile.loadFileAsString());
  23073. lines.removeEmptyStrings();
  23074. }
  23075. return lines;
  23076. }
  23077. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23078. {
  23079. if (deadMansPedalFile != File::nonexistent)
  23080. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23081. }
  23082. END_JUCE_NAMESPACE
  23083. /********* End of inlined file: juce_PluginDirectoryScanner.cpp *********/
  23084. /********* Start of inlined file: juce_PluginListComponent.cpp *********/
  23085. BEGIN_JUCE_NAMESPACE
  23086. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23087. const File& deadMansPedalFile_,
  23088. PropertiesFile* const propertiesToUse_)
  23089. : list (listToEdit),
  23090. deadMansPedalFile (deadMansPedalFile_),
  23091. propertiesToUse (propertiesToUse_)
  23092. {
  23093. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23094. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23095. optionsButton->addButtonListener (this);
  23096. optionsButton->setTriggeredOnMouseDown (true);
  23097. setSize (400, 600);
  23098. list.addChangeListener (this);
  23099. }
  23100. PluginListComponent::~PluginListComponent()
  23101. {
  23102. list.removeChangeListener (this);
  23103. deleteAllChildren();
  23104. }
  23105. void PluginListComponent::resized()
  23106. {
  23107. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23108. optionsButton->changeWidthToFitText (24);
  23109. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23110. }
  23111. void PluginListComponent::changeListenerCallback (void*)
  23112. {
  23113. listBox->updateContent();
  23114. listBox->repaint();
  23115. }
  23116. int PluginListComponent::getNumRows()
  23117. {
  23118. return list.getNumTypes();
  23119. }
  23120. void PluginListComponent::paintListBoxItem (int row,
  23121. Graphics& g,
  23122. int width, int height,
  23123. bool rowIsSelected)
  23124. {
  23125. if (rowIsSelected)
  23126. g.fillAll (findColour (TextEditor::highlightColourId));
  23127. const PluginDescription* const pd = list.getType (row);
  23128. if (pd != 0)
  23129. {
  23130. GlyphArrangement ga;
  23131. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23132. g.setColour (Colours::black);
  23133. ga.draw (g);
  23134. float x, y, r, b;
  23135. ga.getBoundingBox (0, -1, x, y, r, b, false);
  23136. String desc;
  23137. desc << pd->pluginFormatName
  23138. << (pd->isInstrument ? " instrument" : " effect")
  23139. << " - "
  23140. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  23141. << " / "
  23142. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  23143. if (pd->manufacturerName.isNotEmpty())
  23144. desc << " - " << pd->manufacturerName;
  23145. if (pd->version.isNotEmpty())
  23146. desc << " - " << pd->version;
  23147. if (pd->category.isNotEmpty())
  23148. desc << " - category: '" << pd->category << '\'';
  23149. g.setColour (Colours::grey);
  23150. ga.clear();
  23151. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, r + 10.0f, height * 0.8f, width - r - 12.0f, true);
  23152. ga.draw (g);
  23153. }
  23154. }
  23155. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  23156. {
  23157. list.removeType (lastRowSelected);
  23158. }
  23159. void PluginListComponent::buttonClicked (Button* b)
  23160. {
  23161. if (optionsButton == b)
  23162. {
  23163. PopupMenu menu;
  23164. menu.addItem (1, TRANS("Clear list"));
  23165. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  23166. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  23167. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  23168. menu.addSeparator();
  23169. menu.addItem (2, TRANS("Sort alphabetically"));
  23170. menu.addItem (3, TRANS("Sort by category"));
  23171. menu.addItem (4, TRANS("Sort by manufacturer"));
  23172. menu.addSeparator();
  23173. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  23174. {
  23175. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  23176. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  23177. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  23178. }
  23179. const int r = menu.showAt (optionsButton);
  23180. if (r == 1)
  23181. {
  23182. list.clear();
  23183. }
  23184. else if (r == 2)
  23185. {
  23186. list.sort (KnownPluginList::sortAlphabetically);
  23187. }
  23188. else if (r == 3)
  23189. {
  23190. list.sort (KnownPluginList::sortByCategory);
  23191. }
  23192. else if (r == 4)
  23193. {
  23194. list.sort (KnownPluginList::sortByManufacturer);
  23195. }
  23196. else if (r == 5)
  23197. {
  23198. const SparseSet <int> selected (listBox->getSelectedRows());
  23199. for (int i = list.getNumTypes(); --i >= 0;)
  23200. if (selected.contains (i))
  23201. list.removeType (i);
  23202. }
  23203. else if (r == 6)
  23204. {
  23205. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  23206. if (desc != 0)
  23207. {
  23208. if (File (desc->fileOrIdentifier).existsAsFile())
  23209. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  23210. }
  23211. }
  23212. else if (r == 7)
  23213. {
  23214. for (int i = list.getNumTypes(); --i >= 0;)
  23215. {
  23216. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  23217. {
  23218. list.removeType (i);
  23219. }
  23220. }
  23221. }
  23222. else if (r != 0)
  23223. {
  23224. typeToScan = r - 10;
  23225. startTimer (1);
  23226. }
  23227. }
  23228. }
  23229. void PluginListComponent::timerCallback()
  23230. {
  23231. stopTimer();
  23232. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  23233. }
  23234. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  23235. {
  23236. return true;
  23237. }
  23238. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  23239. {
  23240. OwnedArray <PluginDescription> typesFound;
  23241. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  23242. }
  23243. void PluginListComponent::scanFor (AudioPluginFormat* format)
  23244. {
  23245. if (format == 0)
  23246. return;
  23247. FileSearchPath path (format->getDefaultLocationsToSearch());
  23248. if (propertiesToUse != 0)
  23249. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  23250. {
  23251. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  23252. FileSearchPathListComponent pathList;
  23253. pathList.setSize (500, 300);
  23254. pathList.setPath (path);
  23255. aw.addCustomComponent (&pathList);
  23256. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  23257. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  23258. if (aw.runModalLoop() == 0)
  23259. return;
  23260. path = pathList.getPath();
  23261. }
  23262. if (propertiesToUse != 0)
  23263. {
  23264. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  23265. propertiesToUse->saveIfNeeded();
  23266. }
  23267. double progress = 0.0;
  23268. AlertWindow aw (TRANS("Scanning for plugins..."),
  23269. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  23270. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  23271. aw.addProgressBarComponent (progress);
  23272. aw.enterModalState();
  23273. MessageManager::getInstance()->runDispatchLoopUntil (300);
  23274. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  23275. for (;;)
  23276. {
  23277. aw.setMessage (TRANS("Testing:\n\n")
  23278. + scanner.getNextPluginFileThatWillBeScanned());
  23279. MessageManager::getInstance()->runDispatchLoopUntil (20);
  23280. if (! scanner.scanNextFile (true))
  23281. break;
  23282. if (! aw.isCurrentlyModal())
  23283. break;
  23284. progress = scanner.getProgress();
  23285. }
  23286. if (scanner.getFailedFiles().size() > 0)
  23287. {
  23288. StringArray shortNames;
  23289. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  23290. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  23291. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  23292. TRANS("Scan complete"),
  23293. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  23294. + shortNames.joinIntoString (", "));
  23295. }
  23296. }
  23297. END_JUCE_NAMESPACE
  23298. /********* End of inlined file: juce_PluginListComponent.cpp *********/
  23299. /********* Start of inlined file: juce_AudioUnitPluginFormat.mm *********/
  23300. #if JUCE_PLUGINHOST_AU && (! (defined (LINUX) || defined (_WIN32)))
  23301. #include <AudioUnit/AudioUnit.h>
  23302. #include <AudioUnit/AUCocoaUIView.h>
  23303. #include <CoreAudioKit/AUGenericView.h>
  23304. #if JUCE_SUPPORT_CARBON
  23305. #include <AudioToolbox/AudioUnitUtilities.h>
  23306. #include <AudioUnit/AudioUnitCarbonView.h>
  23307. #endif
  23308. BEGIN_JUCE_NAMESPACE
  23309. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  23310. #endif
  23311. #if JUCE_MAC
  23312. #if MACOS_10_3_OR_EARLIER
  23313. #define kAudioUnitType_Generator 'augn'
  23314. #endif
  23315. // Change this to disable logging of various activities
  23316. #ifndef AU_LOGGING
  23317. #define AU_LOGGING 1
  23318. #endif
  23319. #if AU_LOGGING
  23320. #define log(a) Logger::writeToLog(a);
  23321. #else
  23322. #define log(a)
  23323. #endif
  23324. static int insideCallback = 0;
  23325. static const String osTypeToString (OSType type) throw()
  23326. {
  23327. char s[4];
  23328. s[0] = (char) (((uint32) type) >> 24);
  23329. s[1] = (char) (((uint32) type) >> 16);
  23330. s[2] = (char) (((uint32) type) >> 8);
  23331. s[3] = (char) ((uint32) type);
  23332. return String (s, 4);
  23333. }
  23334. static OSType stringToOSType (const String& s1) throw()
  23335. {
  23336. const String s (s1 + " ");
  23337. return (((OSType) (unsigned char) s[0]) << 24)
  23338. | (((OSType) (unsigned char) s[1]) << 16)
  23339. | (((OSType) (unsigned char) s[2]) << 8)
  23340. | ((OSType) (unsigned char) s[3]);
  23341. }
  23342. static const tchar* auIdentifierPrefix = T("AudioUnit:");
  23343. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  23344. {
  23345. jassert (osTypeToString ('abcd') == T("abcd")); // agh, must have got the endianness wrong..
  23346. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  23347. String s (auIdentifierPrefix);
  23348. if (desc.componentType == kAudioUnitType_MusicDevice)
  23349. s << "Synths/";
  23350. else if (desc.componentType == kAudioUnitType_MusicEffect
  23351. || desc.componentType == kAudioUnitType_Effect)
  23352. s << "Effects/";
  23353. else if (desc.componentType == kAudioUnitType_Generator)
  23354. s << "Generators/";
  23355. else if (desc.componentType == kAudioUnitType_Panner)
  23356. s << "Panners/";
  23357. s << osTypeToString (desc.componentType)
  23358. << T(",")
  23359. << osTypeToString (desc.componentSubType)
  23360. << T(",")
  23361. << osTypeToString (desc.componentManufacturer);
  23362. return s;
  23363. }
  23364. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  23365. {
  23366. Handle componentNameHandle = NewHandle (sizeof (void*));
  23367. Handle componentInfoHandle = NewHandle (sizeof (void*));
  23368. if (componentNameHandle != 0 && componentInfoHandle != 0)
  23369. {
  23370. ComponentDescription desc;
  23371. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  23372. {
  23373. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  23374. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  23375. if (nameString != 0 && nameString[0] != 0)
  23376. {
  23377. const String all ((const char*) nameString + 1, nameString[0]);
  23378. DBG ("name: "+ all);
  23379. manufacturer = all.upToFirstOccurrenceOf (T(":"), false, false).trim();
  23380. name = all.fromFirstOccurrenceOf (T(":"), false, false).trim();
  23381. }
  23382. if (infoString != 0 && infoString[0] != 0)
  23383. {
  23384. const String all ((const char*) infoString + 1, infoString[0]);
  23385. DBG ("info: " + all);
  23386. }
  23387. if (name.isEmpty())
  23388. name = "<Unknown>";
  23389. }
  23390. DisposeHandle (componentNameHandle);
  23391. DisposeHandle (componentInfoHandle);
  23392. }
  23393. }
  23394. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  23395. String& name, String& version, String& manufacturer)
  23396. {
  23397. zerostruct (desc);
  23398. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  23399. {
  23400. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (T(':')),
  23401. fileOrIdentifier.lastIndexOfChar (T('/'))) + 1));
  23402. StringArray tokens;
  23403. tokens.addTokens (s, T(","), 0);
  23404. tokens.trim();
  23405. tokens.removeEmptyStrings();
  23406. if (tokens.size() == 3)
  23407. {
  23408. desc.componentType = stringToOSType (tokens[0]);
  23409. desc.componentSubType = stringToOSType (tokens[1]);
  23410. desc.componentManufacturer = stringToOSType (tokens[2]);
  23411. ComponentRecord* comp = FindNextComponent (0, &desc);
  23412. if (comp != 0)
  23413. {
  23414. getAUDetails (comp, name, manufacturer);
  23415. return true;
  23416. }
  23417. }
  23418. }
  23419. return false;
  23420. }
  23421. class AudioUnitPluginWindowCarbon;
  23422. class AudioUnitPluginWindowCocoa;
  23423. class AudioUnitPluginInstance : public AudioPluginInstance
  23424. {
  23425. public:
  23426. ~AudioUnitPluginInstance();
  23427. // AudioPluginInstance methods:
  23428. void fillInPluginDescription (PluginDescription& desc) const
  23429. {
  23430. desc.name = pluginName;
  23431. desc.fileOrIdentifier = createAUPluginIdentifier (componentDesc);
  23432. desc.uid = ((int) componentDesc.componentType)
  23433. ^ ((int) componentDesc.componentSubType)
  23434. ^ ((int) componentDesc.componentManufacturer);
  23435. desc.lastFileModTime = 0;
  23436. desc.pluginFormatName = "AudioUnit";
  23437. desc.category = getCategory();
  23438. desc.manufacturerName = manufacturer;
  23439. desc.version = version;
  23440. desc.numInputChannels = getNumInputChannels();
  23441. desc.numOutputChannels = getNumOutputChannels();
  23442. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  23443. }
  23444. const String getName() const { return pluginName; }
  23445. bool acceptsMidi() const { return wantsMidiMessages; }
  23446. bool producesMidi() const { return false; }
  23447. // AudioProcessor methods:
  23448. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  23449. void releaseResources();
  23450. void processBlock (AudioSampleBuffer& buffer,
  23451. MidiBuffer& midiMessages);
  23452. AudioProcessorEditor* createEditor();
  23453. const String getInputChannelName (const int index) const;
  23454. bool isInputChannelStereoPair (int index) const;
  23455. const String getOutputChannelName (const int index) const;
  23456. bool isOutputChannelStereoPair (int index) const;
  23457. int getNumParameters();
  23458. float getParameter (int index);
  23459. void setParameter (int index, float newValue);
  23460. const String getParameterName (int index);
  23461. const String getParameterText (int index);
  23462. bool isParameterAutomatable (int index) const;
  23463. int getNumPrograms();
  23464. int getCurrentProgram();
  23465. void setCurrentProgram (int index);
  23466. const String getProgramName (int index);
  23467. void changeProgramName (int index, const String& newName);
  23468. void getStateInformation (MemoryBlock& destData);
  23469. void getCurrentProgramStateInformation (MemoryBlock& destData);
  23470. void setStateInformation (const void* data, int sizeInBytes);
  23471. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  23472. juce_UseDebuggingNewOperator
  23473. private:
  23474. friend class AudioUnitPluginWindowCarbon;
  23475. friend class AudioUnitPluginWindowCocoa;
  23476. friend class AudioUnitPluginFormat;
  23477. ComponentDescription componentDesc;
  23478. String pluginName, manufacturer, version;
  23479. String fileOrIdentifier;
  23480. CriticalSection lock;
  23481. bool initialised, wantsMidiMessages, wasPlaying;
  23482. AudioBufferList* outputBufferList;
  23483. AudioTimeStamp timeStamp;
  23484. AudioSampleBuffer* currentBuffer;
  23485. AudioUnit audioUnit;
  23486. Array <int> parameterIds;
  23487. bool getComponentDescFromFile (const String& fileOrIdentifier);
  23488. void initialise();
  23489. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  23490. const AudioTimeStamp* inTimeStamp,
  23491. UInt32 inBusNumber,
  23492. UInt32 inNumberFrames,
  23493. AudioBufferList* ioData) const;
  23494. static OSStatus renderGetInputCallback (void* inRefCon,
  23495. AudioUnitRenderActionFlags* ioActionFlags,
  23496. const AudioTimeStamp* inTimeStamp,
  23497. UInt32 inBusNumber,
  23498. UInt32 inNumberFrames,
  23499. AudioBufferList* ioData)
  23500. {
  23501. return ((AudioUnitPluginInstance*) inRefCon)
  23502. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  23503. }
  23504. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  23505. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  23506. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  23507. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  23508. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  23509. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  23510. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  23511. {
  23512. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  23513. }
  23514. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  23515. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  23516. Float64* outCurrentMeasureDownBeat)
  23517. {
  23518. return ((AudioUnitPluginInstance*) inHostUserData)
  23519. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  23520. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  23521. }
  23522. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  23523. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  23524. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  23525. {
  23526. return ((AudioUnitPluginInstance*) inHostUserData)
  23527. ->getTransportState (outIsPlaying, outTransportStateChanged,
  23528. outCurrentSampleInTimeLine, outIsCycling,
  23529. outCycleStartBeat, outCycleEndBeat);
  23530. }
  23531. void getNumChannels (int& numIns, int& numOuts)
  23532. {
  23533. numIns = 0;
  23534. numOuts = 0;
  23535. AUChannelInfo supportedChannels [128];
  23536. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  23537. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  23538. 0, supportedChannels, &supportedChannelsSize) == noErr
  23539. && supportedChannelsSize > 0)
  23540. {
  23541. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  23542. {
  23543. numIns = jmax (numIns, supportedChannels[i].inChannels);
  23544. numOuts = jmax (numOuts, supportedChannels[i].outChannels);
  23545. }
  23546. }
  23547. else
  23548. {
  23549. // (this really means the plugin will take any number of ins/outs as long
  23550. // as they are the same)
  23551. numIns = numOuts = 2;
  23552. }
  23553. }
  23554. const String getCategory() const;
  23555. AudioUnitPluginInstance (const String& fileOrIdentifier);
  23556. };
  23557. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  23558. : fileOrIdentifier (fileOrIdentifier),
  23559. initialised (false),
  23560. wantsMidiMessages (false),
  23561. audioUnit (0),
  23562. outputBufferList (0),
  23563. currentBuffer (0)
  23564. {
  23565. try
  23566. {
  23567. ++insideCallback;
  23568. log (T("Opening AU: ") + fileOrIdentifier);
  23569. if (getComponentDescFromFile (fileOrIdentifier))
  23570. {
  23571. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  23572. if (comp != 0)
  23573. {
  23574. audioUnit = (AudioUnit) OpenComponent (comp);
  23575. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  23576. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  23577. }
  23578. }
  23579. --insideCallback;
  23580. }
  23581. catch (...)
  23582. {
  23583. --insideCallback;
  23584. }
  23585. }
  23586. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  23587. {
  23588. {
  23589. const ScopedLock sl (lock);
  23590. jassert (insideCallback == 0);
  23591. if (audioUnit != 0)
  23592. {
  23593. AudioUnitUninitialize (audioUnit);
  23594. CloseComponent (audioUnit);
  23595. audioUnit = 0;
  23596. }
  23597. }
  23598. juce_free (outputBufferList);
  23599. }
  23600. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  23601. {
  23602. zerostruct (componentDesc);
  23603. if (getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  23604. return true;
  23605. const File file (fileOrIdentifier);
  23606. if (! file.hasFileExtension (T(".component")))
  23607. return false;
  23608. const char* const utf8 = fileOrIdentifier.toUTF8();
  23609. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  23610. strlen (utf8), file.isDirectory());
  23611. if (url != 0)
  23612. {
  23613. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  23614. CFRelease (url);
  23615. if (bundleRef != 0)
  23616. {
  23617. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  23618. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  23619. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  23620. if (pluginName.isEmpty())
  23621. pluginName = file.getFileNameWithoutExtension();
  23622. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  23623. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  23624. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  23625. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  23626. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  23627. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  23628. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  23629. UseResFile (resFileId);
  23630. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  23631. {
  23632. Handle h = Get1IndResource ('thng', i);
  23633. if (h != 0)
  23634. {
  23635. HLock (h);
  23636. const uint32* const types = (const uint32*) *h;
  23637. if (types[0] == kAudioUnitType_MusicDevice
  23638. || types[0] == kAudioUnitType_MusicEffect
  23639. || types[0] == kAudioUnitType_Effect
  23640. || types[0] == kAudioUnitType_Generator
  23641. || types[0] == kAudioUnitType_Panner)
  23642. {
  23643. componentDesc.componentType = types[0];
  23644. componentDesc.componentSubType = types[1];
  23645. componentDesc.componentManufacturer = types[2];
  23646. break;
  23647. }
  23648. HUnlock (h);
  23649. ReleaseResource (h);
  23650. }
  23651. }
  23652. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  23653. CFRelease (bundleRef);
  23654. }
  23655. }
  23656. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  23657. }
  23658. void AudioUnitPluginInstance::initialise()
  23659. {
  23660. if (initialised || audioUnit == 0)
  23661. return;
  23662. log (T("Initialising AU: ") + pluginName);
  23663. parameterIds.clear();
  23664. {
  23665. UInt32 paramListSize = 0;
  23666. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  23667. 0, 0, &paramListSize);
  23668. if (paramListSize > 0)
  23669. {
  23670. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  23671. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  23672. 0, &parameterIds.getReference(0), &paramListSize);
  23673. }
  23674. }
  23675. {
  23676. AURenderCallbackStruct info;
  23677. zerostruct (info);
  23678. info.inputProcRefCon = this;
  23679. info.inputProc = renderGetInputCallback;
  23680. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  23681. 0, &info, sizeof (info));
  23682. }
  23683. {
  23684. HostCallbackInfo info;
  23685. zerostruct (info);
  23686. info.hostUserData = this;
  23687. info.beatAndTempoProc = getBeatAndTempoCallback;
  23688. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  23689. info.transportStateProc = getTransportStateCallback;
  23690. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  23691. 0, &info, sizeof (info));
  23692. }
  23693. int numIns, numOuts;
  23694. getNumChannels (numIns, numOuts);
  23695. setPlayConfigDetails (numIns, numOuts, 0, 0);
  23696. initialised = AudioUnitInitialize (audioUnit) == noErr;
  23697. setLatencySamples (0);
  23698. }
  23699. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  23700. int samplesPerBlockExpected)
  23701. {
  23702. initialise();
  23703. if (initialised)
  23704. {
  23705. int numIns, numOuts;
  23706. getNumChannels (numIns, numOuts);
  23707. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  23708. Float64 latencySecs = 0.0;
  23709. UInt32 latencySize = sizeof (latencySecs);
  23710. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  23711. 0, &latencySecs, &latencySize);
  23712. setLatencySamples (roundDoubleToInt (latencySecs * sampleRate_));
  23713. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  23714. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  23715. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  23716. AudioStreamBasicDescription stream;
  23717. zerostruct (stream);
  23718. stream.mSampleRate = sampleRate_;
  23719. stream.mFormatID = kAudioFormatLinearPCM;
  23720. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  23721. stream.mFramesPerPacket = 1;
  23722. stream.mBytesPerPacket = 4;
  23723. stream.mBytesPerFrame = 4;
  23724. stream.mBitsPerChannel = 32;
  23725. stream.mChannelsPerFrame = numIns;
  23726. OSStatus err = AudioUnitSetProperty (audioUnit,
  23727. kAudioUnitProperty_StreamFormat,
  23728. kAudioUnitScope_Input,
  23729. 0, &stream, sizeof (stream));
  23730. stream.mChannelsPerFrame = numOuts;
  23731. err = AudioUnitSetProperty (audioUnit,
  23732. kAudioUnitProperty_StreamFormat,
  23733. kAudioUnitScope_Output,
  23734. 0, &stream, sizeof (stream));
  23735. juce_free (outputBufferList);
  23736. outputBufferList = (AudioBufferList*) juce_calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1));
  23737. outputBufferList->mNumberBuffers = numOuts;
  23738. for (int i = numOuts; --i >= 0;)
  23739. outputBufferList->mBuffers[i].mNumberChannels = 1;
  23740. zerostruct (timeStamp);
  23741. timeStamp.mSampleTime = 0;
  23742. timeStamp.mHostTime = AudioGetCurrentHostTime();
  23743. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  23744. currentBuffer = 0;
  23745. wasPlaying = false;
  23746. }
  23747. }
  23748. void AudioUnitPluginInstance::releaseResources()
  23749. {
  23750. if (initialised)
  23751. {
  23752. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  23753. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  23754. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  23755. juce_free (outputBufferList);
  23756. outputBufferList = 0;
  23757. currentBuffer = 0;
  23758. }
  23759. }
  23760. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  23761. const AudioTimeStamp* inTimeStamp,
  23762. UInt32 inBusNumber,
  23763. UInt32 inNumberFrames,
  23764. AudioBufferList* ioData) const
  23765. {
  23766. if (inBusNumber == 0
  23767. && currentBuffer != 0)
  23768. {
  23769. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  23770. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  23771. {
  23772. if (i < currentBuffer->getNumChannels())
  23773. {
  23774. memcpy (ioData->mBuffers[i].mData,
  23775. currentBuffer->getSampleData (i, 0),
  23776. sizeof (float) * inNumberFrames);
  23777. }
  23778. else
  23779. {
  23780. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  23781. }
  23782. }
  23783. }
  23784. return noErr;
  23785. }
  23786. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  23787. MidiBuffer& midiMessages)
  23788. {
  23789. const int numSamples = buffer.getNumSamples();
  23790. if (initialised)
  23791. {
  23792. AudioUnitRenderActionFlags flags = 0;
  23793. timeStamp.mHostTime = AudioGetCurrentHostTime();
  23794. for (int i = getNumOutputChannels(); --i >= 0;)
  23795. {
  23796. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  23797. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  23798. }
  23799. currentBuffer = &buffer;
  23800. if (wantsMidiMessages)
  23801. {
  23802. const uint8* midiEventData;
  23803. int midiEventSize, midiEventPosition;
  23804. MidiBuffer::Iterator i (midiMessages);
  23805. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  23806. {
  23807. if (midiEventSize <= 3)
  23808. MusicDeviceMIDIEvent (audioUnit,
  23809. midiEventData[0], midiEventData[1], midiEventData[2],
  23810. midiEventPosition);
  23811. else
  23812. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  23813. }
  23814. midiMessages.clear();
  23815. }
  23816. AudioUnitRender (audioUnit, &flags, &timeStamp,
  23817. 0, numSamples, outputBufferList);
  23818. timeStamp.mSampleTime += numSamples;
  23819. }
  23820. else
  23821. {
  23822. // Not initialised, so just bypass..
  23823. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  23824. buffer.clear (i, 0, buffer.getNumSamples());
  23825. }
  23826. }
  23827. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  23828. {
  23829. AudioPlayHead* const ph = getPlayHead();
  23830. AudioPlayHead::CurrentPositionInfo result;
  23831. if (ph != 0 && ph->getCurrentPosition (result))
  23832. {
  23833. if (outCurrentBeat != 0)
  23834. *outCurrentBeat = result.ppqPosition;
  23835. if (outCurrentTempo != 0)
  23836. *outCurrentTempo = result.bpm;
  23837. }
  23838. else
  23839. {
  23840. if (outCurrentBeat != 0)
  23841. *outCurrentBeat = 0;
  23842. if (outCurrentTempo != 0)
  23843. *outCurrentTempo = 120.0;
  23844. }
  23845. return noErr;
  23846. }
  23847. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  23848. Float32* outTimeSig_Numerator,
  23849. UInt32* outTimeSig_Denominator,
  23850. Float64* outCurrentMeasureDownBeat) const
  23851. {
  23852. AudioPlayHead* const ph = getPlayHead();
  23853. AudioPlayHead::CurrentPositionInfo result;
  23854. if (ph != 0 && ph->getCurrentPosition (result))
  23855. {
  23856. if (outTimeSig_Numerator != 0)
  23857. *outTimeSig_Numerator = result.timeSigNumerator;
  23858. if (outTimeSig_Denominator != 0)
  23859. *outTimeSig_Denominator = result.timeSigDenominator;
  23860. if (outDeltaSampleOffsetToNextBeat != 0)
  23861. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  23862. if (outCurrentMeasureDownBeat != 0)
  23863. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  23864. }
  23865. else
  23866. {
  23867. if (outDeltaSampleOffsetToNextBeat != 0)
  23868. *outDeltaSampleOffsetToNextBeat = 0;
  23869. if (outTimeSig_Numerator != 0)
  23870. *outTimeSig_Numerator = 4;
  23871. if (outTimeSig_Denominator != 0)
  23872. *outTimeSig_Denominator = 4;
  23873. if (outCurrentMeasureDownBeat != 0)
  23874. *outCurrentMeasureDownBeat = 0;
  23875. }
  23876. return noErr;
  23877. }
  23878. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  23879. Boolean* outTransportStateChanged,
  23880. Float64* outCurrentSampleInTimeLine,
  23881. Boolean* outIsCycling,
  23882. Float64* outCycleStartBeat,
  23883. Float64* outCycleEndBeat)
  23884. {
  23885. AudioPlayHead* const ph = getPlayHead();
  23886. AudioPlayHead::CurrentPositionInfo result;
  23887. if (ph != 0 && ph->getCurrentPosition (result))
  23888. {
  23889. if (outIsPlaying != 0)
  23890. *outIsPlaying = result.isPlaying;
  23891. if (outTransportStateChanged != 0)
  23892. {
  23893. *outTransportStateChanged = result.isPlaying != wasPlaying;
  23894. wasPlaying = result.isPlaying;
  23895. }
  23896. if (outCurrentSampleInTimeLine != 0)
  23897. *outCurrentSampleInTimeLine = roundDoubleToInt (result.timeInSeconds * getSampleRate());
  23898. if (outIsCycling != 0)
  23899. *outIsCycling = false;
  23900. if (outCycleStartBeat != 0)
  23901. *outCycleStartBeat = 0;
  23902. if (outCycleEndBeat != 0)
  23903. *outCycleEndBeat = 0;
  23904. }
  23905. else
  23906. {
  23907. if (outIsPlaying != 0)
  23908. *outIsPlaying = false;
  23909. if (outTransportStateChanged != 0)
  23910. *outTransportStateChanged = false;
  23911. if (outCurrentSampleInTimeLine != 0)
  23912. *outCurrentSampleInTimeLine = 0;
  23913. if (outIsCycling != 0)
  23914. *outIsCycling = false;
  23915. if (outCycleStartBeat != 0)
  23916. *outCycleStartBeat = 0;
  23917. if (outCycleEndBeat != 0)
  23918. *outCycleEndBeat = 0;
  23919. }
  23920. return noErr;
  23921. }
  23922. static VoidArray activeWindows;
  23923. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  23924. {
  23925. public:
  23926. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  23927. : AudioProcessorEditor (&plugin_),
  23928. plugin (plugin_),
  23929. wrapper (0)
  23930. {
  23931. addAndMakeVisible (wrapper = new NSViewComponent());
  23932. activeWindows.add (this);
  23933. setOpaque (true);
  23934. setVisible (true);
  23935. setSize (100, 100);
  23936. createView (createGenericViewIfNeeded);
  23937. }
  23938. ~AudioUnitPluginWindowCocoa()
  23939. {
  23940. const bool wasValid = isValid();
  23941. wrapper->setView (0);
  23942. activeWindows.removeValue (this);
  23943. if (wasValid)
  23944. plugin.editorBeingDeleted (this);
  23945. delete wrapper;
  23946. }
  23947. bool isValid() const { return wrapper->getView() != 0; }
  23948. void paint (Graphics& g)
  23949. {
  23950. g.fillAll (Colours::white);
  23951. }
  23952. void resized()
  23953. {
  23954. wrapper->setSize (getWidth(), getHeight());
  23955. }
  23956. private:
  23957. AudioUnitPluginInstance& plugin;
  23958. NSViewComponent* wrapper;
  23959. bool createView (const bool createGenericViewIfNeeded)
  23960. {
  23961. NSView* pluginView = 0;
  23962. UInt32 dataSize = 0;
  23963. Boolean isWritable = false;
  23964. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  23965. 0, &dataSize, &isWritable) == noErr
  23966. && dataSize != 0
  23967. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  23968. 0, &dataSize, &isWritable) == noErr)
  23969. {
  23970. AudioUnitCocoaViewInfo* info = (AudioUnitCocoaViewInfo*) juce_calloc (dataSize);
  23971. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  23972. 0, info, &dataSize) == noErr)
  23973. {
  23974. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  23975. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  23976. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  23977. Class viewClass = [viewBundle classNamed: viewClassName];
  23978. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  23979. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  23980. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  23981. {
  23982. id factory = [[[viewClass alloc] init] autorelease];
  23983. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  23984. withSize: NSMakeSize (getWidth(), getHeight())];
  23985. }
  23986. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  23987. {
  23988. CFRelease (info->mCocoaAUViewClass[i]);
  23989. CFRelease (info->mCocoaAUViewBundleLocation);
  23990. }
  23991. }
  23992. juce_free (info);
  23993. }
  23994. if (createGenericViewIfNeeded && (pluginView == 0))
  23995. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  23996. wrapper->setView (pluginView);
  23997. if (pluginView != 0)
  23998. setSize ([pluginView frame].size.width,
  23999. [pluginView frame].size.height);
  24000. return pluginView != 0;
  24001. }
  24002. };
  24003. #if JUCE_SUPPORT_CARBON
  24004. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24005. {
  24006. public:
  24007. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24008. : AudioProcessorEditor (&plugin_),
  24009. plugin (plugin_),
  24010. viewComponent (0)
  24011. {
  24012. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24013. activeWindows.add (this);
  24014. setOpaque (true);
  24015. setVisible (true);
  24016. setSize (400, 300);
  24017. ComponentDescription viewList [16];
  24018. UInt32 viewListSize = sizeof (viewList);
  24019. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24020. 0, &viewList, &viewListSize);
  24021. componentRecord = FindNextComponent (0, &viewList[0]);
  24022. }
  24023. ~AudioUnitPluginWindowCarbon()
  24024. {
  24025. deleteAndZero (innerWrapper);
  24026. activeWindows.removeValue (this);
  24027. if (isValid())
  24028. plugin.editorBeingDeleted (this);
  24029. }
  24030. bool isValid() const throw() { return componentRecord != 0; }
  24031. void paint (Graphics& g)
  24032. {
  24033. g.fillAll (Colours::black);
  24034. }
  24035. void resized()
  24036. {
  24037. innerWrapper->setSize (getWidth(), getHeight());
  24038. }
  24039. bool keyStateChanged (const bool)
  24040. {
  24041. return false;
  24042. }
  24043. bool keyPressed (const KeyPress&)
  24044. {
  24045. return false;
  24046. }
  24047. void broughtToFront()
  24048. {
  24049. activeWindows.removeValue (this);
  24050. activeWindows.add (this);
  24051. }
  24052. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24053. AudioUnitCarbonView getViewComponent()
  24054. {
  24055. if (viewComponent == 0 && componentRecord != 0)
  24056. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24057. return viewComponent;
  24058. }
  24059. void closeViewComponent()
  24060. {
  24061. if (viewComponent != 0)
  24062. {
  24063. CloseComponent (viewComponent);
  24064. viewComponent = 0;
  24065. }
  24066. }
  24067. juce_UseDebuggingNewOperator
  24068. private:
  24069. AudioUnitPluginInstance& plugin;
  24070. ComponentRecord* componentRecord;
  24071. AudioUnitCarbonView viewComponent;
  24072. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24073. {
  24074. public:
  24075. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24076. : owner (owner_)
  24077. {
  24078. }
  24079. ~InnerWrapperComponent()
  24080. {
  24081. deleteWindow();
  24082. }
  24083. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24084. {
  24085. log (T("Opening AU GUI: ") + owner->plugin.getName());
  24086. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24087. if (viewComponent == 0)
  24088. return 0;
  24089. Float32Point pos = { 0, 0 };
  24090. Float32Point size = { 250, 200 };
  24091. HIViewRef pluginView = 0;
  24092. AudioUnitCarbonViewCreate (viewComponent,
  24093. owner->getAudioUnit(),
  24094. windowRef,
  24095. rootView,
  24096. &pos,
  24097. &size,
  24098. (ControlRef*) &pluginView);
  24099. return pluginView;
  24100. }
  24101. void removeView (HIViewRef)
  24102. {
  24103. log (T("Closing AU GUI: ") + owner->plugin.getName());
  24104. owner->closeViewComponent();
  24105. }
  24106. private:
  24107. AudioUnitPluginWindowCarbon* const owner;
  24108. };
  24109. friend class InnerWrapperComponent;
  24110. InnerWrapperComponent* innerWrapper;
  24111. };
  24112. #endif
  24113. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24114. {
  24115. AudioProcessorEditor* w = new AudioUnitPluginWindowCocoa (*this, false);
  24116. if (! ((AudioUnitPluginWindowCocoa*) w)->isValid())
  24117. deleteAndZero (w);
  24118. #if JUCE_SUPPORT_CARBON
  24119. if (w == 0)
  24120. {
  24121. w = new AudioUnitPluginWindowCarbon (*this);
  24122. if (! ((AudioUnitPluginWindowCarbon*) w)->isValid())
  24123. deleteAndZero (w);
  24124. }
  24125. #endif
  24126. if (w == 0)
  24127. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24128. return w;
  24129. }
  24130. const String AudioUnitPluginInstance::getCategory() const
  24131. {
  24132. const char* result = 0;
  24133. switch (componentDesc.componentType)
  24134. {
  24135. case kAudioUnitType_Effect:
  24136. case kAudioUnitType_MusicEffect:
  24137. result = "Effect";
  24138. break;
  24139. case kAudioUnitType_MusicDevice:
  24140. result = "Synth";
  24141. break;
  24142. case kAudioUnitType_Generator:
  24143. result = "Generator";
  24144. break;
  24145. case kAudioUnitType_Panner:
  24146. result = "Panner";
  24147. break;
  24148. default:
  24149. break;
  24150. }
  24151. return result;
  24152. }
  24153. int AudioUnitPluginInstance::getNumParameters()
  24154. {
  24155. return parameterIds.size();
  24156. }
  24157. float AudioUnitPluginInstance::getParameter (int index)
  24158. {
  24159. const ScopedLock sl (lock);
  24160. Float32 value = 0.0f;
  24161. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24162. {
  24163. AudioUnitGetParameter (audioUnit,
  24164. (UInt32) parameterIds.getUnchecked (index),
  24165. kAudioUnitScope_Global, 0,
  24166. &value);
  24167. }
  24168. return value;
  24169. }
  24170. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  24171. {
  24172. const ScopedLock sl (lock);
  24173. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24174. {
  24175. AudioUnitSetParameter (audioUnit,
  24176. (UInt32) parameterIds.getUnchecked (index),
  24177. kAudioUnitScope_Global, 0,
  24178. newValue, 0);
  24179. }
  24180. }
  24181. const String AudioUnitPluginInstance::getParameterName (int index)
  24182. {
  24183. AudioUnitParameterInfo info;
  24184. zerostruct (info);
  24185. UInt32 sz = sizeof (info);
  24186. String name;
  24187. if (AudioUnitGetProperty (audioUnit,
  24188. kAudioUnitProperty_ParameterInfo,
  24189. kAudioUnitScope_Global,
  24190. parameterIds [index], &info, &sz) == noErr)
  24191. {
  24192. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  24193. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  24194. else
  24195. name = String (info.name, sizeof (info.name));
  24196. }
  24197. return name;
  24198. }
  24199. const String AudioUnitPluginInstance::getParameterText (int index)
  24200. {
  24201. return String (getParameter (index));
  24202. }
  24203. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  24204. {
  24205. AudioUnitParameterInfo info;
  24206. UInt32 sz = sizeof (info);
  24207. if (AudioUnitGetProperty (audioUnit,
  24208. kAudioUnitProperty_ParameterInfo,
  24209. kAudioUnitScope_Global,
  24210. parameterIds [index], &info, &sz) == noErr)
  24211. {
  24212. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  24213. }
  24214. return true;
  24215. }
  24216. int AudioUnitPluginInstance::getNumPrograms()
  24217. {
  24218. CFArrayRef presets;
  24219. UInt32 sz = sizeof (CFArrayRef);
  24220. int num = 0;
  24221. if (AudioUnitGetProperty (audioUnit,
  24222. kAudioUnitProperty_FactoryPresets,
  24223. kAudioUnitScope_Global,
  24224. 0, &presets, &sz) == noErr)
  24225. {
  24226. num = (int) CFArrayGetCount (presets);
  24227. CFRelease (presets);
  24228. }
  24229. return num;
  24230. }
  24231. int AudioUnitPluginInstance::getCurrentProgram()
  24232. {
  24233. AUPreset current;
  24234. current.presetNumber = 0;
  24235. UInt32 sz = sizeof (AUPreset);
  24236. AudioUnitGetProperty (audioUnit,
  24237. kAudioUnitProperty_FactoryPresets,
  24238. kAudioUnitScope_Global,
  24239. 0, &current, &sz);
  24240. return current.presetNumber;
  24241. }
  24242. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  24243. {
  24244. AUPreset current;
  24245. current.presetNumber = newIndex;
  24246. current.presetName = 0;
  24247. AudioUnitSetProperty (audioUnit,
  24248. kAudioUnitProperty_FactoryPresets,
  24249. kAudioUnitScope_Global,
  24250. 0, &current, sizeof (AUPreset));
  24251. }
  24252. const String AudioUnitPluginInstance::getProgramName (int index)
  24253. {
  24254. String s;
  24255. CFArrayRef presets;
  24256. UInt32 sz = sizeof (CFArrayRef);
  24257. if (AudioUnitGetProperty (audioUnit,
  24258. kAudioUnitProperty_FactoryPresets,
  24259. kAudioUnitScope_Global,
  24260. 0, &presets, &sz) == noErr)
  24261. {
  24262. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  24263. {
  24264. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  24265. if (p != 0 && p->presetNumber == index)
  24266. {
  24267. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  24268. break;
  24269. }
  24270. }
  24271. CFRelease (presets);
  24272. }
  24273. return s;
  24274. }
  24275. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  24276. {
  24277. jassertfalse // xxx not implemented!
  24278. }
  24279. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  24280. {
  24281. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  24282. return T("Input ") + String (index + 1);
  24283. return String::empty;
  24284. }
  24285. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  24286. {
  24287. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  24288. return false;
  24289. return true;
  24290. }
  24291. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  24292. {
  24293. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  24294. return T("Output ") + String (index + 1);
  24295. return String::empty;
  24296. }
  24297. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  24298. {
  24299. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  24300. return false;
  24301. return true;
  24302. }
  24303. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  24304. {
  24305. getCurrentProgramStateInformation (destData);
  24306. }
  24307. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  24308. {
  24309. CFPropertyListRef propertyList = 0;
  24310. UInt32 sz = sizeof (CFPropertyListRef);
  24311. if (AudioUnitGetProperty (audioUnit,
  24312. kAudioUnitProperty_ClassInfo,
  24313. kAudioUnitScope_Global,
  24314. 0, &propertyList, &sz) == noErr)
  24315. {
  24316. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  24317. CFWriteStreamOpen (stream);
  24318. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  24319. CFWriteStreamClose (stream);
  24320. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  24321. destData.setSize (bytesWritten);
  24322. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  24323. CFRelease (data);
  24324. CFRelease (stream);
  24325. CFRelease (propertyList);
  24326. }
  24327. }
  24328. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  24329. {
  24330. setCurrentProgramStateInformation (data, sizeInBytes);
  24331. }
  24332. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24333. {
  24334. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  24335. (const UInt8*) data,
  24336. sizeInBytes,
  24337. kCFAllocatorNull);
  24338. CFReadStreamOpen (stream);
  24339. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  24340. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  24341. stream,
  24342. 0,
  24343. kCFPropertyListImmutable,
  24344. &format,
  24345. 0);
  24346. CFRelease (stream);
  24347. if (propertyList != 0)
  24348. AudioUnitSetProperty (audioUnit,
  24349. kAudioUnitProperty_ClassInfo,
  24350. kAudioUnitScope_Global,
  24351. 0, &propertyList, sizeof (propertyList));
  24352. }
  24353. AudioUnitPluginFormat::AudioUnitPluginFormat()
  24354. {
  24355. }
  24356. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  24357. {
  24358. }
  24359. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  24360. const String& fileOrIdentifier)
  24361. {
  24362. if (! fileMightContainThisPluginType (fileOrIdentifier))
  24363. return;
  24364. PluginDescription desc;
  24365. desc.fileOrIdentifier = fileOrIdentifier;
  24366. desc.uid = 0;
  24367. AudioUnitPluginInstance* instance = dynamic_cast <AudioUnitPluginInstance*> (createInstanceFromDescription (desc));
  24368. if (instance == 0)
  24369. return;
  24370. try
  24371. {
  24372. instance->fillInPluginDescription (desc);
  24373. results.add (new PluginDescription (desc));
  24374. }
  24375. catch (...)
  24376. {
  24377. // crashed while loading...
  24378. }
  24379. deleteAndZero (instance);
  24380. }
  24381. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  24382. {
  24383. AudioUnitPluginInstance* result = 0;
  24384. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  24385. {
  24386. result = new AudioUnitPluginInstance (desc.fileOrIdentifier);
  24387. if (result->audioUnit != 0)
  24388. {
  24389. result->initialise();
  24390. }
  24391. else
  24392. {
  24393. deleteAndZero (result);
  24394. }
  24395. }
  24396. return result;
  24397. }
  24398. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  24399. const bool /*recursive*/)
  24400. {
  24401. StringArray result;
  24402. ComponentRecord* comp = 0;
  24403. ComponentDescription desc;
  24404. zerostruct (desc);
  24405. for (;;)
  24406. {
  24407. zerostruct (desc);
  24408. comp = FindNextComponent (comp, &desc);
  24409. if (comp == 0)
  24410. break;
  24411. GetComponentInfo (comp, &desc, 0, 0, 0);
  24412. if (desc.componentType == kAudioUnitType_MusicDevice
  24413. || desc.componentType == kAudioUnitType_MusicEffect
  24414. || desc.componentType == kAudioUnitType_Effect
  24415. || desc.componentType == kAudioUnitType_Generator
  24416. || desc.componentType == kAudioUnitType_Panner)
  24417. {
  24418. const String s (createAUPluginIdentifier (desc));
  24419. DBG (s);
  24420. result.add (s);
  24421. }
  24422. }
  24423. return result;
  24424. }
  24425. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  24426. {
  24427. ComponentDescription desc;
  24428. String name, version, manufacturer;
  24429. if (getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  24430. return FindNextComponent (0, &desc) != 0;
  24431. const File f (fileOrIdentifier);
  24432. return f.hasFileExtension (T(".component"))
  24433. && f.isDirectory();
  24434. }
  24435. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  24436. {
  24437. ComponentDescription desc;
  24438. String name, version, manufacturer;
  24439. getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  24440. if (name.isEmpty())
  24441. name = fileOrIdentifier;
  24442. return name;
  24443. }
  24444. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  24445. {
  24446. return File (desc.fileOrIdentifier).exists();
  24447. }
  24448. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  24449. {
  24450. return FileSearchPath ("/(Default AudioUnit locations)");
  24451. }
  24452. #endif
  24453. END_JUCE_NAMESPACE
  24454. #undef log
  24455. #endif
  24456. /********* End of inlined file: juce_AudioUnitPluginFormat.mm *********/
  24457. /********* Start of inlined file: juce_VSTPluginFormat.mm *********/
  24458. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  24459. #define JUCE_MAC_VST_INCLUDED 1
  24460. /********* Start of inlined file: juce_VSTPluginFormat.cpp *********/
  24461. #if JUCE_PLUGINHOST_VST
  24462. #if (defined (_WIN32) || defined (_WIN64))
  24463. #undef _WIN32_WINNT
  24464. #define _WIN32_WINNT 0x500
  24465. #undef STRICT
  24466. #define STRICT
  24467. #include <windows.h>
  24468. #include <float.h>
  24469. #pragma warning (disable : 4312 4355)
  24470. #elif defined (LINUX) || defined (__linux__)
  24471. #include <float.h>
  24472. #include <sys/time.h>
  24473. #include <X11/Xlib.h>
  24474. #include <X11/Xutil.h>
  24475. #include <X11/Xatom.h>
  24476. #undef Font
  24477. #undef KeyPress
  24478. #undef Drawable
  24479. #undef Time
  24480. #else
  24481. #ifndef JUCE_MAC_VST_INCLUDED
  24482. // On the mac, this file needs to be compiled indirectly, by using
  24483. // juce_VSTPluginFormat.mm instead - that wraps it as an objective-C file for cocoa
  24484. #error
  24485. #endif
  24486. #include <Cocoa/Cocoa.h>
  24487. #include <Carbon/Carbon.h>
  24488. #endif
  24489. #if ! (JUCE_MAC && JUCE_64BIT)
  24490. BEGIN_JUCE_NAMESPACE
  24491. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24492. #endif
  24493. #undef PRAGMA_ALIGN_SUPPORTED
  24494. #define VST_FORCE_DEPRECATED 0
  24495. #ifdef _MSC_VER
  24496. #pragma warning (push)
  24497. #pragma warning (disable: 4996)
  24498. #endif
  24499. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  24500. your include path if you want to add VST support.
  24501. If you're not interested in VSTs, you can disable them by changing the
  24502. JUCE_PLUGINHOST_VST flag in juce_Config.h
  24503. */
  24504. #include "pluginterfaces/vst2.x/aeffectx.h"
  24505. #ifdef _MSC_VER
  24506. #pragma warning (pop)
  24507. #endif
  24508. #if JUCE_LINUX
  24509. #define Font JUCE_NAMESPACE::Font
  24510. #define KeyPress JUCE_NAMESPACE::KeyPress
  24511. #define Drawable JUCE_NAMESPACE::Drawable
  24512. #define Time JUCE_NAMESPACE::Time
  24513. #endif
  24514. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  24515. #ifdef __aeffect__
  24516. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24517. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24518. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  24519. events to the list.
  24520. This is used by both the VST hosting code and the plugin wrapper.
  24521. */
  24522. class VSTMidiEventList
  24523. {
  24524. public:
  24525. VSTMidiEventList()
  24526. : events (0), numEventsUsed (0), numEventsAllocated (0)
  24527. {
  24528. }
  24529. ~VSTMidiEventList()
  24530. {
  24531. freeEvents();
  24532. }
  24533. void clear()
  24534. {
  24535. numEventsUsed = 0;
  24536. if (events != 0)
  24537. events->numEvents = 0;
  24538. }
  24539. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  24540. {
  24541. ensureSize (numEventsUsed + 1);
  24542. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  24543. events->numEvents = ++numEventsUsed;
  24544. if (numBytes <= 4)
  24545. {
  24546. if (e->type == kVstSysExType)
  24547. {
  24548. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  24549. e->type = kVstMidiType;
  24550. e->byteSize = sizeof (VstMidiEvent);
  24551. e->noteLength = 0;
  24552. e->noteOffset = 0;
  24553. e->detune = 0;
  24554. e->noteOffVelocity = 0;
  24555. }
  24556. e->deltaFrames = frameOffset;
  24557. memcpy (e->midiData, midiData, numBytes);
  24558. }
  24559. else
  24560. {
  24561. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  24562. if (se->type == kVstSysExType)
  24563. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  24564. else
  24565. se->sysexDump = (char*) juce_malloc (numBytes);
  24566. memcpy (se->sysexDump, midiData, numBytes);
  24567. se->type = kVstSysExType;
  24568. se->byteSize = sizeof (VstMidiSysexEvent);
  24569. se->deltaFrames = frameOffset;
  24570. se->flags = 0;
  24571. se->dumpBytes = numBytes;
  24572. se->resvd1 = 0;
  24573. se->resvd2 = 0;
  24574. }
  24575. }
  24576. // Handy method to pull the events out of an event buffer supplied by the host
  24577. // or plugin.
  24578. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  24579. {
  24580. for (int i = 0; i < events->numEvents; ++i)
  24581. {
  24582. const VstEvent* const e = events->events[i];
  24583. if (e != 0)
  24584. {
  24585. if (e->type == kVstMidiType)
  24586. {
  24587. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  24588. 4, e->deltaFrames);
  24589. }
  24590. else if (e->type == kVstSysExType)
  24591. {
  24592. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  24593. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  24594. e->deltaFrames);
  24595. }
  24596. }
  24597. }
  24598. }
  24599. void ensureSize (int numEventsNeeded)
  24600. {
  24601. if (numEventsNeeded > numEventsAllocated)
  24602. {
  24603. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  24604. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  24605. if (events == 0)
  24606. events = (VstEvents*) juce_calloc (size);
  24607. else
  24608. events = (VstEvents*) juce_realloc (events, size);
  24609. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  24610. {
  24611. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  24612. (int) sizeof (VstMidiSysexEvent)));
  24613. e->type = kVstMidiType;
  24614. e->byteSize = sizeof (VstMidiEvent);
  24615. events->events[i] = (VstEvent*) e;
  24616. }
  24617. numEventsAllocated = numEventsNeeded;
  24618. }
  24619. }
  24620. void freeEvents()
  24621. {
  24622. if (events != 0)
  24623. {
  24624. for (int i = numEventsAllocated; --i >= 0;)
  24625. {
  24626. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  24627. if (e->type == kVstSysExType)
  24628. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  24629. juce_free (e);
  24630. }
  24631. juce_free (events);
  24632. events = 0;
  24633. numEventsUsed = 0;
  24634. numEventsAllocated = 0;
  24635. }
  24636. }
  24637. VstEvents* events;
  24638. private:
  24639. int numEventsUsed, numEventsAllocated;
  24640. };
  24641. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24642. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24643. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  24644. #if ! JUCE_WIN32
  24645. #define _fpreset()
  24646. #define _clearfp()
  24647. #endif
  24648. extern void juce_callAnyTimersSynchronously();
  24649. const int fxbVersionNum = 1;
  24650. struct fxProgram
  24651. {
  24652. long chunkMagic; // 'CcnK'
  24653. long byteSize; // of this chunk, excl. magic + byteSize
  24654. long fxMagic; // 'FxCk'
  24655. long version;
  24656. long fxID; // fx unique id
  24657. long fxVersion;
  24658. long numParams;
  24659. char prgName[28];
  24660. float params[1]; // variable no. of parameters
  24661. };
  24662. struct fxSet
  24663. {
  24664. long chunkMagic; // 'CcnK'
  24665. long byteSize; // of this chunk, excl. magic + byteSize
  24666. long fxMagic; // 'FxBk'
  24667. long version;
  24668. long fxID; // fx unique id
  24669. long fxVersion;
  24670. long numPrograms;
  24671. char future[128];
  24672. fxProgram programs[1]; // variable no. of programs
  24673. };
  24674. struct fxChunkSet
  24675. {
  24676. long chunkMagic; // 'CcnK'
  24677. long byteSize; // of this chunk, excl. magic + byteSize
  24678. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  24679. long version;
  24680. long fxID; // fx unique id
  24681. long fxVersion;
  24682. long numPrograms;
  24683. char future[128];
  24684. long chunkSize;
  24685. char chunk[8]; // variable
  24686. };
  24687. struct fxProgramSet
  24688. {
  24689. long chunkMagic; // 'CcnK'
  24690. long byteSize; // of this chunk, excl. magic + byteSize
  24691. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  24692. long version;
  24693. long fxID; // fx unique id
  24694. long fxVersion;
  24695. long numPrograms;
  24696. char name[28];
  24697. long chunkSize;
  24698. char chunk[8]; // variable
  24699. };
  24700. #ifdef JUCE_LITTLE_ENDIAN
  24701. static long vst_swap (const long x) throw() { return (long) swapByteOrder ((uint32) x); }
  24702. static float vst_swapFloat (const float x) throw()
  24703. {
  24704. union { uint32 asInt; float asFloat; } n;
  24705. n.asFloat = x;
  24706. n.asInt = swapByteOrder (n.asInt);
  24707. return n.asFloat;
  24708. }
  24709. #else
  24710. #define vst_swap(x) (x)
  24711. #define vst_swapFloat(x) (x)
  24712. #endif
  24713. typedef AEffect* (*MainCall) (audioMasterCallback);
  24714. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  24715. static int shellUIDToCreate = 0;
  24716. static int insideVSTCallback = 0;
  24717. class VSTPluginWindow;
  24718. // Change this to disable logging of various VST activities
  24719. #ifndef VST_LOGGING
  24720. #define VST_LOGGING 1
  24721. #endif
  24722. #if VST_LOGGING
  24723. #define log(a) Logger::writeToLog(a);
  24724. #else
  24725. #define log(a)
  24726. #endif
  24727. #if JUCE_MAC && JUCE_PPC
  24728. static void* NewCFMFromMachO (void* const machofp) throw()
  24729. {
  24730. void* result = juce_malloc (8);
  24731. ((void**) result)[0] = machofp;
  24732. ((void**) result)[1] = result;
  24733. return result;
  24734. }
  24735. #endif
  24736. #if JUCE_LINUX
  24737. extern Display* display;
  24738. extern XContext improbableNumber;
  24739. typedef void (*EventProcPtr) (XEvent* ev);
  24740. static bool xErrorTriggered;
  24741. static int temporaryErrorHandler (Display*, XErrorEvent*)
  24742. {
  24743. xErrorTriggered = true;
  24744. return 0;
  24745. }
  24746. static int getPropertyFromXWindow (Window handle, Atom atom)
  24747. {
  24748. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  24749. xErrorTriggered = false;
  24750. int userSize;
  24751. unsigned long bytes, userCount;
  24752. unsigned char* data;
  24753. Atom userType;
  24754. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  24755. &userType, &userSize, &userCount, &bytes, &data);
  24756. XSetErrorHandler (oldErrorHandler);
  24757. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  24758. : 0;
  24759. }
  24760. static Window getChildWindow (Window windowToCheck)
  24761. {
  24762. Window rootWindow, parentWindow;
  24763. Window* childWindows;
  24764. unsigned int numChildren;
  24765. XQueryTree (display,
  24766. windowToCheck,
  24767. &rootWindow,
  24768. &parentWindow,
  24769. &childWindows,
  24770. &numChildren);
  24771. if (numChildren > 0)
  24772. return childWindows [0];
  24773. return 0;
  24774. }
  24775. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  24776. {
  24777. if (e.mods.isLeftButtonDown())
  24778. {
  24779. ev.xbutton.button = Button1;
  24780. ev.xbutton.state |= Button1Mask;
  24781. }
  24782. else if (e.mods.isRightButtonDown())
  24783. {
  24784. ev.xbutton.button = Button3;
  24785. ev.xbutton.state |= Button3Mask;
  24786. }
  24787. else if (e.mods.isMiddleButtonDown())
  24788. {
  24789. ev.xbutton.button = Button2;
  24790. ev.xbutton.state |= Button2Mask;
  24791. }
  24792. }
  24793. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  24794. {
  24795. if (e.mods.isLeftButtonDown())
  24796. ev.xmotion.state |= Button1Mask;
  24797. else if (e.mods.isRightButtonDown())
  24798. ev.xmotion.state |= Button3Mask;
  24799. else if (e.mods.isMiddleButtonDown())
  24800. ev.xmotion.state |= Button2Mask;
  24801. }
  24802. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  24803. {
  24804. if (e.mods.isLeftButtonDown())
  24805. ev.xcrossing.state |= Button1Mask;
  24806. else if (e.mods.isRightButtonDown())
  24807. ev.xcrossing.state |= Button3Mask;
  24808. else if (e.mods.isMiddleButtonDown())
  24809. ev.xcrossing.state |= Button2Mask;
  24810. }
  24811. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  24812. {
  24813. if (increment < 0)
  24814. {
  24815. ev.xbutton.button = Button5;
  24816. ev.xbutton.state |= Button5Mask;
  24817. }
  24818. else if (increment > 0)
  24819. {
  24820. ev.xbutton.button = Button4;
  24821. ev.xbutton.state |= Button4Mask;
  24822. }
  24823. }
  24824. #endif
  24825. static VoidArray activeModules;
  24826. class ModuleHandle : public ReferenceCountedObject
  24827. {
  24828. public:
  24829. File file;
  24830. MainCall moduleMain;
  24831. String pluginName;
  24832. static ModuleHandle* findOrCreateModule (const File& file)
  24833. {
  24834. for (int i = activeModules.size(); --i >= 0;)
  24835. {
  24836. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  24837. if (module->file == file)
  24838. return module;
  24839. }
  24840. _fpreset(); // (doesn't do any harm)
  24841. ++insideVSTCallback;
  24842. shellUIDToCreate = 0;
  24843. log ("Attempting to load VST: " + file.getFullPathName());
  24844. ModuleHandle* m = new ModuleHandle (file);
  24845. if (! m->open())
  24846. deleteAndZero (m);
  24847. --insideVSTCallback;
  24848. _fpreset(); // (doesn't do any harm)
  24849. return m;
  24850. }
  24851. ModuleHandle (const File& file_)
  24852. : file (file_),
  24853. moduleMain (0),
  24854. #if JUCE_WIN32 || JUCE_LINUX
  24855. hModule (0)
  24856. #elif JUCE_MAC
  24857. fragId (0),
  24858. resHandle (0),
  24859. bundleRef (0),
  24860. resFileId (0)
  24861. #endif
  24862. {
  24863. activeModules.add (this);
  24864. #if JUCE_WIN32 || JUCE_LINUX
  24865. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  24866. #elif JUCE_MAC
  24867. FSRef ref;
  24868. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  24869. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  24870. #endif
  24871. }
  24872. ~ModuleHandle()
  24873. {
  24874. activeModules.removeValue (this);
  24875. close();
  24876. }
  24877. juce_UseDebuggingNewOperator
  24878. #if JUCE_WIN32 || JUCE_LINUX
  24879. void* hModule;
  24880. String fullParentDirectoryPathName;
  24881. bool open()
  24882. {
  24883. #if JUCE_WIN32
  24884. static bool timePeriodSet = false;
  24885. if (! timePeriodSet)
  24886. {
  24887. timePeriodSet = true;
  24888. timeBeginPeriod (2);
  24889. }
  24890. #endif
  24891. pluginName = file.getFileNameWithoutExtension();
  24892. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  24893. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  24894. if (moduleMain == 0)
  24895. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  24896. return moduleMain != 0;
  24897. }
  24898. void close()
  24899. {
  24900. _fpreset(); // (doesn't do any harm)
  24901. PlatformUtilities::freeDynamicLibrary (hModule);
  24902. }
  24903. void closeEffect (AEffect* eff)
  24904. {
  24905. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  24906. }
  24907. #else
  24908. CFragConnectionID fragId;
  24909. Handle resHandle;
  24910. CFBundleRef bundleRef;
  24911. FSSpec parentDirFSSpec;
  24912. short resFileId;
  24913. bool open()
  24914. {
  24915. bool ok = false;
  24916. const String filename (file.getFullPathName());
  24917. if (file.hasFileExtension (T(".vst")))
  24918. {
  24919. const char* const utf8 = filename.toUTF8();
  24920. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  24921. strlen (utf8), file.isDirectory());
  24922. if (url != 0)
  24923. {
  24924. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  24925. CFRelease (url);
  24926. if (bundleRef != 0)
  24927. {
  24928. if (CFBundleLoadExecutable (bundleRef))
  24929. {
  24930. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  24931. if (moduleMain == 0)
  24932. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  24933. if (moduleMain != 0)
  24934. {
  24935. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  24936. if (name != 0)
  24937. {
  24938. if (CFGetTypeID (name) == CFStringGetTypeID())
  24939. {
  24940. char buffer[1024];
  24941. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  24942. pluginName = buffer;
  24943. }
  24944. }
  24945. if (pluginName.isEmpty())
  24946. pluginName = file.getFileNameWithoutExtension();
  24947. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  24948. ok = true;
  24949. }
  24950. }
  24951. if (! ok)
  24952. {
  24953. CFBundleUnloadExecutable (bundleRef);
  24954. CFRelease (bundleRef);
  24955. bundleRef = 0;
  24956. }
  24957. }
  24958. }
  24959. }
  24960. #if JUCE_PPC
  24961. else
  24962. {
  24963. FSRef fn;
  24964. if (FSPathMakeRef ((UInt8*) (const char*) filename, &fn, 0) == noErr)
  24965. {
  24966. resFileId = FSOpenResFile (&fn, fsRdPerm);
  24967. if (resFileId != -1)
  24968. {
  24969. const int numEffs = Count1Resources ('aEff');
  24970. for (int i = 0; i < numEffs; ++i)
  24971. {
  24972. resHandle = Get1IndResource ('aEff', i + 1);
  24973. if (resHandle != 0)
  24974. {
  24975. OSType type;
  24976. Str255 name;
  24977. SInt16 id;
  24978. GetResInfo (resHandle, &id, &type, name);
  24979. pluginName = String ((const char*) name + 1, name[0]);
  24980. DetachResource (resHandle);
  24981. HLock (resHandle);
  24982. Ptr ptr;
  24983. Str255 errorText;
  24984. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  24985. name, kPrivateCFragCopy,
  24986. &fragId, &ptr, errorText);
  24987. if (err == noErr)
  24988. {
  24989. moduleMain = (MainCall) newMachOFromCFM (ptr);
  24990. ok = true;
  24991. }
  24992. else
  24993. {
  24994. HUnlock (resHandle);
  24995. }
  24996. break;
  24997. }
  24998. }
  24999. if (! ok)
  25000. CloseResFile (resFileId);
  25001. }
  25002. }
  25003. }
  25004. #endif
  25005. return ok;
  25006. }
  25007. void close()
  25008. {
  25009. #if JUCE_PPC
  25010. if (fragId != 0)
  25011. {
  25012. if (moduleMain != 0)
  25013. disposeMachOFromCFM ((void*) moduleMain);
  25014. CloseConnection (&fragId);
  25015. HUnlock (resHandle);
  25016. if (resFileId != 0)
  25017. CloseResFile (resFileId);
  25018. }
  25019. else
  25020. #endif
  25021. if (bundleRef != 0)
  25022. {
  25023. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25024. if (CFGetRetainCount (bundleRef) == 1)
  25025. CFBundleUnloadExecutable (bundleRef);
  25026. if (CFGetRetainCount (bundleRef) > 0)
  25027. CFRelease (bundleRef);
  25028. }
  25029. }
  25030. void closeEffect (AEffect* eff)
  25031. {
  25032. #if JUCE_PPC
  25033. if (fragId != 0)
  25034. {
  25035. VoidArray thingsToDelete;
  25036. thingsToDelete.add ((void*) eff->dispatcher);
  25037. thingsToDelete.add ((void*) eff->process);
  25038. thingsToDelete.add ((void*) eff->setParameter);
  25039. thingsToDelete.add ((void*) eff->getParameter);
  25040. thingsToDelete.add ((void*) eff->processReplacing);
  25041. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25042. for (int i = thingsToDelete.size(); --i >= 0;)
  25043. disposeMachOFromCFM (thingsToDelete[i]);
  25044. }
  25045. else
  25046. #endif
  25047. {
  25048. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25049. }
  25050. }
  25051. #if JUCE_PPC
  25052. static void* newMachOFromCFM (void* cfmfp)
  25053. {
  25054. if (cfmfp == 0)
  25055. return 0;
  25056. UInt32* const mfp = (UInt32*) juce_malloc (sizeof (UInt32) * 6);
  25057. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25058. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25059. mfp[2] = 0x800c0000;
  25060. mfp[3] = 0x804c0004;
  25061. mfp[4] = 0x7c0903a6;
  25062. mfp[5] = 0x4e800420;
  25063. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25064. return mfp;
  25065. }
  25066. static void disposeMachOFromCFM (void* ptr)
  25067. {
  25068. juce_free (ptr);
  25069. }
  25070. void coerceAEffectFunctionCalls (AEffect* eff)
  25071. {
  25072. if (fragId != 0)
  25073. {
  25074. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25075. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25076. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25077. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25078. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25079. }
  25080. }
  25081. #endif
  25082. #endif
  25083. };
  25084. /**
  25085. An instance of a plugin, created by a VSTPluginFormat.
  25086. */
  25087. class VSTPluginInstance : public AudioPluginInstance,
  25088. private Timer,
  25089. private AsyncUpdater
  25090. {
  25091. public:
  25092. ~VSTPluginInstance();
  25093. // AudioPluginInstance methods:
  25094. void fillInPluginDescription (PluginDescription& desc) const
  25095. {
  25096. desc.name = name;
  25097. desc.fileOrIdentifier = module->file.getFullPathName();
  25098. desc.uid = getUID();
  25099. desc.lastFileModTime = module->file.getLastModificationTime();
  25100. desc.pluginFormatName = "VST";
  25101. desc.category = getCategory();
  25102. {
  25103. char buffer [kVstMaxVendorStrLen + 8];
  25104. zerostruct (buffer);
  25105. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25106. desc.manufacturerName = buffer;
  25107. }
  25108. desc.version = getVersion();
  25109. desc.numInputChannels = getNumInputChannels();
  25110. desc.numOutputChannels = getNumOutputChannels();
  25111. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25112. }
  25113. const String getName() const { return name; }
  25114. int getUID() const throw();
  25115. bool acceptsMidi() const { return wantsMidiMessages; }
  25116. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25117. // AudioProcessor methods:
  25118. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25119. void releaseResources();
  25120. void processBlock (AudioSampleBuffer& buffer,
  25121. MidiBuffer& midiMessages);
  25122. AudioProcessorEditor* createEditor();
  25123. const String getInputChannelName (const int index) const;
  25124. bool isInputChannelStereoPair (int index) const;
  25125. const String getOutputChannelName (const int index) const;
  25126. bool isOutputChannelStereoPair (int index) const;
  25127. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25128. float getParameter (int index);
  25129. void setParameter (int index, float newValue);
  25130. const String getParameterName (int index);
  25131. const String getParameterText (int index);
  25132. bool isParameterAutomatable (int index) const;
  25133. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25134. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25135. void setCurrentProgram (int index);
  25136. const String getProgramName (int index);
  25137. void changeProgramName (int index, const String& newName);
  25138. void getStateInformation (MemoryBlock& destData);
  25139. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25140. void setStateInformation (const void* data, int sizeInBytes);
  25141. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25142. void timerCallback();
  25143. void handleAsyncUpdate();
  25144. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  25145. juce_UseDebuggingNewOperator
  25146. private:
  25147. friend class VSTPluginWindow;
  25148. friend class VSTPluginFormat;
  25149. AEffect* effect;
  25150. String name;
  25151. CriticalSection lock;
  25152. bool wantsMidiMessages, initialised, isPowerOn;
  25153. mutable StringArray programNames;
  25154. AudioSampleBuffer tempBuffer;
  25155. CriticalSection midiInLock;
  25156. MidiBuffer incomingMidi;
  25157. VSTMidiEventList midiEventsToSend;
  25158. VstTimeInfo vstHostTime;
  25159. float** channels;
  25160. ReferenceCountedObjectPtr <ModuleHandle> module;
  25161. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  25162. bool restoreProgramSettings (const fxProgram* const prog);
  25163. const String getCurrentProgramName();
  25164. void setParamsInProgramBlock (fxProgram* const prog) throw();
  25165. void updateStoredProgramNames();
  25166. void initialise();
  25167. void handleMidiFromPlugin (const VstEvents* const events);
  25168. void createTempParameterStore (MemoryBlock& dest);
  25169. void restoreFromTempParameterStore (const MemoryBlock& mb);
  25170. const String getParameterLabel (int index) const;
  25171. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  25172. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  25173. void setChunkData (const char* data, int size, bool isPreset);
  25174. bool loadFromFXBFile (const void* data, int numBytes);
  25175. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  25176. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  25177. const String getVersion() const throw();
  25178. const String getCategory() const throw();
  25179. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  25180. void setPower (const bool on);
  25181. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  25182. };
  25183. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  25184. : effect (0),
  25185. wantsMidiMessages (false),
  25186. initialised (false),
  25187. isPowerOn (false),
  25188. tempBuffer (1, 1),
  25189. channels (0),
  25190. module (module_)
  25191. {
  25192. try
  25193. {
  25194. _fpreset();
  25195. ++insideVSTCallback;
  25196. name = module->pluginName;
  25197. log (T("Creating VST instance: ") + name);
  25198. #if JUCE_MAC
  25199. if (module->resFileId != 0)
  25200. UseResFile (module->resFileId);
  25201. #if JUCE_PPC
  25202. if (module->fragId != 0)
  25203. {
  25204. static void* audioMasterCoerced = 0;
  25205. if (audioMasterCoerced == 0)
  25206. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  25207. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  25208. }
  25209. else
  25210. #endif
  25211. #endif
  25212. {
  25213. effect = module->moduleMain (&audioMaster);
  25214. }
  25215. --insideVSTCallback;
  25216. if (effect != 0 && effect->magic == kEffectMagic)
  25217. {
  25218. #if JUCE_PPC
  25219. module->coerceAEffectFunctionCalls (effect);
  25220. #endif
  25221. jassert (effect->resvd2 == 0);
  25222. jassert (effect->object != 0);
  25223. _fpreset(); // some dodgy plugs fuck around with this
  25224. }
  25225. else
  25226. {
  25227. effect = 0;
  25228. }
  25229. }
  25230. catch (...)
  25231. {
  25232. --insideVSTCallback;
  25233. }
  25234. }
  25235. VSTPluginInstance::~VSTPluginInstance()
  25236. {
  25237. {
  25238. const ScopedLock sl (lock);
  25239. jassert (insideVSTCallback == 0);
  25240. if (effect != 0 && effect->magic == kEffectMagic)
  25241. {
  25242. try
  25243. {
  25244. #if JUCE_MAC
  25245. if (module->resFileId != 0)
  25246. UseResFile (module->resFileId);
  25247. #endif
  25248. // Must delete any editors before deleting the plugin instance!
  25249. jassert (getActiveEditor() == 0);
  25250. _fpreset(); // some dodgy plugs fuck around with this
  25251. module->closeEffect (effect);
  25252. }
  25253. catch (...)
  25254. {}
  25255. }
  25256. module = 0;
  25257. effect = 0;
  25258. }
  25259. juce_free (channels);
  25260. channels = 0;
  25261. }
  25262. void VSTPluginInstance::initialise()
  25263. {
  25264. if (initialised || effect == 0)
  25265. return;
  25266. log (T("Initialising VST: ") + module->pluginName);
  25267. initialised = true;
  25268. dispatch (effIdentify, 0, 0, 0, 0);
  25269. // this code would ask the plugin for its name, but so few plugins
  25270. // actually bother implementing this correctly, that it's better to
  25271. // just ignore it and use the file name instead.
  25272. /* {
  25273. char buffer [256];
  25274. zerostruct (buffer);
  25275. dispatch (effGetEffectName, 0, 0, buffer, 0);
  25276. name = String (buffer).trim();
  25277. if (name.isEmpty())
  25278. name = module->pluginName;
  25279. }
  25280. */
  25281. if (getSampleRate() > 0)
  25282. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  25283. if (getBlockSize() > 0)
  25284. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  25285. dispatch (effOpen, 0, 0, 0, 0);
  25286. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  25287. getSampleRate(), getBlockSize());
  25288. if (getNumPrograms() > 1)
  25289. setCurrentProgram (0);
  25290. else
  25291. dispatch (effSetProgram, 0, 0, 0, 0);
  25292. int i;
  25293. for (i = effect->numInputs; --i >= 0;)
  25294. dispatch (effConnectInput, i, 1, 0, 0);
  25295. for (i = effect->numOutputs; --i >= 0;)
  25296. dispatch (effConnectOutput, i, 1, 0, 0);
  25297. updateStoredProgramNames();
  25298. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  25299. setLatencySamples (effect->initialDelay);
  25300. }
  25301. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  25302. int samplesPerBlockExpected)
  25303. {
  25304. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  25305. sampleRate_, samplesPerBlockExpected);
  25306. setLatencySamples (effect->initialDelay);
  25307. juce_free (channels);
  25308. channels = (float**) juce_calloc (sizeof (float*) * jmax (16, getNumOutputChannels() + 2, getNumInputChannels() + 2));
  25309. vstHostTime.tempo = 120.0;
  25310. vstHostTime.timeSigNumerator = 4;
  25311. vstHostTime.timeSigDenominator = 4;
  25312. vstHostTime.sampleRate = sampleRate_;
  25313. vstHostTime.samplePos = 0;
  25314. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  25315. initialise();
  25316. if (initialised)
  25317. {
  25318. wantsMidiMessages = wantsMidiMessages
  25319. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  25320. if (wantsMidiMessages)
  25321. midiEventsToSend.ensureSize (256);
  25322. else
  25323. midiEventsToSend.freeEvents();
  25324. incomingMidi.clear();
  25325. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  25326. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  25327. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  25328. if (! isPowerOn)
  25329. setPower (true);
  25330. // dodgy hack to force some plugins to initialise the sample rate..
  25331. if ((! hasEditor()) && getNumParameters() > 0)
  25332. {
  25333. const float old = getParameter (0);
  25334. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  25335. setParameter (0, old);
  25336. }
  25337. dispatch (effStartProcess, 0, 0, 0, 0);
  25338. }
  25339. }
  25340. void VSTPluginInstance::releaseResources()
  25341. {
  25342. if (initialised)
  25343. {
  25344. dispatch (effStopProcess, 0, 0, 0, 0);
  25345. setPower (false);
  25346. }
  25347. tempBuffer.setSize (1, 1);
  25348. incomingMidi.clear();
  25349. midiEventsToSend.freeEvents();
  25350. juce_free (channels);
  25351. channels = 0;
  25352. }
  25353. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25354. MidiBuffer& midiMessages)
  25355. {
  25356. const int numSamples = buffer.getNumSamples();
  25357. if (initialised)
  25358. {
  25359. AudioPlayHead* playHead = getPlayHead();
  25360. if (playHead != 0)
  25361. {
  25362. AudioPlayHead::CurrentPositionInfo position;
  25363. playHead->getCurrentPosition (position);
  25364. vstHostTime.tempo = position.bpm;
  25365. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  25366. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  25367. vstHostTime.ppqPos = position.ppqPosition;
  25368. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  25369. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  25370. if (position.isPlaying)
  25371. vstHostTime.flags |= kVstTransportPlaying;
  25372. else
  25373. vstHostTime.flags &= ~kVstTransportPlaying;
  25374. }
  25375. #if JUCE_WIN32
  25376. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  25377. #elif JUCE_LINUX
  25378. timeval micro;
  25379. gettimeofday (&micro, 0);
  25380. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  25381. #elif JUCE_MAC
  25382. UnsignedWide micro;
  25383. Microseconds (&micro);
  25384. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  25385. #endif
  25386. if (wantsMidiMessages)
  25387. {
  25388. midiEventsToSend.clear();
  25389. midiEventsToSend.ensureSize (1);
  25390. MidiBuffer::Iterator iter (midiMessages);
  25391. const uint8* midiData;
  25392. int numBytesOfMidiData, samplePosition;
  25393. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  25394. {
  25395. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  25396. jlimit (0, numSamples - 1, samplePosition));
  25397. }
  25398. try
  25399. {
  25400. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  25401. }
  25402. catch (...)
  25403. {}
  25404. }
  25405. int i;
  25406. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  25407. for (i = 0; i < maxChans; ++i)
  25408. channels[i] = buffer.getSampleData (i);
  25409. channels [maxChans] = 0;
  25410. _clearfp();
  25411. if ((effect->flags & effFlagsCanReplacing) != 0)
  25412. {
  25413. try
  25414. {
  25415. effect->processReplacing (effect, channels, channels, numSamples);
  25416. }
  25417. catch (...)
  25418. {}
  25419. }
  25420. else
  25421. {
  25422. tempBuffer.setSize (effect->numOutputs, numSamples);
  25423. tempBuffer.clear();
  25424. float* outs [64];
  25425. for (i = effect->numOutputs; --i >= 0;)
  25426. outs[i] = tempBuffer.getSampleData (i);
  25427. outs [effect->numOutputs] = 0;
  25428. try
  25429. {
  25430. effect->process (effect, channels, outs, numSamples);
  25431. }
  25432. catch (...)
  25433. {}
  25434. for (i = effect->numOutputs; --i >= 0;)
  25435. buffer.copyFrom (i, 0, outs[i], numSamples);
  25436. }
  25437. }
  25438. else
  25439. {
  25440. // Not initialised, so just bypass..
  25441. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25442. buffer.clear (i, 0, buffer.getNumSamples());
  25443. }
  25444. {
  25445. // copy any incoming midi..
  25446. const ScopedLock sl (midiInLock);
  25447. midiMessages = incomingMidi;
  25448. incomingMidi.clear();
  25449. }
  25450. }
  25451. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  25452. {
  25453. if (events != 0)
  25454. {
  25455. const ScopedLock sl (midiInLock);
  25456. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  25457. }
  25458. }
  25459. static Array <VSTPluginWindow*> activeVSTWindows;
  25460. class VSTPluginWindow : public AudioProcessorEditor,
  25461. #if ! JUCE_MAC
  25462. public ComponentMovementWatcher,
  25463. #endif
  25464. public Timer
  25465. {
  25466. public:
  25467. VSTPluginWindow (VSTPluginInstance& plugin_)
  25468. : AudioProcessorEditor (&plugin_),
  25469. #if ! JUCE_MAC
  25470. ComponentMovementWatcher (this),
  25471. #endif
  25472. plugin (plugin_),
  25473. isOpen (false),
  25474. wasShowing (false),
  25475. pluginRefusesToResize (false),
  25476. pluginWantsKeys (false),
  25477. alreadyInside (false),
  25478. recursiveResize (false)
  25479. {
  25480. #if JUCE_WIN32
  25481. sizeCheckCount = 0;
  25482. pluginHWND = 0;
  25483. #elif JUCE_LINUX
  25484. pluginWindow = None;
  25485. pluginProc = None;
  25486. #else
  25487. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25488. #endif
  25489. activeVSTWindows.add (this);
  25490. setSize (1, 1);
  25491. setOpaque (true);
  25492. setVisible (true);
  25493. }
  25494. ~VSTPluginWindow()
  25495. {
  25496. #if JUCE_MAC
  25497. deleteAndZero (innerWrapper);
  25498. #else
  25499. closePluginWindow();
  25500. #endif
  25501. activeVSTWindows.removeValue (this);
  25502. plugin.editorBeingDeleted (this);
  25503. }
  25504. #if ! JUCE_MAC
  25505. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  25506. {
  25507. if (recursiveResize)
  25508. return;
  25509. Component* const topComp = getTopLevelComponent();
  25510. if (topComp->getPeer() != 0)
  25511. {
  25512. int x = 0, y = 0;
  25513. relativePositionToOtherComponent (topComp, x, y);
  25514. recursiveResize = true;
  25515. #if JUCE_WIN32
  25516. if (pluginHWND != 0)
  25517. MoveWindow (pluginHWND, x, y, getWidth(), getHeight(), TRUE);
  25518. #elif JUCE_LINUX
  25519. if (pluginWindow != 0)
  25520. {
  25521. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  25522. XMoveWindow (display, pluginWindow, x, y);
  25523. XMapRaised (display, pluginWindow);
  25524. }
  25525. #endif
  25526. recursiveResize = false;
  25527. }
  25528. }
  25529. void componentVisibilityChanged (Component&)
  25530. {
  25531. const bool isShowingNow = isShowing();
  25532. if (wasShowing != isShowingNow)
  25533. {
  25534. wasShowing = isShowingNow;
  25535. if (isShowingNow)
  25536. openPluginWindow();
  25537. else
  25538. closePluginWindow();
  25539. }
  25540. componentMovedOrResized (true, true);
  25541. }
  25542. void componentPeerChanged()
  25543. {
  25544. closePluginWindow();
  25545. openPluginWindow();
  25546. }
  25547. #endif
  25548. bool keyStateChanged (const bool)
  25549. {
  25550. return pluginWantsKeys;
  25551. }
  25552. bool keyPressed (const KeyPress&)
  25553. {
  25554. return pluginWantsKeys;
  25555. }
  25556. #if JUCE_MAC
  25557. void paint (Graphics& g)
  25558. {
  25559. g.fillAll (Colours::black);
  25560. }
  25561. #else
  25562. void paint (Graphics& g)
  25563. {
  25564. if (isOpen)
  25565. {
  25566. ComponentPeer* const peer = getPeer();
  25567. if (peer != 0)
  25568. {
  25569. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  25570. getScreenY() - peer->getScreenY(),
  25571. getWidth(), getHeight());
  25572. #if JUCE_LINUX
  25573. if (pluginWindow != 0)
  25574. {
  25575. const Rectangle clip (g.getClipBounds());
  25576. XEvent ev;
  25577. zerostruct (ev);
  25578. ev.xexpose.type = Expose;
  25579. ev.xexpose.display = display;
  25580. ev.xexpose.window = pluginWindow;
  25581. ev.xexpose.x = clip.getX();
  25582. ev.xexpose.y = clip.getY();
  25583. ev.xexpose.width = clip.getWidth();
  25584. ev.xexpose.height = clip.getHeight();
  25585. sendEventToChild (&ev);
  25586. }
  25587. #endif
  25588. }
  25589. }
  25590. else
  25591. {
  25592. g.fillAll (Colours::black);
  25593. }
  25594. }
  25595. #endif
  25596. void timerCallback()
  25597. {
  25598. #if JUCE_WIN32
  25599. if (--sizeCheckCount <= 0)
  25600. {
  25601. sizeCheckCount = 10;
  25602. checkPluginWindowSize();
  25603. }
  25604. #endif
  25605. try
  25606. {
  25607. static bool reentrant = false;
  25608. if (! reentrant)
  25609. {
  25610. reentrant = true;
  25611. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  25612. reentrant = false;
  25613. }
  25614. }
  25615. catch (...)
  25616. {}
  25617. }
  25618. void mouseDown (const MouseEvent& e)
  25619. {
  25620. #if JUCE_LINUX
  25621. if (pluginWindow == 0)
  25622. return;
  25623. toFront (true);
  25624. XEvent ev;
  25625. zerostruct (ev);
  25626. ev.xbutton.display = display;
  25627. ev.xbutton.type = ButtonPress;
  25628. ev.xbutton.window = pluginWindow;
  25629. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  25630. ev.xbutton.time = CurrentTime;
  25631. ev.xbutton.x = e.x;
  25632. ev.xbutton.y = e.y;
  25633. ev.xbutton.x_root = e.getScreenX();
  25634. ev.xbutton.y_root = e.getScreenY();
  25635. translateJuceToXButtonModifiers (e, ev);
  25636. sendEventToChild (&ev);
  25637. #elif JUCE_WIN32
  25638. (void) e;
  25639. toFront (true);
  25640. #endif
  25641. }
  25642. void broughtToFront()
  25643. {
  25644. activeVSTWindows.removeValue (this);
  25645. activeVSTWindows.add (this);
  25646. #if JUCE_MAC
  25647. dispatch (effEditTop, 0, 0, 0, 0);
  25648. #endif
  25649. }
  25650. juce_UseDebuggingNewOperator
  25651. private:
  25652. VSTPluginInstance& plugin;
  25653. bool isOpen, wasShowing, recursiveResize;
  25654. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  25655. #if JUCE_WIN32
  25656. HWND pluginHWND;
  25657. void* originalWndProc;
  25658. int sizeCheckCount;
  25659. #elif JUCE_LINUX
  25660. Window pluginWindow;
  25661. EventProcPtr pluginProc;
  25662. #endif
  25663. #if JUCE_MAC
  25664. void openPluginWindow (WindowRef parentWindow)
  25665. {
  25666. if (isOpen || parentWindow == 0)
  25667. return;
  25668. isOpen = true;
  25669. ERect* rect = 0;
  25670. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25671. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  25672. // do this before and after like in the steinberg example
  25673. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25674. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  25675. // Install keyboard hooks
  25676. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  25677. // double-check it's not too tiny
  25678. int w = 250, h = 150;
  25679. if (rect != 0)
  25680. {
  25681. w = rect->right - rect->left;
  25682. h = rect->bottom - rect->top;
  25683. if (w == 0 || h == 0)
  25684. {
  25685. w = 250;
  25686. h = 150;
  25687. }
  25688. }
  25689. w = jmax (w, 32);
  25690. h = jmax (h, 32);
  25691. setSize (w, h);
  25692. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  25693. repaint();
  25694. }
  25695. #else
  25696. void openPluginWindow()
  25697. {
  25698. if (isOpen || getWindowHandle() == 0)
  25699. return;
  25700. log (T("Opening VST UI: ") + plugin.name);
  25701. isOpen = true;
  25702. ERect* rect = 0;
  25703. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25704. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  25705. // do this before and after like in the steinberg example
  25706. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25707. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  25708. // Install keyboard hooks
  25709. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  25710. #if JUCE_WIN32
  25711. originalWndProc = 0;
  25712. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  25713. if (pluginHWND == 0)
  25714. {
  25715. isOpen = false;
  25716. setSize (300, 150);
  25717. return;
  25718. }
  25719. #pragma warning (push)
  25720. #pragma warning (disable: 4244)
  25721. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  25722. if (! pluginWantsKeys)
  25723. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) vstHookWndProc);
  25724. #pragma warning (pop)
  25725. int w, h;
  25726. RECT r;
  25727. GetWindowRect (pluginHWND, &r);
  25728. w = r.right - r.left;
  25729. h = r.bottom - r.top;
  25730. if (rect != 0)
  25731. {
  25732. const int rw = rect->right - rect->left;
  25733. const int rh = rect->bottom - rect->top;
  25734. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  25735. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  25736. {
  25737. // very dodgy logic to decide which size is right.
  25738. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  25739. {
  25740. SetWindowPos (pluginHWND, 0,
  25741. 0, 0, rw, rh,
  25742. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  25743. GetWindowRect (pluginHWND, &r);
  25744. w = r.right - r.left;
  25745. h = r.bottom - r.top;
  25746. pluginRefusesToResize = (w != rw) || (h != rh);
  25747. w = rw;
  25748. h = rh;
  25749. }
  25750. }
  25751. }
  25752. #elif JUCE_LINUX
  25753. pluginWindow = getChildWindow ((Window) getWindowHandle());
  25754. if (pluginWindow != 0)
  25755. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  25756. XInternAtom (display, "_XEventProc", False));
  25757. int w = 250, h = 150;
  25758. if (rect != 0)
  25759. {
  25760. w = rect->right - rect->left;
  25761. h = rect->bottom - rect->top;
  25762. if (w == 0 || h == 0)
  25763. {
  25764. w = 250;
  25765. h = 150;
  25766. }
  25767. }
  25768. if (pluginWindow != 0)
  25769. XMapRaised (display, pluginWindow);
  25770. #endif
  25771. // double-check it's not too tiny
  25772. w = jmax (w, 32);
  25773. h = jmax (h, 32);
  25774. setSize (w, h);
  25775. #if JUCE_WIN32
  25776. checkPluginWindowSize();
  25777. #endif
  25778. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  25779. repaint();
  25780. }
  25781. #endif
  25782. #if ! JUCE_MAC
  25783. void closePluginWindow()
  25784. {
  25785. if (isOpen)
  25786. {
  25787. log (T("Closing VST UI: ") + plugin.getName());
  25788. isOpen = false;
  25789. dispatch (effEditClose, 0, 0, 0, 0);
  25790. #if JUCE_WIN32
  25791. #pragma warning (push)
  25792. #pragma warning (disable: 4244)
  25793. if (pluginHWND != 0 && IsWindow (pluginHWND))
  25794. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) originalWndProc);
  25795. #pragma warning (pop)
  25796. stopTimer();
  25797. if (pluginHWND != 0 && IsWindow (pluginHWND))
  25798. DestroyWindow (pluginHWND);
  25799. pluginHWND = 0;
  25800. #elif JUCE_LINUX
  25801. stopTimer();
  25802. pluginWindow = 0;
  25803. pluginProc = 0;
  25804. #endif
  25805. }
  25806. }
  25807. #endif
  25808. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  25809. {
  25810. return plugin.dispatch (opcode, index, value, ptr, opt);
  25811. }
  25812. #if JUCE_WIN32
  25813. void checkPluginWindowSize() throw()
  25814. {
  25815. RECT r;
  25816. GetWindowRect (pluginHWND, &r);
  25817. const int w = r.right - r.left;
  25818. const int h = r.bottom - r.top;
  25819. if (isShowing() && w > 0 && h > 0
  25820. && (w != getWidth() || h != getHeight())
  25821. && ! pluginRefusesToResize)
  25822. {
  25823. setSize (w, h);
  25824. sizeCheckCount = 0;
  25825. }
  25826. }
  25827. // hooks to get keyboard events from VST windows..
  25828. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  25829. {
  25830. for (int i = activeVSTWindows.size(); --i >= 0;)
  25831. {
  25832. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  25833. if (w->pluginHWND == hW)
  25834. {
  25835. if (message == WM_CHAR
  25836. || message == WM_KEYDOWN
  25837. || message == WM_SYSKEYDOWN
  25838. || message == WM_KEYUP
  25839. || message == WM_SYSKEYUP
  25840. || message == WM_APPCOMMAND)
  25841. {
  25842. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  25843. message, wParam, lParam);
  25844. }
  25845. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  25846. (HWND) w->pluginHWND,
  25847. message,
  25848. wParam,
  25849. lParam);
  25850. }
  25851. }
  25852. return DefWindowProc (hW, message, wParam, lParam);
  25853. }
  25854. #endif
  25855. #if JUCE_LINUX
  25856. // overload mouse/keyboard events to forward them to the plugin's inner window..
  25857. void sendEventToChild (XEvent* event)
  25858. {
  25859. if (pluginProc != 0)
  25860. {
  25861. // if the plugin publishes an event procedure, pass the event directly..
  25862. pluginProc (event);
  25863. }
  25864. else if (pluginWindow != 0)
  25865. {
  25866. // if the plugin has a window, then send the event to the window so that
  25867. // its message thread will pick it up..
  25868. XSendEvent (display, pluginWindow, False, 0L, event);
  25869. XFlush (display);
  25870. }
  25871. }
  25872. void mouseEnter (const MouseEvent& e)
  25873. {
  25874. if (pluginWindow != 0)
  25875. {
  25876. XEvent ev;
  25877. zerostruct (ev);
  25878. ev.xcrossing.display = display;
  25879. ev.xcrossing.type = EnterNotify;
  25880. ev.xcrossing.window = pluginWindow;
  25881. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  25882. ev.xcrossing.time = CurrentTime;
  25883. ev.xcrossing.x = e.x;
  25884. ev.xcrossing.y = e.y;
  25885. ev.xcrossing.x_root = e.getScreenX();
  25886. ev.xcrossing.y_root = e.getScreenY();
  25887. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  25888. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  25889. translateJuceToXCrossingModifiers (e, ev);
  25890. sendEventToChild (&ev);
  25891. }
  25892. }
  25893. void mouseExit (const MouseEvent& e)
  25894. {
  25895. if (pluginWindow != 0)
  25896. {
  25897. XEvent ev;
  25898. zerostruct (ev);
  25899. ev.xcrossing.display = display;
  25900. ev.xcrossing.type = LeaveNotify;
  25901. ev.xcrossing.window = pluginWindow;
  25902. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  25903. ev.xcrossing.time = CurrentTime;
  25904. ev.xcrossing.x = e.x;
  25905. ev.xcrossing.y = e.y;
  25906. ev.xcrossing.x_root = e.getScreenX();
  25907. ev.xcrossing.y_root = e.getScreenY();
  25908. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  25909. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  25910. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  25911. translateJuceToXCrossingModifiers (e, ev);
  25912. sendEventToChild (&ev);
  25913. }
  25914. }
  25915. void mouseMove (const MouseEvent& e)
  25916. {
  25917. if (pluginWindow != 0)
  25918. {
  25919. XEvent ev;
  25920. zerostruct (ev);
  25921. ev.xmotion.display = display;
  25922. ev.xmotion.type = MotionNotify;
  25923. ev.xmotion.window = pluginWindow;
  25924. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  25925. ev.xmotion.time = CurrentTime;
  25926. ev.xmotion.is_hint = NotifyNormal;
  25927. ev.xmotion.x = e.x;
  25928. ev.xmotion.y = e.y;
  25929. ev.xmotion.x_root = e.getScreenX();
  25930. ev.xmotion.y_root = e.getScreenY();
  25931. sendEventToChild (&ev);
  25932. }
  25933. }
  25934. void mouseDrag (const MouseEvent& e)
  25935. {
  25936. if (pluginWindow != 0)
  25937. {
  25938. XEvent ev;
  25939. zerostruct (ev);
  25940. ev.xmotion.display = display;
  25941. ev.xmotion.type = MotionNotify;
  25942. ev.xmotion.window = pluginWindow;
  25943. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  25944. ev.xmotion.time = CurrentTime;
  25945. ev.xmotion.x = e.x ;
  25946. ev.xmotion.y = e.y;
  25947. ev.xmotion.x_root = e.getScreenX();
  25948. ev.xmotion.y_root = e.getScreenY();
  25949. ev.xmotion.is_hint = NotifyNormal;
  25950. translateJuceToXMotionModifiers (e, ev);
  25951. sendEventToChild (&ev);
  25952. }
  25953. }
  25954. void mouseUp (const MouseEvent& e)
  25955. {
  25956. if (pluginWindow != 0)
  25957. {
  25958. XEvent ev;
  25959. zerostruct (ev);
  25960. ev.xbutton.display = display;
  25961. ev.xbutton.type = ButtonRelease;
  25962. ev.xbutton.window = pluginWindow;
  25963. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  25964. ev.xbutton.time = CurrentTime;
  25965. ev.xbutton.x = e.x;
  25966. ev.xbutton.y = e.y;
  25967. ev.xbutton.x_root = e.getScreenX();
  25968. ev.xbutton.y_root = e.getScreenY();
  25969. translateJuceToXButtonModifiers (e, ev);
  25970. sendEventToChild (&ev);
  25971. }
  25972. }
  25973. void mouseWheelMove (const MouseEvent& e,
  25974. float incrementX,
  25975. float incrementY)
  25976. {
  25977. if (pluginWindow != 0)
  25978. {
  25979. XEvent ev;
  25980. zerostruct (ev);
  25981. ev.xbutton.display = display;
  25982. ev.xbutton.type = ButtonPress;
  25983. ev.xbutton.window = pluginWindow;
  25984. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  25985. ev.xbutton.time = CurrentTime;
  25986. ev.xbutton.x = e.x;
  25987. ev.xbutton.y = e.y;
  25988. ev.xbutton.x_root = e.getScreenX();
  25989. ev.xbutton.y_root = e.getScreenY();
  25990. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  25991. sendEventToChild (&ev);
  25992. // TODO - put a usleep here ?
  25993. ev.xbutton.type = ButtonRelease;
  25994. sendEventToChild (&ev);
  25995. }
  25996. }
  25997. #endif
  25998. #if JUCE_MAC
  25999. #if ! JUCE_SUPPORT_CARBON
  26000. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26001. #endif
  26002. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26003. {
  26004. public:
  26005. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26006. : owner (owner_),
  26007. alreadyInside (false)
  26008. {
  26009. }
  26010. ~InnerWrapperComponent()
  26011. {
  26012. deleteWindow();
  26013. }
  26014. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26015. {
  26016. owner->openPluginWindow (windowRef);
  26017. return 0;
  26018. }
  26019. void removeView (HIViewRef)
  26020. {
  26021. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26022. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26023. }
  26024. bool getEmbeddedViewSize (int& w, int& h)
  26025. {
  26026. ERect* rect = 0;
  26027. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26028. w = rect->right - rect->left;
  26029. h = rect->bottom - rect->top;
  26030. return true;
  26031. }
  26032. void mouseDown (int x, int y)
  26033. {
  26034. if (! alreadyInside)
  26035. {
  26036. alreadyInside = true;
  26037. getTopLevelComponent()->toFront (true);
  26038. owner->dispatch (effEditMouse, x, y, 0, 0);
  26039. alreadyInside = false;
  26040. }
  26041. else
  26042. {
  26043. PostEvent (::mouseDown, 0);
  26044. }
  26045. }
  26046. void paint()
  26047. {
  26048. ComponentPeer* const peer = getPeer();
  26049. if (peer != 0)
  26050. {
  26051. ERect r;
  26052. r.left = getScreenX() - peer->getScreenX();
  26053. r.right = r.left + getWidth();
  26054. r.top = getScreenY() - peer->getScreenY();
  26055. r.bottom = r.top + getHeight();
  26056. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26057. }
  26058. }
  26059. private:
  26060. VSTPluginWindow* const owner;
  26061. bool alreadyInside;
  26062. };
  26063. friend class InnerWrapperComponent;
  26064. InnerWrapperComponent* innerWrapper;
  26065. void resized()
  26066. {
  26067. innerWrapper->setSize (getWidth(), getHeight());
  26068. }
  26069. #endif
  26070. };
  26071. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26072. {
  26073. if (hasEditor())
  26074. return new VSTPluginWindow (*this);
  26075. return 0;
  26076. }
  26077. void VSTPluginInstance::handleAsyncUpdate()
  26078. {
  26079. // indicates that something about the plugin has changed..
  26080. updateHostDisplay();
  26081. }
  26082. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26083. {
  26084. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26085. {
  26086. changeProgramName (getCurrentProgram(), prog->prgName);
  26087. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26088. setParameter (i, vst_swapFloat (prog->params[i]));
  26089. return true;
  26090. }
  26091. return false;
  26092. }
  26093. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26094. const int dataSize)
  26095. {
  26096. if (dataSize < 28)
  26097. return false;
  26098. const fxSet* const set = (const fxSet*) data;
  26099. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26100. || vst_swap (set->version) > fxbVersionNum)
  26101. return false;
  26102. if (vst_swap (set->fxMagic) == 'FxBk')
  26103. {
  26104. // bank of programs
  26105. if (vst_swap (set->numPrograms) >= 0)
  26106. {
  26107. const int oldProg = getCurrentProgram();
  26108. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26109. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26110. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26111. {
  26112. if (i != oldProg)
  26113. {
  26114. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26115. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26116. return false;
  26117. if (vst_swap (set->numPrograms) > 0)
  26118. setCurrentProgram (i);
  26119. if (! restoreProgramSettings (prog))
  26120. return false;
  26121. }
  26122. }
  26123. if (vst_swap (set->numPrograms) > 0)
  26124. setCurrentProgram (oldProg);
  26125. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26126. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26127. return false;
  26128. if (! restoreProgramSettings (prog))
  26129. return false;
  26130. }
  26131. }
  26132. else if (vst_swap (set->fxMagic) == 'FxCk')
  26133. {
  26134. // single program
  26135. const fxProgram* const prog = (const fxProgram*) data;
  26136. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26137. return false;
  26138. changeProgramName (getCurrentProgram(), prog->prgName);
  26139. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26140. setParameter (i, vst_swapFloat (prog->params[i]));
  26141. }
  26142. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26143. {
  26144. // non-preset chunk
  26145. const fxChunkSet* const cset = (const fxChunkSet*) data;
  26146. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  26147. return false;
  26148. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  26149. }
  26150. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  26151. {
  26152. // preset chunk
  26153. const fxProgramSet* const cset = (const fxProgramSet*) data;
  26154. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  26155. return false;
  26156. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  26157. changeProgramName (getCurrentProgram(), cset->name);
  26158. }
  26159. else
  26160. {
  26161. return false;
  26162. }
  26163. return true;
  26164. }
  26165. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  26166. {
  26167. const int numParams = getNumParameters();
  26168. prog->chunkMagic = vst_swap ('CcnK');
  26169. prog->byteSize = 0;
  26170. prog->fxMagic = vst_swap ('FxCk');
  26171. prog->version = vst_swap (fxbVersionNum);
  26172. prog->fxID = vst_swap (getUID());
  26173. prog->fxVersion = vst_swap (getVersionNumber());
  26174. prog->numParams = vst_swap (numParams);
  26175. getCurrentProgramName().copyToBuffer (prog->prgName, sizeof (prog->prgName) - 1);
  26176. for (int i = 0; i < numParams; ++i)
  26177. prog->params[i] = vst_swapFloat (getParameter (i));
  26178. }
  26179. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  26180. {
  26181. const int numPrograms = getNumPrograms();
  26182. const int numParams = getNumParameters();
  26183. if (usesChunks())
  26184. {
  26185. if (isFXB)
  26186. {
  26187. MemoryBlock chunk;
  26188. getChunkData (chunk, false, maxSizeMB);
  26189. const int totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  26190. dest.setSize (totalLen, true);
  26191. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  26192. set->chunkMagic = vst_swap ('CcnK');
  26193. set->byteSize = 0;
  26194. set->fxMagic = vst_swap ('FBCh');
  26195. set->version = vst_swap (fxbVersionNum);
  26196. set->fxID = vst_swap (getUID());
  26197. set->fxVersion = vst_swap (getVersionNumber());
  26198. set->numPrograms = vst_swap (numPrograms);
  26199. set->chunkSize = vst_swap (chunk.getSize());
  26200. chunk.copyTo (set->chunk, 0, chunk.getSize());
  26201. }
  26202. else
  26203. {
  26204. MemoryBlock chunk;
  26205. getChunkData (chunk, true, maxSizeMB);
  26206. const int totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  26207. dest.setSize (totalLen, true);
  26208. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  26209. set->chunkMagic = vst_swap ('CcnK');
  26210. set->byteSize = 0;
  26211. set->fxMagic = vst_swap ('FPCh');
  26212. set->version = vst_swap (fxbVersionNum);
  26213. set->fxID = vst_swap (getUID());
  26214. set->fxVersion = vst_swap (getVersionNumber());
  26215. set->numPrograms = vst_swap (numPrograms);
  26216. set->chunkSize = vst_swap (chunk.getSize());
  26217. getCurrentProgramName().copyToBuffer (set->name, sizeof (set->name) - 1);
  26218. chunk.copyTo (set->chunk, 0, chunk.getSize());
  26219. }
  26220. }
  26221. else
  26222. {
  26223. if (isFXB)
  26224. {
  26225. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26226. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  26227. dest.setSize (len, true);
  26228. fxSet* const set = (fxSet*) dest.getData();
  26229. set->chunkMagic = vst_swap ('CcnK');
  26230. set->byteSize = 0;
  26231. set->fxMagic = vst_swap ('FxBk');
  26232. set->version = vst_swap (fxbVersionNum);
  26233. set->fxID = vst_swap (getUID());
  26234. set->fxVersion = vst_swap (getVersionNumber());
  26235. set->numPrograms = vst_swap (numPrograms);
  26236. const int oldProgram = getCurrentProgram();
  26237. MemoryBlock oldSettings;
  26238. createTempParameterStore (oldSettings);
  26239. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  26240. for (int i = 0; i < numPrograms; ++i)
  26241. {
  26242. if (i != oldProgram)
  26243. {
  26244. setCurrentProgram (i);
  26245. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  26246. }
  26247. }
  26248. setCurrentProgram (oldProgram);
  26249. restoreFromTempParameterStore (oldSettings);
  26250. }
  26251. else
  26252. {
  26253. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26254. dest.setSize (totalLen, true);
  26255. setParamsInProgramBlock ((fxProgram*) dest.getData());
  26256. }
  26257. }
  26258. return true;
  26259. }
  26260. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  26261. {
  26262. if (usesChunks())
  26263. {
  26264. void* data = 0;
  26265. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  26266. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  26267. {
  26268. mb.setSize (bytes);
  26269. mb.copyFrom (data, 0, bytes);
  26270. }
  26271. }
  26272. }
  26273. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  26274. {
  26275. if (size > 0 && usesChunks())
  26276. {
  26277. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  26278. if (! isPreset)
  26279. updateStoredProgramNames();
  26280. }
  26281. }
  26282. void VSTPluginInstance::timerCallback()
  26283. {
  26284. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  26285. stopTimer();
  26286. }
  26287. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  26288. {
  26289. const ScopedLock sl (lock);
  26290. ++insideVSTCallback;
  26291. int result = 0;
  26292. try
  26293. {
  26294. if (effect != 0)
  26295. {
  26296. #if JUCE_MAC
  26297. if (module->resFileId != 0)
  26298. UseResFile (module->resFileId);
  26299. CGrafPtr oldPort;
  26300. if (getActiveEditor() != 0)
  26301. {
  26302. int x = 0, y = 0;
  26303. getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), x, y);
  26304. GetPort (&oldPort);
  26305. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  26306. SetOrigin (-x, -y);
  26307. }
  26308. #endif
  26309. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  26310. #if JUCE_MAC
  26311. if (getActiveEditor() != 0)
  26312. SetPort (oldPort);
  26313. module->resFileId = CurResFile();
  26314. #endif
  26315. --insideVSTCallback;
  26316. return result;
  26317. }
  26318. }
  26319. catch (...)
  26320. {
  26321. //char s[512];
  26322. //sprintf (s, "dispatcher (%d, %d, %d, %x, %f)", opcode, index, value, (int)ptr, opt);
  26323. }
  26324. --insideVSTCallback;
  26325. return result;
  26326. }
  26327. // handles non plugin-specific callbacks..
  26328. static const int defaultVSTSampleRateValue = 16384;
  26329. static const int defaultVSTBlockSizeValue = 512;
  26330. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  26331. {
  26332. (void) index;
  26333. (void) value;
  26334. (void) opt;
  26335. switch (opcode)
  26336. {
  26337. case audioMasterCanDo:
  26338. {
  26339. static const char* canDos[] = { "supplyIdle",
  26340. "sendVstEvents",
  26341. "sendVstMidiEvent",
  26342. "sendVstTimeInfo",
  26343. "receiveVstEvents",
  26344. "receiveVstMidiEvent",
  26345. "supportShell",
  26346. "shellCategory" };
  26347. for (int i = 0; i < numElementsInArray (canDos); ++i)
  26348. if (strcmp (canDos[i], (const char*) ptr) == 0)
  26349. return 1;
  26350. return 0;
  26351. }
  26352. case audioMasterVersion:
  26353. return 0x2400;
  26354. case audioMasterCurrentId:
  26355. return shellUIDToCreate;
  26356. case audioMasterGetNumAutomatableParameters:
  26357. return 0;
  26358. case audioMasterGetAutomationState:
  26359. return 1;
  26360. case audioMasterGetVendorVersion:
  26361. return 0x0101;
  26362. case audioMasterGetVendorString:
  26363. case audioMasterGetProductString:
  26364. {
  26365. String hostName ("Juce VST Host");
  26366. if (JUCEApplication::getInstance() != 0)
  26367. hostName = JUCEApplication::getInstance()->getApplicationName();
  26368. hostName.copyToBuffer ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  26369. }
  26370. break;
  26371. case audioMasterGetSampleRate:
  26372. return (VstIntPtr) defaultVSTSampleRateValue;
  26373. case audioMasterGetBlockSize:
  26374. return (VstIntPtr) defaultVSTBlockSizeValue;
  26375. case audioMasterSetOutputSampleRate:
  26376. return 0;
  26377. default:
  26378. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  26379. break;
  26380. }
  26381. return 0;
  26382. }
  26383. // handles callbacks for a specific plugin
  26384. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  26385. {
  26386. switch (opcode)
  26387. {
  26388. case audioMasterAutomate:
  26389. sendParamChangeMessageToListeners (index, opt);
  26390. break;
  26391. case audioMasterProcessEvents:
  26392. handleMidiFromPlugin ((const VstEvents*) ptr);
  26393. break;
  26394. case audioMasterGetTime:
  26395. #ifdef _MSC_VER
  26396. #pragma warning (push)
  26397. #pragma warning (disable: 4311)
  26398. #endif
  26399. return (VstIntPtr) &vstHostTime;
  26400. #ifdef _MSC_VER
  26401. #pragma warning (pop)
  26402. #endif
  26403. break;
  26404. case audioMasterIdle:
  26405. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  26406. {
  26407. ++insideVSTCallback;
  26408. #if JUCE_MAC
  26409. if (getActiveEditor() != 0)
  26410. dispatch (effEditIdle, 0, 0, 0, 0);
  26411. #endif
  26412. juce_callAnyTimersSynchronously();
  26413. handleUpdateNowIfNeeded();
  26414. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  26415. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  26416. --insideVSTCallback;
  26417. }
  26418. break;
  26419. case audioMasterUpdateDisplay:
  26420. triggerAsyncUpdate();
  26421. break;
  26422. case audioMasterTempoAt:
  26423. // returns (10000 * bpm)
  26424. break;
  26425. case audioMasterNeedIdle:
  26426. startTimer (50);
  26427. break;
  26428. case audioMasterSizeWindow:
  26429. if (getActiveEditor() != 0)
  26430. getActiveEditor()->setSize (index, value);
  26431. return 1;
  26432. case audioMasterGetSampleRate:
  26433. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  26434. case audioMasterGetBlockSize:
  26435. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  26436. case audioMasterWantMidi:
  26437. wantsMidiMessages = true;
  26438. break;
  26439. case audioMasterGetDirectory:
  26440. #if JUCE_MAC
  26441. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  26442. #else
  26443. return (VstIntPtr) (pointer_sized_uint) (const char*) module->fullParentDirectoryPathName;
  26444. #endif
  26445. case audioMasterGetAutomationState:
  26446. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  26447. break;
  26448. // none of these are handled (yet)..
  26449. case audioMasterBeginEdit:
  26450. case audioMasterEndEdit:
  26451. case audioMasterSetTime:
  26452. case audioMasterPinConnected:
  26453. case audioMasterGetParameterQuantization:
  26454. case audioMasterIOChanged:
  26455. case audioMasterGetInputLatency:
  26456. case audioMasterGetOutputLatency:
  26457. case audioMasterGetPreviousPlug:
  26458. case audioMasterGetNextPlug:
  26459. case audioMasterWillReplaceOrAccumulate:
  26460. case audioMasterGetCurrentProcessLevel:
  26461. case audioMasterOfflineStart:
  26462. case audioMasterOfflineRead:
  26463. case audioMasterOfflineWrite:
  26464. case audioMasterOfflineGetCurrentPass:
  26465. case audioMasterOfflineGetCurrentMetaPass:
  26466. case audioMasterVendorSpecific:
  26467. case audioMasterSetIcon:
  26468. case audioMasterGetLanguage:
  26469. case audioMasterOpenWindow:
  26470. case audioMasterCloseWindow:
  26471. break;
  26472. default:
  26473. return handleGeneralCallback (opcode, index, value, ptr, opt);
  26474. }
  26475. return 0;
  26476. }
  26477. // entry point for all callbacks from the plugin
  26478. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  26479. {
  26480. try
  26481. {
  26482. if (effect != 0 && effect->resvd2 != 0)
  26483. {
  26484. return ((VSTPluginInstance*)(effect->resvd2))
  26485. ->handleCallback (opcode, index, value, ptr, opt);
  26486. }
  26487. return handleGeneralCallback (opcode, index, value, ptr, opt);
  26488. }
  26489. catch (...)
  26490. {
  26491. return 0;
  26492. }
  26493. }
  26494. const String VSTPluginInstance::getVersion() const throw()
  26495. {
  26496. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  26497. String s;
  26498. if (v == 0 || v == -1)
  26499. v = getVersionNumber();
  26500. if (v != 0)
  26501. {
  26502. int versionBits[4];
  26503. int n = 0;
  26504. while (v != 0)
  26505. {
  26506. versionBits [n++] = (v & 0xff);
  26507. v >>= 8;
  26508. }
  26509. s << 'V';
  26510. while (n > 0)
  26511. {
  26512. s << versionBits [--n];
  26513. if (n > 0)
  26514. s << '.';
  26515. }
  26516. }
  26517. return s;
  26518. }
  26519. int VSTPluginInstance::getUID() const throw()
  26520. {
  26521. int uid = effect != 0 ? effect->uniqueID : 0;
  26522. if (uid == 0)
  26523. uid = module->file.hashCode();
  26524. return uid;
  26525. }
  26526. const String VSTPluginInstance::getCategory() const throw()
  26527. {
  26528. const char* result = 0;
  26529. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  26530. {
  26531. case kPlugCategEffect:
  26532. result = "Effect";
  26533. break;
  26534. case kPlugCategSynth:
  26535. result = "Synth";
  26536. break;
  26537. case kPlugCategAnalysis:
  26538. result = "Anaylsis";
  26539. break;
  26540. case kPlugCategMastering:
  26541. result = "Mastering";
  26542. break;
  26543. case kPlugCategSpacializer:
  26544. result = "Spacial";
  26545. break;
  26546. case kPlugCategRoomFx:
  26547. result = "Reverb";
  26548. break;
  26549. case kPlugSurroundFx:
  26550. result = "Surround";
  26551. break;
  26552. case kPlugCategRestoration:
  26553. result = "Restoration";
  26554. break;
  26555. case kPlugCategGenerator:
  26556. result = "Tone generation";
  26557. break;
  26558. default:
  26559. break;
  26560. }
  26561. return result;
  26562. }
  26563. float VSTPluginInstance::getParameter (int index)
  26564. {
  26565. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  26566. {
  26567. try
  26568. {
  26569. const ScopedLock sl (lock);
  26570. return effect->getParameter (effect, index);
  26571. }
  26572. catch (...)
  26573. {
  26574. }
  26575. }
  26576. return 0.0f;
  26577. }
  26578. void VSTPluginInstance::setParameter (int index, float newValue)
  26579. {
  26580. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  26581. {
  26582. try
  26583. {
  26584. const ScopedLock sl (lock);
  26585. if (effect->getParameter (effect, index) != newValue)
  26586. effect->setParameter (effect, index, newValue);
  26587. }
  26588. catch (...)
  26589. {
  26590. }
  26591. }
  26592. }
  26593. const String VSTPluginInstance::getParameterName (int index)
  26594. {
  26595. if (effect != 0)
  26596. {
  26597. jassert (index >= 0 && index < effect->numParams);
  26598. char nm [256];
  26599. zerostruct (nm);
  26600. dispatch (effGetParamName, index, 0, nm, 0);
  26601. return String (nm).trim();
  26602. }
  26603. return String::empty;
  26604. }
  26605. const String VSTPluginInstance::getParameterLabel (int index) const
  26606. {
  26607. if (effect != 0)
  26608. {
  26609. jassert (index >= 0 && index < effect->numParams);
  26610. char nm [256];
  26611. zerostruct (nm);
  26612. dispatch (effGetParamLabel, index, 0, nm, 0);
  26613. return String (nm).trim();
  26614. }
  26615. return String::empty;
  26616. }
  26617. const String VSTPluginInstance::getParameterText (int index)
  26618. {
  26619. if (effect != 0)
  26620. {
  26621. jassert (index >= 0 && index < effect->numParams);
  26622. char nm [256];
  26623. zerostruct (nm);
  26624. dispatch (effGetParamDisplay, index, 0, nm, 0);
  26625. return String (nm).trim();
  26626. }
  26627. return String::empty;
  26628. }
  26629. bool VSTPluginInstance::isParameterAutomatable (int index) const
  26630. {
  26631. if (effect != 0)
  26632. {
  26633. jassert (index >= 0 && index < effect->numParams);
  26634. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  26635. }
  26636. return false;
  26637. }
  26638. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  26639. {
  26640. dest.setSize (64 + 4 * getNumParameters());
  26641. dest.fillWith (0);
  26642. getCurrentProgramName().copyToBuffer ((char*) dest.getData(), 63);
  26643. float* const p = (float*) (((char*) dest.getData()) + 64);
  26644. for (int i = 0; i < getNumParameters(); ++i)
  26645. p[i] = getParameter(i);
  26646. }
  26647. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  26648. {
  26649. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  26650. float* p = (float*) (((char*) m.getData()) + 64);
  26651. for (int i = 0; i < getNumParameters(); ++i)
  26652. setParameter (i, p[i]);
  26653. }
  26654. void VSTPluginInstance::setCurrentProgram (int newIndex)
  26655. {
  26656. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  26657. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  26658. }
  26659. const String VSTPluginInstance::getProgramName (int index)
  26660. {
  26661. if (index == getCurrentProgram())
  26662. {
  26663. return getCurrentProgramName();
  26664. }
  26665. else if (effect != 0)
  26666. {
  26667. char nm [256];
  26668. zerostruct (nm);
  26669. if (dispatch (effGetProgramNameIndexed,
  26670. jlimit (0, getNumPrograms(), index),
  26671. -1, nm, 0) != 0)
  26672. {
  26673. return String (nm).trim();
  26674. }
  26675. }
  26676. return programNames [index];
  26677. }
  26678. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  26679. {
  26680. if (index == getCurrentProgram())
  26681. {
  26682. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  26683. dispatch (effSetProgramName, 0, 0, (void*) (const char*) newName.substring (0, 24), 0.0f);
  26684. }
  26685. else
  26686. {
  26687. jassertfalse // xxx not implemented!
  26688. }
  26689. }
  26690. void VSTPluginInstance::updateStoredProgramNames()
  26691. {
  26692. if (effect != 0 && getNumPrograms() > 0)
  26693. {
  26694. char nm [256];
  26695. zerostruct (nm);
  26696. // only do this if the plugin can't use indexed names..
  26697. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  26698. {
  26699. const int oldProgram = getCurrentProgram();
  26700. MemoryBlock oldSettings;
  26701. createTempParameterStore (oldSettings);
  26702. for (int i = 0; i < getNumPrograms(); ++i)
  26703. {
  26704. setCurrentProgram (i);
  26705. getCurrentProgramName(); // (this updates the list)
  26706. }
  26707. setCurrentProgram (oldProgram);
  26708. restoreFromTempParameterStore (oldSettings);
  26709. }
  26710. }
  26711. }
  26712. const String VSTPluginInstance::getCurrentProgramName()
  26713. {
  26714. if (effect != 0)
  26715. {
  26716. char nm [256];
  26717. zerostruct (nm);
  26718. dispatch (effGetProgramName, 0, 0, nm, 0);
  26719. const int index = getCurrentProgram();
  26720. if (programNames[index].isEmpty())
  26721. {
  26722. while (programNames.size() < index)
  26723. programNames.add (String::empty);
  26724. programNames.set (index, String (nm).trim());
  26725. }
  26726. return String (nm).trim();
  26727. }
  26728. return String::empty;
  26729. }
  26730. const String VSTPluginInstance::getInputChannelName (const int index) const
  26731. {
  26732. if (index >= 0 && index < getNumInputChannels())
  26733. {
  26734. VstPinProperties pinProps;
  26735. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  26736. return String (pinProps.label, sizeof (pinProps.label));
  26737. }
  26738. return String::empty;
  26739. }
  26740. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  26741. {
  26742. if (index < 0 || index >= getNumInputChannels())
  26743. return false;
  26744. VstPinProperties pinProps;
  26745. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  26746. return (pinProps.flags & kVstPinIsStereo) != 0;
  26747. return true;
  26748. }
  26749. const String VSTPluginInstance::getOutputChannelName (const int index) const
  26750. {
  26751. if (index >= 0 && index < getNumOutputChannels())
  26752. {
  26753. VstPinProperties pinProps;
  26754. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  26755. return String (pinProps.label, sizeof (pinProps.label));
  26756. }
  26757. return String::empty;
  26758. }
  26759. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  26760. {
  26761. if (index < 0 || index >= getNumOutputChannels())
  26762. return false;
  26763. VstPinProperties pinProps;
  26764. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  26765. return (pinProps.flags & kVstPinIsStereo) != 0;
  26766. return true;
  26767. }
  26768. void VSTPluginInstance::setPower (const bool on)
  26769. {
  26770. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  26771. isPowerOn = on;
  26772. }
  26773. const int defaultMaxSizeMB = 64;
  26774. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  26775. {
  26776. saveToFXBFile (destData, true, defaultMaxSizeMB);
  26777. }
  26778. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26779. {
  26780. saveToFXBFile (destData, false, defaultMaxSizeMB);
  26781. }
  26782. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26783. {
  26784. loadFromFXBFile (data, sizeInBytes);
  26785. }
  26786. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26787. {
  26788. loadFromFXBFile (data, sizeInBytes);
  26789. }
  26790. VSTPluginFormat::VSTPluginFormat()
  26791. {
  26792. }
  26793. VSTPluginFormat::~VSTPluginFormat()
  26794. {
  26795. }
  26796. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26797. const String& fileOrIdentifier)
  26798. {
  26799. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26800. return;
  26801. PluginDescription desc;
  26802. desc.fileOrIdentifier = fileOrIdentifier;
  26803. desc.uid = 0;
  26804. VSTPluginInstance* instance = dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc));
  26805. if (instance == 0)
  26806. return;
  26807. try
  26808. {
  26809. #if JUCE_MAC
  26810. if (instance->module->resFileId != 0)
  26811. UseResFile (instance->module->resFileId);
  26812. #endif
  26813. instance->fillInPluginDescription (desc);
  26814. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  26815. if (category != kPlugCategShell)
  26816. {
  26817. // Normal plugin...
  26818. results.add (new PluginDescription (desc));
  26819. ++insideVSTCallback;
  26820. instance->dispatch (effOpen, 0, 0, 0, 0);
  26821. --insideVSTCallback;
  26822. }
  26823. else
  26824. {
  26825. // It's a shell plugin, so iterate all the subtypes...
  26826. char shellEffectName [64];
  26827. for (;;)
  26828. {
  26829. zerostruct (shellEffectName);
  26830. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  26831. if (uid == 0)
  26832. {
  26833. break;
  26834. }
  26835. else
  26836. {
  26837. desc.uid = uid;
  26838. desc.name = shellEffectName;
  26839. bool alreadyThere = false;
  26840. for (int i = results.size(); --i >= 0;)
  26841. {
  26842. PluginDescription* const d = results.getUnchecked(i);
  26843. if (d->isDuplicateOf (desc))
  26844. {
  26845. alreadyThere = true;
  26846. break;
  26847. }
  26848. }
  26849. if (! alreadyThere)
  26850. results.add (new PluginDescription (desc));
  26851. }
  26852. }
  26853. }
  26854. }
  26855. catch (...)
  26856. {
  26857. // crashed while loading...
  26858. }
  26859. deleteAndZero (instance);
  26860. }
  26861. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26862. {
  26863. VSTPluginInstance* result = 0;
  26864. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26865. {
  26866. File file (desc.fileOrIdentifier);
  26867. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  26868. file.getParentDirectory().setAsCurrentWorkingDirectory();
  26869. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  26870. if (module != 0)
  26871. {
  26872. shellUIDToCreate = desc.uid;
  26873. result = new VSTPluginInstance (module);
  26874. if (result->effect != 0)
  26875. {
  26876. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) result;
  26877. result->initialise();
  26878. }
  26879. else
  26880. {
  26881. deleteAndZero (result);
  26882. }
  26883. }
  26884. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  26885. }
  26886. return result;
  26887. }
  26888. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26889. {
  26890. const File f (fileOrIdentifier);
  26891. #if JUCE_MAC
  26892. if (f.isDirectory() && f.hasFileExtension (T(".vst")))
  26893. return true;
  26894. #if JUCE_PPC
  26895. FSRef fileRef;
  26896. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  26897. {
  26898. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  26899. if (resFileId != -1)
  26900. {
  26901. const int numEffects = Count1Resources ('aEff');
  26902. CloseResFile (resFileId);
  26903. if (numEffects > 0)
  26904. return true;
  26905. }
  26906. }
  26907. #endif
  26908. return false;
  26909. #elif JUCE_WIN32
  26910. return f.existsAsFile()
  26911. && f.hasFileExtension (T(".dll"));
  26912. #elif JUCE_LINUX
  26913. return f.existsAsFile()
  26914. && f.hasFileExtension (T(".so"));
  26915. #endif
  26916. }
  26917. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26918. {
  26919. return fileOrIdentifier;
  26920. }
  26921. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26922. {
  26923. return File (desc.fileOrIdentifier).exists();
  26924. }
  26925. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  26926. {
  26927. StringArray results;
  26928. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  26929. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  26930. return results;
  26931. }
  26932. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  26933. {
  26934. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  26935. // .component or .vst directories.
  26936. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  26937. while (iter.next())
  26938. {
  26939. const File f (iter.getFile());
  26940. bool isPlugin = false;
  26941. if (fileMightContainThisPluginType (f.getFullPathName()))
  26942. {
  26943. isPlugin = true;
  26944. results.add (f.getFullPathName());
  26945. }
  26946. if (recursive && (! isPlugin) && f.isDirectory())
  26947. recursiveFileSearch (results, f, true);
  26948. }
  26949. }
  26950. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  26951. {
  26952. #if JUCE_MAC
  26953. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  26954. #elif JUCE_WIN32
  26955. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  26956. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  26957. #elif JUCE_LINUX
  26958. return FileSearchPath ("/usr/lib/vst");
  26959. #endif
  26960. }
  26961. END_JUCE_NAMESPACE
  26962. #endif
  26963. #undef log
  26964. #endif
  26965. /********* End of inlined file: juce_VSTPluginFormat.cpp *********/
  26966. /********* End of inlined file: juce_VSTPluginFormat.mm *********/
  26967. /********* Start of inlined file: juce_AudioProcessor.cpp *********/
  26968. BEGIN_JUCE_NAMESPACE
  26969. AudioProcessor::AudioProcessor()
  26970. : playHead (0),
  26971. activeEditor (0),
  26972. sampleRate (0),
  26973. blockSize (0),
  26974. numInputChannels (0),
  26975. numOutputChannels (0),
  26976. latencySamples (0),
  26977. suspended (false),
  26978. nonRealtime (false)
  26979. {
  26980. }
  26981. AudioProcessor::~AudioProcessor()
  26982. {
  26983. // ooh, nasty - the editor should have been deleted before the filter
  26984. // that it refers to is deleted..
  26985. jassert (activeEditor == 0);
  26986. #ifdef JUCE_DEBUG
  26987. // This will fail if you've called beginParameterChangeGesture() for one
  26988. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  26989. jassert (changingParams.countNumberOfSetBits() == 0);
  26990. #endif
  26991. }
  26992. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  26993. {
  26994. playHead = newPlayHead;
  26995. }
  26996. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  26997. {
  26998. const ScopedLock sl (listenerLock);
  26999. listeners.addIfNotAlreadyThere (newListener);
  27000. }
  27001. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27002. {
  27003. const ScopedLock sl (listenerLock);
  27004. listeners.removeValue (listenerToRemove);
  27005. }
  27006. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27007. const int numOuts,
  27008. const double sampleRate_,
  27009. const int blockSize_) throw()
  27010. {
  27011. numInputChannels = numIns;
  27012. numOutputChannels = numOuts;
  27013. sampleRate = sampleRate_;
  27014. blockSize = blockSize_;
  27015. }
  27016. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27017. {
  27018. nonRealtime = nonRealtime_;
  27019. }
  27020. void AudioProcessor::setLatencySamples (const int newLatency)
  27021. {
  27022. if (latencySamples != newLatency)
  27023. {
  27024. latencySamples = newLatency;
  27025. updateHostDisplay();
  27026. }
  27027. }
  27028. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27029. const float newValue)
  27030. {
  27031. setParameter (parameterIndex, newValue);
  27032. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27033. }
  27034. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27035. {
  27036. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27037. for (int i = listeners.size(); --i >= 0;)
  27038. {
  27039. listenerLock.enter();
  27040. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27041. listenerLock.exit();
  27042. if (l != 0)
  27043. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27044. }
  27045. }
  27046. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27047. {
  27048. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27049. #ifdef JUCE_DEBUG
  27050. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27051. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27052. jassert (! changingParams [parameterIndex]);
  27053. changingParams.setBit (parameterIndex);
  27054. #endif
  27055. for (int i = listeners.size(); --i >= 0;)
  27056. {
  27057. listenerLock.enter();
  27058. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27059. listenerLock.exit();
  27060. if (l != 0)
  27061. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27062. }
  27063. }
  27064. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27065. {
  27066. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27067. #ifdef JUCE_DEBUG
  27068. // This means you've called endParameterChangeGesture without having previously called
  27069. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27070. // calls matched correctly.
  27071. jassert (changingParams [parameterIndex]);
  27072. changingParams.clearBit (parameterIndex);
  27073. #endif
  27074. for (int i = listeners.size(); --i >= 0;)
  27075. {
  27076. listenerLock.enter();
  27077. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27078. listenerLock.exit();
  27079. if (l != 0)
  27080. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27081. }
  27082. }
  27083. void AudioProcessor::updateHostDisplay()
  27084. {
  27085. for (int i = listeners.size(); --i >= 0;)
  27086. {
  27087. listenerLock.enter();
  27088. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27089. listenerLock.exit();
  27090. if (l != 0)
  27091. l->audioProcessorChanged (this);
  27092. }
  27093. }
  27094. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27095. {
  27096. return true;
  27097. }
  27098. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27099. {
  27100. return false;
  27101. }
  27102. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27103. {
  27104. const ScopedLock sl (callbackLock);
  27105. suspended = shouldBeSuspended;
  27106. }
  27107. void AudioProcessor::reset()
  27108. {
  27109. }
  27110. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27111. {
  27112. const ScopedLock sl (callbackLock);
  27113. jassert (activeEditor == editor);
  27114. if (activeEditor == editor)
  27115. activeEditor = 0;
  27116. }
  27117. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27118. {
  27119. if (activeEditor != 0)
  27120. return activeEditor;
  27121. AudioProcessorEditor* const ed = createEditor();
  27122. if (ed != 0)
  27123. {
  27124. // you must give your editor comp a size before returning it..
  27125. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27126. const ScopedLock sl (callbackLock);
  27127. activeEditor = ed;
  27128. }
  27129. return ed;
  27130. }
  27131. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27132. {
  27133. getStateInformation (destData);
  27134. }
  27135. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27136. {
  27137. setStateInformation (data, sizeInBytes);
  27138. }
  27139. // magic number to identify memory blocks that we've stored as XML
  27140. const uint32 magicXmlNumber = 0x21324356;
  27141. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  27142. JUCE_NAMESPACE::MemoryBlock& destData)
  27143. {
  27144. const String xmlString (xml.createDocument (String::empty, true, false));
  27145. const int stringLength = xmlString.length();
  27146. destData.setSize (stringLength + 10);
  27147. char* const d = (char*) destData.getData();
  27148. *(uint32*) d = swapIfBigEndian ((const uint32) magicXmlNumber);
  27149. *(uint32*) (d + 4) = swapIfBigEndian ((const uint32) stringLength);
  27150. xmlString.copyToBuffer (d + 8, stringLength);
  27151. }
  27152. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  27153. const int sizeInBytes)
  27154. {
  27155. if (sizeInBytes > 8
  27156. && littleEndianInt ((const char*) data) == magicXmlNumber)
  27157. {
  27158. const uint32 stringLength = littleEndianInt (((const char*) data) + 4);
  27159. if (stringLength > 0)
  27160. {
  27161. XmlDocument doc (String (((const char*) data) + 8,
  27162. jmin ((sizeInBytes - 8), stringLength)));
  27163. return doc.getDocumentElement();
  27164. }
  27165. }
  27166. return 0;
  27167. }
  27168. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  27169. {
  27170. }
  27171. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  27172. {
  27173. }
  27174. END_JUCE_NAMESPACE
  27175. /********* End of inlined file: juce_AudioProcessor.cpp *********/
  27176. /********* Start of inlined file: juce_AudioProcessorEditor.cpp *********/
  27177. BEGIN_JUCE_NAMESPACE
  27178. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  27179. : owner (owner_)
  27180. {
  27181. // the filter must be valid..
  27182. jassert (owner != 0);
  27183. }
  27184. AudioProcessorEditor::~AudioProcessorEditor()
  27185. {
  27186. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  27187. // filter for some reason..
  27188. jassert (owner->getActiveEditor() != this);
  27189. }
  27190. END_JUCE_NAMESPACE
  27191. /********* End of inlined file: juce_AudioProcessorEditor.cpp *********/
  27192. /********* Start of inlined file: juce_AudioProcessorGraph.cpp *********/
  27193. BEGIN_JUCE_NAMESPACE
  27194. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  27195. AudioProcessorGraph::Node::Node (const uint32 id_,
  27196. AudioProcessor* const processor_) throw()
  27197. : id (id_),
  27198. processor (processor_),
  27199. isPrepared (false)
  27200. {
  27201. jassert (processor_ != 0);
  27202. }
  27203. AudioProcessorGraph::Node::~Node()
  27204. {
  27205. delete processor;
  27206. }
  27207. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  27208. AudioProcessorGraph* const graph)
  27209. {
  27210. if (! isPrepared)
  27211. {
  27212. isPrepared = true;
  27213. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27214. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  27215. if (ioProc != 0)
  27216. ioProc->setParentGraph (graph);
  27217. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  27218. processor->getNumOutputChannels(),
  27219. sampleRate, blockSize);
  27220. processor->prepareToPlay (sampleRate, blockSize);
  27221. }
  27222. }
  27223. void AudioProcessorGraph::Node::unprepare()
  27224. {
  27225. if (isPrepared)
  27226. {
  27227. isPrepared = false;
  27228. processor->releaseResources();
  27229. }
  27230. }
  27231. AudioProcessorGraph::AudioProcessorGraph()
  27232. : lastNodeId (0),
  27233. renderingBuffers (1, 1),
  27234. currentAudioOutputBuffer (1, 1)
  27235. {
  27236. }
  27237. AudioProcessorGraph::~AudioProcessorGraph()
  27238. {
  27239. clearRenderingSequence();
  27240. clear();
  27241. }
  27242. const String AudioProcessorGraph::getName() const
  27243. {
  27244. return "Audio Graph";
  27245. }
  27246. void AudioProcessorGraph::clear()
  27247. {
  27248. nodes.clear();
  27249. connections.clear();
  27250. triggerAsyncUpdate();
  27251. }
  27252. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const throw()
  27253. {
  27254. for (int i = nodes.size(); --i >= 0;)
  27255. if (nodes.getUnchecked(i)->id == nodeId)
  27256. return nodes.getUnchecked(i);
  27257. return 0;
  27258. }
  27259. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  27260. uint32 nodeId)
  27261. {
  27262. if (newProcessor == 0)
  27263. {
  27264. jassertfalse
  27265. return 0;
  27266. }
  27267. if (nodeId == 0)
  27268. {
  27269. nodeId = ++lastNodeId;
  27270. }
  27271. else
  27272. {
  27273. // you can't add a node with an id that already exists in the graph..
  27274. jassert (getNodeForId (nodeId) == 0);
  27275. removeNode (nodeId);
  27276. }
  27277. lastNodeId = nodeId;
  27278. Node* const n = new Node (nodeId, newProcessor);
  27279. nodes.add (n);
  27280. triggerAsyncUpdate();
  27281. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27282. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  27283. if (ioProc != 0)
  27284. ioProc->setParentGraph (this);
  27285. return n;
  27286. }
  27287. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  27288. {
  27289. disconnectNode (nodeId);
  27290. for (int i = nodes.size(); --i >= 0;)
  27291. {
  27292. if (nodes.getUnchecked(i)->id == nodeId)
  27293. {
  27294. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27295. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  27296. if (ioProc != 0)
  27297. ioProc->setParentGraph (0);
  27298. nodes.remove (i);
  27299. triggerAsyncUpdate();
  27300. return true;
  27301. }
  27302. }
  27303. return false;
  27304. }
  27305. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  27306. const int sourceChannelIndex,
  27307. const uint32 destNodeId,
  27308. const int destChannelIndex) const throw()
  27309. {
  27310. for (int i = connections.size(); --i >= 0;)
  27311. {
  27312. const Connection* const c = connections.getUnchecked(i);
  27313. if (c->sourceNodeId == sourceNodeId
  27314. && c->destNodeId == destNodeId
  27315. && c->sourceChannelIndex == sourceChannelIndex
  27316. && c->destChannelIndex == destChannelIndex)
  27317. {
  27318. return c;
  27319. }
  27320. }
  27321. return 0;
  27322. }
  27323. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  27324. const uint32 possibleDestNodeId) const throw()
  27325. {
  27326. for (int i = connections.size(); --i >= 0;)
  27327. {
  27328. const Connection* const c = connections.getUnchecked(i);
  27329. if (c->sourceNodeId == possibleSourceNodeId
  27330. && c->destNodeId == possibleDestNodeId)
  27331. {
  27332. return true;
  27333. }
  27334. }
  27335. return false;
  27336. }
  27337. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  27338. const int sourceChannelIndex,
  27339. const uint32 destNodeId,
  27340. const int destChannelIndex) const throw()
  27341. {
  27342. if (sourceChannelIndex < 0
  27343. || destChannelIndex < 0
  27344. || sourceNodeId == destNodeId
  27345. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  27346. return false;
  27347. const Node* const source = getNodeForId (sourceNodeId);
  27348. if (source == 0
  27349. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  27350. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  27351. return false;
  27352. const Node* const dest = getNodeForId (destNodeId);
  27353. if (dest == 0
  27354. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  27355. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  27356. return false;
  27357. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  27358. destNodeId, destChannelIndex) == 0;
  27359. }
  27360. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  27361. const int sourceChannelIndex,
  27362. const uint32 destNodeId,
  27363. const int destChannelIndex)
  27364. {
  27365. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  27366. return false;
  27367. Connection* const c = new Connection();
  27368. c->sourceNodeId = sourceNodeId;
  27369. c->sourceChannelIndex = sourceChannelIndex;
  27370. c->destNodeId = destNodeId;
  27371. c->destChannelIndex = destChannelIndex;
  27372. connections.add (c);
  27373. triggerAsyncUpdate();
  27374. return true;
  27375. }
  27376. void AudioProcessorGraph::removeConnection (const int index)
  27377. {
  27378. connections.remove (index);
  27379. triggerAsyncUpdate();
  27380. }
  27381. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  27382. const uint32 destNodeId, const int destChannelIndex)
  27383. {
  27384. bool doneAnything = false;
  27385. for (int i = connections.size(); --i >= 0;)
  27386. {
  27387. const Connection* const c = connections.getUnchecked(i);
  27388. if (c->sourceNodeId == sourceNodeId
  27389. && c->destNodeId == destNodeId
  27390. && c->sourceChannelIndex == sourceChannelIndex
  27391. && c->destChannelIndex == destChannelIndex)
  27392. {
  27393. removeConnection (i);
  27394. doneAnything = true;
  27395. triggerAsyncUpdate();
  27396. }
  27397. }
  27398. return doneAnything;
  27399. }
  27400. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  27401. {
  27402. bool doneAnything = false;
  27403. for (int i = connections.size(); --i >= 0;)
  27404. {
  27405. const Connection* const c = connections.getUnchecked(i);
  27406. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  27407. {
  27408. removeConnection (i);
  27409. doneAnything = true;
  27410. triggerAsyncUpdate();
  27411. }
  27412. }
  27413. return doneAnything;
  27414. }
  27415. bool AudioProcessorGraph::removeIllegalConnections()
  27416. {
  27417. bool doneAnything = false;
  27418. for (int i = connections.size(); --i >= 0;)
  27419. {
  27420. const Connection* const c = connections.getUnchecked(i);
  27421. const Node* const source = getNodeForId (c->sourceNodeId);
  27422. const Node* const dest = getNodeForId (c->destNodeId);
  27423. if (source == 0 || dest == 0
  27424. || (c->sourceChannelIndex != midiChannelIndex
  27425. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  27426. || (c->sourceChannelIndex == midiChannelIndex
  27427. && ! source->processor->producesMidi())
  27428. || (c->destChannelIndex != midiChannelIndex
  27429. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  27430. || (c->destChannelIndex == midiChannelIndex
  27431. && ! dest->processor->acceptsMidi()))
  27432. {
  27433. removeConnection (i);
  27434. doneAnything = true;
  27435. triggerAsyncUpdate();
  27436. }
  27437. }
  27438. return doneAnything;
  27439. }
  27440. namespace GraphRenderingOps
  27441. {
  27442. class AudioGraphRenderingOp
  27443. {
  27444. public:
  27445. AudioGraphRenderingOp() throw() {}
  27446. virtual ~AudioGraphRenderingOp() throw() {}
  27447. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  27448. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  27449. const int numSamples) throw() = 0;
  27450. juce_UseDebuggingNewOperator
  27451. };
  27452. class ClearChannelOp : public AudioGraphRenderingOp
  27453. {
  27454. public:
  27455. ClearChannelOp (const int channelNum_) throw()
  27456. : channelNum (channelNum_)
  27457. {}
  27458. ~ClearChannelOp() throw() {}
  27459. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27460. {
  27461. sharedBufferChans.clear (channelNum, 0, numSamples);
  27462. }
  27463. private:
  27464. const int channelNum;
  27465. ClearChannelOp (const ClearChannelOp&);
  27466. const ClearChannelOp& operator= (const ClearChannelOp&);
  27467. };
  27468. class CopyChannelOp : public AudioGraphRenderingOp
  27469. {
  27470. public:
  27471. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  27472. : srcChannelNum (srcChannelNum_),
  27473. dstChannelNum (dstChannelNum_)
  27474. {}
  27475. ~CopyChannelOp() throw() {}
  27476. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27477. {
  27478. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  27479. }
  27480. private:
  27481. const int srcChannelNum, dstChannelNum;
  27482. CopyChannelOp (const CopyChannelOp&);
  27483. const CopyChannelOp& operator= (const CopyChannelOp&);
  27484. };
  27485. class AddChannelOp : public AudioGraphRenderingOp
  27486. {
  27487. public:
  27488. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  27489. : srcChannelNum (srcChannelNum_),
  27490. dstChannelNum (dstChannelNum_)
  27491. {}
  27492. ~AddChannelOp() throw() {}
  27493. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27494. {
  27495. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  27496. }
  27497. private:
  27498. const int srcChannelNum, dstChannelNum;
  27499. AddChannelOp (const AddChannelOp&);
  27500. const AddChannelOp& operator= (const AddChannelOp&);
  27501. };
  27502. class ClearMidiBufferOp : public AudioGraphRenderingOp
  27503. {
  27504. public:
  27505. ClearMidiBufferOp (const int bufferNum_) throw()
  27506. : bufferNum (bufferNum_)
  27507. {}
  27508. ~ClearMidiBufferOp() throw() {}
  27509. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  27510. {
  27511. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  27512. }
  27513. private:
  27514. const int bufferNum;
  27515. ClearMidiBufferOp (const ClearMidiBufferOp&);
  27516. const ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  27517. };
  27518. class CopyMidiBufferOp : public AudioGraphRenderingOp
  27519. {
  27520. public:
  27521. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  27522. : srcBufferNum (srcBufferNum_),
  27523. dstBufferNum (dstBufferNum_)
  27524. {}
  27525. ~CopyMidiBufferOp() throw() {}
  27526. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  27527. {
  27528. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  27529. }
  27530. private:
  27531. const int srcBufferNum, dstBufferNum;
  27532. CopyMidiBufferOp (const CopyMidiBufferOp&);
  27533. const CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  27534. };
  27535. class AddMidiBufferOp : public AudioGraphRenderingOp
  27536. {
  27537. public:
  27538. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  27539. : srcBufferNum (srcBufferNum_),
  27540. dstBufferNum (dstBufferNum_)
  27541. {}
  27542. ~AddMidiBufferOp() throw() {}
  27543. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  27544. {
  27545. sharedMidiBuffers.getUnchecked (dstBufferNum)
  27546. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  27547. }
  27548. private:
  27549. const int srcBufferNum, dstBufferNum;
  27550. AddMidiBufferOp (const AddMidiBufferOp&);
  27551. const AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  27552. };
  27553. class ProcessBufferOp : public AudioGraphRenderingOp
  27554. {
  27555. public:
  27556. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  27557. const Array <int>& audioChannelsToUse_,
  27558. const int totalChans_,
  27559. const int midiBufferToUse_) throw()
  27560. : node (node_),
  27561. processor (node_->processor),
  27562. audioChannelsToUse (audioChannelsToUse_),
  27563. totalChans (jmax (1, totalChans_)),
  27564. midiBufferToUse (midiBufferToUse_)
  27565. {
  27566. channels = (float**) juce_calloc (sizeof (float*) * totalChans);
  27567. while (audioChannelsToUse.size() < totalChans)
  27568. audioChannelsToUse.add (0);
  27569. }
  27570. ~ProcessBufferOp() throw()
  27571. {
  27572. juce_free (channels);
  27573. }
  27574. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  27575. {
  27576. for (int i = totalChans; --i >= 0;)
  27577. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  27578. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  27579. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  27580. }
  27581. const AudioProcessorGraph::Node::Ptr node;
  27582. AudioProcessor* const processor;
  27583. private:
  27584. Array <int> audioChannelsToUse;
  27585. float** channels;
  27586. int totalChans;
  27587. int midiBufferToUse;
  27588. ProcessBufferOp (const ProcessBufferOp&);
  27589. const ProcessBufferOp& operator= (const ProcessBufferOp&);
  27590. };
  27591. /** Used to calculate the correct sequence of rendering ops needed, based on
  27592. the best re-use of shared buffers at each stage.
  27593. */
  27594. class RenderingOpSequenceCalculator
  27595. {
  27596. public:
  27597. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  27598. const VoidArray& orderedNodes_,
  27599. VoidArray& renderingOps)
  27600. : graph (graph_),
  27601. orderedNodes (orderedNodes_)
  27602. {
  27603. nodeIds.add (-2); // first buffer is read-only zeros
  27604. channels.add (0);
  27605. midiNodeIds.add (-2);
  27606. for (int i = 0; i < orderedNodes.size(); ++i)
  27607. {
  27608. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  27609. renderingOps, i);
  27610. markAnyUnusedBuffersAsFree (i);
  27611. }
  27612. }
  27613. int getNumBuffersNeeded() const throw() { return nodeIds.size(); }
  27614. int getNumMidiBuffersNeeded() const throw() { return midiNodeIds.size(); }
  27615. juce_UseDebuggingNewOperator
  27616. private:
  27617. AudioProcessorGraph& graph;
  27618. const VoidArray& orderedNodes;
  27619. Array <int> nodeIds, channels, midiNodeIds;
  27620. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  27621. VoidArray& renderingOps,
  27622. const int ourRenderingIndex)
  27623. {
  27624. const int numIns = node->processor->getNumInputChannels();
  27625. const int numOuts = node->processor->getNumOutputChannels();
  27626. const int totalChans = jmax (numIns, numOuts);
  27627. Array <int> audioChannelsToUse;
  27628. int midiBufferToUse = -1;
  27629. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  27630. {
  27631. // get a list of all the inputs to this node
  27632. Array <int> sourceNodes, sourceOutputChans;
  27633. for (int i = graph.getNumConnections(); --i >= 0;)
  27634. {
  27635. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  27636. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  27637. {
  27638. sourceNodes.add (c->sourceNodeId);
  27639. sourceOutputChans.add (c->sourceChannelIndex);
  27640. }
  27641. }
  27642. int bufIndex = -1;
  27643. if (sourceNodes.size() == 0)
  27644. {
  27645. // unconnected input channel
  27646. if (inputChan >= numOuts)
  27647. {
  27648. bufIndex = getReadOnlyEmptyBuffer();
  27649. jassert (bufIndex >= 0);
  27650. }
  27651. else
  27652. {
  27653. bufIndex = getFreeBuffer (false);
  27654. renderingOps.add (new ClearChannelOp (bufIndex));
  27655. }
  27656. }
  27657. else if (sourceNodes.size() == 1)
  27658. {
  27659. // channel with a straightforward single input..
  27660. const int srcNode = sourceNodes.getUnchecked(0);
  27661. const int srcChan = sourceOutputChans.getUnchecked(0);
  27662. bufIndex = getBufferContaining (srcNode, srcChan);
  27663. if (bufIndex < 0)
  27664. {
  27665. // if not found, this is probably a feedback loop
  27666. bufIndex = getReadOnlyEmptyBuffer();
  27667. jassert (bufIndex >= 0);
  27668. }
  27669. if (inputChan < numOuts
  27670. && isBufferNeededLater (ourRenderingIndex,
  27671. inputChan,
  27672. srcNode, srcChan))
  27673. {
  27674. // can't mess up this channel because it's needed later by another node, so we
  27675. // need to use a copy of it..
  27676. const int newFreeBuffer = getFreeBuffer (false);
  27677. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  27678. bufIndex = newFreeBuffer;
  27679. }
  27680. }
  27681. else
  27682. {
  27683. // channel with a mix of several inputs..
  27684. // try to find a re-usable channel from our inputs..
  27685. int reusableInputIndex = -1;
  27686. for (int i = 0; i < sourceNodes.size(); ++i)
  27687. {
  27688. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  27689. sourceOutputChans.getUnchecked(i));
  27690. if (sourceBufIndex >= 0
  27691. && ! isBufferNeededLater (ourRenderingIndex,
  27692. inputChan,
  27693. sourceNodes.getUnchecked(i),
  27694. sourceOutputChans.getUnchecked(i)))
  27695. {
  27696. // we've found one of our input chans that can be re-used..
  27697. reusableInputIndex = i;
  27698. bufIndex = sourceBufIndex;
  27699. break;
  27700. }
  27701. }
  27702. if (reusableInputIndex < 0)
  27703. {
  27704. // can't re-use any of our input chans, so get a new one and copy everything into it..
  27705. bufIndex = getFreeBuffer (false);
  27706. jassert (bufIndex != 0);
  27707. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  27708. sourceOutputChans.getUnchecked (0));
  27709. if (srcIndex < 0)
  27710. {
  27711. // if not found, this is probably a feedback loop
  27712. renderingOps.add (new ClearChannelOp (bufIndex));
  27713. }
  27714. else
  27715. {
  27716. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  27717. }
  27718. reusableInputIndex = 0;
  27719. }
  27720. for (int j = 0; j < sourceNodes.size(); ++j)
  27721. {
  27722. if (j != reusableInputIndex)
  27723. {
  27724. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  27725. sourceOutputChans.getUnchecked(j));
  27726. if (srcIndex >= 0)
  27727. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  27728. }
  27729. }
  27730. }
  27731. jassert (bufIndex >= 0);
  27732. audioChannelsToUse.add (bufIndex);
  27733. if (inputChan < numOuts)
  27734. markBufferAsContaining (bufIndex, node->id, inputChan);
  27735. }
  27736. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  27737. {
  27738. const int bufIndex = getFreeBuffer (false);
  27739. jassert (bufIndex != 0);
  27740. audioChannelsToUse.add (bufIndex);
  27741. markBufferAsContaining (bufIndex, node->id, outputChan);
  27742. }
  27743. // Now the same thing for midi..
  27744. Array <int> midiSourceNodes;
  27745. for (int i = graph.getNumConnections(); --i >= 0;)
  27746. {
  27747. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  27748. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  27749. midiSourceNodes.add (c->sourceNodeId);
  27750. }
  27751. if (midiSourceNodes.size() == 0)
  27752. {
  27753. // No midi inputs..
  27754. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  27755. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  27756. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  27757. }
  27758. else if (midiSourceNodes.size() == 1)
  27759. {
  27760. // One midi input..
  27761. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  27762. AudioProcessorGraph::midiChannelIndex);
  27763. if (midiBufferToUse >= 0)
  27764. {
  27765. if (isBufferNeededLater (ourRenderingIndex,
  27766. AudioProcessorGraph::midiChannelIndex,
  27767. midiSourceNodes.getUnchecked(0),
  27768. AudioProcessorGraph::midiChannelIndex))
  27769. {
  27770. // can't mess up this channel because it's needed later by another node, so we
  27771. // need to use a copy of it..
  27772. const int newFreeBuffer = getFreeBuffer (true);
  27773. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  27774. midiBufferToUse = newFreeBuffer;
  27775. }
  27776. }
  27777. else
  27778. {
  27779. // probably a feedback loop, so just use an empty one..
  27780. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  27781. }
  27782. }
  27783. else
  27784. {
  27785. // More than one midi input being mixed..
  27786. int reusableInputIndex = -1;
  27787. for (int i = 0; i < midiSourceNodes.size(); ++i)
  27788. {
  27789. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  27790. AudioProcessorGraph::midiChannelIndex);
  27791. if (sourceBufIndex >= 0
  27792. && ! isBufferNeededLater (ourRenderingIndex,
  27793. AudioProcessorGraph::midiChannelIndex,
  27794. midiSourceNodes.getUnchecked(i),
  27795. AudioProcessorGraph::midiChannelIndex))
  27796. {
  27797. // we've found one of our input buffers that can be re-used..
  27798. reusableInputIndex = i;
  27799. midiBufferToUse = sourceBufIndex;
  27800. break;
  27801. }
  27802. }
  27803. if (reusableInputIndex < 0)
  27804. {
  27805. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  27806. midiBufferToUse = getFreeBuffer (true);
  27807. jassert (midiBufferToUse >= 0);
  27808. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  27809. AudioProcessorGraph::midiChannelIndex);
  27810. if (srcIndex >= 0)
  27811. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  27812. else
  27813. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  27814. reusableInputIndex = 0;
  27815. }
  27816. for (int j = 0; j < midiSourceNodes.size(); ++j)
  27817. {
  27818. if (j != reusableInputIndex)
  27819. {
  27820. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  27821. AudioProcessorGraph::midiChannelIndex);
  27822. if (srcIndex >= 0)
  27823. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  27824. }
  27825. }
  27826. }
  27827. if (node->processor->producesMidi())
  27828. markBufferAsContaining (midiBufferToUse, node->id,
  27829. AudioProcessorGraph::midiChannelIndex);
  27830. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  27831. totalChans, midiBufferToUse));
  27832. }
  27833. int getFreeBuffer (const bool forMidi)
  27834. {
  27835. if (forMidi)
  27836. {
  27837. for (int i = 1; i < midiNodeIds.size(); ++i)
  27838. if (midiNodeIds.getUnchecked(i) < 0)
  27839. return i;
  27840. midiNodeIds.add (-1);
  27841. return midiNodeIds.size() - 1;
  27842. }
  27843. else
  27844. {
  27845. for (int i = 1; i < nodeIds.size(); ++i)
  27846. if (nodeIds.getUnchecked(i) < 0)
  27847. return i;
  27848. nodeIds.add (-1);
  27849. channels.add (0);
  27850. return nodeIds.size() - 1;
  27851. }
  27852. }
  27853. int getReadOnlyEmptyBuffer() const throw()
  27854. {
  27855. return 0;
  27856. }
  27857. int getBufferContaining (const int nodeId, const int outputChannel) const throw()
  27858. {
  27859. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  27860. {
  27861. for (int i = midiNodeIds.size(); --i >= 0;)
  27862. if (midiNodeIds.getUnchecked(i) == nodeId)
  27863. return i;
  27864. }
  27865. else
  27866. {
  27867. for (int i = nodeIds.size(); --i >= 0;)
  27868. if (nodeIds.getUnchecked(i) == nodeId
  27869. && channels.getUnchecked(i) == outputChannel)
  27870. return i;
  27871. }
  27872. return -1;
  27873. }
  27874. void markAnyUnusedBuffersAsFree (const int stepIndex)
  27875. {
  27876. int i;
  27877. for (i = 0; i < nodeIds.size(); ++i)
  27878. {
  27879. if (nodeIds.getUnchecked(i) >= 0
  27880. && ! isBufferNeededLater (stepIndex, -1,
  27881. nodeIds.getUnchecked(i),
  27882. channels.getUnchecked(i)))
  27883. {
  27884. nodeIds.set (i, -1);
  27885. }
  27886. }
  27887. for (i = 0; i < midiNodeIds.size(); ++i)
  27888. {
  27889. if (midiNodeIds.getUnchecked(i) >= 0
  27890. && ! isBufferNeededLater (stepIndex, -1,
  27891. midiNodeIds.getUnchecked(i),
  27892. AudioProcessorGraph::midiChannelIndex))
  27893. {
  27894. midiNodeIds.set (i, -1);
  27895. }
  27896. }
  27897. }
  27898. bool isBufferNeededLater (int stepIndexToSearchFrom,
  27899. int inputChannelOfIndexToIgnore,
  27900. const int nodeId,
  27901. const int outputChanIndex) const throw()
  27902. {
  27903. while (stepIndexToSearchFrom < orderedNodes.size())
  27904. {
  27905. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  27906. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  27907. {
  27908. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  27909. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  27910. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  27911. return true;
  27912. }
  27913. else
  27914. {
  27915. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  27916. if (i != inputChannelOfIndexToIgnore
  27917. && graph.getConnectionBetween (nodeId, outputChanIndex,
  27918. node->id, i) != 0)
  27919. return true;
  27920. }
  27921. inputChannelOfIndexToIgnore = -1;
  27922. ++stepIndexToSearchFrom;
  27923. }
  27924. return false;
  27925. }
  27926. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  27927. {
  27928. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  27929. {
  27930. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  27931. midiNodeIds.set (bufferNum, nodeId);
  27932. }
  27933. else
  27934. {
  27935. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  27936. nodeIds.set (bufferNum, nodeId);
  27937. channels.set (bufferNum, outputIndex);
  27938. }
  27939. }
  27940. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  27941. const RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  27942. };
  27943. }
  27944. void AudioProcessorGraph::clearRenderingSequence()
  27945. {
  27946. const ScopedLock sl (renderLock);
  27947. for (int i = renderingOps.size(); --i >= 0;)
  27948. {
  27949. GraphRenderingOps::AudioGraphRenderingOp* const r
  27950. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  27951. renderingOps.remove (i);
  27952. delete r;
  27953. }
  27954. }
  27955. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  27956. const uint32 possibleDestinationId,
  27957. const int recursionCheck) const throw()
  27958. {
  27959. if (recursionCheck > 0)
  27960. {
  27961. for (int i = connections.size(); --i >= 0;)
  27962. {
  27963. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  27964. if (c->destNodeId == possibleDestinationId
  27965. && (c->sourceNodeId == possibleInputId
  27966. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  27967. return true;
  27968. }
  27969. }
  27970. return false;
  27971. }
  27972. void AudioProcessorGraph::buildRenderingSequence()
  27973. {
  27974. VoidArray newRenderingOps;
  27975. int numRenderingBuffersNeeded = 2;
  27976. int numMidiBuffersNeeded = 1;
  27977. {
  27978. MessageManagerLock mml;
  27979. VoidArray orderedNodes;
  27980. int i;
  27981. for (i = 0; i < nodes.size(); ++i)
  27982. {
  27983. Node* const node = nodes.getUnchecked(i);
  27984. node->prepare (getSampleRate(), getBlockSize(), this);
  27985. int j = 0;
  27986. for (; j < orderedNodes.size(); ++j)
  27987. if (isAnInputTo (node->id,
  27988. ((Node*) orderedNodes.getUnchecked (j))->id,
  27989. nodes.size() + 1))
  27990. break;
  27991. orderedNodes.insert (j, node);
  27992. }
  27993. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  27994. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  27995. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  27996. }
  27997. VoidArray oldRenderingOps (renderingOps);
  27998. {
  27999. // swap over to the new rendering sequence..
  28000. const ScopedLock sl (renderLock);
  28001. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28002. renderingBuffers.clear();
  28003. for (int i = midiBuffers.size(); --i >= 0;)
  28004. midiBuffers.getUnchecked(i)->clear();
  28005. while (midiBuffers.size() < numMidiBuffersNeeded)
  28006. midiBuffers.add (new MidiBuffer());
  28007. renderingOps = newRenderingOps;
  28008. }
  28009. for (int i = oldRenderingOps.size(); --i >= 0;)
  28010. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28011. }
  28012. void AudioProcessorGraph::handleAsyncUpdate()
  28013. {
  28014. buildRenderingSequence();
  28015. }
  28016. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28017. {
  28018. currentAudioInputBuffer = 0;
  28019. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28020. currentMidiInputBuffer = 0;
  28021. currentMidiOutputBuffer.clear();
  28022. clearRenderingSequence();
  28023. buildRenderingSequence();
  28024. }
  28025. void AudioProcessorGraph::releaseResources()
  28026. {
  28027. for (int i = 0; i < nodes.size(); ++i)
  28028. nodes.getUnchecked(i)->unprepare();
  28029. renderingBuffers.setSize (1, 1);
  28030. midiBuffers.clear();
  28031. currentAudioInputBuffer = 0;
  28032. currentAudioOutputBuffer.setSize (1, 1);
  28033. currentMidiInputBuffer = 0;
  28034. currentMidiOutputBuffer.clear();
  28035. }
  28036. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28037. {
  28038. const int numSamples = buffer.getNumSamples();
  28039. const ScopedLock sl (renderLock);
  28040. currentAudioInputBuffer = &buffer;
  28041. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28042. currentAudioOutputBuffer.clear();
  28043. currentMidiInputBuffer = &midiMessages;
  28044. currentMidiOutputBuffer.clear();
  28045. int i;
  28046. for (i = 0; i < renderingOps.size(); ++i)
  28047. {
  28048. GraphRenderingOps::AudioGraphRenderingOp* const op
  28049. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28050. op->perform (renderingBuffers, midiBuffers, numSamples);
  28051. }
  28052. for (i = 0; i < buffer.getNumChannels(); ++i)
  28053. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28054. }
  28055. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28056. {
  28057. return "Input " + String (channelIndex + 1);
  28058. }
  28059. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28060. {
  28061. return "Output " + String (channelIndex + 1);
  28062. }
  28063. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28064. {
  28065. return true;
  28066. }
  28067. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28068. {
  28069. return true;
  28070. }
  28071. bool AudioProcessorGraph::acceptsMidi() const
  28072. {
  28073. return true;
  28074. }
  28075. bool AudioProcessorGraph::producesMidi() const
  28076. {
  28077. return true;
  28078. }
  28079. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28080. {
  28081. }
  28082. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28083. {
  28084. }
  28085. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28086. : type (type_),
  28087. graph (0)
  28088. {
  28089. }
  28090. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28091. {
  28092. }
  28093. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28094. {
  28095. switch (type)
  28096. {
  28097. case audioOutputNode:
  28098. return "Audio Output";
  28099. case audioInputNode:
  28100. return "Audio Input";
  28101. case midiOutputNode:
  28102. return "Midi Output";
  28103. case midiInputNode:
  28104. return "Midi Input";
  28105. default:
  28106. break;
  28107. }
  28108. return String::empty;
  28109. }
  28110. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28111. {
  28112. d.name = getName();
  28113. d.uid = d.name.hashCode();
  28114. d.category = "I/O devices";
  28115. d.pluginFormatName = "Internal";
  28116. d.manufacturerName = "Raw Material Software";
  28117. d.version = "1.0";
  28118. d.isInstrument = false;
  28119. d.numInputChannels = getNumInputChannels();
  28120. if (type == audioOutputNode && graph != 0)
  28121. d.numInputChannels = graph->getNumInputChannels();
  28122. d.numOutputChannels = getNumOutputChannels();
  28123. if (type == audioInputNode && graph != 0)
  28124. d.numOutputChannels = graph->getNumOutputChannels();
  28125. }
  28126. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  28127. {
  28128. jassert (graph != 0);
  28129. }
  28130. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  28131. {
  28132. }
  28133. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  28134. MidiBuffer& midiMessages)
  28135. {
  28136. jassert (graph != 0);
  28137. switch (type)
  28138. {
  28139. case audioOutputNode:
  28140. {
  28141. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  28142. buffer.getNumChannels()); --i >= 0;)
  28143. {
  28144. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  28145. }
  28146. break;
  28147. }
  28148. case audioInputNode:
  28149. {
  28150. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  28151. buffer.getNumChannels()); --i >= 0;)
  28152. {
  28153. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  28154. }
  28155. break;
  28156. }
  28157. case midiOutputNode:
  28158. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  28159. break;
  28160. case midiInputNode:
  28161. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  28162. break;
  28163. default:
  28164. break;
  28165. }
  28166. }
  28167. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  28168. {
  28169. return type == midiOutputNode;
  28170. }
  28171. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  28172. {
  28173. return type == midiInputNode;
  28174. }
  28175. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  28176. {
  28177. switch (type)
  28178. {
  28179. case audioOutputNode:
  28180. return "Output " + String (channelIndex + 1);
  28181. case midiOutputNode:
  28182. return "Midi Output";
  28183. default:
  28184. break;
  28185. }
  28186. return String::empty;
  28187. }
  28188. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  28189. {
  28190. switch (type)
  28191. {
  28192. case audioInputNode:
  28193. return "Input " + String (channelIndex + 1);
  28194. case midiInputNode:
  28195. return "Midi Input";
  28196. default:
  28197. break;
  28198. }
  28199. return String::empty;
  28200. }
  28201. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  28202. {
  28203. return type == audioInputNode || type == audioOutputNode;
  28204. }
  28205. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  28206. {
  28207. return isInputChannelStereoPair (index);
  28208. }
  28209. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const throw()
  28210. {
  28211. return type == audioInputNode || type == midiInputNode;
  28212. }
  28213. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const throw()
  28214. {
  28215. return type == audioOutputNode || type == midiOutputNode;
  28216. }
  28217. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  28218. {
  28219. return 0;
  28220. }
  28221. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  28222. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  28223. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  28224. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  28225. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  28226. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  28227. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  28228. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  28229. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  28230. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  28231. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  28232. {
  28233. }
  28234. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  28235. {
  28236. }
  28237. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph) throw()
  28238. {
  28239. graph = newGraph;
  28240. if (graph != 0)
  28241. {
  28242. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  28243. type == audioInputNode ? graph->getNumInputChannels() : 0,
  28244. getSampleRate(),
  28245. getBlockSize());
  28246. updateHostDisplay();
  28247. }
  28248. }
  28249. END_JUCE_NAMESPACE
  28250. /********* End of inlined file: juce_AudioProcessorGraph.cpp *********/
  28251. /********* Start of inlined file: juce_AudioProcessorPlayer.cpp *********/
  28252. BEGIN_JUCE_NAMESPACE
  28253. AudioProcessorPlayer::AudioProcessorPlayer()
  28254. : processor (0),
  28255. sampleRate (0),
  28256. blockSize (0),
  28257. isPrepared (false),
  28258. numInputChans (0),
  28259. numOutputChans (0),
  28260. tempBuffer (1, 1)
  28261. {
  28262. }
  28263. AudioProcessorPlayer::~AudioProcessorPlayer()
  28264. {
  28265. setProcessor (0);
  28266. }
  28267. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  28268. {
  28269. if (processor != processorToPlay)
  28270. {
  28271. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  28272. {
  28273. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  28274. sampleRate, blockSize);
  28275. processorToPlay->prepareToPlay (sampleRate, blockSize);
  28276. }
  28277. lock.enter();
  28278. AudioProcessor* const oldOne = isPrepared ? processor : 0;
  28279. processor = processorToPlay;
  28280. isPrepared = true;
  28281. lock.exit();
  28282. if (oldOne != 0)
  28283. oldOne->releaseResources();
  28284. }
  28285. }
  28286. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  28287. int numInputChannels,
  28288. float** outputChannelData,
  28289. int numOutputChannels,
  28290. int numSamples)
  28291. {
  28292. // these should have been prepared by audioDeviceAboutToStart()...
  28293. jassert (sampleRate > 0 && blockSize > 0);
  28294. incomingMidi.clear();
  28295. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  28296. int i, totalNumChans = 0;
  28297. if (numInputChannels > numOutputChannels)
  28298. {
  28299. // if there aren't enough output channels for the number of
  28300. // inputs, we need to create some temporary extra ones (can't
  28301. // use the input data in case it gets written to)
  28302. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  28303. false, false, true);
  28304. for (i = 0; i < numOutputChannels; ++i)
  28305. {
  28306. channels[totalNumChans] = outputChannelData[i];
  28307. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28308. ++totalNumChans;
  28309. }
  28310. for (i = numOutputChannels; i < numInputChannels; ++i)
  28311. {
  28312. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  28313. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28314. ++totalNumChans;
  28315. }
  28316. }
  28317. else
  28318. {
  28319. for (i = 0; i < numInputChannels; ++i)
  28320. {
  28321. channels[totalNumChans] = outputChannelData[i];
  28322. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28323. ++totalNumChans;
  28324. }
  28325. for (i = numInputChannels; i < numOutputChannels; ++i)
  28326. {
  28327. channels[totalNumChans] = outputChannelData[i];
  28328. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  28329. ++totalNumChans;
  28330. }
  28331. }
  28332. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  28333. const ScopedLock sl (lock);
  28334. if (processor != 0)
  28335. processor->processBlock (buffer, incomingMidi);
  28336. }
  28337. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  28338. {
  28339. const ScopedLock sl (lock);
  28340. sampleRate = device->getCurrentSampleRate();
  28341. blockSize = device->getCurrentBufferSizeSamples();
  28342. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  28343. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  28344. messageCollector.reset (sampleRate);
  28345. zeromem (channels, sizeof (channels));
  28346. if (processor != 0)
  28347. {
  28348. if (isPrepared)
  28349. processor->releaseResources();
  28350. AudioProcessor* const oldProcessor = processor;
  28351. setProcessor (0);
  28352. setProcessor (oldProcessor);
  28353. }
  28354. }
  28355. void AudioProcessorPlayer::audioDeviceStopped()
  28356. {
  28357. const ScopedLock sl (lock);
  28358. if (processor != 0 && isPrepared)
  28359. processor->releaseResources();
  28360. sampleRate = 0.0;
  28361. blockSize = 0;
  28362. isPrepared = false;
  28363. tempBuffer.setSize (1, 1);
  28364. }
  28365. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  28366. {
  28367. messageCollector.addMessageToQueue (message);
  28368. }
  28369. END_JUCE_NAMESPACE
  28370. /********* End of inlined file: juce_AudioProcessorPlayer.cpp *********/
  28371. /********* Start of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  28372. BEGIN_JUCE_NAMESPACE
  28373. class ProcessorParameterPropertyComp : public PropertyComponent,
  28374. public AudioProcessorListener,
  28375. public AsyncUpdater
  28376. {
  28377. public:
  28378. ProcessorParameterPropertyComp (const String& name,
  28379. AudioProcessor* const owner_,
  28380. const int index_)
  28381. : PropertyComponent (name),
  28382. owner (owner_),
  28383. index (index_)
  28384. {
  28385. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  28386. owner_->addListener (this);
  28387. }
  28388. ~ProcessorParameterPropertyComp()
  28389. {
  28390. owner->removeListener (this);
  28391. deleteAllChildren();
  28392. }
  28393. void refresh()
  28394. {
  28395. slider->setValue (owner->getParameter (index), false);
  28396. }
  28397. void audioProcessorChanged (AudioProcessor*) {}
  28398. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  28399. {
  28400. if (parameterIndex == index)
  28401. triggerAsyncUpdate();
  28402. }
  28403. void handleAsyncUpdate()
  28404. {
  28405. refresh();
  28406. }
  28407. juce_UseDebuggingNewOperator
  28408. private:
  28409. AudioProcessor* const owner;
  28410. const int index;
  28411. Slider* slider;
  28412. class ParamSlider : public Slider
  28413. {
  28414. public:
  28415. ParamSlider (AudioProcessor* const owner_, const int index_)
  28416. : Slider (String::empty),
  28417. owner (owner_),
  28418. index (index_)
  28419. {
  28420. setRange (0.0, 1.0, 0.0);
  28421. setSliderStyle (Slider::LinearBar);
  28422. setTextBoxIsEditable (false);
  28423. setScrollWheelEnabled (false);
  28424. }
  28425. ~ParamSlider()
  28426. {
  28427. }
  28428. void valueChanged()
  28429. {
  28430. const float newVal = (float) getValue();
  28431. if (owner->getParameter (index) != newVal)
  28432. owner->setParameter (index, newVal);
  28433. }
  28434. const String getTextFromValue (double /*value*/)
  28435. {
  28436. return owner->getParameterText (index);
  28437. }
  28438. juce_UseDebuggingNewOperator
  28439. private:
  28440. AudioProcessor* const owner;
  28441. const int index;
  28442. };
  28443. };
  28444. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner)
  28445. : AudioProcessorEditor (owner)
  28446. {
  28447. setOpaque (true);
  28448. addAndMakeVisible (panel = new PropertyPanel());
  28449. Array <PropertyComponent*> params;
  28450. const int numParams = owner->getNumParameters();
  28451. int totalHeight = 0;
  28452. for (int i = 0; i < numParams; ++i)
  28453. {
  28454. String name (owner->getParameterName (i));
  28455. if (name.trim().isEmpty())
  28456. name = "Unnamed";
  28457. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner, i);
  28458. params.add (pc);
  28459. totalHeight += pc->getPreferredHeight();
  28460. }
  28461. panel->addProperties (params);
  28462. setSize (400, jlimit (25, 400, totalHeight));
  28463. }
  28464. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  28465. {
  28466. deleteAllChildren();
  28467. }
  28468. void GenericAudioProcessorEditor::paint (Graphics& g)
  28469. {
  28470. g.fillAll (Colours::white);
  28471. }
  28472. void GenericAudioProcessorEditor::resized()
  28473. {
  28474. panel->setSize (getWidth(), getHeight());
  28475. }
  28476. END_JUCE_NAMESPACE
  28477. /********* End of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  28478. /********* Start of inlined file: juce_Sampler.cpp *********/
  28479. BEGIN_JUCE_NAMESPACE
  28480. SamplerSound::SamplerSound (const String& name_,
  28481. AudioFormatReader& source,
  28482. const BitArray& midiNotes_,
  28483. const int midiNoteForNormalPitch,
  28484. const double attackTimeSecs,
  28485. const double releaseTimeSecs,
  28486. const double maxSampleLengthSeconds)
  28487. : name (name_),
  28488. midiNotes (midiNotes_),
  28489. midiRootNote (midiNoteForNormalPitch)
  28490. {
  28491. sourceSampleRate = source.sampleRate;
  28492. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  28493. {
  28494. data = 0;
  28495. length = 0;
  28496. attackSamples = 0;
  28497. releaseSamples = 0;
  28498. }
  28499. else
  28500. {
  28501. length = jmin ((int) source.lengthInSamples,
  28502. (int) (maxSampleLengthSeconds * sourceSampleRate));
  28503. data = new AudioSampleBuffer (jmin (2, source.numChannels), length + 4);
  28504. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  28505. attackSamples = roundDoubleToInt (attackTimeSecs * sourceSampleRate);
  28506. releaseSamples = roundDoubleToInt (releaseTimeSecs * sourceSampleRate);
  28507. }
  28508. }
  28509. SamplerSound::~SamplerSound()
  28510. {
  28511. delete data;
  28512. data = 0;
  28513. }
  28514. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  28515. {
  28516. return midiNotes [midiNoteNumber];
  28517. }
  28518. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  28519. {
  28520. return true;
  28521. }
  28522. SamplerVoice::SamplerVoice()
  28523. : pitchRatio (0.0),
  28524. sourceSamplePosition (0.0),
  28525. lgain (0.0f),
  28526. rgain (0.0f),
  28527. isInAttack (false),
  28528. isInRelease (false)
  28529. {
  28530. }
  28531. SamplerVoice::~SamplerVoice()
  28532. {
  28533. }
  28534. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  28535. {
  28536. return dynamic_cast <const SamplerSound*> (sound) != 0;
  28537. }
  28538. void SamplerVoice::startNote (const int midiNoteNumber,
  28539. const float velocity,
  28540. SynthesiserSound* s,
  28541. const int /*currentPitchWheelPosition*/)
  28542. {
  28543. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  28544. jassert (sound != 0); // this object can only play SamplerSounds!
  28545. if (sound != 0)
  28546. {
  28547. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  28548. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  28549. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  28550. sourceSamplePosition = 0.0;
  28551. lgain = velocity;
  28552. rgain = velocity;
  28553. isInAttack = (sound->attackSamples > 0);
  28554. isInRelease = false;
  28555. if (isInAttack)
  28556. {
  28557. attackReleaseLevel = 0.0f;
  28558. attackDelta = (float) (pitchRatio / sound->attackSamples);
  28559. }
  28560. else
  28561. {
  28562. attackReleaseLevel = 1.0f;
  28563. attackDelta = 0.0f;
  28564. }
  28565. if (sound->releaseSamples > 0)
  28566. {
  28567. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  28568. }
  28569. else
  28570. {
  28571. releaseDelta = 0.0f;
  28572. }
  28573. }
  28574. }
  28575. void SamplerVoice::stopNote (const bool allowTailOff)
  28576. {
  28577. if (allowTailOff)
  28578. {
  28579. isInAttack = false;
  28580. isInRelease = true;
  28581. }
  28582. else
  28583. {
  28584. clearCurrentNote();
  28585. }
  28586. }
  28587. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  28588. {
  28589. }
  28590. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  28591. const int /*newValue*/)
  28592. {
  28593. }
  28594. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  28595. {
  28596. const SamplerSound* const playingSound = (SamplerSound*) (SynthesiserSound*) getCurrentlyPlayingSound();
  28597. if (playingSound != 0)
  28598. {
  28599. const float* const inL = playingSound->data->getSampleData (0, 0);
  28600. const float* const inR = playingSound->data->getNumChannels() > 1
  28601. ? playingSound->data->getSampleData (1, 0) : 0;
  28602. float* outL = outputBuffer.getSampleData (0, startSample);
  28603. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  28604. while (--numSamples >= 0)
  28605. {
  28606. const int pos = (int) sourceSamplePosition;
  28607. const float alpha = (float) (sourceSamplePosition - pos);
  28608. const float invAlpha = 1.0f - alpha;
  28609. // just using a very simple linear interpolation here..
  28610. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  28611. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  28612. : l;
  28613. l *= lgain;
  28614. r *= rgain;
  28615. if (isInAttack)
  28616. {
  28617. l *= attackReleaseLevel;
  28618. r *= attackReleaseLevel;
  28619. attackReleaseLevel += attackDelta;
  28620. if (attackReleaseLevel >= 1.0f)
  28621. {
  28622. attackReleaseLevel = 1.0f;
  28623. isInAttack = false;
  28624. }
  28625. }
  28626. else if (isInRelease)
  28627. {
  28628. l *= attackReleaseLevel;
  28629. r *= attackReleaseLevel;
  28630. attackReleaseLevel += releaseDelta;
  28631. if (attackReleaseLevel <= 0.0f)
  28632. {
  28633. stopNote (false);
  28634. break;
  28635. }
  28636. }
  28637. if (outR != 0)
  28638. {
  28639. *outL++ += l;
  28640. *outR++ += r;
  28641. }
  28642. else
  28643. {
  28644. *outL++ += (l + r) * 0.5f;
  28645. }
  28646. sourceSamplePosition += pitchRatio;
  28647. if (sourceSamplePosition > playingSound->length)
  28648. {
  28649. stopNote (false);
  28650. break;
  28651. }
  28652. }
  28653. }
  28654. }
  28655. END_JUCE_NAMESPACE
  28656. /********* End of inlined file: juce_Sampler.cpp *********/
  28657. /********* Start of inlined file: juce_Synthesiser.cpp *********/
  28658. BEGIN_JUCE_NAMESPACE
  28659. SynthesiserSound::SynthesiserSound()
  28660. {
  28661. }
  28662. SynthesiserSound::~SynthesiserSound()
  28663. {
  28664. }
  28665. SynthesiserVoice::SynthesiserVoice()
  28666. : currentSampleRate (44100.0),
  28667. currentlyPlayingNote (-1),
  28668. noteOnTime (0),
  28669. currentlyPlayingSound (0)
  28670. {
  28671. }
  28672. SynthesiserVoice::~SynthesiserVoice()
  28673. {
  28674. }
  28675. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  28676. {
  28677. return currentlyPlayingSound != 0
  28678. && currentlyPlayingSound->appliesToChannel (midiChannel);
  28679. }
  28680. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  28681. {
  28682. currentSampleRate = newRate;
  28683. }
  28684. void SynthesiserVoice::clearCurrentNote()
  28685. {
  28686. currentlyPlayingNote = -1;
  28687. currentlyPlayingSound = 0;
  28688. }
  28689. Synthesiser::Synthesiser()
  28690. : voices (2),
  28691. sounds (2),
  28692. sampleRate (0),
  28693. lastNoteOnCounter (0),
  28694. shouldStealNotes (true)
  28695. {
  28696. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  28697. lastPitchWheelValues[i] = 0x2000;
  28698. }
  28699. Synthesiser::~Synthesiser()
  28700. {
  28701. }
  28702. SynthesiserVoice* Synthesiser::getVoice (const int index) const throw()
  28703. {
  28704. const ScopedLock sl (lock);
  28705. return voices [index];
  28706. }
  28707. void Synthesiser::clearVoices()
  28708. {
  28709. const ScopedLock sl (lock);
  28710. voices.clear();
  28711. }
  28712. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  28713. {
  28714. const ScopedLock sl (lock);
  28715. voices.add (newVoice);
  28716. }
  28717. void Synthesiser::removeVoice (const int index)
  28718. {
  28719. const ScopedLock sl (lock);
  28720. voices.remove (index);
  28721. }
  28722. void Synthesiser::clearSounds()
  28723. {
  28724. const ScopedLock sl (lock);
  28725. sounds.clear();
  28726. }
  28727. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  28728. {
  28729. const ScopedLock sl (lock);
  28730. sounds.add (newSound);
  28731. }
  28732. void Synthesiser::removeSound (const int index)
  28733. {
  28734. const ScopedLock sl (lock);
  28735. sounds.remove (index);
  28736. }
  28737. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  28738. {
  28739. shouldStealNotes = shouldStealNotes_;
  28740. }
  28741. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  28742. {
  28743. if (sampleRate != newRate)
  28744. {
  28745. const ScopedLock sl (lock);
  28746. allNotesOff (0, false);
  28747. sampleRate = newRate;
  28748. for (int i = voices.size(); --i >= 0;)
  28749. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  28750. }
  28751. }
  28752. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  28753. const MidiBuffer& midiData,
  28754. int startSample,
  28755. int numSamples)
  28756. {
  28757. // must set the sample rate before using this!
  28758. jassert (sampleRate != 0);
  28759. const ScopedLock sl (lock);
  28760. MidiBuffer::Iterator midiIterator (midiData);
  28761. midiIterator.setNextSamplePosition (startSample);
  28762. MidiMessage m (0xf4, 0.0);
  28763. while (numSamples > 0)
  28764. {
  28765. int midiEventPos;
  28766. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  28767. && midiEventPos < startSample + numSamples;
  28768. const int numThisTime = useEvent ? midiEventPos - startSample
  28769. : numSamples;
  28770. if (numThisTime > 0)
  28771. {
  28772. for (int i = voices.size(); --i >= 0;)
  28773. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  28774. }
  28775. if (useEvent)
  28776. {
  28777. if (m.isNoteOn())
  28778. {
  28779. const int channel = m.getChannel();
  28780. noteOn (channel,
  28781. m.getNoteNumber(),
  28782. m.getFloatVelocity());
  28783. }
  28784. else if (m.isNoteOff())
  28785. {
  28786. noteOff (m.getChannel(),
  28787. m.getNoteNumber(),
  28788. true);
  28789. }
  28790. else if (m.isAllNotesOff() || m.isAllSoundOff())
  28791. {
  28792. allNotesOff (m.getChannel(), true);
  28793. }
  28794. else if (m.isPitchWheel())
  28795. {
  28796. const int channel = m.getChannel();
  28797. const int wheelPos = m.getPitchWheelValue();
  28798. lastPitchWheelValues [channel - 1] = wheelPos;
  28799. handlePitchWheel (channel, wheelPos);
  28800. }
  28801. else if (m.isController())
  28802. {
  28803. handleController (m.getChannel(),
  28804. m.getControllerNumber(),
  28805. m.getControllerValue());
  28806. }
  28807. }
  28808. startSample += numThisTime;
  28809. numSamples -= numThisTime;
  28810. }
  28811. }
  28812. void Synthesiser::noteOn (const int midiChannel,
  28813. const int midiNoteNumber,
  28814. const float velocity)
  28815. {
  28816. const ScopedLock sl (lock);
  28817. for (int i = sounds.size(); --i >= 0;)
  28818. {
  28819. SynthesiserSound* const sound = sounds.getUnchecked(i);
  28820. if (sound->appliesToNote (midiNoteNumber)
  28821. && sound->appliesToChannel (midiChannel))
  28822. {
  28823. startVoice (findFreeVoice (sound, shouldStealNotes),
  28824. sound, midiChannel, midiNoteNumber, velocity);
  28825. }
  28826. }
  28827. }
  28828. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  28829. SynthesiserSound* const sound,
  28830. const int midiChannel,
  28831. const int midiNoteNumber,
  28832. const float velocity)
  28833. {
  28834. if (voice != 0 && sound != 0)
  28835. {
  28836. if (voice->currentlyPlayingSound != 0)
  28837. voice->stopNote (false);
  28838. voice->startNote (midiNoteNumber,
  28839. velocity,
  28840. sound,
  28841. lastPitchWheelValues [midiChannel - 1]);
  28842. voice->currentlyPlayingNote = midiNoteNumber;
  28843. voice->noteOnTime = ++lastNoteOnCounter;
  28844. voice->currentlyPlayingSound = sound;
  28845. }
  28846. }
  28847. void Synthesiser::noteOff (const int midiChannel,
  28848. const int midiNoteNumber,
  28849. const bool allowTailOff)
  28850. {
  28851. const ScopedLock sl (lock);
  28852. for (int i = voices.size(); --i >= 0;)
  28853. {
  28854. SynthesiserVoice* const voice = voices.getUnchecked (i);
  28855. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  28856. {
  28857. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  28858. if (sound != 0
  28859. && sound->appliesToNote (midiNoteNumber)
  28860. && sound->appliesToChannel (midiChannel))
  28861. {
  28862. voice->stopNote (allowTailOff);
  28863. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  28864. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  28865. }
  28866. }
  28867. }
  28868. }
  28869. void Synthesiser::allNotesOff (const int midiChannel,
  28870. const bool allowTailOff)
  28871. {
  28872. const ScopedLock sl (lock);
  28873. for (int i = voices.size(); --i >= 0;)
  28874. {
  28875. SynthesiserVoice* const voice = voices.getUnchecked (i);
  28876. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  28877. voice->stopNote (allowTailOff);
  28878. }
  28879. }
  28880. void Synthesiser::handlePitchWheel (const int midiChannel,
  28881. const int wheelValue)
  28882. {
  28883. const ScopedLock sl (lock);
  28884. for (int i = voices.size(); --i >= 0;)
  28885. {
  28886. SynthesiserVoice* const voice = voices.getUnchecked (i);
  28887. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  28888. {
  28889. voice->pitchWheelMoved (wheelValue);
  28890. }
  28891. }
  28892. }
  28893. void Synthesiser::handleController (const int midiChannel,
  28894. const int controllerNumber,
  28895. const int controllerValue)
  28896. {
  28897. const ScopedLock sl (lock);
  28898. for (int i = voices.size(); --i >= 0;)
  28899. {
  28900. SynthesiserVoice* const voice = voices.getUnchecked (i);
  28901. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  28902. voice->controllerMoved (controllerNumber, controllerValue);
  28903. }
  28904. }
  28905. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  28906. const bool stealIfNoneAvailable) const
  28907. {
  28908. const ScopedLock sl (lock);
  28909. for (int i = voices.size(); --i >= 0;)
  28910. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  28911. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  28912. return voices.getUnchecked (i);
  28913. if (stealIfNoneAvailable)
  28914. {
  28915. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  28916. SynthesiserVoice* oldest = 0;
  28917. for (int i = voices.size(); --i >= 0;)
  28918. {
  28919. SynthesiserVoice* const voice = voices.getUnchecked (i);
  28920. if (voice->canPlaySound (soundToPlay)
  28921. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  28922. oldest = voice;
  28923. }
  28924. jassert (oldest != 0);
  28925. return oldest;
  28926. }
  28927. return 0;
  28928. }
  28929. END_JUCE_NAMESPACE
  28930. /********* End of inlined file: juce_Synthesiser.cpp *********/
  28931. /********* Start of inlined file: juce_ActionBroadcaster.cpp *********/
  28932. BEGIN_JUCE_NAMESPACE
  28933. ActionBroadcaster::ActionBroadcaster() throw()
  28934. {
  28935. // are you trying to create this object before or after juce has been intialised??
  28936. jassert (MessageManager::instance != 0);
  28937. }
  28938. ActionBroadcaster::~ActionBroadcaster()
  28939. {
  28940. // all event-based objects must be deleted BEFORE juce is shut down!
  28941. jassert (MessageManager::instance != 0);
  28942. }
  28943. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  28944. {
  28945. actionListenerList.addActionListener (listener);
  28946. }
  28947. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  28948. {
  28949. jassert (actionListenerList.isValidMessageListener());
  28950. if (actionListenerList.isValidMessageListener())
  28951. actionListenerList.removeActionListener (listener);
  28952. }
  28953. void ActionBroadcaster::removeAllActionListeners()
  28954. {
  28955. actionListenerList.removeAllActionListeners();
  28956. }
  28957. void ActionBroadcaster::sendActionMessage (const String& message) const
  28958. {
  28959. actionListenerList.sendActionMessage (message);
  28960. }
  28961. END_JUCE_NAMESPACE
  28962. /********* End of inlined file: juce_ActionBroadcaster.cpp *********/
  28963. /********* Start of inlined file: juce_ActionListenerList.cpp *********/
  28964. BEGIN_JUCE_NAMESPACE
  28965. // special message of our own with a string in it
  28966. class ActionMessage : public Message
  28967. {
  28968. public:
  28969. const String message;
  28970. ActionMessage (const String& messageText,
  28971. void* const listener_) throw()
  28972. : message (messageText)
  28973. {
  28974. pointerParameter = listener_;
  28975. }
  28976. ~ActionMessage() throw()
  28977. {
  28978. }
  28979. private:
  28980. ActionMessage (const ActionMessage&);
  28981. const ActionMessage& operator= (const ActionMessage&);
  28982. };
  28983. ActionListenerList::ActionListenerList() throw()
  28984. {
  28985. }
  28986. ActionListenerList::~ActionListenerList() throw()
  28987. {
  28988. }
  28989. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  28990. {
  28991. const ScopedLock sl (actionListenerLock_);
  28992. jassert (listener != 0);
  28993. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  28994. if (listener != 0)
  28995. actionListeners_.add (listener);
  28996. }
  28997. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  28998. {
  28999. const ScopedLock sl (actionListenerLock_);
  29000. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29001. actionListeners_.removeValue (listener);
  29002. }
  29003. void ActionListenerList::removeAllActionListeners() throw()
  29004. {
  29005. const ScopedLock sl (actionListenerLock_);
  29006. actionListeners_.clear();
  29007. }
  29008. void ActionListenerList::sendActionMessage (const String& message) const
  29009. {
  29010. const ScopedLock sl (actionListenerLock_);
  29011. for (int i = actionListeners_.size(); --i >= 0;)
  29012. {
  29013. postMessage (new ActionMessage (message,
  29014. (ActionListener*) actionListeners_.getUnchecked(i)));
  29015. }
  29016. }
  29017. void ActionListenerList::handleMessage (const Message& message)
  29018. {
  29019. const ActionMessage& am = (const ActionMessage&) message;
  29020. if (actionListeners_.contains (am.pointerParameter))
  29021. ((ActionListener*) am.pointerParameter)->actionListenerCallback (am.message);
  29022. }
  29023. END_JUCE_NAMESPACE
  29024. /********* End of inlined file: juce_ActionListenerList.cpp *********/
  29025. /********* Start of inlined file: juce_AsyncUpdater.cpp *********/
  29026. BEGIN_JUCE_NAMESPACE
  29027. AsyncUpdater::AsyncUpdater() throw()
  29028. : asyncMessagePending (false)
  29029. {
  29030. internalAsyncHandler.owner = this;
  29031. }
  29032. AsyncUpdater::~AsyncUpdater()
  29033. {
  29034. }
  29035. void AsyncUpdater::triggerAsyncUpdate() throw()
  29036. {
  29037. if (! asyncMessagePending)
  29038. {
  29039. asyncMessagePending = true;
  29040. internalAsyncHandler.postMessage (new Message());
  29041. }
  29042. }
  29043. void AsyncUpdater::cancelPendingUpdate() throw()
  29044. {
  29045. asyncMessagePending = false;
  29046. }
  29047. void AsyncUpdater::handleUpdateNowIfNeeded()
  29048. {
  29049. if (asyncMessagePending)
  29050. {
  29051. asyncMessagePending = false;
  29052. handleAsyncUpdate();
  29053. }
  29054. }
  29055. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29056. {
  29057. owner->handleUpdateNowIfNeeded();
  29058. }
  29059. END_JUCE_NAMESPACE
  29060. /********* End of inlined file: juce_AsyncUpdater.cpp *********/
  29061. /********* Start of inlined file: juce_ChangeBroadcaster.cpp *********/
  29062. BEGIN_JUCE_NAMESPACE
  29063. ChangeBroadcaster::ChangeBroadcaster() throw()
  29064. {
  29065. // are you trying to create this object before or after juce has been intialised??
  29066. jassert (MessageManager::instance != 0);
  29067. }
  29068. ChangeBroadcaster::~ChangeBroadcaster()
  29069. {
  29070. // all event-based objects must be deleted BEFORE juce is shut down!
  29071. jassert (MessageManager::instance != 0);
  29072. }
  29073. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29074. {
  29075. changeListenerList.addChangeListener (listener);
  29076. }
  29077. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29078. {
  29079. jassert (changeListenerList.isValidMessageListener());
  29080. if (changeListenerList.isValidMessageListener())
  29081. changeListenerList.removeChangeListener (listener);
  29082. }
  29083. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29084. {
  29085. changeListenerList.removeAllChangeListeners();
  29086. }
  29087. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29088. {
  29089. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29090. }
  29091. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29092. {
  29093. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29094. }
  29095. void ChangeBroadcaster::dispatchPendingMessages()
  29096. {
  29097. changeListenerList.dispatchPendingMessages();
  29098. }
  29099. END_JUCE_NAMESPACE
  29100. /********* End of inlined file: juce_ChangeBroadcaster.cpp *********/
  29101. /********* Start of inlined file: juce_ChangeListenerList.cpp *********/
  29102. BEGIN_JUCE_NAMESPACE
  29103. ChangeListenerList::ChangeListenerList() throw()
  29104. : lastChangedObject (0),
  29105. messagePending (false)
  29106. {
  29107. }
  29108. ChangeListenerList::~ChangeListenerList() throw()
  29109. {
  29110. }
  29111. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  29112. {
  29113. const ScopedLock sl (lock);
  29114. jassert (listener != 0);
  29115. if (listener != 0)
  29116. listeners.add (listener);
  29117. }
  29118. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  29119. {
  29120. const ScopedLock sl (lock);
  29121. listeners.removeValue (listener);
  29122. }
  29123. void ChangeListenerList::removeAllChangeListeners() throw()
  29124. {
  29125. const ScopedLock sl (lock);
  29126. listeners.clear();
  29127. }
  29128. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  29129. {
  29130. const ScopedLock sl (lock);
  29131. if ((! messagePending) && (listeners.size() > 0))
  29132. {
  29133. lastChangedObject = objectThatHasChanged;
  29134. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  29135. messagePending = true;
  29136. }
  29137. }
  29138. void ChangeListenerList::handleMessage (const Message& message)
  29139. {
  29140. sendSynchronousChangeMessage (message.pointerParameter);
  29141. }
  29142. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  29143. {
  29144. const ScopedLock sl (lock);
  29145. messagePending = false;
  29146. for (int i = listeners.size(); --i >= 0;)
  29147. {
  29148. ChangeListener* const l = (ChangeListener*) listeners.getUnchecked (i);
  29149. {
  29150. const ScopedUnlock tempUnlocker (lock);
  29151. l->changeListenerCallback (objectThatHasChanged);
  29152. }
  29153. i = jmin (i, listeners.size());
  29154. }
  29155. }
  29156. void ChangeListenerList::dispatchPendingMessages()
  29157. {
  29158. if (messagePending)
  29159. sendSynchronousChangeMessage (lastChangedObject);
  29160. }
  29161. END_JUCE_NAMESPACE
  29162. /********* End of inlined file: juce_ChangeListenerList.cpp *********/
  29163. /********* Start of inlined file: juce_InterprocessConnection.cpp *********/
  29164. BEGIN_JUCE_NAMESPACE
  29165. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  29166. const uint32 magicMessageHeaderNumber)
  29167. : Thread ("Juce IPC connection"),
  29168. socket (0),
  29169. pipe (0),
  29170. callbackConnectionState (false),
  29171. useMessageThread (callbacksOnMessageThread),
  29172. magicMessageHeader (magicMessageHeaderNumber),
  29173. pipeReceiveMessageTimeout (-1)
  29174. {
  29175. }
  29176. InterprocessConnection::~InterprocessConnection()
  29177. {
  29178. callbackConnectionState = false;
  29179. disconnect();
  29180. }
  29181. bool InterprocessConnection::connectToSocket (const String& hostName,
  29182. const int portNumber,
  29183. const int timeOutMillisecs)
  29184. {
  29185. disconnect();
  29186. const ScopedLock sl (pipeAndSocketLock);
  29187. socket = new StreamingSocket();
  29188. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  29189. {
  29190. connectionMadeInt();
  29191. startThread();
  29192. return true;
  29193. }
  29194. else
  29195. {
  29196. deleteAndZero (socket);
  29197. return false;
  29198. }
  29199. }
  29200. bool InterprocessConnection::connectToPipe (const String& pipeName,
  29201. const int pipeReceiveMessageTimeoutMs)
  29202. {
  29203. disconnect();
  29204. NamedPipe* const newPipe = new NamedPipe();
  29205. if (newPipe->openExisting (pipeName))
  29206. {
  29207. const ScopedLock sl (pipeAndSocketLock);
  29208. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  29209. initialiseWithPipe (newPipe);
  29210. return true;
  29211. }
  29212. else
  29213. {
  29214. delete newPipe;
  29215. return false;
  29216. }
  29217. }
  29218. bool InterprocessConnection::createPipe (const String& pipeName,
  29219. const int pipeReceiveMessageTimeoutMs)
  29220. {
  29221. disconnect();
  29222. NamedPipe* const newPipe = new NamedPipe();
  29223. if (newPipe->createNewPipe (pipeName))
  29224. {
  29225. const ScopedLock sl (pipeAndSocketLock);
  29226. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  29227. initialiseWithPipe (newPipe);
  29228. return true;
  29229. }
  29230. else
  29231. {
  29232. delete newPipe;
  29233. return false;
  29234. }
  29235. }
  29236. void InterprocessConnection::disconnect()
  29237. {
  29238. if (socket != 0)
  29239. socket->close();
  29240. if (pipe != 0)
  29241. {
  29242. pipe->cancelPendingReads();
  29243. pipe->close();
  29244. }
  29245. stopThread (4000);
  29246. {
  29247. const ScopedLock sl (pipeAndSocketLock);
  29248. deleteAndZero (socket);
  29249. deleteAndZero (pipe);
  29250. }
  29251. connectionLostInt();
  29252. }
  29253. bool InterprocessConnection::isConnected() const
  29254. {
  29255. const ScopedLock sl (pipeAndSocketLock);
  29256. return ((socket != 0 && socket->isConnected())
  29257. || (pipe != 0 && pipe->isOpen()))
  29258. && isThreadRunning();
  29259. }
  29260. const String InterprocessConnection::getConnectedHostName() const
  29261. {
  29262. if (pipe != 0)
  29263. {
  29264. return "localhost";
  29265. }
  29266. else if (socket != 0)
  29267. {
  29268. if (! socket->isLocal())
  29269. return socket->getHostName();
  29270. return "localhost";
  29271. }
  29272. return String::empty;
  29273. }
  29274. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  29275. {
  29276. uint32 messageHeader[2];
  29277. messageHeader [0] = swapIfBigEndian (magicMessageHeader);
  29278. messageHeader [1] = swapIfBigEndian ((uint32) message.getSize());
  29279. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  29280. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  29281. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  29282. int bytesWritten = 0;
  29283. const ScopedLock sl (pipeAndSocketLock);
  29284. if (socket != 0)
  29285. {
  29286. bytesWritten = socket->write (messageData.getData(), messageData.getSize());
  29287. }
  29288. else if (pipe != 0)
  29289. {
  29290. bytesWritten = pipe->write (messageData.getData(), messageData.getSize());
  29291. }
  29292. if (bytesWritten < 0)
  29293. {
  29294. // error..
  29295. return false;
  29296. }
  29297. return (bytesWritten == messageData.getSize());
  29298. }
  29299. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  29300. {
  29301. jassert (socket == 0);
  29302. socket = socket_;
  29303. connectionMadeInt();
  29304. startThread();
  29305. }
  29306. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  29307. {
  29308. jassert (pipe == 0);
  29309. pipe = pipe_;
  29310. connectionMadeInt();
  29311. startThread();
  29312. }
  29313. const int messageMagicNumber = 0xb734128b;
  29314. void InterprocessConnection::handleMessage (const Message& message)
  29315. {
  29316. if (message.intParameter1 == messageMagicNumber)
  29317. {
  29318. switch (message.intParameter2)
  29319. {
  29320. case 0:
  29321. {
  29322. MemoryBlock* const data = (MemoryBlock*) message.pointerParameter;
  29323. messageReceived (*data);
  29324. delete data;
  29325. break;
  29326. }
  29327. case 1:
  29328. connectionMade();
  29329. break;
  29330. case 2:
  29331. connectionLost();
  29332. break;
  29333. }
  29334. }
  29335. }
  29336. void InterprocessConnection::connectionMadeInt()
  29337. {
  29338. if (! callbackConnectionState)
  29339. {
  29340. callbackConnectionState = true;
  29341. if (useMessageThread)
  29342. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  29343. else
  29344. connectionMade();
  29345. }
  29346. }
  29347. void InterprocessConnection::connectionLostInt()
  29348. {
  29349. if (callbackConnectionState)
  29350. {
  29351. callbackConnectionState = false;
  29352. if (useMessageThread)
  29353. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  29354. else
  29355. connectionLost();
  29356. }
  29357. }
  29358. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  29359. {
  29360. jassert (callbackConnectionState);
  29361. if (useMessageThread)
  29362. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  29363. else
  29364. messageReceived (data);
  29365. }
  29366. bool InterprocessConnection::readNextMessageInt()
  29367. {
  29368. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  29369. uint32 messageHeader[2];
  29370. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  29371. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  29372. if (bytes == sizeof (messageHeader)
  29373. && swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  29374. {
  29375. const int bytesInMessage = (int) swapIfBigEndian (messageHeader[1]);
  29376. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  29377. {
  29378. MemoryBlock messageData (bytesInMessage, true);
  29379. int bytesRead = 0;
  29380. while (bytesRead < bytesInMessage)
  29381. {
  29382. if (threadShouldExit())
  29383. return false;
  29384. const int numThisTime = jmin (bytesInMessage, 65536);
  29385. const int bytesIn = (socket != 0) ? socket->read (((char*) messageData.getData()) + bytesRead, numThisTime, true)
  29386. : pipe->read (((char*) messageData.getData()) + bytesRead, numThisTime,
  29387. pipeReceiveMessageTimeout);
  29388. if (bytesIn <= 0)
  29389. break;
  29390. bytesRead += bytesIn;
  29391. }
  29392. if (bytesRead >= 0)
  29393. deliverDataInt (messageData);
  29394. }
  29395. }
  29396. else if (bytes < 0)
  29397. {
  29398. {
  29399. const ScopedLock sl (pipeAndSocketLock);
  29400. deleteAndZero (socket);
  29401. }
  29402. connectionLostInt();
  29403. return false;
  29404. }
  29405. return true;
  29406. }
  29407. void InterprocessConnection::run()
  29408. {
  29409. while (! threadShouldExit())
  29410. {
  29411. if (socket != 0)
  29412. {
  29413. const int ready = socket->waitUntilReady (true, 0);
  29414. if (ready < 0)
  29415. {
  29416. {
  29417. const ScopedLock sl (pipeAndSocketLock);
  29418. deleteAndZero (socket);
  29419. }
  29420. connectionLostInt();
  29421. break;
  29422. }
  29423. else if (ready > 0)
  29424. {
  29425. if (! readNextMessageInt())
  29426. break;
  29427. }
  29428. else
  29429. {
  29430. Thread::sleep (2);
  29431. }
  29432. }
  29433. else if (pipe != 0)
  29434. {
  29435. if (! pipe->isOpen())
  29436. {
  29437. {
  29438. const ScopedLock sl (pipeAndSocketLock);
  29439. deleteAndZero (pipe);
  29440. }
  29441. connectionLostInt();
  29442. break;
  29443. }
  29444. else
  29445. {
  29446. if (! readNextMessageInt())
  29447. break;
  29448. }
  29449. }
  29450. else
  29451. {
  29452. break;
  29453. }
  29454. }
  29455. }
  29456. END_JUCE_NAMESPACE
  29457. /********* End of inlined file: juce_InterprocessConnection.cpp *********/
  29458. /********* Start of inlined file: juce_InterprocessConnectionServer.cpp *********/
  29459. BEGIN_JUCE_NAMESPACE
  29460. InterprocessConnectionServer::InterprocessConnectionServer()
  29461. : Thread ("Juce IPC server"),
  29462. socket (0)
  29463. {
  29464. }
  29465. InterprocessConnectionServer::~InterprocessConnectionServer()
  29466. {
  29467. stop();
  29468. }
  29469. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  29470. {
  29471. stop();
  29472. socket = new StreamingSocket();
  29473. if (socket->createListener (portNumber))
  29474. {
  29475. startThread();
  29476. return true;
  29477. }
  29478. deleteAndZero (socket);
  29479. return false;
  29480. }
  29481. void InterprocessConnectionServer::stop()
  29482. {
  29483. signalThreadShouldExit();
  29484. if (socket != 0)
  29485. socket->close();
  29486. stopThread (4000);
  29487. deleteAndZero (socket);
  29488. }
  29489. void InterprocessConnectionServer::run()
  29490. {
  29491. while ((! threadShouldExit()) && socket != 0)
  29492. {
  29493. StreamingSocket* const clientSocket = socket->waitForNextConnection();
  29494. if (clientSocket != 0)
  29495. {
  29496. InterprocessConnection* newConnection = createConnectionObject();
  29497. if (newConnection != 0)
  29498. {
  29499. newConnection->initialiseWithSocket (clientSocket);
  29500. }
  29501. else
  29502. {
  29503. delete clientSocket;
  29504. }
  29505. }
  29506. }
  29507. }
  29508. END_JUCE_NAMESPACE
  29509. /********* End of inlined file: juce_InterprocessConnectionServer.cpp *********/
  29510. /********* Start of inlined file: juce_Message.cpp *********/
  29511. BEGIN_JUCE_NAMESPACE
  29512. Message::Message() throw()
  29513. {
  29514. }
  29515. Message::~Message() throw()
  29516. {
  29517. }
  29518. Message::Message (const int intParameter1_,
  29519. const int intParameter2_,
  29520. const int intParameter3_,
  29521. void* const pointerParameter_) throw()
  29522. : intParameter1 (intParameter1_),
  29523. intParameter2 (intParameter2_),
  29524. intParameter3 (intParameter3_),
  29525. pointerParameter (pointerParameter_)
  29526. {
  29527. }
  29528. END_JUCE_NAMESPACE
  29529. /********* End of inlined file: juce_Message.cpp *********/
  29530. /********* Start of inlined file: juce_MessageListener.cpp *********/
  29531. BEGIN_JUCE_NAMESPACE
  29532. MessageListener::MessageListener() throw()
  29533. {
  29534. // are you trying to create a messagelistener before or after juce has been intialised??
  29535. jassert (MessageManager::instance != 0);
  29536. if (MessageManager::instance != 0)
  29537. MessageManager::instance->messageListeners.add (this);
  29538. }
  29539. MessageListener::~MessageListener()
  29540. {
  29541. if (MessageManager::instance != 0)
  29542. MessageManager::instance->messageListeners.removeValue (this);
  29543. }
  29544. void MessageListener::postMessage (Message* const message) const throw()
  29545. {
  29546. message->messageRecipient = const_cast <MessageListener*> (this);
  29547. if (MessageManager::instance == 0)
  29548. MessageManager::getInstance();
  29549. MessageManager::instance->postMessageToQueue (message);
  29550. }
  29551. bool MessageListener::isValidMessageListener() const throw()
  29552. {
  29553. return (MessageManager::instance != 0)
  29554. && MessageManager::instance->messageListeners.contains (this);
  29555. }
  29556. END_JUCE_NAMESPACE
  29557. /********* End of inlined file: juce_MessageListener.cpp *********/
  29558. /********* Start of inlined file: juce_MessageManager.cpp *********/
  29559. BEGIN_JUCE_NAMESPACE
  29560. // platform-specific functions..
  29561. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  29562. bool juce_postMessageToSystemQueue (void* message);
  29563. MessageManager* MessageManager::instance = 0;
  29564. static const int quitMessageId = 0xfffff321;
  29565. MessageManager::MessageManager() throw()
  29566. : broadcastListeners (0),
  29567. quitMessagePosted (false),
  29568. quitMessageReceived (false),
  29569. threadWithLock (0)
  29570. {
  29571. messageThreadId = Thread::getCurrentThreadId();
  29572. }
  29573. MessageManager::~MessageManager() throw()
  29574. {
  29575. deleteAndZero (broadcastListeners);
  29576. doPlatformSpecificShutdown();
  29577. jassert (instance == this);
  29578. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  29579. }
  29580. MessageManager* MessageManager::getInstance() throw()
  29581. {
  29582. if (instance == 0)
  29583. {
  29584. instance = new MessageManager();
  29585. doPlatformSpecificInitialisation();
  29586. }
  29587. return instance;
  29588. }
  29589. void MessageManager::postMessageToQueue (Message* const message)
  29590. {
  29591. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  29592. delete message;
  29593. }
  29594. CallbackMessage::CallbackMessage() throw() {}
  29595. CallbackMessage::~CallbackMessage() throw() {}
  29596. void CallbackMessage::post()
  29597. {
  29598. if (MessageManager::instance != 0)
  29599. MessageManager::instance->postCallbackMessage (this);
  29600. }
  29601. void MessageManager::postCallbackMessage (Message* const message)
  29602. {
  29603. message->messageRecipient = 0;
  29604. postMessageToQueue (message);
  29605. }
  29606. // not for public use..
  29607. void MessageManager::deliverMessage (void* message)
  29608. {
  29609. Message* const m = (Message*) message;
  29610. MessageListener* const recipient = m->messageRecipient;
  29611. JUCE_TRY
  29612. {
  29613. if (messageListeners.contains (recipient))
  29614. {
  29615. recipient->handleMessage (*m);
  29616. }
  29617. else if (recipient == 0)
  29618. {
  29619. if (m->intParameter1 == quitMessageId)
  29620. {
  29621. quitMessageReceived = true;
  29622. }
  29623. else if (dynamic_cast <CallbackMessage*> (m) != 0)
  29624. {
  29625. (dynamic_cast <CallbackMessage*> (m))->messageCallback();
  29626. }
  29627. }
  29628. }
  29629. JUCE_CATCH_EXCEPTION
  29630. delete m;
  29631. }
  29632. #if ! JUCE_MAC
  29633. void MessageManager::runDispatchLoop()
  29634. {
  29635. jassert (isThisTheMessageThread()); // must only be called by the message thread
  29636. runDispatchLoopUntil (-1);
  29637. }
  29638. void MessageManager::stopDispatchLoop()
  29639. {
  29640. Message* const m = new Message (quitMessageId, 0, 0, 0);
  29641. m->messageRecipient = 0;
  29642. postMessageToQueue (m);
  29643. quitMessagePosted = true;
  29644. }
  29645. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  29646. {
  29647. jassert (isThisTheMessageThread()); // must only be called by the message thread
  29648. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  29649. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  29650. && ! quitMessageReceived)
  29651. {
  29652. JUCE_TRY
  29653. {
  29654. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  29655. {
  29656. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  29657. if (msToWait > 0)
  29658. Thread::sleep (jmin (5, msToWait));
  29659. }
  29660. }
  29661. JUCE_CATCH_EXCEPTION
  29662. }
  29663. return ! quitMessageReceived;
  29664. }
  29665. #endif
  29666. void MessageManager::deliverBroadcastMessage (const String& value)
  29667. {
  29668. if (broadcastListeners != 0)
  29669. broadcastListeners->sendActionMessage (value);
  29670. }
  29671. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  29672. {
  29673. if (broadcastListeners == 0)
  29674. broadcastListeners = new ActionListenerList();
  29675. broadcastListeners->addActionListener (listener);
  29676. }
  29677. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  29678. {
  29679. if (broadcastListeners != 0)
  29680. broadcastListeners->removeActionListener (listener);
  29681. }
  29682. bool MessageManager::isThisTheMessageThread() const throw()
  29683. {
  29684. return Thread::getCurrentThreadId() == messageThreadId;
  29685. }
  29686. void MessageManager::setCurrentMessageThread (const Thread::ThreadID threadId) throw()
  29687. {
  29688. messageThreadId = threadId;
  29689. }
  29690. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  29691. {
  29692. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  29693. return thisThread == messageThreadId || thisThread == threadWithLock;
  29694. }
  29695. /* The only safe way to lock the message thread while another thread does
  29696. some work is by posting a special message, whose purpose is to tie up the event
  29697. loop until the other thread has finished its business.
  29698. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  29699. get locked before making an event callback, because if the same OS lock gets indirectly
  29700. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  29701. in Cocoa).
  29702. */
  29703. class SharedLockingEvents : public ReferenceCountedObject
  29704. {
  29705. public:
  29706. SharedLockingEvents() throw() {}
  29707. ~SharedLockingEvents() {}
  29708. /* This class just holds a couple of events to communicate between the MMLockMessage
  29709. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  29710. this shared data must be kept in a separate, ref-counted container. */
  29711. WaitableEvent lockedEvent, releaseEvent;
  29712. };
  29713. class MMLockMessage : public CallbackMessage
  29714. {
  29715. public:
  29716. MMLockMessage (SharedLockingEvents* const events_) throw()
  29717. : events (events_)
  29718. {}
  29719. ~MMLockMessage() throw() {}
  29720. ReferenceCountedObjectPtr <SharedLockingEvents> events;
  29721. void messageCallback()
  29722. {
  29723. events->lockedEvent.signal();
  29724. events->releaseEvent.wait();
  29725. }
  29726. juce_UseDebuggingNewOperator
  29727. MMLockMessage (const MMLockMessage&);
  29728. const MMLockMessage& operator= (const MMLockMessage&);
  29729. };
  29730. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  29731. : locked (false),
  29732. needsUnlocking (false)
  29733. {
  29734. init (threadToCheck, 0);
  29735. }
  29736. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  29737. : locked (false),
  29738. needsUnlocking (false)
  29739. {
  29740. init (0, jobToCheckForExitSignal);
  29741. }
  29742. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  29743. {
  29744. if (MessageManager::instance != 0)
  29745. {
  29746. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  29747. {
  29748. locked = true; // either we're on the message thread, or this is a re-entrant call.
  29749. }
  29750. else
  29751. {
  29752. if (threadToCheck == 0 && job == 0)
  29753. {
  29754. MessageManager::instance->lockingLock.enter();
  29755. }
  29756. else
  29757. {
  29758. while (! MessageManager::instance->lockingLock.tryEnter())
  29759. {
  29760. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  29761. || (job != 0 && job->shouldExit()))
  29762. return;
  29763. Thread::sleep (1);
  29764. }
  29765. }
  29766. SharedLockingEvents* const events = new SharedLockingEvents();
  29767. sharedEvents = events;
  29768. events->incReferenceCount();
  29769. (new MMLockMessage (events))->post();
  29770. while (! events->lockedEvent.wait (50))
  29771. {
  29772. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  29773. || (job != 0 && job->shouldExit()))
  29774. {
  29775. events->releaseEvent.signal();
  29776. events->decReferenceCount();
  29777. MessageManager::instance->lockingLock.exit();
  29778. return;
  29779. }
  29780. }
  29781. jassert (MessageManager::instance->threadWithLock == 0);
  29782. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  29783. locked = true;
  29784. needsUnlocking = true;
  29785. }
  29786. }
  29787. }
  29788. MessageManagerLock::~MessageManagerLock() throw()
  29789. {
  29790. if (needsUnlocking && MessageManager::instance != 0)
  29791. {
  29792. jassert (MessageManager::instance->currentThreadHasLockedMessageManager());
  29793. ((SharedLockingEvents*) sharedEvents)->releaseEvent.signal();
  29794. ((SharedLockingEvents*) sharedEvents)->decReferenceCount();
  29795. MessageManager::instance->threadWithLock = 0;
  29796. MessageManager::instance->lockingLock.exit();
  29797. }
  29798. }
  29799. END_JUCE_NAMESPACE
  29800. /********* End of inlined file: juce_MessageManager.cpp *********/
  29801. /********* Start of inlined file: juce_MultiTimer.cpp *********/
  29802. BEGIN_JUCE_NAMESPACE
  29803. class InternalMultiTimerCallback : public Timer
  29804. {
  29805. public:
  29806. InternalMultiTimerCallback (const int timerId_, MultiTimer& owner_)
  29807. : timerId (timerId_),
  29808. owner (owner_)
  29809. {
  29810. }
  29811. ~InternalMultiTimerCallback()
  29812. {
  29813. }
  29814. void timerCallback()
  29815. {
  29816. owner.timerCallback (timerId);
  29817. }
  29818. const int timerId;
  29819. private:
  29820. MultiTimer& owner;
  29821. };
  29822. MultiTimer::MultiTimer() throw()
  29823. {
  29824. }
  29825. MultiTimer::MultiTimer (const MultiTimer&) throw()
  29826. {
  29827. }
  29828. MultiTimer::~MultiTimer()
  29829. {
  29830. const ScopedLock sl (timerListLock);
  29831. for (int i = timers.size(); --i >= 0;)
  29832. delete (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29833. timers.clear();
  29834. }
  29835. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  29836. {
  29837. const ScopedLock sl (timerListLock);
  29838. for (int i = timers.size(); --i >= 0;)
  29839. {
  29840. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29841. if (t->timerId == timerId)
  29842. {
  29843. t->startTimer (intervalInMilliseconds);
  29844. return;
  29845. }
  29846. }
  29847. InternalMultiTimerCallback* const newTimer = new InternalMultiTimerCallback (timerId, *this);
  29848. timers.add (newTimer);
  29849. newTimer->startTimer (intervalInMilliseconds);
  29850. }
  29851. void MultiTimer::stopTimer (const int timerId) throw()
  29852. {
  29853. const ScopedLock sl (timerListLock);
  29854. for (int i = timers.size(); --i >= 0;)
  29855. {
  29856. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29857. if (t->timerId == timerId)
  29858. t->stopTimer();
  29859. }
  29860. }
  29861. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  29862. {
  29863. const ScopedLock sl (timerListLock);
  29864. for (int i = timers.size(); --i >= 0;)
  29865. {
  29866. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29867. if (t->timerId == timerId)
  29868. return t->isTimerRunning();
  29869. }
  29870. return false;
  29871. }
  29872. int MultiTimer::getTimerInterval (const int timerId) const throw()
  29873. {
  29874. const ScopedLock sl (timerListLock);
  29875. for (int i = timers.size(); --i >= 0;)
  29876. {
  29877. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29878. if (t->timerId == timerId)
  29879. return t->getTimerInterval();
  29880. }
  29881. return 0;
  29882. }
  29883. END_JUCE_NAMESPACE
  29884. /********* End of inlined file: juce_MultiTimer.cpp *********/
  29885. /********* Start of inlined file: juce_Timer.cpp *********/
  29886. BEGIN_JUCE_NAMESPACE
  29887. class InternalTimerThread : private Thread,
  29888. private MessageListener,
  29889. private DeletedAtShutdown,
  29890. private AsyncUpdater
  29891. {
  29892. private:
  29893. friend class Timer;
  29894. static InternalTimerThread* instance;
  29895. static CriticalSection lock;
  29896. Timer* volatile firstTimer;
  29897. bool volatile callbackNeeded;
  29898. InternalTimerThread (const InternalTimerThread&);
  29899. const InternalTimerThread& operator= (const InternalTimerThread&);
  29900. void addTimer (Timer* const t) throw()
  29901. {
  29902. #ifdef JUCE_DEBUG
  29903. Timer* tt = firstTimer;
  29904. while (tt != 0)
  29905. {
  29906. // trying to add a timer that's already here - shouldn't get to this point,
  29907. // so if you get this assertion, let me know!
  29908. jassert (tt != t);
  29909. tt = tt->next;
  29910. }
  29911. jassert (t->previous == 0 && t->next == 0);
  29912. #endif
  29913. Timer* i = firstTimer;
  29914. if (i == 0 || i->countdownMs > t->countdownMs)
  29915. {
  29916. t->next = firstTimer;
  29917. firstTimer = t;
  29918. }
  29919. else
  29920. {
  29921. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  29922. i = i->next;
  29923. jassert (i != 0);
  29924. t->next = i->next;
  29925. t->previous = i;
  29926. i->next = t;
  29927. }
  29928. if (t->next != 0)
  29929. t->next->previous = t;
  29930. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  29931. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  29932. notify();
  29933. }
  29934. void removeTimer (Timer* const t) throw()
  29935. {
  29936. #ifdef JUCE_DEBUG
  29937. Timer* tt = firstTimer;
  29938. bool found = false;
  29939. while (tt != 0)
  29940. {
  29941. if (tt == t)
  29942. {
  29943. found = true;
  29944. break;
  29945. }
  29946. tt = tt->next;
  29947. }
  29948. // trying to remove a timer that's not here - shouldn't get to this point,
  29949. // so if you get this assertion, let me know!
  29950. jassert (found);
  29951. #endif
  29952. if (t->previous != 0)
  29953. {
  29954. jassert (firstTimer != t);
  29955. t->previous->next = t->next;
  29956. }
  29957. else
  29958. {
  29959. jassert (firstTimer == t);
  29960. firstTimer = t->next;
  29961. }
  29962. if (t->next != 0)
  29963. t->next->previous = t->previous;
  29964. t->next = 0;
  29965. t->previous = 0;
  29966. }
  29967. void decrementAllCounters (const int numMillisecs) const
  29968. {
  29969. Timer* t = firstTimer;
  29970. while (t != 0)
  29971. {
  29972. t->countdownMs -= numMillisecs;
  29973. t = t->next;
  29974. }
  29975. }
  29976. void handleAsyncUpdate()
  29977. {
  29978. startThread (7);
  29979. }
  29980. public:
  29981. InternalTimerThread()
  29982. : Thread ("Juce Timer"),
  29983. firstTimer (0),
  29984. callbackNeeded (false)
  29985. {
  29986. triggerAsyncUpdate();
  29987. }
  29988. ~InternalTimerThread() throw()
  29989. {
  29990. stopThread (4000);
  29991. jassert (instance == this || instance == 0);
  29992. if (instance == this)
  29993. instance = 0;
  29994. }
  29995. void run()
  29996. {
  29997. uint32 lastTime = Time::getMillisecondCounter();
  29998. while (! threadShouldExit())
  29999. {
  30000. uint32 now = Time::getMillisecondCounter();
  30001. if (now <= lastTime)
  30002. {
  30003. wait (2);
  30004. continue;
  30005. }
  30006. const int elapsed = now - lastTime;
  30007. lastTime = now;
  30008. lock.enter();
  30009. decrementAllCounters (elapsed);
  30010. const int timeUntilFirstTimer = (firstTimer != 0) ? firstTimer->countdownMs
  30011. : 1000;
  30012. lock.exit();
  30013. if (timeUntilFirstTimer <= 0)
  30014. {
  30015. callbackNeeded = true;
  30016. postMessage (new Message());
  30017. // sometimes, our message could get discarded by the OS (particularly when running as an RTAS when the app has a modal loop),
  30018. // so this is how long to wait before assuming the message has been lost and trying again.
  30019. const uint32 messageDeliveryTimeout = now + 2000;
  30020. while (callbackNeeded)
  30021. {
  30022. wait (4);
  30023. if (threadShouldExit())
  30024. return;
  30025. now = Time::getMillisecondCounter();
  30026. if (now > messageDeliveryTimeout)
  30027. break;
  30028. }
  30029. }
  30030. else
  30031. {
  30032. // don't wait for too long because running this loop also helps keep the
  30033. // Time::getApproximateMillisecondTimer value stay up-to-date
  30034. wait (jlimit (1, 50, timeUntilFirstTimer));
  30035. }
  30036. }
  30037. }
  30038. void handleMessage (const Message&)
  30039. {
  30040. const ScopedLock sl (lock);
  30041. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30042. {
  30043. Timer* const t = firstTimer;
  30044. t->countdownMs = t->periodMs;
  30045. removeTimer (t);
  30046. addTimer (t);
  30047. const ScopedUnlock ul (lock);
  30048. JUCE_TRY
  30049. {
  30050. t->timerCallback();
  30051. }
  30052. JUCE_CATCH_EXCEPTION
  30053. }
  30054. callbackNeeded = false;
  30055. }
  30056. static void callAnyTimersSynchronously()
  30057. {
  30058. if (InternalTimerThread::instance != 0)
  30059. {
  30060. const Message m;
  30061. InternalTimerThread::instance->handleMessage (m);
  30062. }
  30063. }
  30064. static inline void add (Timer* const tim) throw()
  30065. {
  30066. if (instance == 0)
  30067. instance = new InternalTimerThread();
  30068. const ScopedLock sl (instance->lock);
  30069. instance->addTimer (tim);
  30070. }
  30071. static inline void remove (Timer* const tim) throw()
  30072. {
  30073. if (instance != 0)
  30074. {
  30075. const ScopedLock sl (instance->lock);
  30076. instance->removeTimer (tim);
  30077. }
  30078. }
  30079. static inline void resetCounter (Timer* const tim,
  30080. const int newCounter) throw()
  30081. {
  30082. if (instance != 0)
  30083. {
  30084. tim->countdownMs = newCounter;
  30085. tim->periodMs = newCounter;
  30086. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30087. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30088. {
  30089. const ScopedLock sl (instance->lock);
  30090. instance->removeTimer (tim);
  30091. instance->addTimer (tim);
  30092. }
  30093. }
  30094. }
  30095. };
  30096. InternalTimerThread* InternalTimerThread::instance = 0;
  30097. CriticalSection InternalTimerThread::lock;
  30098. void juce_callAnyTimersSynchronously()
  30099. {
  30100. InternalTimerThread::callAnyTimersSynchronously();
  30101. }
  30102. #ifdef JUCE_DEBUG
  30103. static SortedSet <Timer*> activeTimers;
  30104. #endif
  30105. Timer::Timer() throw()
  30106. : countdownMs (0),
  30107. periodMs (0),
  30108. previous (0),
  30109. next (0)
  30110. {
  30111. #ifdef JUCE_DEBUG
  30112. activeTimers.add (this);
  30113. #endif
  30114. }
  30115. Timer::Timer (const Timer&) throw()
  30116. : countdownMs (0),
  30117. periodMs (0),
  30118. previous (0),
  30119. next (0)
  30120. {
  30121. #ifdef JUCE_DEBUG
  30122. activeTimers.add (this);
  30123. #endif
  30124. }
  30125. Timer::~Timer()
  30126. {
  30127. stopTimer();
  30128. #ifdef JUCE_DEBUG
  30129. activeTimers.removeValue (this);
  30130. #endif
  30131. }
  30132. void Timer::startTimer (const int interval) throw()
  30133. {
  30134. const ScopedLock sl (InternalTimerThread::lock);
  30135. #ifdef JUCE_DEBUG
  30136. // this isn't a valid object! Your timer might be a dangling pointer or something..
  30137. jassert (activeTimers.contains (this));
  30138. #endif
  30139. if (periodMs == 0)
  30140. {
  30141. countdownMs = interval;
  30142. periodMs = jmax (1, interval);
  30143. InternalTimerThread::add (this);
  30144. }
  30145. else
  30146. {
  30147. InternalTimerThread::resetCounter (this, interval);
  30148. }
  30149. }
  30150. void Timer::stopTimer() throw()
  30151. {
  30152. const ScopedLock sl (InternalTimerThread::lock);
  30153. #ifdef JUCE_DEBUG
  30154. // this isn't a valid object! Your timer might be a dangling pointer or something..
  30155. jassert (activeTimers.contains (this));
  30156. #endif
  30157. if (periodMs > 0)
  30158. {
  30159. InternalTimerThread::remove (this);
  30160. periodMs = 0;
  30161. }
  30162. }
  30163. END_JUCE_NAMESPACE
  30164. /********* End of inlined file: juce_Timer.cpp *********/
  30165. /********* Start of inlined file: juce_Component.cpp *********/
  30166. BEGIN_JUCE_NAMESPACE
  30167. Component* Component::componentUnderMouse = 0;
  30168. Component* Component::currentlyFocusedComponent = 0;
  30169. static Array <Component*> modalComponentStack (4), modalComponentReturnValueKeys (4);
  30170. static Array <int> modalReturnValues (4);
  30171. static const int customCommandMessage = 0x7fff0001;
  30172. static const int exitModalStateMessage = 0x7fff0002;
  30173. // these are also used by ComponentPeer
  30174. int64 juce_recentMouseDownTimes [4] = { 0, 0, 0, 0 };
  30175. int juce_recentMouseDownX [4] = { 0, 0, 0, 0 };
  30176. int juce_recentMouseDownY [4] = { 0, 0, 0, 0 };
  30177. Component* juce_recentMouseDownComponent [4] = { 0, 0, 0, 0 };
  30178. int juce_LastMousePosX = 0;
  30179. int juce_LastMousePosY = 0;
  30180. int juce_MouseClickCounter = 0;
  30181. bool juce_MouseHasMovedSignificantlySincePressed = false;
  30182. static int countMouseClicks() throw()
  30183. {
  30184. int numClicks = 0;
  30185. if (juce_recentMouseDownTimes[0] != 0)
  30186. {
  30187. if (! juce_MouseHasMovedSignificantlySincePressed)
  30188. ++numClicks;
  30189. for (int i = 1; i < numElementsInArray (juce_recentMouseDownTimes); ++i)
  30190. {
  30191. if (juce_recentMouseDownTimes[0] - juce_recentMouseDownTimes [i]
  30192. < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  30193. && abs (juce_recentMouseDownX[0] - juce_recentMouseDownX[i]) < 8
  30194. && abs (juce_recentMouseDownY[0] - juce_recentMouseDownY[i]) < 8
  30195. && juce_recentMouseDownComponent[0] == juce_recentMouseDownComponent [i])
  30196. {
  30197. ++numClicks;
  30198. }
  30199. else
  30200. {
  30201. break;
  30202. }
  30203. }
  30204. }
  30205. return numClicks;
  30206. }
  30207. static int unboundedMouseOffsetX = 0;
  30208. static int unboundedMouseOffsetY = 0;
  30209. static bool isUnboundedMouseModeOn = false;
  30210. static bool isCursorVisibleUntilOffscreen;
  30211. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30212. static uint32 nextComponentUID = 0;
  30213. Component::Component() throw()
  30214. : parentComponent_ (0),
  30215. componentUID (++nextComponentUID),
  30216. numDeepMouseListeners (0),
  30217. childComponentList_ (16),
  30218. lookAndFeel_ (0),
  30219. effect_ (0),
  30220. bufferedImage_ (0),
  30221. mouseListeners_ (0),
  30222. keyListeners_ (0),
  30223. componentListeners_ (0),
  30224. propertySet_ (0),
  30225. componentFlags_ (0)
  30226. {
  30227. }
  30228. Component::Component (const String& name) throw()
  30229. : componentName_ (name),
  30230. parentComponent_ (0),
  30231. componentUID (++nextComponentUID),
  30232. numDeepMouseListeners (0),
  30233. childComponentList_ (16),
  30234. lookAndFeel_ (0),
  30235. effect_ (0),
  30236. bufferedImage_ (0),
  30237. mouseListeners_ (0),
  30238. keyListeners_ (0),
  30239. componentListeners_ (0),
  30240. propertySet_ (0),
  30241. componentFlags_ (0)
  30242. {
  30243. }
  30244. Component::~Component()
  30245. {
  30246. if (parentComponent_ != 0)
  30247. {
  30248. parentComponent_->removeChildComponent (this);
  30249. }
  30250. else if ((currentlyFocusedComponent == this)
  30251. || isParentOf (currentlyFocusedComponent))
  30252. {
  30253. giveAwayFocus();
  30254. }
  30255. if (componentUnderMouse == this)
  30256. componentUnderMouse = 0;
  30257. if (flags.hasHeavyweightPeerFlag)
  30258. removeFromDesktop();
  30259. modalComponentStack.removeValue (this);
  30260. for (int i = childComponentList_.size(); --i >= 0;)
  30261. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  30262. delete bufferedImage_;
  30263. delete mouseListeners_;
  30264. delete keyListeners_;
  30265. delete componentListeners_;
  30266. delete propertySet_;
  30267. }
  30268. void Component::setName (const String& name)
  30269. {
  30270. // if component methods are being called from threads other than the message
  30271. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30272. checkMessageManagerIsLocked
  30273. if (componentName_ != name)
  30274. {
  30275. componentName_ = name;
  30276. if (flags.hasHeavyweightPeerFlag)
  30277. {
  30278. ComponentPeer* const peer = getPeer();
  30279. jassert (peer != 0);
  30280. if (peer != 0)
  30281. peer->setTitle (name);
  30282. }
  30283. if (componentListeners_ != 0)
  30284. {
  30285. const ComponentDeletionWatcher deletionChecker (this);
  30286. for (int i = componentListeners_->size(); --i >= 0;)
  30287. {
  30288. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30289. ->componentNameChanged (*this);
  30290. if (deletionChecker.hasBeenDeleted())
  30291. return;
  30292. i = jmin (i, componentListeners_->size());
  30293. }
  30294. }
  30295. }
  30296. }
  30297. void Component::setVisible (bool shouldBeVisible)
  30298. {
  30299. if (flags.visibleFlag != shouldBeVisible)
  30300. {
  30301. // if component methods are being called from threads other than the message
  30302. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30303. checkMessageManagerIsLocked
  30304. const ComponentDeletionWatcher deletionChecker (this);
  30305. flags.visibleFlag = shouldBeVisible;
  30306. internalRepaint (0, 0, getWidth(), getHeight());
  30307. sendFakeMouseMove();
  30308. if (! shouldBeVisible)
  30309. {
  30310. if (currentlyFocusedComponent == this
  30311. || isParentOf (currentlyFocusedComponent))
  30312. {
  30313. if (parentComponent_ != 0)
  30314. parentComponent_->grabKeyboardFocus();
  30315. else
  30316. giveAwayFocus();
  30317. }
  30318. }
  30319. sendVisibilityChangeMessage();
  30320. if ((! deletionChecker.hasBeenDeleted()) && flags.hasHeavyweightPeerFlag)
  30321. {
  30322. ComponentPeer* const peer = getPeer();
  30323. jassert (peer != 0);
  30324. if (peer != 0)
  30325. {
  30326. peer->setVisible (shouldBeVisible);
  30327. internalHierarchyChanged();
  30328. }
  30329. }
  30330. }
  30331. }
  30332. void Component::visibilityChanged()
  30333. {
  30334. }
  30335. void Component::sendVisibilityChangeMessage()
  30336. {
  30337. const ComponentDeletionWatcher deletionChecker (this);
  30338. visibilityChanged();
  30339. if ((! deletionChecker.hasBeenDeleted()) && componentListeners_ != 0)
  30340. {
  30341. for (int i = componentListeners_->size(); --i >= 0;)
  30342. {
  30343. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30344. ->componentVisibilityChanged (*this);
  30345. if (deletionChecker.hasBeenDeleted())
  30346. return;
  30347. i = jmin (i, componentListeners_->size());
  30348. }
  30349. }
  30350. }
  30351. bool Component::isShowing() const throw()
  30352. {
  30353. if (flags.visibleFlag)
  30354. {
  30355. if (parentComponent_ != 0)
  30356. {
  30357. return parentComponent_->isShowing();
  30358. }
  30359. else
  30360. {
  30361. const ComponentPeer* const peer = getPeer();
  30362. return peer != 0 && ! peer->isMinimised();
  30363. }
  30364. }
  30365. return false;
  30366. }
  30367. class FadeOutProxyComponent : public Component,
  30368. public Timer
  30369. {
  30370. public:
  30371. FadeOutProxyComponent (Component* comp,
  30372. const int fadeLengthMs,
  30373. const int deltaXToMove,
  30374. const int deltaYToMove,
  30375. const float scaleFactorAtEnd)
  30376. : lastTime (0),
  30377. alpha (1.0f),
  30378. scale (1.0f)
  30379. {
  30380. image = comp->createComponentSnapshot (Rectangle (0, 0, comp->getWidth(), comp->getHeight()));
  30381. setBounds (comp->getBounds());
  30382. comp->getParentComponent()->addAndMakeVisible (this);
  30383. toBehind (comp);
  30384. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  30385. centreX = comp->getX() + comp->getWidth() * 0.5f;
  30386. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  30387. centreY = comp->getY() + comp->getHeight() * 0.5f;
  30388. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  30389. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  30390. setInterceptsMouseClicks (false, false);
  30391. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  30392. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  30393. }
  30394. ~FadeOutProxyComponent()
  30395. {
  30396. delete image;
  30397. }
  30398. void paint (Graphics& g)
  30399. {
  30400. g.setOpacity (alpha);
  30401. g.drawImage (image,
  30402. 0, 0, getWidth(), getHeight(),
  30403. 0, 0, image->getWidth(), image->getHeight());
  30404. }
  30405. void timerCallback()
  30406. {
  30407. const uint32 now = Time::getMillisecondCounter();
  30408. if (lastTime == 0)
  30409. lastTime = now;
  30410. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  30411. lastTime = now;
  30412. alpha += alphaChangePerMs * msPassed;
  30413. if (alpha > 0)
  30414. {
  30415. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  30416. {
  30417. centreX += xChangePerMs * msPassed;
  30418. centreY += yChangePerMs * msPassed;
  30419. scale += scaleChangePerMs * msPassed;
  30420. const int w = roundFloatToInt (image->getWidth() * scale);
  30421. const int h = roundFloatToInt (image->getHeight() * scale);
  30422. setBounds (roundFloatToInt (centreX) - w / 2,
  30423. roundFloatToInt (centreY) - h / 2,
  30424. w, h);
  30425. }
  30426. repaint();
  30427. }
  30428. else
  30429. {
  30430. delete this;
  30431. }
  30432. }
  30433. juce_UseDebuggingNewOperator
  30434. private:
  30435. Image* image;
  30436. uint32 lastTime;
  30437. float alpha, alphaChangePerMs;
  30438. float centreX, xChangePerMs;
  30439. float centreY, yChangePerMs;
  30440. float scale, scaleChangePerMs;
  30441. FadeOutProxyComponent (const FadeOutProxyComponent&);
  30442. const FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  30443. };
  30444. void Component::fadeOutComponent (const int millisecondsToFade,
  30445. const int deltaXToMove,
  30446. const int deltaYToMove,
  30447. const float scaleFactorAtEnd)
  30448. {
  30449. //xxx won't work for comps without parents
  30450. if (isShowing() && millisecondsToFade > 0)
  30451. new FadeOutProxyComponent (this, millisecondsToFade,
  30452. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  30453. setVisible (false);
  30454. }
  30455. bool Component::isValidComponent() const throw()
  30456. {
  30457. return (this != 0) && isValidMessageListener();
  30458. }
  30459. void* Component::getWindowHandle() const throw()
  30460. {
  30461. const ComponentPeer* const peer = getPeer();
  30462. if (peer != 0)
  30463. return peer->getNativeHandle();
  30464. return 0;
  30465. }
  30466. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  30467. {
  30468. // if component methods are being called from threads other than the message
  30469. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30470. checkMessageManagerIsLocked
  30471. if (! isOpaque())
  30472. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  30473. int currentStyleFlags = 0;
  30474. // don't use getPeer(), so that we only get the peer that's specifically
  30475. // for this comp, and not for one of its parents.
  30476. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  30477. if (peer != 0)
  30478. currentStyleFlags = peer->getStyleFlags();
  30479. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  30480. {
  30481. const ComponentDeletionWatcher deletionChecker (this);
  30482. #if JUCE_LINUX
  30483. // it's wise to give the component a non-zero size before
  30484. // putting it on the desktop, as X windows get confused by this, and
  30485. // a (1, 1) minimum size is enforced here.
  30486. setSize (jmax (1, getWidth()),
  30487. jmax (1, getHeight()));
  30488. #endif
  30489. int x = 0, y = 0;
  30490. relativePositionToGlobal (x, y);
  30491. bool wasFullscreen = false;
  30492. bool wasMinimised = false;
  30493. ComponentBoundsConstrainer* currentConstainer = 0;
  30494. Rectangle oldNonFullScreenBounds;
  30495. if (peer != 0)
  30496. {
  30497. wasFullscreen = peer->isFullScreen();
  30498. wasMinimised = peer->isMinimised();
  30499. currentConstainer = peer->getConstrainer();
  30500. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  30501. removeFromDesktop();
  30502. setTopLeftPosition (x, y);
  30503. }
  30504. if (parentComponent_ != 0)
  30505. parentComponent_->removeChildComponent (this);
  30506. if (! deletionChecker.hasBeenDeleted())
  30507. {
  30508. flags.hasHeavyweightPeerFlag = true;
  30509. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  30510. Desktop::getInstance().addDesktopComponent (this);
  30511. bounds_.setPosition (x, y);
  30512. peer->setBounds (x, y, getWidth(), getHeight(), false);
  30513. peer->setVisible (isVisible());
  30514. if (wasFullscreen)
  30515. {
  30516. peer->setFullScreen (true);
  30517. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  30518. }
  30519. if (wasMinimised)
  30520. peer->setMinimised (true);
  30521. if (isAlwaysOnTop())
  30522. peer->setAlwaysOnTop (true);
  30523. peer->setConstrainer (currentConstainer);
  30524. repaint();
  30525. }
  30526. internalHierarchyChanged();
  30527. }
  30528. }
  30529. void Component::removeFromDesktop()
  30530. {
  30531. // if component methods are being called from threads other than the message
  30532. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30533. checkMessageManagerIsLocked
  30534. if (flags.hasHeavyweightPeerFlag)
  30535. {
  30536. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  30537. flags.hasHeavyweightPeerFlag = false;
  30538. jassert (peer != 0);
  30539. delete peer;
  30540. Desktop::getInstance().removeDesktopComponent (this);
  30541. }
  30542. }
  30543. bool Component::isOnDesktop() const throw()
  30544. {
  30545. return flags.hasHeavyweightPeerFlag;
  30546. }
  30547. void Component::userTriedToCloseWindow()
  30548. {
  30549. /* This means that the user's trying to get rid of your window with the 'close window' system
  30550. menu option (on windows) or possibly the task manager - you should really handle this
  30551. and delete or hide your component in an appropriate way.
  30552. If you want to ignore the event and don't want to trigger this assertion, just override
  30553. this method and do nothing.
  30554. */
  30555. jassertfalse
  30556. }
  30557. void Component::minimisationStateChanged (bool)
  30558. {
  30559. }
  30560. void Component::setOpaque (const bool shouldBeOpaque) throw()
  30561. {
  30562. if (shouldBeOpaque != flags.opaqueFlag)
  30563. {
  30564. flags.opaqueFlag = shouldBeOpaque;
  30565. if (flags.hasHeavyweightPeerFlag)
  30566. {
  30567. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  30568. if (peer != 0)
  30569. {
  30570. // to make it recreate the heavyweight window
  30571. addToDesktop (peer->getStyleFlags());
  30572. }
  30573. }
  30574. repaint();
  30575. }
  30576. }
  30577. bool Component::isOpaque() const throw()
  30578. {
  30579. return flags.opaqueFlag;
  30580. }
  30581. void Component::setBufferedToImage (const bool shouldBeBuffered) throw()
  30582. {
  30583. if (shouldBeBuffered != flags.bufferToImageFlag)
  30584. {
  30585. deleteAndZero (bufferedImage_);
  30586. flags.bufferToImageFlag = shouldBeBuffered;
  30587. }
  30588. }
  30589. void Component::toFront (const bool setAsForeground)
  30590. {
  30591. // if component methods are being called from threads other than the message
  30592. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30593. checkMessageManagerIsLocked
  30594. if (flags.hasHeavyweightPeerFlag)
  30595. {
  30596. ComponentPeer* const peer = getPeer();
  30597. if (peer != 0)
  30598. {
  30599. peer->toFront (setAsForeground);
  30600. if (setAsForeground && ! hasKeyboardFocus (true))
  30601. grabKeyboardFocus();
  30602. }
  30603. }
  30604. else if (parentComponent_ != 0)
  30605. {
  30606. if (parentComponent_->childComponentList_.getLast() != this)
  30607. {
  30608. const int index = parentComponent_->childComponentList_.indexOf (this);
  30609. if (index >= 0)
  30610. {
  30611. int insertIndex = -1;
  30612. if (! flags.alwaysOnTopFlag)
  30613. {
  30614. insertIndex = parentComponent_->childComponentList_.size() - 1;
  30615. while (insertIndex > 0
  30616. && parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  30617. {
  30618. --insertIndex;
  30619. }
  30620. }
  30621. if (index != insertIndex)
  30622. {
  30623. parentComponent_->childComponentList_.move (index, insertIndex);
  30624. sendFakeMouseMove();
  30625. repaintParent();
  30626. }
  30627. }
  30628. }
  30629. if (setAsForeground)
  30630. {
  30631. internalBroughtToFront();
  30632. grabKeyboardFocus();
  30633. }
  30634. }
  30635. }
  30636. void Component::toBehind (Component* const other)
  30637. {
  30638. if (other != 0)
  30639. {
  30640. // the two components must belong to the same parent..
  30641. jassert (parentComponent_ == other->parentComponent_);
  30642. if (parentComponent_ != 0)
  30643. {
  30644. const int index = parentComponent_->childComponentList_.indexOf (this);
  30645. int otherIndex = parentComponent_->childComponentList_.indexOf (other);
  30646. if (index >= 0
  30647. && otherIndex >= 0
  30648. && index != otherIndex - 1
  30649. && other != this)
  30650. {
  30651. if (index < otherIndex)
  30652. --otherIndex;
  30653. parentComponent_->childComponentList_.move (index, otherIndex);
  30654. sendFakeMouseMove();
  30655. repaintParent();
  30656. }
  30657. }
  30658. else if (isOnDesktop())
  30659. {
  30660. jassert (other->isOnDesktop());
  30661. if (other->isOnDesktop())
  30662. {
  30663. ComponentPeer* const us = getPeer();
  30664. ComponentPeer* const them = other->getPeer();
  30665. jassert (us != 0 && them != 0);
  30666. if (us != 0 && them != 0)
  30667. us->toBehind (them);
  30668. }
  30669. }
  30670. }
  30671. }
  30672. void Component::toBack()
  30673. {
  30674. if (isOnDesktop())
  30675. {
  30676. jassertfalse //xxx need to add this to native window
  30677. }
  30678. else if (parentComponent_ != 0
  30679. && parentComponent_->childComponentList_.getFirst() != this)
  30680. {
  30681. const int index = parentComponent_->childComponentList_.indexOf (this);
  30682. if (index > 0)
  30683. {
  30684. int insertIndex = 0;
  30685. if (flags.alwaysOnTopFlag)
  30686. {
  30687. while (insertIndex < parentComponent_->childComponentList_.size()
  30688. && ! parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  30689. {
  30690. ++insertIndex;
  30691. }
  30692. }
  30693. if (index != insertIndex)
  30694. {
  30695. parentComponent_->childComponentList_.move (index, insertIndex);
  30696. sendFakeMouseMove();
  30697. repaintParent();
  30698. }
  30699. }
  30700. }
  30701. }
  30702. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  30703. {
  30704. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  30705. {
  30706. flags.alwaysOnTopFlag = shouldStayOnTop;
  30707. if (isOnDesktop())
  30708. {
  30709. ComponentPeer* const peer = getPeer();
  30710. jassert (peer != 0);
  30711. if (peer != 0)
  30712. {
  30713. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  30714. {
  30715. // some kinds of peer can't change their always-on-top status, so
  30716. // for these, we'll need to create a new window
  30717. const int oldFlags = peer->getStyleFlags();
  30718. removeFromDesktop();
  30719. addToDesktop (oldFlags);
  30720. }
  30721. }
  30722. }
  30723. if (shouldStayOnTop)
  30724. toFront (false);
  30725. internalHierarchyChanged();
  30726. }
  30727. }
  30728. bool Component::isAlwaysOnTop() const throw()
  30729. {
  30730. return flags.alwaysOnTopFlag;
  30731. }
  30732. int Component::proportionOfWidth (const float proportion) const throw()
  30733. {
  30734. return roundDoubleToInt (proportion * bounds_.getWidth());
  30735. }
  30736. int Component::proportionOfHeight (const float proportion) const throw()
  30737. {
  30738. return roundDoubleToInt (proportion * bounds_.getHeight());
  30739. }
  30740. int Component::getParentWidth() const throw()
  30741. {
  30742. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  30743. : getParentMonitorArea().getWidth();
  30744. }
  30745. int Component::getParentHeight() const throw()
  30746. {
  30747. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  30748. : getParentMonitorArea().getHeight();
  30749. }
  30750. int Component::getScreenX() const throw()
  30751. {
  30752. return (parentComponent_ != 0) ? parentComponent_->getScreenX() + getX()
  30753. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenX()
  30754. : getX());
  30755. }
  30756. int Component::getScreenY() const throw()
  30757. {
  30758. return (parentComponent_ != 0) ? parentComponent_->getScreenY() + getY()
  30759. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenY()
  30760. : getY());
  30761. }
  30762. void Component::relativePositionToGlobal (int& x, int& y) const throw()
  30763. {
  30764. const Component* c = this;
  30765. do
  30766. {
  30767. if (c->flags.hasHeavyweightPeerFlag)
  30768. {
  30769. c->getPeer()->relativePositionToGlobal (x, y);
  30770. break;
  30771. }
  30772. x += c->getX();
  30773. y += c->getY();
  30774. c = c->parentComponent_;
  30775. }
  30776. while (c != 0);
  30777. }
  30778. void Component::globalPositionToRelative (int& x, int& y) const throw()
  30779. {
  30780. if (flags.hasHeavyweightPeerFlag)
  30781. {
  30782. getPeer()->globalPositionToRelative (x, y);
  30783. }
  30784. else
  30785. {
  30786. if (parentComponent_ != 0)
  30787. parentComponent_->globalPositionToRelative (x, y);
  30788. x -= getX();
  30789. y -= getY();
  30790. }
  30791. }
  30792. void Component::relativePositionToOtherComponent (const Component* const targetComponent, int& x, int& y) const throw()
  30793. {
  30794. if (targetComponent != 0)
  30795. {
  30796. const Component* c = this;
  30797. do
  30798. {
  30799. if (c == targetComponent)
  30800. return;
  30801. if (c->flags.hasHeavyweightPeerFlag)
  30802. {
  30803. c->getPeer()->relativePositionToGlobal (x, y);
  30804. break;
  30805. }
  30806. x += c->getX();
  30807. y += c->getY();
  30808. c = c->parentComponent_;
  30809. }
  30810. while (c != 0);
  30811. targetComponent->globalPositionToRelative (x, y);
  30812. }
  30813. }
  30814. void Component::setBounds (int x, int y, int w, int h)
  30815. {
  30816. // if component methods are being called from threads other than the message
  30817. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30818. checkMessageManagerIsLocked
  30819. if (w < 0) w = 0;
  30820. if (h < 0) h = 0;
  30821. const bool wasResized = (getWidth() != w || getHeight() != h);
  30822. const bool wasMoved = (getX() != x || getY() != y);
  30823. #ifdef JUCE_DEBUG
  30824. // It's a very bad idea to try to resize a window during its paint() method!
  30825. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  30826. #endif
  30827. if (wasMoved || wasResized)
  30828. {
  30829. if (flags.visibleFlag)
  30830. {
  30831. // send a fake mouse move to trigger enter/exit messages if needed..
  30832. sendFakeMouseMove();
  30833. if (! flags.hasHeavyweightPeerFlag)
  30834. repaintParent();
  30835. }
  30836. bounds_.setBounds (x, y, w, h);
  30837. if (wasResized)
  30838. repaint();
  30839. else if (! flags.hasHeavyweightPeerFlag)
  30840. repaintParent();
  30841. if (flags.hasHeavyweightPeerFlag)
  30842. {
  30843. ComponentPeer* const peer = getPeer();
  30844. if (peer != 0)
  30845. {
  30846. if (wasMoved && wasResized)
  30847. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  30848. else if (wasMoved)
  30849. peer->setPosition (getX(), getY());
  30850. else if (wasResized)
  30851. peer->setSize (getWidth(), getHeight());
  30852. }
  30853. }
  30854. sendMovedResizedMessages (wasMoved, wasResized);
  30855. }
  30856. }
  30857. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  30858. {
  30859. JUCE_TRY
  30860. {
  30861. if (wasMoved)
  30862. moved();
  30863. if (wasResized)
  30864. {
  30865. resized();
  30866. for (int i = childComponentList_.size(); --i >= 0;)
  30867. {
  30868. childComponentList_.getUnchecked(i)->parentSizeChanged();
  30869. i = jmin (i, childComponentList_.size());
  30870. }
  30871. }
  30872. if (parentComponent_ != 0)
  30873. parentComponent_->childBoundsChanged (this);
  30874. if (componentListeners_ != 0)
  30875. {
  30876. const ComponentDeletionWatcher deletionChecker (this);
  30877. for (int i = componentListeners_->size(); --i >= 0;)
  30878. {
  30879. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30880. ->componentMovedOrResized (*this, wasMoved, wasResized);
  30881. if (deletionChecker.hasBeenDeleted())
  30882. return;
  30883. i = jmin (i, componentListeners_->size());
  30884. }
  30885. }
  30886. }
  30887. JUCE_CATCH_EXCEPTION
  30888. }
  30889. void Component::setSize (const int w, const int h)
  30890. {
  30891. setBounds (getX(), getY(), w, h);
  30892. }
  30893. void Component::setTopLeftPosition (const int x, const int y)
  30894. {
  30895. setBounds (x, y, getWidth(), getHeight());
  30896. }
  30897. void Component::setTopRightPosition (const int x, const int y)
  30898. {
  30899. setTopLeftPosition (x - getWidth(), y);
  30900. }
  30901. void Component::setBounds (const Rectangle& r)
  30902. {
  30903. setBounds (r.getX(),
  30904. r.getY(),
  30905. r.getWidth(),
  30906. r.getHeight());
  30907. }
  30908. void Component::setBoundsRelative (const float x, const float y,
  30909. const float w, const float h)
  30910. {
  30911. const int pw = getParentWidth();
  30912. const int ph = getParentHeight();
  30913. setBounds (roundFloatToInt (x * pw),
  30914. roundFloatToInt (y * ph),
  30915. roundFloatToInt (w * pw),
  30916. roundFloatToInt (h * ph));
  30917. }
  30918. void Component::setCentrePosition (const int x, const int y)
  30919. {
  30920. setTopLeftPosition (x - getWidth() / 2,
  30921. y - getHeight() / 2);
  30922. }
  30923. void Component::setCentreRelative (const float x, const float y)
  30924. {
  30925. setCentrePosition (roundFloatToInt (getParentWidth() * x),
  30926. roundFloatToInt (getParentHeight() * y));
  30927. }
  30928. void Component::centreWithSize (const int width, const int height)
  30929. {
  30930. setBounds ((getParentWidth() - width) / 2,
  30931. (getParentHeight() - height) / 2,
  30932. width,
  30933. height);
  30934. }
  30935. void Component::setBoundsInset (const BorderSize& borders)
  30936. {
  30937. setBounds (borders.getLeft(),
  30938. borders.getTop(),
  30939. getParentWidth() - (borders.getLeftAndRight()),
  30940. getParentHeight() - (borders.getTopAndBottom()));
  30941. }
  30942. void Component::setBoundsToFit (int x, int y, int width, int height,
  30943. const Justification& justification,
  30944. const bool onlyReduceInSize)
  30945. {
  30946. // it's no good calling this method unless both the component and
  30947. // target rectangle have a finite size.
  30948. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  30949. if (getWidth() > 0 && getHeight() > 0
  30950. && width > 0 && height > 0)
  30951. {
  30952. int newW, newH;
  30953. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  30954. {
  30955. newW = getWidth();
  30956. newH = getHeight();
  30957. }
  30958. else
  30959. {
  30960. const double imageRatio = getHeight() / (double) getWidth();
  30961. const double targetRatio = height / (double) width;
  30962. if (imageRatio <= targetRatio)
  30963. {
  30964. newW = width;
  30965. newH = jmin (height, roundDoubleToInt (newW * imageRatio));
  30966. }
  30967. else
  30968. {
  30969. newH = height;
  30970. newW = jmin (width, roundDoubleToInt (newH / imageRatio));
  30971. }
  30972. }
  30973. if (newW > 0 && newH > 0)
  30974. {
  30975. int newX, newY;
  30976. justification.applyToRectangle (newX, newY, newW, newH,
  30977. x, y, width, height);
  30978. setBounds (newX, newY, newW, newH);
  30979. }
  30980. }
  30981. }
  30982. bool Component::hitTest (int x, int y)
  30983. {
  30984. if (! flags.ignoresMouseClicksFlag)
  30985. return true;
  30986. if (flags.allowChildMouseClicksFlag)
  30987. {
  30988. for (int i = getNumChildComponents(); --i >= 0;)
  30989. {
  30990. Component* const c = getChildComponent (i);
  30991. if (c->isVisible()
  30992. && c->bounds_.contains (x, y)
  30993. && c->hitTest (x - c->getX(),
  30994. y - c->getY()))
  30995. {
  30996. return true;
  30997. }
  30998. }
  30999. }
  31000. return false;
  31001. }
  31002. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31003. const bool allowClicksOnChildComponents) throw()
  31004. {
  31005. flags.ignoresMouseClicksFlag = ! allowClicks;
  31006. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31007. }
  31008. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31009. bool& allowsClicksOnChildComponents) const throw()
  31010. {
  31011. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31012. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31013. }
  31014. bool Component::contains (const int x, const int y)
  31015. {
  31016. if (((unsigned int) x) < (unsigned int) getWidth()
  31017. && ((unsigned int) y) < (unsigned int) getHeight()
  31018. && hitTest (x, y))
  31019. {
  31020. if (parentComponent_ != 0)
  31021. {
  31022. return parentComponent_->contains (x + getX(),
  31023. y + getY());
  31024. }
  31025. else if (flags.hasHeavyweightPeerFlag)
  31026. {
  31027. const ComponentPeer* const peer = getPeer();
  31028. if (peer != 0)
  31029. return peer->contains (x, y, true);
  31030. }
  31031. }
  31032. return false;
  31033. }
  31034. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31035. {
  31036. if (! contains (x, y))
  31037. return false;
  31038. Component* p = this;
  31039. while (p->parentComponent_ != 0)
  31040. {
  31041. x += p->getX();
  31042. y += p->getY();
  31043. p = p->parentComponent_;
  31044. }
  31045. const Component* const c = p->getComponentAt (x, y);
  31046. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31047. }
  31048. Component* Component::getComponentAt (const int x, const int y)
  31049. {
  31050. if (flags.visibleFlag
  31051. && ((unsigned int) x) < (unsigned int) getWidth()
  31052. && ((unsigned int) y) < (unsigned int) getHeight()
  31053. && hitTest (x, y))
  31054. {
  31055. for (int i = childComponentList_.size(); --i >= 0;)
  31056. {
  31057. Component* const child = childComponentList_.getUnchecked(i);
  31058. Component* const c = child->getComponentAt (x - child->getX(),
  31059. y - child->getY());
  31060. if (c != 0)
  31061. return c;
  31062. }
  31063. return this;
  31064. }
  31065. return 0;
  31066. }
  31067. void Component::addChildComponent (Component* const child, int zOrder)
  31068. {
  31069. // if component methods are being called from threads other than the message
  31070. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31071. checkMessageManagerIsLocked
  31072. if (child != 0 && child->parentComponent_ != this)
  31073. {
  31074. if (child->parentComponent_ != 0)
  31075. child->parentComponent_->removeChildComponent (child);
  31076. else
  31077. child->removeFromDesktop();
  31078. child->parentComponent_ = this;
  31079. if (child->isVisible())
  31080. child->repaintParent();
  31081. if (! child->isAlwaysOnTop())
  31082. {
  31083. if (zOrder < 0 || zOrder > childComponentList_.size())
  31084. zOrder = childComponentList_.size();
  31085. while (zOrder > 0)
  31086. {
  31087. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31088. break;
  31089. --zOrder;
  31090. }
  31091. }
  31092. childComponentList_.insert (zOrder, child);
  31093. child->internalHierarchyChanged();
  31094. internalChildrenChanged();
  31095. }
  31096. }
  31097. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31098. {
  31099. if (child != 0)
  31100. {
  31101. child->setVisible (true);
  31102. addChildComponent (child, zOrder);
  31103. }
  31104. }
  31105. void Component::removeChildComponent (Component* const child)
  31106. {
  31107. removeChildComponent (childComponentList_.indexOf (child));
  31108. }
  31109. Component* Component::removeChildComponent (const int index)
  31110. {
  31111. // if component methods are being called from threads other than the message
  31112. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31113. checkMessageManagerIsLocked
  31114. Component* const child = childComponentList_ [index];
  31115. if (child != 0)
  31116. {
  31117. sendFakeMouseMove();
  31118. child->repaintParent();
  31119. childComponentList_.remove (index);
  31120. child->parentComponent_ = 0;
  31121. JUCE_TRY
  31122. {
  31123. if ((currentlyFocusedComponent == child)
  31124. || child->isParentOf (currentlyFocusedComponent))
  31125. {
  31126. // get rid first to force the grabKeyboardFocus to change to us.
  31127. giveAwayFocus();
  31128. grabKeyboardFocus();
  31129. }
  31130. }
  31131. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31132. catch (const std::exception& e)
  31133. {
  31134. currentlyFocusedComponent = 0;
  31135. Desktop::getInstance().triggerFocusCallback();
  31136. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31137. }
  31138. catch (...)
  31139. {
  31140. currentlyFocusedComponent = 0;
  31141. Desktop::getInstance().triggerFocusCallback();
  31142. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31143. }
  31144. #endif
  31145. child->internalHierarchyChanged();
  31146. internalChildrenChanged();
  31147. }
  31148. return child;
  31149. }
  31150. void Component::removeAllChildren()
  31151. {
  31152. for (int i = childComponentList_.size(); --i >= 0;)
  31153. removeChildComponent (i);
  31154. }
  31155. void Component::deleteAllChildren()
  31156. {
  31157. for (int i = childComponentList_.size(); --i >= 0;)
  31158. delete (removeChildComponent (i));
  31159. }
  31160. int Component::getNumChildComponents() const throw()
  31161. {
  31162. return childComponentList_.size();
  31163. }
  31164. Component* Component::getChildComponent (const int index) const throw()
  31165. {
  31166. return childComponentList_ [index];
  31167. }
  31168. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  31169. {
  31170. return childComponentList_.indexOf (const_cast <Component*> (child));
  31171. }
  31172. Component* Component::getTopLevelComponent() const throw()
  31173. {
  31174. const Component* comp = this;
  31175. while (comp->parentComponent_ != 0)
  31176. comp = comp->parentComponent_;
  31177. return (Component*) comp;
  31178. }
  31179. bool Component::isParentOf (const Component* possibleChild) const throw()
  31180. {
  31181. while (possibleChild->isValidComponent())
  31182. {
  31183. possibleChild = possibleChild->parentComponent_;
  31184. if (possibleChild == this)
  31185. return true;
  31186. }
  31187. return false;
  31188. }
  31189. void Component::parentHierarchyChanged()
  31190. {
  31191. }
  31192. void Component::childrenChanged()
  31193. {
  31194. }
  31195. void Component::internalChildrenChanged()
  31196. {
  31197. const ComponentDeletionWatcher deletionChecker (this);
  31198. const bool hasListeners = componentListeners_ != 0;
  31199. childrenChanged();
  31200. if (hasListeners)
  31201. {
  31202. if (deletionChecker.hasBeenDeleted())
  31203. return;
  31204. for (int i = componentListeners_->size(); --i >= 0;)
  31205. {
  31206. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31207. ->componentChildrenChanged (*this);
  31208. if (deletionChecker.hasBeenDeleted())
  31209. return;
  31210. i = jmin (i, componentListeners_->size());
  31211. }
  31212. }
  31213. }
  31214. void Component::internalHierarchyChanged()
  31215. {
  31216. parentHierarchyChanged();
  31217. const ComponentDeletionWatcher deletionChecker (this);
  31218. if (componentListeners_ != 0)
  31219. {
  31220. for (int i = componentListeners_->size(); --i >= 0;)
  31221. {
  31222. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31223. ->componentParentHierarchyChanged (*this);
  31224. if (deletionChecker.hasBeenDeleted())
  31225. return;
  31226. i = jmin (i, componentListeners_->size());
  31227. }
  31228. }
  31229. for (int i = childComponentList_.size(); --i >= 0;)
  31230. {
  31231. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  31232. // you really shouldn't delete the parent component during a callback telling you
  31233. // that it's changed..
  31234. jassert (! deletionChecker.hasBeenDeleted());
  31235. if (deletionChecker.hasBeenDeleted())
  31236. return;
  31237. i = jmin (i, childComponentList_.size());
  31238. }
  31239. }
  31240. void* Component::runModalLoopCallback (void* userData)
  31241. {
  31242. return (void*) (pointer_sized_int) ((Component*) userData)->runModalLoop();
  31243. }
  31244. int Component::runModalLoop()
  31245. {
  31246. if (! MessageManager::getInstance()->isThisTheMessageThread())
  31247. {
  31248. // use a callback so this can be called from non-gui threads
  31249. return (int) (pointer_sized_int)
  31250. MessageManager::getInstance()
  31251. ->callFunctionOnMessageThread (&runModalLoopCallback, (void*) this);
  31252. }
  31253. Component* const prevFocused = getCurrentlyFocusedComponent();
  31254. ComponentDeletionWatcher* deletionChecker = 0;
  31255. if (prevFocused != 0)
  31256. deletionChecker = new ComponentDeletionWatcher (prevFocused);
  31257. if (! isCurrentlyModal())
  31258. enterModalState();
  31259. JUCE_TRY
  31260. {
  31261. while (flags.currentlyModalFlag && flags.visibleFlag)
  31262. {
  31263. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  31264. break;
  31265. // check whether this component was deleted during the last message
  31266. if (! isValidMessageListener())
  31267. break;
  31268. }
  31269. }
  31270. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31271. catch (const std::exception& e)
  31272. {
  31273. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31274. return 0;
  31275. }
  31276. catch (...)
  31277. {
  31278. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31279. return 0;
  31280. }
  31281. #endif
  31282. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  31283. int returnValue = 0;
  31284. if (modalIndex >= 0)
  31285. {
  31286. modalComponentReturnValueKeys.remove (modalIndex);
  31287. returnValue = modalReturnValues.remove (modalIndex);
  31288. }
  31289. modalComponentStack.removeValue (this);
  31290. if (deletionChecker != 0)
  31291. {
  31292. if (! deletionChecker->hasBeenDeleted())
  31293. prevFocused->grabKeyboardFocus();
  31294. delete deletionChecker;
  31295. }
  31296. return returnValue;
  31297. }
  31298. void Component::enterModalState (const bool takeKeyboardFocus)
  31299. {
  31300. // if component methods are being called from threads other than the message
  31301. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31302. checkMessageManagerIsLocked
  31303. // Check for an attempt to make a component modal when it already is!
  31304. // This can cause nasty problems..
  31305. jassert (! flags.currentlyModalFlag);
  31306. if (! isCurrentlyModal())
  31307. {
  31308. modalComponentStack.add (this);
  31309. modalComponentReturnValueKeys.add (this);
  31310. modalReturnValues.add (0);
  31311. flags.currentlyModalFlag = true;
  31312. setVisible (true);
  31313. if (takeKeyboardFocus)
  31314. grabKeyboardFocus();
  31315. }
  31316. }
  31317. void Component::exitModalState (const int returnValue)
  31318. {
  31319. if (isCurrentlyModal())
  31320. {
  31321. if (MessageManager::getInstance()->isThisTheMessageThread())
  31322. {
  31323. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  31324. if (modalIndex >= 0)
  31325. {
  31326. modalReturnValues.set (modalIndex, returnValue);
  31327. }
  31328. else
  31329. {
  31330. modalComponentReturnValueKeys.add (this);
  31331. modalReturnValues.add (returnValue);
  31332. }
  31333. modalComponentStack.removeValue (this);
  31334. flags.currentlyModalFlag = false;
  31335. bringModalComponentToFront();
  31336. }
  31337. else
  31338. {
  31339. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  31340. }
  31341. }
  31342. }
  31343. bool Component::isCurrentlyModal() const throw()
  31344. {
  31345. return flags.currentlyModalFlag
  31346. && getCurrentlyModalComponent() == this;
  31347. }
  31348. bool Component::isCurrentlyBlockedByAnotherModalComponent() const throw()
  31349. {
  31350. Component* const mc = getCurrentlyModalComponent();
  31351. return mc != 0
  31352. && mc != this
  31353. && (! mc->isParentOf (this))
  31354. && ! mc->canModalEventBeSentToComponent (this);
  31355. }
  31356. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  31357. {
  31358. return modalComponentStack.size();
  31359. }
  31360. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  31361. {
  31362. Component* const c = (Component*) (modalComponentStack [modalComponentStack.size() - index - 1]);
  31363. return c->isValidComponent() ? c : 0;
  31364. }
  31365. void Component::bringModalComponentToFront()
  31366. {
  31367. ComponentPeer* lastOne = 0;
  31368. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  31369. {
  31370. Component* const c = getCurrentlyModalComponent (i);
  31371. if (c == 0)
  31372. break;
  31373. ComponentPeer* peer = c->getPeer();
  31374. if (peer != 0 && peer != lastOne)
  31375. {
  31376. if (lastOne == 0)
  31377. {
  31378. peer->toFront (true);
  31379. peer->grabFocus();
  31380. }
  31381. else
  31382. peer->toBehind (lastOne);
  31383. lastOne = peer;
  31384. }
  31385. }
  31386. }
  31387. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  31388. {
  31389. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  31390. }
  31391. bool Component::isBroughtToFrontOnMouseClick() const throw()
  31392. {
  31393. return flags.bringToFrontOnClickFlag;
  31394. }
  31395. void Component::setMouseCursor (const MouseCursor& cursor) throw()
  31396. {
  31397. cursor_ = cursor;
  31398. if (flags.visibleFlag)
  31399. {
  31400. int mx, my;
  31401. getMouseXYRelative (mx, my);
  31402. if (flags.draggingFlag || reallyContains (mx, my, false))
  31403. {
  31404. internalUpdateMouseCursor (false);
  31405. }
  31406. }
  31407. }
  31408. const MouseCursor Component::getMouseCursor()
  31409. {
  31410. return cursor_;
  31411. }
  31412. void Component::updateMouseCursor() const throw()
  31413. {
  31414. sendFakeMouseMove();
  31415. }
  31416. void Component::internalUpdateMouseCursor (bool forcedUpdate) throw()
  31417. {
  31418. ComponentPeer* const peer = getPeer();
  31419. if (peer != 0)
  31420. {
  31421. MouseCursor mc (getMouseCursor());
  31422. if (isUnboundedMouseModeOn && (unboundedMouseOffsetX != 0
  31423. || unboundedMouseOffsetY != 0
  31424. || ! isCursorVisibleUntilOffscreen))
  31425. {
  31426. mc = MouseCursor::NoCursor;
  31427. forcedUpdate = true;
  31428. }
  31429. static void* currentCursorHandle = 0;
  31430. if (forcedUpdate || mc.getHandle() != currentCursorHandle)
  31431. {
  31432. currentCursorHandle = mc.getHandle();
  31433. mc.showInWindow (peer);
  31434. }
  31435. }
  31436. }
  31437. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  31438. {
  31439. flags.repaintOnMouseActivityFlag = shouldRepaint;
  31440. }
  31441. void Component::repaintParent() throw()
  31442. {
  31443. if (flags.visibleFlag)
  31444. internalRepaint (0, 0, getWidth(), getHeight());
  31445. }
  31446. void Component::repaint() throw()
  31447. {
  31448. repaint (0, 0, getWidth(), getHeight());
  31449. }
  31450. void Component::repaint (const int x, const int y,
  31451. const int w, const int h) throw()
  31452. {
  31453. deleteAndZero (bufferedImage_);
  31454. if (flags.visibleFlag)
  31455. internalRepaint (x, y, w, h);
  31456. }
  31457. void Component::internalRepaint (int x, int y, int w, int h)
  31458. {
  31459. // if component methods are being called from threads other than the message
  31460. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31461. checkMessageManagerIsLocked
  31462. if (x < 0)
  31463. {
  31464. w += x;
  31465. x = 0;
  31466. }
  31467. if (x + w > getWidth())
  31468. w = getWidth() - x;
  31469. if (w > 0)
  31470. {
  31471. if (y < 0)
  31472. {
  31473. h += y;
  31474. y = 0;
  31475. }
  31476. if (y + h > getHeight())
  31477. h = getHeight() - y;
  31478. if (h > 0)
  31479. {
  31480. if (parentComponent_ != 0)
  31481. {
  31482. x += getX();
  31483. y += getY();
  31484. if (parentComponent_->flags.visibleFlag)
  31485. parentComponent_->internalRepaint (x, y, w, h);
  31486. }
  31487. else if (flags.hasHeavyweightPeerFlag)
  31488. {
  31489. ComponentPeer* const peer = getPeer();
  31490. if (peer != 0)
  31491. peer->repaint (x, y, w, h);
  31492. }
  31493. }
  31494. }
  31495. }
  31496. void Component::paintEntireComponent (Graphics& originalContext)
  31497. {
  31498. jassert (! originalContext.isClipEmpty());
  31499. #ifdef JUCE_DEBUG
  31500. flags.isInsidePaintCall = true;
  31501. #endif
  31502. Graphics* g = &originalContext;
  31503. Image* effectImage = 0;
  31504. if (effect_ != 0)
  31505. {
  31506. effectImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31507. getWidth(), getHeight(),
  31508. ! flags.opaqueFlag);
  31509. g = new Graphics (*effectImage);
  31510. }
  31511. g->saveState();
  31512. clipObscuredRegions (*g, g->getClipBounds(), 0, 0);
  31513. if (! g->isClipEmpty())
  31514. {
  31515. if (bufferedImage_ != 0)
  31516. {
  31517. g->setColour (Colours::black);
  31518. g->drawImageAt (bufferedImage_, 0, 0);
  31519. }
  31520. else
  31521. {
  31522. if (flags.bufferToImageFlag)
  31523. {
  31524. if (bufferedImage_ == 0)
  31525. {
  31526. bufferedImage_ = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31527. getWidth(), getHeight(), ! flags.opaqueFlag);
  31528. Graphics imG (*bufferedImage_);
  31529. paint (imG);
  31530. }
  31531. g->setColour (Colours::black);
  31532. g->drawImageAt (bufferedImage_, 0, 0);
  31533. }
  31534. else
  31535. {
  31536. paint (*g);
  31537. g->resetToDefaultState();
  31538. }
  31539. }
  31540. }
  31541. g->restoreState();
  31542. for (int i = 0; i < childComponentList_.size(); ++i)
  31543. {
  31544. Component* const child = childComponentList_.getUnchecked (i);
  31545. if (child->isVisible())
  31546. {
  31547. g->saveState();
  31548. if (g->reduceClipRegion (child->getX(), child->getY(),
  31549. child->getWidth(), child->getHeight()))
  31550. {
  31551. for (int j = i + 1; j < childComponentList_.size(); ++j)
  31552. {
  31553. const Component* const sibling = childComponentList_.getUnchecked (j);
  31554. if (sibling->flags.opaqueFlag && sibling->isVisible())
  31555. g->excludeClipRegion (sibling->getX(), sibling->getY(),
  31556. sibling->getWidth(), sibling->getHeight());
  31557. }
  31558. if (! g->isClipEmpty())
  31559. {
  31560. g->setOrigin (child->getX(), child->getY());
  31561. child->paintEntireComponent (*g);
  31562. }
  31563. }
  31564. g->restoreState();
  31565. }
  31566. }
  31567. JUCE_TRY
  31568. {
  31569. g->saveState();
  31570. paintOverChildren (*g);
  31571. g->restoreState();
  31572. }
  31573. JUCE_CATCH_EXCEPTION
  31574. if (effect_ != 0)
  31575. {
  31576. delete g;
  31577. effect_->applyEffect (*effectImage, originalContext);
  31578. delete effectImage;
  31579. }
  31580. #ifdef JUCE_DEBUG
  31581. flags.isInsidePaintCall = false;
  31582. #endif
  31583. }
  31584. Image* Component::createComponentSnapshot (const Rectangle& areaToGrab,
  31585. const bool clipImageToComponentBounds)
  31586. {
  31587. Rectangle r (areaToGrab);
  31588. if (clipImageToComponentBounds)
  31589. r = r.getIntersection (Rectangle (0, 0, getWidth(), getHeight()));
  31590. Image* const componentImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31591. jmax (1, r.getWidth()),
  31592. jmax (1, r.getHeight()),
  31593. true);
  31594. Graphics imageContext (*componentImage);
  31595. imageContext.setOrigin (-r.getX(),
  31596. -r.getY());
  31597. paintEntireComponent (imageContext);
  31598. return componentImage;
  31599. }
  31600. void Component::setComponentEffect (ImageEffectFilter* const effect)
  31601. {
  31602. if (effect_ != effect)
  31603. {
  31604. effect_ = effect;
  31605. repaint();
  31606. }
  31607. }
  31608. LookAndFeel& Component::getLookAndFeel() const throw()
  31609. {
  31610. const Component* c = this;
  31611. do
  31612. {
  31613. if (c->lookAndFeel_ != 0)
  31614. return *(c->lookAndFeel_);
  31615. c = c->parentComponent_;
  31616. }
  31617. while (c != 0);
  31618. return LookAndFeel::getDefaultLookAndFeel();
  31619. }
  31620. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  31621. {
  31622. if (lookAndFeel_ != newLookAndFeel)
  31623. {
  31624. lookAndFeel_ = newLookAndFeel;
  31625. sendLookAndFeelChange();
  31626. }
  31627. }
  31628. void Component::lookAndFeelChanged()
  31629. {
  31630. }
  31631. void Component::sendLookAndFeelChange()
  31632. {
  31633. repaint();
  31634. lookAndFeelChanged();
  31635. // (it's not a great idea to do anything that would delete this component
  31636. // during the lookAndFeelChanged() callback)
  31637. jassert (isValidComponent());
  31638. const ComponentDeletionWatcher deletionChecker (this);
  31639. for (int i = childComponentList_.size(); --i >= 0;)
  31640. {
  31641. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  31642. if (deletionChecker.hasBeenDeleted())
  31643. return;
  31644. i = jmin (i, childComponentList_.size());
  31645. }
  31646. }
  31647. static const String getColourPropertyName (const int colourId) throw()
  31648. {
  31649. String s;
  31650. s.preallocateStorage (18);
  31651. s << T("jcclr_") << colourId;
  31652. return s;
  31653. }
  31654. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const throw()
  31655. {
  31656. const String customColour (getComponentProperty (getColourPropertyName (colourId),
  31657. inheritFromParent,
  31658. String::empty));
  31659. if (customColour.isNotEmpty())
  31660. return Colour (customColour.getIntValue());
  31661. return getLookAndFeel().findColour (colourId);
  31662. }
  31663. bool Component::isColourSpecified (const int colourId) const throw()
  31664. {
  31665. return getComponentProperty (getColourPropertyName (colourId),
  31666. false,
  31667. String::empty).isNotEmpty();
  31668. }
  31669. void Component::removeColour (const int colourId)
  31670. {
  31671. if (isColourSpecified (colourId))
  31672. {
  31673. removeComponentProperty (getColourPropertyName (colourId));
  31674. colourChanged();
  31675. }
  31676. }
  31677. void Component::setColour (const int colourId, const Colour& colour)
  31678. {
  31679. const String colourName (getColourPropertyName (colourId));
  31680. const String customColour (getComponentProperty (colourName, false, String::empty));
  31681. if (customColour.isEmpty() || Colour (customColour.getIntValue()) != colour)
  31682. {
  31683. setComponentProperty (colourName, colour);
  31684. colourChanged();
  31685. }
  31686. }
  31687. void Component::copyAllExplicitColoursTo (Component& target) const throw()
  31688. {
  31689. if (propertySet_ != 0)
  31690. {
  31691. const StringPairArray& props = propertySet_->getAllProperties();
  31692. const StringArray& keys = props.getAllKeys();
  31693. for (int i = 0; i < keys.size(); ++i)
  31694. {
  31695. if (keys[i].startsWith (T("jcclr_")))
  31696. {
  31697. target.setComponentProperty (keys[i],
  31698. props.getAllValues() [i]);
  31699. }
  31700. }
  31701. target.colourChanged();
  31702. }
  31703. }
  31704. void Component::colourChanged()
  31705. {
  31706. }
  31707. const Rectangle Component::getUnclippedArea() const
  31708. {
  31709. int x = 0, y = 0, w = getWidth(), h = getHeight();
  31710. Component* p = parentComponent_;
  31711. int px = getX();
  31712. int py = getY();
  31713. while (p != 0)
  31714. {
  31715. if (! Rectangle::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  31716. return Rectangle();
  31717. px += p->getX();
  31718. py += p->getY();
  31719. p = p->parentComponent_;
  31720. }
  31721. return Rectangle (x, y, w, h);
  31722. }
  31723. void Component::clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  31724. const int deltaX, const int deltaY) const throw()
  31725. {
  31726. for (int i = childComponentList_.size(); --i >= 0;)
  31727. {
  31728. const Component* const c = childComponentList_.getUnchecked(i);
  31729. if (c->isVisible())
  31730. {
  31731. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  31732. if (! newClip.isEmpty())
  31733. {
  31734. if (c->isOpaque())
  31735. {
  31736. g.excludeClipRegion (deltaX + newClip.getX(),
  31737. deltaY + newClip.getY(),
  31738. newClip.getWidth(),
  31739. newClip.getHeight());
  31740. }
  31741. else
  31742. {
  31743. newClip.translate (-c->getX(), -c->getY());
  31744. c->clipObscuredRegions (g, newClip,
  31745. c->getX() + deltaX,
  31746. c->getY() + deltaY);
  31747. }
  31748. }
  31749. }
  31750. }
  31751. }
  31752. void Component::getVisibleArea (RectangleList& result,
  31753. const bool includeSiblings) const
  31754. {
  31755. result.clear();
  31756. const Rectangle unclipped (getUnclippedArea());
  31757. if (! unclipped.isEmpty())
  31758. {
  31759. result.add (unclipped);
  31760. if (includeSiblings)
  31761. {
  31762. const Component* const c = getTopLevelComponent();
  31763. int x = 0, y = 0;
  31764. c->relativePositionToOtherComponent (this, x, y);
  31765. c->subtractObscuredRegions (result, x, y,
  31766. Rectangle (0, 0, c->getWidth(), c->getHeight()),
  31767. this);
  31768. }
  31769. subtractObscuredRegions (result, 0, 0, unclipped, 0);
  31770. result.consolidate();
  31771. }
  31772. }
  31773. void Component::subtractObscuredRegions (RectangleList& result,
  31774. const int deltaX,
  31775. const int deltaY,
  31776. const Rectangle& clipRect,
  31777. const Component* const compToAvoid) const throw()
  31778. {
  31779. for (int i = childComponentList_.size(); --i >= 0;)
  31780. {
  31781. const Component* const c = childComponentList_.getUnchecked(i);
  31782. if (c != compToAvoid && c->isVisible())
  31783. {
  31784. if (c->isOpaque())
  31785. {
  31786. Rectangle childBounds (c->bounds_.getIntersection (clipRect));
  31787. childBounds.translate (deltaX, deltaY);
  31788. result.subtract (childBounds);
  31789. }
  31790. else
  31791. {
  31792. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  31793. newClip.translate (-c->getX(), -c->getY());
  31794. c->subtractObscuredRegions (result,
  31795. c->getX() + deltaX,
  31796. c->getY() + deltaY,
  31797. newClip,
  31798. compToAvoid);
  31799. }
  31800. }
  31801. }
  31802. }
  31803. void Component::mouseEnter (const MouseEvent&)
  31804. {
  31805. // base class does nothing
  31806. }
  31807. void Component::mouseExit (const MouseEvent&)
  31808. {
  31809. // base class does nothing
  31810. }
  31811. void Component::mouseDown (const MouseEvent&)
  31812. {
  31813. // base class does nothing
  31814. }
  31815. void Component::mouseUp (const MouseEvent&)
  31816. {
  31817. // base class does nothing
  31818. }
  31819. void Component::mouseDrag (const MouseEvent&)
  31820. {
  31821. // base class does nothing
  31822. }
  31823. void Component::mouseMove (const MouseEvent&)
  31824. {
  31825. // base class does nothing
  31826. }
  31827. void Component::mouseDoubleClick (const MouseEvent&)
  31828. {
  31829. // base class does nothing
  31830. }
  31831. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  31832. {
  31833. // the base class just passes this event up to its parent..
  31834. if (parentComponent_ != 0)
  31835. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  31836. wheelIncrementX, wheelIncrementY);
  31837. }
  31838. void Component::resized()
  31839. {
  31840. // base class does nothing
  31841. }
  31842. void Component::moved()
  31843. {
  31844. // base class does nothing
  31845. }
  31846. void Component::childBoundsChanged (Component*)
  31847. {
  31848. // base class does nothing
  31849. }
  31850. void Component::parentSizeChanged()
  31851. {
  31852. // base class does nothing
  31853. }
  31854. void Component::addComponentListener (ComponentListener* const newListener) throw()
  31855. {
  31856. if (componentListeners_ == 0)
  31857. componentListeners_ = new VoidArray (4);
  31858. componentListeners_->addIfNotAlreadyThere (newListener);
  31859. }
  31860. void Component::removeComponentListener (ComponentListener* const listenerToRemove) throw()
  31861. {
  31862. jassert (isValidComponent());
  31863. if (componentListeners_ != 0)
  31864. componentListeners_->removeValue (listenerToRemove);
  31865. }
  31866. void Component::inputAttemptWhenModal()
  31867. {
  31868. bringModalComponentToFront();
  31869. getLookAndFeel().playAlertSound();
  31870. }
  31871. bool Component::canModalEventBeSentToComponent (const Component*)
  31872. {
  31873. return false;
  31874. }
  31875. void Component::internalModalInputAttempt()
  31876. {
  31877. Component* const current = getCurrentlyModalComponent();
  31878. if (current != 0)
  31879. current->inputAttemptWhenModal();
  31880. }
  31881. void Component::paint (Graphics&)
  31882. {
  31883. // all painting is done in the subclasses
  31884. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  31885. }
  31886. void Component::paintOverChildren (Graphics&)
  31887. {
  31888. // all painting is done in the subclasses
  31889. }
  31890. void Component::handleMessage (const Message& message)
  31891. {
  31892. if (message.intParameter1 == exitModalStateMessage)
  31893. {
  31894. exitModalState (message.intParameter2);
  31895. }
  31896. else if (message.intParameter1 == customCommandMessage)
  31897. {
  31898. handleCommandMessage (message.intParameter2);
  31899. }
  31900. }
  31901. void Component::postCommandMessage (const int commandId) throw()
  31902. {
  31903. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  31904. }
  31905. void Component::handleCommandMessage (int)
  31906. {
  31907. // used by subclasses
  31908. }
  31909. void Component::addMouseListener (MouseListener* const newListener,
  31910. const bool wantsEventsForAllNestedChildComponents) throw()
  31911. {
  31912. // if component methods are being called from threads other than the message
  31913. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31914. checkMessageManagerIsLocked
  31915. if (mouseListeners_ == 0)
  31916. mouseListeners_ = new VoidArray (4);
  31917. if (! mouseListeners_->contains (newListener))
  31918. {
  31919. if (wantsEventsForAllNestedChildComponents)
  31920. {
  31921. mouseListeners_->insert (0, newListener);
  31922. ++numDeepMouseListeners;
  31923. }
  31924. else
  31925. {
  31926. mouseListeners_->add (newListener);
  31927. }
  31928. }
  31929. }
  31930. void Component::removeMouseListener (MouseListener* const listenerToRemove) throw()
  31931. {
  31932. // if component methods are being called from threads other than the message
  31933. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31934. checkMessageManagerIsLocked
  31935. if (mouseListeners_ != 0)
  31936. {
  31937. const int index = mouseListeners_->indexOf (listenerToRemove);
  31938. if (index >= 0)
  31939. {
  31940. if (index < numDeepMouseListeners)
  31941. --numDeepMouseListeners;
  31942. mouseListeners_->remove (index);
  31943. }
  31944. }
  31945. }
  31946. void Component::internalMouseEnter (int x, int y, int64 time)
  31947. {
  31948. if (isCurrentlyBlockedByAnotherModalComponent())
  31949. {
  31950. // if something else is modal, always just show a normal mouse cursor
  31951. if (componentUnderMouse == this)
  31952. {
  31953. ComponentPeer* const peer = getPeer();
  31954. if (peer != 0)
  31955. {
  31956. MouseCursor mc (MouseCursor::NormalCursor);
  31957. mc.showInWindow (peer);
  31958. }
  31959. }
  31960. return;
  31961. }
  31962. if (! flags.mouseInsideFlag)
  31963. {
  31964. flags.mouseInsideFlag = true;
  31965. flags.mouseOverFlag = true;
  31966. flags.draggingFlag = false;
  31967. if (isValidComponent())
  31968. {
  31969. const ComponentDeletionWatcher deletionChecker (this);
  31970. if (flags.repaintOnMouseActivityFlag)
  31971. repaint();
  31972. const MouseEvent me (x, y,
  31973. ModifierKeys::getCurrentModifiers(),
  31974. this,
  31975. Time (time),
  31976. x, y,
  31977. Time (time),
  31978. 0, false);
  31979. mouseEnter (me);
  31980. if (deletionChecker.hasBeenDeleted())
  31981. return;
  31982. Desktop::getInstance().resetTimer();
  31983. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  31984. {
  31985. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseEnter (me);
  31986. if (deletionChecker.hasBeenDeleted())
  31987. return;
  31988. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  31989. }
  31990. if (mouseListeners_ != 0)
  31991. {
  31992. for (int i = mouseListeners_->size(); --i >= 0;)
  31993. {
  31994. ((MouseListener*) mouseListeners_->getUnchecked(i))->mouseEnter (me);
  31995. if (deletionChecker.hasBeenDeleted())
  31996. return;
  31997. i = jmin (i, mouseListeners_->size());
  31998. }
  31999. }
  32000. const Component* p = parentComponent_;
  32001. while (p != 0)
  32002. {
  32003. const ComponentDeletionWatcher parentDeletionChecker (p);
  32004. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32005. {
  32006. ((MouseListener*) (p->mouseListeners_->getUnchecked(i)))->mouseEnter (me);
  32007. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32008. return;
  32009. i = jmin (i, p->numDeepMouseListeners);
  32010. }
  32011. p = p->parentComponent_;
  32012. }
  32013. }
  32014. }
  32015. if (componentUnderMouse == this)
  32016. internalUpdateMouseCursor (true);
  32017. }
  32018. void Component::internalMouseExit (int x, int y, int64 time)
  32019. {
  32020. const ComponentDeletionWatcher deletionChecker (this);
  32021. if (flags.draggingFlag)
  32022. {
  32023. internalMouseUp (ModifierKeys::getCurrentModifiers().getRawFlags(), x, y, time);
  32024. if (deletionChecker.hasBeenDeleted())
  32025. return;
  32026. }
  32027. enableUnboundedMouseMovement (false);
  32028. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32029. {
  32030. flags.mouseInsideFlag = false;
  32031. flags.mouseOverFlag = false;
  32032. flags.draggingFlag = false;
  32033. if (flags.repaintOnMouseActivityFlag)
  32034. repaint();
  32035. const MouseEvent me (x, y,
  32036. ModifierKeys::getCurrentModifiers(),
  32037. this,
  32038. Time (time),
  32039. x, y,
  32040. Time (time),
  32041. 0, false);
  32042. mouseExit (me);
  32043. if (deletionChecker.hasBeenDeleted())
  32044. return;
  32045. Desktop::getInstance().resetTimer();
  32046. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32047. {
  32048. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseExit (me);
  32049. if (deletionChecker.hasBeenDeleted())
  32050. return;
  32051. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32052. }
  32053. if (mouseListeners_ != 0)
  32054. {
  32055. for (int i = mouseListeners_->size(); --i >= 0;)
  32056. {
  32057. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32058. if (deletionChecker.hasBeenDeleted())
  32059. return;
  32060. i = jmin (i, mouseListeners_->size());
  32061. }
  32062. }
  32063. const Component* p = parentComponent_;
  32064. while (p != 0)
  32065. {
  32066. const ComponentDeletionWatcher parentDeletionChecker (p);
  32067. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32068. {
  32069. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseExit (me);
  32070. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32071. return;
  32072. i = jmin (i, p->numDeepMouseListeners);
  32073. }
  32074. p = p->parentComponent_;
  32075. }
  32076. }
  32077. }
  32078. class InternalDragRepeater : public Timer
  32079. {
  32080. public:
  32081. InternalDragRepeater()
  32082. {}
  32083. ~InternalDragRepeater()
  32084. {}
  32085. void timerCallback()
  32086. {
  32087. Component* const c = Component::getComponentUnderMouse();
  32088. if (c != 0 && c->isMouseButtonDown())
  32089. {
  32090. int x, y;
  32091. c->getMouseXYRelative (x, y);
  32092. // the offsets have been added on, so must be taken off before calling the
  32093. // drag.. otherwise they'll be added twice
  32094. x -= unboundedMouseOffsetX;
  32095. y -= unboundedMouseOffsetY;
  32096. c->internalMouseDrag (x, y, Time::currentTimeMillis());
  32097. }
  32098. }
  32099. juce_UseDebuggingNewOperator
  32100. };
  32101. static InternalDragRepeater* dragRepeater = 0;
  32102. void Component::beginDragAutoRepeat (const int interval)
  32103. {
  32104. if (interval > 0)
  32105. {
  32106. if (dragRepeater == 0)
  32107. dragRepeater = new InternalDragRepeater();
  32108. if (dragRepeater->getTimerInterval() != interval)
  32109. dragRepeater->startTimer (interval);
  32110. }
  32111. else
  32112. {
  32113. deleteAndZero (dragRepeater);
  32114. }
  32115. }
  32116. void Component::internalMouseDown (const int x, const int y)
  32117. {
  32118. const ComponentDeletionWatcher deletionChecker (this);
  32119. if (isCurrentlyBlockedByAnotherModalComponent())
  32120. {
  32121. internalModalInputAttempt();
  32122. if (deletionChecker.hasBeenDeleted())
  32123. return;
  32124. // If processing the input attempt has exited the modal loop, we'll allow the event
  32125. // to be delivered..
  32126. if (isCurrentlyBlockedByAnotherModalComponent())
  32127. {
  32128. // allow blocked mouse-events to go to global listeners..
  32129. const MouseEvent me (x, y,
  32130. ModifierKeys::getCurrentModifiers(),
  32131. this,
  32132. Time (juce_recentMouseDownTimes[0]),
  32133. x, y,
  32134. Time (juce_recentMouseDownTimes[0]),
  32135. countMouseClicks(),
  32136. false);
  32137. Desktop::getInstance().resetTimer();
  32138. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32139. {
  32140. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  32141. if (deletionChecker.hasBeenDeleted())
  32142. return;
  32143. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32144. }
  32145. return;
  32146. }
  32147. }
  32148. {
  32149. Component* c = this;
  32150. while (c != 0)
  32151. {
  32152. if (c->isBroughtToFrontOnMouseClick())
  32153. {
  32154. c->toFront (true);
  32155. if (deletionChecker.hasBeenDeleted())
  32156. return;
  32157. }
  32158. c = c->parentComponent_;
  32159. }
  32160. }
  32161. if (! flags.dontFocusOnMouseClickFlag)
  32162. grabFocusInternal (focusChangedByMouseClick);
  32163. if (! deletionChecker.hasBeenDeleted())
  32164. {
  32165. flags.draggingFlag = true;
  32166. flags.mouseOverFlag = true;
  32167. if (flags.repaintOnMouseActivityFlag)
  32168. repaint();
  32169. const MouseEvent me (x, y,
  32170. ModifierKeys::getCurrentModifiers(),
  32171. this,
  32172. Time (juce_recentMouseDownTimes[0]),
  32173. x, y,
  32174. Time (juce_recentMouseDownTimes[0]),
  32175. countMouseClicks(),
  32176. false);
  32177. mouseDown (me);
  32178. if (deletionChecker.hasBeenDeleted())
  32179. return;
  32180. Desktop::getInstance().resetTimer();
  32181. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32182. {
  32183. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  32184. if (deletionChecker.hasBeenDeleted())
  32185. return;
  32186. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32187. }
  32188. if (mouseListeners_ != 0)
  32189. {
  32190. for (int i = mouseListeners_->size(); --i >= 0;)
  32191. {
  32192. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32193. if (deletionChecker.hasBeenDeleted())
  32194. return;
  32195. i = jmin (i, mouseListeners_->size());
  32196. }
  32197. }
  32198. const Component* p = parentComponent_;
  32199. while (p != 0)
  32200. {
  32201. const ComponentDeletionWatcher parentDeletionChecker (p);
  32202. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32203. {
  32204. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDown (me);
  32205. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32206. return;
  32207. i = jmin (i, p->numDeepMouseListeners);
  32208. }
  32209. p = p->parentComponent_;
  32210. }
  32211. }
  32212. }
  32213. void Component::internalMouseUp (const int oldModifiers, int x, int y, const int64 time)
  32214. {
  32215. if (isValidComponent() && flags.draggingFlag)
  32216. {
  32217. flags.draggingFlag = false;
  32218. deleteAndZero (dragRepeater);
  32219. x += unboundedMouseOffsetX;
  32220. y += unboundedMouseOffsetY;
  32221. juce_LastMousePosX = x;
  32222. juce_LastMousePosY = y;
  32223. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  32224. const ComponentDeletionWatcher deletionChecker (this);
  32225. if (flags.repaintOnMouseActivityFlag)
  32226. repaint();
  32227. int mdx = juce_recentMouseDownX[0];
  32228. int mdy = juce_recentMouseDownY[0];
  32229. globalPositionToRelative (mdx, mdy);
  32230. const MouseEvent me (x, y,
  32231. oldModifiers,
  32232. this,
  32233. Time (time),
  32234. mdx, mdy,
  32235. Time (juce_recentMouseDownTimes [0]),
  32236. countMouseClicks(),
  32237. juce_MouseHasMovedSignificantlySincePressed
  32238. || juce_recentMouseDownTimes[0] + 300 < time);
  32239. mouseUp (me);
  32240. if (deletionChecker.hasBeenDeleted())
  32241. return;
  32242. Desktop::getInstance().resetTimer();
  32243. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32244. {
  32245. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseUp (me);
  32246. if (deletionChecker.hasBeenDeleted())
  32247. return;
  32248. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32249. }
  32250. if (mouseListeners_ != 0)
  32251. {
  32252. for (int i = mouseListeners_->size(); --i >= 0;)
  32253. {
  32254. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32255. if (deletionChecker.hasBeenDeleted())
  32256. return;
  32257. i = jmin (i, mouseListeners_->size());
  32258. }
  32259. }
  32260. {
  32261. const Component* p = parentComponent_;
  32262. while (p != 0)
  32263. {
  32264. const ComponentDeletionWatcher parentDeletionChecker (p);
  32265. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32266. {
  32267. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseUp (me);
  32268. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32269. return;
  32270. i = jmin (i, p->numDeepMouseListeners);
  32271. }
  32272. p = p->parentComponent_;
  32273. }
  32274. }
  32275. // check for double-click
  32276. if (me.getNumberOfClicks() >= 2)
  32277. {
  32278. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32279. mouseDoubleClick (me);
  32280. int i;
  32281. for (i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32282. {
  32283. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDoubleClick (me);
  32284. if (deletionChecker.hasBeenDeleted())
  32285. return;
  32286. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32287. }
  32288. for (i = numListeners; --i >= 0;)
  32289. {
  32290. if (deletionChecker.hasBeenDeleted() || mouseListeners_ == 0)
  32291. return;
  32292. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  32293. if (ml != 0)
  32294. ml->mouseDoubleClick (me);
  32295. }
  32296. if (deletionChecker.hasBeenDeleted())
  32297. return;
  32298. const Component* p = parentComponent_;
  32299. while (p != 0)
  32300. {
  32301. const ComponentDeletionWatcher parentDeletionChecker (p);
  32302. for (i = p->numDeepMouseListeners; --i >= 0;)
  32303. {
  32304. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDoubleClick (me);
  32305. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32306. return;
  32307. i = jmin (i, p->numDeepMouseListeners);
  32308. }
  32309. p = p->parentComponent_;
  32310. }
  32311. }
  32312. }
  32313. enableUnboundedMouseMovement (false);
  32314. }
  32315. void Component::internalMouseDrag (int x, int y, const int64 time)
  32316. {
  32317. if (isValidComponent() && flags.draggingFlag)
  32318. {
  32319. flags.mouseOverFlag = reallyContains (x, y, false);
  32320. x += unboundedMouseOffsetX;
  32321. y += unboundedMouseOffsetY;
  32322. juce_LastMousePosX = x;
  32323. juce_LastMousePosY = y;
  32324. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  32325. juce_MouseHasMovedSignificantlySincePressed
  32326. = juce_MouseHasMovedSignificantlySincePressed
  32327. || abs (juce_recentMouseDownX[0] - juce_LastMousePosX) >= 4
  32328. || abs (juce_recentMouseDownY[0] - juce_LastMousePosY) >= 4;
  32329. const ComponentDeletionWatcher deletionChecker (this);
  32330. int mdx = juce_recentMouseDownX[0];
  32331. int mdy = juce_recentMouseDownY[0];
  32332. globalPositionToRelative (mdx, mdy);
  32333. const MouseEvent me (x, y,
  32334. ModifierKeys::getCurrentModifiers(),
  32335. this,
  32336. Time (time),
  32337. mdx, mdy,
  32338. Time (juce_recentMouseDownTimes[0]),
  32339. countMouseClicks(),
  32340. juce_MouseHasMovedSignificantlySincePressed
  32341. || juce_recentMouseDownTimes[0] + 300 < time);
  32342. mouseDrag (me);
  32343. if (deletionChecker.hasBeenDeleted())
  32344. return;
  32345. Desktop::getInstance().resetTimer();
  32346. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32347. {
  32348. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDrag (me);
  32349. if (deletionChecker.hasBeenDeleted())
  32350. return;
  32351. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32352. }
  32353. if (mouseListeners_ != 0)
  32354. {
  32355. for (int i = mouseListeners_->size(); --i >= 0;)
  32356. {
  32357. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  32358. if (deletionChecker.hasBeenDeleted())
  32359. return;
  32360. i = jmin (i, mouseListeners_->size());
  32361. }
  32362. }
  32363. const Component* p = parentComponent_;
  32364. while (p != 0)
  32365. {
  32366. const ComponentDeletionWatcher parentDeletionChecker (p);
  32367. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32368. {
  32369. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDrag (me);
  32370. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32371. return;
  32372. i = jmin (i, p->numDeepMouseListeners);
  32373. }
  32374. p = p->parentComponent_;
  32375. }
  32376. if (this == componentUnderMouse)
  32377. {
  32378. if (isUnboundedMouseModeOn)
  32379. {
  32380. Rectangle screenArea (getParentMonitorArea().expanded (-2, -2));
  32381. int mx, my;
  32382. Desktop::getMousePosition (mx, my);
  32383. if (! screenArea.contains (mx, my))
  32384. {
  32385. int deltaX = 0, deltaY = 0;
  32386. if (mx <= screenArea.getX() || mx >= screenArea.getRight())
  32387. deltaX = getScreenX() + getWidth() / 2 - mx;
  32388. if (my <= screenArea.getY() || my >= screenArea.getBottom())
  32389. deltaY = getScreenY() + getHeight() / 2 - my;
  32390. unboundedMouseOffsetX -= deltaX;
  32391. unboundedMouseOffsetY -= deltaY;
  32392. Desktop::setMousePosition (mx + deltaX,
  32393. my + deltaY);
  32394. }
  32395. else if (isCursorVisibleUntilOffscreen
  32396. && (unboundedMouseOffsetX != 0 || unboundedMouseOffsetY != 0)
  32397. && screenArea.contains (mx + unboundedMouseOffsetX,
  32398. my + unboundedMouseOffsetY))
  32399. {
  32400. mx += unboundedMouseOffsetX;
  32401. my += unboundedMouseOffsetY;
  32402. unboundedMouseOffsetX = 0;
  32403. unboundedMouseOffsetY = 0;
  32404. Desktop::setMousePosition (mx, my);
  32405. }
  32406. }
  32407. internalUpdateMouseCursor (false);
  32408. }
  32409. }
  32410. }
  32411. void Component::internalMouseMove (const int x, const int y, const int64 time)
  32412. {
  32413. const ComponentDeletionWatcher deletionChecker (this);
  32414. if (isValidComponent())
  32415. {
  32416. const MouseEvent me (x, y,
  32417. ModifierKeys::getCurrentModifiers(),
  32418. this,
  32419. Time (time),
  32420. x, y,
  32421. Time (time),
  32422. 0, false);
  32423. if (isCurrentlyBlockedByAnotherModalComponent())
  32424. {
  32425. // allow blocked mouse-events to go to global listeners..
  32426. Desktop::getInstance().sendMouseMove();
  32427. }
  32428. else
  32429. {
  32430. if (this == componentUnderMouse)
  32431. internalUpdateMouseCursor (false);
  32432. flags.mouseOverFlag = true;
  32433. mouseMove (me);
  32434. if (deletionChecker.hasBeenDeleted())
  32435. return;
  32436. Desktop::getInstance().resetTimer();
  32437. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32438. {
  32439. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseMove (me);
  32440. if (deletionChecker.hasBeenDeleted())
  32441. return;
  32442. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32443. }
  32444. if (mouseListeners_ != 0)
  32445. {
  32446. for (int i = mouseListeners_->size(); --i >= 0;)
  32447. {
  32448. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  32449. if (deletionChecker.hasBeenDeleted())
  32450. return;
  32451. i = jmin (i, mouseListeners_->size());
  32452. }
  32453. }
  32454. const Component* p = parentComponent_;
  32455. while (p != 0)
  32456. {
  32457. const ComponentDeletionWatcher parentDeletionChecker (p);
  32458. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32459. {
  32460. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseMove (me);
  32461. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32462. return;
  32463. i = jmin (i, p->numDeepMouseListeners);
  32464. }
  32465. p = p->parentComponent_;
  32466. }
  32467. }
  32468. }
  32469. }
  32470. void Component::internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time)
  32471. {
  32472. const ComponentDeletionWatcher deletionChecker (this);
  32473. const float wheelIncrementX = intAmountX * (1.0f / 256.0f);
  32474. const float wheelIncrementY = intAmountY * (1.0f / 256.0f);
  32475. int mx, my;
  32476. getMouseXYRelative (mx, my);
  32477. const MouseEvent me (mx, my,
  32478. ModifierKeys::getCurrentModifiers(),
  32479. this,
  32480. Time (time),
  32481. mx, my,
  32482. Time (time),
  32483. 0, false);
  32484. if (isCurrentlyBlockedByAnotherModalComponent())
  32485. {
  32486. // allow blocked mouse-events to go to global listeners..
  32487. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32488. {
  32489. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32490. if (deletionChecker.hasBeenDeleted())
  32491. return;
  32492. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32493. }
  32494. }
  32495. else
  32496. {
  32497. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32498. if (deletionChecker.hasBeenDeleted())
  32499. return;
  32500. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32501. {
  32502. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32503. if (deletionChecker.hasBeenDeleted())
  32504. return;
  32505. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32506. }
  32507. if (mouseListeners_ != 0)
  32508. {
  32509. for (int i = mouseListeners_->size(); --i >= 0;)
  32510. {
  32511. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32512. if (deletionChecker.hasBeenDeleted())
  32513. return;
  32514. i = jmin (i, mouseListeners_->size());
  32515. }
  32516. }
  32517. const Component* p = parentComponent_;
  32518. while (p != 0)
  32519. {
  32520. const ComponentDeletionWatcher parentDeletionChecker (p);
  32521. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32522. {
  32523. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32524. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32525. return;
  32526. i = jmin (i, p->numDeepMouseListeners);
  32527. }
  32528. p = p->parentComponent_;
  32529. }
  32530. sendFakeMouseMove();
  32531. }
  32532. }
  32533. void Component::sendFakeMouseMove() const
  32534. {
  32535. ComponentPeer* const peer = getPeer();
  32536. if (peer != 0)
  32537. peer->sendFakeMouseMove();
  32538. }
  32539. void Component::broughtToFront()
  32540. {
  32541. }
  32542. void Component::internalBroughtToFront()
  32543. {
  32544. if (isValidComponent())
  32545. {
  32546. if (flags.hasHeavyweightPeerFlag)
  32547. Desktop::getInstance().componentBroughtToFront (this);
  32548. const ComponentDeletionWatcher deletionChecker (this);
  32549. broughtToFront();
  32550. if (deletionChecker.hasBeenDeleted())
  32551. return;
  32552. if (componentListeners_ != 0)
  32553. {
  32554. for (int i = componentListeners_->size(); --i >= 0;)
  32555. {
  32556. ((ComponentListener*) componentListeners_->getUnchecked (i))
  32557. ->componentBroughtToFront (*this);
  32558. if (deletionChecker.hasBeenDeleted())
  32559. return;
  32560. i = jmin (i, componentListeners_->size());
  32561. }
  32562. }
  32563. // when brought to the front and there's a modal component blocking this one,
  32564. // we need to bring the modal one to the front instead..
  32565. Component* const cm = getCurrentlyModalComponent();
  32566. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  32567. bringModalComponentToFront();
  32568. }
  32569. }
  32570. void Component::focusGained (FocusChangeType)
  32571. {
  32572. // base class does nothing
  32573. }
  32574. void Component::internalFocusGain (const FocusChangeType cause)
  32575. {
  32576. const ComponentDeletionWatcher deletionChecker (this);
  32577. focusGained (cause);
  32578. if (! deletionChecker.hasBeenDeleted())
  32579. internalChildFocusChange (cause);
  32580. }
  32581. void Component::focusLost (FocusChangeType)
  32582. {
  32583. // base class does nothing
  32584. }
  32585. void Component::internalFocusLoss (const FocusChangeType cause)
  32586. {
  32587. const ComponentDeletionWatcher deletionChecker (this);
  32588. focusLost (focusChangedDirectly);
  32589. if (! deletionChecker.hasBeenDeleted())
  32590. internalChildFocusChange (cause);
  32591. }
  32592. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  32593. {
  32594. // base class does nothing
  32595. }
  32596. void Component::internalChildFocusChange (FocusChangeType cause)
  32597. {
  32598. const bool childIsNowFocused = hasKeyboardFocus (true);
  32599. if (flags.childCompFocusedFlag != childIsNowFocused)
  32600. {
  32601. flags.childCompFocusedFlag = childIsNowFocused;
  32602. const ComponentDeletionWatcher deletionChecker (this);
  32603. focusOfChildComponentChanged (cause);
  32604. if (deletionChecker.hasBeenDeleted())
  32605. return;
  32606. }
  32607. if (parentComponent_ != 0)
  32608. parentComponent_->internalChildFocusChange (cause);
  32609. }
  32610. bool Component::isEnabled() const throw()
  32611. {
  32612. return (! flags.isDisabledFlag)
  32613. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  32614. }
  32615. void Component::setEnabled (const bool shouldBeEnabled)
  32616. {
  32617. if (flags.isDisabledFlag == shouldBeEnabled)
  32618. {
  32619. flags.isDisabledFlag = ! shouldBeEnabled;
  32620. // if any parent components are disabled, setting our flag won't make a difference,
  32621. // so no need to send a change message
  32622. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  32623. sendEnablementChangeMessage();
  32624. }
  32625. }
  32626. void Component::sendEnablementChangeMessage()
  32627. {
  32628. const ComponentDeletionWatcher deletionChecker (this);
  32629. enablementChanged();
  32630. if (deletionChecker.hasBeenDeleted())
  32631. return;
  32632. for (int i = getNumChildComponents(); --i >= 0;)
  32633. {
  32634. Component* const c = getChildComponent (i);
  32635. if (c != 0)
  32636. {
  32637. c->sendEnablementChangeMessage();
  32638. if (deletionChecker.hasBeenDeleted())
  32639. return;
  32640. }
  32641. }
  32642. }
  32643. void Component::enablementChanged()
  32644. {
  32645. }
  32646. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  32647. {
  32648. flags.wantsFocusFlag = wantsFocus;
  32649. }
  32650. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  32651. {
  32652. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  32653. }
  32654. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  32655. {
  32656. return ! flags.dontFocusOnMouseClickFlag;
  32657. }
  32658. bool Component::getWantsKeyboardFocus() const throw()
  32659. {
  32660. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  32661. }
  32662. void Component::setFocusContainer (const bool isFocusContainer) throw()
  32663. {
  32664. flags.isFocusContainerFlag = isFocusContainer;
  32665. }
  32666. bool Component::isFocusContainer() const throw()
  32667. {
  32668. return flags.isFocusContainerFlag;
  32669. }
  32670. int Component::getExplicitFocusOrder() const throw()
  32671. {
  32672. return getComponentPropertyInt (T("_jexfo"), false, 0);
  32673. }
  32674. void Component::setExplicitFocusOrder (const int newFocusOrderIndex) throw()
  32675. {
  32676. setComponentProperty (T("_jexfo"), newFocusOrderIndex);
  32677. }
  32678. KeyboardFocusTraverser* Component::createFocusTraverser()
  32679. {
  32680. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  32681. return new KeyboardFocusTraverser();
  32682. return parentComponent_->createFocusTraverser();
  32683. }
  32684. void Component::takeKeyboardFocus (const FocusChangeType cause)
  32685. {
  32686. // give the focus to this component
  32687. if (currentlyFocusedComponent != this)
  32688. {
  32689. JUCE_TRY
  32690. {
  32691. // get the focus onto our desktop window
  32692. ComponentPeer* const peer = getPeer();
  32693. if (peer != 0)
  32694. {
  32695. const ComponentDeletionWatcher deletionChecker (this);
  32696. peer->grabFocus();
  32697. if (peer->isFocused() && currentlyFocusedComponent != this)
  32698. {
  32699. Component* const componentLosingFocus = currentlyFocusedComponent;
  32700. currentlyFocusedComponent = this;
  32701. Desktop::getInstance().triggerFocusCallback();
  32702. // call this after setting currentlyFocusedComponent so that the one that's
  32703. // losing it has a chance to see where focus is going
  32704. if (componentLosingFocus->isValidComponent())
  32705. componentLosingFocus->internalFocusLoss (cause);
  32706. if (currentlyFocusedComponent == this)
  32707. {
  32708. focusGained (cause);
  32709. if (! deletionChecker.hasBeenDeleted())
  32710. internalChildFocusChange (cause);
  32711. }
  32712. }
  32713. }
  32714. }
  32715. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32716. catch (const std::exception& e)
  32717. {
  32718. currentlyFocusedComponent = 0;
  32719. Desktop::getInstance().triggerFocusCallback();
  32720. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32721. }
  32722. catch (...)
  32723. {
  32724. currentlyFocusedComponent = 0;
  32725. Desktop::getInstance().triggerFocusCallback();
  32726. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32727. }
  32728. #endif
  32729. }
  32730. }
  32731. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  32732. {
  32733. if (isShowing())
  32734. {
  32735. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  32736. {
  32737. takeKeyboardFocus (cause);
  32738. }
  32739. else
  32740. {
  32741. if (isParentOf (currentlyFocusedComponent)
  32742. && currentlyFocusedComponent->isShowing())
  32743. {
  32744. // do nothing if the focused component is actually a child of ours..
  32745. }
  32746. else
  32747. {
  32748. // find the default child component..
  32749. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  32750. if (traverser != 0)
  32751. {
  32752. Component* const defaultComp = traverser->getDefaultComponent (this);
  32753. delete traverser;
  32754. if (defaultComp != 0)
  32755. {
  32756. defaultComp->grabFocusInternal (cause, false);
  32757. return;
  32758. }
  32759. }
  32760. if (canTryParent && parentComponent_ != 0)
  32761. {
  32762. // if no children want it and we're allowed to try our parent comp,
  32763. // then pass up to parent, which will try our siblings.
  32764. parentComponent_->grabFocusInternal (cause, true);
  32765. }
  32766. }
  32767. }
  32768. }
  32769. }
  32770. void Component::grabKeyboardFocus()
  32771. {
  32772. // if component methods are being called from threads other than the message
  32773. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32774. checkMessageManagerIsLocked
  32775. grabFocusInternal (focusChangedDirectly);
  32776. }
  32777. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  32778. {
  32779. // if component methods are being called from threads other than the message
  32780. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32781. checkMessageManagerIsLocked
  32782. if (parentComponent_ != 0)
  32783. {
  32784. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  32785. if (traverser != 0)
  32786. {
  32787. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  32788. : traverser->getPreviousComponent (this);
  32789. delete traverser;
  32790. if (nextComp != 0)
  32791. {
  32792. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  32793. {
  32794. const ComponentDeletionWatcher deletionChecker (nextComp);
  32795. internalModalInputAttempt();
  32796. if (deletionChecker.hasBeenDeleted()
  32797. || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  32798. return;
  32799. }
  32800. nextComp->grabFocusInternal (focusChangedByTabKey);
  32801. return;
  32802. }
  32803. }
  32804. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  32805. }
  32806. }
  32807. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const throw()
  32808. {
  32809. return (currentlyFocusedComponent == this)
  32810. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  32811. }
  32812. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  32813. {
  32814. return currentlyFocusedComponent;
  32815. }
  32816. void Component::giveAwayFocus()
  32817. {
  32818. // use a copy so we can clear the value before the call
  32819. Component* const componentLosingFocus = currentlyFocusedComponent;
  32820. currentlyFocusedComponent = 0;
  32821. Desktop::getInstance().triggerFocusCallback();
  32822. if (componentLosingFocus->isValidComponent())
  32823. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  32824. }
  32825. bool Component::isMouseOver() const throw()
  32826. {
  32827. return flags.mouseOverFlag;
  32828. }
  32829. bool Component::isMouseButtonDown() const throw()
  32830. {
  32831. return flags.draggingFlag;
  32832. }
  32833. bool Component::isMouseOverOrDragging() const throw()
  32834. {
  32835. return flags.mouseOverFlag || flags.draggingFlag;
  32836. }
  32837. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  32838. {
  32839. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  32840. }
  32841. void Component::getMouseXYRelative (int& mx, int& my) const throw()
  32842. {
  32843. Desktop::getMousePosition (mx, my);
  32844. globalPositionToRelative (mx, my);
  32845. mx += unboundedMouseOffsetX;
  32846. my += unboundedMouseOffsetY;
  32847. }
  32848. void Component::enableUnboundedMouseMovement (bool enable,
  32849. bool keepCursorVisibleUntilOffscreen) throw()
  32850. {
  32851. enable = enable && isMouseButtonDown();
  32852. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  32853. if (enable != isUnboundedMouseModeOn)
  32854. {
  32855. if ((! enable) && ((! isCursorVisibleUntilOffscreen)
  32856. || unboundedMouseOffsetX != 0
  32857. || unboundedMouseOffsetY != 0))
  32858. {
  32859. // when released, return the mouse to within the component's bounds
  32860. int mx, my;
  32861. getMouseXYRelative (mx, my);
  32862. mx = jlimit (0, getWidth(), mx);
  32863. my = jlimit (0, getHeight(), my);
  32864. relativePositionToGlobal (mx, my);
  32865. Desktop::setMousePosition (mx, my);
  32866. }
  32867. isUnboundedMouseModeOn = enable;
  32868. unboundedMouseOffsetX = 0;
  32869. unboundedMouseOffsetY = 0;
  32870. internalUpdateMouseCursor (true);
  32871. }
  32872. }
  32873. Component* JUCE_CALLTYPE Component::getComponentUnderMouse() throw()
  32874. {
  32875. return componentUnderMouse;
  32876. }
  32877. const Rectangle Component::getParentMonitorArea() const throw()
  32878. {
  32879. int centreX = getWidth() / 2;
  32880. int centreY = getHeight() / 2;
  32881. relativePositionToGlobal (centreX, centreY);
  32882. return Desktop::getInstance().getMonitorAreaContaining (centreX, centreY);
  32883. }
  32884. void Component::addKeyListener (KeyListener* const newListener) throw()
  32885. {
  32886. if (keyListeners_ == 0)
  32887. keyListeners_ = new VoidArray (4);
  32888. keyListeners_->addIfNotAlreadyThere (newListener);
  32889. }
  32890. void Component::removeKeyListener (KeyListener* const listenerToRemove) throw()
  32891. {
  32892. if (keyListeners_ != 0)
  32893. keyListeners_->removeValue (listenerToRemove);
  32894. }
  32895. bool Component::keyPressed (const KeyPress&)
  32896. {
  32897. return false;
  32898. }
  32899. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  32900. {
  32901. return false;
  32902. }
  32903. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  32904. {
  32905. if (parentComponent_ != 0)
  32906. parentComponent_->modifierKeysChanged (modifiers);
  32907. }
  32908. void Component::internalModifierKeysChanged()
  32909. {
  32910. sendFakeMouseMove();
  32911. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  32912. }
  32913. ComponentPeer* Component::getPeer() const throw()
  32914. {
  32915. if (flags.hasHeavyweightPeerFlag)
  32916. return ComponentPeer::getPeerFor (this);
  32917. else if (parentComponent_ != 0)
  32918. return parentComponent_->getPeer();
  32919. else
  32920. return 0;
  32921. }
  32922. const String Component::getComponentProperty (const String& keyName,
  32923. const bool useParentComponentIfNotFound,
  32924. const String& defaultReturnValue) const throw()
  32925. {
  32926. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  32927. return propertySet_->getValue (keyName, defaultReturnValue);
  32928. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  32929. return parentComponent_->getComponentProperty (keyName, true, defaultReturnValue);
  32930. return defaultReturnValue;
  32931. }
  32932. int Component::getComponentPropertyInt (const String& keyName,
  32933. const bool useParentComponentIfNotFound,
  32934. const int defaultReturnValue) const throw()
  32935. {
  32936. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  32937. return propertySet_->getIntValue (keyName, defaultReturnValue);
  32938. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  32939. return parentComponent_->getComponentPropertyInt (keyName, true, defaultReturnValue);
  32940. return defaultReturnValue;
  32941. }
  32942. double Component::getComponentPropertyDouble (const String& keyName,
  32943. const bool useParentComponentIfNotFound,
  32944. const double defaultReturnValue) const throw()
  32945. {
  32946. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  32947. return propertySet_->getDoubleValue (keyName, defaultReturnValue);
  32948. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  32949. return parentComponent_->getComponentPropertyDouble (keyName, true, defaultReturnValue);
  32950. return defaultReturnValue;
  32951. }
  32952. bool Component::getComponentPropertyBool (const String& keyName,
  32953. const bool useParentComponentIfNotFound,
  32954. const bool defaultReturnValue) const throw()
  32955. {
  32956. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  32957. return propertySet_->getBoolValue (keyName, defaultReturnValue);
  32958. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  32959. return parentComponent_->getComponentPropertyBool (keyName, true, defaultReturnValue);
  32960. return defaultReturnValue;
  32961. }
  32962. const Colour Component::getComponentPropertyColour (const String& keyName,
  32963. const bool useParentComponentIfNotFound,
  32964. const Colour& defaultReturnValue) const throw()
  32965. {
  32966. return Colour ((uint32) getComponentPropertyInt (keyName,
  32967. useParentComponentIfNotFound,
  32968. defaultReturnValue.getARGB()));
  32969. }
  32970. void Component::setComponentProperty (const String& keyName, const String& value) throw()
  32971. {
  32972. if (propertySet_ == 0)
  32973. propertySet_ = new PropertySet();
  32974. propertySet_->setValue (keyName, value);
  32975. }
  32976. void Component::setComponentProperty (const String& keyName, const int value) throw()
  32977. {
  32978. if (propertySet_ == 0)
  32979. propertySet_ = new PropertySet();
  32980. propertySet_->setValue (keyName, value);
  32981. }
  32982. void Component::setComponentProperty (const String& keyName, const double value) throw()
  32983. {
  32984. if (propertySet_ == 0)
  32985. propertySet_ = new PropertySet();
  32986. propertySet_->setValue (keyName, value);
  32987. }
  32988. void Component::setComponentProperty (const String& keyName, const bool value) throw()
  32989. {
  32990. if (propertySet_ == 0)
  32991. propertySet_ = new PropertySet();
  32992. propertySet_->setValue (keyName, value);
  32993. }
  32994. void Component::setComponentProperty (const String& keyName, const Colour& colour) throw()
  32995. {
  32996. setComponentProperty (keyName, (int) colour.getARGB());
  32997. }
  32998. void Component::removeComponentProperty (const String& keyName) throw()
  32999. {
  33000. if (propertySet_ != 0)
  33001. propertySet_->removeValue (keyName);
  33002. }
  33003. ComponentDeletionWatcher::ComponentDeletionWatcher (const Component* const componentToWatch_) throw()
  33004. : componentToWatch (componentToWatch_),
  33005. componentUID (componentToWatch_->getComponentUID())
  33006. {
  33007. // not possible to check on an already-deleted object..
  33008. jassert (componentToWatch_->isValidComponent());
  33009. }
  33010. ComponentDeletionWatcher::~ComponentDeletionWatcher() throw() {}
  33011. bool ComponentDeletionWatcher::hasBeenDeleted() const throw()
  33012. {
  33013. return ! (componentToWatch->isValidComponent()
  33014. && componentToWatch->getComponentUID() == componentUID);
  33015. }
  33016. const Component* ComponentDeletionWatcher::getComponent() const throw()
  33017. {
  33018. return hasBeenDeleted() ? 0 : componentToWatch;
  33019. }
  33020. END_JUCE_NAMESPACE
  33021. /********* End of inlined file: juce_Component.cpp *********/
  33022. /********* Start of inlined file: juce_ComponentListener.cpp *********/
  33023. BEGIN_JUCE_NAMESPACE
  33024. void ComponentListener::componentMovedOrResized (Component&, bool, bool)
  33025. {
  33026. }
  33027. void ComponentListener::componentBroughtToFront (Component&)
  33028. {
  33029. }
  33030. void ComponentListener::componentVisibilityChanged (Component&)
  33031. {
  33032. }
  33033. void ComponentListener::componentChildrenChanged (Component&)
  33034. {
  33035. }
  33036. void ComponentListener::componentParentHierarchyChanged (Component&)
  33037. {
  33038. }
  33039. void ComponentListener::componentNameChanged (Component&)
  33040. {
  33041. }
  33042. END_JUCE_NAMESPACE
  33043. /********* End of inlined file: juce_ComponentListener.cpp *********/
  33044. /********* Start of inlined file: juce_Desktop.cpp *********/
  33045. BEGIN_JUCE_NAMESPACE
  33046. extern void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords,
  33047. const bool clipToWorkArea) throw();
  33048. static Desktop* juce_desktopInstance = 0;
  33049. Desktop::Desktop() throw()
  33050. : mouseListeners (2),
  33051. desktopComponents (4),
  33052. monitorCoordsClipped (2),
  33053. monitorCoordsUnclipped (2),
  33054. lastMouseX (0),
  33055. lastMouseY (0),
  33056. kioskModeComponent (0)
  33057. {
  33058. refreshMonitorSizes();
  33059. }
  33060. Desktop::~Desktop() throw()
  33061. {
  33062. jassert (juce_desktopInstance == this);
  33063. juce_desktopInstance = 0;
  33064. // doh! If you don't delete all your windows before exiting, you're going to
  33065. // be leaking memory!
  33066. jassert (desktopComponents.size() == 0);
  33067. }
  33068. Desktop& JUCE_CALLTYPE Desktop::getInstance() throw()
  33069. {
  33070. if (juce_desktopInstance == 0)
  33071. juce_desktopInstance = new Desktop();
  33072. return *juce_desktopInstance;
  33073. }
  33074. void Desktop::refreshMonitorSizes() throw()
  33075. {
  33076. const Array <Rectangle> oldClipped (monitorCoordsClipped);
  33077. const Array <Rectangle> oldUnclipped (monitorCoordsUnclipped);
  33078. monitorCoordsClipped.clear();
  33079. monitorCoordsUnclipped.clear();
  33080. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33081. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33082. jassert (monitorCoordsClipped.size() > 0
  33083. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33084. if (oldClipped != monitorCoordsClipped
  33085. || oldUnclipped != monitorCoordsUnclipped)
  33086. {
  33087. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33088. {
  33089. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33090. if (p != 0)
  33091. p->handleScreenSizeChange();
  33092. }
  33093. }
  33094. }
  33095. int Desktop::getNumDisplayMonitors() const throw()
  33096. {
  33097. return monitorCoordsClipped.size();
  33098. }
  33099. const Rectangle Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33100. {
  33101. return clippedToWorkArea ? monitorCoordsClipped [index]
  33102. : monitorCoordsUnclipped [index];
  33103. }
  33104. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33105. {
  33106. RectangleList rl;
  33107. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33108. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33109. return rl;
  33110. }
  33111. const Rectangle Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33112. {
  33113. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33114. }
  33115. const Rectangle Desktop::getMonitorAreaContaining (int cx, int cy, const bool clippedToWorkArea) const throw()
  33116. {
  33117. Rectangle best (getMainMonitorArea (clippedToWorkArea));
  33118. double bestDistance = 1.0e10;
  33119. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33120. {
  33121. const Rectangle rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33122. if (rect.contains (cx, cy))
  33123. return rect;
  33124. const double distance = juce_hypot ((double) (rect.getCentreX() - cx),
  33125. (double) (rect.getCentreY() - cy));
  33126. if (distance < bestDistance)
  33127. {
  33128. bestDistance = distance;
  33129. best = rect;
  33130. }
  33131. }
  33132. return best;
  33133. }
  33134. int Desktop::getNumComponents() const throw()
  33135. {
  33136. return desktopComponents.size();
  33137. }
  33138. Component* Desktop::getComponent (const int index) const throw()
  33139. {
  33140. return (Component*) desktopComponents [index];
  33141. }
  33142. Component* Desktop::findComponentAt (const int screenX,
  33143. const int screenY) const
  33144. {
  33145. for (int i = desktopComponents.size(); --i >= 0;)
  33146. {
  33147. Component* const c = (Component*) desktopComponents.getUnchecked(i);
  33148. int x = screenX, y = screenY;
  33149. c->globalPositionToRelative (x, y);
  33150. if (c->contains (x, y))
  33151. return c->getComponentAt (x, y);
  33152. }
  33153. return 0;
  33154. }
  33155. void Desktop::addDesktopComponent (Component* const c) throw()
  33156. {
  33157. jassert (c != 0);
  33158. jassert (! desktopComponents.contains (c));
  33159. desktopComponents.addIfNotAlreadyThere (c);
  33160. }
  33161. void Desktop::removeDesktopComponent (Component* const c) throw()
  33162. {
  33163. desktopComponents.removeValue (c);
  33164. }
  33165. void Desktop::componentBroughtToFront (Component* const c) throw()
  33166. {
  33167. const int index = desktopComponents.indexOf (c);
  33168. jassert (index >= 0);
  33169. if (index >= 0)
  33170. desktopComponents.move (index, -1);
  33171. }
  33172. // from Component.cpp
  33173. extern int juce_recentMouseDownX [4];
  33174. extern int juce_recentMouseDownY [4];
  33175. extern int juce_MouseClickCounter;
  33176. void Desktop::getLastMouseDownPosition (int& x, int& y) throw()
  33177. {
  33178. x = juce_recentMouseDownX [0];
  33179. y = juce_recentMouseDownY [0];
  33180. }
  33181. int Desktop::getMouseButtonClickCounter() throw()
  33182. {
  33183. return juce_MouseClickCounter;
  33184. }
  33185. void Desktop::addGlobalMouseListener (MouseListener* const listener) throw()
  33186. {
  33187. jassert (listener != 0);
  33188. if (listener != 0)
  33189. {
  33190. mouseListeners.add (listener);
  33191. resetTimer();
  33192. }
  33193. }
  33194. void Desktop::removeGlobalMouseListener (MouseListener* const listener) throw()
  33195. {
  33196. mouseListeners.removeValue (listener);
  33197. resetTimer();
  33198. }
  33199. void Desktop::addFocusChangeListener (FocusChangeListener* const listener) throw()
  33200. {
  33201. jassert (listener != 0);
  33202. if (listener != 0)
  33203. focusListeners.add (listener);
  33204. }
  33205. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener) throw()
  33206. {
  33207. focusListeners.removeValue (listener);
  33208. }
  33209. void Desktop::triggerFocusCallback() throw()
  33210. {
  33211. triggerAsyncUpdate();
  33212. }
  33213. void Desktop::handleAsyncUpdate()
  33214. {
  33215. for (int i = focusListeners.size(); --i >= 0;)
  33216. {
  33217. ((FocusChangeListener*) focusListeners.getUnchecked (i))->globalFocusChanged (Component::getCurrentlyFocusedComponent());
  33218. i = jmin (i, focusListeners.size());
  33219. }
  33220. }
  33221. void Desktop::timerCallback()
  33222. {
  33223. int x, y;
  33224. getMousePosition (x, y);
  33225. if (lastMouseX != x || lastMouseY != y)
  33226. sendMouseMove();
  33227. }
  33228. void Desktop::sendMouseMove()
  33229. {
  33230. if (mouseListeners.size() > 0)
  33231. {
  33232. startTimer (20);
  33233. int x, y;
  33234. getMousePosition (x, y);
  33235. lastMouseX = x;
  33236. lastMouseY = y;
  33237. Component* const target = findComponentAt (x, y);
  33238. if (target != 0)
  33239. {
  33240. target->globalPositionToRelative (x, y);
  33241. ComponentDeletionWatcher deletionChecker (target);
  33242. const MouseEvent me (x, y,
  33243. ModifierKeys::getCurrentModifiers(),
  33244. target,
  33245. Time::getCurrentTime(),
  33246. x, y,
  33247. Time::getCurrentTime(),
  33248. 0, false);
  33249. for (int i = mouseListeners.size(); --i >= 0;)
  33250. {
  33251. if (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  33252. ((MouseListener*) mouseListeners[i])->mouseDrag (me);
  33253. else
  33254. ((MouseListener*) mouseListeners[i])->mouseMove (me);
  33255. if (deletionChecker.hasBeenDeleted())
  33256. return;
  33257. i = jmin (i, mouseListeners.size());
  33258. }
  33259. }
  33260. }
  33261. }
  33262. void Desktop::resetTimer() throw()
  33263. {
  33264. if (mouseListeners.size() == 0)
  33265. stopTimer();
  33266. else
  33267. startTimer (100);
  33268. getMousePosition (lastMouseX, lastMouseY);
  33269. }
  33270. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33271. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33272. {
  33273. if (kioskModeComponent != componentToUse)
  33274. {
  33275. // agh! Don't delete a component without first stopping it being the kiosk comp
  33276. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33277. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33278. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33279. if (kioskModeComponent->isValidComponent())
  33280. {
  33281. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33282. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33283. }
  33284. kioskModeComponent = componentToUse;
  33285. if (kioskModeComponent != 0)
  33286. {
  33287. jassert (kioskModeComponent->isValidComponent());
  33288. // Only components that are already on the desktop can be put into kiosk mode!
  33289. jassert (kioskModeComponent->isOnDesktop());
  33290. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33291. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33292. }
  33293. }
  33294. }
  33295. END_JUCE_NAMESPACE
  33296. /********* End of inlined file: juce_Desktop.cpp *********/
  33297. /********* Start of inlined file: juce_ArrowButton.cpp *********/
  33298. BEGIN_JUCE_NAMESPACE
  33299. ArrowButton::ArrowButton (const String& name,
  33300. float arrowDirectionInRadians,
  33301. const Colour& arrowColour)
  33302. : Button (name),
  33303. colour (arrowColour)
  33304. {
  33305. path.lineTo (0.0f, 1.0f);
  33306. path.lineTo (1.0f, 0.5f);
  33307. path.closeSubPath();
  33308. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33309. 0.5f, 0.5f));
  33310. setComponentEffect (&shadow);
  33311. buttonStateChanged();
  33312. }
  33313. ArrowButton::~ArrowButton()
  33314. {
  33315. }
  33316. void ArrowButton::paintButton (Graphics& g,
  33317. bool /*isMouseOverButton*/,
  33318. bool /*isButtonDown*/)
  33319. {
  33320. g.setColour (colour);
  33321. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33322. (float) offset,
  33323. (float) (getWidth() - 3),
  33324. (float) (getHeight() - 3),
  33325. false));
  33326. }
  33327. void ArrowButton::buttonStateChanged()
  33328. {
  33329. offset = (isDown()) ? 1 : 0;
  33330. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33331. 0.3f, -1, 0);
  33332. }
  33333. END_JUCE_NAMESPACE
  33334. /********* End of inlined file: juce_ArrowButton.cpp *********/
  33335. /********* Start of inlined file: juce_Button.cpp *********/
  33336. BEGIN_JUCE_NAMESPACE
  33337. Button::Button (const String& name)
  33338. : Component (name),
  33339. shortcuts (2),
  33340. keySource (0),
  33341. text (name),
  33342. buttonListeners (2),
  33343. repeatTimer (0),
  33344. buttonPressTime (0),
  33345. lastTimeCallbackTime (0),
  33346. commandManagerToUse (0),
  33347. autoRepeatDelay (-1),
  33348. autoRepeatSpeed (0),
  33349. autoRepeatMinimumDelay (-1),
  33350. radioGroupId (0),
  33351. commandID (0),
  33352. connectedEdgeFlags (0),
  33353. buttonState (buttonNormal),
  33354. isOn (false),
  33355. clickTogglesState (false),
  33356. needsToRelease (false),
  33357. needsRepainting (false),
  33358. isKeyDown (false),
  33359. triggerOnMouseDown (false),
  33360. generateTooltip (false)
  33361. {
  33362. setWantsKeyboardFocus (true);
  33363. }
  33364. Button::~Button()
  33365. {
  33366. if (commandManagerToUse != 0)
  33367. commandManagerToUse->removeListener (this);
  33368. delete repeatTimer;
  33369. clearShortcuts();
  33370. }
  33371. void Button::setButtonText (const String& newText) throw()
  33372. {
  33373. if (text != newText)
  33374. {
  33375. text = newText;
  33376. repaint();
  33377. }
  33378. }
  33379. void Button::setTooltip (const String& newTooltip)
  33380. {
  33381. SettableTooltipClient::setTooltip (newTooltip);
  33382. generateTooltip = false;
  33383. }
  33384. const String Button::getTooltip()
  33385. {
  33386. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  33387. {
  33388. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  33389. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  33390. for (int i = 0; i < keyPresses.size(); ++i)
  33391. {
  33392. const String key (keyPresses.getReference(i).getTextDescription());
  33393. if (key.length() == 1)
  33394. tt << " [shortcut: '" << key << "']";
  33395. else
  33396. tt << " [" << key << ']';
  33397. }
  33398. return tt;
  33399. }
  33400. return SettableTooltipClient::getTooltip();
  33401. }
  33402. void Button::setConnectedEdges (const int connectedEdgeFlags_) throw()
  33403. {
  33404. if (connectedEdgeFlags != connectedEdgeFlags_)
  33405. {
  33406. connectedEdgeFlags = connectedEdgeFlags_;
  33407. repaint();
  33408. }
  33409. }
  33410. void Button::setToggleState (const bool shouldBeOn,
  33411. const bool sendChangeNotification)
  33412. {
  33413. if (shouldBeOn != isOn)
  33414. {
  33415. const ComponentDeletionWatcher deletionWatcher (this);
  33416. isOn = shouldBeOn;
  33417. repaint();
  33418. if (sendChangeNotification)
  33419. sendClickMessage (ModifierKeys());
  33420. if ((! deletionWatcher.hasBeenDeleted()) && isOn)
  33421. turnOffOtherButtonsInGroup (sendChangeNotification);
  33422. }
  33423. }
  33424. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  33425. {
  33426. clickTogglesState = shouldToggle;
  33427. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33428. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33429. // it is that this button represents, and the button will update its state to reflect this
  33430. // in the applicationCommandListChanged() method.
  33431. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33432. }
  33433. bool Button::getClickingTogglesState() const throw()
  33434. {
  33435. return clickTogglesState;
  33436. }
  33437. void Button::setRadioGroupId (const int newGroupId)
  33438. {
  33439. if (radioGroupId != newGroupId)
  33440. {
  33441. radioGroupId = newGroupId;
  33442. if (isOn)
  33443. turnOffOtherButtonsInGroup (true);
  33444. }
  33445. }
  33446. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  33447. {
  33448. Component* const p = getParentComponent();
  33449. if (p != 0 && radioGroupId != 0)
  33450. {
  33451. const ComponentDeletionWatcher deletionWatcher (this);
  33452. for (int i = p->getNumChildComponents(); --i >= 0;)
  33453. {
  33454. Component* const c = p->getChildComponent (i);
  33455. if (c != this)
  33456. {
  33457. Button* const b = dynamic_cast <Button*> (c);
  33458. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  33459. {
  33460. b->setToggleState (false, sendChangeNotification);
  33461. if (deletionWatcher.hasBeenDeleted())
  33462. return;
  33463. }
  33464. }
  33465. }
  33466. }
  33467. }
  33468. void Button::enablementChanged()
  33469. {
  33470. updateState (0);
  33471. repaint();
  33472. }
  33473. Button::ButtonState Button::updateState (const MouseEvent* const e) throw()
  33474. {
  33475. ButtonState state = buttonNormal;
  33476. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  33477. {
  33478. int mx, my;
  33479. if (e == 0)
  33480. {
  33481. getMouseXYRelative (mx, my);
  33482. }
  33483. else
  33484. {
  33485. const MouseEvent e2 (e->getEventRelativeTo (this));
  33486. mx = e2.x;
  33487. my = e2.y;
  33488. }
  33489. const bool over = reallyContains (mx, my, true);
  33490. const bool down = isMouseButtonDown();
  33491. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  33492. state = buttonDown;
  33493. else if (over)
  33494. state = buttonOver;
  33495. }
  33496. setState (state);
  33497. return state;
  33498. }
  33499. void Button::setState (const ButtonState newState)
  33500. {
  33501. if (buttonState != newState)
  33502. {
  33503. buttonState = newState;
  33504. repaint();
  33505. if (buttonState == buttonDown)
  33506. {
  33507. buttonPressTime = Time::getApproximateMillisecondCounter();
  33508. lastTimeCallbackTime = buttonPressTime;
  33509. }
  33510. sendStateMessage();
  33511. }
  33512. }
  33513. bool Button::isDown() const throw()
  33514. {
  33515. return buttonState == buttonDown;
  33516. }
  33517. bool Button::isOver() const throw()
  33518. {
  33519. return buttonState != buttonNormal;
  33520. }
  33521. void Button::buttonStateChanged()
  33522. {
  33523. }
  33524. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  33525. {
  33526. const uint32 now = Time::getApproximateMillisecondCounter();
  33527. return now > buttonPressTime ? now - buttonPressTime : 0;
  33528. }
  33529. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  33530. {
  33531. triggerOnMouseDown = isTriggeredOnMouseDown;
  33532. }
  33533. void Button::clicked()
  33534. {
  33535. }
  33536. void Button::clicked (const ModifierKeys& /*modifiers*/)
  33537. {
  33538. clicked();
  33539. }
  33540. static const int clickMessageId = 0x2f3f4f99;
  33541. void Button::triggerClick()
  33542. {
  33543. postCommandMessage (clickMessageId);
  33544. }
  33545. void Button::internalClickCallback (const ModifierKeys& modifiers)
  33546. {
  33547. if (clickTogglesState)
  33548. setToggleState ((radioGroupId != 0) || ! isOn, false);
  33549. sendClickMessage (modifiers);
  33550. }
  33551. void Button::flashButtonState() throw()
  33552. {
  33553. if (isEnabled())
  33554. {
  33555. needsToRelease = true;
  33556. setState (buttonDown);
  33557. getRepeatTimer().startTimer (100);
  33558. }
  33559. }
  33560. void Button::handleCommandMessage (int commandId)
  33561. {
  33562. if (commandId == clickMessageId)
  33563. {
  33564. if (isEnabled())
  33565. {
  33566. flashButtonState();
  33567. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33568. }
  33569. }
  33570. else
  33571. {
  33572. Component::handleCommandMessage (commandId);
  33573. }
  33574. }
  33575. void Button::addButtonListener (ButtonListener* const newListener) throw()
  33576. {
  33577. jassert (newListener != 0);
  33578. jassert (! buttonListeners.contains (newListener)); // trying to add a listener to the list twice!
  33579. if (newListener != 0)
  33580. buttonListeners.add (newListener);
  33581. }
  33582. void Button::removeButtonListener (ButtonListener* const listener) throw()
  33583. {
  33584. jassert (buttonListeners.contains (listener)); // trying to remove a listener that isn't on the list!
  33585. buttonListeners.removeValue (listener);
  33586. }
  33587. void Button::sendClickMessage (const ModifierKeys& modifiers)
  33588. {
  33589. const ComponentDeletionWatcher cdw (this);
  33590. if (commandManagerToUse != 0 && commandID != 0)
  33591. {
  33592. ApplicationCommandTarget::InvocationInfo info (commandID);
  33593. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  33594. info.originatingComponent = this;
  33595. commandManagerToUse->invoke (info, true);
  33596. }
  33597. clicked (modifiers);
  33598. if (! cdw.hasBeenDeleted())
  33599. {
  33600. for (int i = buttonListeners.size(); --i >= 0;)
  33601. {
  33602. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  33603. if (bl != 0)
  33604. {
  33605. bl->buttonClicked (this);
  33606. if (cdw.hasBeenDeleted())
  33607. return;
  33608. }
  33609. }
  33610. }
  33611. }
  33612. void Button::sendStateMessage()
  33613. {
  33614. const ComponentDeletionWatcher cdw (this);
  33615. buttonStateChanged();
  33616. if (cdw.hasBeenDeleted())
  33617. return;
  33618. for (int i = buttonListeners.size(); --i >= 0;)
  33619. {
  33620. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  33621. if (bl != 0)
  33622. {
  33623. bl->buttonStateChanged (this);
  33624. if (cdw.hasBeenDeleted())
  33625. return;
  33626. }
  33627. }
  33628. }
  33629. void Button::paint (Graphics& g)
  33630. {
  33631. if (needsToRelease && isEnabled())
  33632. {
  33633. needsToRelease = false;
  33634. needsRepainting = true;
  33635. }
  33636. paintButton (g, isOver(), isDown());
  33637. }
  33638. void Button::mouseEnter (const MouseEvent& e)
  33639. {
  33640. updateState (&e);
  33641. }
  33642. void Button::mouseExit (const MouseEvent& e)
  33643. {
  33644. updateState (&e);
  33645. }
  33646. void Button::mouseDown (const MouseEvent& e)
  33647. {
  33648. updateState (&e);
  33649. if (isDown())
  33650. {
  33651. if (autoRepeatDelay >= 0)
  33652. getRepeatTimer().startTimer (autoRepeatDelay);
  33653. if (triggerOnMouseDown)
  33654. internalClickCallback (e.mods);
  33655. }
  33656. }
  33657. void Button::mouseUp (const MouseEvent& e)
  33658. {
  33659. const bool wasDown = isDown();
  33660. updateState (&e);
  33661. if (wasDown && isOver() && ! triggerOnMouseDown)
  33662. internalClickCallback (e.mods);
  33663. }
  33664. void Button::mouseDrag (const MouseEvent& e)
  33665. {
  33666. const ButtonState oldState = buttonState;
  33667. updateState (&e);
  33668. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  33669. getRepeatTimer().startTimer (autoRepeatSpeed);
  33670. }
  33671. void Button::focusGained (FocusChangeType)
  33672. {
  33673. updateState (0);
  33674. repaint();
  33675. }
  33676. void Button::focusLost (FocusChangeType)
  33677. {
  33678. updateState (0);
  33679. repaint();
  33680. }
  33681. void Button::setVisible (bool shouldBeVisible)
  33682. {
  33683. if (shouldBeVisible != isVisible())
  33684. {
  33685. Component::setVisible (shouldBeVisible);
  33686. if (! shouldBeVisible)
  33687. needsToRelease = false;
  33688. updateState (0);
  33689. }
  33690. else
  33691. {
  33692. Component::setVisible (shouldBeVisible);
  33693. }
  33694. }
  33695. void Button::parentHierarchyChanged()
  33696. {
  33697. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  33698. if (newKeySource != keySource)
  33699. {
  33700. if (keySource->isValidComponent())
  33701. keySource->removeKeyListener (this);
  33702. keySource = newKeySource;
  33703. if (keySource->isValidComponent())
  33704. keySource->addKeyListener (this);
  33705. }
  33706. }
  33707. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  33708. const int commandID_,
  33709. const bool generateTooltip_)
  33710. {
  33711. commandID = commandID_;
  33712. generateTooltip = generateTooltip_;
  33713. if (commandManagerToUse != commandManagerToUse_)
  33714. {
  33715. if (commandManagerToUse != 0)
  33716. commandManagerToUse->removeListener (this);
  33717. commandManagerToUse = commandManagerToUse_;
  33718. if (commandManagerToUse != 0)
  33719. commandManagerToUse->addListener (this);
  33720. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33721. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33722. // it is that this button represents, and the button will update its state to reflect this
  33723. // in the applicationCommandListChanged() method.
  33724. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33725. }
  33726. if (commandManagerToUse != 0)
  33727. applicationCommandListChanged();
  33728. else
  33729. setEnabled (true);
  33730. }
  33731. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  33732. {
  33733. if (info.commandID == commandID
  33734. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  33735. {
  33736. flashButtonState();
  33737. }
  33738. }
  33739. void Button::applicationCommandListChanged()
  33740. {
  33741. if (commandManagerToUse != 0)
  33742. {
  33743. ApplicationCommandInfo info (0);
  33744. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  33745. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  33746. if (target != 0)
  33747. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  33748. }
  33749. }
  33750. void Button::addShortcut (const KeyPress& key)
  33751. {
  33752. if (key.isValid())
  33753. {
  33754. jassert (! isRegisteredForShortcut (key)); // already registered!
  33755. shortcuts.add (key);
  33756. parentHierarchyChanged();
  33757. }
  33758. }
  33759. void Button::clearShortcuts()
  33760. {
  33761. shortcuts.clear();
  33762. parentHierarchyChanged();
  33763. }
  33764. bool Button::isShortcutPressed() const throw()
  33765. {
  33766. if (! isCurrentlyBlockedByAnotherModalComponent())
  33767. {
  33768. for (int i = shortcuts.size(); --i >= 0;)
  33769. if (shortcuts.getReference(i).isCurrentlyDown())
  33770. return true;
  33771. }
  33772. return false;
  33773. }
  33774. bool Button::isRegisteredForShortcut (const KeyPress& key) const throw()
  33775. {
  33776. for (int i = shortcuts.size(); --i >= 0;)
  33777. if (key == shortcuts.getReference(i))
  33778. return true;
  33779. return false;
  33780. }
  33781. bool Button::keyStateChanged (const bool, Component*)
  33782. {
  33783. if (! isEnabled())
  33784. return false;
  33785. const bool wasDown = isKeyDown;
  33786. isKeyDown = isShortcutPressed();
  33787. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  33788. getRepeatTimer().startTimer (autoRepeatDelay);
  33789. updateState (0);
  33790. if (isEnabled() && wasDown && ! isKeyDown)
  33791. {
  33792. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33793. // (return immediately - this button may now have been deleted)
  33794. return true;
  33795. }
  33796. return wasDown || isKeyDown;
  33797. }
  33798. bool Button::keyPressed (const KeyPress&, Component*)
  33799. {
  33800. // returning true will avoid forwarding events for keys that we're using as shortcuts
  33801. return isShortcutPressed();
  33802. }
  33803. bool Button::keyPressed (const KeyPress& key)
  33804. {
  33805. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  33806. {
  33807. triggerClick();
  33808. return true;
  33809. }
  33810. return false;
  33811. }
  33812. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  33813. const int repeatMillisecs,
  33814. const int minimumDelayInMillisecs) throw()
  33815. {
  33816. autoRepeatDelay = initialDelayMillisecs;
  33817. autoRepeatSpeed = repeatMillisecs;
  33818. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  33819. }
  33820. void Button::repeatTimerCallback() throw()
  33821. {
  33822. if (needsRepainting)
  33823. {
  33824. getRepeatTimer().stopTimer();
  33825. updateState (0);
  33826. needsRepainting = false;
  33827. }
  33828. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  33829. {
  33830. int repeatSpeed = autoRepeatSpeed;
  33831. if (autoRepeatMinimumDelay >= 0)
  33832. {
  33833. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  33834. timeHeldDown *= timeHeldDown;
  33835. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  33836. }
  33837. repeatSpeed = jmax (1, repeatSpeed);
  33838. getRepeatTimer().startTimer (repeatSpeed);
  33839. const uint32 now = Time::getApproximateMillisecondCounter();
  33840. const int numTimesToCallback
  33841. = (now > lastTimeCallbackTime) ? jmax (1, (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  33842. lastTimeCallbackTime = now;
  33843. const ComponentDeletionWatcher cdw (this);
  33844. for (int i = numTimesToCallback; --i >= 0;)
  33845. {
  33846. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33847. if (cdw.hasBeenDeleted() || ! isDown())
  33848. return;
  33849. }
  33850. }
  33851. else if (! needsToRelease)
  33852. {
  33853. getRepeatTimer().stopTimer();
  33854. }
  33855. }
  33856. class InternalButtonRepeatTimer : public Timer
  33857. {
  33858. public:
  33859. InternalButtonRepeatTimer (Button& owner_) throw()
  33860. : owner (owner_)
  33861. {
  33862. }
  33863. ~InternalButtonRepeatTimer()
  33864. {
  33865. }
  33866. void timerCallback()
  33867. {
  33868. owner.repeatTimerCallback();
  33869. }
  33870. private:
  33871. Button& owner;
  33872. InternalButtonRepeatTimer (const InternalButtonRepeatTimer&);
  33873. const InternalButtonRepeatTimer& operator= (const InternalButtonRepeatTimer&);
  33874. };
  33875. Timer& Button::getRepeatTimer() throw()
  33876. {
  33877. if (repeatTimer == 0)
  33878. repeatTimer = new InternalButtonRepeatTimer (*this);
  33879. return *repeatTimer;
  33880. }
  33881. END_JUCE_NAMESPACE
  33882. /********* End of inlined file: juce_Button.cpp *********/
  33883. /********* Start of inlined file: juce_DrawableButton.cpp *********/
  33884. BEGIN_JUCE_NAMESPACE
  33885. DrawableButton::DrawableButton (const String& name,
  33886. const DrawableButton::ButtonStyle buttonStyle)
  33887. : Button (name),
  33888. style (buttonStyle),
  33889. normalImage (0),
  33890. overImage (0),
  33891. downImage (0),
  33892. disabledImage (0),
  33893. normalImageOn (0),
  33894. overImageOn (0),
  33895. downImageOn (0),
  33896. disabledImageOn (0),
  33897. edgeIndent (3)
  33898. {
  33899. if (buttonStyle == ImageOnButtonBackground)
  33900. {
  33901. backgroundOff = Colour (0xffbbbbff);
  33902. backgroundOn = Colour (0xff3333ff);
  33903. }
  33904. else
  33905. {
  33906. backgroundOff = Colours::transparentBlack;
  33907. backgroundOn = Colour (0xaabbbbff);
  33908. }
  33909. }
  33910. DrawableButton::~DrawableButton()
  33911. {
  33912. deleteImages();
  33913. }
  33914. void DrawableButton::deleteImages()
  33915. {
  33916. deleteAndZero (normalImage);
  33917. deleteAndZero (overImage);
  33918. deleteAndZero (downImage);
  33919. deleteAndZero (disabledImage);
  33920. deleteAndZero (normalImageOn);
  33921. deleteAndZero (overImageOn);
  33922. deleteAndZero (downImageOn);
  33923. deleteAndZero (disabledImageOn);
  33924. }
  33925. void DrawableButton::setImages (const Drawable* normal,
  33926. const Drawable* over,
  33927. const Drawable* down,
  33928. const Drawable* disabled,
  33929. const Drawable* normalOn,
  33930. const Drawable* overOn,
  33931. const Drawable* downOn,
  33932. const Drawable* disabledOn)
  33933. {
  33934. deleteImages();
  33935. jassert (normal != 0); // you really need to give it at least a normal image..
  33936. if (normal != 0)
  33937. normalImage = normal->createCopy();
  33938. if (over != 0)
  33939. overImage = over->createCopy();
  33940. if (down != 0)
  33941. downImage = down->createCopy();
  33942. if (disabled != 0)
  33943. disabledImage = disabled->createCopy();
  33944. if (normalOn != 0)
  33945. normalImageOn = normalOn->createCopy();
  33946. if (overOn != 0)
  33947. overImageOn = overOn->createCopy();
  33948. if (downOn != 0)
  33949. downImageOn = downOn->createCopy();
  33950. if (disabledOn != 0)
  33951. disabledImageOn = disabledOn->createCopy();
  33952. repaint();
  33953. }
  33954. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  33955. {
  33956. if (style != newStyle)
  33957. {
  33958. style = newStyle;
  33959. repaint();
  33960. }
  33961. }
  33962. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  33963. const Colour& toggledOnColour)
  33964. {
  33965. if (backgroundOff != toggledOffColour
  33966. || backgroundOn != toggledOnColour)
  33967. {
  33968. backgroundOff = toggledOffColour;
  33969. backgroundOn = toggledOnColour;
  33970. repaint();
  33971. }
  33972. }
  33973. const Colour& DrawableButton::getBackgroundColour() const throw()
  33974. {
  33975. return getToggleState() ? backgroundOn
  33976. : backgroundOff;
  33977. }
  33978. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  33979. {
  33980. edgeIndent = numPixelsIndent;
  33981. repaint();
  33982. }
  33983. void DrawableButton::paintButton (Graphics& g,
  33984. bool isMouseOverButton,
  33985. bool isButtonDown)
  33986. {
  33987. Rectangle imageSpace;
  33988. if (style == ImageOnButtonBackground)
  33989. {
  33990. const int insetX = getWidth() / 4;
  33991. const int insetY = getHeight() / 4;
  33992. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  33993. getLookAndFeel().drawButtonBackground (g, *this,
  33994. getBackgroundColour(),
  33995. isMouseOverButton,
  33996. isButtonDown);
  33997. }
  33998. else
  33999. {
  34000. g.fillAll (getBackgroundColour());
  34001. const int textH = (style == ImageAboveTextLabel)
  34002. ? jmin (16, proportionOfHeight (0.25f))
  34003. : 0;
  34004. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34005. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34006. imageSpace.setBounds (indentX, indentY,
  34007. getWidth() - indentX * 2,
  34008. getHeight() - indentY * 2 - textH);
  34009. if (textH > 0)
  34010. {
  34011. g.setFont ((float) textH);
  34012. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34013. g.drawFittedText (getButtonText(),
  34014. 2, getHeight() - textH - 1,
  34015. getWidth() - 4, textH,
  34016. Justification::centred, 1);
  34017. }
  34018. }
  34019. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34020. g.setOpacity (1.0f);
  34021. const Drawable* imageToDraw = 0;
  34022. if (isEnabled())
  34023. {
  34024. imageToDraw = getCurrentImage();
  34025. }
  34026. else
  34027. {
  34028. imageToDraw = getToggleState() ? disabledImageOn
  34029. : disabledImage;
  34030. if (imageToDraw == 0)
  34031. {
  34032. g.setOpacity (0.4f);
  34033. imageToDraw = getNormalImage();
  34034. }
  34035. }
  34036. if (imageToDraw != 0)
  34037. {
  34038. if (style == ImageRaw)
  34039. {
  34040. imageToDraw->draw (g);
  34041. }
  34042. else
  34043. {
  34044. imageToDraw->drawWithin (g,
  34045. imageSpace.getX(),
  34046. imageSpace.getY(),
  34047. imageSpace.getWidth(),
  34048. imageSpace.getHeight(),
  34049. RectanglePlacement::centred);
  34050. }
  34051. }
  34052. }
  34053. const Drawable* DrawableButton::getCurrentImage() const throw()
  34054. {
  34055. if (isDown())
  34056. return getDownImage();
  34057. if (isOver())
  34058. return getOverImage();
  34059. return getNormalImage();
  34060. }
  34061. const Drawable* DrawableButton::getNormalImage() const throw()
  34062. {
  34063. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34064. : normalImage;
  34065. }
  34066. const Drawable* DrawableButton::getOverImage() const throw()
  34067. {
  34068. const Drawable* d = normalImage;
  34069. if (getToggleState())
  34070. {
  34071. if (overImageOn != 0)
  34072. d = overImageOn;
  34073. else if (normalImageOn != 0)
  34074. d = normalImageOn;
  34075. else if (overImage != 0)
  34076. d = overImage;
  34077. }
  34078. else
  34079. {
  34080. if (overImage != 0)
  34081. d = overImage;
  34082. }
  34083. return d;
  34084. }
  34085. const Drawable* DrawableButton::getDownImage() const throw()
  34086. {
  34087. const Drawable* d = normalImage;
  34088. if (getToggleState())
  34089. {
  34090. if (downImageOn != 0)
  34091. d = downImageOn;
  34092. else if (overImageOn != 0)
  34093. d = overImageOn;
  34094. else if (normalImageOn != 0)
  34095. d = normalImageOn;
  34096. else if (downImage != 0)
  34097. d = downImage;
  34098. else
  34099. d = getOverImage();
  34100. }
  34101. else
  34102. {
  34103. if (downImage != 0)
  34104. d = downImage;
  34105. else
  34106. d = getOverImage();
  34107. }
  34108. return d;
  34109. }
  34110. END_JUCE_NAMESPACE
  34111. /********* End of inlined file: juce_DrawableButton.cpp *********/
  34112. /********* Start of inlined file: juce_HyperlinkButton.cpp *********/
  34113. BEGIN_JUCE_NAMESPACE
  34114. HyperlinkButton::HyperlinkButton (const String& linkText,
  34115. const URL& linkURL)
  34116. : Button (linkText),
  34117. url (linkURL),
  34118. font (14.0f, Font::underlined),
  34119. resizeFont (true),
  34120. justification (Justification::centred)
  34121. {
  34122. setMouseCursor (MouseCursor::PointingHandCursor);
  34123. setTooltip (linkURL.toString (false));
  34124. }
  34125. HyperlinkButton::~HyperlinkButton()
  34126. {
  34127. }
  34128. void HyperlinkButton::setFont (const Font& newFont,
  34129. const bool resizeToMatchComponentHeight,
  34130. const Justification& justificationType)
  34131. {
  34132. font = newFont;
  34133. resizeFont = resizeToMatchComponentHeight;
  34134. justification = justificationType;
  34135. repaint();
  34136. }
  34137. void HyperlinkButton::setURL (const URL& newURL) throw()
  34138. {
  34139. url = newURL;
  34140. setTooltip (newURL.toString (false));
  34141. }
  34142. const Font HyperlinkButton::getFontToUse() const
  34143. {
  34144. Font f (font);
  34145. if (resizeFont)
  34146. f.setHeight (getHeight() * 0.7f);
  34147. return f;
  34148. }
  34149. void HyperlinkButton::changeWidthToFitText()
  34150. {
  34151. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34152. }
  34153. void HyperlinkButton::colourChanged()
  34154. {
  34155. repaint();
  34156. }
  34157. void HyperlinkButton::clicked()
  34158. {
  34159. if (url.isWellFormed())
  34160. url.launchInDefaultBrowser();
  34161. }
  34162. void HyperlinkButton::paintButton (Graphics& g,
  34163. bool isMouseOverButton,
  34164. bool isButtonDown)
  34165. {
  34166. const Colour textColour (findColour (textColourId));
  34167. if (isEnabled())
  34168. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34169. : textColour);
  34170. else
  34171. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34172. g.setFont (getFontToUse());
  34173. g.drawText (getButtonText(),
  34174. 2, 0, getWidth() - 2, getHeight(),
  34175. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34176. true);
  34177. }
  34178. END_JUCE_NAMESPACE
  34179. /********* End of inlined file: juce_HyperlinkButton.cpp *********/
  34180. /********* Start of inlined file: juce_ImageButton.cpp *********/
  34181. BEGIN_JUCE_NAMESPACE
  34182. ImageButton::ImageButton (const String& text_)
  34183. : Button (text_),
  34184. scaleImageToFit (true),
  34185. preserveProportions (true),
  34186. alphaThreshold (0),
  34187. imageX (0),
  34188. imageY (0),
  34189. imageW (0),
  34190. imageH (0),
  34191. normalImage (0),
  34192. overImage (0),
  34193. downImage (0)
  34194. {
  34195. }
  34196. ImageButton::~ImageButton()
  34197. {
  34198. deleteImages();
  34199. }
  34200. void ImageButton::deleteImages()
  34201. {
  34202. if (normalImage != 0)
  34203. {
  34204. if (ImageCache::isImageInCache (normalImage))
  34205. ImageCache::release (normalImage);
  34206. else
  34207. delete normalImage;
  34208. }
  34209. if (overImage != 0)
  34210. {
  34211. if (ImageCache::isImageInCache (overImage))
  34212. ImageCache::release (overImage);
  34213. else
  34214. delete overImage;
  34215. }
  34216. if (downImage != 0)
  34217. {
  34218. if (ImageCache::isImageInCache (downImage))
  34219. ImageCache::release (downImage);
  34220. else
  34221. delete downImage;
  34222. }
  34223. }
  34224. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34225. const bool rescaleImagesWhenButtonSizeChanges,
  34226. const bool preserveImageProportions,
  34227. Image* const normalImage_,
  34228. const float imageOpacityWhenNormal,
  34229. const Colour& overlayColourWhenNormal,
  34230. Image* const overImage_,
  34231. const float imageOpacityWhenOver,
  34232. const Colour& overlayColourWhenOver,
  34233. Image* const downImage_,
  34234. const float imageOpacityWhenDown,
  34235. const Colour& overlayColourWhenDown,
  34236. const float hitTestAlphaThreshold)
  34237. {
  34238. deleteImages();
  34239. normalImage = normalImage_;
  34240. overImage = overImage_;
  34241. downImage = downImage_;
  34242. if (resizeButtonNowToFitThisImage && normalImage != 0)
  34243. {
  34244. imageW = normalImage->getWidth();
  34245. imageH = normalImage->getHeight();
  34246. setSize (imageW, imageH);
  34247. }
  34248. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34249. preserveProportions = preserveImageProportions;
  34250. normalOpacity = imageOpacityWhenNormal;
  34251. normalOverlay = overlayColourWhenNormal;
  34252. overOpacity = imageOpacityWhenOver;
  34253. overOverlay = overlayColourWhenOver;
  34254. downOpacity = imageOpacityWhenDown;
  34255. downOverlay = overlayColourWhenDown;
  34256. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundFloatToInt (255.0f * hitTestAlphaThreshold));
  34257. repaint();
  34258. }
  34259. Image* ImageButton::getCurrentImage() const
  34260. {
  34261. if (isDown() || getToggleState())
  34262. return getDownImage();
  34263. if (isOver())
  34264. return getOverImage();
  34265. return getNormalImage();
  34266. }
  34267. Image* ImageButton::getNormalImage() const throw()
  34268. {
  34269. return normalImage;
  34270. }
  34271. Image* ImageButton::getOverImage() const throw()
  34272. {
  34273. return (overImage != 0) ? overImage
  34274. : normalImage;
  34275. }
  34276. Image* ImageButton::getDownImage() const throw()
  34277. {
  34278. return (downImage != 0) ? downImage
  34279. : getOverImage();
  34280. }
  34281. void ImageButton::paintButton (Graphics& g,
  34282. bool isMouseOverButton,
  34283. bool isButtonDown)
  34284. {
  34285. if (! isEnabled())
  34286. {
  34287. isMouseOverButton = false;
  34288. isButtonDown = false;
  34289. }
  34290. Image* const im = getCurrentImage();
  34291. if (im != 0)
  34292. {
  34293. const int iw = im->getWidth();
  34294. const int ih = im->getHeight();
  34295. imageW = getWidth();
  34296. imageH = getHeight();
  34297. imageX = (imageW - iw) >> 1;
  34298. imageY = (imageH - ih) >> 1;
  34299. if (scaleImageToFit)
  34300. {
  34301. if (preserveProportions)
  34302. {
  34303. int newW, newH;
  34304. const float imRatio = ih / (float)iw;
  34305. const float destRatio = imageH / (float)imageW;
  34306. if (imRatio > destRatio)
  34307. {
  34308. newW = roundFloatToInt (imageH / imRatio);
  34309. newH = imageH;
  34310. }
  34311. else
  34312. {
  34313. newW = imageW;
  34314. newH = roundFloatToInt (imageW * imRatio);
  34315. }
  34316. imageX = (imageW - newW) / 2;
  34317. imageY = (imageH - newH) / 2;
  34318. imageW = newW;
  34319. imageH = newH;
  34320. }
  34321. else
  34322. {
  34323. imageX = 0;
  34324. imageY = 0;
  34325. }
  34326. }
  34327. if (! scaleImageToFit)
  34328. {
  34329. imageW = iw;
  34330. imageH = ih;
  34331. }
  34332. getLookAndFeel().drawImageButton (g, im, imageX, imageY, imageW, imageH,
  34333. isButtonDown ? downOverlay
  34334. : (isMouseOverButton ? overOverlay
  34335. : normalOverlay),
  34336. isButtonDown ? downOpacity
  34337. : (isMouseOverButton ? overOpacity
  34338. : normalOpacity),
  34339. *this);
  34340. }
  34341. }
  34342. bool ImageButton::hitTest (int x, int y)
  34343. {
  34344. if (alphaThreshold == 0)
  34345. return true;
  34346. Image* const im = getCurrentImage();
  34347. return im == 0
  34348. || (imageW > 0 && imageH > 0
  34349. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  34350. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  34351. }
  34352. END_JUCE_NAMESPACE
  34353. /********* End of inlined file: juce_ImageButton.cpp *********/
  34354. /********* Start of inlined file: juce_ShapeButton.cpp *********/
  34355. BEGIN_JUCE_NAMESPACE
  34356. ShapeButton::ShapeButton (const String& text,
  34357. const Colour& normalColour_,
  34358. const Colour& overColour_,
  34359. const Colour& downColour_)
  34360. : Button (text),
  34361. normalColour (normalColour_),
  34362. overColour (overColour_),
  34363. downColour (downColour_),
  34364. maintainShapeProportions (false),
  34365. outlineWidth (0.0f)
  34366. {
  34367. }
  34368. ShapeButton::~ShapeButton()
  34369. {
  34370. }
  34371. void ShapeButton::setColours (const Colour& newNormalColour,
  34372. const Colour& newOverColour,
  34373. const Colour& newDownColour)
  34374. {
  34375. normalColour = newNormalColour;
  34376. overColour = newOverColour;
  34377. downColour = newDownColour;
  34378. }
  34379. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34380. const float newOutlineWidth)
  34381. {
  34382. outlineColour = newOutlineColour;
  34383. outlineWidth = newOutlineWidth;
  34384. }
  34385. void ShapeButton::setShape (const Path& newShape,
  34386. const bool resizeNowToFitThisShape,
  34387. const bool maintainShapeProportions_,
  34388. const bool hasShadow)
  34389. {
  34390. shape = newShape;
  34391. maintainShapeProportions = maintainShapeProportions_;
  34392. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34393. setComponentEffect ((hasShadow) ? &shadow : 0);
  34394. if (resizeNowToFitThisShape)
  34395. {
  34396. float x, y, w, h;
  34397. shape.getBounds (x, y, w, h);
  34398. shape.applyTransform (AffineTransform::translation (-x, -y));
  34399. if (hasShadow)
  34400. {
  34401. w += 4.0f;
  34402. h += 4.0f;
  34403. shape.applyTransform (AffineTransform::translation (2.0f, 2.0f));
  34404. }
  34405. setSize (1 + (int) (w + outlineWidth),
  34406. 1 + (int) (h + outlineWidth));
  34407. }
  34408. }
  34409. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34410. {
  34411. if (! isEnabled())
  34412. {
  34413. isMouseOverButton = false;
  34414. isButtonDown = false;
  34415. }
  34416. g.setColour ((isButtonDown) ? downColour
  34417. : (isMouseOverButton) ? overColour
  34418. : normalColour);
  34419. int w = getWidth();
  34420. int h = getHeight();
  34421. if (getComponentEffect() != 0)
  34422. {
  34423. w -= 4;
  34424. h -= 4;
  34425. }
  34426. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  34427. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  34428. w - offset - outlineWidth,
  34429. h - offset - outlineWidth,
  34430. maintainShapeProportions));
  34431. g.fillPath (shape, trans);
  34432. if (outlineWidth > 0.0f)
  34433. {
  34434. g.setColour (outlineColour);
  34435. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  34436. }
  34437. }
  34438. END_JUCE_NAMESPACE
  34439. /********* End of inlined file: juce_ShapeButton.cpp *********/
  34440. /********* Start of inlined file: juce_TextButton.cpp *********/
  34441. BEGIN_JUCE_NAMESPACE
  34442. TextButton::TextButton (const String& name,
  34443. const String& toolTip)
  34444. : Button (name)
  34445. {
  34446. setTooltip (toolTip);
  34447. }
  34448. TextButton::~TextButton()
  34449. {
  34450. }
  34451. void TextButton::paintButton (Graphics& g,
  34452. bool isMouseOverButton,
  34453. bool isButtonDown)
  34454. {
  34455. getLookAndFeel().drawButtonBackground (g, *this,
  34456. findColour (getToggleState() ? buttonOnColourId
  34457. : buttonColourId),
  34458. isMouseOverButton,
  34459. isButtonDown);
  34460. getLookAndFeel().drawButtonText (g, *this,
  34461. isMouseOverButton,
  34462. isButtonDown);
  34463. }
  34464. void TextButton::colourChanged()
  34465. {
  34466. repaint();
  34467. }
  34468. const Font TextButton::getFont()
  34469. {
  34470. return Font (jmin (15.0f, getHeight() * 0.6f));
  34471. }
  34472. void TextButton::changeWidthToFitText (const int newHeight)
  34473. {
  34474. if (newHeight >= 0)
  34475. setSize (jmax (1, getWidth()), newHeight);
  34476. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  34477. getHeight());
  34478. }
  34479. END_JUCE_NAMESPACE
  34480. /********* End of inlined file: juce_TextButton.cpp *********/
  34481. /********* Start of inlined file: juce_ToggleButton.cpp *********/
  34482. BEGIN_JUCE_NAMESPACE
  34483. ToggleButton::ToggleButton (const String& buttonText)
  34484. : Button (buttonText)
  34485. {
  34486. setClickingTogglesState (true);
  34487. }
  34488. ToggleButton::~ToggleButton()
  34489. {
  34490. }
  34491. void ToggleButton::paintButton (Graphics& g,
  34492. bool isMouseOverButton,
  34493. bool isButtonDown)
  34494. {
  34495. getLookAndFeel().drawToggleButton (g, *this,
  34496. isMouseOverButton,
  34497. isButtonDown);
  34498. }
  34499. void ToggleButton::changeWidthToFitText()
  34500. {
  34501. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  34502. }
  34503. void ToggleButton::colourChanged()
  34504. {
  34505. repaint();
  34506. }
  34507. END_JUCE_NAMESPACE
  34508. /********* End of inlined file: juce_ToggleButton.cpp *********/
  34509. /********* Start of inlined file: juce_ToolbarButton.cpp *********/
  34510. BEGIN_JUCE_NAMESPACE
  34511. ToolbarButton::ToolbarButton (const int itemId_,
  34512. const String& buttonText,
  34513. Drawable* const normalImage_,
  34514. Drawable* const toggledOnImage_)
  34515. : ToolbarItemComponent (itemId_, buttonText, true),
  34516. normalImage (normalImage_),
  34517. toggledOnImage (toggledOnImage_)
  34518. {
  34519. }
  34520. ToolbarButton::~ToolbarButton()
  34521. {
  34522. delete normalImage;
  34523. delete toggledOnImage;
  34524. }
  34525. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  34526. bool /*isToolbarVertical*/,
  34527. int& preferredSize,
  34528. int& minSize, int& maxSize)
  34529. {
  34530. preferredSize = minSize = maxSize = toolbarDepth;
  34531. return true;
  34532. }
  34533. void ToolbarButton::paintButtonArea (Graphics& g,
  34534. int width, int height,
  34535. bool /*isMouseOver*/,
  34536. bool /*isMouseDown*/)
  34537. {
  34538. Drawable* d = normalImage;
  34539. if (getToggleState() && toggledOnImage != 0)
  34540. d = toggledOnImage;
  34541. if (! isEnabled())
  34542. {
  34543. Image im (Image::ARGB, width, height, true);
  34544. Graphics g2 (im);
  34545. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred);
  34546. im.desaturate();
  34547. g.drawImageAt (&im, 0, 0);
  34548. }
  34549. else
  34550. {
  34551. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred);
  34552. }
  34553. }
  34554. void ToolbarButton::contentAreaChanged (const Rectangle&)
  34555. {
  34556. }
  34557. END_JUCE_NAMESPACE
  34558. /********* End of inlined file: juce_ToolbarButton.cpp *********/
  34559. /********* Start of inlined file: juce_ComboBox.cpp *********/
  34560. BEGIN_JUCE_NAMESPACE
  34561. ComboBox::ComboBox (const String& name)
  34562. : Component (name),
  34563. items (4),
  34564. currentIndex (-1),
  34565. isButtonDown (false),
  34566. separatorPending (false),
  34567. menuActive (false),
  34568. listeners (2),
  34569. label (0)
  34570. {
  34571. noChoicesMessage = TRANS("(no choices)");
  34572. setRepaintsOnMouseActivity (true);
  34573. lookAndFeelChanged();
  34574. }
  34575. ComboBox::~ComboBox()
  34576. {
  34577. if (menuActive)
  34578. PopupMenu::dismissAllActiveMenus();
  34579. deleteAllChildren();
  34580. }
  34581. void ComboBox::setEditableText (const bool isEditable)
  34582. {
  34583. label->setEditable (isEditable, isEditable, false);
  34584. setWantsKeyboardFocus (! isEditable);
  34585. resized();
  34586. }
  34587. bool ComboBox::isTextEditable() const throw()
  34588. {
  34589. return label->isEditable();
  34590. }
  34591. void ComboBox::setJustificationType (const Justification& justification) throw()
  34592. {
  34593. label->setJustificationType (justification);
  34594. }
  34595. const Justification ComboBox::getJustificationType() const throw()
  34596. {
  34597. return label->getJustificationType();
  34598. }
  34599. void ComboBox::setTooltip (const String& newTooltip)
  34600. {
  34601. SettableTooltipClient::setTooltip (newTooltip);
  34602. label->setTooltip (newTooltip);
  34603. }
  34604. void ComboBox::addItem (const String& newItemText,
  34605. const int newItemId) throw()
  34606. {
  34607. // you can't add empty strings to the list..
  34608. jassert (newItemText.isNotEmpty());
  34609. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  34610. jassert (newItemId != 0);
  34611. // you shouldn't use duplicate item IDs!
  34612. jassert (getItemForId (newItemId) == 0);
  34613. if (newItemText.isNotEmpty() && newItemId != 0)
  34614. {
  34615. if (separatorPending)
  34616. {
  34617. separatorPending = false;
  34618. ItemInfo* const item = new ItemInfo();
  34619. item->itemId = 0;
  34620. item->isEnabled = false;
  34621. item->isHeading = false;
  34622. items.add (item);
  34623. }
  34624. ItemInfo* const item = new ItemInfo();
  34625. item->name = newItemText;
  34626. item->itemId = newItemId;
  34627. item->isEnabled = true;
  34628. item->isHeading = false;
  34629. items.add (item);
  34630. }
  34631. }
  34632. void ComboBox::addSeparator() throw()
  34633. {
  34634. separatorPending = (items.size() > 0);
  34635. }
  34636. void ComboBox::addSectionHeading (const String& headingName) throw()
  34637. {
  34638. // you can't add empty strings to the list..
  34639. jassert (headingName.isNotEmpty());
  34640. if (headingName.isNotEmpty())
  34641. {
  34642. if (separatorPending)
  34643. {
  34644. separatorPending = false;
  34645. ItemInfo* const item = new ItemInfo();
  34646. item->itemId = 0;
  34647. item->isEnabled = false;
  34648. item->isHeading = false;
  34649. items.add (item);
  34650. }
  34651. ItemInfo* const item = new ItemInfo();
  34652. item->name = headingName;
  34653. item->itemId = 0;
  34654. item->isEnabled = true;
  34655. item->isHeading = true;
  34656. items.add (item);
  34657. }
  34658. }
  34659. void ComboBox::setItemEnabled (const int itemId,
  34660. const bool isEnabled) throw()
  34661. {
  34662. ItemInfo* const item = getItemForId (itemId);
  34663. if (item != 0)
  34664. item->isEnabled = isEnabled;
  34665. }
  34666. void ComboBox::changeItemText (const int itemId,
  34667. const String& newText) throw()
  34668. {
  34669. ItemInfo* const item = getItemForId (itemId);
  34670. jassert (item != 0);
  34671. if (item != 0)
  34672. item->name = newText;
  34673. }
  34674. void ComboBox::clear (const bool dontSendChangeMessage)
  34675. {
  34676. items.clear();
  34677. separatorPending = false;
  34678. if (! label->isEditable())
  34679. setSelectedItemIndex (-1, dontSendChangeMessage);
  34680. }
  34681. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  34682. {
  34683. jassert (itemId != 0);
  34684. if (itemId != 0)
  34685. {
  34686. for (int i = items.size(); --i >= 0;)
  34687. if (items.getUnchecked(i)->itemId == itemId)
  34688. return items.getUnchecked(i);
  34689. }
  34690. return 0;
  34691. }
  34692. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  34693. {
  34694. int n = 0;
  34695. for (int i = 0; i < items.size(); ++i)
  34696. {
  34697. ItemInfo* const item = items.getUnchecked(i);
  34698. if (item->isRealItem())
  34699. {
  34700. if (n++ == index)
  34701. return item;
  34702. }
  34703. }
  34704. return 0;
  34705. }
  34706. int ComboBox::getNumItems() const throw()
  34707. {
  34708. int n = 0;
  34709. for (int i = items.size(); --i >= 0;)
  34710. {
  34711. ItemInfo* const item = items.getUnchecked(i);
  34712. if (item->isRealItem())
  34713. ++n;
  34714. }
  34715. return n;
  34716. }
  34717. const String ComboBox::getItemText (const int index) const throw()
  34718. {
  34719. ItemInfo* const item = getItemForIndex (index);
  34720. if (item != 0)
  34721. return item->name;
  34722. return String::empty;
  34723. }
  34724. int ComboBox::getItemId (const int index) const throw()
  34725. {
  34726. ItemInfo* const item = getItemForIndex (index);
  34727. return (item != 0) ? item->itemId : 0;
  34728. }
  34729. bool ComboBox::ItemInfo::isSeparator() const throw()
  34730. {
  34731. return name.isEmpty();
  34732. }
  34733. bool ComboBox::ItemInfo::isRealItem() const throw()
  34734. {
  34735. return ! (isHeading || name.isEmpty());
  34736. }
  34737. int ComboBox::getSelectedItemIndex() const throw()
  34738. {
  34739. return (currentIndex >= 0 && getText() == getItemText (currentIndex))
  34740. ? currentIndex
  34741. : -1;
  34742. }
  34743. void ComboBox::setSelectedItemIndex (const int index,
  34744. const bool dontSendChangeMessage) throw()
  34745. {
  34746. if (currentIndex != index || label->getText() != getItemText (currentIndex))
  34747. {
  34748. if (((unsigned int) index) < (unsigned int) getNumItems())
  34749. currentIndex = index;
  34750. else
  34751. currentIndex = -1;
  34752. label->setText (getItemText (currentIndex), false);
  34753. if (! dontSendChangeMessage)
  34754. triggerAsyncUpdate();
  34755. }
  34756. }
  34757. void ComboBox::setSelectedId (const int newItemId,
  34758. const bool dontSendChangeMessage) throw()
  34759. {
  34760. for (int i = getNumItems(); --i >= 0;)
  34761. {
  34762. if (getItemId(i) == newItemId)
  34763. {
  34764. setSelectedItemIndex (i, dontSendChangeMessage);
  34765. break;
  34766. }
  34767. }
  34768. }
  34769. int ComboBox::getSelectedId() const throw()
  34770. {
  34771. const ItemInfo* const item = getItemForIndex (currentIndex);
  34772. return (item != 0 && getText() == item->name)
  34773. ? item->itemId
  34774. : 0;
  34775. }
  34776. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  34777. {
  34778. jassert (listener != 0);
  34779. if (listener != 0)
  34780. listeners.add (listener);
  34781. }
  34782. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  34783. {
  34784. listeners.removeValue (listener);
  34785. }
  34786. void ComboBox::handleAsyncUpdate()
  34787. {
  34788. for (int i = listeners.size(); --i >= 0;)
  34789. {
  34790. ((ComboBoxListener*) listeners.getUnchecked (i))->comboBoxChanged (this);
  34791. i = jmin (i, listeners.size());
  34792. }
  34793. }
  34794. const String ComboBox::getText() const throw()
  34795. {
  34796. return label->getText();
  34797. }
  34798. void ComboBox::setText (const String& newText,
  34799. const bool dontSendChangeMessage) throw()
  34800. {
  34801. for (int i = items.size(); --i >= 0;)
  34802. {
  34803. ItemInfo* const item = items.getUnchecked(i);
  34804. if (item->isRealItem()
  34805. && item->name == newText)
  34806. {
  34807. setSelectedId (item->itemId, dontSendChangeMessage);
  34808. return;
  34809. }
  34810. }
  34811. currentIndex = -1;
  34812. if (label->getText() != newText)
  34813. {
  34814. label->setText (newText, false);
  34815. if (! dontSendChangeMessage)
  34816. triggerAsyncUpdate();
  34817. }
  34818. repaint();
  34819. }
  34820. void ComboBox::showEditor()
  34821. {
  34822. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  34823. label->showEditor();
  34824. }
  34825. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  34826. {
  34827. textWhenNothingSelected = newMessage;
  34828. repaint();
  34829. }
  34830. const String ComboBox::getTextWhenNothingSelected() const throw()
  34831. {
  34832. return textWhenNothingSelected;
  34833. }
  34834. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  34835. {
  34836. noChoicesMessage = newMessage;
  34837. }
  34838. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  34839. {
  34840. return noChoicesMessage;
  34841. }
  34842. void ComboBox::paint (Graphics& g)
  34843. {
  34844. getLookAndFeel().drawComboBox (g,
  34845. getWidth(),
  34846. getHeight(),
  34847. isButtonDown,
  34848. label->getRight(),
  34849. 0,
  34850. getWidth() - label->getRight(),
  34851. getHeight(),
  34852. *this);
  34853. if (textWhenNothingSelected.isNotEmpty()
  34854. && label->getText().isEmpty()
  34855. && ! label->isBeingEdited())
  34856. {
  34857. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  34858. g.setFont (label->getFont());
  34859. g.drawFittedText (textWhenNothingSelected,
  34860. label->getX() + 2, label->getY() + 1,
  34861. label->getWidth() - 4, label->getHeight() - 2,
  34862. label->getJustificationType(),
  34863. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  34864. }
  34865. }
  34866. void ComboBox::resized()
  34867. {
  34868. if (getHeight() > 0 && getWidth() > 0)
  34869. getLookAndFeel().positionComboBoxText (*this, *label);
  34870. }
  34871. void ComboBox::enablementChanged()
  34872. {
  34873. repaint();
  34874. }
  34875. void ComboBox::lookAndFeelChanged()
  34876. {
  34877. repaint();
  34878. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  34879. if (label != 0)
  34880. {
  34881. newLabel->setEditable (label->isEditable());
  34882. newLabel->setJustificationType (label->getJustificationType());
  34883. newLabel->setTooltip (label->getTooltip());
  34884. newLabel->setText (label->getText(), false);
  34885. }
  34886. delete label;
  34887. label = newLabel;
  34888. addAndMakeVisible (newLabel);
  34889. newLabel->addListener (this);
  34890. newLabel->addMouseListener (this, false);
  34891. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  34892. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  34893. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  34894. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  34895. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  34896. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  34897. resized();
  34898. }
  34899. void ComboBox::colourChanged()
  34900. {
  34901. lookAndFeelChanged();
  34902. }
  34903. bool ComboBox::keyPressed (const KeyPress& key)
  34904. {
  34905. bool used = false;
  34906. if (key.isKeyCode (KeyPress::upKey)
  34907. || key.isKeyCode (KeyPress::leftKey))
  34908. {
  34909. setSelectedItemIndex (jmax (0, currentIndex - 1));
  34910. used = true;
  34911. }
  34912. else if (key.isKeyCode (KeyPress::downKey)
  34913. || key.isKeyCode (KeyPress::rightKey))
  34914. {
  34915. setSelectedItemIndex (jmin (currentIndex + 1, getNumItems() - 1));
  34916. used = true;
  34917. }
  34918. else if (key.isKeyCode (KeyPress::returnKey))
  34919. {
  34920. showPopup();
  34921. used = true;
  34922. }
  34923. return used;
  34924. }
  34925. bool ComboBox::keyStateChanged (const bool isKeyDown)
  34926. {
  34927. // only forward key events that aren't used by this component
  34928. return isKeyDown
  34929. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  34930. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  34931. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  34932. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  34933. }
  34934. void ComboBox::focusGained (FocusChangeType)
  34935. {
  34936. repaint();
  34937. }
  34938. void ComboBox::focusLost (FocusChangeType)
  34939. {
  34940. repaint();
  34941. }
  34942. void ComboBox::labelTextChanged (Label*)
  34943. {
  34944. triggerAsyncUpdate();
  34945. }
  34946. void ComboBox::showPopup()
  34947. {
  34948. if (! menuActive)
  34949. {
  34950. const int currentId = getSelectedId();
  34951. ComponentDeletionWatcher deletionWatcher (this);
  34952. PopupMenu menu;
  34953. menu.setLookAndFeel (&getLookAndFeel());
  34954. for (int i = 0; i < items.size(); ++i)
  34955. {
  34956. const ItemInfo* const item = items.getUnchecked(i);
  34957. if (item->isSeparator())
  34958. menu.addSeparator();
  34959. else if (item->isHeading)
  34960. menu.addSectionHeader (item->name);
  34961. else
  34962. menu.addItem (item->itemId, item->name,
  34963. item->isEnabled, item->itemId == currentId);
  34964. }
  34965. if (items.size() == 0)
  34966. menu.addItem (1, noChoicesMessage, false);
  34967. const int itemHeight = jlimit (12, 24, getHeight());
  34968. menuActive = true;
  34969. const int resultId = menu.showAt (this, currentId,
  34970. getWidth(), 1, itemHeight);
  34971. if (deletionWatcher.hasBeenDeleted())
  34972. return;
  34973. menuActive = false;
  34974. if (resultId != 0)
  34975. setSelectedId (resultId);
  34976. }
  34977. }
  34978. void ComboBox::mouseDown (const MouseEvent& e)
  34979. {
  34980. beginDragAutoRepeat (300);
  34981. isButtonDown = isEnabled();
  34982. if (isButtonDown
  34983. && (e.eventComponent == this || ! label->isEditable()))
  34984. {
  34985. showPopup();
  34986. }
  34987. }
  34988. void ComboBox::mouseDrag (const MouseEvent& e)
  34989. {
  34990. beginDragAutoRepeat (50);
  34991. if (isButtonDown && ! e.mouseWasClicked())
  34992. showPopup();
  34993. }
  34994. void ComboBox::mouseUp (const MouseEvent& e2)
  34995. {
  34996. if (isButtonDown)
  34997. {
  34998. isButtonDown = false;
  34999. repaint();
  35000. const MouseEvent e (e2.getEventRelativeTo (this));
  35001. if (reallyContains (e.x, e.y, true)
  35002. && (e2.eventComponent == this || ! label->isEditable()))
  35003. {
  35004. showPopup();
  35005. }
  35006. }
  35007. }
  35008. END_JUCE_NAMESPACE
  35009. /********* End of inlined file: juce_ComboBox.cpp *********/
  35010. /********* Start of inlined file: juce_Label.cpp *********/
  35011. BEGIN_JUCE_NAMESPACE
  35012. Label::Label (const String& componentName,
  35013. const String& labelText)
  35014. : Component (componentName),
  35015. text (labelText),
  35016. font (15.0f),
  35017. justification (Justification::centredLeft),
  35018. editor (0),
  35019. listeners (2),
  35020. ownerComponent (0),
  35021. deletionWatcher (0),
  35022. horizontalBorderSize (3),
  35023. verticalBorderSize (1),
  35024. minimumHorizontalScale (0.7f),
  35025. editSingleClick (false),
  35026. editDoubleClick (false),
  35027. lossOfFocusDiscardsChanges (false)
  35028. {
  35029. setColour (TextEditor::textColourId, Colours::black);
  35030. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  35031. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  35032. }
  35033. Label::~Label()
  35034. {
  35035. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35036. ownerComponent->removeComponentListener (this);
  35037. deleteAndZero (deletionWatcher);
  35038. if (editor != 0)
  35039. delete editor;
  35040. }
  35041. void Label::setText (const String& newText,
  35042. const bool broadcastChangeMessage)
  35043. {
  35044. hideEditor (true);
  35045. if (text != newText)
  35046. {
  35047. text = newText;
  35048. repaint();
  35049. textWasChanged();
  35050. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35051. componentMovedOrResized (*ownerComponent, true, true);
  35052. if (broadcastChangeMessage)
  35053. callChangeListeners();
  35054. }
  35055. }
  35056. const String Label::getText (const bool returnActiveEditorContents) const throw()
  35057. {
  35058. return (returnActiveEditorContents && isBeingEdited())
  35059. ? editor->getText()
  35060. : text;
  35061. }
  35062. void Label::setFont (const Font& newFont) throw()
  35063. {
  35064. font = newFont;
  35065. repaint();
  35066. }
  35067. const Font& Label::getFont() const throw()
  35068. {
  35069. return font;
  35070. }
  35071. void Label::setEditable (const bool editOnSingleClick,
  35072. const bool editOnDoubleClick,
  35073. const bool lossOfFocusDiscardsChanges_) throw()
  35074. {
  35075. editSingleClick = editOnSingleClick;
  35076. editDoubleClick = editOnDoubleClick;
  35077. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  35078. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  35079. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  35080. }
  35081. void Label::setJustificationType (const Justification& justification_) throw()
  35082. {
  35083. justification = justification_;
  35084. repaint();
  35085. }
  35086. void Label::setBorderSize (int h, int v)
  35087. {
  35088. horizontalBorderSize = h;
  35089. verticalBorderSize = v;
  35090. repaint();
  35091. }
  35092. void Label::attachToComponent (Component* owner,
  35093. const bool onLeft)
  35094. {
  35095. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35096. ownerComponent->removeComponentListener (this);
  35097. deleteAndZero (deletionWatcher);
  35098. ownerComponent = owner;
  35099. leftOfOwnerComp = onLeft;
  35100. if (ownerComponent != 0)
  35101. {
  35102. deletionWatcher = new ComponentDeletionWatcher (owner);
  35103. setVisible (owner->isVisible());
  35104. ownerComponent->addComponentListener (this);
  35105. componentParentHierarchyChanged (*ownerComponent);
  35106. componentMovedOrResized (*ownerComponent, true, true);
  35107. }
  35108. }
  35109. void Label::componentMovedOrResized (Component& component,
  35110. bool /*wasMoved*/,
  35111. bool /*wasResized*/)
  35112. {
  35113. if (leftOfOwnerComp)
  35114. {
  35115. setSize (jmin (getFont().getStringWidth (text) + 8, component.getX()),
  35116. component.getHeight());
  35117. setTopRightPosition (component.getX(), component.getY());
  35118. }
  35119. else
  35120. {
  35121. setSize (component.getWidth(),
  35122. 8 + roundFloatToInt (getFont().getHeight()));
  35123. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  35124. }
  35125. }
  35126. void Label::componentParentHierarchyChanged (Component& component)
  35127. {
  35128. if (component.getParentComponent() != 0)
  35129. component.getParentComponent()->addChildComponent (this);
  35130. }
  35131. void Label::componentVisibilityChanged (Component& component)
  35132. {
  35133. setVisible (component.isVisible());
  35134. }
  35135. void Label::textWasEdited()
  35136. {
  35137. }
  35138. void Label::textWasChanged()
  35139. {
  35140. }
  35141. void Label::showEditor()
  35142. {
  35143. if (editor == 0)
  35144. {
  35145. addAndMakeVisible (editor = createEditorComponent());
  35146. editor->setText (getText(), false);
  35147. editor->addListener (this);
  35148. editor->grabKeyboardFocus();
  35149. editor->setHighlightedRegion (0, text.length());
  35150. editor->addListener (this);
  35151. resized();
  35152. repaint();
  35153. editorShown (editor);
  35154. enterModalState();
  35155. editor->grabKeyboardFocus();
  35156. }
  35157. }
  35158. void Label::editorShown (TextEditor* editorComponent)
  35159. {
  35160. }
  35161. void Label::editorAboutToBeHidden (TextEditor* editorComponent)
  35162. {
  35163. }
  35164. bool Label::updateFromTextEditorContents()
  35165. {
  35166. jassert (editor != 0);
  35167. const String newText (editor->getText());
  35168. if (text != newText)
  35169. {
  35170. text = newText;
  35171. repaint();
  35172. textWasChanged();
  35173. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35174. componentMovedOrResized (*ownerComponent, true, true);
  35175. return true;
  35176. }
  35177. return false;
  35178. }
  35179. void Label::hideEditor (const bool discardCurrentEditorContents)
  35180. {
  35181. if (editor != 0)
  35182. {
  35183. editorAboutToBeHidden (editor);
  35184. const bool changed = (! discardCurrentEditorContents)
  35185. && updateFromTextEditorContents();
  35186. deleteAndZero (editor);
  35187. repaint();
  35188. if (changed)
  35189. textWasEdited();
  35190. exitModalState (0);
  35191. if (changed && isValidComponent())
  35192. callChangeListeners();
  35193. }
  35194. }
  35195. void Label::inputAttemptWhenModal()
  35196. {
  35197. if (editor != 0)
  35198. {
  35199. if (lossOfFocusDiscardsChanges)
  35200. textEditorEscapeKeyPressed (*editor);
  35201. else
  35202. textEditorReturnKeyPressed (*editor);
  35203. }
  35204. }
  35205. bool Label::isBeingEdited() const throw()
  35206. {
  35207. return editor != 0;
  35208. }
  35209. TextEditor* Label::createEditorComponent()
  35210. {
  35211. TextEditor* const ed = new TextEditor (getName());
  35212. ed->setFont (font);
  35213. // copy these colours from our own settings..
  35214. const int cols[] = { TextEditor::backgroundColourId,
  35215. TextEditor::textColourId,
  35216. TextEditor::highlightColourId,
  35217. TextEditor::highlightedTextColourId,
  35218. TextEditor::caretColourId,
  35219. TextEditor::outlineColourId,
  35220. TextEditor::focusedOutlineColourId,
  35221. TextEditor::shadowColourId };
  35222. for (int i = 0; i < numElementsInArray (cols); ++i)
  35223. ed->setColour (cols[i], findColour (cols[i]));
  35224. return ed;
  35225. }
  35226. void Label::paint (Graphics& g)
  35227. {
  35228. getLookAndFeel().drawLabel (g, *this);
  35229. }
  35230. void Label::mouseUp (const MouseEvent& e)
  35231. {
  35232. if (editSingleClick
  35233. && e.mouseWasClicked()
  35234. && contains (e.x, e.y)
  35235. && ! e.mods.isPopupMenu())
  35236. {
  35237. showEditor();
  35238. }
  35239. }
  35240. void Label::mouseDoubleClick (const MouseEvent& e)
  35241. {
  35242. if (editDoubleClick && ! e.mods.isPopupMenu())
  35243. showEditor();
  35244. }
  35245. void Label::resized()
  35246. {
  35247. if (editor != 0)
  35248. editor->setBoundsInset (BorderSize (0));
  35249. }
  35250. void Label::focusGained (FocusChangeType cause)
  35251. {
  35252. if (editSingleClick && cause == focusChangedByTabKey)
  35253. showEditor();
  35254. }
  35255. void Label::enablementChanged()
  35256. {
  35257. repaint();
  35258. }
  35259. void Label::colourChanged()
  35260. {
  35261. repaint();
  35262. }
  35263. void Label::setMinimumHorizontalScale (const float newScale)
  35264. {
  35265. if (minimumHorizontalScale != newScale)
  35266. {
  35267. minimumHorizontalScale = newScale;
  35268. repaint();
  35269. }
  35270. }
  35271. // We'll use a custom focus traverser here to make sure focus goes from the
  35272. // text editor to another component rather than back to the label itself.
  35273. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  35274. {
  35275. public:
  35276. LabelKeyboardFocusTraverser() {}
  35277. Component* getNextComponent (Component* current)
  35278. {
  35279. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  35280. ? current->getParentComponent() : current);
  35281. }
  35282. Component* getPreviousComponent (Component* current)
  35283. {
  35284. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  35285. ? current->getParentComponent() : current);
  35286. }
  35287. };
  35288. KeyboardFocusTraverser* Label::createFocusTraverser()
  35289. {
  35290. return new LabelKeyboardFocusTraverser();
  35291. }
  35292. void Label::addListener (LabelListener* const listener) throw()
  35293. {
  35294. jassert (listener != 0);
  35295. if (listener != 0)
  35296. listeners.add (listener);
  35297. }
  35298. void Label::removeListener (LabelListener* const listener) throw()
  35299. {
  35300. listeners.removeValue (listener);
  35301. }
  35302. void Label::callChangeListeners()
  35303. {
  35304. for (int i = listeners.size(); --i >= 0;)
  35305. {
  35306. ((LabelListener*) listeners.getUnchecked (i))->labelTextChanged (this);
  35307. i = jmin (i, listeners.size());
  35308. }
  35309. }
  35310. void Label::textEditorTextChanged (TextEditor& ed)
  35311. {
  35312. if (editor != 0)
  35313. {
  35314. jassert (&ed == editor);
  35315. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  35316. {
  35317. if (lossOfFocusDiscardsChanges)
  35318. textEditorEscapeKeyPressed (ed);
  35319. else
  35320. textEditorReturnKeyPressed (ed);
  35321. }
  35322. }
  35323. }
  35324. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  35325. {
  35326. if (editor != 0)
  35327. {
  35328. jassert (&ed == editor);
  35329. (void) ed;
  35330. const bool changed = updateFromTextEditorContents();
  35331. hideEditor (true);
  35332. if (changed)
  35333. {
  35334. textWasEdited();
  35335. if (isValidComponent())
  35336. callChangeListeners();
  35337. }
  35338. }
  35339. }
  35340. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  35341. {
  35342. if (editor != 0)
  35343. {
  35344. jassert (&ed == editor);
  35345. (void) ed;
  35346. editor->setText (text, false);
  35347. hideEditor (true);
  35348. }
  35349. }
  35350. void Label::textEditorFocusLost (TextEditor& ed)
  35351. {
  35352. textEditorTextChanged (ed);
  35353. }
  35354. END_JUCE_NAMESPACE
  35355. /********* End of inlined file: juce_Label.cpp *********/
  35356. /********* Start of inlined file: juce_ListBox.cpp *********/
  35357. BEGIN_JUCE_NAMESPACE
  35358. class ListBoxRowComponent : public Component
  35359. {
  35360. public:
  35361. ListBoxRowComponent (ListBox& owner_)
  35362. : owner (owner_),
  35363. row (-1),
  35364. selected (false),
  35365. isDragging (false)
  35366. {
  35367. }
  35368. ~ListBoxRowComponent()
  35369. {
  35370. deleteAllChildren();
  35371. }
  35372. void paint (Graphics& g)
  35373. {
  35374. if (owner.getModel() != 0)
  35375. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  35376. }
  35377. void update (const int row_, const bool selected_)
  35378. {
  35379. if (row != row_ || selected != selected_)
  35380. {
  35381. repaint();
  35382. row = row_;
  35383. selected = selected_;
  35384. }
  35385. if (owner.getModel() != 0)
  35386. {
  35387. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  35388. if (customComp != 0)
  35389. {
  35390. addAndMakeVisible (customComp);
  35391. customComp->setBounds (0, 0, getWidth(), getHeight());
  35392. for (int i = getNumChildComponents(); --i >= 0;)
  35393. if (getChildComponent (i) != customComp)
  35394. delete getChildComponent (i);
  35395. }
  35396. else
  35397. {
  35398. deleteAllChildren();
  35399. }
  35400. }
  35401. }
  35402. void mouseDown (const MouseEvent& e)
  35403. {
  35404. isDragging = false;
  35405. selectRowOnMouseUp = false;
  35406. if (isEnabled())
  35407. {
  35408. if (! selected)
  35409. {
  35410. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  35411. if (owner.getModel() != 0)
  35412. owner.getModel()->listBoxItemClicked (row, e);
  35413. }
  35414. else
  35415. {
  35416. selectRowOnMouseUp = true;
  35417. }
  35418. }
  35419. }
  35420. void mouseUp (const MouseEvent& e)
  35421. {
  35422. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  35423. {
  35424. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  35425. if (owner.getModel() != 0)
  35426. owner.getModel()->listBoxItemClicked (row, e);
  35427. }
  35428. }
  35429. void mouseDoubleClick (const MouseEvent& e)
  35430. {
  35431. if (owner.getModel() != 0 && isEnabled())
  35432. owner.getModel()->listBoxItemDoubleClicked (row, e);
  35433. }
  35434. void mouseDrag (const MouseEvent& e)
  35435. {
  35436. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  35437. {
  35438. const SparseSet <int> selectedRows (owner.getSelectedRows());
  35439. if (selectedRows.size() > 0)
  35440. {
  35441. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  35442. if (dragDescription.isNotEmpty())
  35443. {
  35444. isDragging = true;
  35445. DragAndDropContainer* const dragContainer
  35446. = DragAndDropContainer::findParentDragContainerFor (this);
  35447. if (dragContainer != 0)
  35448. {
  35449. Image* dragImage = owner.createSnapshotOfSelectedRows();
  35450. dragImage->multiplyAllAlphas (0.6f);
  35451. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  35452. }
  35453. else
  35454. {
  35455. // to be able to do a drag-and-drop operation, the listbox needs to
  35456. // be inside a component which is also a DragAndDropContainer.
  35457. jassertfalse
  35458. }
  35459. }
  35460. }
  35461. }
  35462. }
  35463. void resized()
  35464. {
  35465. if (getNumChildComponents() > 0)
  35466. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  35467. }
  35468. juce_UseDebuggingNewOperator
  35469. bool neededFlag;
  35470. private:
  35471. ListBox& owner;
  35472. int row;
  35473. bool selected, isDragging, selectRowOnMouseUp;
  35474. ListBoxRowComponent (const ListBoxRowComponent&);
  35475. const ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  35476. };
  35477. class ListViewport : public Viewport
  35478. {
  35479. public:
  35480. int firstIndex, firstWholeIndex, lastWholeIndex;
  35481. bool hasUpdated;
  35482. ListViewport (ListBox& owner_)
  35483. : owner (owner_)
  35484. {
  35485. setWantsKeyboardFocus (false);
  35486. setViewedComponent (new Component());
  35487. getViewedComponent()->addMouseListener (this, false);
  35488. getViewedComponent()->setWantsKeyboardFocus (false);
  35489. }
  35490. ~ListViewport()
  35491. {
  35492. getViewedComponent()->removeMouseListener (this);
  35493. getViewedComponent()->deleteAllChildren();
  35494. }
  35495. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  35496. {
  35497. return (ListBoxRowComponent*) getViewedComponent()
  35498. ->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents()));
  35499. }
  35500. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  35501. {
  35502. const int index = getIndexOfChildComponent (rowComponent);
  35503. const int num = getViewedComponent()->getNumChildComponents();
  35504. for (int i = num; --i >= 0;)
  35505. if (((firstIndex + i) % jmax (1, num)) == index)
  35506. return firstIndex + i;
  35507. return -1;
  35508. }
  35509. Component* getComponentForRowIfOnscreen (const int row) const throw()
  35510. {
  35511. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  35512. ? getComponentForRow (row) : 0;
  35513. }
  35514. void visibleAreaChanged (int, int, int, int)
  35515. {
  35516. updateVisibleArea (true);
  35517. if (owner.getModel() != 0)
  35518. owner.getModel()->listWasScrolled();
  35519. }
  35520. void updateVisibleArea (const bool makeSureItUpdatesContent)
  35521. {
  35522. hasUpdated = false;
  35523. const int newX = getViewedComponent()->getX();
  35524. int newY = getViewedComponent()->getY();
  35525. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  35526. const int newH = owner.totalItems * owner.getRowHeight();
  35527. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  35528. newY = getMaximumVisibleHeight() - newH;
  35529. getViewedComponent()->setBounds (newX, newY, newW, newH);
  35530. if (makeSureItUpdatesContent && ! hasUpdated)
  35531. updateContents();
  35532. }
  35533. void updateContents()
  35534. {
  35535. hasUpdated = true;
  35536. const int rowHeight = owner.getRowHeight();
  35537. if (rowHeight > 0)
  35538. {
  35539. const int y = getViewPositionY();
  35540. const int w = getViewedComponent()->getWidth();
  35541. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  35542. while (numNeeded > getViewedComponent()->getNumChildComponents())
  35543. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  35544. jassert (numNeeded >= 0);
  35545. while (numNeeded < getViewedComponent()->getNumChildComponents())
  35546. {
  35547. Component* const rowToRemove
  35548. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  35549. delete rowToRemove;
  35550. }
  35551. firstIndex = y / rowHeight;
  35552. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  35553. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  35554. for (int i = 0; i < numNeeded; ++i)
  35555. {
  35556. const int row = i + firstIndex;
  35557. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  35558. if (rowComp != 0)
  35559. {
  35560. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  35561. rowComp->update (row, owner.isRowSelected (row));
  35562. }
  35563. }
  35564. }
  35565. if (owner.headerComponent != 0)
  35566. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  35567. owner.outlineThickness,
  35568. jmax (owner.getWidth() - owner.outlineThickness * 2,
  35569. getViewedComponent()->getWidth()),
  35570. owner.headerComponent->getHeight());
  35571. }
  35572. void paint (Graphics& g)
  35573. {
  35574. if (isOpaque())
  35575. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  35576. }
  35577. bool keyPressed (const KeyPress& key)
  35578. {
  35579. if (key.isKeyCode (KeyPress::upKey)
  35580. || key.isKeyCode (KeyPress::downKey)
  35581. || key.isKeyCode (KeyPress::pageUpKey)
  35582. || key.isKeyCode (KeyPress::pageDownKey)
  35583. || key.isKeyCode (KeyPress::homeKey)
  35584. || key.isKeyCode (KeyPress::endKey))
  35585. {
  35586. // we want to avoid these keypresses going to the viewport, and instead allow
  35587. // them to pass up to our listbox..
  35588. return false;
  35589. }
  35590. return Viewport::keyPressed (key);
  35591. }
  35592. juce_UseDebuggingNewOperator
  35593. private:
  35594. ListBox& owner;
  35595. ListViewport (const ListViewport&);
  35596. const ListViewport& operator= (const ListViewport&);
  35597. };
  35598. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  35599. : Component (name),
  35600. model (model_),
  35601. headerComponent (0),
  35602. totalItems (0),
  35603. rowHeight (22),
  35604. minimumRowWidth (0),
  35605. outlineThickness (0),
  35606. lastRowSelected (-1),
  35607. mouseMoveSelects (false),
  35608. multipleSelection (false),
  35609. hasDoneInitialUpdate (false)
  35610. {
  35611. addAndMakeVisible (viewport = new ListViewport (*this));
  35612. setWantsKeyboardFocus (true);
  35613. }
  35614. ListBox::~ListBox()
  35615. {
  35616. deleteAllChildren();
  35617. }
  35618. void ListBox::setModel (ListBoxModel* const newModel)
  35619. {
  35620. if (model != newModel)
  35621. {
  35622. model = newModel;
  35623. updateContent();
  35624. }
  35625. }
  35626. void ListBox::setMultipleSelectionEnabled (bool b)
  35627. {
  35628. multipleSelection = b;
  35629. }
  35630. void ListBox::setMouseMoveSelectsRows (bool b)
  35631. {
  35632. mouseMoveSelects = b;
  35633. if (b)
  35634. addMouseListener (this, true);
  35635. }
  35636. void ListBox::paint (Graphics& g)
  35637. {
  35638. if (! hasDoneInitialUpdate)
  35639. updateContent();
  35640. g.fillAll (findColour (backgroundColourId));
  35641. }
  35642. void ListBox::paintOverChildren (Graphics& g)
  35643. {
  35644. if (outlineThickness > 0)
  35645. {
  35646. g.setColour (findColour (outlineColourId));
  35647. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  35648. }
  35649. }
  35650. void ListBox::resized()
  35651. {
  35652. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  35653. outlineThickness,
  35654. outlineThickness,
  35655. outlineThickness));
  35656. viewport->setSingleStepSizes (20, getRowHeight());
  35657. viewport->updateVisibleArea (false);
  35658. }
  35659. void ListBox::visibilityChanged()
  35660. {
  35661. viewport->updateVisibleArea (true);
  35662. }
  35663. Viewport* ListBox::getViewport() const throw()
  35664. {
  35665. return viewport;
  35666. }
  35667. void ListBox::updateContent()
  35668. {
  35669. hasDoneInitialUpdate = true;
  35670. totalItems = (model != 0) ? model->getNumRows() : 0;
  35671. bool selectionChanged = false;
  35672. if (selected [selected.size() - 1] >= totalItems)
  35673. {
  35674. selected.removeRange (totalItems, INT_MAX - totalItems);
  35675. lastRowSelected = getSelectedRow (0);
  35676. selectionChanged = true;
  35677. }
  35678. viewport->updateVisibleArea (isVisible());
  35679. viewport->resized();
  35680. if (selectionChanged && model != 0)
  35681. model->selectedRowsChanged (lastRowSelected);
  35682. }
  35683. void ListBox::selectRow (const int row,
  35684. bool dontScroll,
  35685. bool deselectOthersFirst)
  35686. {
  35687. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  35688. }
  35689. void ListBox::selectRowInternal (const int row,
  35690. bool dontScroll,
  35691. bool deselectOthersFirst,
  35692. bool isMouseClick)
  35693. {
  35694. if (! multipleSelection)
  35695. deselectOthersFirst = true;
  35696. if ((! isRowSelected (row))
  35697. || (deselectOthersFirst && getNumSelectedRows() > 1))
  35698. {
  35699. if (((unsigned int) row) < (unsigned int) totalItems)
  35700. {
  35701. if (deselectOthersFirst)
  35702. selected.clear();
  35703. selected.addRange (row, 1);
  35704. if (getHeight() == 0 || getWidth() == 0)
  35705. dontScroll = true;
  35706. viewport->hasUpdated = false;
  35707. if (row < viewport->firstWholeIndex && ! dontScroll)
  35708. {
  35709. viewport->setViewPosition (viewport->getViewPositionX(),
  35710. row * getRowHeight());
  35711. }
  35712. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  35713. {
  35714. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  35715. if (row >= lastRowSelected + rowsOnScreen
  35716. && rowsOnScreen < totalItems - 1
  35717. && ! isMouseClick)
  35718. {
  35719. viewport->setViewPosition (viewport->getViewPositionX(),
  35720. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  35721. * getRowHeight());
  35722. }
  35723. else
  35724. {
  35725. viewport->setViewPosition (viewport->getViewPositionX(),
  35726. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  35727. }
  35728. }
  35729. if (! viewport->hasUpdated)
  35730. viewport->updateContents();
  35731. lastRowSelected = row;
  35732. model->selectedRowsChanged (row);
  35733. }
  35734. else
  35735. {
  35736. if (deselectOthersFirst)
  35737. deselectAllRows();
  35738. }
  35739. }
  35740. }
  35741. void ListBox::deselectRow (const int row)
  35742. {
  35743. if (selected.contains (row))
  35744. {
  35745. selected.removeRange (row, 1);
  35746. if (row == lastRowSelected)
  35747. lastRowSelected = getSelectedRow (0);
  35748. viewport->updateContents();
  35749. model->selectedRowsChanged (lastRowSelected);
  35750. }
  35751. }
  35752. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  35753. const bool sendNotificationEventToModel)
  35754. {
  35755. selected = setOfRowsToBeSelected;
  35756. selected.removeRange (totalItems, INT_MAX - totalItems);
  35757. if (! isRowSelected (lastRowSelected))
  35758. lastRowSelected = getSelectedRow (0);
  35759. viewport->updateContents();
  35760. if ((model != 0) && sendNotificationEventToModel)
  35761. model->selectedRowsChanged (lastRowSelected);
  35762. }
  35763. const SparseSet<int> ListBox::getSelectedRows() const
  35764. {
  35765. return selected;
  35766. }
  35767. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  35768. {
  35769. if (multipleSelection && (firstRow != lastRow))
  35770. {
  35771. const int numRows = totalItems - 1;
  35772. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  35773. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  35774. selected.addRange (jmin (firstRow, lastRow),
  35775. abs (firstRow - lastRow) + 1);
  35776. selected.removeRange (lastRow, 1);
  35777. }
  35778. selectRowInternal (lastRow, false, false, true);
  35779. }
  35780. void ListBox::flipRowSelection (const int row)
  35781. {
  35782. if (isRowSelected (row))
  35783. deselectRow (row);
  35784. else
  35785. selectRowInternal (row, false, false, true);
  35786. }
  35787. void ListBox::deselectAllRows()
  35788. {
  35789. if (! selected.isEmpty())
  35790. {
  35791. selected.clear();
  35792. lastRowSelected = -1;
  35793. viewport->updateContents();
  35794. if (model != 0)
  35795. model->selectedRowsChanged (lastRowSelected);
  35796. }
  35797. }
  35798. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  35799. const ModifierKeys& mods)
  35800. {
  35801. if (multipleSelection && mods.isCommandDown())
  35802. {
  35803. flipRowSelection (row);
  35804. }
  35805. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  35806. {
  35807. selectRangeOfRows (lastRowSelected, row);
  35808. }
  35809. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  35810. {
  35811. selectRowInternal (row, false, true, true);
  35812. }
  35813. }
  35814. int ListBox::getNumSelectedRows() const
  35815. {
  35816. return selected.size();
  35817. }
  35818. int ListBox::getSelectedRow (const int index) const
  35819. {
  35820. return (((unsigned int) index) < (unsigned int) selected.size())
  35821. ? selected [index] : -1;
  35822. }
  35823. bool ListBox::isRowSelected (const int row) const
  35824. {
  35825. return selected.contains (row);
  35826. }
  35827. int ListBox::getLastRowSelected() const
  35828. {
  35829. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  35830. }
  35831. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  35832. {
  35833. if (((unsigned int) x) < (unsigned int) getWidth())
  35834. {
  35835. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  35836. if (((unsigned int) row) < (unsigned int) totalItems)
  35837. return row;
  35838. }
  35839. return -1;
  35840. }
  35841. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  35842. {
  35843. if (((unsigned int) x) < (unsigned int) getWidth())
  35844. {
  35845. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  35846. return jlimit (0, totalItems, row);
  35847. }
  35848. return -1;
  35849. }
  35850. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  35851. {
  35852. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  35853. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  35854. }
  35855. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  35856. {
  35857. return viewport->getRowNumberOfComponent (rowComponent);
  35858. }
  35859. const Rectangle ListBox::getRowPosition (const int rowNumber,
  35860. const bool relativeToComponentTopLeft) const throw()
  35861. {
  35862. const int rowHeight = getRowHeight();
  35863. int y = viewport->getY() + rowHeight * rowNumber;
  35864. if (relativeToComponentTopLeft)
  35865. y -= viewport->getViewPositionY();
  35866. return Rectangle (viewport->getX(), y,
  35867. viewport->getViewedComponent()->getWidth(), rowHeight);
  35868. }
  35869. void ListBox::setVerticalPosition (const double proportion)
  35870. {
  35871. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  35872. viewport->setViewPosition (viewport->getViewPositionX(),
  35873. jmax (0, roundDoubleToInt (proportion * offscreen)));
  35874. }
  35875. double ListBox::getVerticalPosition() const
  35876. {
  35877. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  35878. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  35879. : 0;
  35880. }
  35881. int ListBox::getVisibleRowWidth() const throw()
  35882. {
  35883. return viewport->getViewWidth();
  35884. }
  35885. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  35886. {
  35887. if (row < viewport->firstWholeIndex)
  35888. {
  35889. viewport->setViewPosition (viewport->getViewPositionX(),
  35890. row * getRowHeight());
  35891. }
  35892. else if (row >= viewport->lastWholeIndex)
  35893. {
  35894. viewport->setViewPosition (viewport->getViewPositionX(),
  35895. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  35896. }
  35897. }
  35898. bool ListBox::keyPressed (const KeyPress& key)
  35899. {
  35900. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  35901. const bool multiple = multipleSelection
  35902. && (lastRowSelected >= 0)
  35903. && (key.getModifiers().isShiftDown()
  35904. || key.getModifiers().isCtrlDown()
  35905. || key.getModifiers().isCommandDown());
  35906. if (key.isKeyCode (KeyPress::upKey))
  35907. {
  35908. if (multiple)
  35909. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  35910. else
  35911. selectRow (jmax (0, lastRowSelected - 1));
  35912. }
  35913. else if (key.isKeyCode (KeyPress::returnKey)
  35914. && isRowSelected (lastRowSelected))
  35915. {
  35916. if (model != 0)
  35917. model->returnKeyPressed (lastRowSelected);
  35918. }
  35919. else if (key.isKeyCode (KeyPress::pageUpKey))
  35920. {
  35921. if (multiple)
  35922. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  35923. else
  35924. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  35925. }
  35926. else if (key.isKeyCode (KeyPress::pageDownKey))
  35927. {
  35928. if (multiple)
  35929. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  35930. else
  35931. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  35932. }
  35933. else if (key.isKeyCode (KeyPress::homeKey))
  35934. {
  35935. if (multiple && key.getModifiers().isShiftDown())
  35936. selectRangeOfRows (lastRowSelected, 0);
  35937. else
  35938. selectRow (0);
  35939. }
  35940. else if (key.isKeyCode (KeyPress::endKey))
  35941. {
  35942. if (multiple && key.getModifiers().isShiftDown())
  35943. selectRangeOfRows (lastRowSelected, totalItems - 1);
  35944. else
  35945. selectRow (totalItems - 1);
  35946. }
  35947. else if (key.isKeyCode (KeyPress::downKey))
  35948. {
  35949. if (multiple)
  35950. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  35951. else
  35952. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  35953. }
  35954. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  35955. && isRowSelected (lastRowSelected))
  35956. {
  35957. if (model != 0)
  35958. model->deleteKeyPressed (lastRowSelected);
  35959. }
  35960. else if (multiple && key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  35961. {
  35962. selectRangeOfRows (0, INT_MAX);
  35963. }
  35964. else
  35965. {
  35966. return false;
  35967. }
  35968. return true;
  35969. }
  35970. bool ListBox::keyStateChanged (const bool isKeyDown)
  35971. {
  35972. return isKeyDown
  35973. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  35974. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  35975. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  35976. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  35977. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  35978. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  35979. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  35980. }
  35981. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  35982. {
  35983. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  35984. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  35985. }
  35986. void ListBox::mouseMove (const MouseEvent& e)
  35987. {
  35988. if (mouseMoveSelects)
  35989. {
  35990. const MouseEvent e2 (e.getEventRelativeTo (this));
  35991. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  35992. lastMouseX = e2.x;
  35993. lastMouseY = e2.y;
  35994. }
  35995. }
  35996. void ListBox::mouseExit (const MouseEvent& e)
  35997. {
  35998. mouseMove (e);
  35999. }
  36000. void ListBox::mouseUp (const MouseEvent& e)
  36001. {
  36002. if (e.mouseWasClicked() && model != 0)
  36003. model->backgroundClicked();
  36004. }
  36005. void ListBox::setRowHeight (const int newHeight)
  36006. {
  36007. rowHeight = jmax (1, newHeight);
  36008. viewport->setSingleStepSizes (20, rowHeight);
  36009. updateContent();
  36010. }
  36011. int ListBox::getNumRowsOnScreen() const throw()
  36012. {
  36013. return viewport->getMaximumVisibleHeight() / rowHeight;
  36014. }
  36015. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  36016. {
  36017. minimumRowWidth = newMinimumWidth;
  36018. updateContent();
  36019. }
  36020. int ListBox::getVisibleContentWidth() const throw()
  36021. {
  36022. return viewport->getMaximumVisibleWidth();
  36023. }
  36024. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  36025. {
  36026. return viewport->getVerticalScrollBar();
  36027. }
  36028. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  36029. {
  36030. return viewport->getHorizontalScrollBar();
  36031. }
  36032. void ListBox::colourChanged()
  36033. {
  36034. setOpaque (findColour (backgroundColourId).isOpaque());
  36035. viewport->setOpaque (isOpaque());
  36036. repaint();
  36037. }
  36038. void ListBox::setOutlineThickness (const int outlineThickness_)
  36039. {
  36040. outlineThickness = outlineThickness_;
  36041. resized();
  36042. }
  36043. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  36044. {
  36045. if (headerComponent != newHeaderComponent)
  36046. {
  36047. if (headerComponent != 0)
  36048. delete headerComponent;
  36049. headerComponent = newHeaderComponent;
  36050. addAndMakeVisible (newHeaderComponent);
  36051. ListBox::resized();
  36052. }
  36053. }
  36054. void ListBox::repaintRow (const int rowNumber) throw()
  36055. {
  36056. const Rectangle r (getRowPosition (rowNumber, true));
  36057. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  36058. }
  36059. Image* ListBox::createSnapshotOfSelectedRows()
  36060. {
  36061. Image* snapshot = new Image (Image::ARGB, getWidth(), getHeight(), true);
  36062. Graphics g (*snapshot);
  36063. const int firstRow = getRowContainingPosition (0, 0);
  36064. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  36065. {
  36066. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  36067. if (rowComp != 0 && isRowSelected (firstRow + i))
  36068. {
  36069. g.saveState();
  36070. int x = 0, y = 0;
  36071. rowComp->relativePositionToOtherComponent (this, x, y);
  36072. g.setOrigin (x, y);
  36073. g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight());
  36074. rowComp->paintEntireComponent (g);
  36075. g.restoreState();
  36076. }
  36077. }
  36078. return snapshot;
  36079. }
  36080. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  36081. {
  36082. (void) existingComponentToUpdate;
  36083. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  36084. return 0;
  36085. }
  36086. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  36087. {
  36088. }
  36089. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  36090. {
  36091. }
  36092. void ListBoxModel::backgroundClicked()
  36093. {
  36094. }
  36095. void ListBoxModel::selectedRowsChanged (int)
  36096. {
  36097. }
  36098. void ListBoxModel::deleteKeyPressed (int)
  36099. {
  36100. }
  36101. void ListBoxModel::returnKeyPressed (int)
  36102. {
  36103. }
  36104. void ListBoxModel::listWasScrolled()
  36105. {
  36106. }
  36107. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  36108. {
  36109. return String::empty;
  36110. }
  36111. END_JUCE_NAMESPACE
  36112. /********* End of inlined file: juce_ListBox.cpp *********/
  36113. /********* Start of inlined file: juce_ProgressBar.cpp *********/
  36114. BEGIN_JUCE_NAMESPACE
  36115. ProgressBar::ProgressBar (double& progress_)
  36116. : progress (progress_),
  36117. displayPercentage (true),
  36118. lastCallbackTime (0)
  36119. {
  36120. currentValue = jlimit (0.0, 1.0, progress);
  36121. }
  36122. ProgressBar::~ProgressBar()
  36123. {
  36124. }
  36125. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  36126. {
  36127. displayPercentage = shouldDisplayPercentage;
  36128. repaint();
  36129. }
  36130. void ProgressBar::setTextToDisplay (const String& text)
  36131. {
  36132. displayPercentage = false;
  36133. displayedMessage = text;
  36134. }
  36135. void ProgressBar::lookAndFeelChanged()
  36136. {
  36137. setOpaque (findColour (backgroundColourId).isOpaque());
  36138. }
  36139. void ProgressBar::colourChanged()
  36140. {
  36141. lookAndFeelChanged();
  36142. }
  36143. void ProgressBar::paint (Graphics& g)
  36144. {
  36145. String text;
  36146. if (displayPercentage)
  36147. {
  36148. if (currentValue >= 0 && currentValue <= 1.0)
  36149. text << roundDoubleToInt (currentValue * 100.0) << T("%");
  36150. }
  36151. else
  36152. {
  36153. text = displayedMessage;
  36154. }
  36155. getLookAndFeel().drawProgressBar (g, *this,
  36156. getWidth(), getHeight(),
  36157. currentValue, text);
  36158. }
  36159. void ProgressBar::visibilityChanged()
  36160. {
  36161. if (isVisible())
  36162. startTimer (30);
  36163. else
  36164. stopTimer();
  36165. }
  36166. void ProgressBar::timerCallback()
  36167. {
  36168. double newProgress = progress;
  36169. if (currentValue != newProgress
  36170. || newProgress < 0 || newProgress >= 1.0
  36171. || currentMessage != displayedMessage)
  36172. {
  36173. if (currentValue < newProgress
  36174. && newProgress >= 0 && newProgress < 1.0
  36175. && currentValue >= 0 && currentValue < 1.0)
  36176. {
  36177. const uint32 now = Time::getMillisecondCounter();
  36178. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  36179. lastCallbackTime = now;
  36180. newProgress = jmin (currentValue + 0.00018 * timeSinceLastCallback,
  36181. newProgress);
  36182. }
  36183. currentValue = newProgress;
  36184. currentMessage = displayedMessage;
  36185. repaint();
  36186. }
  36187. }
  36188. END_JUCE_NAMESPACE
  36189. /********* End of inlined file: juce_ProgressBar.cpp *********/
  36190. /********* Start of inlined file: juce_Slider.cpp *********/
  36191. BEGIN_JUCE_NAMESPACE
  36192. class SliderPopupDisplayComponent : public BubbleComponent
  36193. {
  36194. public:
  36195. SliderPopupDisplayComponent (Slider* const owner_)
  36196. : owner (owner_),
  36197. font (15.0f, Font::bold)
  36198. {
  36199. setAlwaysOnTop (true);
  36200. }
  36201. ~SliderPopupDisplayComponent()
  36202. {
  36203. }
  36204. void paintContent (Graphics& g, int w, int h)
  36205. {
  36206. g.setFont (font);
  36207. g.setColour (Colours::black);
  36208. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  36209. }
  36210. void getContentSize (int& w, int& h)
  36211. {
  36212. w = font.getStringWidth (text) + 18;
  36213. h = (int) (font.getHeight() * 1.6f);
  36214. }
  36215. void updatePosition (const String& newText)
  36216. {
  36217. if (text != newText)
  36218. {
  36219. text = newText;
  36220. repaint();
  36221. }
  36222. BubbleComponent::setPosition (owner);
  36223. }
  36224. juce_UseDebuggingNewOperator
  36225. private:
  36226. Slider* owner;
  36227. Font font;
  36228. String text;
  36229. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  36230. const SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  36231. };
  36232. Slider::Slider (const String& name)
  36233. : Component (name),
  36234. listeners (2),
  36235. currentValue (0.0),
  36236. valueMin (0.0),
  36237. valueMax (0.0),
  36238. minimum (0),
  36239. maximum (10),
  36240. interval (0),
  36241. skewFactor (1.0),
  36242. velocityModeSensitivity (1.0),
  36243. velocityModeOffset (0.0),
  36244. velocityModeThreshold (1),
  36245. rotaryStart (float_Pi * 1.2f),
  36246. rotaryEnd (float_Pi * 2.8f),
  36247. numDecimalPlaces (7),
  36248. sliderRegionStart (0),
  36249. sliderRegionSize (1),
  36250. sliderBeingDragged (-1),
  36251. pixelsForFullDragExtent (250),
  36252. style (LinearHorizontal),
  36253. textBoxPos (TextBoxLeft),
  36254. textBoxWidth (80),
  36255. textBoxHeight (20),
  36256. incDecButtonMode (incDecButtonsNotDraggable),
  36257. editableText (true),
  36258. doubleClickToValue (false),
  36259. isVelocityBased (false),
  36260. userKeyOverridesVelocity (true),
  36261. rotaryStop (true),
  36262. incDecButtonsSideBySide (false),
  36263. sendChangeOnlyOnRelease (false),
  36264. popupDisplayEnabled (false),
  36265. menuEnabled (false),
  36266. menuShown (false),
  36267. scrollWheelEnabled (true),
  36268. snapsToMousePos (true),
  36269. valueBox (0),
  36270. incButton (0),
  36271. decButton (0),
  36272. popupDisplay (0),
  36273. parentForPopupDisplay (0)
  36274. {
  36275. setWantsKeyboardFocus (false);
  36276. setRepaintsOnMouseActivity (true);
  36277. lookAndFeelChanged();
  36278. updateText();
  36279. }
  36280. Slider::~Slider()
  36281. {
  36282. deleteAndZero (popupDisplay);
  36283. deleteAllChildren();
  36284. }
  36285. void Slider::handleAsyncUpdate()
  36286. {
  36287. cancelPendingUpdate();
  36288. for (int i = listeners.size(); --i >= 0;)
  36289. {
  36290. ((SliderListener*) listeners.getUnchecked (i))->sliderValueChanged (this);
  36291. i = jmin (i, listeners.size());
  36292. }
  36293. }
  36294. void Slider::sendDragStart()
  36295. {
  36296. startedDragging();
  36297. for (int i = listeners.size(); --i >= 0;)
  36298. {
  36299. ((SliderListener*) listeners.getUnchecked (i))->sliderDragStarted (this);
  36300. i = jmin (i, listeners.size());
  36301. }
  36302. }
  36303. void Slider::sendDragEnd()
  36304. {
  36305. stoppedDragging();
  36306. sliderBeingDragged = -1;
  36307. for (int i = listeners.size(); --i >= 0;)
  36308. {
  36309. ((SliderListener*) listeners.getUnchecked (i))->sliderDragEnded (this);
  36310. i = jmin (i, listeners.size());
  36311. }
  36312. }
  36313. void Slider::addListener (SliderListener* const listener) throw()
  36314. {
  36315. jassert (listener != 0);
  36316. if (listener != 0)
  36317. listeners.add (listener);
  36318. }
  36319. void Slider::removeListener (SliderListener* const listener) throw()
  36320. {
  36321. listeners.removeValue (listener);
  36322. }
  36323. void Slider::setSliderStyle (const SliderStyle newStyle)
  36324. {
  36325. if (style != newStyle)
  36326. {
  36327. style = newStyle;
  36328. repaint();
  36329. lookAndFeelChanged();
  36330. }
  36331. }
  36332. void Slider::setRotaryParameters (const float startAngleRadians,
  36333. const float endAngleRadians,
  36334. const bool stopAtEnd)
  36335. {
  36336. // make sure the values are sensible..
  36337. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  36338. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  36339. jassert (rotaryStart < rotaryEnd);
  36340. rotaryStart = startAngleRadians;
  36341. rotaryEnd = endAngleRadians;
  36342. rotaryStop = stopAtEnd;
  36343. }
  36344. void Slider::setVelocityBasedMode (const bool velBased) throw()
  36345. {
  36346. isVelocityBased = velBased;
  36347. }
  36348. void Slider::setVelocityModeParameters (const double sensitivity,
  36349. const int threshold,
  36350. const double offset,
  36351. const bool userCanPressKeyToSwapMode) throw()
  36352. {
  36353. jassert (threshold >= 0);
  36354. jassert (sensitivity > 0);
  36355. jassert (offset >= 0);
  36356. velocityModeSensitivity = sensitivity;
  36357. velocityModeOffset = offset;
  36358. velocityModeThreshold = threshold;
  36359. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  36360. }
  36361. void Slider::setSkewFactor (const double factor) throw()
  36362. {
  36363. skewFactor = factor;
  36364. }
  36365. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw()
  36366. {
  36367. if (maximum > minimum)
  36368. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  36369. / (maximum - minimum));
  36370. }
  36371. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  36372. {
  36373. jassert (distanceForFullScaleDrag > 0);
  36374. pixelsForFullDragExtent = distanceForFullScaleDrag;
  36375. }
  36376. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  36377. {
  36378. if (incDecButtonMode != mode)
  36379. {
  36380. incDecButtonMode = mode;
  36381. lookAndFeelChanged();
  36382. }
  36383. }
  36384. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  36385. const bool isReadOnly,
  36386. const int textEntryBoxWidth,
  36387. const int textEntryBoxHeight)
  36388. {
  36389. textBoxPos = newPosition;
  36390. editableText = ! isReadOnly;
  36391. textBoxWidth = textEntryBoxWidth;
  36392. textBoxHeight = textEntryBoxHeight;
  36393. repaint();
  36394. lookAndFeelChanged();
  36395. }
  36396. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) throw()
  36397. {
  36398. editableText = shouldBeEditable;
  36399. if (valueBox != 0)
  36400. valueBox->setEditable (shouldBeEditable && isEnabled());
  36401. }
  36402. void Slider::showTextBox()
  36403. {
  36404. jassert (editableText); // this should probably be avoided in read-only sliders.
  36405. if (valueBox != 0)
  36406. valueBox->showEditor();
  36407. }
  36408. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  36409. {
  36410. if (valueBox != 0)
  36411. {
  36412. valueBox->hideEditor (discardCurrentEditorContents);
  36413. if (discardCurrentEditorContents)
  36414. updateText();
  36415. }
  36416. }
  36417. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw()
  36418. {
  36419. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  36420. }
  36421. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw()
  36422. {
  36423. snapsToMousePos = shouldSnapToMouse;
  36424. }
  36425. void Slider::setPopupDisplayEnabled (const bool enabled,
  36426. Component* const parentComponentToUse) throw()
  36427. {
  36428. popupDisplayEnabled = enabled;
  36429. parentForPopupDisplay = parentComponentToUse;
  36430. }
  36431. void Slider::colourChanged()
  36432. {
  36433. lookAndFeelChanged();
  36434. }
  36435. void Slider::lookAndFeelChanged()
  36436. {
  36437. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  36438. : getTextFromValue (currentValue));
  36439. deleteAllChildren();
  36440. valueBox = 0;
  36441. LookAndFeel& lf = getLookAndFeel();
  36442. if (textBoxPos != NoTextBox)
  36443. {
  36444. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  36445. valueBox->setWantsKeyboardFocus (false);
  36446. valueBox->setText (previousTextBoxContent, false);
  36447. valueBox->setEditable (editableText && isEnabled());
  36448. valueBox->addListener (this);
  36449. if (style == LinearBar)
  36450. valueBox->addMouseListener (this, false);
  36451. valueBox->setTooltip (getTooltip());
  36452. }
  36453. if (style == IncDecButtons)
  36454. {
  36455. addAndMakeVisible (incButton = lf.createSliderButton (true));
  36456. incButton->addButtonListener (this);
  36457. addAndMakeVisible (decButton = lf.createSliderButton (false));
  36458. decButton->addButtonListener (this);
  36459. if (incDecButtonMode != incDecButtonsNotDraggable)
  36460. {
  36461. incButton->addMouseListener (this, false);
  36462. decButton->addMouseListener (this, false);
  36463. }
  36464. else
  36465. {
  36466. incButton->setRepeatSpeed (300, 100, 20);
  36467. incButton->addMouseListener (decButton, false);
  36468. decButton->setRepeatSpeed (300, 100, 20);
  36469. decButton->addMouseListener (incButton, false);
  36470. }
  36471. incButton->setTooltip (getTooltip());
  36472. decButton->setTooltip (getTooltip());
  36473. }
  36474. setComponentEffect (lf.getSliderEffect());
  36475. resized();
  36476. repaint();
  36477. }
  36478. void Slider::setRange (const double newMin,
  36479. const double newMax,
  36480. const double newInt)
  36481. {
  36482. if (minimum != newMin
  36483. || maximum != newMax
  36484. || interval != newInt)
  36485. {
  36486. minimum = newMin;
  36487. maximum = newMax;
  36488. interval = newInt;
  36489. // figure out the number of DPs needed to display all values at this
  36490. // interval setting.
  36491. numDecimalPlaces = 7;
  36492. if (newInt != 0)
  36493. {
  36494. int v = abs ((int) (newInt * 10000000));
  36495. while ((v % 10) == 0)
  36496. {
  36497. --numDecimalPlaces;
  36498. v /= 10;
  36499. }
  36500. }
  36501. // keep the current values inside the new range..
  36502. if (style != TwoValueHorizontal && style != TwoValueVertical)
  36503. {
  36504. setValue (currentValue, false, false);
  36505. }
  36506. else
  36507. {
  36508. setMinValue (getMinValue(), false, false);
  36509. setMaxValue (getMaxValue(), false, false);
  36510. }
  36511. updateText();
  36512. }
  36513. }
  36514. void Slider::triggerChangeMessage (const bool synchronous)
  36515. {
  36516. if (synchronous)
  36517. handleAsyncUpdate();
  36518. else
  36519. triggerAsyncUpdate();
  36520. valueChanged();
  36521. }
  36522. double Slider::getValue() const throw()
  36523. {
  36524. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  36525. // methods to get the two values.
  36526. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  36527. return currentValue;
  36528. }
  36529. void Slider::setValue (double newValue,
  36530. const bool sendUpdateMessage,
  36531. const bool sendMessageSynchronously)
  36532. {
  36533. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  36534. // methods to set the two values.
  36535. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  36536. newValue = constrainedValue (newValue);
  36537. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  36538. {
  36539. jassert (valueMin <= valueMax);
  36540. newValue = jlimit (valueMin, valueMax, newValue);
  36541. }
  36542. if (currentValue != newValue)
  36543. {
  36544. if (valueBox != 0)
  36545. valueBox->hideEditor (true);
  36546. currentValue = newValue;
  36547. updateText();
  36548. repaint();
  36549. if (popupDisplay != 0)
  36550. {
  36551. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (currentValue));
  36552. popupDisplay->repaint();
  36553. }
  36554. if (sendUpdateMessage)
  36555. triggerChangeMessage (sendMessageSynchronously);
  36556. }
  36557. }
  36558. double Slider::getMinValue() const throw()
  36559. {
  36560. // The minimum value only applies to sliders that are in two- or three-value mode.
  36561. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36562. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36563. return valueMin;
  36564. }
  36565. double Slider::getMaxValue() const throw()
  36566. {
  36567. // The maximum value only applies to sliders that are in two- or three-value mode.
  36568. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36569. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36570. return valueMax;
  36571. }
  36572. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  36573. {
  36574. // The minimum value only applies to sliders that are in two- or three-value mode.
  36575. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36576. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36577. newValue = constrainedValue (newValue);
  36578. if (style == TwoValueHorizontal || style == TwoValueVertical)
  36579. {
  36580. if (allowNudgingOfOtherValues && newValue > valueMax)
  36581. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36582. newValue = jmin (valueMax, newValue);
  36583. }
  36584. else
  36585. {
  36586. if (allowNudgingOfOtherValues && newValue > currentValue)
  36587. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36588. newValue = jmin (currentValue, newValue);
  36589. }
  36590. if (valueMin != newValue)
  36591. {
  36592. valueMin = newValue;
  36593. repaint();
  36594. if (popupDisplay != 0)
  36595. {
  36596. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMin));
  36597. popupDisplay->repaint();
  36598. }
  36599. if (sendUpdateMessage)
  36600. triggerChangeMessage (sendMessageSynchronously);
  36601. }
  36602. }
  36603. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  36604. {
  36605. // The maximum value only applies to sliders that are in two- or three-value mode.
  36606. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36607. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36608. newValue = constrainedValue (newValue);
  36609. if (style == TwoValueHorizontal || style == TwoValueVertical)
  36610. {
  36611. if (allowNudgingOfOtherValues && newValue < valueMin)
  36612. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36613. newValue = jmax (valueMin, newValue);
  36614. }
  36615. else
  36616. {
  36617. if (allowNudgingOfOtherValues && newValue < currentValue)
  36618. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36619. newValue = jmax (currentValue, newValue);
  36620. }
  36621. if (valueMax != newValue)
  36622. {
  36623. valueMax = newValue;
  36624. repaint();
  36625. if (popupDisplay != 0)
  36626. {
  36627. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMax));
  36628. popupDisplay->repaint();
  36629. }
  36630. if (sendUpdateMessage)
  36631. triggerChangeMessage (sendMessageSynchronously);
  36632. }
  36633. }
  36634. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  36635. const double valueToSetOnDoubleClick) throw()
  36636. {
  36637. doubleClickToValue = isDoubleClickEnabled;
  36638. doubleClickReturnValue = valueToSetOnDoubleClick;
  36639. }
  36640. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const throw()
  36641. {
  36642. isEnabled_ = doubleClickToValue;
  36643. return doubleClickReturnValue;
  36644. }
  36645. void Slider::updateText()
  36646. {
  36647. if (valueBox != 0)
  36648. valueBox->setText (getTextFromValue (currentValue), false);
  36649. }
  36650. void Slider::setTextValueSuffix (const String& suffix)
  36651. {
  36652. if (textSuffix != suffix)
  36653. {
  36654. textSuffix = suffix;
  36655. updateText();
  36656. }
  36657. }
  36658. const String Slider::getTextFromValue (double v)
  36659. {
  36660. if (numDecimalPlaces > 0)
  36661. return String (v, numDecimalPlaces) + textSuffix;
  36662. else
  36663. return String (roundDoubleToInt (v)) + textSuffix;
  36664. }
  36665. double Slider::getValueFromText (const String& text)
  36666. {
  36667. String t (text.trimStart());
  36668. if (t.endsWith (textSuffix))
  36669. t = t.substring (0, t.length() - textSuffix.length());
  36670. while (t.startsWithChar (T('+')))
  36671. t = t.substring (1).trimStart();
  36672. return t.initialSectionContainingOnly (T("0123456789.,-"))
  36673. .getDoubleValue();
  36674. }
  36675. double Slider::proportionOfLengthToValue (double proportion)
  36676. {
  36677. if (skewFactor != 1.0 && proportion > 0.0)
  36678. proportion = exp (log (proportion) / skewFactor);
  36679. return minimum + (maximum - minimum) * proportion;
  36680. }
  36681. double Slider::valueToProportionOfLength (double value)
  36682. {
  36683. const double n = (value - minimum) / (maximum - minimum);
  36684. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  36685. }
  36686. double Slider::snapValue (double attemptedValue, const bool)
  36687. {
  36688. return attemptedValue;
  36689. }
  36690. void Slider::startedDragging()
  36691. {
  36692. }
  36693. void Slider::stoppedDragging()
  36694. {
  36695. }
  36696. void Slider::valueChanged()
  36697. {
  36698. }
  36699. void Slider::enablementChanged()
  36700. {
  36701. repaint();
  36702. }
  36703. void Slider::setPopupMenuEnabled (const bool menuEnabled_) throw()
  36704. {
  36705. menuEnabled = menuEnabled_;
  36706. }
  36707. void Slider::setScrollWheelEnabled (const bool enabled) throw()
  36708. {
  36709. scrollWheelEnabled = enabled;
  36710. }
  36711. void Slider::labelTextChanged (Label* label)
  36712. {
  36713. const double newValue = snapValue (getValueFromText (label->getText()), false);
  36714. if (getValue() != newValue)
  36715. {
  36716. sendDragStart();
  36717. setValue (newValue, true, true);
  36718. sendDragEnd();
  36719. }
  36720. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  36721. }
  36722. void Slider::buttonClicked (Button* button)
  36723. {
  36724. if (style == IncDecButtons)
  36725. {
  36726. sendDragStart();
  36727. if (button == incButton)
  36728. setValue (snapValue (getValue() + interval, false), true, true);
  36729. else if (button == decButton)
  36730. setValue (snapValue (getValue() - interval, false), true, true);
  36731. sendDragEnd();
  36732. }
  36733. }
  36734. double Slider::constrainedValue (double value) const throw()
  36735. {
  36736. if (interval > 0)
  36737. value = minimum + interval * floor ((value - minimum) / interval + 0.5);
  36738. if (value <= minimum || maximum <= minimum)
  36739. value = minimum;
  36740. else if (value >= maximum)
  36741. value = maximum;
  36742. return value;
  36743. }
  36744. float Slider::getLinearSliderPos (const double value)
  36745. {
  36746. double sliderPosProportional;
  36747. if (maximum > minimum)
  36748. {
  36749. if (value < minimum)
  36750. {
  36751. sliderPosProportional = 0.0;
  36752. }
  36753. else if (value > maximum)
  36754. {
  36755. sliderPosProportional = 1.0;
  36756. }
  36757. else
  36758. {
  36759. sliderPosProportional = valueToProportionOfLength (value);
  36760. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  36761. }
  36762. }
  36763. else
  36764. {
  36765. sliderPosProportional = 0.5;
  36766. }
  36767. if (isVertical() || style == IncDecButtons)
  36768. sliderPosProportional = 1.0 - sliderPosProportional;
  36769. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  36770. }
  36771. bool Slider::isHorizontal() const throw()
  36772. {
  36773. return style == LinearHorizontal
  36774. || style == LinearBar
  36775. || style == TwoValueHorizontal
  36776. || style == ThreeValueHorizontal;
  36777. }
  36778. bool Slider::isVertical() const throw()
  36779. {
  36780. return style == LinearVertical
  36781. || style == TwoValueVertical
  36782. || style == ThreeValueVertical;
  36783. }
  36784. bool Slider::incDecDragDirectionIsHorizontal() const throw()
  36785. {
  36786. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  36787. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  36788. }
  36789. float Slider::getPositionOfValue (const double value)
  36790. {
  36791. if (isHorizontal() || isVertical())
  36792. {
  36793. return getLinearSliderPos (value);
  36794. }
  36795. else
  36796. {
  36797. jassertfalse // not a valid call on a slider that doesn't work linearly!
  36798. return 0.0f;
  36799. }
  36800. }
  36801. void Slider::paint (Graphics& g)
  36802. {
  36803. if (style != IncDecButtons)
  36804. {
  36805. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  36806. {
  36807. const float sliderPos = (float) valueToProportionOfLength (currentValue);
  36808. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  36809. getLookAndFeel().drawRotarySlider (g,
  36810. sliderRect.getX(),
  36811. sliderRect.getY(),
  36812. sliderRect.getWidth(),
  36813. sliderRect.getHeight(),
  36814. sliderPos,
  36815. rotaryStart, rotaryEnd,
  36816. *this);
  36817. }
  36818. else
  36819. {
  36820. getLookAndFeel().drawLinearSlider (g,
  36821. sliderRect.getX(),
  36822. sliderRect.getY(),
  36823. sliderRect.getWidth(),
  36824. sliderRect.getHeight(),
  36825. getLinearSliderPos (currentValue),
  36826. getLinearSliderPos (valueMin),
  36827. getLinearSliderPos (valueMax),
  36828. style,
  36829. *this);
  36830. }
  36831. if (style == LinearBar && valueBox == 0)
  36832. {
  36833. g.setColour (findColour (Slider::textBoxOutlineColourId));
  36834. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  36835. }
  36836. }
  36837. }
  36838. void Slider::resized()
  36839. {
  36840. int minXSpace = 0;
  36841. int minYSpace = 0;
  36842. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  36843. minXSpace = 30;
  36844. else
  36845. minYSpace = 15;
  36846. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  36847. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  36848. if (style == LinearBar)
  36849. {
  36850. if (valueBox != 0)
  36851. valueBox->setBounds (0, 0, getWidth(), getHeight());
  36852. }
  36853. else
  36854. {
  36855. if (textBoxPos == NoTextBox)
  36856. {
  36857. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  36858. }
  36859. else if (textBoxPos == TextBoxLeft)
  36860. {
  36861. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  36862. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  36863. }
  36864. else if (textBoxPos == TextBoxRight)
  36865. {
  36866. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  36867. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  36868. }
  36869. else if (textBoxPos == TextBoxAbove)
  36870. {
  36871. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  36872. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  36873. }
  36874. else if (textBoxPos == TextBoxBelow)
  36875. {
  36876. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  36877. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  36878. }
  36879. }
  36880. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  36881. if (style == LinearBar)
  36882. {
  36883. const int barIndent = 1;
  36884. sliderRegionStart = barIndent;
  36885. sliderRegionSize = getWidth() - barIndent * 2;
  36886. sliderRect.setBounds (sliderRegionStart, barIndent,
  36887. sliderRegionSize, getHeight() - barIndent * 2);
  36888. }
  36889. else if (isHorizontal())
  36890. {
  36891. sliderRegionStart = sliderRect.getX() + indent;
  36892. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  36893. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  36894. sliderRegionSize, sliderRect.getHeight());
  36895. }
  36896. else if (isVertical())
  36897. {
  36898. sliderRegionStart = sliderRect.getY() + indent;
  36899. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  36900. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  36901. sliderRect.getWidth(), sliderRegionSize);
  36902. }
  36903. else
  36904. {
  36905. sliderRegionStart = 0;
  36906. sliderRegionSize = 100;
  36907. }
  36908. if (style == IncDecButtons)
  36909. {
  36910. Rectangle buttonRect (sliderRect);
  36911. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  36912. buttonRect.expand (-2, 0);
  36913. else
  36914. buttonRect.expand (0, -2);
  36915. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  36916. if (incDecButtonsSideBySide)
  36917. {
  36918. decButton->setBounds (buttonRect.getX(),
  36919. buttonRect.getY(),
  36920. buttonRect.getWidth() / 2,
  36921. buttonRect.getHeight());
  36922. decButton->setConnectedEdges (Button::ConnectedOnRight);
  36923. incButton->setBounds (buttonRect.getCentreX(),
  36924. buttonRect.getY(),
  36925. buttonRect.getWidth() / 2,
  36926. buttonRect.getHeight());
  36927. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  36928. }
  36929. else
  36930. {
  36931. incButton->setBounds (buttonRect.getX(),
  36932. buttonRect.getY(),
  36933. buttonRect.getWidth(),
  36934. buttonRect.getHeight() / 2);
  36935. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  36936. decButton->setBounds (buttonRect.getX(),
  36937. buttonRect.getCentreY(),
  36938. buttonRect.getWidth(),
  36939. buttonRect.getHeight() / 2);
  36940. decButton->setConnectedEdges (Button::ConnectedOnTop);
  36941. }
  36942. }
  36943. }
  36944. void Slider::focusOfChildComponentChanged (FocusChangeType)
  36945. {
  36946. repaint();
  36947. }
  36948. void Slider::mouseDown (const MouseEvent& e)
  36949. {
  36950. mouseWasHidden = false;
  36951. incDecDragged = false;
  36952. mouseXWhenLastDragged = e.x;
  36953. mouseYWhenLastDragged = e.y;
  36954. mouseDragStartX = e.getMouseDownX();
  36955. mouseDragStartY = e.getMouseDownY();
  36956. if (isEnabled())
  36957. {
  36958. if (e.mods.isPopupMenu() && menuEnabled)
  36959. {
  36960. menuShown = true;
  36961. PopupMenu m;
  36962. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  36963. m.addSeparator();
  36964. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  36965. {
  36966. PopupMenu rotaryMenu;
  36967. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  36968. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  36969. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  36970. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  36971. }
  36972. const int r = m.show();
  36973. if (r == 1)
  36974. {
  36975. setVelocityBasedMode (! isVelocityBased);
  36976. }
  36977. else if (r == 2)
  36978. {
  36979. setSliderStyle (Rotary);
  36980. }
  36981. else if (r == 3)
  36982. {
  36983. setSliderStyle (RotaryHorizontalDrag);
  36984. }
  36985. else if (r == 4)
  36986. {
  36987. setSliderStyle (RotaryVerticalDrag);
  36988. }
  36989. }
  36990. else if (maximum > minimum)
  36991. {
  36992. menuShown = false;
  36993. if (valueBox != 0)
  36994. valueBox->hideEditor (true);
  36995. sliderBeingDragged = 0;
  36996. if (style == TwoValueHorizontal
  36997. || style == TwoValueVertical
  36998. || style == ThreeValueHorizontal
  36999. || style == ThreeValueVertical)
  37000. {
  37001. const float mousePos = (float) (isVertical() ? e.y : e.x);
  37002. const float normalPosDistance = fabsf (getLinearSliderPos (currentValue) - mousePos);
  37003. const float minPosDistance = fabsf (getLinearSliderPos (valueMin) - 0.1f - mousePos);
  37004. const float maxPosDistance = fabsf (getLinearSliderPos (valueMax) + 0.1f - mousePos);
  37005. if (style == TwoValueHorizontal || style == TwoValueVertical)
  37006. {
  37007. if (maxPosDistance <= minPosDistance)
  37008. sliderBeingDragged = 2;
  37009. else
  37010. sliderBeingDragged = 1;
  37011. }
  37012. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  37013. {
  37014. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  37015. sliderBeingDragged = 1;
  37016. else if (normalPosDistance >= maxPosDistance)
  37017. sliderBeingDragged = 2;
  37018. }
  37019. }
  37020. minMaxDiff = valueMax - valueMin;
  37021. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  37022. * valueToProportionOfLength (currentValue);
  37023. if (sliderBeingDragged == 2)
  37024. valueWhenLastDragged = valueMax;
  37025. else if (sliderBeingDragged == 1)
  37026. valueWhenLastDragged = valueMin;
  37027. else
  37028. valueWhenLastDragged = currentValue;
  37029. valueOnMouseDown = valueWhenLastDragged;
  37030. if (popupDisplayEnabled)
  37031. {
  37032. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  37033. popupDisplay = popup;
  37034. if (parentForPopupDisplay != 0)
  37035. {
  37036. parentForPopupDisplay->addChildComponent (popup);
  37037. }
  37038. else
  37039. {
  37040. popup->addToDesktop (0);
  37041. }
  37042. popup->setVisible (true);
  37043. }
  37044. sendDragStart();
  37045. mouseDrag (e);
  37046. }
  37047. }
  37048. }
  37049. void Slider::mouseUp (const MouseEvent&)
  37050. {
  37051. if (isEnabled()
  37052. && (! menuShown)
  37053. && (maximum > minimum)
  37054. && (style != IncDecButtons || incDecDragged))
  37055. {
  37056. restoreMouseIfHidden();
  37057. if (sendChangeOnlyOnRelease && valueOnMouseDown != currentValue)
  37058. triggerChangeMessage (false);
  37059. sendDragEnd();
  37060. deleteAndZero (popupDisplay);
  37061. if (style == IncDecButtons)
  37062. {
  37063. incButton->setState (Button::buttonNormal);
  37064. decButton->setState (Button::buttonNormal);
  37065. }
  37066. }
  37067. }
  37068. void Slider::restoreMouseIfHidden()
  37069. {
  37070. if (mouseWasHidden)
  37071. {
  37072. mouseWasHidden = false;
  37073. Component* c = Component::getComponentUnderMouse();
  37074. if (c == 0)
  37075. c = this;
  37076. c->enableUnboundedMouseMovement (false);
  37077. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  37078. : ((sliderBeingDragged == 1) ? getMinValue()
  37079. : currentValue);
  37080. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  37081. {
  37082. int x, y, downX, downY;
  37083. Desktop::getMousePosition (x, y);
  37084. Desktop::getLastMouseDownPosition (downX, downY);
  37085. if (style == RotaryHorizontalDrag)
  37086. {
  37087. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  37088. x = roundDoubleToInt (pixelsForFullDragExtent * posDiff + downX);
  37089. y = downY;
  37090. }
  37091. else
  37092. {
  37093. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  37094. x = downX;
  37095. y = roundDoubleToInt (pixelsForFullDragExtent * posDiff + downY);
  37096. }
  37097. Desktop::setMousePosition (x, y);
  37098. }
  37099. else
  37100. {
  37101. const int pixelPos = (int) getLinearSliderPos (pos);
  37102. int x = isHorizontal() ? pixelPos : (getWidth() / 2);
  37103. int y = isVertical() ? pixelPos : (getHeight() / 2);
  37104. relativePositionToGlobal (x, y);
  37105. Desktop::setMousePosition (x, y);
  37106. }
  37107. }
  37108. }
  37109. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  37110. {
  37111. if (isEnabled()
  37112. && style != IncDecButtons
  37113. && style != Rotary
  37114. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  37115. {
  37116. restoreMouseIfHidden();
  37117. }
  37118. }
  37119. static double smallestAngleBetween (double a1, double a2)
  37120. {
  37121. return jmin (fabs (a1 - a2),
  37122. fabs (a1 + double_Pi * 2.0 - a2),
  37123. fabs (a2 + double_Pi * 2.0 - a1));
  37124. }
  37125. void Slider::mouseDrag (const MouseEvent& e)
  37126. {
  37127. if (isEnabled()
  37128. && (! menuShown)
  37129. && (maximum > minimum))
  37130. {
  37131. if (style == Rotary)
  37132. {
  37133. int dx = e.x - sliderRect.getCentreX();
  37134. int dy = e.y - sliderRect.getCentreY();
  37135. if (dx * dx + dy * dy > 25)
  37136. {
  37137. double angle = atan2 ((double) dx, (double) -dy);
  37138. while (angle < 0.0)
  37139. angle += double_Pi * 2.0;
  37140. if (rotaryStop && ! e.mouseWasClicked())
  37141. {
  37142. if (fabs (angle - lastAngle) > double_Pi)
  37143. {
  37144. if (angle >= lastAngle)
  37145. angle -= double_Pi * 2.0;
  37146. else
  37147. angle += double_Pi * 2.0;
  37148. }
  37149. if (angle >= lastAngle)
  37150. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  37151. else
  37152. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  37153. }
  37154. else
  37155. {
  37156. while (angle < rotaryStart)
  37157. angle += double_Pi * 2.0;
  37158. if (angle > rotaryEnd)
  37159. {
  37160. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  37161. angle = rotaryStart;
  37162. else
  37163. angle = rotaryEnd;
  37164. }
  37165. }
  37166. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  37167. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  37168. lastAngle = angle;
  37169. }
  37170. }
  37171. else
  37172. {
  37173. if (style == LinearBar && e.mouseWasClicked()
  37174. && valueBox != 0 && valueBox->isEditable())
  37175. return;
  37176. if (style == IncDecButtons && ! incDecDragged)
  37177. {
  37178. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  37179. return;
  37180. incDecDragged = true;
  37181. mouseDragStartX = e.x;
  37182. mouseDragStartY = e.y;
  37183. }
  37184. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  37185. : false))
  37186. || ((maximum - minimum) / sliderRegionSize < interval))
  37187. {
  37188. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  37189. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  37190. if (style == RotaryHorizontalDrag
  37191. || style == RotaryVerticalDrag
  37192. || style == IncDecButtons
  37193. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  37194. && ! snapsToMousePos))
  37195. {
  37196. const int mouseDiff = (style == RotaryHorizontalDrag
  37197. || style == LinearHorizontal
  37198. || style == LinearBar
  37199. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  37200. ? e.x - mouseDragStartX
  37201. : mouseDragStartY - e.y;
  37202. double newPos = valueToProportionOfLength (valueOnMouseDown)
  37203. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  37204. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  37205. if (style == IncDecButtons)
  37206. {
  37207. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  37208. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  37209. }
  37210. }
  37211. else
  37212. {
  37213. if (isVertical())
  37214. scaledMousePos = 1.0 - scaledMousePos;
  37215. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  37216. }
  37217. }
  37218. else
  37219. {
  37220. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  37221. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  37222. ? e.x - mouseXWhenLastDragged
  37223. : e.y - mouseYWhenLastDragged;
  37224. const double maxSpeed = jmax (200, sliderRegionSize);
  37225. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  37226. if (speed != 0)
  37227. {
  37228. speed = 0.2 * velocityModeSensitivity
  37229. * (1.0 + sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  37230. + jmax (0.0, (double) (speed - velocityModeThreshold))
  37231. / maxSpeed))));
  37232. if (mouseDiff < 0)
  37233. speed = -speed;
  37234. if (isVertical() || style == RotaryVerticalDrag
  37235. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  37236. speed = -speed;
  37237. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  37238. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  37239. e.originalComponent->enableUnboundedMouseMovement (true, false);
  37240. mouseWasHidden = true;
  37241. }
  37242. }
  37243. }
  37244. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  37245. if (sliderBeingDragged == 0)
  37246. {
  37247. setValue (snapValue (valueWhenLastDragged, true),
  37248. ! sendChangeOnlyOnRelease, true);
  37249. }
  37250. else if (sliderBeingDragged == 1)
  37251. {
  37252. setMinValue (snapValue (valueWhenLastDragged, true),
  37253. ! sendChangeOnlyOnRelease, false, true);
  37254. if (e.mods.isShiftDown())
  37255. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  37256. else
  37257. minMaxDiff = valueMax - valueMin;
  37258. }
  37259. else
  37260. {
  37261. jassert (sliderBeingDragged == 2);
  37262. setMaxValue (snapValue (valueWhenLastDragged, true),
  37263. ! sendChangeOnlyOnRelease, false, true);
  37264. if (e.mods.isShiftDown())
  37265. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  37266. else
  37267. minMaxDiff = valueMax - valueMin;
  37268. }
  37269. mouseXWhenLastDragged = e.x;
  37270. mouseYWhenLastDragged = e.y;
  37271. }
  37272. }
  37273. void Slider::mouseDoubleClick (const MouseEvent&)
  37274. {
  37275. if (doubleClickToValue
  37276. && isEnabled()
  37277. && style != IncDecButtons
  37278. && minimum <= doubleClickReturnValue
  37279. && maximum >= doubleClickReturnValue)
  37280. {
  37281. sendDragStart();
  37282. setValue (doubleClickReturnValue, true, true);
  37283. sendDragEnd();
  37284. }
  37285. }
  37286. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37287. {
  37288. if (scrollWheelEnabled && isEnabled()
  37289. && style != TwoValueHorizontal
  37290. && style != TwoValueVertical)
  37291. {
  37292. if (maximum > minimum && ! isMouseButtonDownAnywhere())
  37293. {
  37294. if (valueBox != 0)
  37295. valueBox->hideEditor (false);
  37296. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  37297. const double currentPos = valueToProportionOfLength (currentValue);
  37298. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  37299. double delta = (newValue != currentValue)
  37300. ? jmax (fabs (newValue - currentValue), interval) : 0;
  37301. if (currentValue > newValue)
  37302. delta = -delta;
  37303. sendDragStart();
  37304. setValue (snapValue (currentValue + delta, false), true, true);
  37305. sendDragEnd();
  37306. }
  37307. }
  37308. else
  37309. {
  37310. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37311. }
  37312. }
  37313. void SliderListener::sliderDragStarted (Slider*)
  37314. {
  37315. }
  37316. void SliderListener::sliderDragEnded (Slider*)
  37317. {
  37318. }
  37319. END_JUCE_NAMESPACE
  37320. /********* End of inlined file: juce_Slider.cpp *********/
  37321. /********* Start of inlined file: juce_TableHeaderComponent.cpp *********/
  37322. BEGIN_JUCE_NAMESPACE
  37323. class DragOverlayComp : public Component
  37324. {
  37325. public:
  37326. DragOverlayComp (Image* const image_)
  37327. : image (image_)
  37328. {
  37329. image->multiplyAllAlphas (0.8f);
  37330. setAlwaysOnTop (true);
  37331. }
  37332. ~DragOverlayComp()
  37333. {
  37334. delete image;
  37335. }
  37336. void paint (Graphics& g)
  37337. {
  37338. g.drawImageAt (image, 0, 0);
  37339. }
  37340. private:
  37341. Image* image;
  37342. DragOverlayComp (const DragOverlayComp&);
  37343. const DragOverlayComp& operator= (const DragOverlayComp&);
  37344. };
  37345. TableHeaderComponent::TableHeaderComponent()
  37346. : listeners (2),
  37347. dragOverlayComp (0),
  37348. columnsChanged (false),
  37349. columnsResized (false),
  37350. sortChanged (false),
  37351. menuActive (true),
  37352. stretchToFit (false),
  37353. columnIdBeingResized (0),
  37354. columnIdBeingDragged (0),
  37355. columnIdUnderMouse (0),
  37356. lastDeliberateWidth (0)
  37357. {
  37358. }
  37359. TableHeaderComponent::~TableHeaderComponent()
  37360. {
  37361. delete dragOverlayComp;
  37362. }
  37363. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  37364. {
  37365. menuActive = hasMenu;
  37366. }
  37367. bool TableHeaderComponent::isPopupMenuActive() const throw() { return menuActive; }
  37368. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const throw()
  37369. {
  37370. if (onlyCountVisibleColumns)
  37371. {
  37372. int num = 0;
  37373. for (int i = columns.size(); --i >= 0;)
  37374. if (columns.getUnchecked(i)->isVisible())
  37375. ++num;
  37376. return num;
  37377. }
  37378. else
  37379. {
  37380. return columns.size();
  37381. }
  37382. }
  37383. const String TableHeaderComponent::getColumnName (const int columnId) const throw()
  37384. {
  37385. const ColumnInfo* const ci = getInfoForId (columnId);
  37386. return ci != 0 ? ci->name : String::empty;
  37387. }
  37388. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  37389. {
  37390. ColumnInfo* const ci = getInfoForId (columnId);
  37391. if (ci != 0 && ci->name != newName)
  37392. {
  37393. ci->name = newName;
  37394. sendColumnsChanged();
  37395. }
  37396. }
  37397. void TableHeaderComponent::addColumn (const String& columnName,
  37398. const int columnId,
  37399. const int width,
  37400. const int minimumWidth,
  37401. const int maximumWidth,
  37402. const int propertyFlags,
  37403. const int insertIndex)
  37404. {
  37405. // can't have a duplicate or null ID!
  37406. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  37407. jassert (width > 0);
  37408. ColumnInfo* const ci = new ColumnInfo();
  37409. ci->name = columnName;
  37410. ci->id = columnId;
  37411. ci->width = width;
  37412. ci->lastDeliberateWidth = width;
  37413. ci->minimumWidth = minimumWidth;
  37414. ci->maximumWidth = maximumWidth;
  37415. if (ci->maximumWidth < 0)
  37416. ci->maximumWidth = INT_MAX;
  37417. jassert (ci->maximumWidth >= ci->minimumWidth);
  37418. ci->propertyFlags = propertyFlags;
  37419. columns.insert (insertIndex, ci);
  37420. sendColumnsChanged();
  37421. }
  37422. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  37423. {
  37424. const int index = getIndexOfColumnId (columnIdToRemove, false);
  37425. if (index >= 0)
  37426. {
  37427. columns.remove (index);
  37428. sortChanged = true;
  37429. sendColumnsChanged();
  37430. }
  37431. }
  37432. void TableHeaderComponent::removeAllColumns()
  37433. {
  37434. if (columns.size() > 0)
  37435. {
  37436. columns.clear();
  37437. sendColumnsChanged();
  37438. }
  37439. }
  37440. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  37441. {
  37442. const int currentIndex = getIndexOfColumnId (columnId, false);
  37443. newIndex = visibleIndexToTotalIndex (newIndex);
  37444. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  37445. {
  37446. columns.move (currentIndex, newIndex);
  37447. sendColumnsChanged();
  37448. }
  37449. }
  37450. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  37451. {
  37452. ColumnInfo* const ci = getInfoForId (columnId);
  37453. if (ci != 0 && ci->width != newWidth)
  37454. {
  37455. const int numColumns = getNumColumns (true);
  37456. ci->lastDeliberateWidth = ci->width
  37457. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  37458. if (stretchToFit)
  37459. {
  37460. const int index = getIndexOfColumnId (columnId, true) + 1;
  37461. if (((unsigned int) index) < (unsigned int) numColumns)
  37462. {
  37463. const int x = getColumnPosition (index).getX();
  37464. if (lastDeliberateWidth == 0)
  37465. lastDeliberateWidth = getTotalWidth();
  37466. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  37467. }
  37468. }
  37469. repaint();
  37470. columnsResized = true;
  37471. triggerAsyncUpdate();
  37472. }
  37473. }
  37474. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw()
  37475. {
  37476. int n = 0;
  37477. for (int i = 0; i < columns.size(); ++i)
  37478. {
  37479. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  37480. {
  37481. if (columns.getUnchecked(i)->id == columnId)
  37482. return n;
  37483. ++n;
  37484. }
  37485. }
  37486. return -1;
  37487. }
  37488. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw()
  37489. {
  37490. if (onlyCountVisibleColumns)
  37491. index = visibleIndexToTotalIndex (index);
  37492. const ColumnInfo* const ci = columns [index];
  37493. return (ci != 0) ? ci->id : 0;
  37494. }
  37495. const Rectangle TableHeaderComponent::getColumnPosition (const int index) const throw()
  37496. {
  37497. int x = 0, width = 0, n = 0;
  37498. for (int i = 0; i < columns.size(); ++i)
  37499. {
  37500. x += width;
  37501. if (columns.getUnchecked(i)->isVisible())
  37502. {
  37503. width = columns.getUnchecked(i)->width;
  37504. if (n++ == index)
  37505. break;
  37506. }
  37507. else
  37508. {
  37509. width = 0;
  37510. }
  37511. }
  37512. return Rectangle (x, 0, width, getHeight());
  37513. }
  37514. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const throw()
  37515. {
  37516. if (xToFind >= 0)
  37517. {
  37518. int x = 0;
  37519. for (int i = 0; i < columns.size(); ++i)
  37520. {
  37521. const ColumnInfo* const ci = columns.getUnchecked(i);
  37522. if (ci->isVisible())
  37523. {
  37524. x += ci->width;
  37525. if (xToFind < x)
  37526. return ci->id;
  37527. }
  37528. }
  37529. }
  37530. return 0;
  37531. }
  37532. int TableHeaderComponent::getTotalWidth() const throw()
  37533. {
  37534. int w = 0;
  37535. for (int i = columns.size(); --i >= 0;)
  37536. if (columns.getUnchecked(i)->isVisible())
  37537. w += columns.getUnchecked(i)->width;
  37538. return w;
  37539. }
  37540. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  37541. {
  37542. stretchToFit = shouldStretchToFit;
  37543. lastDeliberateWidth = getTotalWidth();
  37544. resized();
  37545. }
  37546. bool TableHeaderComponent::isStretchToFitActive() const throw()
  37547. {
  37548. return stretchToFit;
  37549. }
  37550. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  37551. {
  37552. if (stretchToFit && getWidth() > 0
  37553. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  37554. {
  37555. lastDeliberateWidth = targetTotalWidth;
  37556. resizeColumnsToFit (0, targetTotalWidth);
  37557. }
  37558. }
  37559. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  37560. {
  37561. targetTotalWidth = jmax (targetTotalWidth, 0);
  37562. StretchableObjectResizer sor;
  37563. int i;
  37564. for (i = firstColumnIndex; i < columns.size(); ++i)
  37565. {
  37566. ColumnInfo* const ci = columns.getUnchecked(i);
  37567. if (ci->isVisible())
  37568. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  37569. }
  37570. sor.resizeToFit (targetTotalWidth);
  37571. int visIndex = 0;
  37572. for (i = firstColumnIndex; i < columns.size(); ++i)
  37573. {
  37574. ColumnInfo* const ci = columns.getUnchecked(i);
  37575. if (ci->isVisible())
  37576. {
  37577. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  37578. (int) floor (sor.getItemSize (visIndex++)));
  37579. if (newWidth != ci->width)
  37580. {
  37581. ci->width = newWidth;
  37582. repaint();
  37583. columnsResized = true;
  37584. triggerAsyncUpdate();
  37585. }
  37586. }
  37587. }
  37588. }
  37589. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  37590. {
  37591. ColumnInfo* const ci = getInfoForId (columnId);
  37592. if (ci != 0 && shouldBeVisible != ci->isVisible())
  37593. {
  37594. if (shouldBeVisible)
  37595. ci->propertyFlags |= visible;
  37596. else
  37597. ci->propertyFlags &= ~visible;
  37598. sendColumnsChanged();
  37599. resized();
  37600. }
  37601. }
  37602. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  37603. {
  37604. const ColumnInfo* const ci = getInfoForId (columnId);
  37605. return ci != 0 && ci->isVisible();
  37606. }
  37607. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  37608. {
  37609. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  37610. {
  37611. for (int i = columns.size(); --i >= 0;)
  37612. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  37613. ColumnInfo* const ci = getInfoForId (columnId);
  37614. if (ci != 0)
  37615. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  37616. reSortTable();
  37617. }
  37618. }
  37619. int TableHeaderComponent::getSortColumnId() const throw()
  37620. {
  37621. for (int i = columns.size(); --i >= 0;)
  37622. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  37623. return columns.getUnchecked(i)->id;
  37624. return 0;
  37625. }
  37626. bool TableHeaderComponent::isSortedForwards() const throw()
  37627. {
  37628. for (int i = columns.size(); --i >= 0;)
  37629. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  37630. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  37631. return true;
  37632. }
  37633. void TableHeaderComponent::reSortTable()
  37634. {
  37635. sortChanged = true;
  37636. repaint();
  37637. triggerAsyncUpdate();
  37638. }
  37639. const String TableHeaderComponent::toString() const
  37640. {
  37641. String s;
  37642. XmlElement doc (T("TABLELAYOUT"));
  37643. doc.setAttribute (T("sortedCol"), getSortColumnId());
  37644. doc.setAttribute (T("sortForwards"), isSortedForwards());
  37645. for (int i = 0; i < columns.size(); ++i)
  37646. {
  37647. const ColumnInfo* const ci = columns.getUnchecked (i);
  37648. XmlElement* const e = new XmlElement (T("COLUMN"));
  37649. doc.addChildElement (e);
  37650. e->setAttribute (T("id"), ci->id);
  37651. e->setAttribute (T("visible"), ci->isVisible());
  37652. e->setAttribute (T("width"), ci->width);
  37653. }
  37654. return doc.createDocument (String::empty, true, false);
  37655. }
  37656. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  37657. {
  37658. XmlDocument doc (storedVersion);
  37659. XmlElement* const storedXml = doc.getDocumentElement();
  37660. int index = 0;
  37661. if (storedXml != 0 && storedXml->hasTagName (T("TABLELAYOUT")))
  37662. {
  37663. forEachXmlChildElement (*storedXml, col)
  37664. {
  37665. const int tabId = col->getIntAttribute (T("id"));
  37666. ColumnInfo* const ci = getInfoForId (tabId);
  37667. if (ci != 0)
  37668. {
  37669. columns.move (columns.indexOf (ci), index);
  37670. ci->width = col->getIntAttribute (T("width"));
  37671. setColumnVisible (tabId, col->getBoolAttribute (T("visible")));
  37672. }
  37673. ++index;
  37674. }
  37675. columnsResized = true;
  37676. sendColumnsChanged();
  37677. setSortColumnId (storedXml->getIntAttribute (T("sortedCol")),
  37678. storedXml->getBoolAttribute (T("sortForwards"), true));
  37679. }
  37680. delete storedXml;
  37681. }
  37682. void TableHeaderComponent::addListener (TableHeaderListener* const newListener) throw()
  37683. {
  37684. listeners.addIfNotAlreadyThere (newListener);
  37685. }
  37686. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove) throw()
  37687. {
  37688. listeners.removeValue (listenerToRemove);
  37689. }
  37690. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  37691. {
  37692. const ColumnInfo* const ci = getInfoForId (columnId);
  37693. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  37694. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  37695. }
  37696. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  37697. {
  37698. for (int i = 0; i < columns.size(); ++i)
  37699. {
  37700. const ColumnInfo* const ci = columns.getUnchecked(i);
  37701. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  37702. menu.addItem (ci->id, ci->name,
  37703. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  37704. isColumnVisible (ci->id));
  37705. }
  37706. }
  37707. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  37708. {
  37709. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  37710. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  37711. }
  37712. void TableHeaderComponent::paint (Graphics& g)
  37713. {
  37714. LookAndFeel& lf = getLookAndFeel();
  37715. lf.drawTableHeaderBackground (g, *this);
  37716. const Rectangle clip (g.getClipBounds());
  37717. int x = 0;
  37718. for (int i = 0; i < columns.size(); ++i)
  37719. {
  37720. const ColumnInfo* const ci = columns.getUnchecked(i);
  37721. if (ci->isVisible())
  37722. {
  37723. if (x + ci->width > clip.getX()
  37724. && (ci->id != columnIdBeingDragged
  37725. || dragOverlayComp == 0
  37726. || ! dragOverlayComp->isVisible()))
  37727. {
  37728. g.saveState();
  37729. g.setOrigin (x, 0);
  37730. g.reduceClipRegion (0, 0, ci->width, getHeight());
  37731. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  37732. ci->id == columnIdUnderMouse,
  37733. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  37734. ci->propertyFlags);
  37735. g.restoreState();
  37736. }
  37737. x += ci->width;
  37738. if (x >= clip.getRight())
  37739. break;
  37740. }
  37741. }
  37742. }
  37743. void TableHeaderComponent::resized()
  37744. {
  37745. }
  37746. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  37747. {
  37748. updateColumnUnderMouse (e.x, e.y);
  37749. }
  37750. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  37751. {
  37752. updateColumnUnderMouse (e.x, e.y);
  37753. }
  37754. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  37755. {
  37756. updateColumnUnderMouse (e.x, e.y);
  37757. }
  37758. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  37759. {
  37760. repaint();
  37761. columnIdBeingResized = 0;
  37762. columnIdBeingDragged = 0;
  37763. if (columnIdUnderMouse != 0)
  37764. {
  37765. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  37766. if (e.mods.isPopupMenu())
  37767. columnClicked (columnIdUnderMouse, e.mods);
  37768. }
  37769. if (menuActive && e.mods.isPopupMenu())
  37770. showColumnChooserMenu (columnIdUnderMouse);
  37771. }
  37772. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  37773. {
  37774. if (columnIdBeingResized == 0
  37775. && columnIdBeingDragged == 0
  37776. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  37777. {
  37778. deleteAndZero (dragOverlayComp);
  37779. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  37780. if (columnIdBeingResized != 0)
  37781. {
  37782. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  37783. initialColumnWidth = ci->width;
  37784. }
  37785. else
  37786. {
  37787. beginDrag (e);
  37788. }
  37789. }
  37790. if (columnIdBeingResized != 0)
  37791. {
  37792. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  37793. if (ci != 0)
  37794. {
  37795. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  37796. initialColumnWidth + e.getDistanceFromDragStartX());
  37797. if (stretchToFit)
  37798. {
  37799. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  37800. int minWidthOnRight = 0;
  37801. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  37802. if (columns.getUnchecked (i)->isVisible())
  37803. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  37804. const Rectangle currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  37805. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  37806. }
  37807. setColumnWidth (columnIdBeingResized, w);
  37808. }
  37809. }
  37810. else if (columnIdBeingDragged != 0)
  37811. {
  37812. if (e.y >= -50 && e.y < getHeight() + 50)
  37813. {
  37814. beginDrag (e);
  37815. if (dragOverlayComp != 0)
  37816. {
  37817. dragOverlayComp->setVisible (true);
  37818. dragOverlayComp->setBounds (jlimit (0,
  37819. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  37820. e.x - draggingColumnOffset),
  37821. 0,
  37822. dragOverlayComp->getWidth(),
  37823. getHeight());
  37824. for (int i = columns.size(); --i >= 0;)
  37825. {
  37826. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  37827. int newIndex = currentIndex;
  37828. if (newIndex > 0)
  37829. {
  37830. // if the previous column isn't draggable, we can't move our column
  37831. // past it, because that'd change the undraggable column's position..
  37832. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  37833. if ((previous->propertyFlags & draggable) != 0)
  37834. {
  37835. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  37836. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  37837. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  37838. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  37839. {
  37840. --newIndex;
  37841. }
  37842. }
  37843. }
  37844. if (newIndex < columns.size() - 1)
  37845. {
  37846. // if the next column isn't draggable, we can't move our column
  37847. // past it, because that'd change the undraggable column's position..
  37848. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  37849. if ((nextCol->propertyFlags & draggable) != 0)
  37850. {
  37851. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  37852. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  37853. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  37854. > abs (dragOverlayComp->getRight() - rightOfNext))
  37855. {
  37856. ++newIndex;
  37857. }
  37858. }
  37859. }
  37860. if (newIndex != currentIndex)
  37861. moveColumn (columnIdBeingDragged, newIndex);
  37862. else
  37863. break;
  37864. }
  37865. }
  37866. }
  37867. else
  37868. {
  37869. endDrag (draggingColumnOriginalIndex);
  37870. }
  37871. }
  37872. }
  37873. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  37874. {
  37875. if (columnIdBeingDragged == 0)
  37876. {
  37877. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  37878. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  37879. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  37880. {
  37881. columnIdBeingDragged = 0;
  37882. }
  37883. else
  37884. {
  37885. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  37886. const Rectangle columnRect (getColumnPosition (draggingColumnOriginalIndex));
  37887. const int temp = columnIdBeingDragged;
  37888. columnIdBeingDragged = 0;
  37889. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  37890. columnIdBeingDragged = temp;
  37891. dragOverlayComp->setBounds (columnRect);
  37892. for (int i = listeners.size(); --i >= 0;)
  37893. {
  37894. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  37895. i = jmin (i, listeners.size() - 1);
  37896. }
  37897. }
  37898. }
  37899. }
  37900. void TableHeaderComponent::endDrag (const int finalIndex)
  37901. {
  37902. if (columnIdBeingDragged != 0)
  37903. {
  37904. moveColumn (columnIdBeingDragged, finalIndex);
  37905. columnIdBeingDragged = 0;
  37906. repaint();
  37907. for (int i = listeners.size(); --i >= 0;)
  37908. {
  37909. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  37910. i = jmin (i, listeners.size() - 1);
  37911. }
  37912. }
  37913. }
  37914. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  37915. {
  37916. mouseDrag (e);
  37917. for (int i = columns.size(); --i >= 0;)
  37918. if (columns.getUnchecked (i)->isVisible())
  37919. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  37920. columnIdBeingResized = 0;
  37921. repaint();
  37922. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  37923. updateColumnUnderMouse (e.x, e.y);
  37924. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  37925. columnClicked (columnIdUnderMouse, e.mods);
  37926. deleteAndZero (dragOverlayComp);
  37927. }
  37928. const MouseCursor TableHeaderComponent::getMouseCursor()
  37929. {
  37930. int x, y;
  37931. getMouseXYRelative (x, y);
  37932. if (columnIdBeingResized != 0 || (getResizeDraggerAt (x) != 0 && ! isMouseButtonDown()))
  37933. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  37934. return Component::getMouseCursor();
  37935. }
  37936. bool TableHeaderComponent::ColumnInfo::isVisible() const throw()
  37937. {
  37938. return (propertyFlags & TableHeaderComponent::visible) != 0;
  37939. }
  37940. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const throw()
  37941. {
  37942. for (int i = columns.size(); --i >= 0;)
  37943. if (columns.getUnchecked(i)->id == id)
  37944. return columns.getUnchecked(i);
  37945. return 0;
  37946. }
  37947. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const throw()
  37948. {
  37949. int n = 0;
  37950. for (int i = 0; i < columns.size(); ++i)
  37951. {
  37952. if (columns.getUnchecked(i)->isVisible())
  37953. {
  37954. if (n == visibleIndex)
  37955. return i;
  37956. ++n;
  37957. }
  37958. }
  37959. return -1;
  37960. }
  37961. void TableHeaderComponent::sendColumnsChanged()
  37962. {
  37963. if (stretchToFit && lastDeliberateWidth > 0)
  37964. resizeAllColumnsToFit (lastDeliberateWidth);
  37965. repaint();
  37966. columnsChanged = true;
  37967. triggerAsyncUpdate();
  37968. }
  37969. void TableHeaderComponent::handleAsyncUpdate()
  37970. {
  37971. const bool changed = columnsChanged || sortChanged;
  37972. const bool sized = columnsResized || changed;
  37973. const bool sorted = sortChanged;
  37974. columnsChanged = false;
  37975. columnsResized = false;
  37976. sortChanged = false;
  37977. if (sorted)
  37978. {
  37979. for (int i = listeners.size(); --i >= 0;)
  37980. {
  37981. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  37982. i = jmin (i, listeners.size() - 1);
  37983. }
  37984. }
  37985. if (changed)
  37986. {
  37987. for (int i = listeners.size(); --i >= 0;)
  37988. {
  37989. listeners.getUnchecked(i)->tableColumnsChanged (this);
  37990. i = jmin (i, listeners.size() - 1);
  37991. }
  37992. }
  37993. if (sized)
  37994. {
  37995. for (int i = listeners.size(); --i >= 0;)
  37996. {
  37997. listeners.getUnchecked(i)->tableColumnsResized (this);
  37998. i = jmin (i, listeners.size() - 1);
  37999. }
  38000. }
  38001. }
  38002. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const throw()
  38003. {
  38004. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  38005. {
  38006. const int draggableDistance = 3;
  38007. int x = 0;
  38008. for (int i = 0; i < columns.size(); ++i)
  38009. {
  38010. const ColumnInfo* const ci = columns.getUnchecked(i);
  38011. if (ci->isVisible())
  38012. {
  38013. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  38014. && (ci->propertyFlags & resizable) != 0)
  38015. return ci->id;
  38016. x += ci->width;
  38017. }
  38018. }
  38019. }
  38020. return 0;
  38021. }
  38022. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  38023. {
  38024. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  38025. ? getColumnIdAtX (x) : 0;
  38026. if (newCol != columnIdUnderMouse)
  38027. {
  38028. columnIdUnderMouse = newCol;
  38029. repaint();
  38030. }
  38031. }
  38032. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  38033. {
  38034. PopupMenu m;
  38035. addMenuItems (m, columnIdClicked);
  38036. if (m.getNumItems() > 0)
  38037. {
  38038. const int result = m.show();
  38039. if (result != 0)
  38040. reactToMenuItem (result, columnIdClicked);
  38041. }
  38042. }
  38043. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  38044. {
  38045. }
  38046. END_JUCE_NAMESPACE
  38047. /********* End of inlined file: juce_TableHeaderComponent.cpp *********/
  38048. /********* Start of inlined file: juce_TableListBox.cpp *********/
  38049. BEGIN_JUCE_NAMESPACE
  38050. static const tchar* const tableColumnPropertyTag = T("_tableColumnID");
  38051. class TableListRowComp : public Component
  38052. {
  38053. public:
  38054. TableListRowComp (TableListBox& owner_)
  38055. : owner (owner_),
  38056. row (-1),
  38057. isSelected (false)
  38058. {
  38059. }
  38060. ~TableListRowComp()
  38061. {
  38062. deleteAllChildren();
  38063. }
  38064. void paint (Graphics& g)
  38065. {
  38066. TableListBoxModel* const model = owner.getModel();
  38067. if (model != 0)
  38068. {
  38069. const TableHeaderComponent* const header = owner.getHeader();
  38070. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  38071. const int numColumns = header->getNumColumns (true);
  38072. for (int i = 0; i < numColumns; ++i)
  38073. {
  38074. if (! columnsWithComponents [i])
  38075. {
  38076. const int columnId = header->getColumnIdOfIndex (i, true);
  38077. Rectangle columnRect (header->getColumnPosition (i));
  38078. columnRect.setSize (columnRect.getWidth(), getHeight());
  38079. g.saveState();
  38080. g.reduceClipRegion (columnRect);
  38081. g.setOrigin (columnRect.getX(), 0);
  38082. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  38083. g.restoreState();
  38084. }
  38085. }
  38086. }
  38087. }
  38088. void update (const int newRow, const bool isNowSelected)
  38089. {
  38090. if (newRow != row || isNowSelected != isSelected)
  38091. {
  38092. row = newRow;
  38093. isSelected = isNowSelected;
  38094. repaint();
  38095. }
  38096. if (row < owner.getNumRows())
  38097. {
  38098. jassert (row >= 0);
  38099. const tchar* const tagPropertyName = T("_tableLastUseNum");
  38100. const int newTag = Random::getSystemRandom().nextInt();
  38101. const TableHeaderComponent* const header = owner.getHeader();
  38102. const int numColumns = header->getNumColumns (true);
  38103. int i;
  38104. columnsWithComponents.clear();
  38105. if (owner.getModel() != 0)
  38106. {
  38107. for (i = 0; i < numColumns; ++i)
  38108. {
  38109. const int columnId = header->getColumnIdOfIndex (i, true);
  38110. Component* const newComp
  38111. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  38112. findChildComponentForColumn (columnId));
  38113. if (newComp != 0)
  38114. {
  38115. addAndMakeVisible (newComp);
  38116. newComp->setComponentProperty (tagPropertyName, newTag);
  38117. newComp->setComponentProperty (tableColumnPropertyTag, columnId);
  38118. const Rectangle columnRect (header->getColumnPosition (i));
  38119. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  38120. columnsWithComponents.setBit (i);
  38121. }
  38122. }
  38123. }
  38124. for (i = getNumChildComponents(); --i >= 0;)
  38125. {
  38126. Component* const c = getChildComponent (i);
  38127. if (c->getComponentPropertyInt (tagPropertyName, false, 0) != newTag)
  38128. delete c;
  38129. }
  38130. }
  38131. else
  38132. {
  38133. columnsWithComponents.clear();
  38134. deleteAllChildren();
  38135. }
  38136. }
  38137. void resized()
  38138. {
  38139. for (int i = getNumChildComponents(); --i >= 0;)
  38140. {
  38141. Component* const c = getChildComponent (i);
  38142. const int columnId = c->getComponentPropertyInt (tableColumnPropertyTag, false, 0);
  38143. if (columnId != 0)
  38144. {
  38145. const Rectangle columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  38146. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  38147. }
  38148. }
  38149. }
  38150. void mouseDown (const MouseEvent& e)
  38151. {
  38152. isDragging = false;
  38153. selectRowOnMouseUp = false;
  38154. if (isEnabled())
  38155. {
  38156. if (! isSelected)
  38157. {
  38158. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38159. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38160. if (columnId != 0 && owner.getModel() != 0)
  38161. owner.getModel()->cellClicked (row, columnId, e);
  38162. }
  38163. else
  38164. {
  38165. selectRowOnMouseUp = true;
  38166. }
  38167. }
  38168. }
  38169. void mouseDrag (const MouseEvent& e)
  38170. {
  38171. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38172. {
  38173. const SparseSet <int> selectedRows (owner.getSelectedRows());
  38174. if (selectedRows.size() > 0)
  38175. {
  38176. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38177. if (dragDescription.isNotEmpty())
  38178. {
  38179. isDragging = true;
  38180. DragAndDropContainer* const dragContainer
  38181. = DragAndDropContainer::findParentDragContainerFor (this);
  38182. if (dragContainer != 0)
  38183. {
  38184. Image* dragImage = owner.createSnapshotOfSelectedRows();
  38185. dragImage->multiplyAllAlphas (0.6f);
  38186. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  38187. }
  38188. else
  38189. {
  38190. // to be able to do a drag-and-drop operation, the listbox needs to
  38191. // be inside a component which is also a DragAndDropContainer.
  38192. jassertfalse
  38193. }
  38194. }
  38195. }
  38196. }
  38197. }
  38198. void mouseUp (const MouseEvent& e)
  38199. {
  38200. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  38201. {
  38202. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38203. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38204. if (columnId != 0 && owner.getModel() != 0)
  38205. owner.getModel()->cellClicked (row, columnId, e);
  38206. }
  38207. }
  38208. void mouseDoubleClick (const MouseEvent& e)
  38209. {
  38210. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38211. if (columnId != 0 && owner.getModel() != 0)
  38212. owner.getModel()->cellDoubleClicked (row, columnId, e);
  38213. }
  38214. juce_UseDebuggingNewOperator
  38215. private:
  38216. TableListBox& owner;
  38217. int row;
  38218. bool isSelected, isDragging, selectRowOnMouseUp;
  38219. BitArray columnsWithComponents;
  38220. Component* findChildComponentForColumn (const int columnId) const
  38221. {
  38222. for (int i = getNumChildComponents(); --i >= 0;)
  38223. {
  38224. Component* const c = getChildComponent (i);
  38225. if (c->getComponentPropertyInt (tableColumnPropertyTag, false, 0) == columnId)
  38226. return c;
  38227. }
  38228. return 0;
  38229. }
  38230. TableListRowComp (const TableListRowComp&);
  38231. const TableListRowComp& operator= (const TableListRowComp&);
  38232. };
  38233. class TableListBoxHeader : public TableHeaderComponent
  38234. {
  38235. public:
  38236. TableListBoxHeader (TableListBox& owner_)
  38237. : owner (owner_)
  38238. {
  38239. }
  38240. ~TableListBoxHeader()
  38241. {
  38242. }
  38243. void addMenuItems (PopupMenu& menu, const int columnIdClicked)
  38244. {
  38245. if (owner.isAutoSizeMenuOptionShown())
  38246. {
  38247. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  38248. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  38249. menu.addSeparator();
  38250. }
  38251. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  38252. }
  38253. void reactToMenuItem (const int menuReturnId, const int columnIdClicked)
  38254. {
  38255. if (menuReturnId == 0xf836743)
  38256. {
  38257. owner.autoSizeColumn (columnIdClicked);
  38258. }
  38259. else if (menuReturnId == 0xf836744)
  38260. {
  38261. owner.autoSizeAllColumns();
  38262. }
  38263. else
  38264. {
  38265. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  38266. }
  38267. }
  38268. juce_UseDebuggingNewOperator
  38269. private:
  38270. TableListBox& owner;
  38271. TableListBoxHeader (const TableListBoxHeader&);
  38272. const TableListBoxHeader& operator= (const TableListBoxHeader&);
  38273. };
  38274. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  38275. : ListBox (name, 0),
  38276. model (model_),
  38277. autoSizeOptionsShown (true)
  38278. {
  38279. ListBox::model = this;
  38280. header = new TableListBoxHeader (*this);
  38281. header->setSize (100, 28);
  38282. header->addListener (this);
  38283. setHeaderComponent (header);
  38284. }
  38285. TableListBox::~TableListBox()
  38286. {
  38287. deleteAllChildren();
  38288. }
  38289. void TableListBox::setModel (TableListBoxModel* const newModel)
  38290. {
  38291. if (model != newModel)
  38292. {
  38293. model = newModel;
  38294. updateContent();
  38295. }
  38296. }
  38297. int TableListBox::getHeaderHeight() const throw()
  38298. {
  38299. return header->getHeight();
  38300. }
  38301. void TableListBox::setHeaderHeight (const int newHeight)
  38302. {
  38303. header->setSize (header->getWidth(), newHeight);
  38304. resized();
  38305. }
  38306. void TableListBox::autoSizeColumn (const int columnId)
  38307. {
  38308. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  38309. if (width > 0)
  38310. header->setColumnWidth (columnId, width);
  38311. }
  38312. void TableListBox::autoSizeAllColumns()
  38313. {
  38314. for (int i = 0; i < header->getNumColumns (true); ++i)
  38315. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  38316. }
  38317. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  38318. {
  38319. autoSizeOptionsShown = shouldBeShown;
  38320. }
  38321. bool TableListBox::isAutoSizeMenuOptionShown() const throw()
  38322. {
  38323. return autoSizeOptionsShown;
  38324. }
  38325. const Rectangle TableListBox::getCellPosition (const int columnId,
  38326. const int rowNumber,
  38327. const bool relativeToComponentTopLeft) const
  38328. {
  38329. Rectangle headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  38330. if (relativeToComponentTopLeft)
  38331. headerCell.translate (header->getX(), 0);
  38332. const Rectangle row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  38333. return Rectangle (headerCell.getX(), row.getY(),
  38334. headerCell.getWidth(), row.getHeight());
  38335. }
  38336. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  38337. {
  38338. ScrollBar* const scrollbar = getHorizontalScrollBar();
  38339. if (scrollbar != 0)
  38340. {
  38341. const Rectangle pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  38342. double x = scrollbar->getCurrentRangeStart();
  38343. const double w = scrollbar->getCurrentRangeSize();
  38344. if (pos.getX() < x)
  38345. x = pos.getX();
  38346. else if (pos.getRight() > x + w)
  38347. x += jmax (0.0, pos.getRight() - (x + w));
  38348. scrollbar->setCurrentRangeStart (x);
  38349. }
  38350. }
  38351. int TableListBox::getNumRows()
  38352. {
  38353. return model != 0 ? model->getNumRows() : 0;
  38354. }
  38355. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  38356. {
  38357. }
  38358. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  38359. {
  38360. if (existingComponentToUpdate == 0)
  38361. existingComponentToUpdate = new TableListRowComp (*this);
  38362. ((TableListRowComp*) existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  38363. return existingComponentToUpdate;
  38364. }
  38365. void TableListBox::selectedRowsChanged (int row)
  38366. {
  38367. if (model != 0)
  38368. model->selectedRowsChanged (row);
  38369. }
  38370. void TableListBox::deleteKeyPressed (int row)
  38371. {
  38372. if (model != 0)
  38373. model->deleteKeyPressed (row);
  38374. }
  38375. void TableListBox::returnKeyPressed (int row)
  38376. {
  38377. if (model != 0)
  38378. model->returnKeyPressed (row);
  38379. }
  38380. void TableListBox::backgroundClicked()
  38381. {
  38382. if (model != 0)
  38383. model->backgroundClicked();
  38384. }
  38385. void TableListBox::listWasScrolled()
  38386. {
  38387. if (model != 0)
  38388. model->listWasScrolled();
  38389. }
  38390. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  38391. {
  38392. setMinimumContentWidth (header->getTotalWidth());
  38393. repaint();
  38394. updateColumnComponents();
  38395. }
  38396. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  38397. {
  38398. setMinimumContentWidth (header->getTotalWidth());
  38399. repaint();
  38400. updateColumnComponents();
  38401. }
  38402. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  38403. {
  38404. if (model != 0)
  38405. model->sortOrderChanged (header->getSortColumnId(),
  38406. header->isSortedForwards());
  38407. }
  38408. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  38409. {
  38410. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  38411. repaint();
  38412. }
  38413. void TableListBox::resized()
  38414. {
  38415. ListBox::resized();
  38416. header->resizeAllColumnsToFit (getVisibleContentWidth());
  38417. setMinimumContentWidth (header->getTotalWidth());
  38418. }
  38419. void TableListBox::updateColumnComponents() const
  38420. {
  38421. const int firstRow = getRowContainingPosition (0, 0);
  38422. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  38423. {
  38424. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  38425. if (rowComp != 0)
  38426. rowComp->resized();
  38427. }
  38428. }
  38429. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  38430. {
  38431. }
  38432. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  38433. {
  38434. }
  38435. void TableListBoxModel::backgroundClicked()
  38436. {
  38437. }
  38438. void TableListBoxModel::sortOrderChanged (int, const bool)
  38439. {
  38440. }
  38441. int TableListBoxModel::getColumnAutoSizeWidth (int)
  38442. {
  38443. return 0;
  38444. }
  38445. void TableListBoxModel::selectedRowsChanged (int)
  38446. {
  38447. }
  38448. void TableListBoxModel::deleteKeyPressed (int)
  38449. {
  38450. }
  38451. void TableListBoxModel::returnKeyPressed (int)
  38452. {
  38453. }
  38454. void TableListBoxModel::listWasScrolled()
  38455. {
  38456. }
  38457. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38458. {
  38459. return String::empty;
  38460. }
  38461. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  38462. {
  38463. (void) existingComponentToUpdate;
  38464. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38465. return 0;
  38466. }
  38467. END_JUCE_NAMESPACE
  38468. /********* End of inlined file: juce_TableListBox.cpp *********/
  38469. /********* Start of inlined file: juce_TextEditor.cpp *********/
  38470. BEGIN_JUCE_NAMESPACE
  38471. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  38472. // a word or space that can't be broken down any further
  38473. struct TextAtom
  38474. {
  38475. String atomText;
  38476. float width;
  38477. uint16 numChars;
  38478. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (atomText[0]); }
  38479. bool isNewLine() const throw() { return atomText[0] == T('\r') || atomText[0] == T('\n'); }
  38480. const String getText (const tchar passwordCharacter) const throw()
  38481. {
  38482. if (passwordCharacter == 0)
  38483. return atomText;
  38484. else
  38485. return String::repeatedString (String::charToString (passwordCharacter),
  38486. atomText.length());
  38487. }
  38488. const String getTrimmedText (const tchar passwordCharacter) const throw()
  38489. {
  38490. if (passwordCharacter == 0)
  38491. return atomText.substring (0, numChars);
  38492. else if (isNewLine())
  38493. return String::empty;
  38494. else
  38495. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  38496. }
  38497. };
  38498. // a run of text with a single font and colour
  38499. class UniformTextSection
  38500. {
  38501. public:
  38502. UniformTextSection (const String& text,
  38503. const Font& font_,
  38504. const Colour& colour_,
  38505. const tchar passwordCharacter) throw()
  38506. : font (font_),
  38507. colour (colour_),
  38508. atoms (64)
  38509. {
  38510. initialiseAtoms (text, passwordCharacter);
  38511. }
  38512. UniformTextSection (const UniformTextSection& other) throw()
  38513. : font (other.font),
  38514. colour (other.colour),
  38515. atoms (64)
  38516. {
  38517. for (int i = 0; i < other.atoms.size(); ++i)
  38518. atoms.add (new TextAtom (*(const TextAtom*) other.atoms.getUnchecked(i)));
  38519. }
  38520. ~UniformTextSection() throw()
  38521. {
  38522. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  38523. }
  38524. void clear() throw()
  38525. {
  38526. for (int i = atoms.size(); --i >= 0;)
  38527. {
  38528. TextAtom* const atom = getAtom(i);
  38529. delete atom;
  38530. }
  38531. atoms.clear();
  38532. }
  38533. int getNumAtoms() const throw()
  38534. {
  38535. return atoms.size();
  38536. }
  38537. TextAtom* getAtom (const int index) const throw()
  38538. {
  38539. return (TextAtom*) atoms.getUnchecked (index);
  38540. }
  38541. void append (const UniformTextSection& other, const tchar passwordCharacter) throw()
  38542. {
  38543. if (other.atoms.size() > 0)
  38544. {
  38545. TextAtom* const lastAtom = (TextAtom*) atoms.getLast();
  38546. int i = 0;
  38547. if (lastAtom != 0)
  38548. {
  38549. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  38550. {
  38551. TextAtom* const first = other.getAtom(0);
  38552. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  38553. {
  38554. lastAtom->atomText += first->atomText;
  38555. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  38556. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  38557. delete first;
  38558. ++i;
  38559. }
  38560. }
  38561. }
  38562. while (i < other.atoms.size())
  38563. {
  38564. atoms.add (other.getAtom(i));
  38565. ++i;
  38566. }
  38567. }
  38568. }
  38569. UniformTextSection* split (const int indexToBreakAt,
  38570. const tchar passwordCharacter) throw()
  38571. {
  38572. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  38573. font, colour,
  38574. passwordCharacter);
  38575. int index = 0;
  38576. for (int i = 0; i < atoms.size(); ++i)
  38577. {
  38578. TextAtom* const atom = getAtom(i);
  38579. const int nextIndex = index + atom->numChars;
  38580. if (index == indexToBreakAt)
  38581. {
  38582. int j;
  38583. for (j = i; j < atoms.size(); ++j)
  38584. section2->atoms.add (getAtom (j));
  38585. for (j = atoms.size(); --j >= i;)
  38586. atoms.remove (j);
  38587. break;
  38588. }
  38589. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  38590. {
  38591. TextAtom* const secondAtom = new TextAtom();
  38592. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  38593. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  38594. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  38595. section2->atoms.add (secondAtom);
  38596. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  38597. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  38598. atom->numChars = (uint16) (indexToBreakAt - index);
  38599. int j;
  38600. for (j = i + 1; j < atoms.size(); ++j)
  38601. section2->atoms.add (getAtom (j));
  38602. for (j = atoms.size(); --j > i;)
  38603. atoms.remove (j);
  38604. break;
  38605. }
  38606. index = nextIndex;
  38607. }
  38608. return section2;
  38609. }
  38610. const String getAllText() const throw()
  38611. {
  38612. String s;
  38613. s.preallocateStorage (getTotalLength());
  38614. tchar* endOfString = (tchar*) &(s[0]);
  38615. for (int i = 0; i < atoms.size(); ++i)
  38616. {
  38617. const TextAtom* const atom = getAtom(i);
  38618. memcpy (endOfString, &(atom->atomText[0]), atom->numChars * sizeof (tchar));
  38619. endOfString += atom->numChars;
  38620. }
  38621. *endOfString = 0;
  38622. jassert ((endOfString - (tchar*) &(s[0])) <= getTotalLength());
  38623. return s;
  38624. }
  38625. const String getTextSubstring (const int startCharacter,
  38626. const int endCharacter) const throw()
  38627. {
  38628. int index = 0;
  38629. int totalLen = 0;
  38630. int i;
  38631. for (i = 0; i < atoms.size(); ++i)
  38632. {
  38633. const TextAtom* const atom = getAtom (i);
  38634. const int nextIndex = index + atom->numChars;
  38635. if (startCharacter < nextIndex)
  38636. {
  38637. if (endCharacter <= index)
  38638. break;
  38639. const int start = jmax (0, startCharacter - index);
  38640. const int end = jmin (endCharacter - index, atom->numChars);
  38641. jassert (end >= start);
  38642. totalLen += end - start;
  38643. }
  38644. index = nextIndex;
  38645. }
  38646. String s;
  38647. s.preallocateStorage (totalLen + 1);
  38648. tchar* psz = (tchar*) (const tchar*) s;
  38649. index = 0;
  38650. for (i = 0; i < atoms.size(); ++i)
  38651. {
  38652. const TextAtom* const atom = getAtom (i);
  38653. const int nextIndex = index + atom->numChars;
  38654. if (startCharacter < nextIndex)
  38655. {
  38656. if (endCharacter <= index)
  38657. break;
  38658. const int start = jmax (0, startCharacter - index);
  38659. const int len = jmin (endCharacter - index, atom->numChars) - start;
  38660. memcpy (psz, ((const tchar*) atom->atomText) + start, len * sizeof (tchar));
  38661. psz += len;
  38662. *psz = 0;
  38663. }
  38664. index = nextIndex;
  38665. }
  38666. return s;
  38667. }
  38668. int getTotalLength() const throw()
  38669. {
  38670. int c = 0;
  38671. for (int i = atoms.size(); --i >= 0;)
  38672. c += getAtom(i)->numChars;
  38673. return c;
  38674. }
  38675. void setFont (const Font& newFont,
  38676. const tchar passwordCharacter) throw()
  38677. {
  38678. if (font != newFont)
  38679. {
  38680. font = newFont;
  38681. for (int i = atoms.size(); --i >= 0;)
  38682. {
  38683. TextAtom* const atom = (TextAtom*) atoms.getUnchecked(i);
  38684. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  38685. }
  38686. }
  38687. }
  38688. juce_UseDebuggingNewOperator
  38689. Font font;
  38690. Colour colour;
  38691. private:
  38692. VoidArray atoms;
  38693. void initialiseAtoms (const String& textToParse,
  38694. const tchar passwordCharacter) throw()
  38695. {
  38696. int i = 0;
  38697. const int len = textToParse.length();
  38698. const tchar* const text = (const tchar*) textToParse;
  38699. while (i < len)
  38700. {
  38701. int start = i;
  38702. // create a whitespace atom unless it starts with non-ws
  38703. if (CharacterFunctions::isWhitespace (text[i])
  38704. && text[i] != T('\r')
  38705. && text[i] != T('\n'))
  38706. {
  38707. while (i < len
  38708. && CharacterFunctions::isWhitespace (text[i])
  38709. && text[i] != T('\r')
  38710. && text[i] != T('\n'))
  38711. {
  38712. ++i;
  38713. }
  38714. }
  38715. else
  38716. {
  38717. if (text[i] == T('\r'))
  38718. {
  38719. ++i;
  38720. if ((i < len) && (text[i] == T('\n')))
  38721. {
  38722. ++start;
  38723. ++i;
  38724. }
  38725. }
  38726. else if (text[i] == T('\n'))
  38727. {
  38728. ++i;
  38729. }
  38730. else
  38731. {
  38732. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  38733. ++i;
  38734. }
  38735. }
  38736. TextAtom* const atom = new TextAtom();
  38737. atom->atomText = String (text + start, i - start);
  38738. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  38739. atom->numChars = (uint16) (i - start);
  38740. atoms.add (atom);
  38741. }
  38742. }
  38743. const UniformTextSection& operator= (const UniformTextSection& other);
  38744. };
  38745. class TextEditorIterator
  38746. {
  38747. public:
  38748. TextEditorIterator (const VoidArray& sections_,
  38749. const float wordWrapWidth_,
  38750. const tchar passwordCharacter_) throw()
  38751. : indexInText (0),
  38752. lineY (0),
  38753. lineHeight (0),
  38754. maxDescent (0),
  38755. atomX (0),
  38756. atomRight (0),
  38757. atom (0),
  38758. currentSection (0),
  38759. sections (sections_),
  38760. sectionIndex (0),
  38761. atomIndex (0),
  38762. wordWrapWidth (wordWrapWidth_),
  38763. passwordCharacter (passwordCharacter_)
  38764. {
  38765. jassert (wordWrapWidth_ > 0);
  38766. if (sections.size() > 0)
  38767. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  38768. if (currentSection != 0)
  38769. {
  38770. lineHeight = currentSection->font.getHeight();
  38771. maxDescent = currentSection->font.getDescent();
  38772. }
  38773. }
  38774. TextEditorIterator (const TextEditorIterator& other) throw()
  38775. : indexInText (other.indexInText),
  38776. lineY (other.lineY),
  38777. lineHeight (other.lineHeight),
  38778. maxDescent (other.maxDescent),
  38779. atomX (other.atomX),
  38780. atomRight (other.atomRight),
  38781. atom (other.atom),
  38782. currentSection (other.currentSection),
  38783. sections (other.sections),
  38784. sectionIndex (other.sectionIndex),
  38785. atomIndex (other.atomIndex),
  38786. wordWrapWidth (other.wordWrapWidth),
  38787. passwordCharacter (other.passwordCharacter),
  38788. tempAtom (other.tempAtom)
  38789. {
  38790. }
  38791. ~TextEditorIterator() throw()
  38792. {
  38793. }
  38794. bool next() throw()
  38795. {
  38796. if (atom == &tempAtom)
  38797. {
  38798. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  38799. if (numRemaining > 0)
  38800. {
  38801. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  38802. atomX = 0;
  38803. if (tempAtom.numChars > 0)
  38804. lineY += lineHeight;
  38805. indexInText += tempAtom.numChars;
  38806. GlyphArrangement g;
  38807. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  38808. int split;
  38809. for (split = 0; split < g.getNumGlyphs(); ++split)
  38810. if (SHOULD_WRAP (g.getGlyph (split).getRight(), wordWrapWidth))
  38811. break;
  38812. if (split > 0 && split <= numRemaining)
  38813. {
  38814. tempAtom.numChars = (uint16) split;
  38815. tempAtom.width = g.getGlyph (split - 1).getRight();
  38816. atomRight = atomX + tempAtom.width;
  38817. return true;
  38818. }
  38819. }
  38820. }
  38821. bool forceNewLine = false;
  38822. if (sectionIndex >= sections.size())
  38823. {
  38824. moveToEndOfLastAtom();
  38825. return false;
  38826. }
  38827. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  38828. {
  38829. if (atomIndex >= currentSection->getNumAtoms())
  38830. {
  38831. if (++sectionIndex >= sections.size())
  38832. {
  38833. moveToEndOfLastAtom();
  38834. return false;
  38835. }
  38836. atomIndex = 0;
  38837. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  38838. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  38839. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  38840. }
  38841. else
  38842. {
  38843. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  38844. if (! lastAtom->isWhitespace())
  38845. {
  38846. // handle the case where the last atom in a section is actually part of the same
  38847. // word as the first atom of the next section...
  38848. float right = atomRight + lastAtom->width;
  38849. float lineHeight2 = lineHeight;
  38850. float maxDescent2 = maxDescent;
  38851. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  38852. {
  38853. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked (section);
  38854. if (s->getNumAtoms() == 0)
  38855. break;
  38856. const TextAtom* const nextAtom = s->getAtom (0);
  38857. if (nextAtom->isWhitespace())
  38858. break;
  38859. right += nextAtom->width;
  38860. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  38861. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  38862. if (SHOULD_WRAP (right, wordWrapWidth))
  38863. {
  38864. lineHeight = lineHeight2;
  38865. maxDescent = maxDescent2;
  38866. forceNewLine = true;
  38867. break;
  38868. }
  38869. if (s->getNumAtoms() > 1)
  38870. break;
  38871. }
  38872. }
  38873. }
  38874. }
  38875. if (atom != 0)
  38876. {
  38877. atomX = atomRight;
  38878. indexInText += atom->numChars;
  38879. if (atom->isNewLine())
  38880. {
  38881. atomX = 0;
  38882. lineY += lineHeight;
  38883. }
  38884. }
  38885. atom = currentSection->getAtom (atomIndex);
  38886. atomRight = atomX + atom->width;
  38887. ++atomIndex;
  38888. if (SHOULD_WRAP (atomRight, wordWrapWidth) || forceNewLine)
  38889. {
  38890. if (atom->isWhitespace())
  38891. {
  38892. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  38893. atomRight = jmin (atomRight, wordWrapWidth);
  38894. }
  38895. else
  38896. {
  38897. return wrapCurrentAtom();
  38898. }
  38899. }
  38900. return true;
  38901. }
  38902. bool wrapCurrentAtom() throw()
  38903. {
  38904. atomRight = atom->width;
  38905. if (SHOULD_WRAP (atomRight, wordWrapWidth)) // atom too big to fit on a line, so break it up..
  38906. {
  38907. tempAtom = *atom;
  38908. tempAtom.width = 0;
  38909. tempAtom.numChars = 0;
  38910. atom = &tempAtom;
  38911. if (atomX > 0)
  38912. {
  38913. atomX = 0;
  38914. lineY += lineHeight;
  38915. }
  38916. return next();
  38917. }
  38918. atomX = 0;
  38919. lineY += lineHeight;
  38920. return true;
  38921. }
  38922. void draw (Graphics& g, const UniformTextSection*& lastSection) const throw()
  38923. {
  38924. if (passwordCharacter != 0 || ! atom->isWhitespace())
  38925. {
  38926. if (lastSection != currentSection)
  38927. {
  38928. lastSection = currentSection;
  38929. g.setColour (currentSection->colour);
  38930. g.setFont (currentSection->font);
  38931. }
  38932. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  38933. GlyphArrangement ga;
  38934. ga.addLineOfText (currentSection->font,
  38935. atom->getTrimmedText (passwordCharacter),
  38936. atomX,
  38937. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  38938. ga.draw (g);
  38939. }
  38940. }
  38941. void drawSelection (Graphics& g,
  38942. const int selectionStart,
  38943. const int selectionEnd) const throw()
  38944. {
  38945. const int startX = roundFloatToInt (indexToX (selectionStart));
  38946. const int endX = roundFloatToInt (indexToX (selectionEnd));
  38947. const int y = roundFloatToInt (lineY);
  38948. const int nextY = roundFloatToInt (lineY + lineHeight);
  38949. g.fillRect (startX, y, endX - startX, nextY - y);
  38950. }
  38951. void drawSelectedText (Graphics& g,
  38952. const int selectionStart,
  38953. const int selectionEnd,
  38954. const Colour& selectedTextColour) const throw()
  38955. {
  38956. if (passwordCharacter != 0 || ! atom->isWhitespace())
  38957. {
  38958. GlyphArrangement ga;
  38959. ga.addLineOfText (currentSection->font,
  38960. atom->getTrimmedText (passwordCharacter),
  38961. atomX,
  38962. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  38963. if (selectionEnd < indexInText + atom->numChars)
  38964. {
  38965. GlyphArrangement ga2 (ga);
  38966. ga2.removeRangeOfGlyphs (0, selectionEnd - indexInText);
  38967. ga.removeRangeOfGlyphs (selectionEnd - indexInText, -1);
  38968. g.setColour (currentSection->colour);
  38969. ga2.draw (g);
  38970. }
  38971. if (selectionStart > indexInText)
  38972. {
  38973. GlyphArrangement ga2 (ga);
  38974. ga2.removeRangeOfGlyphs (selectionStart - indexInText, -1);
  38975. ga.removeRangeOfGlyphs (0, selectionStart - indexInText);
  38976. g.setColour (currentSection->colour);
  38977. ga2.draw (g);
  38978. }
  38979. g.setColour (selectedTextColour);
  38980. ga.draw (g);
  38981. }
  38982. }
  38983. float indexToX (const int indexToFind) const throw()
  38984. {
  38985. if (indexToFind <= indexInText)
  38986. return atomX;
  38987. if (indexToFind >= indexInText + atom->numChars)
  38988. return atomRight;
  38989. GlyphArrangement g;
  38990. g.addLineOfText (currentSection->font,
  38991. atom->getText (passwordCharacter),
  38992. atomX, 0.0f);
  38993. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  38994. }
  38995. int xToIndex (const float xToFind) const throw()
  38996. {
  38997. if (xToFind <= atomX || atom->isNewLine())
  38998. return indexInText;
  38999. if (xToFind >= atomRight)
  39000. return indexInText + atom->numChars;
  39001. GlyphArrangement g;
  39002. g.addLineOfText (currentSection->font,
  39003. atom->getText (passwordCharacter),
  39004. atomX, 0.0f);
  39005. int j;
  39006. for (j = 0; j < atom->numChars; ++j)
  39007. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  39008. break;
  39009. return indexInText + j;
  39010. }
  39011. void updateLineHeight() throw()
  39012. {
  39013. float x = atomRight;
  39014. int tempSectionIndex = sectionIndex;
  39015. int tempAtomIndex = atomIndex;
  39016. const UniformTextSection* currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  39017. while (! SHOULD_WRAP (x, wordWrapWidth))
  39018. {
  39019. if (tempSectionIndex >= sections.size())
  39020. break;
  39021. bool checkSize = false;
  39022. if (tempAtomIndex >= currentSection->getNumAtoms())
  39023. {
  39024. if (++tempSectionIndex >= sections.size())
  39025. break;
  39026. tempAtomIndex = 0;
  39027. currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  39028. checkSize = true;
  39029. }
  39030. const TextAtom* const atom = currentSection->getAtom (tempAtomIndex);
  39031. if (atom == 0)
  39032. break;
  39033. x += atom->width;
  39034. if (SHOULD_WRAP (x, wordWrapWidth) || atom->isNewLine())
  39035. break;
  39036. if (checkSize)
  39037. {
  39038. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  39039. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  39040. }
  39041. ++tempAtomIndex;
  39042. }
  39043. }
  39044. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_) throw()
  39045. {
  39046. while (next())
  39047. {
  39048. if (indexInText + atom->numChars >= index)
  39049. {
  39050. updateLineHeight();
  39051. if (indexInText + atom->numChars > index)
  39052. {
  39053. cx = indexToX (index);
  39054. cy = lineY;
  39055. lineHeight_ = lineHeight;
  39056. return true;
  39057. }
  39058. }
  39059. }
  39060. cx = atomX;
  39061. cy = lineY;
  39062. lineHeight_ = lineHeight;
  39063. return false;
  39064. }
  39065. juce_UseDebuggingNewOperator
  39066. int indexInText;
  39067. float lineY, lineHeight, maxDescent;
  39068. float atomX, atomRight;
  39069. const TextAtom* atom;
  39070. const UniformTextSection* currentSection;
  39071. private:
  39072. const VoidArray& sections;
  39073. int sectionIndex, atomIndex;
  39074. const float wordWrapWidth;
  39075. const tchar passwordCharacter;
  39076. TextAtom tempAtom;
  39077. const TextEditorIterator& operator= (const TextEditorIterator&);
  39078. void moveToEndOfLastAtom() throw()
  39079. {
  39080. if (atom != 0)
  39081. {
  39082. atomX = atomRight;
  39083. if (atom->isNewLine())
  39084. {
  39085. atomX = 0.0f;
  39086. lineY += lineHeight;
  39087. }
  39088. }
  39089. }
  39090. };
  39091. class TextEditorInsertAction : public UndoableAction
  39092. {
  39093. TextEditor& owner;
  39094. const String text;
  39095. const int insertIndex, oldCaretPos, newCaretPos;
  39096. const Font font;
  39097. const Colour colour;
  39098. TextEditorInsertAction (const TextEditorInsertAction&);
  39099. const TextEditorInsertAction& operator= (const TextEditorInsertAction&);
  39100. public:
  39101. TextEditorInsertAction (TextEditor& owner_,
  39102. const String& text_,
  39103. const int insertIndex_,
  39104. const Font& font_,
  39105. const Colour& colour_,
  39106. const int oldCaretPos_,
  39107. const int newCaretPos_) throw()
  39108. : owner (owner_),
  39109. text (text_),
  39110. insertIndex (insertIndex_),
  39111. oldCaretPos (oldCaretPos_),
  39112. newCaretPos (newCaretPos_),
  39113. font (font_),
  39114. colour (colour_)
  39115. {
  39116. }
  39117. ~TextEditorInsertAction()
  39118. {
  39119. }
  39120. bool perform()
  39121. {
  39122. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  39123. return true;
  39124. }
  39125. bool undo()
  39126. {
  39127. owner.remove (insertIndex, insertIndex + text.length(), 0, oldCaretPos);
  39128. return true;
  39129. }
  39130. int getSizeInUnits()
  39131. {
  39132. return text.length() + 16;
  39133. }
  39134. };
  39135. class TextEditorRemoveAction : public UndoableAction
  39136. {
  39137. TextEditor& owner;
  39138. const int startIndex, endIndex, oldCaretPos, newCaretPos;
  39139. VoidArray removedSections;
  39140. TextEditorRemoveAction (const TextEditorRemoveAction&);
  39141. const TextEditorRemoveAction& operator= (const TextEditorRemoveAction&);
  39142. public:
  39143. TextEditorRemoveAction (TextEditor& owner_,
  39144. const int startIndex_,
  39145. const int endIndex_,
  39146. const int oldCaretPos_,
  39147. const int newCaretPos_,
  39148. const VoidArray& removedSections_) throw()
  39149. : owner (owner_),
  39150. startIndex (startIndex_),
  39151. endIndex (endIndex_),
  39152. oldCaretPos (oldCaretPos_),
  39153. newCaretPos (newCaretPos_),
  39154. removedSections (removedSections_)
  39155. {
  39156. }
  39157. ~TextEditorRemoveAction()
  39158. {
  39159. for (int i = removedSections.size(); --i >= 0;)
  39160. {
  39161. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  39162. section->clear();
  39163. delete section;
  39164. }
  39165. }
  39166. bool perform()
  39167. {
  39168. owner.remove (startIndex, endIndex, 0, newCaretPos);
  39169. return true;
  39170. }
  39171. bool undo()
  39172. {
  39173. owner.reinsert (startIndex, removedSections);
  39174. owner.moveCursorTo (oldCaretPos, false);
  39175. return true;
  39176. }
  39177. int getSizeInUnits()
  39178. {
  39179. int n = 0;
  39180. for (int i = removedSections.size(); --i >= 0;)
  39181. {
  39182. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  39183. n += section->getTotalLength();
  39184. }
  39185. return n + 16;
  39186. }
  39187. };
  39188. class TextHolderComponent : public Component,
  39189. public Timer
  39190. {
  39191. TextEditor* const owner;
  39192. TextHolderComponent (const TextHolderComponent&);
  39193. const TextHolderComponent& operator= (const TextHolderComponent&);
  39194. public:
  39195. TextHolderComponent (TextEditor* const owner_)
  39196. : owner (owner_)
  39197. {
  39198. setWantsKeyboardFocus (false);
  39199. setInterceptsMouseClicks (false, true);
  39200. }
  39201. ~TextHolderComponent()
  39202. {
  39203. }
  39204. void paint (Graphics& g)
  39205. {
  39206. owner->drawContent (g);
  39207. }
  39208. void timerCallback()
  39209. {
  39210. owner->timerCallbackInt();
  39211. }
  39212. const MouseCursor getMouseCursor()
  39213. {
  39214. return owner->getMouseCursor();
  39215. }
  39216. };
  39217. class TextEditorViewport : public Viewport
  39218. {
  39219. TextEditor* const owner;
  39220. float lastWordWrapWidth;
  39221. TextEditorViewport (const TextEditorViewport&);
  39222. const TextEditorViewport& operator= (const TextEditorViewport&);
  39223. public:
  39224. TextEditorViewport (TextEditor* const owner_)
  39225. : owner (owner_),
  39226. lastWordWrapWidth (0)
  39227. {
  39228. }
  39229. ~TextEditorViewport()
  39230. {
  39231. }
  39232. void visibleAreaChanged (int, int, int, int)
  39233. {
  39234. const float wordWrapWidth = owner->getWordWrapWidth();
  39235. if (wordWrapWidth != lastWordWrapWidth)
  39236. {
  39237. lastWordWrapWidth = wordWrapWidth;
  39238. owner->updateTextHolderSize();
  39239. }
  39240. }
  39241. };
  39242. const int flashSpeedIntervalMs = 380;
  39243. const int textChangeMessageId = 0x10003001;
  39244. const int returnKeyMessageId = 0x10003002;
  39245. const int escapeKeyMessageId = 0x10003003;
  39246. const int focusLossMessageId = 0x10003004;
  39247. TextEditor::TextEditor (const String& name,
  39248. const tchar passwordCharacter_)
  39249. : Component (name),
  39250. borderSize (1, 1, 1, 3),
  39251. readOnly (false),
  39252. multiline (false),
  39253. wordWrap (false),
  39254. returnKeyStartsNewLine (false),
  39255. caretVisible (true),
  39256. popupMenuEnabled (true),
  39257. selectAllTextWhenFocused (false),
  39258. scrollbarVisible (true),
  39259. wasFocused (false),
  39260. caretFlashState (true),
  39261. keepCursorOnScreen (true),
  39262. tabKeyUsed (false),
  39263. menuActive (false),
  39264. cursorX (0),
  39265. cursorY (0),
  39266. cursorHeight (0),
  39267. maxTextLength (0),
  39268. selectionStart (0),
  39269. selectionEnd (0),
  39270. leftIndent (4),
  39271. topIndent (4),
  39272. lastTransactionTime (0),
  39273. currentFont (14.0f),
  39274. totalNumChars (0),
  39275. caretPosition (0),
  39276. sections (8),
  39277. passwordCharacter (passwordCharacter_),
  39278. dragType (notDragging),
  39279. listeners (2)
  39280. {
  39281. setOpaque (true);
  39282. addAndMakeVisible (viewport = new TextEditorViewport (this));
  39283. viewport->setViewedComponent (textHolder = new TextHolderComponent (this));
  39284. viewport->setWantsKeyboardFocus (false);
  39285. viewport->setScrollBarsShown (false, false);
  39286. setMouseCursor (MouseCursor::IBeamCursor);
  39287. setWantsKeyboardFocus (true);
  39288. }
  39289. TextEditor::~TextEditor()
  39290. {
  39291. clearInternal (0);
  39292. delete viewport;
  39293. }
  39294. void TextEditor::newTransaction() throw()
  39295. {
  39296. lastTransactionTime = Time::getApproximateMillisecondCounter();
  39297. undoManager.beginNewTransaction();
  39298. }
  39299. void TextEditor::doUndoRedo (const bool isRedo)
  39300. {
  39301. if (! isReadOnly())
  39302. {
  39303. if ((isRedo) ? undoManager.redo()
  39304. : undoManager.undo())
  39305. {
  39306. scrollToMakeSureCursorIsVisible();
  39307. repaint();
  39308. textChanged();
  39309. }
  39310. }
  39311. }
  39312. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  39313. const bool shouldWordWrap)
  39314. {
  39315. multiline = shouldBeMultiLine;
  39316. wordWrap = shouldWordWrap && shouldBeMultiLine;
  39317. setScrollbarsShown (scrollbarVisible);
  39318. viewport->setViewPosition (0, 0);
  39319. resized();
  39320. scrollToMakeSureCursorIsVisible();
  39321. }
  39322. bool TextEditor::isMultiLine() const throw()
  39323. {
  39324. return multiline;
  39325. }
  39326. void TextEditor::setScrollbarsShown (bool enabled) throw()
  39327. {
  39328. scrollbarVisible = enabled;
  39329. enabled = enabled && isMultiLine();
  39330. viewport->setScrollBarsShown (enabled, enabled);
  39331. }
  39332. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  39333. {
  39334. readOnly = shouldBeReadOnly;
  39335. enablementChanged();
  39336. }
  39337. bool TextEditor::isReadOnly() const throw()
  39338. {
  39339. return readOnly || ! isEnabled();
  39340. }
  39341. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  39342. {
  39343. returnKeyStartsNewLine = shouldStartNewLine;
  39344. }
  39345. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw()
  39346. {
  39347. tabKeyUsed = shouldTabKeyBeUsed;
  39348. }
  39349. void TextEditor::setPopupMenuEnabled (const bool b) throw()
  39350. {
  39351. popupMenuEnabled = b;
  39352. }
  39353. void TextEditor::setSelectAllWhenFocused (const bool b) throw()
  39354. {
  39355. selectAllTextWhenFocused = b;
  39356. }
  39357. const Font TextEditor::getFont() const throw()
  39358. {
  39359. return currentFont;
  39360. }
  39361. void TextEditor::setFont (const Font& newFont) throw()
  39362. {
  39363. currentFont = newFont;
  39364. scrollToMakeSureCursorIsVisible();
  39365. }
  39366. void TextEditor::applyFontToAllText (const Font& newFont)
  39367. {
  39368. currentFont = newFont;
  39369. const Colour overallColour (findColour (textColourId));
  39370. for (int i = sections.size(); --i >= 0;)
  39371. {
  39372. UniformTextSection* const uts = (UniformTextSection*) sections.getUnchecked(i);
  39373. uts->setFont (newFont, passwordCharacter);
  39374. uts->colour = overallColour;
  39375. }
  39376. coalesceSimilarSections();
  39377. updateTextHolderSize();
  39378. scrollToMakeSureCursorIsVisible();
  39379. repaint();
  39380. }
  39381. void TextEditor::colourChanged()
  39382. {
  39383. setOpaque (findColour (backgroundColourId).isOpaque());
  39384. repaint();
  39385. }
  39386. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible) throw()
  39387. {
  39388. caretVisible = shouldCaretBeVisible;
  39389. if (shouldCaretBeVisible)
  39390. textHolder->startTimer (flashSpeedIntervalMs);
  39391. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  39392. : MouseCursor::NormalCursor);
  39393. }
  39394. void TextEditor::setInputRestrictions (const int maxLen,
  39395. const String& chars) throw()
  39396. {
  39397. maxTextLength = jmax (0, maxLen);
  39398. allowedCharacters = chars;
  39399. }
  39400. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw()
  39401. {
  39402. textToShowWhenEmpty = text;
  39403. colourForTextWhenEmpty = colourToUse;
  39404. }
  39405. void TextEditor::setPasswordCharacter (const tchar newPasswordCharacter) throw()
  39406. {
  39407. if (passwordCharacter != newPasswordCharacter)
  39408. {
  39409. passwordCharacter = newPasswordCharacter;
  39410. resized();
  39411. repaint();
  39412. }
  39413. }
  39414. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  39415. {
  39416. viewport->setScrollBarThickness (newThicknessPixels);
  39417. }
  39418. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  39419. {
  39420. viewport->setScrollBarButtonVisibility (buttonsVisible);
  39421. }
  39422. void TextEditor::clear()
  39423. {
  39424. clearInternal (0);
  39425. updateTextHolderSize();
  39426. undoManager.clearUndoHistory();
  39427. }
  39428. void TextEditor::setText (const String& newText,
  39429. const bool sendTextChangeMessage)
  39430. {
  39431. const int newLength = newText.length();
  39432. if (newLength != getTotalNumChars() || getText() != newText)
  39433. {
  39434. const int oldCursorPos = caretPosition;
  39435. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  39436. clearInternal (0);
  39437. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  39438. // if you're adding text with line-feeds to a single-line text editor, it
  39439. // ain't gonna look right!
  39440. jassert (multiline || ! newText.containsAnyOf (T("\r\n")));
  39441. if (cursorWasAtEnd && ! isMultiLine())
  39442. moveCursorTo (getTotalNumChars(), false);
  39443. else
  39444. moveCursorTo (oldCursorPos, false);
  39445. if (sendTextChangeMessage)
  39446. textChanged();
  39447. repaint();
  39448. }
  39449. updateTextHolderSize();
  39450. scrollToMakeSureCursorIsVisible();
  39451. undoManager.clearUndoHistory();
  39452. }
  39453. void TextEditor::textChanged() throw()
  39454. {
  39455. updateTextHolderSize();
  39456. postCommandMessage (textChangeMessageId);
  39457. }
  39458. void TextEditor::returnPressed()
  39459. {
  39460. postCommandMessage (returnKeyMessageId);
  39461. }
  39462. void TextEditor::escapePressed()
  39463. {
  39464. postCommandMessage (escapeKeyMessageId);
  39465. }
  39466. void TextEditor::addListener (TextEditorListener* const newListener) throw()
  39467. {
  39468. jassert (newListener != 0)
  39469. if (newListener != 0)
  39470. listeners.add (newListener);
  39471. }
  39472. void TextEditor::removeListener (TextEditorListener* const listenerToRemove) throw()
  39473. {
  39474. listeners.removeValue (listenerToRemove);
  39475. }
  39476. void TextEditor::timerCallbackInt()
  39477. {
  39478. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  39479. if (caretFlashState != newState)
  39480. {
  39481. caretFlashState = newState;
  39482. if (caretFlashState)
  39483. wasFocused = true;
  39484. if (caretVisible
  39485. && hasKeyboardFocus (false)
  39486. && ! isReadOnly())
  39487. {
  39488. repaintCaret();
  39489. }
  39490. }
  39491. const unsigned int now = Time::getApproximateMillisecondCounter();
  39492. if (now > lastTransactionTime + 200)
  39493. newTransaction();
  39494. }
  39495. void TextEditor::repaintCaret()
  39496. {
  39497. if (! findColour (caretColourId).isTransparent())
  39498. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundFloatToInt (cursorX) - 1,
  39499. borderSize.getTop() + textHolder->getY() + topIndent + roundFloatToInt (cursorY) - 1,
  39500. 4,
  39501. roundFloatToInt (cursorHeight) + 2);
  39502. }
  39503. void TextEditor::repaintText (int textStartIndex, int textEndIndex)
  39504. {
  39505. if (textStartIndex > textEndIndex && textEndIndex > 0)
  39506. swapVariables (textStartIndex, textEndIndex);
  39507. float x = 0, y = 0, lh = currentFont.getHeight();
  39508. const float wordWrapWidth = getWordWrapWidth();
  39509. if (wordWrapWidth > 0)
  39510. {
  39511. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39512. i.getCharPosition (textStartIndex, x, y, lh);
  39513. const int y1 = (int) y;
  39514. int y2;
  39515. if (textEndIndex >= 0)
  39516. {
  39517. i.getCharPosition (textEndIndex, x, y, lh);
  39518. y2 = (int) (y + lh * 2.0f);
  39519. }
  39520. else
  39521. {
  39522. y2 = textHolder->getHeight();
  39523. }
  39524. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  39525. }
  39526. }
  39527. void TextEditor::moveCaret (int newCaretPos) throw()
  39528. {
  39529. if (newCaretPos < 0)
  39530. newCaretPos = 0;
  39531. else if (newCaretPos > getTotalNumChars())
  39532. newCaretPos = getTotalNumChars();
  39533. if (newCaretPos != getCaretPosition())
  39534. {
  39535. repaintCaret();
  39536. caretFlashState = true;
  39537. caretPosition = newCaretPos;
  39538. textHolder->startTimer (flashSpeedIntervalMs);
  39539. scrollToMakeSureCursorIsVisible();
  39540. repaintCaret();
  39541. }
  39542. }
  39543. void TextEditor::setCaretPosition (const int newIndex) throw()
  39544. {
  39545. moveCursorTo (newIndex, false);
  39546. }
  39547. int TextEditor::getCaretPosition() const throw()
  39548. {
  39549. return caretPosition;
  39550. }
  39551. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  39552. const int desiredCaretY) throw()
  39553. {
  39554. updateCaretPosition();
  39555. int vx = roundFloatToInt (cursorX) - desiredCaretX;
  39556. int vy = roundFloatToInt (cursorY) - desiredCaretY;
  39557. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  39558. {
  39559. vx += desiredCaretX - proportionOfWidth (0.2f);
  39560. }
  39561. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  39562. {
  39563. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  39564. }
  39565. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  39566. if (! isMultiLine())
  39567. {
  39568. vy = viewport->getViewPositionY();
  39569. }
  39570. else
  39571. {
  39572. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  39573. const int curH = roundFloatToInt (cursorHeight);
  39574. if (desiredCaretY < 0)
  39575. {
  39576. vy = jmax (0, desiredCaretY + vy);
  39577. }
  39578. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  39579. {
  39580. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  39581. }
  39582. }
  39583. viewport->setViewPosition (vx, vy);
  39584. }
  39585. const Rectangle TextEditor::getCaretRectangle() throw()
  39586. {
  39587. updateCaretPosition();
  39588. return Rectangle (roundFloatToInt (cursorX) - viewport->getX(),
  39589. roundFloatToInt (cursorY) - viewport->getY(),
  39590. 1, roundFloatToInt (cursorHeight));
  39591. }
  39592. float TextEditor::getWordWrapWidth() const throw()
  39593. {
  39594. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  39595. : 1.0e10f;
  39596. }
  39597. void TextEditor::updateTextHolderSize() throw()
  39598. {
  39599. const float wordWrapWidth = getWordWrapWidth();
  39600. if (wordWrapWidth > 0)
  39601. {
  39602. float maxWidth = 0.0f;
  39603. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39604. while (i.next())
  39605. maxWidth = jmax (maxWidth, i.atomRight);
  39606. const int w = leftIndent + roundFloatToInt (maxWidth);
  39607. const int h = topIndent + roundFloatToInt (jmax (i.lineY + i.lineHeight,
  39608. currentFont.getHeight()));
  39609. textHolder->setSize (w + 1, h + 1);
  39610. }
  39611. }
  39612. int TextEditor::getTextWidth() const throw()
  39613. {
  39614. return textHolder->getWidth();
  39615. }
  39616. int TextEditor::getTextHeight() const throw()
  39617. {
  39618. return textHolder->getHeight();
  39619. }
  39620. void TextEditor::setIndents (const int newLeftIndent,
  39621. const int newTopIndent) throw()
  39622. {
  39623. leftIndent = newLeftIndent;
  39624. topIndent = newTopIndent;
  39625. }
  39626. void TextEditor::setBorder (const BorderSize& border) throw()
  39627. {
  39628. borderSize = border;
  39629. resized();
  39630. }
  39631. const BorderSize TextEditor::getBorder() const throw()
  39632. {
  39633. return borderSize;
  39634. }
  39635. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor) throw()
  39636. {
  39637. keepCursorOnScreen = shouldScrollToShowCursor;
  39638. }
  39639. void TextEditor::updateCaretPosition() throw()
  39640. {
  39641. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  39642. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  39643. }
  39644. void TextEditor::scrollToMakeSureCursorIsVisible() throw()
  39645. {
  39646. updateCaretPosition();
  39647. if (keepCursorOnScreen)
  39648. {
  39649. int x = viewport->getViewPositionX();
  39650. int y = viewport->getViewPositionY();
  39651. const int relativeCursorX = roundFloatToInt (cursorX) - x;
  39652. const int relativeCursorY = roundFloatToInt (cursorY) - y;
  39653. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  39654. {
  39655. x += relativeCursorX - proportionOfWidth (0.2f);
  39656. }
  39657. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  39658. {
  39659. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  39660. }
  39661. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  39662. if (! isMultiLine())
  39663. {
  39664. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  39665. }
  39666. else
  39667. {
  39668. const int curH = roundFloatToInt (cursorHeight);
  39669. if (relativeCursorY < 0)
  39670. {
  39671. y = jmax (0, relativeCursorY + y);
  39672. }
  39673. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  39674. {
  39675. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  39676. }
  39677. }
  39678. viewport->setViewPosition (x, y);
  39679. }
  39680. }
  39681. void TextEditor::moveCursorTo (const int newPosition,
  39682. const bool isSelecting) throw()
  39683. {
  39684. if (isSelecting)
  39685. {
  39686. moveCaret (newPosition);
  39687. const int oldSelStart = selectionStart;
  39688. const int oldSelEnd = selectionEnd;
  39689. if (dragType == notDragging)
  39690. {
  39691. if (abs (getCaretPosition() - selectionStart) < abs (getCaretPosition() - selectionEnd))
  39692. dragType = draggingSelectionStart;
  39693. else
  39694. dragType = draggingSelectionEnd;
  39695. }
  39696. if (dragType == draggingSelectionStart)
  39697. {
  39698. selectionStart = getCaretPosition();
  39699. if (selectionEnd < selectionStart)
  39700. {
  39701. swapVariables (selectionStart, selectionEnd);
  39702. dragType = draggingSelectionEnd;
  39703. }
  39704. }
  39705. else
  39706. {
  39707. selectionEnd = getCaretPosition();
  39708. if (selectionEnd < selectionStart)
  39709. {
  39710. swapVariables (selectionStart, selectionEnd);
  39711. dragType = draggingSelectionStart;
  39712. }
  39713. }
  39714. jassert (selectionStart <= selectionEnd);
  39715. jassert (oldSelStart <= oldSelEnd);
  39716. repaintText (jmin (oldSelStart, selectionStart),
  39717. jmax (oldSelEnd, selectionEnd));
  39718. }
  39719. else
  39720. {
  39721. dragType = notDragging;
  39722. if (selectionEnd > selectionStart)
  39723. repaintText (selectionStart, selectionEnd);
  39724. moveCaret (newPosition);
  39725. selectionStart = getCaretPosition();
  39726. selectionEnd = getCaretPosition();
  39727. }
  39728. }
  39729. int TextEditor::getTextIndexAt (const int x,
  39730. const int y) throw()
  39731. {
  39732. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  39733. (float) (y + viewport->getViewPositionY() - topIndent));
  39734. }
  39735. void TextEditor::insertTextAtCursor (String newText)
  39736. {
  39737. if (allowedCharacters.isNotEmpty())
  39738. newText = newText.retainCharacters (allowedCharacters);
  39739. if (! isMultiLine())
  39740. newText = newText.replaceCharacters (T("\r\n"), T(" "));
  39741. else
  39742. newText = newText.replace (T("\r\n"), T("\n"));
  39743. const int newCaretPos = selectionStart + newText.length();
  39744. const int insertIndex = selectionStart;
  39745. remove (selectionStart, selectionEnd,
  39746. &undoManager,
  39747. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  39748. if (maxTextLength > 0)
  39749. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  39750. if (newText.isNotEmpty())
  39751. insert (newText,
  39752. insertIndex,
  39753. currentFont,
  39754. findColour (textColourId),
  39755. &undoManager,
  39756. newCaretPos);
  39757. textChanged();
  39758. }
  39759. void TextEditor::setHighlightedRegion (int startPos, int numChars) throw()
  39760. {
  39761. moveCursorTo (startPos, false);
  39762. moveCursorTo (startPos + numChars, true);
  39763. }
  39764. void TextEditor::copy()
  39765. {
  39766. if (passwordCharacter == 0)
  39767. {
  39768. const String selection (getTextSubstring (selectionStart, selectionEnd));
  39769. if (selection.isNotEmpty())
  39770. SystemClipboard::copyTextToClipboard (selection);
  39771. }
  39772. }
  39773. void TextEditor::paste()
  39774. {
  39775. if (! isReadOnly())
  39776. {
  39777. const String clip (SystemClipboard::getTextFromClipboard());
  39778. if (clip.isNotEmpty())
  39779. insertTextAtCursor (clip);
  39780. }
  39781. }
  39782. void TextEditor::cut()
  39783. {
  39784. if (! isReadOnly())
  39785. {
  39786. moveCaret (selectionEnd);
  39787. insertTextAtCursor (String::empty);
  39788. }
  39789. }
  39790. void TextEditor::drawContent (Graphics& g)
  39791. {
  39792. const float wordWrapWidth = getWordWrapWidth();
  39793. if (wordWrapWidth > 0)
  39794. {
  39795. g.setOrigin (leftIndent, topIndent);
  39796. const Rectangle clip (g.getClipBounds());
  39797. Colour selectedTextColour;
  39798. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39799. while (i.lineY + 200.0 < clip.getY() && i.next())
  39800. {}
  39801. if (selectionStart < selectionEnd)
  39802. {
  39803. g.setColour (findColour (highlightColourId)
  39804. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  39805. selectedTextColour = findColour (highlightedTextColourId);
  39806. TextEditorIterator i2 (i);
  39807. while (i2.next() && i2.lineY < clip.getBottom())
  39808. {
  39809. i2.updateLineHeight();
  39810. if (i2.lineY + i2.lineHeight >= clip.getY()
  39811. && selectionEnd >= i2.indexInText
  39812. && selectionStart <= i2.indexInText + i2.atom->numChars)
  39813. {
  39814. i2.drawSelection (g, selectionStart, selectionEnd);
  39815. }
  39816. }
  39817. }
  39818. const UniformTextSection* lastSection = 0;
  39819. while (i.next() && i.lineY < clip.getBottom())
  39820. {
  39821. i.updateLineHeight();
  39822. if (i.lineY + i.lineHeight >= clip.getY())
  39823. {
  39824. if (selectionEnd >= i.indexInText
  39825. && selectionStart <= i.indexInText + i.atom->numChars)
  39826. {
  39827. i.drawSelectedText (g, selectionStart, selectionEnd, selectedTextColour);
  39828. lastSection = 0;
  39829. }
  39830. else
  39831. {
  39832. i.draw (g, lastSection);
  39833. }
  39834. }
  39835. }
  39836. }
  39837. }
  39838. void TextEditor::paint (Graphics& g)
  39839. {
  39840. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  39841. }
  39842. void TextEditor::paintOverChildren (Graphics& g)
  39843. {
  39844. if (caretFlashState
  39845. && hasKeyboardFocus (false)
  39846. && caretVisible
  39847. && ! isReadOnly())
  39848. {
  39849. g.setColour (findColour (caretColourId));
  39850. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  39851. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  39852. 2.0f, cursorHeight);
  39853. }
  39854. if (textToShowWhenEmpty.isNotEmpty()
  39855. && (! hasKeyboardFocus (false))
  39856. && getTotalNumChars() == 0)
  39857. {
  39858. g.setColour (colourForTextWhenEmpty);
  39859. g.setFont (getFont());
  39860. if (isMultiLine())
  39861. {
  39862. g.drawText (textToShowWhenEmpty,
  39863. 0, 0, getWidth(), getHeight(),
  39864. Justification::centred, true);
  39865. }
  39866. else
  39867. {
  39868. g.drawText (textToShowWhenEmpty,
  39869. leftIndent, topIndent,
  39870. viewport->getWidth() - leftIndent,
  39871. viewport->getHeight() - topIndent,
  39872. Justification::centredLeft, true);
  39873. }
  39874. }
  39875. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  39876. }
  39877. void TextEditor::mouseDown (const MouseEvent& e)
  39878. {
  39879. beginDragAutoRepeat (100);
  39880. newTransaction();
  39881. if (wasFocused || ! selectAllTextWhenFocused)
  39882. {
  39883. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  39884. {
  39885. moveCursorTo (getTextIndexAt (e.x, e.y),
  39886. e.mods.isShiftDown());
  39887. }
  39888. else
  39889. {
  39890. PopupMenu m;
  39891. addPopupMenuItems (m, &e);
  39892. menuActive = true;
  39893. const int result = m.show();
  39894. menuActive = false;
  39895. if (result != 0)
  39896. performPopupMenuAction (result);
  39897. }
  39898. }
  39899. }
  39900. void TextEditor::mouseDrag (const MouseEvent& e)
  39901. {
  39902. if (wasFocused || ! selectAllTextWhenFocused)
  39903. {
  39904. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  39905. {
  39906. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  39907. }
  39908. }
  39909. }
  39910. void TextEditor::mouseUp (const MouseEvent& e)
  39911. {
  39912. newTransaction();
  39913. textHolder->startTimer (flashSpeedIntervalMs);
  39914. if (wasFocused || ! selectAllTextWhenFocused)
  39915. {
  39916. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  39917. {
  39918. moveCaret (getTextIndexAt (e.x, e.y));
  39919. }
  39920. }
  39921. wasFocused = true;
  39922. }
  39923. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  39924. {
  39925. int tokenEnd = getTextIndexAt (e.x, e.y);
  39926. int tokenStart = tokenEnd;
  39927. if (e.getNumberOfClicks() > 3)
  39928. {
  39929. tokenStart = 0;
  39930. tokenEnd = getTotalNumChars();
  39931. }
  39932. else
  39933. {
  39934. const String t (getText());
  39935. const int totalLength = getTotalNumChars();
  39936. while (tokenEnd < totalLength)
  39937. {
  39938. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  39939. ++tokenEnd;
  39940. else
  39941. break;
  39942. }
  39943. tokenStart = tokenEnd;
  39944. while (tokenStart > 0)
  39945. {
  39946. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  39947. --tokenStart;
  39948. else
  39949. break;
  39950. }
  39951. if (e.getNumberOfClicks() > 2)
  39952. {
  39953. while (tokenEnd < totalLength)
  39954. {
  39955. if (t [tokenEnd] != T('\r') && t [tokenEnd] != T('\n'))
  39956. ++tokenEnd;
  39957. else
  39958. break;
  39959. }
  39960. while (tokenStart > 0)
  39961. {
  39962. if (t [tokenStart - 1] != T('\r') && t [tokenStart - 1] != T('\n'))
  39963. --tokenStart;
  39964. else
  39965. break;
  39966. }
  39967. }
  39968. }
  39969. moveCursorTo (tokenEnd, false);
  39970. moveCursorTo (tokenStart, true);
  39971. }
  39972. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39973. {
  39974. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  39975. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  39976. }
  39977. bool TextEditor::keyPressed (const KeyPress& key)
  39978. {
  39979. if (isReadOnly() && key != KeyPress (T('c'), ModifierKeys::commandModifier, 0))
  39980. return false;
  39981. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  39982. if (key.isKeyCode (KeyPress::leftKey)
  39983. || key.isKeyCode (KeyPress::upKey))
  39984. {
  39985. newTransaction();
  39986. int newPos;
  39987. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  39988. newPos = indexAtPosition (cursorX, cursorY - 1);
  39989. else if (moveInWholeWordSteps)
  39990. newPos = findWordBreakBefore (getCaretPosition());
  39991. else
  39992. newPos = getCaretPosition() - 1;
  39993. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  39994. }
  39995. else if (key.isKeyCode (KeyPress::rightKey)
  39996. || key.isKeyCode (KeyPress::downKey))
  39997. {
  39998. newTransaction();
  39999. int newPos;
  40000. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  40001. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  40002. else if (moveInWholeWordSteps)
  40003. newPos = findWordBreakAfter (getCaretPosition());
  40004. else
  40005. newPos = getCaretPosition() + 1;
  40006. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  40007. }
  40008. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  40009. {
  40010. newTransaction();
  40011. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  40012. key.getModifiers().isShiftDown());
  40013. }
  40014. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  40015. {
  40016. newTransaction();
  40017. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  40018. key.getModifiers().isShiftDown());
  40019. }
  40020. else if (key.isKeyCode (KeyPress::homeKey))
  40021. {
  40022. newTransaction();
  40023. if (isMultiLine() && ! moveInWholeWordSteps)
  40024. moveCursorTo (indexAtPosition (0.0f, cursorY),
  40025. key.getModifiers().isShiftDown());
  40026. else
  40027. moveCursorTo (0, key.getModifiers().isShiftDown());
  40028. }
  40029. else if (key.isKeyCode (KeyPress::endKey))
  40030. {
  40031. newTransaction();
  40032. if (isMultiLine() && ! moveInWholeWordSteps)
  40033. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  40034. key.getModifiers().isShiftDown());
  40035. else
  40036. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  40037. }
  40038. else if (key.isKeyCode (KeyPress::backspaceKey))
  40039. {
  40040. if (moveInWholeWordSteps)
  40041. {
  40042. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  40043. }
  40044. else
  40045. {
  40046. if (selectionStart == selectionEnd && selectionStart > 0)
  40047. --selectionStart;
  40048. }
  40049. cut();
  40050. }
  40051. else if (key.isKeyCode (KeyPress::deleteKey))
  40052. {
  40053. if (key.getModifiers().isShiftDown())
  40054. copy();
  40055. if (selectionStart == selectionEnd
  40056. && selectionEnd < getTotalNumChars())
  40057. {
  40058. ++selectionEnd;
  40059. }
  40060. cut();
  40061. }
  40062. else if (key == KeyPress (T('c'), ModifierKeys::commandModifier, 0)
  40063. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  40064. {
  40065. newTransaction();
  40066. copy();
  40067. }
  40068. else if (key == KeyPress (T('x'), ModifierKeys::commandModifier, 0))
  40069. {
  40070. newTransaction();
  40071. copy();
  40072. cut();
  40073. }
  40074. else if (key == KeyPress (T('v'), ModifierKeys::commandModifier, 0)
  40075. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  40076. {
  40077. newTransaction();
  40078. paste();
  40079. }
  40080. else if (key == KeyPress (T('z'), ModifierKeys::commandModifier, 0))
  40081. {
  40082. newTransaction();
  40083. doUndoRedo (false);
  40084. }
  40085. else if (key == KeyPress (T('y'), ModifierKeys::commandModifier, 0))
  40086. {
  40087. newTransaction();
  40088. doUndoRedo (true);
  40089. }
  40090. else if (key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  40091. {
  40092. newTransaction();
  40093. moveCursorTo (getTotalNumChars(), false);
  40094. moveCursorTo (0, true);
  40095. }
  40096. else if (key == KeyPress::returnKey)
  40097. {
  40098. newTransaction();
  40099. if (returnKeyStartsNewLine)
  40100. insertTextAtCursor (T("\n"));
  40101. else
  40102. returnPressed();
  40103. }
  40104. else if (key.isKeyCode (KeyPress::escapeKey))
  40105. {
  40106. newTransaction();
  40107. moveCursorTo (getCaretPosition(), false);
  40108. escapePressed();
  40109. }
  40110. else if (key.getTextCharacter() >= ' '
  40111. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  40112. {
  40113. insertTextAtCursor (String::charToString (key.getTextCharacter()));
  40114. lastTransactionTime = Time::getApproximateMillisecondCounter();
  40115. }
  40116. else
  40117. {
  40118. return false;
  40119. }
  40120. return true;
  40121. }
  40122. bool TextEditor::keyStateChanged (const bool isKeyDown)
  40123. {
  40124. if (! isKeyDown)
  40125. return false;
  40126. #if JUCE_WIN32
  40127. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  40128. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  40129. #endif
  40130. // (overridden to avoid forwarding key events to the parent)
  40131. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  40132. }
  40133. const int baseMenuItemID = 0x7fff0000;
  40134. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  40135. {
  40136. const bool writable = ! isReadOnly();
  40137. if (passwordCharacter == 0)
  40138. {
  40139. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  40140. m.addItem (baseMenuItemID + 2, TRANS("copy"), selectionStart < selectionEnd);
  40141. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  40142. }
  40143. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  40144. m.addSeparator();
  40145. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  40146. m.addSeparator();
  40147. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  40148. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  40149. }
  40150. void TextEditor::performPopupMenuAction (const int menuItemID)
  40151. {
  40152. switch (menuItemID)
  40153. {
  40154. case baseMenuItemID + 1:
  40155. copy();
  40156. cut();
  40157. break;
  40158. case baseMenuItemID + 2:
  40159. copy();
  40160. break;
  40161. case baseMenuItemID + 3:
  40162. paste();
  40163. break;
  40164. case baseMenuItemID + 4:
  40165. cut();
  40166. break;
  40167. case baseMenuItemID + 5:
  40168. moveCursorTo (getTotalNumChars(), false);
  40169. moveCursorTo (0, true);
  40170. break;
  40171. case baseMenuItemID + 6:
  40172. doUndoRedo (false);
  40173. break;
  40174. case baseMenuItemID + 7:
  40175. doUndoRedo (true);
  40176. break;
  40177. default:
  40178. break;
  40179. }
  40180. }
  40181. void TextEditor::focusGained (FocusChangeType)
  40182. {
  40183. newTransaction();
  40184. caretFlashState = true;
  40185. if (selectAllTextWhenFocused)
  40186. {
  40187. moveCursorTo (0, false);
  40188. moveCursorTo (getTotalNumChars(), true);
  40189. }
  40190. repaint();
  40191. if (caretVisible)
  40192. textHolder->startTimer (flashSpeedIntervalMs);
  40193. ComponentPeer* const peer = getPeer();
  40194. if (peer != 0)
  40195. peer->textInputRequired (getScreenX() - peer->getScreenX(),
  40196. getScreenY() - peer->getScreenY());
  40197. }
  40198. void TextEditor::focusLost (FocusChangeType)
  40199. {
  40200. newTransaction();
  40201. wasFocused = false;
  40202. textHolder->stopTimer();
  40203. caretFlashState = false;
  40204. postCommandMessage (focusLossMessageId);
  40205. repaint();
  40206. }
  40207. void TextEditor::resized()
  40208. {
  40209. viewport->setBoundsInset (borderSize);
  40210. viewport->setSingleStepSizes (16, roundFloatToInt (currentFont.getHeight()));
  40211. updateTextHolderSize();
  40212. if (! isMultiLine())
  40213. {
  40214. scrollToMakeSureCursorIsVisible();
  40215. }
  40216. else
  40217. {
  40218. updateCaretPosition();
  40219. }
  40220. }
  40221. void TextEditor::handleCommandMessage (const int commandId)
  40222. {
  40223. const ComponentDeletionWatcher deletionChecker (this);
  40224. for (int i = listeners.size(); --i >= 0;)
  40225. {
  40226. TextEditorListener* const tl = (TextEditorListener*) listeners [i];
  40227. if (tl != 0)
  40228. {
  40229. switch (commandId)
  40230. {
  40231. case textChangeMessageId:
  40232. tl->textEditorTextChanged (*this);
  40233. break;
  40234. case returnKeyMessageId:
  40235. tl->textEditorReturnKeyPressed (*this);
  40236. break;
  40237. case escapeKeyMessageId:
  40238. tl->textEditorEscapeKeyPressed (*this);
  40239. break;
  40240. case focusLossMessageId:
  40241. tl->textEditorFocusLost (*this);
  40242. break;
  40243. default:
  40244. jassertfalse
  40245. break;
  40246. }
  40247. if (i > 0 && deletionChecker.hasBeenDeleted())
  40248. return;
  40249. }
  40250. }
  40251. }
  40252. void TextEditor::enablementChanged()
  40253. {
  40254. setMouseCursor (MouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  40255. : MouseCursor::IBeamCursor));
  40256. repaint();
  40257. }
  40258. void TextEditor::clearInternal (UndoManager* const um) throw()
  40259. {
  40260. remove (0, getTotalNumChars(), um, caretPosition);
  40261. }
  40262. void TextEditor::insert (const String& text,
  40263. const int insertIndex,
  40264. const Font& font,
  40265. const Colour& colour,
  40266. UndoManager* const um,
  40267. const int caretPositionToMoveTo) throw()
  40268. {
  40269. if (text.isNotEmpty())
  40270. {
  40271. if (um != 0)
  40272. {
  40273. um->perform (new TextEditorInsertAction (*this,
  40274. text,
  40275. insertIndex,
  40276. font,
  40277. colour,
  40278. caretPosition,
  40279. caretPositionToMoveTo));
  40280. }
  40281. else
  40282. {
  40283. repaintText (insertIndex, -1); // must do this before and after changing the data, in case
  40284. // a line gets moved due to word wrap
  40285. int index = 0;
  40286. int nextIndex = 0;
  40287. for (int i = 0; i < sections.size(); ++i)
  40288. {
  40289. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40290. if (insertIndex == index)
  40291. {
  40292. sections.insert (i, new UniformTextSection (text,
  40293. font, colour,
  40294. passwordCharacter));
  40295. break;
  40296. }
  40297. else if (insertIndex > index && insertIndex < nextIndex)
  40298. {
  40299. splitSection (i, insertIndex - index);
  40300. sections.insert (i + 1, new UniformTextSection (text,
  40301. font, colour,
  40302. passwordCharacter));
  40303. break;
  40304. }
  40305. index = nextIndex;
  40306. }
  40307. if (nextIndex == insertIndex)
  40308. sections.add (new UniformTextSection (text,
  40309. font, colour,
  40310. passwordCharacter));
  40311. coalesceSimilarSections();
  40312. totalNumChars = -1;
  40313. moveCursorTo (caretPositionToMoveTo, false);
  40314. repaintText (insertIndex, -1);
  40315. }
  40316. }
  40317. }
  40318. void TextEditor::reinsert (const int insertIndex,
  40319. const VoidArray& sectionsToInsert) throw()
  40320. {
  40321. int index = 0;
  40322. int nextIndex = 0;
  40323. for (int i = 0; i < sections.size(); ++i)
  40324. {
  40325. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40326. if (insertIndex == index)
  40327. {
  40328. for (int j = sectionsToInsert.size(); --j >= 0;)
  40329. sections.insert (i, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40330. break;
  40331. }
  40332. else if (insertIndex > index && insertIndex < nextIndex)
  40333. {
  40334. splitSection (i, insertIndex - index);
  40335. for (int j = sectionsToInsert.size(); --j >= 0;)
  40336. sections.insert (i + 1, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40337. break;
  40338. }
  40339. index = nextIndex;
  40340. }
  40341. if (nextIndex == insertIndex)
  40342. {
  40343. for (int j = 0; j < sectionsToInsert.size(); ++j)
  40344. sections.add (new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40345. }
  40346. coalesceSimilarSections();
  40347. totalNumChars = -1;
  40348. }
  40349. void TextEditor::remove (const int startIndex,
  40350. int endIndex,
  40351. UndoManager* const um,
  40352. const int caretPositionToMoveTo) throw()
  40353. {
  40354. if (endIndex > startIndex)
  40355. {
  40356. int index = 0;
  40357. for (int i = 0; i < sections.size(); ++i)
  40358. {
  40359. const int nextIndex = index + ((UniformTextSection*) sections[i])->getTotalLength();
  40360. if (startIndex > index && startIndex < nextIndex)
  40361. {
  40362. splitSection (i, startIndex - index);
  40363. --i;
  40364. }
  40365. else if (endIndex > index && endIndex < nextIndex)
  40366. {
  40367. splitSection (i, endIndex - index);
  40368. --i;
  40369. }
  40370. else
  40371. {
  40372. index = nextIndex;
  40373. if (index > endIndex)
  40374. break;
  40375. }
  40376. }
  40377. index = 0;
  40378. if (um != 0)
  40379. {
  40380. VoidArray removedSections;
  40381. for (int i = 0; i < sections.size(); ++i)
  40382. {
  40383. if (endIndex <= startIndex)
  40384. break;
  40385. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  40386. const int nextIndex = index + section->getTotalLength();
  40387. if (startIndex <= index && endIndex >= nextIndex)
  40388. removedSections.add (new UniformTextSection (*section));
  40389. index = nextIndex;
  40390. }
  40391. um->perform (new TextEditorRemoveAction (*this,
  40392. startIndex,
  40393. endIndex,
  40394. caretPosition,
  40395. caretPositionToMoveTo,
  40396. removedSections));
  40397. }
  40398. else
  40399. {
  40400. for (int i = 0; i < sections.size(); ++i)
  40401. {
  40402. if (endIndex <= startIndex)
  40403. break;
  40404. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  40405. const int nextIndex = index + section->getTotalLength();
  40406. if (startIndex <= index && endIndex >= nextIndex)
  40407. {
  40408. sections.remove(i);
  40409. endIndex -= (nextIndex - index);
  40410. section->clear();
  40411. delete section;
  40412. --i;
  40413. }
  40414. else
  40415. {
  40416. index = nextIndex;
  40417. }
  40418. }
  40419. coalesceSimilarSections();
  40420. totalNumChars = -1;
  40421. moveCursorTo (caretPositionToMoveTo, false);
  40422. repaintText (startIndex, -1);
  40423. }
  40424. }
  40425. }
  40426. const String TextEditor::getText() const throw()
  40427. {
  40428. String t;
  40429. for (int i = 0; i < sections.size(); ++i)
  40430. t += ((const UniformTextSection*) sections.getUnchecked(i))->getAllText();
  40431. return t;
  40432. }
  40433. const String TextEditor::getTextSubstring (const int startCharacter, const int endCharacter) const throw()
  40434. {
  40435. String t;
  40436. int index = 0;
  40437. for (int i = 0; i < sections.size(); ++i)
  40438. {
  40439. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked(i);
  40440. const int nextIndex = index + s->getTotalLength();
  40441. if (startCharacter < nextIndex)
  40442. {
  40443. if (endCharacter <= index)
  40444. break;
  40445. const int start = jmax (index, startCharacter);
  40446. t += s->getTextSubstring (start - index, endCharacter - index);
  40447. }
  40448. index = nextIndex;
  40449. }
  40450. return t;
  40451. }
  40452. const String TextEditor::getHighlightedText() const throw()
  40453. {
  40454. return getTextSubstring (getHighlightedRegionStart(),
  40455. getHighlightedRegionStart() + getHighlightedRegionLength());
  40456. }
  40457. int TextEditor::getTotalNumChars() throw()
  40458. {
  40459. if (totalNumChars < 0)
  40460. {
  40461. totalNumChars = 0;
  40462. for (int i = sections.size(); --i >= 0;)
  40463. totalNumChars += ((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40464. }
  40465. return totalNumChars;
  40466. }
  40467. bool TextEditor::isEmpty() const throw()
  40468. {
  40469. if (totalNumChars != 0)
  40470. {
  40471. for (int i = sections.size(); --i >= 0;)
  40472. if (((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength() > 0)
  40473. return false;
  40474. }
  40475. return true;
  40476. }
  40477. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const throw()
  40478. {
  40479. const float wordWrapWidth = getWordWrapWidth();
  40480. if (wordWrapWidth > 0 && sections.size() > 0)
  40481. {
  40482. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  40483. i.getCharPosition (index, cx, cy, lineHeight);
  40484. }
  40485. else
  40486. {
  40487. cx = cy = 0;
  40488. lineHeight = currentFont.getHeight();
  40489. }
  40490. }
  40491. int TextEditor::indexAtPosition (const float x, const float y) throw()
  40492. {
  40493. const float wordWrapWidth = getWordWrapWidth();
  40494. if (wordWrapWidth > 0)
  40495. {
  40496. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  40497. while (i.next())
  40498. {
  40499. if (i.lineY + getHeight() > y)
  40500. i.updateLineHeight();
  40501. if (i.lineY + i.lineHeight > y)
  40502. {
  40503. if (i.lineY > y)
  40504. return jmax (0, i.indexInText - 1);
  40505. if (i.atomX >= x)
  40506. return i.indexInText;
  40507. if (x < i.atomRight)
  40508. return i.xToIndex (x);
  40509. }
  40510. }
  40511. }
  40512. return getTotalNumChars();
  40513. }
  40514. static int getCharacterCategory (const tchar character) throw()
  40515. {
  40516. return CharacterFunctions::isLetterOrDigit (character)
  40517. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  40518. }
  40519. int TextEditor::findWordBreakAfter (const int position) const throw()
  40520. {
  40521. const String t (getTextSubstring (position, position + 512));
  40522. const int totalLength = t.length();
  40523. int i = 0;
  40524. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  40525. ++i;
  40526. const int type = getCharacterCategory (t[i]);
  40527. while (i < totalLength && type == getCharacterCategory (t[i]))
  40528. ++i;
  40529. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  40530. ++i;
  40531. return position + i;
  40532. }
  40533. int TextEditor::findWordBreakBefore (const int position) const throw()
  40534. {
  40535. if (position <= 0)
  40536. return 0;
  40537. const int startOfBuffer = jmax (0, position - 512);
  40538. const String t (getTextSubstring (startOfBuffer, position));
  40539. int i = position - startOfBuffer;
  40540. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  40541. --i;
  40542. if (i > 0)
  40543. {
  40544. const int type = getCharacterCategory (t [i - 1]);
  40545. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  40546. --i;
  40547. }
  40548. jassert (startOfBuffer + i >= 0);
  40549. return startOfBuffer + i;
  40550. }
  40551. void TextEditor::splitSection (const int sectionIndex,
  40552. const int charToSplitAt) throw()
  40553. {
  40554. jassert (sections[sectionIndex] != 0);
  40555. sections.insert (sectionIndex + 1,
  40556. ((UniformTextSection*) sections.getUnchecked (sectionIndex))
  40557. ->split (charToSplitAt, passwordCharacter));
  40558. }
  40559. void TextEditor::coalesceSimilarSections() throw()
  40560. {
  40561. for (int i = 0; i < sections.size() - 1; ++i)
  40562. {
  40563. UniformTextSection* const s1 = (UniformTextSection*) (sections.getUnchecked (i));
  40564. UniformTextSection* const s2 = (UniformTextSection*) (sections.getUnchecked (i + 1));
  40565. if (s1->font == s2->font
  40566. && s1->colour == s2->colour)
  40567. {
  40568. s1->append (*s2, passwordCharacter);
  40569. sections.remove (i + 1);
  40570. delete s2;
  40571. --i;
  40572. }
  40573. }
  40574. }
  40575. END_JUCE_NAMESPACE
  40576. /********* End of inlined file: juce_TextEditor.cpp *********/
  40577. /********* Start of inlined file: juce_Toolbar.cpp *********/
  40578. BEGIN_JUCE_NAMESPACE
  40579. const tchar* const Toolbar::toolbarDragDescriptor = T("_toolbarItem_");
  40580. class ToolbarSpacerComp : public ToolbarItemComponent
  40581. {
  40582. public:
  40583. ToolbarSpacerComp (const int itemId, const float fixedSize_, const bool drawBar_)
  40584. : ToolbarItemComponent (itemId, String::empty, false),
  40585. fixedSize (fixedSize_),
  40586. drawBar (drawBar_)
  40587. {
  40588. }
  40589. ~ToolbarSpacerComp()
  40590. {
  40591. }
  40592. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  40593. int& preferredSize, int& minSize, int& maxSize)
  40594. {
  40595. if (fixedSize <= 0)
  40596. {
  40597. preferredSize = toolbarThickness * 2;
  40598. minSize = 4;
  40599. maxSize = 32768;
  40600. }
  40601. else
  40602. {
  40603. maxSize = roundFloatToInt (toolbarThickness * fixedSize);
  40604. minSize = drawBar ? maxSize : jmin (4, maxSize);
  40605. preferredSize = maxSize;
  40606. if (getEditingMode() == editableOnPalette)
  40607. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  40608. }
  40609. return true;
  40610. }
  40611. void paintButtonArea (Graphics&, int, int, bool, bool)
  40612. {
  40613. }
  40614. void contentAreaChanged (const Rectangle&)
  40615. {
  40616. }
  40617. int getResizeOrder() const throw()
  40618. {
  40619. return fixedSize <= 0 ? 0 : 1;
  40620. }
  40621. void paint (Graphics& g)
  40622. {
  40623. const int w = getWidth();
  40624. const int h = getHeight();
  40625. if (drawBar)
  40626. {
  40627. g.setColour (findColour (Toolbar::separatorColourId, true));
  40628. const float thickness = 0.2f;
  40629. if (isToolbarVertical())
  40630. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  40631. else
  40632. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  40633. }
  40634. if (getEditingMode() != normalMode && ! drawBar)
  40635. {
  40636. g.setColour (findColour (Toolbar::separatorColourId, true));
  40637. const int indentX = jmin (2, (w - 3) / 2);
  40638. const int indentY = jmin (2, (h - 3) / 2);
  40639. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  40640. if (fixedSize <= 0)
  40641. {
  40642. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  40643. if (isToolbarVertical())
  40644. {
  40645. x1 = w * 0.5f;
  40646. y1 = h * 0.4f;
  40647. x2 = x1;
  40648. y2 = indentX * 2.0f;
  40649. x3 = x1;
  40650. y3 = h * 0.6f;
  40651. x4 = x1;
  40652. y4 = h - y2;
  40653. hw = w * 0.15f;
  40654. hl = w * 0.2f;
  40655. }
  40656. else
  40657. {
  40658. x1 = w * 0.4f;
  40659. y1 = h * 0.5f;
  40660. x2 = indentX * 2.0f;
  40661. y2 = y1;
  40662. x3 = w * 0.6f;
  40663. y3 = y1;
  40664. x4 = w - x2;
  40665. y4 = y1;
  40666. hw = h * 0.15f;
  40667. hl = h * 0.2f;
  40668. }
  40669. Path p;
  40670. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  40671. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  40672. g.fillPath (p);
  40673. }
  40674. }
  40675. }
  40676. juce_UseDebuggingNewOperator
  40677. private:
  40678. const float fixedSize;
  40679. const bool drawBar;
  40680. ToolbarSpacerComp (const ToolbarSpacerComp&);
  40681. const ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  40682. };
  40683. class MissingItemsComponent : public PopupMenuCustomComponent
  40684. {
  40685. public:
  40686. MissingItemsComponent (Toolbar& owner_, const int height_)
  40687. : PopupMenuCustomComponent (true),
  40688. owner (owner_),
  40689. height (height_)
  40690. {
  40691. for (int i = owner_.items.size(); --i >= 0;)
  40692. {
  40693. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  40694. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  40695. {
  40696. oldIndexes.insert (0, i);
  40697. addAndMakeVisible (tc, 0);
  40698. }
  40699. }
  40700. layout (400);
  40701. }
  40702. ~MissingItemsComponent()
  40703. {
  40704. // deleting the toolbar while its menu it open??
  40705. jassert (owner.isValidComponent());
  40706. for (int i = 0; i < getNumChildComponents(); ++i)
  40707. {
  40708. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  40709. if (tc != 0)
  40710. {
  40711. tc->setVisible (false);
  40712. const int index = oldIndexes.remove (i);
  40713. owner.addChildComponent (tc, index);
  40714. --i;
  40715. }
  40716. }
  40717. owner.resized();
  40718. }
  40719. void layout (const int preferredWidth)
  40720. {
  40721. const int indent = 8;
  40722. int x = indent;
  40723. int y = indent;
  40724. int maxX = 0;
  40725. for (int i = 0; i < getNumChildComponents(); ++i)
  40726. {
  40727. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  40728. if (tc != 0)
  40729. {
  40730. int preferredSize = 1, minSize = 1, maxSize = 1;
  40731. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  40732. {
  40733. if (x + preferredSize > preferredWidth && x > indent)
  40734. {
  40735. x = indent;
  40736. y += height;
  40737. }
  40738. tc->setBounds (x, y, preferredSize, height);
  40739. x += preferredSize;
  40740. maxX = jmax (maxX, x);
  40741. }
  40742. }
  40743. }
  40744. setSize (maxX + 8, y + height + 8);
  40745. }
  40746. void getIdealSize (int& idealWidth, int& idealHeight)
  40747. {
  40748. idealWidth = getWidth();
  40749. idealHeight = getHeight();
  40750. }
  40751. juce_UseDebuggingNewOperator
  40752. private:
  40753. Toolbar& owner;
  40754. const int height;
  40755. Array <int> oldIndexes;
  40756. MissingItemsComponent (const MissingItemsComponent&);
  40757. const MissingItemsComponent& operator= (const MissingItemsComponent&);
  40758. };
  40759. Toolbar::Toolbar()
  40760. : vertical (false),
  40761. isEditingActive (false),
  40762. toolbarStyle (Toolbar::iconsOnly)
  40763. {
  40764. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  40765. missingItemsButton->setAlwaysOnTop (true);
  40766. missingItemsButton->addButtonListener (this);
  40767. }
  40768. Toolbar::~Toolbar()
  40769. {
  40770. animator.cancelAllAnimations (true);
  40771. deleteAllChildren();
  40772. }
  40773. void Toolbar::setVertical (const bool shouldBeVertical)
  40774. {
  40775. if (vertical != shouldBeVertical)
  40776. {
  40777. vertical = shouldBeVertical;
  40778. resized();
  40779. }
  40780. }
  40781. void Toolbar::clear()
  40782. {
  40783. for (int i = items.size(); --i >= 0;)
  40784. {
  40785. ToolbarItemComponent* const tc = items.getUnchecked(i);
  40786. items.remove (i);
  40787. delete tc;
  40788. }
  40789. resized();
  40790. }
  40791. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  40792. {
  40793. if (itemId == ToolbarItemFactory::separatorBarId)
  40794. return new ToolbarSpacerComp (itemId, 0.1f, true);
  40795. else if (itemId == ToolbarItemFactory::spacerId)
  40796. return new ToolbarSpacerComp (itemId, 0.5f, false);
  40797. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  40798. return new ToolbarSpacerComp (itemId, 0, false);
  40799. return factory.createItem (itemId);
  40800. }
  40801. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  40802. const int itemId,
  40803. const int insertIndex)
  40804. {
  40805. // An ID can't be zero - this might indicate a mistake somewhere?
  40806. jassert (itemId != 0);
  40807. ToolbarItemComponent* const tc = createItem (factory, itemId);
  40808. if (tc != 0)
  40809. {
  40810. #ifdef JUCE_DEBUG
  40811. Array <int> allowedIds;
  40812. factory.getAllToolbarItemIds (allowedIds);
  40813. // If your factory can create an item for a given ID, it must also return
  40814. // that ID from its getAllToolbarItemIds() method!
  40815. jassert (allowedIds.contains (itemId));
  40816. #endif
  40817. items.insert (insertIndex, tc);
  40818. addAndMakeVisible (tc, insertIndex);
  40819. }
  40820. }
  40821. void Toolbar::addItem (ToolbarItemFactory& factory,
  40822. const int itemId,
  40823. const int insertIndex)
  40824. {
  40825. addItemInternal (factory, itemId, insertIndex);
  40826. resized();
  40827. }
  40828. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  40829. {
  40830. Array <int> ids;
  40831. factoryToUse.getDefaultItemSet (ids);
  40832. clear();
  40833. for (int i = 0; i < ids.size(); ++i)
  40834. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  40835. resized();
  40836. }
  40837. void Toolbar::removeToolbarItem (const int itemIndex)
  40838. {
  40839. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  40840. if (tc != 0)
  40841. {
  40842. items.removeValue (tc);
  40843. delete tc;
  40844. resized();
  40845. }
  40846. }
  40847. int Toolbar::getNumItems() const throw()
  40848. {
  40849. return items.size();
  40850. }
  40851. int Toolbar::getItemId (const int itemIndex) const throw()
  40852. {
  40853. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  40854. return tc != 0 ? tc->getItemId() : 0;
  40855. }
  40856. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  40857. {
  40858. return items [itemIndex];
  40859. }
  40860. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  40861. {
  40862. for (;;)
  40863. {
  40864. index += delta;
  40865. ToolbarItemComponent* const tc = getItemComponent (index);
  40866. if (tc == 0)
  40867. break;
  40868. if (tc->isActive)
  40869. return tc;
  40870. }
  40871. return 0;
  40872. }
  40873. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  40874. {
  40875. if (toolbarStyle != newStyle)
  40876. {
  40877. toolbarStyle = newStyle;
  40878. updateAllItemPositions (false);
  40879. }
  40880. }
  40881. const String Toolbar::toString() const
  40882. {
  40883. String s (T("TB:"));
  40884. for (int i = 0; i < getNumItems(); ++i)
  40885. s << getItemId(i) << T(' ');
  40886. return s.trimEnd();
  40887. }
  40888. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  40889. const String& savedVersion)
  40890. {
  40891. if (! savedVersion.startsWith (T("TB:")))
  40892. return false;
  40893. StringArray tokens;
  40894. tokens.addTokens (savedVersion.substring (3), false);
  40895. clear();
  40896. for (int i = 0; i < tokens.size(); ++i)
  40897. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  40898. resized();
  40899. return true;
  40900. }
  40901. void Toolbar::paint (Graphics& g)
  40902. {
  40903. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  40904. }
  40905. int Toolbar::getThickness() const throw()
  40906. {
  40907. return vertical ? getWidth() : getHeight();
  40908. }
  40909. int Toolbar::getLength() const throw()
  40910. {
  40911. return vertical ? getHeight() : getWidth();
  40912. }
  40913. void Toolbar::setEditingActive (const bool active)
  40914. {
  40915. if (isEditingActive != active)
  40916. {
  40917. isEditingActive = active;
  40918. updateAllItemPositions (false);
  40919. }
  40920. }
  40921. void Toolbar::resized()
  40922. {
  40923. updateAllItemPositions (false);
  40924. }
  40925. void Toolbar::updateAllItemPositions (const bool animate)
  40926. {
  40927. if (getWidth() > 0 && getHeight() > 0)
  40928. {
  40929. StretchableObjectResizer resizer;
  40930. int i;
  40931. for (i = 0; i < items.size(); ++i)
  40932. {
  40933. ToolbarItemComponent* const tc = items.getUnchecked(i);
  40934. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  40935. : ToolbarItemComponent::normalMode);
  40936. tc->setStyle (toolbarStyle);
  40937. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  40938. int preferredSize = 1, minSize = 1, maxSize = 1;
  40939. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  40940. preferredSize, minSize, maxSize))
  40941. {
  40942. tc->isActive = true;
  40943. resizer.addItem (preferredSize, minSize, maxSize,
  40944. spacer != 0 ? spacer->getResizeOrder() : 2);
  40945. }
  40946. else
  40947. {
  40948. tc->isActive = false;
  40949. tc->setVisible (false);
  40950. }
  40951. }
  40952. resizer.resizeToFit (getLength());
  40953. int totalLength = 0;
  40954. for (i = 0; i < resizer.getNumItems(); ++i)
  40955. totalLength += (int) resizer.getItemSize (i);
  40956. const bool itemsOffTheEnd = totalLength > getLength();
  40957. const int extrasButtonSize = getThickness() / 2;
  40958. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  40959. missingItemsButton->setVisible (itemsOffTheEnd);
  40960. missingItemsButton->setEnabled (! isEditingActive);
  40961. if (vertical)
  40962. missingItemsButton->setCentrePosition (getWidth() / 2,
  40963. getHeight() - 4 - extrasButtonSize / 2);
  40964. else
  40965. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  40966. getHeight() / 2);
  40967. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  40968. : missingItemsButton->getX()) - 4
  40969. : getLength();
  40970. int pos = 0, activeIndex = 0;
  40971. for (i = 0; i < items.size(); ++i)
  40972. {
  40973. ToolbarItemComponent* const tc = items.getUnchecked(i);
  40974. if (tc->isActive)
  40975. {
  40976. const int size = (int) resizer.getItemSize (activeIndex++);
  40977. Rectangle newBounds;
  40978. if (vertical)
  40979. newBounds.setBounds (0, pos, getWidth(), size);
  40980. else
  40981. newBounds.setBounds (pos, 0, size, getHeight());
  40982. if (animate)
  40983. {
  40984. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  40985. }
  40986. else
  40987. {
  40988. animator.cancelAnimation (tc, false);
  40989. tc->setBounds (newBounds);
  40990. }
  40991. pos += size;
  40992. tc->setVisible (pos <= maxLength
  40993. && ((! tc->isBeingDragged)
  40994. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  40995. }
  40996. }
  40997. }
  40998. }
  40999. void Toolbar::buttonClicked (Button*)
  41000. {
  41001. jassert (missingItemsButton->isShowing());
  41002. if (missingItemsButton->isShowing())
  41003. {
  41004. PopupMenu m;
  41005. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  41006. m.showAt (missingItemsButton);
  41007. }
  41008. }
  41009. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  41010. Component* /*sourceComponent*/)
  41011. {
  41012. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  41013. }
  41014. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  41015. {
  41016. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  41017. if (tc != 0)
  41018. {
  41019. if (getNumItems() == 0)
  41020. {
  41021. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  41022. {
  41023. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  41024. if (palette != 0)
  41025. palette->replaceComponent (tc);
  41026. }
  41027. else
  41028. {
  41029. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  41030. }
  41031. items.add (tc);
  41032. addChildComponent (tc);
  41033. updateAllItemPositions (false);
  41034. }
  41035. else
  41036. {
  41037. for (int i = getNumItems(); --i >= 0;)
  41038. {
  41039. int currentIndex = getIndexOfChildComponent (tc);
  41040. if (currentIndex < 0)
  41041. {
  41042. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  41043. {
  41044. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  41045. if (palette != 0)
  41046. palette->replaceComponent (tc);
  41047. }
  41048. else
  41049. {
  41050. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  41051. }
  41052. items.add (tc);
  41053. addChildComponent (tc);
  41054. currentIndex = getIndexOfChildComponent (tc);
  41055. updateAllItemPositions (true);
  41056. }
  41057. int newIndex = currentIndex;
  41058. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  41059. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  41060. const Rectangle current (animator.getComponentDestination (getChildComponent (newIndex)));
  41061. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  41062. if (prev != 0)
  41063. {
  41064. const Rectangle previousPos (animator.getComponentDestination (prev));
  41065. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  41066. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  41067. {
  41068. newIndex = getIndexOfChildComponent (prev);
  41069. }
  41070. }
  41071. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  41072. if (next != 0)
  41073. {
  41074. const Rectangle nextPos (animator.getComponentDestination (next));
  41075. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  41076. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  41077. {
  41078. newIndex = getIndexOfChildComponent (next) + 1;
  41079. }
  41080. }
  41081. if (newIndex != currentIndex)
  41082. {
  41083. items.removeValue (tc);
  41084. removeChildComponent (tc);
  41085. addChildComponent (tc, newIndex);
  41086. items.insert (newIndex, tc);
  41087. updateAllItemPositions (true);
  41088. }
  41089. else
  41090. {
  41091. break;
  41092. }
  41093. }
  41094. }
  41095. }
  41096. }
  41097. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  41098. {
  41099. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  41100. if (tc != 0)
  41101. {
  41102. if (isParentOf (tc))
  41103. {
  41104. items.removeValue (tc);
  41105. removeChildComponent (tc);
  41106. updateAllItemPositions (true);
  41107. }
  41108. }
  41109. }
  41110. void Toolbar::itemDropped (const String&, Component*, int, int)
  41111. {
  41112. }
  41113. void Toolbar::mouseDown (const MouseEvent& e)
  41114. {
  41115. if (e.mods.isPopupMenu())
  41116. {
  41117. }
  41118. }
  41119. class ToolbarCustomisationDialog : public DialogWindow
  41120. {
  41121. public:
  41122. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  41123. Toolbar* const toolbar_,
  41124. const int optionFlags)
  41125. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  41126. toolbar (toolbar_)
  41127. {
  41128. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  41129. setResizable (true, true);
  41130. setResizeLimits (400, 300, 1500, 1000);
  41131. positionNearBar();
  41132. }
  41133. ~ToolbarCustomisationDialog()
  41134. {
  41135. setContentComponent (0, true);
  41136. }
  41137. void closeButtonPressed()
  41138. {
  41139. setVisible (false);
  41140. }
  41141. bool canModalEventBeSentToComponent (const Component* comp)
  41142. {
  41143. return toolbar->isParentOf (comp);
  41144. }
  41145. void positionNearBar()
  41146. {
  41147. const Rectangle screenSize (toolbar->getParentMonitorArea());
  41148. const int tbx = toolbar->getScreenX();
  41149. const int tby = toolbar->getScreenY();
  41150. const int gap = 8;
  41151. int x, y;
  41152. if (toolbar->isVertical())
  41153. {
  41154. y = tby;
  41155. if (tbx > screenSize.getCentreX())
  41156. x = tbx - getWidth() - gap;
  41157. else
  41158. x = tbx + toolbar->getWidth() + gap;
  41159. }
  41160. else
  41161. {
  41162. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  41163. if (tby > screenSize.getCentreY())
  41164. y = tby - getHeight() - gap;
  41165. else
  41166. y = tby + toolbar->getHeight() + gap;
  41167. }
  41168. setTopLeftPosition (x, y);
  41169. }
  41170. private:
  41171. Toolbar* const toolbar;
  41172. class CustomiserPanel : public Component,
  41173. private ComboBoxListener,
  41174. private ButtonListener
  41175. {
  41176. public:
  41177. CustomiserPanel (ToolbarItemFactory& factory_,
  41178. Toolbar* const toolbar_,
  41179. const int optionFlags)
  41180. : factory (factory_),
  41181. toolbar (toolbar_),
  41182. styleBox (0),
  41183. defaultButton (0)
  41184. {
  41185. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  41186. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  41187. | Toolbar::allowIconsWithTextChoice
  41188. | Toolbar::allowTextOnlyChoice)) != 0)
  41189. {
  41190. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  41191. styleBox->setEditableText (false);
  41192. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  41193. styleBox->addItem (TRANS("Show icons only"), 1);
  41194. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  41195. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  41196. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  41197. styleBox->addItem (TRANS("Show descriptions only"), 3);
  41198. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  41199. styleBox->setSelectedId (1);
  41200. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  41201. styleBox->setSelectedId (2);
  41202. else if (toolbar_->getStyle() == Toolbar::textOnly)
  41203. styleBox->setSelectedId (3);
  41204. styleBox->addListener (this);
  41205. }
  41206. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  41207. {
  41208. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  41209. defaultButton->addButtonListener (this);
  41210. }
  41211. addAndMakeVisible (instructions = new Label (String::empty,
  41212. TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\nItems on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")));
  41213. instructions->setFont (Font (13.0f));
  41214. setSize (500, 300);
  41215. }
  41216. ~CustomiserPanel()
  41217. {
  41218. deleteAllChildren();
  41219. }
  41220. void comboBoxChanged (ComboBox*)
  41221. {
  41222. if (styleBox->getSelectedId() == 1)
  41223. toolbar->setStyle (Toolbar::iconsOnly);
  41224. else if (styleBox->getSelectedId() == 2)
  41225. toolbar->setStyle (Toolbar::iconsWithText);
  41226. else if (styleBox->getSelectedId() == 3)
  41227. toolbar->setStyle (Toolbar::textOnly);
  41228. palette->resized(); // to make it update the styles
  41229. }
  41230. void buttonClicked (Button*)
  41231. {
  41232. toolbar->addDefaultItems (factory);
  41233. }
  41234. void paint (Graphics& g)
  41235. {
  41236. Colour background;
  41237. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  41238. if (dw != 0)
  41239. background = dw->getBackgroundColour();
  41240. g.setColour (background.contrasting().withAlpha (0.3f));
  41241. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  41242. }
  41243. void resized()
  41244. {
  41245. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  41246. if (styleBox != 0)
  41247. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  41248. if (defaultButton != 0)
  41249. {
  41250. defaultButton->changeWidthToFitText (22);
  41251. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  41252. }
  41253. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  41254. }
  41255. private:
  41256. ToolbarItemFactory& factory;
  41257. Toolbar* const toolbar;
  41258. Label* instructions;
  41259. ToolbarItemPalette* palette;
  41260. ComboBox* styleBox;
  41261. TextButton* defaultButton;
  41262. };
  41263. };
  41264. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  41265. {
  41266. setEditingActive (true);
  41267. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  41268. dw.runModalLoop();
  41269. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  41270. setEditingActive (false);
  41271. }
  41272. END_JUCE_NAMESPACE
  41273. /********* End of inlined file: juce_Toolbar.cpp *********/
  41274. /********* Start of inlined file: juce_ToolbarItemComponent.cpp *********/
  41275. BEGIN_JUCE_NAMESPACE
  41276. ToolbarItemFactory::ToolbarItemFactory()
  41277. {
  41278. }
  41279. ToolbarItemFactory::~ToolbarItemFactory()
  41280. {
  41281. }
  41282. class ItemDragAndDropOverlayComponent : public Component
  41283. {
  41284. public:
  41285. ItemDragAndDropOverlayComponent()
  41286. : isDragging (false)
  41287. {
  41288. setAlwaysOnTop (true);
  41289. setRepaintsOnMouseActivity (true);
  41290. setMouseCursor (MouseCursor::DraggingHandCursor);
  41291. }
  41292. ~ItemDragAndDropOverlayComponent()
  41293. {
  41294. }
  41295. void paint (Graphics& g)
  41296. {
  41297. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41298. if (isMouseOverOrDragging()
  41299. && tc != 0
  41300. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41301. {
  41302. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  41303. g.drawRect (0, 0, getWidth(), getHeight(),
  41304. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  41305. }
  41306. }
  41307. void mouseDown (const MouseEvent& e)
  41308. {
  41309. isDragging = false;
  41310. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41311. if (tc != 0)
  41312. {
  41313. tc->dragOffsetX = e.x;
  41314. tc->dragOffsetY = e.y;
  41315. }
  41316. }
  41317. void mouseDrag (const MouseEvent& e)
  41318. {
  41319. if (! (isDragging || e.mouseWasClicked()))
  41320. {
  41321. isDragging = true;
  41322. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  41323. if (dnd != 0)
  41324. {
  41325. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  41326. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41327. if (tc != 0)
  41328. {
  41329. tc->isBeingDragged = true;
  41330. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41331. tc->setVisible (false);
  41332. }
  41333. }
  41334. }
  41335. }
  41336. void mouseUp (const MouseEvent&)
  41337. {
  41338. isDragging = false;
  41339. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41340. if (tc != 0)
  41341. {
  41342. tc->isBeingDragged = false;
  41343. Toolbar* const tb = tc->getToolbar();
  41344. if (tb != 0)
  41345. tb->updateAllItemPositions (true);
  41346. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41347. delete tc;
  41348. }
  41349. }
  41350. void parentSizeChanged()
  41351. {
  41352. setBounds (0, 0, getParentWidth(), getParentHeight());
  41353. }
  41354. juce_UseDebuggingNewOperator
  41355. private:
  41356. bool isDragging;
  41357. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  41358. const ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  41359. };
  41360. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  41361. const String& labelText,
  41362. const bool isBeingUsedAsAButton_)
  41363. : Button (labelText),
  41364. itemId (itemId_),
  41365. mode (normalMode),
  41366. toolbarStyle (Toolbar::iconsOnly),
  41367. overlayComp (0),
  41368. dragOffsetX (0),
  41369. dragOffsetY (0),
  41370. isActive (true),
  41371. isBeingDragged (false),
  41372. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  41373. {
  41374. // Your item ID can't be 0!
  41375. jassert (itemId_ != 0);
  41376. }
  41377. ToolbarItemComponent::~ToolbarItemComponent()
  41378. {
  41379. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  41380. delete overlayComp;
  41381. }
  41382. Toolbar* ToolbarItemComponent::getToolbar() const
  41383. {
  41384. return dynamic_cast <Toolbar*> (getParentComponent());
  41385. }
  41386. bool ToolbarItemComponent::isToolbarVertical() const
  41387. {
  41388. const Toolbar* const t = getToolbar();
  41389. return t != 0 && t->isVertical();
  41390. }
  41391. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  41392. {
  41393. if (toolbarStyle != newStyle)
  41394. {
  41395. toolbarStyle = newStyle;
  41396. repaint();
  41397. resized();
  41398. }
  41399. }
  41400. void ToolbarItemComponent::paintButton (Graphics& g, bool isMouseOver, bool isMouseDown)
  41401. {
  41402. if (isBeingUsedAsAButton)
  41403. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  41404. isMouseOver, isMouseDown, *this);
  41405. if (toolbarStyle != Toolbar::iconsOnly)
  41406. {
  41407. const int indent = contentArea.getX();
  41408. int y = indent;
  41409. int h = getHeight() - indent * 2;
  41410. if (toolbarStyle == Toolbar::iconsWithText)
  41411. {
  41412. y = contentArea.getBottom() + indent / 2;
  41413. h -= contentArea.getHeight();
  41414. }
  41415. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  41416. getButtonText(), *this);
  41417. }
  41418. if (! contentArea.isEmpty())
  41419. {
  41420. g.saveState();
  41421. g.setOrigin (contentArea.getX(), contentArea.getY());
  41422. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  41423. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), isMouseOver, isMouseDown);
  41424. g.restoreState();
  41425. }
  41426. }
  41427. void ToolbarItemComponent::resized()
  41428. {
  41429. if (toolbarStyle != Toolbar::textOnly)
  41430. {
  41431. const int indent = jmin (proportionOfWidth (0.08f),
  41432. proportionOfHeight (0.08f));
  41433. contentArea = Rectangle (indent, indent,
  41434. getWidth() - indent * 2,
  41435. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  41436. : (getHeight() - indent * 2));
  41437. }
  41438. else
  41439. {
  41440. contentArea = Rectangle();
  41441. }
  41442. contentAreaChanged (contentArea);
  41443. }
  41444. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  41445. {
  41446. if (mode != newMode)
  41447. {
  41448. mode = newMode;
  41449. repaint();
  41450. if (mode == normalMode)
  41451. {
  41452. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  41453. delete overlayComp;
  41454. overlayComp = 0;
  41455. }
  41456. else if (overlayComp == 0)
  41457. {
  41458. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  41459. overlayComp->parentSizeChanged();
  41460. }
  41461. resized();
  41462. }
  41463. }
  41464. END_JUCE_NAMESPACE
  41465. /********* End of inlined file: juce_ToolbarItemComponent.cpp *********/
  41466. /********* Start of inlined file: juce_ToolbarItemPalette.cpp *********/
  41467. BEGIN_JUCE_NAMESPACE
  41468. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  41469. Toolbar* const toolbar_)
  41470. : factory (factory_),
  41471. toolbar (toolbar_)
  41472. {
  41473. Component* const itemHolder = new Component();
  41474. Array <int> allIds;
  41475. factory_.getAllToolbarItemIds (allIds);
  41476. for (int i = 0; i < allIds.size(); ++i)
  41477. {
  41478. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  41479. jassert (tc != 0);
  41480. if (tc != 0)
  41481. {
  41482. itemHolder->addAndMakeVisible (tc);
  41483. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  41484. }
  41485. }
  41486. viewport = new Viewport();
  41487. viewport->setViewedComponent (itemHolder);
  41488. addAndMakeVisible (viewport);
  41489. }
  41490. ToolbarItemPalette::~ToolbarItemPalette()
  41491. {
  41492. viewport->getViewedComponent()->deleteAllChildren();
  41493. deleteAllChildren();
  41494. }
  41495. void ToolbarItemPalette::resized()
  41496. {
  41497. viewport->setBoundsInset (BorderSize (1));
  41498. Component* const itemHolder = viewport->getViewedComponent();
  41499. const int indent = 8;
  41500. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  41501. const int height = toolbar->getThickness();
  41502. int x = indent;
  41503. int y = indent;
  41504. int maxX = 0;
  41505. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  41506. {
  41507. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  41508. if (tc != 0)
  41509. {
  41510. tc->setStyle (toolbar->getStyle());
  41511. int preferredSize = 1, minSize = 1, maxSize = 1;
  41512. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  41513. {
  41514. if (x + preferredSize > preferredWidth && x > indent)
  41515. {
  41516. x = indent;
  41517. y += height;
  41518. }
  41519. tc->setBounds (x, y, preferredSize, height);
  41520. x += preferredSize + 8;
  41521. maxX = jmax (maxX, x);
  41522. }
  41523. }
  41524. }
  41525. itemHolder->setSize (maxX, y + height + 8);
  41526. }
  41527. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  41528. {
  41529. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  41530. jassert (tc != 0);
  41531. if (tc != 0)
  41532. {
  41533. tc->setBounds (comp->getBounds());
  41534. tc->setStyle (toolbar->getStyle());
  41535. tc->setEditingMode (comp->getEditingMode());
  41536. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  41537. }
  41538. }
  41539. END_JUCE_NAMESPACE
  41540. /********* End of inlined file: juce_ToolbarItemPalette.cpp *********/
  41541. /********* Start of inlined file: juce_TreeView.cpp *********/
  41542. BEGIN_JUCE_NAMESPACE
  41543. class TreeViewContentComponent : public Component,
  41544. public TooltipClient
  41545. {
  41546. public:
  41547. TreeViewContentComponent (TreeView* const owner_)
  41548. : owner (owner_),
  41549. buttonUnderMouse (0),
  41550. isDragging (false)
  41551. {
  41552. }
  41553. ~TreeViewContentComponent()
  41554. {
  41555. deleteAllChildren();
  41556. }
  41557. void mouseDown (const MouseEvent& e)
  41558. {
  41559. updateButtonUnderMouse (e);
  41560. isDragging = false;
  41561. needSelectionOnMouseUp = false;
  41562. Rectangle pos;
  41563. TreeViewItem* const item = findItemAt (e.y, pos);
  41564. if (item == 0)
  41565. return;
  41566. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  41567. // as selection clicks)
  41568. if (e.x < pos.getX() && owner->openCloseButtonsVisible)
  41569. {
  41570. if (e.x >= pos.getX() - owner->getIndentSize())
  41571. item->setOpen (! item->isOpen());
  41572. // (clicks to the left of an open/close button are ignored)
  41573. }
  41574. else
  41575. {
  41576. // mouse-down inside the body of the item..
  41577. if (! owner->isMultiSelectEnabled())
  41578. item->setSelected (true, true);
  41579. else if (item->isSelected())
  41580. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  41581. else
  41582. selectBasedOnModifiers (item, e.mods);
  41583. MouseEvent e2 (e);
  41584. e2.x -= pos.getX();
  41585. e2.y -= pos.getY();
  41586. if (e2.x >= 0)
  41587. item->itemClicked (e2);
  41588. }
  41589. }
  41590. void mouseUp (const MouseEvent& e)
  41591. {
  41592. updateButtonUnderMouse (e);
  41593. if (needSelectionOnMouseUp && e.mouseWasClicked())
  41594. {
  41595. Rectangle pos;
  41596. TreeViewItem* const item = findItemAt (e.y, pos);
  41597. if (item != 0)
  41598. selectBasedOnModifiers (item, e.mods);
  41599. }
  41600. }
  41601. void mouseDoubleClick (const MouseEvent& e)
  41602. {
  41603. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  41604. {
  41605. Rectangle pos;
  41606. TreeViewItem* const item = findItemAt (e.y, pos);
  41607. if (item != 0 && (e.x >= pos.getX() || ! owner->openCloseButtonsVisible))
  41608. {
  41609. MouseEvent e2 (e);
  41610. e2.x -= pos.getX();
  41611. e2.y -= pos.getY();
  41612. item->itemDoubleClicked (e2);
  41613. }
  41614. }
  41615. }
  41616. void mouseDrag (const MouseEvent& e)
  41617. {
  41618. if (isEnabled() && ! (e.mouseWasClicked() || isDragging))
  41619. {
  41620. isDragging = true;
  41621. Rectangle pos;
  41622. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  41623. if (item != 0 && e.getMouseDownX() >= pos.getX())
  41624. {
  41625. const String dragDescription (item->getDragSourceDescription());
  41626. if (dragDescription.isNotEmpty())
  41627. {
  41628. DragAndDropContainer* const dragContainer
  41629. = DragAndDropContainer::findParentDragContainerFor (this);
  41630. if (dragContainer != 0)
  41631. {
  41632. pos.setSize (pos.getWidth(), item->itemHeight);
  41633. Image* dragImage = Component::createComponentSnapshot (pos, true);
  41634. dragImage->multiplyAllAlphas (0.6f);
  41635. dragContainer->startDragging (dragDescription, owner, dragImage, true);
  41636. }
  41637. else
  41638. {
  41639. // to be able to do a drag-and-drop operation, the treeview needs to
  41640. // be inside a component which is also a DragAndDropContainer.
  41641. jassertfalse
  41642. }
  41643. }
  41644. }
  41645. }
  41646. }
  41647. void mouseMove (const MouseEvent& e)
  41648. {
  41649. updateButtonUnderMouse (e);
  41650. }
  41651. void mouseExit (const MouseEvent& e)
  41652. {
  41653. updateButtonUnderMouse (e);
  41654. }
  41655. void paint (Graphics& g);
  41656. TreeViewItem* findItemAt (int y, Rectangle& itemPosition) const;
  41657. void updateComponents()
  41658. {
  41659. int xAdjust = 0, yAdjust = 0;
  41660. const int visibleTop = -getY();
  41661. const int visibleBottom = visibleTop + getParentHeight();
  41662. BitArray itemsToKeep;
  41663. TreeViewItem* item = owner->rootItem;
  41664. int y = -yAdjust;
  41665. while (item != 0 && y < visibleBottom)
  41666. {
  41667. y += item->itemHeight;
  41668. if (y >= visibleTop)
  41669. {
  41670. const int index = rowComponentIds.indexOf (item->uid);
  41671. if (index < 0)
  41672. {
  41673. Component* const comp = item->createItemComponent();
  41674. if (comp != 0)
  41675. {
  41676. addAndMakeVisible (comp);
  41677. itemsToKeep.setBit (rowComponentItems.size());
  41678. rowComponentItems.add (item);
  41679. rowComponentIds.add (item->uid);
  41680. rowComponents.add (comp);
  41681. }
  41682. }
  41683. else
  41684. {
  41685. itemsToKeep.setBit (index);
  41686. }
  41687. }
  41688. item = item->getNextVisibleItem (true);
  41689. }
  41690. for (int i = rowComponentItems.size(); --i >= 0;)
  41691. {
  41692. Component* const comp = (Component*) (rowComponents.getUnchecked(i));
  41693. bool keep = false;
  41694. if ((itemsToKeep[i] || (comp == Component::getComponentUnderMouse() && comp->isMouseButtonDown()))
  41695. && isParentOf (comp))
  41696. {
  41697. if (itemsToKeep[i])
  41698. {
  41699. const TreeViewItem* const item = (TreeViewItem*) rowComponentItems.getUnchecked(i);
  41700. Rectangle pos (item->getItemPosition (false));
  41701. pos.setSize (pos.getWidth() + xAdjust, item->itemHeight);
  41702. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  41703. {
  41704. keep = true;
  41705. comp->setBounds (pos);
  41706. }
  41707. }
  41708. else
  41709. {
  41710. comp->setSize (0, 0);
  41711. }
  41712. }
  41713. if (! keep)
  41714. {
  41715. delete comp;
  41716. rowComponents.remove (i);
  41717. rowComponentIds.remove (i);
  41718. rowComponentItems.remove (i);
  41719. }
  41720. }
  41721. }
  41722. void updateButtonUnderMouse (const MouseEvent& e)
  41723. {
  41724. TreeViewItem* newItem = 0;
  41725. if (owner->openCloseButtonsVisible)
  41726. {
  41727. Rectangle pos;
  41728. TreeViewItem* item = findItemAt (e.y, pos);
  41729. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner->getIndentSize())
  41730. {
  41731. newItem = item;
  41732. if (! newItem->mightContainSubItems())
  41733. newItem = 0;
  41734. }
  41735. }
  41736. if (buttonUnderMouse != newItem)
  41737. {
  41738. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  41739. {
  41740. const Rectangle r (buttonUnderMouse->getItemPosition (false));
  41741. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  41742. }
  41743. buttonUnderMouse = newItem;
  41744. if (buttonUnderMouse != 0)
  41745. {
  41746. const Rectangle r (buttonUnderMouse->getItemPosition (false));
  41747. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  41748. }
  41749. }
  41750. }
  41751. bool isMouseOverButton (TreeViewItem* item) const throw()
  41752. {
  41753. return item == buttonUnderMouse;
  41754. }
  41755. void resized()
  41756. {
  41757. owner->itemsChanged();
  41758. }
  41759. const String getTooltip()
  41760. {
  41761. int x, y;
  41762. getMouseXYRelative (x, y);
  41763. Rectangle pos;
  41764. TreeViewItem* const item = findItemAt (y, pos);
  41765. if (item != 0)
  41766. return item->getTooltip();
  41767. return owner->getTooltip();
  41768. }
  41769. juce_UseDebuggingNewOperator
  41770. private:
  41771. TreeView* const owner;
  41772. VoidArray rowComponentItems;
  41773. Array <int> rowComponentIds;
  41774. VoidArray rowComponents;
  41775. TreeViewItem* buttonUnderMouse;
  41776. bool isDragging, needSelectionOnMouseUp;
  41777. TreeViewContentComponent (const TreeViewContentComponent&);
  41778. const TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  41779. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  41780. {
  41781. TreeViewItem* firstSelected = 0;
  41782. if (modifiers.isShiftDown() && ((firstSelected = owner->getSelectedItem (0)) != 0))
  41783. {
  41784. TreeViewItem* const lastSelected = owner->getSelectedItem (owner->getNumSelectedItems() - 1);
  41785. jassert (lastSelected != 0);
  41786. int rowStart = firstSelected->getRowNumberInTree();
  41787. int rowEnd = lastSelected->getRowNumberInTree();
  41788. if (rowStart > rowEnd)
  41789. swapVariables (rowStart, rowEnd);
  41790. int ourRow = item->getRowNumberInTree();
  41791. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  41792. if (ourRow > otherEnd)
  41793. swapVariables (ourRow, otherEnd);
  41794. for (int i = ourRow; i <= otherEnd; ++i)
  41795. owner->getItemOnRow (i)->setSelected (true, false);
  41796. }
  41797. else
  41798. {
  41799. const bool cmd = modifiers.isCommandDown();
  41800. item->setSelected ((! cmd) || (! item->isSelected()), ! cmd);
  41801. }
  41802. }
  41803. bool containsItem (TreeViewItem* const item) const
  41804. {
  41805. for (int i = rowComponentItems.size(); --i >= 0;)
  41806. if ((TreeViewItem*) rowComponentItems.getUnchecked (i) == item)
  41807. return true;
  41808. return false;
  41809. }
  41810. };
  41811. class TreeViewport : public Viewport
  41812. {
  41813. public:
  41814. TreeViewport() throw() {}
  41815. ~TreeViewport() throw() {}
  41816. void updateComponents()
  41817. {
  41818. if (getViewedComponent() != 0)
  41819. ((TreeViewContentComponent*) getViewedComponent())->updateComponents();
  41820. repaint();
  41821. }
  41822. void visibleAreaChanged (int, int, int, int)
  41823. {
  41824. updateComponents();
  41825. }
  41826. juce_UseDebuggingNewOperator
  41827. private:
  41828. TreeViewport (const TreeViewport&);
  41829. const TreeViewport& operator= (const TreeViewport&);
  41830. };
  41831. TreeView::TreeView (const String& componentName)
  41832. : Component (componentName),
  41833. rootItem (0),
  41834. indentSize (24),
  41835. defaultOpenness (false),
  41836. needsRecalculating (true),
  41837. rootItemVisible (true),
  41838. multiSelectEnabled (false),
  41839. openCloseButtonsVisible (true)
  41840. {
  41841. addAndMakeVisible (viewport = new TreeViewport());
  41842. viewport->setViewedComponent (new TreeViewContentComponent (this));
  41843. viewport->setWantsKeyboardFocus (false);
  41844. setWantsKeyboardFocus (true);
  41845. }
  41846. TreeView::~TreeView()
  41847. {
  41848. if (rootItem != 0)
  41849. rootItem->setOwnerView (0);
  41850. deleteAllChildren();
  41851. }
  41852. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  41853. {
  41854. if (rootItem != newRootItem)
  41855. {
  41856. if (newRootItem != 0)
  41857. {
  41858. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  41859. if (newRootItem->ownerView != 0)
  41860. newRootItem->ownerView->setRootItem (0);
  41861. }
  41862. if (rootItem != 0)
  41863. rootItem->setOwnerView (0);
  41864. rootItem = newRootItem;
  41865. if (newRootItem != 0)
  41866. newRootItem->setOwnerView (this);
  41867. needsRecalculating = true;
  41868. handleAsyncUpdate();
  41869. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  41870. {
  41871. rootItem->setOpen (false); // force a re-open
  41872. rootItem->setOpen (true);
  41873. }
  41874. }
  41875. }
  41876. void TreeView::deleteRootItem()
  41877. {
  41878. TreeViewItem* const oldItem = rootItem;
  41879. setRootItem (0);
  41880. delete oldItem;
  41881. }
  41882. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  41883. {
  41884. rootItemVisible = shouldBeVisible;
  41885. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  41886. {
  41887. rootItem->setOpen (false); // force a re-open
  41888. rootItem->setOpen (true);
  41889. }
  41890. itemsChanged();
  41891. }
  41892. void TreeView::colourChanged()
  41893. {
  41894. setOpaque (findColour (backgroundColourId).isOpaque());
  41895. repaint();
  41896. }
  41897. void TreeView::setIndentSize (const int newIndentSize)
  41898. {
  41899. if (indentSize != newIndentSize)
  41900. {
  41901. indentSize = newIndentSize;
  41902. resized();
  41903. }
  41904. }
  41905. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  41906. {
  41907. if (defaultOpenness != isOpenByDefault)
  41908. {
  41909. defaultOpenness = isOpenByDefault;
  41910. itemsChanged();
  41911. }
  41912. }
  41913. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  41914. {
  41915. multiSelectEnabled = canMultiSelect;
  41916. }
  41917. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  41918. {
  41919. if (openCloseButtonsVisible != shouldBeVisible)
  41920. {
  41921. openCloseButtonsVisible = shouldBeVisible;
  41922. itemsChanged();
  41923. }
  41924. }
  41925. void TreeView::clearSelectedItems()
  41926. {
  41927. if (rootItem != 0)
  41928. rootItem->deselectAllRecursively();
  41929. }
  41930. int TreeView::getNumSelectedItems() const throw()
  41931. {
  41932. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  41933. }
  41934. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  41935. {
  41936. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  41937. }
  41938. int TreeView::getNumRowsInTree() const
  41939. {
  41940. if (rootItem != 0)
  41941. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  41942. return 0;
  41943. }
  41944. TreeViewItem* TreeView::getItemOnRow (int index) const
  41945. {
  41946. if (! rootItemVisible)
  41947. ++index;
  41948. if (rootItem != 0 && index >= 0)
  41949. return rootItem->getItemOnRow (index);
  41950. return 0;
  41951. }
  41952. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  41953. {
  41954. XmlElement* e = 0;
  41955. if (rootItem != 0)
  41956. {
  41957. e = rootItem->createXmlOpenness();
  41958. if (e != 0 && alsoIncludeScrollPosition)
  41959. e->setAttribute (T("scrollPos"), viewport->getViewPositionY());
  41960. }
  41961. return e;
  41962. }
  41963. void TreeView::restoreOpennessState (const XmlElement& newState)
  41964. {
  41965. if (rootItem != 0)
  41966. {
  41967. rootItem->restoreFromXml (newState);
  41968. if (newState.hasAttribute (T("scrollPos")))
  41969. viewport->setViewPosition (viewport->getViewPositionX(),
  41970. newState.getIntAttribute (T("scrollPos")));
  41971. }
  41972. }
  41973. void TreeView::paint (Graphics& g)
  41974. {
  41975. g.fillAll (findColour (backgroundColourId));
  41976. }
  41977. void TreeView::resized()
  41978. {
  41979. viewport->setBounds (0, 0, getWidth(), getHeight());
  41980. itemsChanged();
  41981. handleAsyncUpdate();
  41982. }
  41983. void TreeView::enablementChanged()
  41984. {
  41985. repaint();
  41986. }
  41987. void TreeView::moveSelectedRow (int delta)
  41988. {
  41989. if (delta == 0)
  41990. return;
  41991. int rowSelected = 0;
  41992. TreeViewItem* const firstSelected = getSelectedItem (0);
  41993. if (firstSelected != 0)
  41994. rowSelected = firstSelected->getRowNumberInTree();
  41995. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  41996. for (;;)
  41997. {
  41998. TreeViewItem* item = getItemOnRow (rowSelected);
  41999. if (item != 0)
  42000. {
  42001. if (! item->canBeSelected())
  42002. {
  42003. // if the row we want to highlight doesn't allow it, try skipping
  42004. // to the next item..
  42005. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  42006. rowSelected + (delta < 0 ? -1 : 1));
  42007. if (rowSelected != nextRowToTry)
  42008. {
  42009. rowSelected = nextRowToTry;
  42010. continue;
  42011. }
  42012. else
  42013. {
  42014. break;
  42015. }
  42016. }
  42017. item->setSelected (true, true);
  42018. scrollToKeepItemVisible (item);
  42019. }
  42020. break;
  42021. }
  42022. }
  42023. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  42024. {
  42025. if (item != 0 && item->ownerView == this)
  42026. {
  42027. handleAsyncUpdate();
  42028. item = item->getDeepestOpenParentItem();
  42029. int y = item->y;
  42030. int viewTop = viewport->getViewPositionY();
  42031. if (y < viewTop)
  42032. {
  42033. viewport->setViewPosition (viewport->getViewPositionX(), y);
  42034. }
  42035. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  42036. {
  42037. viewport->setViewPosition (viewport->getViewPositionX(),
  42038. (y + item->itemHeight) - viewport->getViewHeight());
  42039. }
  42040. }
  42041. }
  42042. bool TreeView::keyPressed (const KeyPress& key)
  42043. {
  42044. if (key.isKeyCode (KeyPress::upKey))
  42045. {
  42046. moveSelectedRow (-1);
  42047. }
  42048. else if (key.isKeyCode (KeyPress::downKey))
  42049. {
  42050. moveSelectedRow (1);
  42051. }
  42052. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  42053. {
  42054. if (rootItem != 0)
  42055. {
  42056. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  42057. if (key.isKeyCode (KeyPress::pageUpKey))
  42058. rowsOnScreen = -rowsOnScreen;
  42059. moveSelectedRow (rowsOnScreen);
  42060. }
  42061. }
  42062. else if (key.isKeyCode (KeyPress::homeKey))
  42063. {
  42064. moveSelectedRow (-0x3fffffff);
  42065. }
  42066. else if (key.isKeyCode (KeyPress::endKey))
  42067. {
  42068. moveSelectedRow (0x3fffffff);
  42069. }
  42070. else if (key.isKeyCode (KeyPress::returnKey))
  42071. {
  42072. TreeViewItem* const firstSelected = getSelectedItem (0);
  42073. if (firstSelected != 0)
  42074. firstSelected->setOpen (! firstSelected->isOpen());
  42075. }
  42076. else if (key.isKeyCode (KeyPress::leftKey))
  42077. {
  42078. TreeViewItem* const firstSelected = getSelectedItem (0);
  42079. if (firstSelected != 0)
  42080. {
  42081. if (firstSelected->isOpen())
  42082. {
  42083. firstSelected->setOpen (false);
  42084. }
  42085. else
  42086. {
  42087. TreeViewItem* parent = firstSelected->parentItem;
  42088. if ((! rootItemVisible) && parent == rootItem)
  42089. parent = 0;
  42090. if (parent != 0)
  42091. {
  42092. parent->setSelected (true, true);
  42093. scrollToKeepItemVisible (parent);
  42094. }
  42095. }
  42096. }
  42097. }
  42098. else if (key.isKeyCode (KeyPress::rightKey))
  42099. {
  42100. TreeViewItem* const firstSelected = getSelectedItem (0);
  42101. if (firstSelected != 0)
  42102. {
  42103. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  42104. moveSelectedRow (1);
  42105. else
  42106. firstSelected->setOpen (true);
  42107. }
  42108. }
  42109. else
  42110. {
  42111. return false;
  42112. }
  42113. return true;
  42114. }
  42115. void TreeView::itemsChanged() throw()
  42116. {
  42117. needsRecalculating = true;
  42118. repaint();
  42119. triggerAsyncUpdate();
  42120. }
  42121. void TreeView::handleAsyncUpdate()
  42122. {
  42123. if (needsRecalculating)
  42124. {
  42125. needsRecalculating = false;
  42126. const ScopedLock sl (nodeAlterationLock);
  42127. if (rootItem != 0)
  42128. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  42129. ((TreeViewport*) viewport)->updateComponents();
  42130. if (rootItem != 0)
  42131. {
  42132. viewport->getViewedComponent()
  42133. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  42134. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  42135. }
  42136. else
  42137. {
  42138. viewport->getViewedComponent()->setSize (0, 0);
  42139. }
  42140. }
  42141. }
  42142. void TreeViewContentComponent::paint (Graphics& g)
  42143. {
  42144. if (owner->rootItem != 0)
  42145. {
  42146. owner->handleAsyncUpdate();
  42147. if (! owner->rootItemVisible)
  42148. g.setOrigin (0, -owner->rootItem->itemHeight);
  42149. owner->rootItem->paintRecursively (g, getWidth());
  42150. }
  42151. }
  42152. TreeViewItem* TreeViewContentComponent::findItemAt (int y, Rectangle& itemPosition) const
  42153. {
  42154. if (owner->rootItem != 0)
  42155. {
  42156. owner->handleAsyncUpdate();
  42157. if (! owner->rootItemVisible)
  42158. y += owner->rootItem->itemHeight;
  42159. TreeViewItem* const ti = owner->rootItem->findItemRecursively (y);
  42160. if (ti != 0)
  42161. itemPosition = ti->getItemPosition (false);
  42162. return ti;
  42163. }
  42164. return 0;
  42165. }
  42166. #define opennessDefault 0
  42167. #define opennessClosed 1
  42168. #define opennessOpen 2
  42169. TreeViewItem::TreeViewItem()
  42170. : ownerView (0),
  42171. parentItem (0),
  42172. subItems (8),
  42173. y (0),
  42174. itemHeight (0),
  42175. totalHeight (0),
  42176. selected (false),
  42177. redrawNeeded (true),
  42178. drawLinesInside (true),
  42179. drawsInLeftMargin (false),
  42180. openness (opennessDefault)
  42181. {
  42182. static int nextUID = 0;
  42183. uid = nextUID++;
  42184. }
  42185. TreeViewItem::~TreeViewItem()
  42186. {
  42187. }
  42188. const String TreeViewItem::getUniqueName() const
  42189. {
  42190. return String::empty;
  42191. }
  42192. void TreeViewItem::itemOpennessChanged (bool)
  42193. {
  42194. }
  42195. int TreeViewItem::getNumSubItems() const throw()
  42196. {
  42197. return subItems.size();
  42198. }
  42199. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  42200. {
  42201. return subItems [index];
  42202. }
  42203. void TreeViewItem::clearSubItems()
  42204. {
  42205. if (subItems.size() > 0)
  42206. {
  42207. if (ownerView != 0)
  42208. {
  42209. const ScopedLock sl (ownerView->nodeAlterationLock);
  42210. subItems.clear();
  42211. treeHasChanged();
  42212. }
  42213. else
  42214. {
  42215. subItems.clear();
  42216. }
  42217. }
  42218. }
  42219. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  42220. {
  42221. if (newItem != 0)
  42222. {
  42223. newItem->parentItem = this;
  42224. newItem->setOwnerView (ownerView);
  42225. newItem->y = 0;
  42226. newItem->itemHeight = newItem->getItemHeight();
  42227. newItem->totalHeight = 0;
  42228. newItem->itemWidth = newItem->getItemWidth();
  42229. newItem->totalWidth = 0;
  42230. if (ownerView != 0)
  42231. {
  42232. const ScopedLock sl (ownerView->nodeAlterationLock);
  42233. subItems.insert (insertPosition, newItem);
  42234. treeHasChanged();
  42235. if (newItem->isOpen())
  42236. newItem->itemOpennessChanged (true);
  42237. }
  42238. else
  42239. {
  42240. subItems.insert (insertPosition, newItem);
  42241. if (newItem->isOpen())
  42242. newItem->itemOpennessChanged (true);
  42243. }
  42244. }
  42245. }
  42246. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  42247. {
  42248. if (ownerView != 0)
  42249. ownerView->nodeAlterationLock.enter();
  42250. if (((unsigned int) index) < (unsigned int) subItems.size())
  42251. {
  42252. subItems.remove (index, deleteItem);
  42253. treeHasChanged();
  42254. }
  42255. if (ownerView != 0)
  42256. ownerView->nodeAlterationLock.exit();
  42257. }
  42258. bool TreeViewItem::isOpen() const throw()
  42259. {
  42260. if (openness == opennessDefault)
  42261. return ownerView != 0 && ownerView->defaultOpenness;
  42262. else
  42263. return openness == opennessOpen;
  42264. }
  42265. void TreeViewItem::setOpen (const bool shouldBeOpen)
  42266. {
  42267. if (isOpen() != shouldBeOpen)
  42268. {
  42269. openness = shouldBeOpen ? opennessOpen
  42270. : opennessClosed;
  42271. treeHasChanged();
  42272. itemOpennessChanged (isOpen());
  42273. }
  42274. }
  42275. bool TreeViewItem::isSelected() const throw()
  42276. {
  42277. return selected;
  42278. }
  42279. void TreeViewItem::deselectAllRecursively()
  42280. {
  42281. setSelected (false, false);
  42282. for (int i = 0; i < subItems.size(); ++i)
  42283. subItems.getUnchecked(i)->deselectAllRecursively();
  42284. }
  42285. void TreeViewItem::setSelected (const bool shouldBeSelected,
  42286. const bool deselectOtherItemsFirst)
  42287. {
  42288. if (shouldBeSelected && ! canBeSelected())
  42289. return;
  42290. if (deselectOtherItemsFirst)
  42291. getTopLevelItem()->deselectAllRecursively();
  42292. if (shouldBeSelected != selected)
  42293. {
  42294. selected = shouldBeSelected;
  42295. if (ownerView != 0)
  42296. ownerView->repaint();
  42297. itemSelectionChanged (shouldBeSelected);
  42298. }
  42299. }
  42300. void TreeViewItem::paintItem (Graphics&, int, int)
  42301. {
  42302. }
  42303. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  42304. {
  42305. ownerView->getLookAndFeel()
  42306. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  42307. }
  42308. void TreeViewItem::itemClicked (const MouseEvent&)
  42309. {
  42310. }
  42311. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  42312. {
  42313. if (mightContainSubItems())
  42314. setOpen (! isOpen());
  42315. }
  42316. void TreeViewItem::itemSelectionChanged (bool)
  42317. {
  42318. }
  42319. const String TreeViewItem::getTooltip()
  42320. {
  42321. return String::empty;
  42322. }
  42323. const String TreeViewItem::getDragSourceDescription()
  42324. {
  42325. return String::empty;
  42326. }
  42327. const Rectangle TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  42328. {
  42329. const int indentX = getIndentX();
  42330. int width = itemWidth;
  42331. if (ownerView != 0 && width < 0)
  42332. width = ownerView->viewport->getViewWidth() - indentX;
  42333. Rectangle r (indentX, y, jmax (0, width), totalHeight);
  42334. if (relativeToTreeViewTopLeft)
  42335. r.setPosition (r.getX() - ownerView->viewport->getViewPositionX(),
  42336. r.getY() - ownerView->viewport->getViewPositionY());
  42337. return r;
  42338. }
  42339. void TreeViewItem::treeHasChanged() const throw()
  42340. {
  42341. if (ownerView != 0)
  42342. ownerView->itemsChanged();
  42343. }
  42344. void TreeViewItem::repaintItem() const
  42345. {
  42346. if (ownerView != 0 && areAllParentsOpen())
  42347. {
  42348. const Rectangle r (getItemPosition (true));
  42349. ownerView->viewport->repaint (0, r.getY(), r.getRight(), r.getHeight());
  42350. }
  42351. }
  42352. bool TreeViewItem::areAllParentsOpen() const throw()
  42353. {
  42354. return parentItem == 0
  42355. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  42356. }
  42357. void TreeViewItem::updatePositions (int newY)
  42358. {
  42359. y = newY;
  42360. itemHeight = getItemHeight();
  42361. totalHeight = itemHeight;
  42362. itemWidth = getItemWidth();
  42363. totalWidth = jmax (itemWidth, 0) + getIndentX();
  42364. if (isOpen())
  42365. {
  42366. newY += totalHeight;
  42367. for (int i = 0; i < subItems.size(); ++i)
  42368. {
  42369. TreeViewItem* const ti = subItems.getUnchecked(i);
  42370. ti->updatePositions (newY);
  42371. newY += ti->totalHeight;
  42372. totalHeight += ti->totalHeight;
  42373. totalWidth = jmax (totalWidth, ti->totalWidth);
  42374. }
  42375. }
  42376. }
  42377. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  42378. {
  42379. TreeViewItem* result = this;
  42380. TreeViewItem* item = this;
  42381. while (item->parentItem != 0)
  42382. {
  42383. item = item->parentItem;
  42384. if (! item->isOpen())
  42385. result = item;
  42386. }
  42387. return result;
  42388. }
  42389. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  42390. {
  42391. ownerView = newOwner;
  42392. for (int i = subItems.size(); --i >= 0;)
  42393. subItems.getUnchecked(i)->setOwnerView (newOwner);
  42394. }
  42395. int TreeViewItem::getIndentX() const throw()
  42396. {
  42397. const int indentWidth = ownerView->getIndentSize();
  42398. int x = ownerView->rootItemVisible ? indentWidth : 0;
  42399. if (! ownerView->openCloseButtonsVisible)
  42400. x -= indentWidth;
  42401. TreeViewItem* p = parentItem;
  42402. while (p != 0)
  42403. {
  42404. x += indentWidth;
  42405. p = p->parentItem;
  42406. }
  42407. return x;
  42408. }
  42409. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  42410. {
  42411. drawsInLeftMargin = canDrawInLeftMargin;
  42412. }
  42413. void TreeViewItem::paintRecursively (Graphics& g, int width)
  42414. {
  42415. jassert (ownerView != 0);
  42416. if (ownerView == 0)
  42417. return;
  42418. const int indent = getIndentX();
  42419. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  42420. g.setColour (ownerView->findColour (TreeView::linesColourId));
  42421. const float halfH = itemHeight * 0.5f;
  42422. int depth = 0;
  42423. TreeViewItem* p = parentItem;
  42424. while (p != 0)
  42425. {
  42426. ++depth;
  42427. p = p->parentItem;
  42428. }
  42429. if (! ownerView->rootItemVisible)
  42430. --depth;
  42431. const int indentWidth = ownerView->getIndentSize();
  42432. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  42433. {
  42434. float x = (depth + 0.5f) * indentWidth;
  42435. if (depth >= 0)
  42436. {
  42437. if (parentItem != 0 && parentItem->drawLinesInside)
  42438. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  42439. if ((parentItem != 0 && parentItem->drawLinesInside)
  42440. || (parentItem == 0 && drawLinesInside))
  42441. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  42442. }
  42443. p = parentItem;
  42444. int d = depth;
  42445. while (p != 0 && --d >= 0)
  42446. {
  42447. x -= (float) indentWidth;
  42448. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  42449. && ! p->isLastOfSiblings())
  42450. {
  42451. g.drawLine (x, 0, x, (float) itemHeight);
  42452. }
  42453. p = p->parentItem;
  42454. }
  42455. if (mightContainSubItems())
  42456. {
  42457. g.saveState();
  42458. g.setOrigin (depth * indentWidth, 0);
  42459. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  42460. paintOpenCloseButton (g, indentWidth, itemHeight,
  42461. ((TreeViewContentComponent*) ownerView->viewport->getViewedComponent())
  42462. ->isMouseOverButton (this));
  42463. g.restoreState();
  42464. }
  42465. }
  42466. {
  42467. g.saveState();
  42468. g.setOrigin (indent, 0);
  42469. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  42470. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  42471. paintItem (g, itemW, itemHeight);
  42472. g.restoreState();
  42473. }
  42474. if (isOpen())
  42475. {
  42476. const Rectangle clip (g.getClipBounds());
  42477. for (int i = 0; i < subItems.size(); ++i)
  42478. {
  42479. TreeViewItem* const ti = subItems.getUnchecked(i);
  42480. const int relY = ti->y - y;
  42481. if (relY >= clip.getBottom())
  42482. break;
  42483. if (relY + ti->totalHeight >= clip.getY())
  42484. {
  42485. g.saveState();
  42486. g.setOrigin (0, relY);
  42487. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  42488. ti->paintRecursively (g, width);
  42489. g.restoreState();
  42490. }
  42491. }
  42492. }
  42493. }
  42494. bool TreeViewItem::isLastOfSiblings() const throw()
  42495. {
  42496. return parentItem == 0
  42497. || parentItem->subItems.getLast() == this;
  42498. }
  42499. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  42500. {
  42501. return (parentItem == 0) ? this
  42502. : parentItem->getTopLevelItem();
  42503. }
  42504. int TreeViewItem::getNumRows() const throw()
  42505. {
  42506. int num = 1;
  42507. if (isOpen())
  42508. {
  42509. for (int i = subItems.size(); --i >= 0;)
  42510. num += subItems.getUnchecked(i)->getNumRows();
  42511. }
  42512. return num;
  42513. }
  42514. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  42515. {
  42516. if (index == 0)
  42517. return this;
  42518. if (index > 0 && isOpen())
  42519. {
  42520. --index;
  42521. for (int i = 0; i < subItems.size(); ++i)
  42522. {
  42523. TreeViewItem* const item = subItems.getUnchecked(i);
  42524. if (index == 0)
  42525. return item;
  42526. const int numRows = item->getNumRows();
  42527. if (numRows > index)
  42528. return item->getItemOnRow (index);
  42529. index -= numRows;
  42530. }
  42531. }
  42532. return 0;
  42533. }
  42534. TreeViewItem* TreeViewItem::findItemRecursively (int y) throw()
  42535. {
  42536. if (((unsigned int) y) < (unsigned int) totalHeight)
  42537. {
  42538. const int h = itemHeight;
  42539. if (y < h)
  42540. return this;
  42541. if (isOpen())
  42542. {
  42543. y -= h;
  42544. for (int i = 0; i < subItems.size(); ++i)
  42545. {
  42546. TreeViewItem* const ti = subItems.getUnchecked(i);
  42547. if (ti->totalHeight >= y)
  42548. return ti->findItemRecursively (y);
  42549. y -= ti->totalHeight;
  42550. }
  42551. }
  42552. }
  42553. return 0;
  42554. }
  42555. int TreeViewItem::countSelectedItemsRecursively() const throw()
  42556. {
  42557. int total = 0;
  42558. if (isSelected())
  42559. ++total;
  42560. for (int i = subItems.size(); --i >= 0;)
  42561. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  42562. return total;
  42563. }
  42564. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  42565. {
  42566. if (isSelected())
  42567. {
  42568. if (index == 0)
  42569. return this;
  42570. --index;
  42571. }
  42572. if (index >= 0)
  42573. {
  42574. for (int i = 0; i < subItems.size(); ++i)
  42575. {
  42576. TreeViewItem* const item = subItems.getUnchecked(i);
  42577. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  42578. if (found != 0)
  42579. return found;
  42580. index -= item->countSelectedItemsRecursively();
  42581. }
  42582. }
  42583. return 0;
  42584. }
  42585. int TreeViewItem::getRowNumberInTree() const throw()
  42586. {
  42587. if (parentItem != 0 && ownerView != 0)
  42588. {
  42589. int n = 1 + parentItem->getRowNumberInTree();
  42590. int ourIndex = parentItem->subItems.indexOf (this);
  42591. jassert (ourIndex >= 0);
  42592. while (--ourIndex >= 0)
  42593. n += parentItem->subItems [ourIndex]->getNumRows();
  42594. if (parentItem->parentItem == 0
  42595. && ! ownerView->rootItemVisible)
  42596. --n;
  42597. return n;
  42598. }
  42599. else
  42600. {
  42601. return 0;
  42602. }
  42603. }
  42604. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  42605. {
  42606. drawLinesInside = drawLines;
  42607. }
  42608. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  42609. {
  42610. if (recurse && isOpen() && subItems.size() > 0)
  42611. return subItems [0];
  42612. if (parentItem != 0)
  42613. {
  42614. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  42615. if (nextIndex >= parentItem->subItems.size())
  42616. return parentItem->getNextVisibleItem (false);
  42617. return parentItem->subItems [nextIndex];
  42618. }
  42619. return 0;
  42620. }
  42621. void TreeViewItem::restoreFromXml (const XmlElement& e)
  42622. {
  42623. if (e.hasTagName (T("CLOSED")))
  42624. {
  42625. setOpen (false);
  42626. }
  42627. else if (e.hasTagName (T("OPEN")))
  42628. {
  42629. setOpen (true);
  42630. forEachXmlChildElement (e, n)
  42631. {
  42632. const String id (n->getStringAttribute (T("id")));
  42633. for (int i = 0; i < subItems.size(); ++i)
  42634. {
  42635. TreeViewItem* const ti = subItems.getUnchecked(i);
  42636. if (ti->getUniqueName() == id)
  42637. {
  42638. ti->restoreFromXml (*n);
  42639. break;
  42640. }
  42641. }
  42642. }
  42643. }
  42644. }
  42645. XmlElement* TreeViewItem::createXmlOpenness() const
  42646. {
  42647. if (openness != opennessDefault)
  42648. {
  42649. const String name (getUniqueName());
  42650. if (name.isNotEmpty())
  42651. {
  42652. XmlElement* e;
  42653. if (isOpen())
  42654. {
  42655. e = new XmlElement (T("OPEN"));
  42656. for (int i = 0; i < subItems.size(); ++i)
  42657. e->addChildElement (subItems.getUnchecked(i)->createXmlOpenness());
  42658. }
  42659. else
  42660. {
  42661. e = new XmlElement (T("CLOSED"));
  42662. }
  42663. e->setAttribute (T("id"), name);
  42664. return e;
  42665. }
  42666. else
  42667. {
  42668. // trying to save the openness for an element that has no name - this won't
  42669. // work because it needs the names to identify what to open.
  42670. jassertfalse
  42671. }
  42672. }
  42673. return 0;
  42674. }
  42675. END_JUCE_NAMESPACE
  42676. /********* End of inlined file: juce_TreeView.cpp *********/
  42677. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  42678. BEGIN_JUCE_NAMESPACE
  42679. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  42680. : fileList (listToShow),
  42681. listeners (2)
  42682. {
  42683. }
  42684. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  42685. {
  42686. }
  42687. FileBrowserListener::~FileBrowserListener()
  42688. {
  42689. }
  42690. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener) throw()
  42691. {
  42692. jassert (listener != 0);
  42693. if (listener != 0)
  42694. listeners.add (listener);
  42695. }
  42696. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener) throw()
  42697. {
  42698. listeners.removeValue (listener);
  42699. }
  42700. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  42701. {
  42702. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  42703. for (int i = listeners.size(); --i >= 0;)
  42704. {
  42705. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  42706. if (deletionWatcher.hasBeenDeleted())
  42707. return;
  42708. i = jmin (i, listeners.size() - 1);
  42709. }
  42710. }
  42711. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  42712. {
  42713. if (fileList.getDirectory().exists())
  42714. {
  42715. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  42716. for (int i = listeners.size(); --i >= 0;)
  42717. {
  42718. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (file, e);
  42719. if (deletionWatcher.hasBeenDeleted())
  42720. return;
  42721. i = jmin (i, listeners.size() - 1);
  42722. }
  42723. }
  42724. }
  42725. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  42726. {
  42727. if (fileList.getDirectory().exists())
  42728. {
  42729. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  42730. for (int i = listeners.size(); --i >= 0;)
  42731. {
  42732. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (file);
  42733. if (deletionWatcher.hasBeenDeleted())
  42734. return;
  42735. i = jmin (i, listeners.size() - 1);
  42736. }
  42737. }
  42738. }
  42739. END_JUCE_NAMESPACE
  42740. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  42741. /********* Start of inlined file: juce_DirectoryContentsList.cpp *********/
  42742. BEGIN_JUCE_NAMESPACE
  42743. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  42744. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  42745. Time* creationTime, bool* isReadOnly) throw();
  42746. bool juce_findFileNext (void* handle, String& resultFile,
  42747. bool* isDirectory, bool* isHidden, int64* fileSize,
  42748. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  42749. void juce_findFileClose (void* handle) throw();
  42750. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  42751. TimeSliceThread& thread_)
  42752. : fileFilter (fileFilter_),
  42753. thread (thread_),
  42754. includeDirectories (false),
  42755. includeFiles (false),
  42756. ignoreHiddenFiles (true),
  42757. fileFindHandle (0),
  42758. shouldStop (true)
  42759. {
  42760. }
  42761. DirectoryContentsList::~DirectoryContentsList()
  42762. {
  42763. clear();
  42764. }
  42765. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  42766. {
  42767. ignoreHiddenFiles = shouldIgnoreHiddenFiles;
  42768. }
  42769. const File& DirectoryContentsList::getDirectory() const throw()
  42770. {
  42771. return root;
  42772. }
  42773. void DirectoryContentsList::setDirectory (const File& directory,
  42774. const bool includeDirectories_,
  42775. const bool includeFiles_)
  42776. {
  42777. if (directory != root
  42778. || includeDirectories != includeDirectories_
  42779. || includeFiles != includeFiles_)
  42780. {
  42781. clear();
  42782. root = directory;
  42783. includeDirectories = includeDirectories_;
  42784. includeFiles = includeFiles_;
  42785. refresh();
  42786. }
  42787. }
  42788. void DirectoryContentsList::clear()
  42789. {
  42790. shouldStop = true;
  42791. thread.removeTimeSliceClient (this);
  42792. if (fileFindHandle != 0)
  42793. {
  42794. juce_findFileClose (fileFindHandle);
  42795. fileFindHandle = 0;
  42796. }
  42797. if (files.size() > 0)
  42798. {
  42799. files.clear();
  42800. changed();
  42801. }
  42802. }
  42803. void DirectoryContentsList::refresh()
  42804. {
  42805. clear();
  42806. if (root.isDirectory())
  42807. {
  42808. String fileFound;
  42809. bool fileFoundIsDir, isHidden, isReadOnly;
  42810. int64 fileSize;
  42811. Time modTime, creationTime;
  42812. String path (root.getFullPathName());
  42813. if (! path.endsWithChar (File::separator))
  42814. path += File::separator;
  42815. jassert (fileFindHandle == 0);
  42816. fileFindHandle = juce_findFileStart (path, T("*"), fileFound,
  42817. &fileFoundIsDir,
  42818. &isHidden,
  42819. &fileSize,
  42820. &modTime,
  42821. &creationTime,
  42822. &isReadOnly);
  42823. if (fileFindHandle != 0 && fileFound.isNotEmpty())
  42824. {
  42825. if (addFile (fileFound, fileFoundIsDir, isHidden,
  42826. fileSize, modTime, creationTime, isReadOnly))
  42827. {
  42828. changed();
  42829. }
  42830. }
  42831. shouldStop = false;
  42832. thread.addTimeSliceClient (this);
  42833. }
  42834. }
  42835. int DirectoryContentsList::getNumFiles() const
  42836. {
  42837. return files.size();
  42838. }
  42839. bool DirectoryContentsList::getFileInfo (const int index,
  42840. FileInfo& result) const
  42841. {
  42842. const ScopedLock sl (fileListLock);
  42843. const FileInfo* const info = files [index];
  42844. if (info != 0)
  42845. {
  42846. result = *info;
  42847. return true;
  42848. }
  42849. return false;
  42850. }
  42851. const File DirectoryContentsList::getFile (const int index) const
  42852. {
  42853. const ScopedLock sl (fileListLock);
  42854. const FileInfo* const info = files [index];
  42855. if (info != 0)
  42856. return root.getChildFile (info->filename);
  42857. return File::nonexistent;
  42858. }
  42859. bool DirectoryContentsList::isStillLoading() const
  42860. {
  42861. return fileFindHandle != 0;
  42862. }
  42863. void DirectoryContentsList::changed()
  42864. {
  42865. sendChangeMessage (this);
  42866. }
  42867. bool DirectoryContentsList::useTimeSlice()
  42868. {
  42869. const uint32 startTime = Time::getApproximateMillisecondCounter();
  42870. bool hasChanged = false;
  42871. for (int i = 100; --i >= 0;)
  42872. {
  42873. if (! checkNextFile (hasChanged))
  42874. {
  42875. if (hasChanged)
  42876. changed();
  42877. return false;
  42878. }
  42879. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  42880. break;
  42881. }
  42882. if (hasChanged)
  42883. changed();
  42884. return true;
  42885. }
  42886. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  42887. {
  42888. if (fileFindHandle != 0)
  42889. {
  42890. String fileFound;
  42891. bool fileFoundIsDir, isHidden, isReadOnly;
  42892. int64 fileSize;
  42893. Time modTime, creationTime;
  42894. if (juce_findFileNext (fileFindHandle, fileFound,
  42895. &fileFoundIsDir, &isHidden,
  42896. &fileSize,
  42897. &modTime,
  42898. &creationTime,
  42899. &isReadOnly))
  42900. {
  42901. if (addFile (fileFound, fileFoundIsDir, isHidden, fileSize,
  42902. modTime, creationTime, isReadOnly))
  42903. {
  42904. hasChanged = true;
  42905. }
  42906. return true;
  42907. }
  42908. else
  42909. {
  42910. juce_findFileClose (fileFindHandle);
  42911. fileFindHandle = 0;
  42912. }
  42913. }
  42914. return false;
  42915. }
  42916. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  42917. const DirectoryContentsList::FileInfo* const second) throw()
  42918. {
  42919. #if JUCE_WIN32
  42920. if (first->isDirectory != second->isDirectory)
  42921. return first->isDirectory ? -1 : 1;
  42922. #endif
  42923. return first->filename.compareIgnoreCase (second->filename);
  42924. }
  42925. bool DirectoryContentsList::addFile (const String& filename,
  42926. const bool isDir,
  42927. const bool isHidden,
  42928. const int64 fileSize,
  42929. const Time& modTime,
  42930. const Time& creationTime,
  42931. const bool isReadOnly)
  42932. {
  42933. if (filename == T("..")
  42934. || filename == T(".")
  42935. || (ignoreHiddenFiles && isHidden))
  42936. return false;
  42937. const File file (root.getChildFile (filename));
  42938. if (((isDir && includeDirectories) || ((! isDir) && includeFiles))
  42939. && (fileFilter == 0
  42940. || ((! isDir) && fileFilter->isFileSuitable (file))
  42941. || (isDir && fileFilter->isDirectorySuitable (file))))
  42942. {
  42943. FileInfo* const info = new FileInfo();
  42944. info->filename = filename;
  42945. info->fileSize = fileSize;
  42946. info->modificationTime = modTime;
  42947. info->creationTime = creationTime;
  42948. info->isDirectory = isDir;
  42949. info->isReadOnly = isReadOnly;
  42950. const ScopedLock sl (fileListLock);
  42951. for (int i = files.size(); --i >= 0;)
  42952. {
  42953. if (files.getUnchecked(i)->filename == info->filename)
  42954. {
  42955. delete info;
  42956. return false;
  42957. }
  42958. }
  42959. files.addSorted (*this, info);
  42960. return true;
  42961. }
  42962. return false;
  42963. }
  42964. END_JUCE_NAMESPACE
  42965. /********* End of inlined file: juce_DirectoryContentsList.cpp *********/
  42966. /********* Start of inlined file: juce_FileBrowserComponent.cpp *********/
  42967. BEGIN_JUCE_NAMESPACE
  42968. class DirectoriesOnlyFilter : public FileFilter
  42969. {
  42970. public:
  42971. DirectoriesOnlyFilter() : FileFilter (String::empty) {}
  42972. bool isFileSuitable (const File&) const { return false; }
  42973. bool isDirectorySuitable (const File&) const { return true; }
  42974. };
  42975. FileBrowserComponent::FileBrowserComponent (FileChooserMode mode_,
  42976. const File& initialFileOrDirectory,
  42977. const FileFilter* fileFilter,
  42978. FilePreviewComponent* previewComp_,
  42979. const bool useTreeView,
  42980. const bool filenameTextBoxIsReadOnly)
  42981. : directoriesOnlyFilter (0),
  42982. mode (mode_),
  42983. listeners (2),
  42984. previewComp (previewComp_),
  42985. thread ("Juce FileBrowser")
  42986. {
  42987. String filename;
  42988. if (initialFileOrDirectory == File::nonexistent)
  42989. {
  42990. currentRoot = File::getCurrentWorkingDirectory();
  42991. }
  42992. else if (initialFileOrDirectory.isDirectory())
  42993. {
  42994. currentRoot = initialFileOrDirectory;
  42995. }
  42996. else
  42997. {
  42998. currentRoot = initialFileOrDirectory.getParentDirectory();
  42999. filename = initialFileOrDirectory.getFileName();
  43000. }
  43001. if (mode_ == chooseDirectoryMode)
  43002. fileFilter = directoriesOnlyFilter = new DirectoriesOnlyFilter();
  43003. fileList = new DirectoryContentsList (fileFilter, thread);
  43004. if (useTreeView)
  43005. {
  43006. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  43007. addAndMakeVisible (tree);
  43008. fileListComponent = tree;
  43009. }
  43010. else
  43011. {
  43012. FileListComponent* const list = new FileListComponent (*fileList);
  43013. list->setOutlineThickness (1);
  43014. addAndMakeVisible (list);
  43015. fileListComponent = list;
  43016. }
  43017. fileListComponent->addListener (this);
  43018. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  43019. currentPathBox->setEditableText (true);
  43020. StringArray rootNames, rootPaths;
  43021. const BitArray separators (getRoots (rootNames, rootPaths));
  43022. for (int i = 0; i < rootNames.size(); ++i)
  43023. {
  43024. if (separators [i])
  43025. currentPathBox->addSeparator();
  43026. currentPathBox->addItem (rootNames[i], i + 1);
  43027. }
  43028. currentPathBox->addSeparator();
  43029. currentPathBox->addListener (this);
  43030. addAndMakeVisible (filenameBox = new TextEditor());
  43031. filenameBox->setMultiLine (false);
  43032. filenameBox->setSelectAllWhenFocused (true);
  43033. filenameBox->setText (filename, false);
  43034. filenameBox->addListener (this);
  43035. filenameBox->setReadOnly (filenameTextBoxIsReadOnly);
  43036. Label* label = new Label ("f", (mode == chooseDirectoryMode) ? TRANS("folder:")
  43037. : TRANS("file:"));
  43038. addAndMakeVisible (label);
  43039. label->attachToComponent (filenameBox, true);
  43040. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  43041. goUpButton->addButtonListener (this);
  43042. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  43043. if (previewComp != 0)
  43044. addAndMakeVisible (previewComp);
  43045. setRoot (currentRoot);
  43046. thread.startThread (4);
  43047. }
  43048. FileBrowserComponent::~FileBrowserComponent()
  43049. {
  43050. if (previewComp != 0)
  43051. removeChildComponent (previewComp);
  43052. deleteAllChildren();
  43053. deleteAndZero (fileList);
  43054. delete directoriesOnlyFilter;
  43055. thread.stopThread (10000);
  43056. }
  43057. void FileBrowserComponent::addListener (FileBrowserListener* const newListener) throw()
  43058. {
  43059. jassert (newListener != 0)
  43060. if (newListener != 0)
  43061. listeners.add (newListener);
  43062. }
  43063. void FileBrowserComponent::removeListener (FileBrowserListener* const listener) throw()
  43064. {
  43065. listeners.removeValue (listener);
  43066. }
  43067. const File FileBrowserComponent::getCurrentFile() const throw()
  43068. {
  43069. return currentRoot.getChildFile (filenameBox->getText());
  43070. }
  43071. bool FileBrowserComponent::currentFileIsValid() const
  43072. {
  43073. if (mode == saveFileMode)
  43074. return ! getCurrentFile().isDirectory();
  43075. else if (mode == loadFileMode)
  43076. return getCurrentFile().existsAsFile();
  43077. else if (mode == chooseDirectoryMode)
  43078. return getCurrentFile().isDirectory();
  43079. jassertfalse
  43080. return false;
  43081. }
  43082. const File FileBrowserComponent::getRoot() const
  43083. {
  43084. return currentRoot;
  43085. }
  43086. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  43087. {
  43088. if (currentRoot != newRootDirectory)
  43089. {
  43090. fileListComponent->scrollToTop();
  43091. if (mode == chooseDirectoryMode)
  43092. filenameBox->setText (String::empty, false);
  43093. String path (newRootDirectory.getFullPathName());
  43094. if (path.isEmpty())
  43095. path += File::separator;
  43096. StringArray rootNames, rootPaths;
  43097. getRoots (rootNames, rootPaths);
  43098. if (! rootPaths.contains (path, true))
  43099. {
  43100. bool alreadyListed = false;
  43101. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  43102. {
  43103. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  43104. {
  43105. alreadyListed = true;
  43106. break;
  43107. }
  43108. }
  43109. if (! alreadyListed)
  43110. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  43111. }
  43112. }
  43113. currentRoot = newRootDirectory;
  43114. fileList->setDirectory (currentRoot, true, true);
  43115. String currentRootName (currentRoot.getFullPathName());
  43116. if (currentRootName.isEmpty())
  43117. currentRootName += File::separator;
  43118. currentPathBox->setText (currentRootName, true);
  43119. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  43120. && currentRoot.getParentDirectory() != currentRoot);
  43121. }
  43122. void FileBrowserComponent::goUp()
  43123. {
  43124. setRoot (getRoot().getParentDirectory());
  43125. }
  43126. void FileBrowserComponent::refresh()
  43127. {
  43128. fileList->refresh();
  43129. }
  43130. const String FileBrowserComponent::getActionVerb() const
  43131. {
  43132. return (mode == chooseDirectoryMode) ? TRANS("Choose")
  43133. : ((mode == saveFileMode) ? TRANS("Save") : TRANS("Open"));
  43134. }
  43135. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  43136. {
  43137. return previewComp;
  43138. }
  43139. void FileBrowserComponent::resized()
  43140. {
  43141. getLookAndFeel()
  43142. .layoutFileBrowserComponent (*this, fileListComponent,
  43143. previewComp, currentPathBox,
  43144. filenameBox, goUpButton);
  43145. }
  43146. void FileBrowserComponent::sendListenerChangeMessage()
  43147. {
  43148. ComponentDeletionWatcher deletionWatcher (this);
  43149. if (previewComp != 0)
  43150. previewComp->selectedFileChanged (getCurrentFile());
  43151. jassert (! deletionWatcher.hasBeenDeleted());
  43152. for (int i = listeners.size(); --i >= 0;)
  43153. {
  43154. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  43155. if (deletionWatcher.hasBeenDeleted())
  43156. return;
  43157. i = jmin (i, listeners.size() - 1);
  43158. }
  43159. }
  43160. void FileBrowserComponent::selectionChanged()
  43161. {
  43162. const File selected (fileListComponent->getSelectedFile());
  43163. if ((mode == chooseDirectoryMode && selected.isDirectory())
  43164. || selected.existsAsFile())
  43165. {
  43166. filenameBox->setText (selected.getRelativePathFrom (getRoot()), false);
  43167. }
  43168. sendListenerChangeMessage();
  43169. }
  43170. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  43171. {
  43172. ComponentDeletionWatcher deletionWatcher (this);
  43173. for (int i = listeners.size(); --i >= 0;)
  43174. {
  43175. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (f, e);
  43176. if (deletionWatcher.hasBeenDeleted())
  43177. return;
  43178. i = jmin (i, listeners.size() - 1);
  43179. }
  43180. }
  43181. void FileBrowserComponent::fileDoubleClicked (const File& f)
  43182. {
  43183. if (f.isDirectory())
  43184. {
  43185. setRoot (f);
  43186. }
  43187. else
  43188. {
  43189. ComponentDeletionWatcher deletionWatcher (this);
  43190. for (int i = listeners.size(); --i >= 0;)
  43191. {
  43192. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (f);
  43193. if (deletionWatcher.hasBeenDeleted())
  43194. return;
  43195. i = jmin (i, listeners.size() - 1);
  43196. }
  43197. }
  43198. }
  43199. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  43200. {
  43201. #if JUCE_LINUX || JUCE_WIN32
  43202. if (key.getModifiers().isCommandDown()
  43203. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  43204. {
  43205. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  43206. fileList->refresh();
  43207. return true;
  43208. }
  43209. #endif
  43210. return false;
  43211. }
  43212. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  43213. {
  43214. sendListenerChangeMessage();
  43215. }
  43216. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  43217. {
  43218. if (filenameBox->getText().containsChar (File::separator))
  43219. {
  43220. const File f (currentRoot.getChildFile (filenameBox->getText()));
  43221. if (f.isDirectory())
  43222. {
  43223. setRoot (f);
  43224. filenameBox->setText (String::empty);
  43225. }
  43226. else
  43227. {
  43228. setRoot (f.getParentDirectory());
  43229. filenameBox->setText (f.getFileName());
  43230. }
  43231. }
  43232. else
  43233. {
  43234. fileDoubleClicked (getCurrentFile());
  43235. }
  43236. }
  43237. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  43238. {
  43239. }
  43240. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  43241. {
  43242. if (mode != saveFileMode)
  43243. selectionChanged();
  43244. }
  43245. void FileBrowserComponent::buttonClicked (Button*)
  43246. {
  43247. goUp();
  43248. }
  43249. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  43250. {
  43251. const String newText (currentPathBox->getText().trim().unquoted());
  43252. if (newText.isNotEmpty())
  43253. {
  43254. const int index = currentPathBox->getSelectedId() - 1;
  43255. StringArray rootNames, rootPaths;
  43256. getRoots (rootNames, rootPaths);
  43257. if (rootPaths [index].isNotEmpty())
  43258. {
  43259. setRoot (File (rootPaths [index]));
  43260. }
  43261. else
  43262. {
  43263. File f (newText);
  43264. for (;;)
  43265. {
  43266. if (f.isDirectory())
  43267. {
  43268. setRoot (f);
  43269. break;
  43270. }
  43271. if (f.getParentDirectory() == f)
  43272. break;
  43273. f = f.getParentDirectory();
  43274. }
  43275. }
  43276. }
  43277. }
  43278. const BitArray FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  43279. {
  43280. BitArray separators;
  43281. #if JUCE_WIN32
  43282. OwnedArray<File> roots;
  43283. File::findFileSystemRoots (roots);
  43284. rootPaths.clear();
  43285. for (int i = 0; i < roots.size(); ++i)
  43286. {
  43287. const File* const drive = roots.getUnchecked(i);
  43288. String name (drive->getFullPathName());
  43289. rootPaths.add (name);
  43290. if (drive->isOnHardDisk())
  43291. {
  43292. String volume (drive->getVolumeLabel());
  43293. if (volume.isEmpty())
  43294. volume = TRANS("Hard Drive");
  43295. name << " [" << drive->getVolumeLabel() << ']';
  43296. }
  43297. else if (drive->isOnCDRomDrive())
  43298. {
  43299. name << TRANS(" [CD/DVD drive]");
  43300. }
  43301. rootNames.add (name);
  43302. }
  43303. separators.setBit (rootPaths.size());
  43304. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  43305. rootNames.add ("Documents");
  43306. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43307. rootNames.add ("Desktop");
  43308. #endif
  43309. #if JUCE_MAC
  43310. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  43311. rootNames.add ("Home folder");
  43312. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  43313. rootNames.add ("Documents");
  43314. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43315. rootNames.add ("Desktop");
  43316. separators.setBit (rootPaths.size());
  43317. OwnedArray <File> volumes;
  43318. File vol ("/Volumes");
  43319. vol.findChildFiles (volumes, File::findDirectories, false);
  43320. for (int i = 0; i < volumes.size(); ++i)
  43321. {
  43322. const File* const volume = volumes.getUnchecked(i);
  43323. if (volume->isDirectory() && ! volume->getFileName().startsWithChar (T('.')))
  43324. {
  43325. rootPaths.add (volume->getFullPathName());
  43326. rootNames.add (volume->getFileName());
  43327. }
  43328. }
  43329. #endif
  43330. #if JUCE_LINUX
  43331. rootPaths.add ("/");
  43332. rootNames.add ("/");
  43333. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  43334. rootNames.add ("Home folder");
  43335. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43336. rootNames.add ("Desktop");
  43337. #endif
  43338. return separators;
  43339. }
  43340. END_JUCE_NAMESPACE
  43341. /********* End of inlined file: juce_FileBrowserComponent.cpp *********/
  43342. /********* Start of inlined file: juce_FileChooser.cpp *********/
  43343. BEGIN_JUCE_NAMESPACE
  43344. FileChooser::FileChooser (const String& chooserBoxTitle,
  43345. const File& currentFileOrDirectory,
  43346. const String& fileFilters,
  43347. const bool useNativeDialogBox_)
  43348. : title (chooserBoxTitle),
  43349. filters (fileFilters),
  43350. startingFile (currentFileOrDirectory),
  43351. useNativeDialogBox (useNativeDialogBox_)
  43352. {
  43353. #if JUCE_LINUX
  43354. useNativeDialogBox = false;
  43355. #endif
  43356. if (! fileFilters.containsNonWhitespaceChars())
  43357. filters = T("*");
  43358. }
  43359. FileChooser::~FileChooser()
  43360. {
  43361. }
  43362. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  43363. {
  43364. return showDialog (false, false, false, false, previewComponent);
  43365. }
  43366. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  43367. {
  43368. return showDialog (false, false, false, true, previewComponent);
  43369. }
  43370. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  43371. {
  43372. return showDialog (false, true, warnAboutOverwritingExistingFiles, false, 0);
  43373. }
  43374. bool FileChooser::browseForDirectory()
  43375. {
  43376. return showDialog (true, false, false, false, 0);
  43377. }
  43378. const File FileChooser::getResult() const
  43379. {
  43380. // if you've used a multiple-file select, you should use the getResults() method
  43381. // to retrieve all the files that were chosen.
  43382. jassert (results.size() <= 1);
  43383. const File* const f = results.getFirst();
  43384. if (f != 0)
  43385. return *f;
  43386. return File::nonexistent;
  43387. }
  43388. const OwnedArray <File>& FileChooser::getResults() const
  43389. {
  43390. return results;
  43391. }
  43392. bool FileChooser::showDialog (const bool isDirectory,
  43393. const bool isSave,
  43394. const bool warnAboutOverwritingExistingFiles,
  43395. const bool selectMultipleFiles,
  43396. FilePreviewComponent* const previewComponent)
  43397. {
  43398. ComponentDeletionWatcher* currentlyFocusedChecker = 0;
  43399. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  43400. if (currentlyFocused != 0)
  43401. currentlyFocusedChecker = new ComponentDeletionWatcher (currentlyFocused);
  43402. results.clear();
  43403. // the preview component needs to be the right size before you pass it in here..
  43404. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  43405. && previewComponent->getHeight() > 10));
  43406. #if JUCE_WIN32
  43407. if (useNativeDialogBox)
  43408. #else
  43409. if (useNativeDialogBox && (previewComponent == 0))
  43410. #endif
  43411. {
  43412. showPlatformDialog (results, title, startingFile, filters,
  43413. isDirectory, isSave,
  43414. warnAboutOverwritingExistingFiles,
  43415. selectMultipleFiles,
  43416. previewComponent);
  43417. }
  43418. else
  43419. {
  43420. jassert (! selectMultipleFiles); // not yet implemented for juce dialogs!
  43421. WildcardFileFilter wildcard (filters, String::empty);
  43422. FileBrowserComponent browserComponent (isDirectory ? FileBrowserComponent::chooseDirectoryMode
  43423. : (isSave ? FileBrowserComponent::saveFileMode
  43424. : FileBrowserComponent::loadFileMode),
  43425. startingFile, &wildcard, previewComponent);
  43426. FileChooserDialogBox box (title, String::empty,
  43427. browserComponent,
  43428. warnAboutOverwritingExistingFiles,
  43429. browserComponent.findColour (AlertWindow::backgroundColourId));
  43430. if (box.show())
  43431. results.add (new File (browserComponent.getCurrentFile()));
  43432. }
  43433. if (currentlyFocused != 0 && ! currentlyFocusedChecker->hasBeenDeleted())
  43434. currentlyFocused->grabKeyboardFocus();
  43435. delete currentlyFocusedChecker;
  43436. return results.size() > 0;
  43437. }
  43438. FilePreviewComponent::FilePreviewComponent()
  43439. {
  43440. }
  43441. FilePreviewComponent::~FilePreviewComponent()
  43442. {
  43443. }
  43444. END_JUCE_NAMESPACE
  43445. /********* End of inlined file: juce_FileChooser.cpp *********/
  43446. /********* Start of inlined file: juce_FileChooserDialogBox.cpp *********/
  43447. BEGIN_JUCE_NAMESPACE
  43448. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  43449. const String& instructions,
  43450. FileBrowserComponent& chooserComponent,
  43451. const bool warnAboutOverwritingExistingFiles_,
  43452. const Colour& backgroundColour)
  43453. : ResizableWindow (name, backgroundColour, true),
  43454. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  43455. {
  43456. content = new ContentComponent();
  43457. content->setName (name);
  43458. content->instructions = instructions;
  43459. content->chooserComponent = &chooserComponent;
  43460. content->addAndMakeVisible (&chooserComponent);
  43461. content->okButton = new TextButton (chooserComponent.getActionVerb());
  43462. content->addAndMakeVisible (content->okButton);
  43463. content->okButton->addButtonListener (this);
  43464. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  43465. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  43466. content->cancelButton = new TextButton (TRANS("Cancel"));
  43467. content->addAndMakeVisible (content->cancelButton);
  43468. content->cancelButton->addButtonListener (this);
  43469. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  43470. setContentComponent (content);
  43471. setResizable (true, true);
  43472. setResizeLimits (300, 300, 1200, 1000);
  43473. content->chooserComponent->addListener (this);
  43474. }
  43475. FileChooserDialogBox::~FileChooserDialogBox()
  43476. {
  43477. content->chooserComponent->removeListener (this);
  43478. }
  43479. bool FileChooserDialogBox::show (int w, int h)
  43480. {
  43481. if (w <= 0)
  43482. {
  43483. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  43484. if (previewComp != 0)
  43485. w = 400 + previewComp->getWidth();
  43486. else
  43487. w = 600;
  43488. }
  43489. if (h <= 0)
  43490. h = 500;
  43491. centreWithSize (w, h);
  43492. const bool ok = (runModalLoop() != 0);
  43493. setVisible (false);
  43494. return ok;
  43495. }
  43496. void FileChooserDialogBox::buttonClicked (Button* button)
  43497. {
  43498. if (button == content->okButton)
  43499. {
  43500. if (warnAboutOverwritingExistingFiles
  43501. && content->chooserComponent->getMode() == FileBrowserComponent::saveFileMode
  43502. && content->chooserComponent->getCurrentFile().exists())
  43503. {
  43504. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  43505. TRANS("File already exists"),
  43506. TRANS("There's already a file called:\n\n")
  43507. + content->chooserComponent->getCurrentFile().getFullPathName()
  43508. + T("\n\nAre you sure you want to overwrite it?"),
  43509. TRANS("overwrite"),
  43510. TRANS("cancel")))
  43511. {
  43512. return;
  43513. }
  43514. }
  43515. exitModalState (1);
  43516. }
  43517. else if (button == content->cancelButton)
  43518. closeButtonPressed();
  43519. }
  43520. void FileChooserDialogBox::closeButtonPressed()
  43521. {
  43522. setVisible (false);
  43523. }
  43524. void FileChooserDialogBox::selectionChanged()
  43525. {
  43526. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  43527. }
  43528. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  43529. {
  43530. }
  43531. void FileChooserDialogBox::fileDoubleClicked (const File&)
  43532. {
  43533. selectionChanged();
  43534. content->okButton->triggerClick();
  43535. }
  43536. FileChooserDialogBox::ContentComponent::ContentComponent()
  43537. {
  43538. setInterceptsMouseClicks (false, true);
  43539. }
  43540. FileChooserDialogBox::ContentComponent::~ContentComponent()
  43541. {
  43542. delete okButton;
  43543. delete cancelButton;
  43544. }
  43545. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  43546. {
  43547. g.setColour (Colours::black);
  43548. text.draw (g);
  43549. }
  43550. void FileChooserDialogBox::ContentComponent::resized()
  43551. {
  43552. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  43553. float left, top, right, bottom;
  43554. text.getBoundingBox (0, text.getNumGlyphs(), left, top, right, bottom, false);
  43555. const int y = roundFloatToInt (bottom) + 10;
  43556. const int buttonHeight = 26;
  43557. const int buttonY = getHeight() - buttonHeight - 8;
  43558. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  43559. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  43560. proportionOfWidth (0.2f), buttonHeight);
  43561. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  43562. proportionOfWidth (0.2f), buttonHeight);
  43563. }
  43564. END_JUCE_NAMESPACE
  43565. /********* End of inlined file: juce_FileChooserDialogBox.cpp *********/
  43566. /********* Start of inlined file: juce_FileFilter.cpp *********/
  43567. BEGIN_JUCE_NAMESPACE
  43568. FileFilter::FileFilter (const String& filterDescription)
  43569. : description (filterDescription)
  43570. {
  43571. }
  43572. FileFilter::~FileFilter()
  43573. {
  43574. }
  43575. const String& FileFilter::getDescription() const throw()
  43576. {
  43577. return description;
  43578. }
  43579. END_JUCE_NAMESPACE
  43580. /********* End of inlined file: juce_FileFilter.cpp *********/
  43581. /********* Start of inlined file: juce_FileListComponent.cpp *********/
  43582. BEGIN_JUCE_NAMESPACE
  43583. Image* juce_createIconForFile (const File& file);
  43584. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  43585. : ListBox (String::empty, 0),
  43586. DirectoryContentsDisplayComponent (listToShow)
  43587. {
  43588. setModel (this);
  43589. fileList.addChangeListener (this);
  43590. }
  43591. FileListComponent::~FileListComponent()
  43592. {
  43593. fileList.removeChangeListener (this);
  43594. deleteAllChildren();
  43595. }
  43596. const File FileListComponent::getSelectedFile() const
  43597. {
  43598. return fileList.getFile (getSelectedRow());
  43599. }
  43600. void FileListComponent::scrollToTop()
  43601. {
  43602. getVerticalScrollBar()->setCurrentRangeStart (0);
  43603. }
  43604. void FileListComponent::changeListenerCallback (void*)
  43605. {
  43606. updateContent();
  43607. if (lastDirectory != fileList.getDirectory())
  43608. {
  43609. lastDirectory = fileList.getDirectory();
  43610. deselectAllRows();
  43611. }
  43612. }
  43613. class FileListItemComponent : public Component,
  43614. public TimeSliceClient,
  43615. public AsyncUpdater
  43616. {
  43617. public:
  43618. FileListItemComponent (FileListComponent& owner_,
  43619. TimeSliceThread& thread_) throw()
  43620. : owner (owner_),
  43621. thread (thread_),
  43622. icon (0)
  43623. {
  43624. }
  43625. ~FileListItemComponent() throw()
  43626. {
  43627. thread.removeTimeSliceClient (this);
  43628. clearIcon();
  43629. }
  43630. void paint (Graphics& g)
  43631. {
  43632. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  43633. file.getFileName(),
  43634. icon,
  43635. fileSize, modTime,
  43636. isDirectory, highlighted,
  43637. index);
  43638. }
  43639. void mouseDown (const MouseEvent& e)
  43640. {
  43641. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  43642. owner.sendMouseClickMessage (file, e);
  43643. }
  43644. void mouseDoubleClick (const MouseEvent&)
  43645. {
  43646. owner.sendDoubleClickMessage (file);
  43647. }
  43648. void update (const File& root,
  43649. const DirectoryContentsList::FileInfo* const fileInfo,
  43650. const int index_,
  43651. const bool highlighted_) throw()
  43652. {
  43653. thread.removeTimeSliceClient (this);
  43654. if (highlighted_ != highlighted
  43655. || index_ != index)
  43656. {
  43657. index = index_;
  43658. highlighted = highlighted_;
  43659. repaint();
  43660. }
  43661. File newFile;
  43662. String newFileSize;
  43663. String newModTime;
  43664. if (fileInfo != 0)
  43665. {
  43666. newFile = root.getChildFile (fileInfo->filename);
  43667. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  43668. newModTime = fileInfo->modificationTime.formatted (T("%d %b '%y %H:%M"));
  43669. }
  43670. if (newFile != file
  43671. || fileSize != newFileSize
  43672. || modTime != newModTime)
  43673. {
  43674. file = newFile;
  43675. fileSize = newFileSize;
  43676. modTime = newModTime;
  43677. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  43678. repaint();
  43679. clearIcon();
  43680. }
  43681. if (file != File::nonexistent
  43682. && icon == 0 && ! isDirectory)
  43683. {
  43684. updateIcon (true);
  43685. if (icon == 0)
  43686. thread.addTimeSliceClient (this);
  43687. }
  43688. }
  43689. bool useTimeSlice()
  43690. {
  43691. updateIcon (false);
  43692. return false;
  43693. }
  43694. void handleAsyncUpdate()
  43695. {
  43696. repaint();
  43697. }
  43698. juce_UseDebuggingNewOperator
  43699. private:
  43700. FileListComponent& owner;
  43701. TimeSliceThread& thread;
  43702. bool highlighted;
  43703. int index;
  43704. File file;
  43705. String fileSize;
  43706. String modTime;
  43707. Image* icon;
  43708. bool isDirectory;
  43709. void clearIcon() throw()
  43710. {
  43711. ImageCache::release (icon);
  43712. icon = 0;
  43713. }
  43714. void updateIcon (const bool onlyUpdateIfCached) throw()
  43715. {
  43716. if (icon == 0)
  43717. {
  43718. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  43719. Image* im = ImageCache::getFromHashCode (hashCode);
  43720. if (im == 0 && ! onlyUpdateIfCached)
  43721. {
  43722. im = juce_createIconForFile (file);
  43723. if (im != 0)
  43724. ImageCache::addImageToCache (im, hashCode);
  43725. }
  43726. if (im != 0)
  43727. {
  43728. icon = im;
  43729. triggerAsyncUpdate();
  43730. }
  43731. }
  43732. }
  43733. };
  43734. int FileListComponent::getNumRows()
  43735. {
  43736. return fileList.getNumFiles();
  43737. }
  43738. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  43739. {
  43740. }
  43741. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  43742. {
  43743. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  43744. if (comp == 0)
  43745. {
  43746. delete existingComponentToUpdate;
  43747. existingComponentToUpdate = comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  43748. }
  43749. DirectoryContentsList::FileInfo fileInfo;
  43750. if (fileList.getFileInfo (row, fileInfo))
  43751. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  43752. else
  43753. comp->update (fileList.getDirectory(), 0, row, isSelected);
  43754. return comp;
  43755. }
  43756. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  43757. {
  43758. sendSelectionChangeMessage();
  43759. }
  43760. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  43761. {
  43762. }
  43763. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  43764. {
  43765. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  43766. }
  43767. END_JUCE_NAMESPACE
  43768. /********* End of inlined file: juce_FileListComponent.cpp *********/
  43769. /********* Start of inlined file: juce_FilenameComponent.cpp *********/
  43770. BEGIN_JUCE_NAMESPACE
  43771. FilenameComponent::FilenameComponent (const String& name,
  43772. const File& currentFile,
  43773. const bool canEditFilename,
  43774. const bool isDirectory,
  43775. const bool isForSaving,
  43776. const String& fileBrowserWildcard,
  43777. const String& enforcedSuffix_,
  43778. const String& textWhenNothingSelected)
  43779. : Component (name),
  43780. maxRecentFiles (30),
  43781. isDir (isDirectory),
  43782. isSaving (isForSaving),
  43783. isFileDragOver (false),
  43784. wildcard (fileBrowserWildcard),
  43785. enforcedSuffix (enforcedSuffix_)
  43786. {
  43787. addAndMakeVisible (filenameBox = new ComboBox (T("fn")));
  43788. filenameBox->setEditableText (canEditFilename);
  43789. filenameBox->addListener (this);
  43790. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  43791. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  43792. browseButton = 0;
  43793. setBrowseButtonText (T("..."));
  43794. setCurrentFile (currentFile, true);
  43795. }
  43796. FilenameComponent::~FilenameComponent()
  43797. {
  43798. deleteAllChildren();
  43799. }
  43800. void FilenameComponent::paintOverChildren (Graphics& g)
  43801. {
  43802. if (isFileDragOver)
  43803. {
  43804. g.setColour (Colours::red.withAlpha (0.2f));
  43805. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  43806. }
  43807. }
  43808. void FilenameComponent::resized()
  43809. {
  43810. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  43811. }
  43812. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  43813. {
  43814. browseButtonText = newBrowseButtonText;
  43815. lookAndFeelChanged();
  43816. }
  43817. void FilenameComponent::lookAndFeelChanged()
  43818. {
  43819. deleteAndZero (browseButton);
  43820. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  43821. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  43822. resized();
  43823. browseButton->addButtonListener (this);
  43824. }
  43825. void FilenameComponent::setTooltip (const String& newTooltip)
  43826. {
  43827. SettableTooltipClient::setTooltip (newTooltip);
  43828. filenameBox->setTooltip (newTooltip);
  43829. }
  43830. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  43831. {
  43832. defaultBrowseFile = newDefaultDirectory;
  43833. }
  43834. void FilenameComponent::buttonClicked (Button*)
  43835. {
  43836. FileChooser fc (TRANS("Choose a new file"),
  43837. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  43838. : getCurrentFile(),
  43839. wildcard);
  43840. if (isDir ? fc.browseForDirectory()
  43841. : (isSaving ? fc.browseForFileToSave (false)
  43842. : fc.browseForFileToOpen()))
  43843. {
  43844. setCurrentFile (fc.getResult(), true);
  43845. }
  43846. }
  43847. void FilenameComponent::comboBoxChanged (ComboBox*)
  43848. {
  43849. setCurrentFile (getCurrentFile(), true);
  43850. }
  43851. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  43852. {
  43853. return true;
  43854. }
  43855. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  43856. {
  43857. isFileDragOver = false;
  43858. repaint();
  43859. const File f (filenames[0]);
  43860. if (f.exists() && (f.isDirectory() == isDir))
  43861. setCurrentFile (f, true);
  43862. }
  43863. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  43864. {
  43865. isFileDragOver = true;
  43866. repaint();
  43867. }
  43868. void FilenameComponent::fileDragExit (const StringArray&)
  43869. {
  43870. isFileDragOver = false;
  43871. repaint();
  43872. }
  43873. const File FilenameComponent::getCurrentFile() const
  43874. {
  43875. File f (filenameBox->getText());
  43876. if (enforcedSuffix.isNotEmpty())
  43877. f = f.withFileExtension (enforcedSuffix);
  43878. return f;
  43879. }
  43880. void FilenameComponent::setCurrentFile (File newFile,
  43881. const bool addToRecentlyUsedList,
  43882. const bool sendChangeNotification)
  43883. {
  43884. if (enforcedSuffix.isNotEmpty())
  43885. newFile = newFile.withFileExtension (enforcedSuffix);
  43886. if (newFile.getFullPathName() != lastFilename)
  43887. {
  43888. lastFilename = newFile.getFullPathName();
  43889. if (addToRecentlyUsedList)
  43890. addRecentlyUsedFile (newFile);
  43891. filenameBox->setText (lastFilename, true);
  43892. if (sendChangeNotification)
  43893. triggerAsyncUpdate();
  43894. }
  43895. }
  43896. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  43897. {
  43898. filenameBox->setEditableText (shouldBeEditable);
  43899. }
  43900. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  43901. {
  43902. StringArray names;
  43903. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  43904. names.add (filenameBox->getItemText (i));
  43905. return names;
  43906. }
  43907. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  43908. {
  43909. if (filenames != getRecentlyUsedFilenames())
  43910. {
  43911. filenameBox->clear();
  43912. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  43913. filenameBox->addItem (filenames[i], i + 1);
  43914. }
  43915. }
  43916. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  43917. {
  43918. maxRecentFiles = jmax (1, newMaximum);
  43919. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  43920. }
  43921. void FilenameComponent::addRecentlyUsedFile (const File& file)
  43922. {
  43923. StringArray files (getRecentlyUsedFilenames());
  43924. if (file.getFullPathName().isNotEmpty())
  43925. {
  43926. files.removeString (file.getFullPathName(), true);
  43927. files.insert (0, file.getFullPathName());
  43928. setRecentlyUsedFilenames (files);
  43929. }
  43930. }
  43931. void FilenameComponent::addListener (FilenameComponentListener* const listener) throw()
  43932. {
  43933. jassert (listener != 0);
  43934. if (listener != 0)
  43935. listeners.add (listener);
  43936. }
  43937. void FilenameComponent::removeListener (FilenameComponentListener* const listener) throw()
  43938. {
  43939. listeners.removeValue (listener);
  43940. }
  43941. void FilenameComponent::handleAsyncUpdate()
  43942. {
  43943. for (int i = listeners.size(); --i >= 0;)
  43944. {
  43945. ((FilenameComponentListener*) listeners.getUnchecked (i))->filenameComponentChanged (this);
  43946. i = jmin (i, listeners.size());
  43947. }
  43948. }
  43949. END_JUCE_NAMESPACE
  43950. /********* End of inlined file: juce_FilenameComponent.cpp *********/
  43951. /********* Start of inlined file: juce_FileSearchPathListComponent.cpp *********/
  43952. BEGIN_JUCE_NAMESPACE
  43953. FileSearchPathListComponent::FileSearchPathListComponent()
  43954. {
  43955. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  43956. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  43957. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  43958. listBox->setOutlineThickness (1);
  43959. addAndMakeVisible (addButton = new TextButton ("+"));
  43960. addButton->addButtonListener (this);
  43961. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  43962. addAndMakeVisible (removeButton = new TextButton ("-"));
  43963. removeButton->addButtonListener (this);
  43964. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  43965. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  43966. changeButton->addButtonListener (this);
  43967. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  43968. upButton->addButtonListener (this);
  43969. {
  43970. Path arrowPath;
  43971. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  43972. DrawablePath arrowImage;
  43973. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  43974. arrowImage.setPath (arrowPath);
  43975. ((DrawableButton*) upButton)->setImages (&arrowImage);
  43976. }
  43977. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  43978. downButton->addButtonListener (this);
  43979. {
  43980. Path arrowPath;
  43981. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  43982. DrawablePath arrowImage;
  43983. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  43984. arrowImage.setPath (arrowPath);
  43985. ((DrawableButton*) downButton)->setImages (&arrowImage);
  43986. }
  43987. updateButtons();
  43988. }
  43989. FileSearchPathListComponent::~FileSearchPathListComponent()
  43990. {
  43991. deleteAllChildren();
  43992. }
  43993. void FileSearchPathListComponent::updateButtons() throw()
  43994. {
  43995. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  43996. removeButton->setEnabled (anythingSelected);
  43997. changeButton->setEnabled (anythingSelected);
  43998. upButton->setEnabled (anythingSelected);
  43999. downButton->setEnabled (anythingSelected);
  44000. }
  44001. void FileSearchPathListComponent::changed() throw()
  44002. {
  44003. listBox->updateContent();
  44004. listBox->repaint();
  44005. updateButtons();
  44006. }
  44007. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  44008. {
  44009. if (newPath.toString() != path.toString())
  44010. {
  44011. path = newPath;
  44012. changed();
  44013. }
  44014. }
  44015. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  44016. {
  44017. defaultBrowseTarget = newDefaultDirectory;
  44018. }
  44019. int FileSearchPathListComponent::getNumRows()
  44020. {
  44021. return path.getNumPaths();
  44022. }
  44023. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  44024. {
  44025. if (rowIsSelected)
  44026. g.fillAll (findColour (TextEditor::highlightColourId));
  44027. g.setColour (findColour (ListBox::textColourId));
  44028. Font f (height * 0.7f);
  44029. f.setHorizontalScale (0.9f);
  44030. g.setFont (f);
  44031. g.drawText (path [rowNumber].getFullPathName(),
  44032. 4, 0, width - 6, height,
  44033. Justification::centredLeft, true);
  44034. }
  44035. void FileSearchPathListComponent::deleteKeyPressed (int row)
  44036. {
  44037. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  44038. {
  44039. path.remove (row);
  44040. changed();
  44041. }
  44042. }
  44043. void FileSearchPathListComponent::returnKeyPressed (int row)
  44044. {
  44045. FileChooser chooser (TRANS("Change folder..."), path [row], T("*"));
  44046. if (chooser.browseForDirectory())
  44047. {
  44048. path.remove (row);
  44049. path.add (chooser.getResult(), row);
  44050. changed();
  44051. }
  44052. }
  44053. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  44054. {
  44055. returnKeyPressed (row);
  44056. }
  44057. void FileSearchPathListComponent::selectedRowsChanged (int)
  44058. {
  44059. updateButtons();
  44060. }
  44061. void FileSearchPathListComponent::paint (Graphics& g)
  44062. {
  44063. g.fillAll (findColour (backgroundColourId));
  44064. }
  44065. void FileSearchPathListComponent::resized()
  44066. {
  44067. const int buttonH = 22;
  44068. const int buttonY = getHeight() - buttonH - 4;
  44069. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  44070. addButton->setBounds (2, buttonY, buttonH, buttonH);
  44071. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  44072. ((TextButton*) changeButton)->changeWidthToFitText (buttonH);
  44073. downButton->setSize (buttonH * 2, buttonH);
  44074. upButton->setSize (buttonH * 2, buttonH);
  44075. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  44076. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  44077. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  44078. }
  44079. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  44080. {
  44081. return true;
  44082. }
  44083. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  44084. {
  44085. for (int i = filenames.size(); --i >= 0;)
  44086. {
  44087. const File f (filenames[i]);
  44088. if (f.isDirectory())
  44089. {
  44090. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  44091. path.add (f, row);
  44092. changed();
  44093. }
  44094. }
  44095. }
  44096. void FileSearchPathListComponent::buttonClicked (Button* button)
  44097. {
  44098. const int currentRow = listBox->getSelectedRow();
  44099. if (button == removeButton)
  44100. {
  44101. deleteKeyPressed (currentRow);
  44102. }
  44103. else if (button == addButton)
  44104. {
  44105. File start (defaultBrowseTarget);
  44106. if (start == File::nonexistent)
  44107. start = path [0];
  44108. if (start == File::nonexistent)
  44109. start = File::getCurrentWorkingDirectory();
  44110. FileChooser chooser (TRANS("Add a folder..."), start, T("*"));
  44111. if (chooser.browseForDirectory())
  44112. {
  44113. path.add (chooser.getResult(), currentRow);
  44114. }
  44115. }
  44116. else if (button == changeButton)
  44117. {
  44118. returnKeyPressed (currentRow);
  44119. }
  44120. else if (button == upButton)
  44121. {
  44122. if (currentRow > 0 && currentRow < path.getNumPaths())
  44123. {
  44124. const File f (path[currentRow]);
  44125. path.remove (currentRow);
  44126. path.add (f, currentRow - 1);
  44127. listBox->selectRow (currentRow - 1);
  44128. }
  44129. }
  44130. else if (button == downButton)
  44131. {
  44132. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  44133. {
  44134. const File f (path[currentRow]);
  44135. path.remove (currentRow);
  44136. path.add (f, currentRow + 1);
  44137. listBox->selectRow (currentRow + 1);
  44138. }
  44139. }
  44140. changed();
  44141. }
  44142. END_JUCE_NAMESPACE
  44143. /********* End of inlined file: juce_FileSearchPathListComponent.cpp *********/
  44144. /********* Start of inlined file: juce_FileTreeComponent.cpp *********/
  44145. BEGIN_JUCE_NAMESPACE
  44146. Image* juce_createIconForFile (const File& file);
  44147. class FileListTreeItem : public TreeViewItem,
  44148. public TimeSliceClient,
  44149. public AsyncUpdater,
  44150. public ChangeListener
  44151. {
  44152. public:
  44153. FileListTreeItem (FileTreeComponent& owner_,
  44154. DirectoryContentsList* const parentContentsList_,
  44155. const int indexInContentsList_,
  44156. const File& file_,
  44157. TimeSliceThread& thread_) throw()
  44158. : file (file_),
  44159. owner (owner_),
  44160. parentContentsList (parentContentsList_),
  44161. indexInContentsList (indexInContentsList_),
  44162. subContentsList (0),
  44163. canDeleteSubContentsList (false),
  44164. thread (thread_),
  44165. icon (0)
  44166. {
  44167. DirectoryContentsList::FileInfo fileInfo;
  44168. if (parentContentsList_ != 0
  44169. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  44170. {
  44171. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  44172. modTime = fileInfo.modificationTime.formatted (T("%d %b '%y %H:%M"));
  44173. isDirectory = fileInfo.isDirectory;
  44174. }
  44175. else
  44176. {
  44177. isDirectory = true;
  44178. }
  44179. }
  44180. ~FileListTreeItem() throw()
  44181. {
  44182. thread.removeTimeSliceClient (this);
  44183. clearSubItems();
  44184. ImageCache::release (icon);
  44185. if (canDeleteSubContentsList)
  44186. delete subContentsList;
  44187. }
  44188. bool mightContainSubItems() { return isDirectory; }
  44189. const String getUniqueName() const { return file.getFullPathName(); }
  44190. int getItemHeight() const { return 22; }
  44191. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  44192. void itemOpennessChanged (bool isNowOpen)
  44193. {
  44194. if (isNowOpen)
  44195. {
  44196. clearSubItems();
  44197. isDirectory = file.isDirectory();
  44198. if (isDirectory)
  44199. {
  44200. if (subContentsList == 0)
  44201. {
  44202. jassert (parentContentsList != 0);
  44203. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  44204. l->setDirectory (file, true, true);
  44205. setSubContentsList (l);
  44206. canDeleteSubContentsList = true;
  44207. }
  44208. changeListenerCallback (0);
  44209. }
  44210. }
  44211. }
  44212. void setSubContentsList (DirectoryContentsList* newList) throw()
  44213. {
  44214. jassert (subContentsList == 0);
  44215. subContentsList = newList;
  44216. newList->addChangeListener (this);
  44217. }
  44218. void changeListenerCallback (void*)
  44219. {
  44220. clearSubItems();
  44221. if (isOpen() && subContentsList != 0)
  44222. {
  44223. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  44224. {
  44225. FileListTreeItem* const item
  44226. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  44227. addSubItem (item);
  44228. }
  44229. }
  44230. }
  44231. void paintItem (Graphics& g, int width, int height)
  44232. {
  44233. if (file != File::nonexistent && ! isDirectory)
  44234. {
  44235. updateIcon (true);
  44236. if (icon == 0)
  44237. thread.addTimeSliceClient (this);
  44238. }
  44239. owner.getLookAndFeel()
  44240. .drawFileBrowserRow (g, width, height,
  44241. file.getFileName(),
  44242. icon,
  44243. fileSize, modTime,
  44244. isDirectory, isSelected(),
  44245. indexInContentsList);
  44246. }
  44247. void itemClicked (const MouseEvent& e)
  44248. {
  44249. owner.sendMouseClickMessage (file, e);
  44250. }
  44251. void itemDoubleClicked (const MouseEvent& e)
  44252. {
  44253. TreeViewItem::itemDoubleClicked (e);
  44254. owner.sendDoubleClickMessage (file);
  44255. }
  44256. void itemSelectionChanged (bool)
  44257. {
  44258. owner.sendSelectionChangeMessage();
  44259. }
  44260. bool useTimeSlice()
  44261. {
  44262. updateIcon (false);
  44263. thread.removeTimeSliceClient (this);
  44264. return false;
  44265. }
  44266. void handleAsyncUpdate()
  44267. {
  44268. owner.repaint();
  44269. }
  44270. const File file;
  44271. juce_UseDebuggingNewOperator
  44272. private:
  44273. FileTreeComponent& owner;
  44274. DirectoryContentsList* parentContentsList;
  44275. int indexInContentsList;
  44276. DirectoryContentsList* subContentsList;
  44277. bool isDirectory, canDeleteSubContentsList;
  44278. TimeSliceThread& thread;
  44279. Image* icon;
  44280. String fileSize;
  44281. String modTime;
  44282. void updateIcon (const bool onlyUpdateIfCached) throw()
  44283. {
  44284. if (icon == 0)
  44285. {
  44286. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  44287. Image* im = ImageCache::getFromHashCode (hashCode);
  44288. if (im == 0 && ! onlyUpdateIfCached)
  44289. {
  44290. im = juce_createIconForFile (file);
  44291. if (im != 0)
  44292. ImageCache::addImageToCache (im, hashCode);
  44293. }
  44294. if (im != 0)
  44295. {
  44296. icon = im;
  44297. triggerAsyncUpdate();
  44298. }
  44299. }
  44300. }
  44301. };
  44302. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  44303. : DirectoryContentsDisplayComponent (listToShow)
  44304. {
  44305. FileListTreeItem* const root
  44306. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  44307. listToShow.getTimeSliceThread());
  44308. root->setSubContentsList (&listToShow);
  44309. setRootItemVisible (false);
  44310. setRootItem (root);
  44311. }
  44312. FileTreeComponent::~FileTreeComponent()
  44313. {
  44314. TreeViewItem* const root = getRootItem();
  44315. setRootItem (0);
  44316. delete root;
  44317. }
  44318. const File FileTreeComponent::getSelectedFile() const
  44319. {
  44320. return getSelectedFile (0);
  44321. }
  44322. const File FileTreeComponent::getSelectedFile (const int index) const throw()
  44323. {
  44324. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  44325. if (item != 0)
  44326. return item->file;
  44327. return File::nonexistent;
  44328. }
  44329. void FileTreeComponent::scrollToTop()
  44330. {
  44331. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  44332. }
  44333. void FileTreeComponent::setDragAndDropDescription (const String& description) throw()
  44334. {
  44335. dragAndDropDescription = description;
  44336. }
  44337. END_JUCE_NAMESPACE
  44338. /********* End of inlined file: juce_FileTreeComponent.cpp *********/
  44339. /********* Start of inlined file: juce_ImagePreviewComponent.cpp *********/
  44340. BEGIN_JUCE_NAMESPACE
  44341. ImagePreviewComponent::ImagePreviewComponent()
  44342. : currentThumbnail (0)
  44343. {
  44344. }
  44345. ImagePreviewComponent::~ImagePreviewComponent()
  44346. {
  44347. delete currentThumbnail;
  44348. }
  44349. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  44350. {
  44351. const int availableW = proportionOfWidth (0.97f);
  44352. const int availableH = getHeight() - 13 * 4;
  44353. const double scale = jmin (1.0,
  44354. availableW / (double) w,
  44355. availableH / (double) h);
  44356. w = roundDoubleToInt (scale * w);
  44357. h = roundDoubleToInt (scale * h);
  44358. }
  44359. void ImagePreviewComponent::selectedFileChanged (const File& file)
  44360. {
  44361. if (fileToLoad != file)
  44362. {
  44363. fileToLoad = file;
  44364. startTimer (100);
  44365. }
  44366. }
  44367. void ImagePreviewComponent::timerCallback()
  44368. {
  44369. stopTimer();
  44370. deleteAndZero (currentThumbnail);
  44371. currentDetails = String::empty;
  44372. repaint();
  44373. FileInputStream* const in = fileToLoad.createInputStream();
  44374. if (in != 0)
  44375. {
  44376. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  44377. if (format != 0)
  44378. {
  44379. currentThumbnail = format->decodeImage (*in);
  44380. if (currentThumbnail != 0)
  44381. {
  44382. int w = currentThumbnail->getWidth();
  44383. int h = currentThumbnail->getHeight();
  44384. currentDetails
  44385. << fileToLoad.getFileName() << "\n"
  44386. << format->getFormatName() << "\n"
  44387. << w << " x " << h << " pixels\n"
  44388. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  44389. getThumbSize (w, h);
  44390. Image* const reduced = currentThumbnail->createCopy (w, h);
  44391. delete currentThumbnail;
  44392. currentThumbnail = reduced;
  44393. }
  44394. }
  44395. delete in;
  44396. }
  44397. }
  44398. void ImagePreviewComponent::paint (Graphics& g)
  44399. {
  44400. if (currentThumbnail != 0)
  44401. {
  44402. g.setFont (13.0f);
  44403. int w = currentThumbnail->getWidth();
  44404. int h = currentThumbnail->getHeight();
  44405. getThumbSize (w, h);
  44406. const int numLines = 4;
  44407. const int totalH = 13 * numLines + h + 4;
  44408. const int y = (getHeight() - totalH) / 2;
  44409. g.drawImageWithin (currentThumbnail,
  44410. (getWidth() - w) / 2, y, w, h,
  44411. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  44412. false);
  44413. g.drawFittedText (currentDetails,
  44414. 0, y + h + 4, getWidth(), 100,
  44415. Justification::centredTop, numLines);
  44416. }
  44417. }
  44418. END_JUCE_NAMESPACE
  44419. /********* End of inlined file: juce_ImagePreviewComponent.cpp *********/
  44420. /********* Start of inlined file: juce_WildcardFileFilter.cpp *********/
  44421. BEGIN_JUCE_NAMESPACE
  44422. WildcardFileFilter::WildcardFileFilter (const String& wildcardPatterns,
  44423. const String& description)
  44424. : FileFilter (description.isEmpty() ? wildcardPatterns
  44425. : (description + T(" (") + wildcardPatterns + T(")")))
  44426. {
  44427. wildcards.addTokens (wildcardPatterns.toLowerCase(), T(";,"), T("\"'"));
  44428. wildcards.trim();
  44429. wildcards.removeEmptyStrings();
  44430. // special case for *.*, because people use it to mean "any file", but it
  44431. // would actually ignore files with no extension.
  44432. for (int i = wildcards.size(); --i >= 0;)
  44433. if (wildcards[i] == T("*.*"))
  44434. wildcards.set (i, T("*"));
  44435. }
  44436. WildcardFileFilter::~WildcardFileFilter()
  44437. {
  44438. }
  44439. bool WildcardFileFilter::isFileSuitable (const File& file) const
  44440. {
  44441. const String filename (file.getFileName());
  44442. for (int i = wildcards.size(); --i >= 0;)
  44443. if (filename.matchesWildcard (wildcards[i], true))
  44444. return true;
  44445. return false;
  44446. }
  44447. bool WildcardFileFilter::isDirectorySuitable (const File&) const
  44448. {
  44449. return true;
  44450. }
  44451. END_JUCE_NAMESPACE
  44452. /********* End of inlined file: juce_WildcardFileFilter.cpp *********/
  44453. /********* Start of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  44454. BEGIN_JUCE_NAMESPACE
  44455. KeyboardFocusTraverser::KeyboardFocusTraverser()
  44456. {
  44457. }
  44458. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  44459. {
  44460. }
  44461. // This will sort a set of components, so that they are ordered in terms of
  44462. // left-to-right and then top-to-bottom.
  44463. class ScreenPositionComparator
  44464. {
  44465. public:
  44466. ScreenPositionComparator() {}
  44467. static int compareElements (const Component* const first, const Component* const second) throw()
  44468. {
  44469. int explicitOrder1 = first->getExplicitFocusOrder();
  44470. if (explicitOrder1 <= 0)
  44471. explicitOrder1 = INT_MAX / 2;
  44472. int explicitOrder2 = second->getExplicitFocusOrder();
  44473. if (explicitOrder2 <= 0)
  44474. explicitOrder2 = INT_MAX / 2;
  44475. if (explicitOrder1 != explicitOrder2)
  44476. return explicitOrder1 - explicitOrder2;
  44477. const int diff = first->getY() - second->getY();
  44478. return (diff == 0) ? first->getX() - second->getX()
  44479. : diff;
  44480. }
  44481. };
  44482. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  44483. {
  44484. if (parent->getNumChildComponents() > 0)
  44485. {
  44486. Array <Component*> localComps;
  44487. ScreenPositionComparator comparator;
  44488. int i;
  44489. for (i = parent->getNumChildComponents(); --i >= 0;)
  44490. {
  44491. Component* const c = parent->getChildComponent (i);
  44492. if (c->isVisible() && c->isEnabled())
  44493. localComps.addSorted (comparator, c);
  44494. }
  44495. for (i = 0; i < localComps.size(); ++i)
  44496. {
  44497. Component* const c = localComps.getUnchecked (i);
  44498. if (c->getWantsKeyboardFocus())
  44499. comps.add (c);
  44500. if (! c->isFocusContainer())
  44501. findAllFocusableComponents (c, comps);
  44502. }
  44503. }
  44504. }
  44505. static Component* getIncrementedComponent (Component* const current, const int delta) throw()
  44506. {
  44507. Component* focusContainer = current->getParentComponent();
  44508. if (focusContainer != 0)
  44509. {
  44510. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  44511. focusContainer = focusContainer->getParentComponent();
  44512. if (focusContainer != 0)
  44513. {
  44514. Array <Component*> comps;
  44515. findAllFocusableComponents (focusContainer, comps);
  44516. if (comps.size() > 0)
  44517. {
  44518. const int index = comps.indexOf (current);
  44519. return comps [(index + comps.size() + delta) % comps.size()];
  44520. }
  44521. }
  44522. }
  44523. return 0;
  44524. }
  44525. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  44526. {
  44527. return getIncrementedComponent (current, 1);
  44528. }
  44529. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  44530. {
  44531. return getIncrementedComponent (current, -1);
  44532. }
  44533. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  44534. {
  44535. Array <Component*> comps;
  44536. if (parentComponent != 0)
  44537. findAllFocusableComponents (parentComponent, comps);
  44538. return comps.getFirst();
  44539. }
  44540. END_JUCE_NAMESPACE
  44541. /********* End of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  44542. /********* Start of inlined file: juce_KeyListener.cpp *********/
  44543. BEGIN_JUCE_NAMESPACE
  44544. bool KeyListener::keyStateChanged (const bool, Component*)
  44545. {
  44546. return false;
  44547. }
  44548. END_JUCE_NAMESPACE
  44549. /********* End of inlined file: juce_KeyListener.cpp *********/
  44550. /********* Start of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  44551. BEGIN_JUCE_NAMESPACE
  44552. // N.B. these two includes are put here deliberately to avoid problems with
  44553. // old GCCs failing on long include paths
  44554. const int maxKeys = 3;
  44555. class KeyMappingChangeButton : public Button
  44556. {
  44557. public:
  44558. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  44559. const CommandID commandID_,
  44560. const String& keyName,
  44561. const int keyNum_)
  44562. : Button (keyName),
  44563. owner (owner_),
  44564. commandID (commandID_),
  44565. keyNum (keyNum_)
  44566. {
  44567. setWantsKeyboardFocus (false);
  44568. setTriggeredOnMouseDown (keyNum >= 0);
  44569. if (keyNum_ < 0)
  44570. setTooltip (TRANS("adds a new key-mapping"));
  44571. else
  44572. setTooltip (TRANS("click to change this key-mapping"));
  44573. }
  44574. ~KeyMappingChangeButton()
  44575. {
  44576. }
  44577. void paintButton (Graphics& g, bool isOver, bool isDown)
  44578. {
  44579. if (keyNum >= 0)
  44580. {
  44581. if (isEnabled())
  44582. {
  44583. const float alpha = isDown ? 0.3f : (isOver ? 0.15f : 0.08f);
  44584. g.fillAll (owner->textColour.withAlpha (alpha));
  44585. g.setOpacity (0.3f);
  44586. g.drawBevel (0, 0, getWidth(), getHeight(), 2);
  44587. }
  44588. g.setColour (owner->textColour);
  44589. g.setFont (getHeight() * 0.6f);
  44590. g.drawFittedText (getName(),
  44591. 3, 0, getWidth() - 6, getHeight(),
  44592. Justification::centred, 1);
  44593. }
  44594. else
  44595. {
  44596. const float thickness = 7.0f;
  44597. const float indent = 22.0f;
  44598. Path p;
  44599. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  44600. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  44601. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  44602. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  44603. p.setUsingNonZeroWinding (false);
  44604. g.setColour (owner->textColour.withAlpha (isDown ? 0.7f : (isOver ? 0.5f : 0.3f)));
  44605. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, true));
  44606. }
  44607. if (hasKeyboardFocus (false))
  44608. {
  44609. g.setColour (owner->textColour.withAlpha (0.4f));
  44610. g.drawRect (0, 0, getWidth(), getHeight());
  44611. }
  44612. }
  44613. void clicked()
  44614. {
  44615. if (keyNum >= 0)
  44616. {
  44617. // existing key clicked..
  44618. PopupMenu m;
  44619. m.addItem (1, TRANS("change this key-mapping"));
  44620. m.addSeparator();
  44621. m.addItem (2, TRANS("remove this key-mapping"));
  44622. const int res = m.show();
  44623. if (res == 1)
  44624. {
  44625. owner->assignNewKey (commandID, keyNum);
  44626. }
  44627. else if (res == 2)
  44628. {
  44629. owner->getMappings()->removeKeyPress (commandID, keyNum);
  44630. }
  44631. }
  44632. else
  44633. {
  44634. // + button pressed..
  44635. owner->assignNewKey (commandID, -1);
  44636. }
  44637. }
  44638. void fitToContent (const int h) throw()
  44639. {
  44640. if (keyNum < 0)
  44641. {
  44642. setSize (h, h);
  44643. }
  44644. else
  44645. {
  44646. Font f (h * 0.6f);
  44647. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  44648. }
  44649. }
  44650. juce_UseDebuggingNewOperator
  44651. private:
  44652. KeyMappingEditorComponent* const owner;
  44653. const CommandID commandID;
  44654. const int keyNum;
  44655. KeyMappingChangeButton (const KeyMappingChangeButton&);
  44656. const KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  44657. };
  44658. class KeyMappingItemComponent : public Component
  44659. {
  44660. public:
  44661. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  44662. const CommandID commandID_)
  44663. : owner (owner_),
  44664. commandID (commandID_)
  44665. {
  44666. setInterceptsMouseClicks (false, true);
  44667. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  44668. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  44669. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  44670. {
  44671. KeyMappingChangeButton* const kb
  44672. = new KeyMappingChangeButton (owner_, commandID,
  44673. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  44674. kb->setEnabled (! isReadOnly);
  44675. addAndMakeVisible (kb);
  44676. }
  44677. KeyMappingChangeButton* const kb
  44678. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  44679. addChildComponent (kb);
  44680. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  44681. }
  44682. ~KeyMappingItemComponent()
  44683. {
  44684. deleteAllChildren();
  44685. }
  44686. void paint (Graphics& g)
  44687. {
  44688. g.setFont (getHeight() * 0.7f);
  44689. g.setColour (owner->textColour);
  44690. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  44691. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  44692. Justification::centredLeft, true);
  44693. }
  44694. void resized()
  44695. {
  44696. int x = getWidth() - 4;
  44697. for (int i = getNumChildComponents(); --i >= 0;)
  44698. {
  44699. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  44700. kb->fitToContent (getHeight() - 2);
  44701. kb->setTopRightPosition (x, 1);
  44702. x -= kb->getWidth() + 5;
  44703. }
  44704. }
  44705. juce_UseDebuggingNewOperator
  44706. private:
  44707. KeyMappingEditorComponent* const owner;
  44708. const CommandID commandID;
  44709. KeyMappingItemComponent (const KeyMappingItemComponent&);
  44710. const KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  44711. };
  44712. class KeyMappingTreeViewItem : public TreeViewItem
  44713. {
  44714. public:
  44715. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  44716. const CommandID commandID_)
  44717. : owner (owner_),
  44718. commandID (commandID_)
  44719. {
  44720. }
  44721. ~KeyMappingTreeViewItem()
  44722. {
  44723. }
  44724. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  44725. bool mightContainSubItems() { return false; }
  44726. int getItemHeight() const { return 20; }
  44727. Component* createItemComponent()
  44728. {
  44729. return new KeyMappingItemComponent (owner, commandID);
  44730. }
  44731. juce_UseDebuggingNewOperator
  44732. private:
  44733. KeyMappingEditorComponent* const owner;
  44734. const CommandID commandID;
  44735. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  44736. const KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  44737. };
  44738. class KeyCategoryTreeViewItem : public TreeViewItem
  44739. {
  44740. public:
  44741. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  44742. const String& name)
  44743. : owner (owner_),
  44744. categoryName (name)
  44745. {
  44746. }
  44747. ~KeyCategoryTreeViewItem()
  44748. {
  44749. }
  44750. const String getUniqueName() const { return categoryName + "_cat"; }
  44751. bool mightContainSubItems() { return true; }
  44752. int getItemHeight() const { return 28; }
  44753. void paintItem (Graphics& g, int width, int height)
  44754. {
  44755. g.setFont (height * 0.6f, Font::bold);
  44756. g.setColour (owner->textColour);
  44757. g.drawText (categoryName,
  44758. 2, 0, width - 2, height,
  44759. Justification::centredLeft, true);
  44760. }
  44761. void itemOpennessChanged (bool isNowOpen)
  44762. {
  44763. if (isNowOpen)
  44764. {
  44765. if (getNumSubItems() == 0)
  44766. {
  44767. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  44768. for (int i = 0; i < commands.size(); ++i)
  44769. {
  44770. if (owner->shouldCommandBeIncluded (commands[i]))
  44771. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  44772. }
  44773. }
  44774. }
  44775. else
  44776. {
  44777. clearSubItems();
  44778. }
  44779. }
  44780. juce_UseDebuggingNewOperator
  44781. private:
  44782. KeyMappingEditorComponent* owner;
  44783. String categoryName;
  44784. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  44785. const KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  44786. };
  44787. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  44788. const bool showResetToDefaultButton)
  44789. : mappings (mappingManager),
  44790. textColour (Colours::black)
  44791. {
  44792. jassert (mappingManager != 0); // can't be null!
  44793. mappingManager->addChangeListener (this);
  44794. setLinesDrawnForSubItems (false);
  44795. resetButton = 0;
  44796. if (showResetToDefaultButton)
  44797. {
  44798. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  44799. resetButton->addButtonListener (this);
  44800. }
  44801. addAndMakeVisible (tree = new TreeView());
  44802. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  44803. tree->setRootItemVisible (false);
  44804. tree->setDefaultOpenness (true);
  44805. tree->setRootItem (this);
  44806. }
  44807. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  44808. {
  44809. mappings->removeChangeListener (this);
  44810. deleteAllChildren();
  44811. }
  44812. bool KeyMappingEditorComponent::mightContainSubItems()
  44813. {
  44814. return true;
  44815. }
  44816. const String KeyMappingEditorComponent::getUniqueName() const
  44817. {
  44818. return T("keys");
  44819. }
  44820. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  44821. const Colour& textColour_)
  44822. {
  44823. backgroundColour = mainBackground;
  44824. textColour = textColour_;
  44825. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  44826. }
  44827. void KeyMappingEditorComponent::parentHierarchyChanged()
  44828. {
  44829. changeListenerCallback (0);
  44830. }
  44831. void KeyMappingEditorComponent::resized()
  44832. {
  44833. int h = getHeight();
  44834. if (resetButton != 0)
  44835. {
  44836. const int buttonHeight = 20;
  44837. h -= buttonHeight + 8;
  44838. int x = getWidth() - 8;
  44839. const int y = h + 6;
  44840. resetButton->changeWidthToFitText (buttonHeight);
  44841. resetButton->setTopRightPosition (x, y);
  44842. }
  44843. tree->setBounds (0, 0, getWidth(), h);
  44844. }
  44845. void KeyMappingEditorComponent::buttonClicked (Button* button)
  44846. {
  44847. if (button == resetButton)
  44848. {
  44849. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  44850. TRANS("Reset to defaults"),
  44851. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  44852. TRANS("Reset")))
  44853. {
  44854. mappings->resetToDefaultMappings();
  44855. }
  44856. }
  44857. }
  44858. void KeyMappingEditorComponent::changeListenerCallback (void*)
  44859. {
  44860. XmlElement* openness = tree->getOpennessState (true);
  44861. clearSubItems();
  44862. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  44863. for (int i = 0; i < categories.size(); ++i)
  44864. {
  44865. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  44866. int count = 0;
  44867. for (int j = 0; j < commands.size(); ++j)
  44868. if (shouldCommandBeIncluded (commands[j]))
  44869. ++count;
  44870. if (count > 0)
  44871. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  44872. }
  44873. if (openness != 0)
  44874. {
  44875. tree->restoreOpennessState (*openness);
  44876. delete openness;
  44877. }
  44878. }
  44879. class KeyEntryWindow : public AlertWindow
  44880. {
  44881. public:
  44882. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  44883. : AlertWindow (TRANS("New key-mapping"),
  44884. TRANS("Please press a key combination now..."),
  44885. AlertWindow::NoIcon),
  44886. owner (owner_)
  44887. {
  44888. addButton (TRANS("ok"), 1);
  44889. addButton (TRANS("cancel"), 0);
  44890. // (avoid return + escape keys getting processed by the buttons..)
  44891. for (int i = getNumChildComponents(); --i >= 0;)
  44892. getChildComponent (i)->setWantsKeyboardFocus (false);
  44893. setWantsKeyboardFocus (true);
  44894. grabKeyboardFocus();
  44895. }
  44896. ~KeyEntryWindow()
  44897. {
  44898. }
  44899. bool keyPressed (const KeyPress& key)
  44900. {
  44901. lastPress = key;
  44902. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  44903. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  44904. if (previousCommand != 0)
  44905. {
  44906. message << "\n\n"
  44907. << TRANS("(Currently assigned to \"")
  44908. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  44909. << "\")";
  44910. }
  44911. setMessage (message);
  44912. return true;
  44913. }
  44914. bool keyStateChanged (const bool)
  44915. {
  44916. return true;
  44917. }
  44918. KeyPress lastPress;
  44919. juce_UseDebuggingNewOperator
  44920. private:
  44921. KeyMappingEditorComponent* owner;
  44922. KeyEntryWindow (const KeyEntryWindow&);
  44923. const KeyEntryWindow& operator= (const KeyEntryWindow&);
  44924. };
  44925. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  44926. {
  44927. KeyEntryWindow entryWindow (this);
  44928. if (entryWindow.runModalLoop() != 0)
  44929. {
  44930. entryWindow.setVisible (false);
  44931. if (entryWindow.lastPress.isValid())
  44932. {
  44933. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  44934. if (previousCommand != 0)
  44935. {
  44936. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  44937. TRANS("Change key-mapping"),
  44938. TRANS("This key is already assigned to the command \"")
  44939. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  44940. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  44941. TRANS("re-assign"),
  44942. TRANS("cancel")))
  44943. {
  44944. return;
  44945. }
  44946. }
  44947. mappings->removeKeyPress (entryWindow.lastPress);
  44948. if (index >= 0)
  44949. mappings->removeKeyPress (commandID, index);
  44950. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  44951. }
  44952. }
  44953. }
  44954. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  44955. {
  44956. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  44957. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  44958. }
  44959. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  44960. {
  44961. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  44962. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  44963. }
  44964. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  44965. {
  44966. return key.getTextDescription();
  44967. }
  44968. END_JUCE_NAMESPACE
  44969. /********* End of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  44970. /********* Start of inlined file: juce_KeyPress.cpp *********/
  44971. BEGIN_JUCE_NAMESPACE
  44972. KeyPress::KeyPress() throw()
  44973. : keyCode (0),
  44974. mods (0),
  44975. textCharacter (0)
  44976. {
  44977. }
  44978. KeyPress::KeyPress (const int keyCode_,
  44979. const ModifierKeys& mods_,
  44980. const juce_wchar textCharacter_) throw()
  44981. : keyCode (keyCode_),
  44982. mods (mods_),
  44983. textCharacter (textCharacter_)
  44984. {
  44985. }
  44986. KeyPress::KeyPress (const int keyCode_) throw()
  44987. : keyCode (keyCode_),
  44988. textCharacter (0)
  44989. {
  44990. }
  44991. KeyPress::KeyPress (const KeyPress& other) throw()
  44992. : keyCode (other.keyCode),
  44993. mods (other.mods),
  44994. textCharacter (other.textCharacter)
  44995. {
  44996. }
  44997. const KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  44998. {
  44999. keyCode = other.keyCode;
  45000. mods = other.mods;
  45001. textCharacter = other.textCharacter;
  45002. return *this;
  45003. }
  45004. bool KeyPress::operator== (const KeyPress& other) const throw()
  45005. {
  45006. return mods.getRawFlags() == other.mods.getRawFlags()
  45007. && (textCharacter == other.textCharacter
  45008. || textCharacter == 0
  45009. || other.textCharacter == 0)
  45010. && (keyCode == other.keyCode
  45011. || (keyCode < 256
  45012. && other.keyCode < 256
  45013. && CharacterFunctions::toLowerCase ((tchar) keyCode)
  45014. == CharacterFunctions::toLowerCase ((tchar) other.keyCode)));
  45015. }
  45016. bool KeyPress::operator!= (const KeyPress& other) const throw()
  45017. {
  45018. return ! operator== (other);
  45019. }
  45020. bool KeyPress::isCurrentlyDown() const throw()
  45021. {
  45022. return isKeyCurrentlyDown (keyCode)
  45023. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  45024. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  45025. }
  45026. struct KeyNameAndCode
  45027. {
  45028. const char* name;
  45029. int code;
  45030. };
  45031. static const KeyNameAndCode keyNameTranslations[] =
  45032. {
  45033. { "spacebar", KeyPress::spaceKey },
  45034. { "return", KeyPress::returnKey },
  45035. { "escape", KeyPress::escapeKey },
  45036. { "backspace", KeyPress::backspaceKey },
  45037. { "cursor left", KeyPress::leftKey },
  45038. { "cursor right", KeyPress::rightKey },
  45039. { "cursor up", KeyPress::upKey },
  45040. { "cursor down", KeyPress::downKey },
  45041. { "page up", KeyPress::pageUpKey },
  45042. { "page down", KeyPress::pageDownKey },
  45043. { "home", KeyPress::homeKey },
  45044. { "end", KeyPress::endKey },
  45045. { "delete", KeyPress::deleteKey },
  45046. { "insert", KeyPress::insertKey },
  45047. { "tab", KeyPress::tabKey },
  45048. { "play", KeyPress::playKey },
  45049. { "stop", KeyPress::stopKey },
  45050. { "fast forward", KeyPress::fastForwardKey },
  45051. { "rewind", KeyPress::rewindKey }
  45052. };
  45053. static const tchar* const numberPadPrefix = T("numpad ");
  45054. const KeyPress KeyPress::createFromDescription (const String& desc) throw()
  45055. {
  45056. int modifiers = 0;
  45057. if (desc.containsWholeWordIgnoreCase (T("ctrl"))
  45058. || desc.containsWholeWordIgnoreCase (T("control"))
  45059. || desc.containsWholeWordIgnoreCase (T("ctl")))
  45060. modifiers |= ModifierKeys::ctrlModifier;
  45061. if (desc.containsWholeWordIgnoreCase (T("shift"))
  45062. || desc.containsWholeWordIgnoreCase (T("shft")))
  45063. modifiers |= ModifierKeys::shiftModifier;
  45064. if (desc.containsWholeWordIgnoreCase (T("alt"))
  45065. || desc.containsWholeWordIgnoreCase (T("option")))
  45066. modifiers |= ModifierKeys::altModifier;
  45067. if (desc.containsWholeWordIgnoreCase (T("command"))
  45068. || desc.containsWholeWordIgnoreCase (T("cmd")))
  45069. modifiers |= ModifierKeys::commandModifier;
  45070. int key = 0;
  45071. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  45072. {
  45073. if (desc.containsWholeWordIgnoreCase (String (keyNameTranslations[i].name)))
  45074. {
  45075. key = keyNameTranslations[i].code;
  45076. break;
  45077. }
  45078. }
  45079. if (key == 0)
  45080. {
  45081. // see if it's a numpad key..
  45082. if (desc.containsIgnoreCase (numberPadPrefix))
  45083. {
  45084. const tchar lastChar = desc.trimEnd().getLastCharacter();
  45085. if (lastChar >= T('0') && lastChar <= T('9'))
  45086. key = numberPad0 + lastChar - T('0');
  45087. else if (lastChar == T('+'))
  45088. key = numberPadAdd;
  45089. else if (lastChar == T('-'))
  45090. key = numberPadSubtract;
  45091. else if (lastChar == T('*'))
  45092. key = numberPadMultiply;
  45093. else if (lastChar == T('/'))
  45094. key = numberPadDivide;
  45095. else if (lastChar == T('.'))
  45096. key = numberPadDecimalPoint;
  45097. else if (lastChar == T('='))
  45098. key = numberPadEquals;
  45099. else if (desc.endsWith (T("separator")))
  45100. key = numberPadSeparator;
  45101. else if (desc.endsWith (T("delete")))
  45102. key = numberPadDelete;
  45103. }
  45104. if (key == 0)
  45105. {
  45106. // see if it's a function key..
  45107. for (int i = 1; i <= 12; ++i)
  45108. if (desc.containsWholeWordIgnoreCase (T("f") + String (i)))
  45109. key = F1Key + i - 1;
  45110. if (key == 0)
  45111. {
  45112. // give up and use the hex code..
  45113. const int hexCode = desc.fromFirstOccurrenceOf (T("#"), false, false)
  45114. .toLowerCase()
  45115. .retainCharacters (T("0123456789abcdef"))
  45116. .getHexValue32();
  45117. if (hexCode > 0)
  45118. key = hexCode;
  45119. else
  45120. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  45121. }
  45122. }
  45123. }
  45124. return KeyPress (key, ModifierKeys (modifiers), 0);
  45125. }
  45126. const String KeyPress::getTextDescription() const throw()
  45127. {
  45128. String desc;
  45129. if (keyCode > 0)
  45130. {
  45131. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  45132. // want to store it as being a slash, not shift+whatever.
  45133. if (textCharacter == T('/'))
  45134. return "/";
  45135. if (mods.isCtrlDown())
  45136. desc << "ctrl + ";
  45137. if (mods.isShiftDown())
  45138. desc << "shift + ";
  45139. #if JUCE_MAC
  45140. // only do this on the mac, because on Windows ctrl and command are the same,
  45141. // and this would get confusing
  45142. if (mods.isCommandDown())
  45143. desc << "command + ";
  45144. if (mods.isAltDown())
  45145. desc << "option + ";
  45146. #else
  45147. if (mods.isAltDown())
  45148. desc << "alt + ";
  45149. #endif
  45150. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  45151. if (keyCode == keyNameTranslations[i].code)
  45152. return desc + keyNameTranslations[i].name;
  45153. if (keyCode >= F1Key && keyCode <= F16Key)
  45154. desc << 'F' << (1 + keyCode - F1Key);
  45155. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  45156. desc << numberPadPrefix << (keyCode - numberPad0);
  45157. else if (keyCode >= 33 && keyCode < 176)
  45158. desc += CharacterFunctions::toUpperCase ((tchar) keyCode);
  45159. else if (keyCode == numberPadAdd)
  45160. desc << numberPadPrefix << '+';
  45161. else if (keyCode == numberPadSubtract)
  45162. desc << numberPadPrefix << '-';
  45163. else if (keyCode == numberPadMultiply)
  45164. desc << numberPadPrefix << '*';
  45165. else if (keyCode == numberPadDivide)
  45166. desc << numberPadPrefix << '/';
  45167. else if (keyCode == numberPadSeparator)
  45168. desc << numberPadPrefix << "separator";
  45169. else if (keyCode == numberPadDecimalPoint)
  45170. desc << numberPadPrefix << '.';
  45171. else if (keyCode == numberPadDelete)
  45172. desc << numberPadPrefix << "delete";
  45173. else
  45174. desc << '#' << String::toHexString (keyCode);
  45175. }
  45176. return desc;
  45177. }
  45178. END_JUCE_NAMESPACE
  45179. /********* End of inlined file: juce_KeyPress.cpp *********/
  45180. /********* Start of inlined file: juce_KeyPressMappingSet.cpp *********/
  45181. BEGIN_JUCE_NAMESPACE
  45182. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_) throw()
  45183. : commandManager (commandManager_)
  45184. {
  45185. // A manager is needed to get the descriptions of commands, and will be called when
  45186. // a command is invoked. So you can't leave this null..
  45187. jassert (commandManager_ != 0);
  45188. Desktop::getInstance().addFocusChangeListener (this);
  45189. }
  45190. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other) throw()
  45191. : commandManager (other.commandManager)
  45192. {
  45193. Desktop::getInstance().addFocusChangeListener (this);
  45194. }
  45195. KeyPressMappingSet::~KeyPressMappingSet()
  45196. {
  45197. Desktop::getInstance().removeFocusChangeListener (this);
  45198. }
  45199. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const throw()
  45200. {
  45201. for (int i = 0; i < mappings.size(); ++i)
  45202. if (mappings.getUnchecked(i)->commandID == commandID)
  45203. return mappings.getUnchecked (i)->keypresses;
  45204. return Array <KeyPress> ();
  45205. }
  45206. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  45207. const KeyPress& newKeyPress,
  45208. int insertIndex) throw()
  45209. {
  45210. if (findCommandForKeyPress (newKeyPress) != commandID)
  45211. {
  45212. removeKeyPress (newKeyPress);
  45213. if (newKeyPress.isValid())
  45214. {
  45215. for (int i = mappings.size(); --i >= 0;)
  45216. {
  45217. if (mappings.getUnchecked(i)->commandID == commandID)
  45218. {
  45219. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  45220. sendChangeMessage (this);
  45221. return;
  45222. }
  45223. }
  45224. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45225. if (ci != 0)
  45226. {
  45227. CommandMapping* const cm = new CommandMapping();
  45228. cm->commandID = commandID;
  45229. cm->keypresses.add (newKeyPress);
  45230. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  45231. mappings.add (cm);
  45232. sendChangeMessage (this);
  45233. }
  45234. }
  45235. }
  45236. }
  45237. void KeyPressMappingSet::resetToDefaultMappings() throw()
  45238. {
  45239. mappings.clear();
  45240. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  45241. {
  45242. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  45243. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  45244. {
  45245. addKeyPress (ci->commandID,
  45246. ci->defaultKeypresses.getReference (j));
  45247. }
  45248. }
  45249. sendChangeMessage (this);
  45250. }
  45251. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID) throw()
  45252. {
  45253. clearAllKeyPresses (commandID);
  45254. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45255. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  45256. {
  45257. addKeyPress (ci->commandID,
  45258. ci->defaultKeypresses.getReference (j));
  45259. }
  45260. }
  45261. void KeyPressMappingSet::clearAllKeyPresses() throw()
  45262. {
  45263. if (mappings.size() > 0)
  45264. {
  45265. sendChangeMessage (this);
  45266. mappings.clear();
  45267. }
  45268. }
  45269. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID) throw()
  45270. {
  45271. for (int i = mappings.size(); --i >= 0;)
  45272. {
  45273. if (mappings.getUnchecked(i)->commandID == commandID)
  45274. {
  45275. mappings.remove (i);
  45276. sendChangeMessage (this);
  45277. }
  45278. }
  45279. }
  45280. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress) throw()
  45281. {
  45282. if (keypress.isValid())
  45283. {
  45284. for (int i = mappings.size(); --i >= 0;)
  45285. {
  45286. CommandMapping* const cm = mappings.getUnchecked(i);
  45287. for (int j = cm->keypresses.size(); --j >= 0;)
  45288. {
  45289. if (keypress == cm->keypresses [j])
  45290. {
  45291. cm->keypresses.remove (j);
  45292. sendChangeMessage (this);
  45293. }
  45294. }
  45295. }
  45296. }
  45297. }
  45298. void KeyPressMappingSet::removeKeyPress (const CommandID commandID,
  45299. const int keyPressIndex) throw()
  45300. {
  45301. for (int i = mappings.size(); --i >= 0;)
  45302. {
  45303. if (mappings.getUnchecked(i)->commandID == commandID)
  45304. {
  45305. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  45306. sendChangeMessage (this);
  45307. break;
  45308. }
  45309. }
  45310. }
  45311. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  45312. {
  45313. for (int i = 0; i < mappings.size(); ++i)
  45314. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  45315. return mappings.getUnchecked(i)->commandID;
  45316. return 0;
  45317. }
  45318. bool KeyPressMappingSet::containsMapping (const CommandID commandID,
  45319. const KeyPress& keyPress) const throw()
  45320. {
  45321. for (int i = mappings.size(); --i >= 0;)
  45322. if (mappings.getUnchecked(i)->commandID == commandID)
  45323. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  45324. return false;
  45325. }
  45326. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  45327. const KeyPress& key,
  45328. const bool isKeyDown,
  45329. const int millisecsSinceKeyPressed,
  45330. Component* const originatingComponent) const
  45331. {
  45332. ApplicationCommandTarget::InvocationInfo info (commandID);
  45333. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  45334. info.isKeyDown = isKeyDown;
  45335. info.keyPress = key;
  45336. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  45337. info.originatingComponent = originatingComponent;
  45338. commandManager->invoke (info, false);
  45339. }
  45340. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  45341. {
  45342. if (xmlVersion.hasTagName (T("KEYMAPPINGS")))
  45343. {
  45344. if (xmlVersion.getBoolAttribute (T("basedOnDefaults"), true))
  45345. {
  45346. // if the XML was created as a set of differences from the default mappings,
  45347. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  45348. resetToDefaultMappings();
  45349. }
  45350. else
  45351. {
  45352. // if the XML was created calling createXml (false), then we need to clear all
  45353. // the keys and treat the xml as describing the entire set of mappings.
  45354. clearAllKeyPresses();
  45355. }
  45356. forEachXmlChildElement (xmlVersion, map)
  45357. {
  45358. const CommandID commandId = map->getStringAttribute (T("commandId")).getHexValue32();
  45359. if (commandId != 0)
  45360. {
  45361. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute (T("key"))));
  45362. if (map->hasTagName (T("MAPPING")))
  45363. {
  45364. addKeyPress (commandId, key);
  45365. }
  45366. else if (map->hasTagName (T("UNMAPPING")))
  45367. {
  45368. if (containsMapping (commandId, key))
  45369. removeKeyPress (key);
  45370. }
  45371. }
  45372. }
  45373. return true;
  45374. }
  45375. return false;
  45376. }
  45377. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  45378. {
  45379. KeyPressMappingSet* defaultSet = 0;
  45380. if (saveDifferencesFromDefaultSet)
  45381. {
  45382. defaultSet = new KeyPressMappingSet (commandManager);
  45383. defaultSet->resetToDefaultMappings();
  45384. }
  45385. XmlElement* const doc = new XmlElement (T("KEYMAPPINGS"));
  45386. doc->setAttribute (T("basedOnDefaults"), saveDifferencesFromDefaultSet);
  45387. int i;
  45388. for (i = 0; i < mappings.size(); ++i)
  45389. {
  45390. const CommandMapping* const cm = mappings.getUnchecked(i);
  45391. for (int j = 0; j < cm->keypresses.size(); ++j)
  45392. {
  45393. if (defaultSet == 0
  45394. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  45395. {
  45396. XmlElement* const map = new XmlElement (T("MAPPING"));
  45397. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  45398. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  45399. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  45400. doc->addChildElement (map);
  45401. }
  45402. }
  45403. }
  45404. if (defaultSet != 0)
  45405. {
  45406. for (i = 0; i < defaultSet->mappings.size(); ++i)
  45407. {
  45408. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  45409. for (int j = 0; j < cm->keypresses.size(); ++j)
  45410. {
  45411. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  45412. {
  45413. XmlElement* const map = new XmlElement (T("UNMAPPING"));
  45414. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  45415. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  45416. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  45417. doc->addChildElement (map);
  45418. }
  45419. }
  45420. }
  45421. delete defaultSet;
  45422. }
  45423. return doc;
  45424. }
  45425. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  45426. Component* originatingComponent)
  45427. {
  45428. bool used = false;
  45429. const CommandID commandID = findCommandForKeyPress (key);
  45430. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45431. if (ci != 0
  45432. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  45433. {
  45434. ApplicationCommandInfo info (0);
  45435. if (commandManager->getTargetForCommand (commandID, info) != 0
  45436. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  45437. {
  45438. invokeCommand (commandID, key, true, 0, originatingComponent);
  45439. used = true;
  45440. }
  45441. else
  45442. {
  45443. if (originatingComponent != 0)
  45444. originatingComponent->getLookAndFeel().playAlertSound();
  45445. }
  45446. }
  45447. return used;
  45448. }
  45449. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  45450. {
  45451. bool used = false;
  45452. const uint32 now = Time::getMillisecondCounter();
  45453. for (int i = mappings.size(); --i >= 0;)
  45454. {
  45455. CommandMapping* const cm = mappings.getUnchecked(i);
  45456. if (cm->wantsKeyUpDownCallbacks)
  45457. {
  45458. for (int j = cm->keypresses.size(); --j >= 0;)
  45459. {
  45460. const KeyPress key (cm->keypresses.getReference (j));
  45461. const bool isDown = key.isCurrentlyDown();
  45462. int keyPressEntryIndex = 0;
  45463. bool wasDown = false;
  45464. for (int k = keysDown.size(); --k >= 0;)
  45465. {
  45466. if (key == keysDown.getUnchecked(k)->key)
  45467. {
  45468. keyPressEntryIndex = k;
  45469. wasDown = true;
  45470. used = true;
  45471. break;
  45472. }
  45473. }
  45474. if (isDown != wasDown)
  45475. {
  45476. int millisecs = 0;
  45477. if (isDown)
  45478. {
  45479. KeyPressTime* const k = new KeyPressTime();
  45480. k->key = key;
  45481. k->timeWhenPressed = now;
  45482. keysDown.add (k);
  45483. }
  45484. else
  45485. {
  45486. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  45487. if (now > pressTime)
  45488. millisecs = now - pressTime;
  45489. keysDown.remove (keyPressEntryIndex);
  45490. }
  45491. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  45492. used = true;
  45493. }
  45494. }
  45495. }
  45496. }
  45497. return used;
  45498. }
  45499. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  45500. {
  45501. if (focusedComponent != 0)
  45502. focusedComponent->keyStateChanged (false);
  45503. }
  45504. END_JUCE_NAMESPACE
  45505. /********* End of inlined file: juce_KeyPressMappingSet.cpp *********/
  45506. /********* Start of inlined file: juce_ModifierKeys.cpp *********/
  45507. BEGIN_JUCE_NAMESPACE
  45508. ModifierKeys::ModifierKeys (const int flags_) throw()
  45509. : flags (flags_)
  45510. {
  45511. }
  45512. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  45513. : flags (other.flags)
  45514. {
  45515. }
  45516. const ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  45517. {
  45518. flags = other.flags;
  45519. return *this;
  45520. }
  45521. int ModifierKeys::currentModifierFlags = 0;
  45522. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  45523. {
  45524. return ModifierKeys (currentModifierFlags);
  45525. }
  45526. END_JUCE_NAMESPACE
  45527. /********* End of inlined file: juce_ModifierKeys.cpp *********/
  45528. /********* Start of inlined file: juce_ComponentAnimator.cpp *********/
  45529. BEGIN_JUCE_NAMESPACE
  45530. struct AnimationTask
  45531. {
  45532. AnimationTask (Component* const comp)
  45533. : component (comp),
  45534. watcher (comp)
  45535. {
  45536. }
  45537. Component* component;
  45538. ComponentDeletionWatcher watcher;
  45539. Rectangle destination;
  45540. int msElapsed, msTotal;
  45541. double startSpeed, midSpeed, endSpeed, lastProgress;
  45542. double left, top, right, bottom;
  45543. bool useTimeslice (const int elapsed)
  45544. {
  45545. if (watcher.hasBeenDeleted())
  45546. return false;
  45547. msElapsed += elapsed;
  45548. double newProgress = msElapsed / (double) msTotal;
  45549. if (newProgress >= 0 && newProgress < 1.0)
  45550. {
  45551. newProgress = timeToDistance (newProgress);
  45552. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  45553. jassert (newProgress >= lastProgress);
  45554. lastProgress = newProgress;
  45555. left += (destination.getX() - left) * delta;
  45556. top += (destination.getY() - top) * delta;
  45557. right += (destination.getRight() - right) * delta;
  45558. bottom += (destination.getBottom() - bottom) * delta;
  45559. if (delta < 1.0)
  45560. {
  45561. const Rectangle newBounds (roundDoubleToInt (left),
  45562. roundDoubleToInt (top),
  45563. roundDoubleToInt (right - left),
  45564. roundDoubleToInt (bottom - top));
  45565. if (newBounds != destination)
  45566. {
  45567. component->setBounds (newBounds);
  45568. return true;
  45569. }
  45570. }
  45571. }
  45572. component->setBounds (destination);
  45573. return false;
  45574. }
  45575. void moveToFinalDestination()
  45576. {
  45577. if (! watcher.hasBeenDeleted())
  45578. component->setBounds (destination);
  45579. }
  45580. private:
  45581. inline double timeToDistance (const double time) const
  45582. {
  45583. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  45584. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  45585. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  45586. }
  45587. };
  45588. ComponentAnimator::ComponentAnimator()
  45589. : lastTime (0)
  45590. {
  45591. }
  45592. ComponentAnimator::~ComponentAnimator()
  45593. {
  45594. cancelAllAnimations (false);
  45595. jassert (tasks.size() == 0);
  45596. }
  45597. void* ComponentAnimator::findTaskFor (Component* const component) const
  45598. {
  45599. for (int i = tasks.size(); --i >= 0;)
  45600. if (component == ((AnimationTask*) tasks.getUnchecked(i))->component)
  45601. return tasks.getUnchecked(i);
  45602. return 0;
  45603. }
  45604. void ComponentAnimator::animateComponent (Component* const component,
  45605. const Rectangle& finalPosition,
  45606. const int millisecondsToSpendMoving,
  45607. const double startSpeed,
  45608. const double endSpeed)
  45609. {
  45610. if (component != 0)
  45611. {
  45612. AnimationTask* at = (AnimationTask*) findTaskFor (component);
  45613. if (at == 0)
  45614. {
  45615. at = new AnimationTask (component);
  45616. tasks.add (at);
  45617. sendChangeMessage (this);
  45618. }
  45619. at->msElapsed = 0;
  45620. at->lastProgress = 0;
  45621. at->msTotal = jmax (1, millisecondsToSpendMoving);
  45622. at->destination = finalPosition;
  45623. // the speeds must be 0 or greater!
  45624. jassert (startSpeed >= 0 && endSpeed >= 0)
  45625. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  45626. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  45627. at->midSpeed = invTotalDistance;
  45628. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  45629. at->left = component->getX();
  45630. at->top = component->getY();
  45631. at->right = component->getRight();
  45632. at->bottom = component->getBottom();
  45633. if (! isTimerRunning())
  45634. {
  45635. lastTime = Time::getMillisecondCounter();
  45636. startTimer (1000 / 50);
  45637. }
  45638. }
  45639. }
  45640. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  45641. {
  45642. for (int i = tasks.size(); --i >= 0;)
  45643. {
  45644. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  45645. if (moveComponentsToTheirFinalPositions)
  45646. at->moveToFinalDestination();
  45647. delete at;
  45648. tasks.remove (i);
  45649. sendChangeMessage (this);
  45650. }
  45651. }
  45652. void ComponentAnimator::cancelAnimation (Component* const component,
  45653. const bool moveComponentToItsFinalPosition)
  45654. {
  45655. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  45656. if (at != 0)
  45657. {
  45658. if (moveComponentToItsFinalPosition)
  45659. at->moveToFinalDestination();
  45660. tasks.removeValue (at);
  45661. delete at;
  45662. sendChangeMessage (this);
  45663. }
  45664. }
  45665. const Rectangle ComponentAnimator::getComponentDestination (Component* const component)
  45666. {
  45667. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  45668. if (at != 0)
  45669. return at->destination;
  45670. else if (component != 0)
  45671. return component->getBounds();
  45672. return Rectangle();
  45673. }
  45674. bool ComponentAnimator::isAnimating (Component* component) const
  45675. {
  45676. return findTaskFor (component) != 0;
  45677. }
  45678. void ComponentAnimator::timerCallback()
  45679. {
  45680. const uint32 timeNow = Time::getMillisecondCounter();
  45681. if (lastTime == 0 || lastTime == timeNow)
  45682. lastTime = timeNow;
  45683. const int elapsed = timeNow - lastTime;
  45684. for (int i = tasks.size(); --i >= 0;)
  45685. {
  45686. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  45687. if (! at->useTimeslice (elapsed))
  45688. {
  45689. tasks.remove (i);
  45690. delete at;
  45691. sendChangeMessage (this);
  45692. }
  45693. }
  45694. lastTime = timeNow;
  45695. if (tasks.size() == 0)
  45696. stopTimer();
  45697. }
  45698. END_JUCE_NAMESPACE
  45699. /********* End of inlined file: juce_ComponentAnimator.cpp *********/
  45700. /********* Start of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  45701. BEGIN_JUCE_NAMESPACE
  45702. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  45703. : minW (0),
  45704. maxW (0x3fffffff),
  45705. minH (0),
  45706. maxH (0x3fffffff),
  45707. minOffTop (0),
  45708. minOffLeft (0),
  45709. minOffBottom (0),
  45710. minOffRight (0),
  45711. aspectRatio (0.0)
  45712. {
  45713. }
  45714. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  45715. {
  45716. }
  45717. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  45718. {
  45719. minW = minimumWidth;
  45720. }
  45721. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  45722. {
  45723. maxW = maximumWidth;
  45724. }
  45725. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  45726. {
  45727. minH = minimumHeight;
  45728. }
  45729. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  45730. {
  45731. maxH = maximumHeight;
  45732. }
  45733. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  45734. {
  45735. jassert (maxW >= minimumWidth);
  45736. jassert (maxH >= minimumHeight);
  45737. jassert (minimumWidth > 0 && minimumHeight > 0);
  45738. minW = minimumWidth;
  45739. minH = minimumHeight;
  45740. if (minW > maxW)
  45741. maxW = minW;
  45742. if (minH > maxH)
  45743. maxH = minH;
  45744. }
  45745. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  45746. {
  45747. jassert (maximumWidth >= minW);
  45748. jassert (maximumHeight >= minH);
  45749. jassert (maximumWidth > 0 && maximumHeight > 0);
  45750. maxW = jmax (minW, maximumWidth);
  45751. maxH = jmax (minH, maximumHeight);
  45752. }
  45753. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  45754. const int minimumHeight,
  45755. const int maximumWidth,
  45756. const int maximumHeight) throw()
  45757. {
  45758. jassert (maximumWidth >= minimumWidth);
  45759. jassert (maximumHeight >= minimumHeight);
  45760. jassert (maximumWidth > 0 && maximumHeight > 0);
  45761. jassert (minimumWidth > 0 && minimumHeight > 0);
  45762. minW = jmax (0, minimumWidth);
  45763. minH = jmax (0, minimumHeight);
  45764. maxW = jmax (minW, maximumWidth);
  45765. maxH = jmax (minH, maximumHeight);
  45766. }
  45767. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  45768. const int minimumWhenOffTheLeft,
  45769. const int minimumWhenOffTheBottom,
  45770. const int minimumWhenOffTheRight) throw()
  45771. {
  45772. minOffTop = minimumWhenOffTheTop;
  45773. minOffLeft = minimumWhenOffTheLeft;
  45774. minOffBottom = minimumWhenOffTheBottom;
  45775. minOffRight = minimumWhenOffTheRight;
  45776. }
  45777. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  45778. {
  45779. aspectRatio = jmax (0.0, widthOverHeight);
  45780. }
  45781. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  45782. {
  45783. return aspectRatio;
  45784. }
  45785. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  45786. int x, int y, int w, int h,
  45787. const bool isStretchingTop,
  45788. const bool isStretchingLeft,
  45789. const bool isStretchingBottom,
  45790. const bool isStretchingRight)
  45791. {
  45792. jassert (component != 0);
  45793. Rectangle limits;
  45794. Component* const p = component->getParentComponent();
  45795. if (p == 0)
  45796. limits = Desktop::getInstance().getAllMonitorDisplayAreas().getBounds();
  45797. else
  45798. limits.setSize (p->getWidth(), p->getHeight());
  45799. if (component->isOnDesktop())
  45800. {
  45801. ComponentPeer* const peer = component->getPeer();
  45802. const BorderSize border (peer->getFrameSize());
  45803. x -= border.getLeft();
  45804. y -= border.getTop();
  45805. w += border.getLeftAndRight();
  45806. h += border.getTopAndBottom();
  45807. checkBounds (x, y, w, h,
  45808. border.addedTo (component->getBounds()), limits,
  45809. isStretchingTop, isStretchingLeft,
  45810. isStretchingBottom, isStretchingRight);
  45811. x += border.getLeft();
  45812. y += border.getTop();
  45813. w -= border.getLeftAndRight();
  45814. h -= border.getTopAndBottom();
  45815. }
  45816. else
  45817. {
  45818. checkBounds (x, y, w, h,
  45819. component->getBounds(), limits,
  45820. isStretchingTop, isStretchingLeft,
  45821. isStretchingBottom, isStretchingRight);
  45822. }
  45823. applyBoundsToComponent (component, x, y, w, h);
  45824. }
  45825. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  45826. {
  45827. setBoundsForComponent (component,
  45828. component->getX(), component->getY(),
  45829. component->getWidth(), component->getHeight(),
  45830. false, false, false, false);
  45831. }
  45832. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  45833. int x, int y, int w, int h)
  45834. {
  45835. component->setBounds (x, y, w, h);
  45836. }
  45837. void ComponentBoundsConstrainer::resizeStart()
  45838. {
  45839. }
  45840. void ComponentBoundsConstrainer::resizeEnd()
  45841. {
  45842. }
  45843. void ComponentBoundsConstrainer::checkBounds (int& x, int& y, int& w, int& h,
  45844. const Rectangle& old,
  45845. const Rectangle& limits,
  45846. const bool isStretchingTop,
  45847. const bool isStretchingLeft,
  45848. const bool isStretchingBottom,
  45849. const bool isStretchingRight)
  45850. {
  45851. // constrain the size if it's being stretched..
  45852. if (isStretchingLeft)
  45853. {
  45854. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  45855. w = old.getRight() - x;
  45856. }
  45857. if (isStretchingRight)
  45858. {
  45859. w = jlimit (minW, maxW, w);
  45860. }
  45861. if (isStretchingTop)
  45862. {
  45863. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  45864. h = old.getBottom() - y;
  45865. }
  45866. if (isStretchingBottom)
  45867. {
  45868. h = jlimit (minH, maxH, h);
  45869. }
  45870. // constrain the aspect ratio if one has been specified..
  45871. if (aspectRatio > 0.0 && w > 0 && h > 0)
  45872. {
  45873. bool adjustWidth;
  45874. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  45875. {
  45876. adjustWidth = true;
  45877. }
  45878. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  45879. {
  45880. adjustWidth = false;
  45881. }
  45882. else
  45883. {
  45884. const double oldRatio = (old.getHeight() > 0) ? fabs (old.getWidth() / (double) old.getHeight()) : 0.0;
  45885. const double newRatio = fabs (w / (double) h);
  45886. adjustWidth = (oldRatio > newRatio);
  45887. }
  45888. if (adjustWidth)
  45889. {
  45890. w = roundDoubleToInt (h * aspectRatio);
  45891. if (w > maxW || w < minW)
  45892. {
  45893. w = jlimit (minW, maxW, w);
  45894. h = roundDoubleToInt (w / aspectRatio);
  45895. }
  45896. }
  45897. else
  45898. {
  45899. h = roundDoubleToInt (w / aspectRatio);
  45900. if (h > maxH || h < minH)
  45901. {
  45902. h = jlimit (minH, maxH, h);
  45903. w = roundDoubleToInt (h * aspectRatio);
  45904. }
  45905. }
  45906. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  45907. {
  45908. x = old.getX() + (old.getWidth() - w) / 2;
  45909. }
  45910. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  45911. {
  45912. y = old.getY() + (old.getHeight() - h) / 2;
  45913. }
  45914. else
  45915. {
  45916. if (isStretchingLeft)
  45917. x = old.getRight() - w;
  45918. if (isStretchingTop)
  45919. y = old.getBottom() - h;
  45920. }
  45921. }
  45922. // ...and constrain the position if limits have been set for that.
  45923. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  45924. {
  45925. if (minOffTop > 0)
  45926. {
  45927. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  45928. if (y < limit)
  45929. {
  45930. if (isStretchingTop)
  45931. h -= (limit - y);
  45932. y = limit;
  45933. }
  45934. }
  45935. if (minOffLeft > 0)
  45936. {
  45937. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  45938. if (x < limit)
  45939. {
  45940. if (isStretchingLeft)
  45941. w -= (limit - x);
  45942. x = limit;
  45943. }
  45944. }
  45945. if (minOffBottom > 0)
  45946. {
  45947. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  45948. if (y > limit)
  45949. {
  45950. if (isStretchingBottom)
  45951. h += (limit - y);
  45952. else
  45953. y = limit;
  45954. }
  45955. }
  45956. if (minOffRight > 0)
  45957. {
  45958. const int limit = limits.getRight() - jmin (minOffRight, w);
  45959. if (x > limit)
  45960. {
  45961. if (isStretchingRight)
  45962. w += (limit - x);
  45963. else
  45964. x = limit;
  45965. }
  45966. }
  45967. }
  45968. jassert (w >= 0 && h >= 0);
  45969. }
  45970. END_JUCE_NAMESPACE
  45971. /********* End of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  45972. /********* Start of inlined file: juce_ComponentMovementWatcher.cpp *********/
  45973. BEGIN_JUCE_NAMESPACE
  45974. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  45975. : component (component_),
  45976. lastPeer (0),
  45977. registeredParentComps (4),
  45978. reentrant (false)
  45979. {
  45980. jassert (component != 0); // can't use this with a null pointer..
  45981. #ifdef JUCE_DEBUG
  45982. deletionWatcher = new ComponentDeletionWatcher (component_);
  45983. #endif
  45984. component->addComponentListener (this);
  45985. registerWithParentComps();
  45986. }
  45987. ComponentMovementWatcher::~ComponentMovementWatcher()
  45988. {
  45989. component->removeComponentListener (this);
  45990. unregister();
  45991. #ifdef JUCE_DEBUG
  45992. delete deletionWatcher;
  45993. #endif
  45994. }
  45995. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  45996. {
  45997. #ifdef JUCE_DEBUG
  45998. // agh! don't delete the target component without deleting this object first!
  45999. jassert (! deletionWatcher->hasBeenDeleted());
  46000. #endif
  46001. if (! reentrant)
  46002. {
  46003. reentrant = true;
  46004. ComponentPeer* const peer = component->getPeer();
  46005. if (peer != lastPeer)
  46006. {
  46007. ComponentDeletionWatcher watcher (component);
  46008. componentPeerChanged();
  46009. if (watcher.hasBeenDeleted())
  46010. return;
  46011. lastPeer = peer;
  46012. }
  46013. unregister();
  46014. registerWithParentComps();
  46015. reentrant = false;
  46016. componentMovedOrResized (*component, true, true);
  46017. }
  46018. }
  46019. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  46020. {
  46021. #ifdef JUCE_DEBUG
  46022. // agh! don't delete the target component without deleting this object first!
  46023. jassert (! deletionWatcher->hasBeenDeleted());
  46024. #endif
  46025. if (wasMoved)
  46026. {
  46027. int x = 0, y = 0;
  46028. component->relativePositionToOtherComponent (component->getTopLevelComponent(), x, y);
  46029. wasMoved = (lastX != x || lastY != y);
  46030. lastX = x;
  46031. lastY = y;
  46032. }
  46033. wasResized = (lastWidth != component->getWidth() || lastHeight != component->getHeight());
  46034. lastWidth = component->getWidth();
  46035. lastHeight = component->getHeight();
  46036. if (wasMoved || wasResized)
  46037. componentMovedOrResized (wasMoved, wasResized);
  46038. }
  46039. void ComponentMovementWatcher::registerWithParentComps() throw()
  46040. {
  46041. Component* p = component->getParentComponent();
  46042. while (p != 0)
  46043. {
  46044. p->addComponentListener (this);
  46045. registeredParentComps.add (p);
  46046. p = p->getParentComponent();
  46047. }
  46048. }
  46049. void ComponentMovementWatcher::unregister() throw()
  46050. {
  46051. for (int i = registeredParentComps.size(); --i >= 0;)
  46052. ((Component*) registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  46053. registeredParentComps.clear();
  46054. }
  46055. END_JUCE_NAMESPACE
  46056. /********* End of inlined file: juce_ComponentMovementWatcher.cpp *********/
  46057. /********* Start of inlined file: juce_GroupComponent.cpp *********/
  46058. BEGIN_JUCE_NAMESPACE
  46059. GroupComponent::GroupComponent (const String& componentName,
  46060. const String& labelText)
  46061. : Component (componentName),
  46062. text (labelText),
  46063. justification (Justification::left)
  46064. {
  46065. setInterceptsMouseClicks (false, true);
  46066. }
  46067. GroupComponent::~GroupComponent()
  46068. {
  46069. }
  46070. void GroupComponent::setText (const String& newText) throw()
  46071. {
  46072. if (text != newText)
  46073. {
  46074. text = newText;
  46075. repaint();
  46076. }
  46077. }
  46078. const String GroupComponent::getText() const throw()
  46079. {
  46080. return text;
  46081. }
  46082. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  46083. {
  46084. if (justification.getFlags() != newJustification.getFlags())
  46085. {
  46086. justification = newJustification;
  46087. repaint();
  46088. }
  46089. }
  46090. void GroupComponent::paint (Graphics& g)
  46091. {
  46092. getLookAndFeel()
  46093. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  46094. text, justification,
  46095. *this);
  46096. }
  46097. void GroupComponent::enablementChanged()
  46098. {
  46099. repaint();
  46100. }
  46101. void GroupComponent::colourChanged()
  46102. {
  46103. repaint();
  46104. }
  46105. END_JUCE_NAMESPACE
  46106. /********* End of inlined file: juce_GroupComponent.cpp *********/
  46107. /********* Start of inlined file: juce_MultiDocumentPanel.cpp *********/
  46108. BEGIN_JUCE_NAMESPACE
  46109. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  46110. : DocumentWindow (String::empty, backgroundColour,
  46111. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  46112. {
  46113. }
  46114. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  46115. {
  46116. }
  46117. void MultiDocumentPanelWindow::maximiseButtonPressed()
  46118. {
  46119. MultiDocumentPanel* const owner = getOwner();
  46120. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  46121. if (owner != 0)
  46122. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  46123. }
  46124. void MultiDocumentPanelWindow::closeButtonPressed()
  46125. {
  46126. MultiDocumentPanel* const owner = getOwner();
  46127. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  46128. if (owner != 0)
  46129. owner->closeDocument (getContentComponent(), true);
  46130. }
  46131. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  46132. {
  46133. DocumentWindow::activeWindowStatusChanged();
  46134. updateOrder();
  46135. }
  46136. void MultiDocumentPanelWindow::broughtToFront()
  46137. {
  46138. DocumentWindow::broughtToFront();
  46139. updateOrder();
  46140. }
  46141. void MultiDocumentPanelWindow::updateOrder()
  46142. {
  46143. MultiDocumentPanel* const owner = getOwner();
  46144. if (owner != 0)
  46145. owner->updateOrder();
  46146. }
  46147. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  46148. {
  46149. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  46150. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  46151. }
  46152. class MDITabbedComponentInternal : public TabbedComponent
  46153. {
  46154. public:
  46155. MDITabbedComponentInternal()
  46156. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  46157. {
  46158. }
  46159. ~MDITabbedComponentInternal()
  46160. {
  46161. }
  46162. void currentTabChanged (const int, const String&)
  46163. {
  46164. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  46165. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  46166. if (owner != 0)
  46167. owner->updateOrder();
  46168. }
  46169. };
  46170. MultiDocumentPanel::MultiDocumentPanel()
  46171. : mode (MaximisedWindowsWithTabs),
  46172. tabComponent (0),
  46173. backgroundColour (Colours::lightblue),
  46174. maximumNumDocuments (0),
  46175. numDocsBeforeTabsUsed (0)
  46176. {
  46177. setOpaque (true);
  46178. }
  46179. MultiDocumentPanel::~MultiDocumentPanel()
  46180. {
  46181. closeAllDocuments (false);
  46182. }
  46183. static bool shouldDeleteComp (Component* const c)
  46184. {
  46185. return c->getComponentPropertyBool (T("mdiDocumentDelete_"), false);
  46186. }
  46187. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  46188. {
  46189. while (components.size() > 0)
  46190. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  46191. return false;
  46192. return true;
  46193. }
  46194. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  46195. {
  46196. return new MultiDocumentPanelWindow (backgroundColour);
  46197. }
  46198. void MultiDocumentPanel::addWindow (Component* component)
  46199. {
  46200. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  46201. dw->setResizable (true, false);
  46202. dw->setContentComponent (component, false, true);
  46203. dw->setName (component->getName());
  46204. dw->setBackgroundColour (component->getComponentPropertyColour (T("mdiDocumentBkg_"), false, backgroundColour));
  46205. int x = 4;
  46206. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  46207. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  46208. x += 16;
  46209. dw->setTopLeftPosition (x, x);
  46210. if (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty).isNotEmpty())
  46211. dw->restoreWindowStateFromString (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty));
  46212. addAndMakeVisible (dw);
  46213. dw->toFront (true);
  46214. }
  46215. bool MultiDocumentPanel::addDocument (Component* const component,
  46216. const Colour& docColour,
  46217. const bool deleteWhenRemoved)
  46218. {
  46219. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  46220. // with a frame-within-a-frame! Just pass in the bare content component.
  46221. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  46222. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  46223. return false;
  46224. components.add (component);
  46225. component->setComponentProperty (T("mdiDocumentDelete_"), deleteWhenRemoved);
  46226. component->setComponentProperty (T("mdiDocumentBkg_"), docColour);
  46227. component->addComponentListener (this);
  46228. if (mode == FloatingWindows)
  46229. {
  46230. if (isFullscreenWhenOneDocument())
  46231. {
  46232. if (components.size() == 1)
  46233. {
  46234. addAndMakeVisible (component);
  46235. }
  46236. else
  46237. {
  46238. if (components.size() == 2)
  46239. addWindow (components.getFirst());
  46240. addWindow (component);
  46241. }
  46242. }
  46243. else
  46244. {
  46245. addWindow (component);
  46246. }
  46247. }
  46248. else
  46249. {
  46250. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  46251. {
  46252. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  46253. Array <Component*> temp (components);
  46254. for (int i = 0; i < temp.size(); ++i)
  46255. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  46256. resized();
  46257. }
  46258. else
  46259. {
  46260. if (tabComponent != 0)
  46261. tabComponent->addTab (component->getName(), docColour, component, false);
  46262. else
  46263. addAndMakeVisible (component);
  46264. }
  46265. setActiveDocument (component);
  46266. }
  46267. resized();
  46268. activeDocumentChanged();
  46269. return true;
  46270. }
  46271. bool MultiDocumentPanel::closeDocument (Component* component,
  46272. const bool checkItsOkToCloseFirst)
  46273. {
  46274. if (components.contains (component))
  46275. {
  46276. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  46277. return false;
  46278. component->removeComponentListener (this);
  46279. const bool shouldDelete = shouldDeleteComp (component);
  46280. component->removeComponentProperty (T("mdiDocumentDelete_"));
  46281. component->removeComponentProperty (T("mdiDocumentBkg_"));
  46282. if (mode == FloatingWindows)
  46283. {
  46284. for (int i = getNumChildComponents(); --i >= 0;)
  46285. {
  46286. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46287. if (dw != 0 && dw->getContentComponent() == component)
  46288. {
  46289. dw->setContentComponent (0, false);
  46290. delete dw;
  46291. break;
  46292. }
  46293. }
  46294. if (shouldDelete)
  46295. delete component;
  46296. components.removeValue (component);
  46297. if (isFullscreenWhenOneDocument() && components.size() == 1)
  46298. {
  46299. for (int i = getNumChildComponents(); --i >= 0;)
  46300. {
  46301. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46302. if (dw != 0)
  46303. {
  46304. dw->setContentComponent (0, false);
  46305. delete dw;
  46306. }
  46307. }
  46308. addAndMakeVisible (components.getFirst());
  46309. }
  46310. }
  46311. else
  46312. {
  46313. jassert (components.indexOf (component) >= 0);
  46314. if (tabComponent != 0)
  46315. {
  46316. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46317. if (tabComponent->getTabContentComponent (i) == component)
  46318. tabComponent->removeTab (i);
  46319. }
  46320. else
  46321. {
  46322. removeChildComponent (component);
  46323. }
  46324. if (shouldDelete)
  46325. delete component;
  46326. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  46327. deleteAndZero (tabComponent);
  46328. components.removeValue (component);
  46329. if (components.size() > 0 && tabComponent == 0)
  46330. addAndMakeVisible (components.getFirst());
  46331. }
  46332. resized();
  46333. activeDocumentChanged();
  46334. }
  46335. else
  46336. {
  46337. jassertfalse
  46338. }
  46339. return true;
  46340. }
  46341. int MultiDocumentPanel::getNumDocuments() const throw()
  46342. {
  46343. return components.size();
  46344. }
  46345. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  46346. {
  46347. return components [index];
  46348. }
  46349. Component* MultiDocumentPanel::getActiveDocument() const throw()
  46350. {
  46351. if (mode == FloatingWindows)
  46352. {
  46353. for (int i = getNumChildComponents(); --i >= 0;)
  46354. {
  46355. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46356. if (dw != 0 && dw->isActiveWindow())
  46357. return dw->getContentComponent();
  46358. }
  46359. }
  46360. return components.getLast();
  46361. }
  46362. void MultiDocumentPanel::setActiveDocument (Component* component)
  46363. {
  46364. if (mode == FloatingWindows)
  46365. {
  46366. component = getContainerComp (component);
  46367. if (component != 0)
  46368. component->toFront (true);
  46369. }
  46370. else if (tabComponent != 0)
  46371. {
  46372. jassert (components.indexOf (component) >= 0);
  46373. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46374. {
  46375. if (tabComponent->getTabContentComponent (i) == component)
  46376. {
  46377. tabComponent->setCurrentTabIndex (i);
  46378. break;
  46379. }
  46380. }
  46381. }
  46382. else
  46383. {
  46384. component->grabKeyboardFocus();
  46385. }
  46386. }
  46387. void MultiDocumentPanel::activeDocumentChanged()
  46388. {
  46389. }
  46390. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  46391. {
  46392. maximumNumDocuments = newNumber;
  46393. }
  46394. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  46395. {
  46396. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  46397. }
  46398. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  46399. {
  46400. return numDocsBeforeTabsUsed != 0;
  46401. }
  46402. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  46403. {
  46404. if (mode != newLayoutMode)
  46405. {
  46406. mode = newLayoutMode;
  46407. if (mode == FloatingWindows)
  46408. {
  46409. deleteAndZero (tabComponent);
  46410. }
  46411. else
  46412. {
  46413. for (int i = getNumChildComponents(); --i >= 0;)
  46414. {
  46415. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46416. if (dw != 0)
  46417. {
  46418. dw->getContentComponent()->setComponentProperty (T("mdiDocumentPos_"), dw->getWindowStateAsString());
  46419. dw->setContentComponent (0, false);
  46420. delete dw;
  46421. }
  46422. }
  46423. }
  46424. resized();
  46425. const Array <Component*> tempComps (components);
  46426. components.clear();
  46427. for (int i = 0; i < tempComps.size(); ++i)
  46428. {
  46429. Component* const c = tempComps.getUnchecked(i);
  46430. addDocument (c,
  46431. c->getComponentPropertyColour (T("mdiDocumentBkg_"), false, Colours::white),
  46432. shouldDeleteComp (c));
  46433. }
  46434. }
  46435. }
  46436. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  46437. {
  46438. if (backgroundColour != newBackgroundColour)
  46439. {
  46440. backgroundColour = newBackgroundColour;
  46441. setOpaque (newBackgroundColour.isOpaque());
  46442. repaint();
  46443. }
  46444. }
  46445. void MultiDocumentPanel::paint (Graphics& g)
  46446. {
  46447. g.fillAll (backgroundColour);
  46448. }
  46449. void MultiDocumentPanel::resized()
  46450. {
  46451. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  46452. {
  46453. for (int i = getNumChildComponents(); --i >= 0;)
  46454. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  46455. }
  46456. setWantsKeyboardFocus (components.size() == 0);
  46457. }
  46458. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  46459. {
  46460. if (mode == FloatingWindows)
  46461. {
  46462. for (int i = 0; i < getNumChildComponents(); ++i)
  46463. {
  46464. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46465. if (dw != 0 && dw->getContentComponent() == c)
  46466. {
  46467. c = dw;
  46468. break;
  46469. }
  46470. }
  46471. }
  46472. return c;
  46473. }
  46474. void MultiDocumentPanel::componentNameChanged (Component&)
  46475. {
  46476. if (mode == FloatingWindows)
  46477. {
  46478. for (int i = 0; i < getNumChildComponents(); ++i)
  46479. {
  46480. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46481. if (dw != 0)
  46482. dw->setName (dw->getContentComponent()->getName());
  46483. }
  46484. }
  46485. else if (tabComponent != 0)
  46486. {
  46487. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46488. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  46489. }
  46490. }
  46491. void MultiDocumentPanel::updateOrder()
  46492. {
  46493. const Array <Component*> oldList (components);
  46494. if (mode == FloatingWindows)
  46495. {
  46496. components.clear();
  46497. for (int i = 0; i < getNumChildComponents(); ++i)
  46498. {
  46499. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46500. if (dw != 0)
  46501. components.add (dw->getContentComponent());
  46502. }
  46503. }
  46504. else
  46505. {
  46506. if (tabComponent != 0)
  46507. {
  46508. Component* const current = tabComponent->getCurrentContentComponent();
  46509. if (current != 0)
  46510. {
  46511. components.removeValue (current);
  46512. components.add (current);
  46513. }
  46514. }
  46515. }
  46516. if (components != oldList)
  46517. activeDocumentChanged();
  46518. }
  46519. END_JUCE_NAMESPACE
  46520. /********* End of inlined file: juce_MultiDocumentPanel.cpp *********/
  46521. /********* Start of inlined file: juce_ResizableBorderComponent.cpp *********/
  46522. BEGIN_JUCE_NAMESPACE
  46523. const int zoneL = 1;
  46524. const int zoneR = 2;
  46525. const int zoneT = 4;
  46526. const int zoneB = 8;
  46527. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  46528. ComponentBoundsConstrainer* const constrainer_)
  46529. : component (componentToResize),
  46530. constrainer (constrainer_),
  46531. borderSize (5),
  46532. mouseZone (0)
  46533. {
  46534. }
  46535. ResizableBorderComponent::~ResizableBorderComponent()
  46536. {
  46537. }
  46538. void ResizableBorderComponent::paint (Graphics& g)
  46539. {
  46540. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  46541. }
  46542. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  46543. {
  46544. updateMouseZone (e);
  46545. }
  46546. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  46547. {
  46548. updateMouseZone (e);
  46549. }
  46550. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  46551. {
  46552. if (component->isValidComponent())
  46553. {
  46554. updateMouseZone (e);
  46555. originalX = component->getX();
  46556. originalY = component->getY();
  46557. originalW = component->getWidth();
  46558. originalH = component->getHeight();
  46559. if (constrainer != 0)
  46560. constrainer->resizeStart();
  46561. }
  46562. else
  46563. {
  46564. jassertfalse
  46565. }
  46566. }
  46567. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  46568. {
  46569. if (! component->isValidComponent())
  46570. {
  46571. jassertfalse
  46572. return;
  46573. }
  46574. int x = originalX;
  46575. int y = originalY;
  46576. int w = originalW;
  46577. int h = originalH;
  46578. const int dx = e.getDistanceFromDragStartX();
  46579. const int dy = e.getDistanceFromDragStartY();
  46580. if ((mouseZone & zoneL) != 0)
  46581. {
  46582. x += dx;
  46583. w -= dx;
  46584. }
  46585. if ((mouseZone & zoneT) != 0)
  46586. {
  46587. y += dy;
  46588. h -= dy;
  46589. }
  46590. if ((mouseZone & zoneR) != 0)
  46591. w += dx;
  46592. if ((mouseZone & zoneB) != 0)
  46593. h += dy;
  46594. if (constrainer != 0)
  46595. constrainer->setBoundsForComponent (component,
  46596. x, y, w, h,
  46597. (mouseZone & zoneT) != 0,
  46598. (mouseZone & zoneL) != 0,
  46599. (mouseZone & zoneB) != 0,
  46600. (mouseZone & zoneR) != 0);
  46601. else
  46602. component->setBounds (x, y, w, h);
  46603. }
  46604. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  46605. {
  46606. if (constrainer != 0)
  46607. constrainer->resizeEnd();
  46608. }
  46609. bool ResizableBorderComponent::hitTest (int x, int y)
  46610. {
  46611. return x < borderSize.getLeft()
  46612. || x >= getWidth() - borderSize.getRight()
  46613. || y < borderSize.getTop()
  46614. || y >= getHeight() - borderSize.getBottom();
  46615. }
  46616. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize) throw()
  46617. {
  46618. if (borderSize != newBorderSize)
  46619. {
  46620. borderSize = newBorderSize;
  46621. repaint();
  46622. }
  46623. }
  46624. const BorderSize ResizableBorderComponent::getBorderThickness() const throw()
  46625. {
  46626. return borderSize;
  46627. }
  46628. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e) throw()
  46629. {
  46630. int newZone = 0;
  46631. if (ResizableBorderComponent::hitTest (e.x, e.y))
  46632. {
  46633. if (e.x < jmax (borderSize.getLeft(),
  46634. proportionOfWidth (0.1f),
  46635. jmin (10, proportionOfWidth (0.33f))))
  46636. newZone |= zoneL;
  46637. else if (e.x >= jmin (getWidth() - borderSize.getRight(),
  46638. proportionOfWidth (0.9f),
  46639. getWidth() - jmin (10, proportionOfWidth (0.33f))))
  46640. newZone |= zoneR;
  46641. if (e.y < jmax (borderSize.getTop(),
  46642. proportionOfHeight (0.1f),
  46643. jmin (10, proportionOfHeight (0.33f))))
  46644. newZone |= zoneT;
  46645. else if (e.y >= jmin (getHeight() - borderSize.getBottom(),
  46646. proportionOfHeight (0.9f),
  46647. getHeight() - jmin (10, proportionOfHeight (0.33f))))
  46648. newZone |= zoneB;
  46649. }
  46650. if (mouseZone != newZone)
  46651. {
  46652. mouseZone = newZone;
  46653. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  46654. switch (newZone)
  46655. {
  46656. case (zoneL | zoneT):
  46657. mc = MouseCursor::TopLeftCornerResizeCursor;
  46658. break;
  46659. case zoneT:
  46660. mc = MouseCursor::TopEdgeResizeCursor;
  46661. break;
  46662. case (zoneR | zoneT):
  46663. mc = MouseCursor::TopRightCornerResizeCursor;
  46664. break;
  46665. case zoneL:
  46666. mc = MouseCursor::LeftEdgeResizeCursor;
  46667. break;
  46668. case zoneR:
  46669. mc = MouseCursor::RightEdgeResizeCursor;
  46670. break;
  46671. case (zoneL | zoneB):
  46672. mc = MouseCursor::BottomLeftCornerResizeCursor;
  46673. break;
  46674. case zoneB:
  46675. mc = MouseCursor::BottomEdgeResizeCursor;
  46676. break;
  46677. case (zoneR | zoneB):
  46678. mc = MouseCursor::BottomRightCornerResizeCursor;
  46679. break;
  46680. default:
  46681. break;
  46682. }
  46683. setMouseCursor (mc);
  46684. }
  46685. }
  46686. END_JUCE_NAMESPACE
  46687. /********* End of inlined file: juce_ResizableBorderComponent.cpp *********/
  46688. /********* Start of inlined file: juce_ResizableCornerComponent.cpp *********/
  46689. BEGIN_JUCE_NAMESPACE
  46690. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  46691. ComponentBoundsConstrainer* const constrainer_)
  46692. : component (componentToResize),
  46693. constrainer (constrainer_)
  46694. {
  46695. setRepaintsOnMouseActivity (true);
  46696. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  46697. }
  46698. ResizableCornerComponent::~ResizableCornerComponent()
  46699. {
  46700. }
  46701. void ResizableCornerComponent::paint (Graphics& g)
  46702. {
  46703. getLookAndFeel()
  46704. .drawCornerResizer (g, getWidth(), getHeight(),
  46705. isMouseOverOrDragging(),
  46706. isMouseButtonDown());
  46707. }
  46708. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  46709. {
  46710. if (component->isValidComponent())
  46711. {
  46712. originalX = component->getX();
  46713. originalY = component->getY();
  46714. originalW = component->getWidth();
  46715. originalH = component->getHeight();
  46716. if (constrainer != 0)
  46717. constrainer->resizeStart();
  46718. }
  46719. else
  46720. {
  46721. jassertfalse
  46722. }
  46723. }
  46724. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  46725. {
  46726. if (! component->isValidComponent())
  46727. {
  46728. jassertfalse
  46729. return;
  46730. }
  46731. int x = originalX;
  46732. int y = originalY;
  46733. int w = originalW + e.getDistanceFromDragStartX();
  46734. int h = originalH + e.getDistanceFromDragStartY();
  46735. if (constrainer != 0)
  46736. constrainer->setBoundsForComponent (component, x, y, w, h,
  46737. false, false, true, true);
  46738. else
  46739. component->setBounds (x, y, w, h);
  46740. }
  46741. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  46742. {
  46743. if (constrainer != 0)
  46744. constrainer->resizeStart();
  46745. }
  46746. bool ResizableCornerComponent::hitTest (int x, int y)
  46747. {
  46748. if (getWidth() <= 0)
  46749. return false;
  46750. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  46751. return y >= yAtX - getHeight() / 4;
  46752. }
  46753. END_JUCE_NAMESPACE
  46754. /********* End of inlined file: juce_ResizableCornerComponent.cpp *********/
  46755. /********* Start of inlined file: juce_ScrollBar.cpp *********/
  46756. BEGIN_JUCE_NAMESPACE
  46757. class ScrollbarButton : public Button
  46758. {
  46759. public:
  46760. int direction;
  46761. ScrollbarButton (const int direction_,
  46762. ScrollBar& owner_) throw()
  46763. : Button (String::empty),
  46764. direction (direction_),
  46765. owner (owner_)
  46766. {
  46767. setWantsKeyboardFocus (false);
  46768. }
  46769. ~ScrollbarButton()
  46770. {
  46771. }
  46772. void paintButton (Graphics& g,
  46773. bool isMouseOver,
  46774. bool isMouseDown)
  46775. {
  46776. getLookAndFeel()
  46777. .drawScrollbarButton (g, owner,
  46778. getWidth(), getHeight(),
  46779. direction,
  46780. owner.isVertical(),
  46781. isMouseOver, isMouseDown);
  46782. }
  46783. void clicked()
  46784. {
  46785. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  46786. }
  46787. juce_UseDebuggingNewOperator
  46788. private:
  46789. ScrollBar& owner;
  46790. ScrollbarButton (const ScrollbarButton&);
  46791. const ScrollbarButton& operator= (const ScrollbarButton&);
  46792. };
  46793. ScrollBar::ScrollBar (const bool vertical_,
  46794. const bool buttonsAreVisible)
  46795. : minimum (0.0),
  46796. maximum (1.0),
  46797. rangeStart (0.0),
  46798. rangeSize (0.1),
  46799. singleStepSize (0.1),
  46800. thumbAreaStart (0),
  46801. thumbAreaSize (0),
  46802. thumbStart (0),
  46803. thumbSize (0),
  46804. initialDelayInMillisecs (100),
  46805. repeatDelayInMillisecs (50),
  46806. minimumDelayInMillisecs (10),
  46807. vertical (vertical_),
  46808. isDraggingThumb (false),
  46809. alwaysVisible (false),
  46810. upButton (0),
  46811. downButton (0),
  46812. listeners (2)
  46813. {
  46814. setButtonVisibility (buttonsAreVisible);
  46815. setRepaintsOnMouseActivity (true);
  46816. setFocusContainer (true);
  46817. }
  46818. ScrollBar::~ScrollBar()
  46819. {
  46820. deleteAllChildren();
  46821. }
  46822. void ScrollBar::setRangeLimits (const double newMinimum,
  46823. const double newMaximum) throw()
  46824. {
  46825. minimum = newMinimum;
  46826. maximum = newMaximum;
  46827. jassert (maximum >= minimum); // these can't be the wrong way round!
  46828. setCurrentRangeStart (rangeStart);
  46829. updateThumbPosition();
  46830. }
  46831. void ScrollBar::setCurrentRange (double newStart,
  46832. double newSize) throw()
  46833. {
  46834. newSize = jlimit (0.0, maximum - minimum, newSize);
  46835. newStart = jlimit (minimum, maximum - newSize, newStart);
  46836. if (rangeStart != newStart
  46837. || rangeSize != newSize)
  46838. {
  46839. rangeStart = newStart;
  46840. rangeSize = newSize;
  46841. updateThumbPosition();
  46842. triggerAsyncUpdate();
  46843. }
  46844. }
  46845. void ScrollBar::setCurrentRangeStart (double newStart) throw()
  46846. {
  46847. setCurrentRange (newStart, rangeSize);
  46848. }
  46849. void ScrollBar::setSingleStepSize (const double newSingleStepSize) throw()
  46850. {
  46851. singleStepSize = newSingleStepSize;
  46852. }
  46853. void ScrollBar::moveScrollbarInSteps (const int howManySteps) throw()
  46854. {
  46855. setCurrentRangeStart (rangeStart + howManySteps * singleStepSize);
  46856. }
  46857. void ScrollBar::moveScrollbarInPages (const int howManyPages) throw()
  46858. {
  46859. setCurrentRangeStart (rangeStart + howManyPages * rangeSize);
  46860. }
  46861. void ScrollBar::scrollToTop() throw()
  46862. {
  46863. setCurrentRangeStart (minimum);
  46864. }
  46865. void ScrollBar::scrollToBottom() throw()
  46866. {
  46867. setCurrentRangeStart (maximum - rangeSize);
  46868. }
  46869. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  46870. const int repeatDelayInMillisecs_,
  46871. const int minimumDelayInMillisecs_) throw()
  46872. {
  46873. initialDelayInMillisecs = initialDelayInMillisecs_;
  46874. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  46875. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  46876. if (upButton != 0)
  46877. {
  46878. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  46879. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  46880. }
  46881. }
  46882. void ScrollBar::addListener (ScrollBarListener* const listener) throw()
  46883. {
  46884. jassert (listener != 0);
  46885. if (listener != 0)
  46886. listeners.add (listener);
  46887. }
  46888. void ScrollBar::removeListener (ScrollBarListener* const listener) throw()
  46889. {
  46890. listeners.removeValue (listener);
  46891. }
  46892. void ScrollBar::handleAsyncUpdate()
  46893. {
  46894. const double value = getCurrentRangeStart();
  46895. for (int i = listeners.size(); --i >= 0;)
  46896. {
  46897. ((ScrollBarListener*) listeners.getUnchecked (i))->scrollBarMoved (this, value);
  46898. i = jmin (i, listeners.size());
  46899. }
  46900. }
  46901. void ScrollBar::updateThumbPosition() throw()
  46902. {
  46903. int newThumbSize = roundDoubleToInt ((maximum > minimum) ? (rangeSize * thumbAreaSize) / (maximum - minimum)
  46904. : thumbAreaSize);
  46905. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  46906. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  46907. if (newThumbSize > thumbAreaSize)
  46908. newThumbSize = thumbAreaSize;
  46909. int newThumbStart = thumbAreaStart;
  46910. if (maximum - minimum > rangeSize)
  46911. newThumbStart += roundDoubleToInt (((rangeStart - minimum) * (thumbAreaSize - newThumbSize))
  46912. / ((maximum - minimum) - rangeSize));
  46913. setVisible (alwaysVisible || (maximum - minimum > rangeSize && rangeSize > 0.0));
  46914. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  46915. {
  46916. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  46917. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  46918. if (vertical)
  46919. repaint (0, repaintStart, getWidth(), repaintSize);
  46920. else
  46921. repaint (repaintStart, 0, repaintSize, getHeight());
  46922. thumbStart = newThumbStart;
  46923. thumbSize = newThumbSize;
  46924. }
  46925. }
  46926. void ScrollBar::setOrientation (const bool shouldBeVertical) throw()
  46927. {
  46928. if (vertical != shouldBeVertical)
  46929. {
  46930. vertical = shouldBeVertical;
  46931. if (upButton != 0)
  46932. {
  46933. ((ScrollbarButton*) upButton)->direction = (vertical) ? 0 : 3;
  46934. ((ScrollbarButton*) downButton)->direction = (vertical) ? 2 : 1;
  46935. }
  46936. updateThumbPosition();
  46937. }
  46938. }
  46939. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  46940. {
  46941. deleteAndZero (upButton);
  46942. deleteAndZero (downButton);
  46943. if (buttonsAreVisible)
  46944. {
  46945. addAndMakeVisible (upButton = new ScrollbarButton ((vertical) ? 0 : 3, *this));
  46946. addAndMakeVisible (downButton = new ScrollbarButton ((vertical) ? 2 : 1, *this));
  46947. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  46948. }
  46949. updateThumbPosition();
  46950. }
  46951. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  46952. {
  46953. alwaysVisible = ! shouldHideWhenFullRange;
  46954. updateThumbPosition();
  46955. }
  46956. void ScrollBar::paint (Graphics& g)
  46957. {
  46958. if (thumbAreaSize > 0)
  46959. {
  46960. LookAndFeel& lf = getLookAndFeel();
  46961. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  46962. ? thumbSize : 0;
  46963. if (vertical)
  46964. {
  46965. lf.drawScrollbar (g, *this,
  46966. 0, thumbAreaStart,
  46967. getWidth(), thumbAreaSize,
  46968. vertical,
  46969. thumbStart, thumb,
  46970. isMouseOver(), isMouseButtonDown());
  46971. }
  46972. else
  46973. {
  46974. lf.drawScrollbar (g, *this,
  46975. thumbAreaStart, 0,
  46976. thumbAreaSize, getHeight(),
  46977. vertical,
  46978. thumbStart, thumb,
  46979. isMouseOver(), isMouseButtonDown());
  46980. }
  46981. }
  46982. }
  46983. void ScrollBar::lookAndFeelChanged()
  46984. {
  46985. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  46986. }
  46987. void ScrollBar::resized()
  46988. {
  46989. const int length = ((vertical) ? getHeight() : getWidth());
  46990. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  46991. : 0;
  46992. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  46993. {
  46994. thumbAreaStart = length >> 1;
  46995. thumbAreaSize = 0;
  46996. }
  46997. else
  46998. {
  46999. thumbAreaStart = buttonSize;
  47000. thumbAreaSize = length - (buttonSize << 1);
  47001. }
  47002. if (upButton != 0)
  47003. {
  47004. if (vertical)
  47005. {
  47006. upButton->setBounds (0, 0, getWidth(), buttonSize);
  47007. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  47008. }
  47009. else
  47010. {
  47011. upButton->setBounds (0, 0, buttonSize, getHeight());
  47012. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  47013. }
  47014. }
  47015. updateThumbPosition();
  47016. }
  47017. void ScrollBar::mouseDown (const MouseEvent& e)
  47018. {
  47019. isDraggingThumb = false;
  47020. lastMousePos = vertical ? e.y : e.x;
  47021. dragStartMousePos = lastMousePos;
  47022. dragStartRange = rangeStart;
  47023. if (dragStartMousePos < thumbStart)
  47024. {
  47025. moveScrollbarInPages (-1);
  47026. startTimer (400);
  47027. }
  47028. else if (dragStartMousePos >= thumbStart + thumbSize)
  47029. {
  47030. moveScrollbarInPages (1);
  47031. startTimer (400);
  47032. }
  47033. else
  47034. {
  47035. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47036. && (thumbAreaSize > thumbSize);
  47037. }
  47038. }
  47039. void ScrollBar::mouseDrag (const MouseEvent& e)
  47040. {
  47041. if (isDraggingThumb)
  47042. {
  47043. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  47044. setCurrentRangeStart (dragStartRange
  47045. + deltaPixels * ((maximum - minimum) - rangeSize)
  47046. / (thumbAreaSize - thumbSize));
  47047. }
  47048. else
  47049. {
  47050. lastMousePos = (vertical) ? e.y : e.x;
  47051. }
  47052. }
  47053. void ScrollBar::mouseUp (const MouseEvent&)
  47054. {
  47055. isDraggingThumb = false;
  47056. stopTimer();
  47057. repaint();
  47058. }
  47059. void ScrollBar::mouseWheelMove (const MouseEvent&,
  47060. float wheelIncrementX,
  47061. float wheelIncrementY)
  47062. {
  47063. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  47064. if (increment < 0)
  47065. increment = jmin (increment * 10.0f, -1.0f);
  47066. else if (increment > 0)
  47067. increment = jmax (increment * 10.0f, 1.0f);
  47068. setCurrentRangeStart (rangeStart - singleStepSize * increment);
  47069. }
  47070. void ScrollBar::timerCallback()
  47071. {
  47072. if (isMouseButtonDown())
  47073. {
  47074. startTimer (40);
  47075. if (lastMousePos < thumbStart)
  47076. setCurrentRangeStart (rangeStart - rangeSize);
  47077. else if (lastMousePos > thumbStart + thumbSize)
  47078. setCurrentRangeStart (rangeStart + rangeSize);
  47079. }
  47080. else
  47081. {
  47082. stopTimer();
  47083. }
  47084. }
  47085. bool ScrollBar::keyPressed (const KeyPress& key)
  47086. {
  47087. if (! isVisible())
  47088. return false;
  47089. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  47090. moveScrollbarInSteps (-1);
  47091. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  47092. moveScrollbarInSteps (1);
  47093. else if (key.isKeyCode (KeyPress::pageUpKey))
  47094. moveScrollbarInPages (-1);
  47095. else if (key.isKeyCode (KeyPress::pageDownKey))
  47096. moveScrollbarInPages (1);
  47097. else if (key.isKeyCode (KeyPress::homeKey))
  47098. scrollToTop();
  47099. else if (key.isKeyCode (KeyPress::endKey))
  47100. scrollToBottom();
  47101. else
  47102. return false;
  47103. return true;
  47104. }
  47105. END_JUCE_NAMESPACE
  47106. /********* End of inlined file: juce_ScrollBar.cpp *********/
  47107. /********* Start of inlined file: juce_StretchableLayoutManager.cpp *********/
  47108. BEGIN_JUCE_NAMESPACE
  47109. StretchableLayoutManager::StretchableLayoutManager()
  47110. : totalSize (0)
  47111. {
  47112. }
  47113. StretchableLayoutManager::~StretchableLayoutManager()
  47114. {
  47115. }
  47116. void StretchableLayoutManager::clearAllItems()
  47117. {
  47118. items.clear();
  47119. totalSize = 0;
  47120. }
  47121. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  47122. const double minimumSize,
  47123. const double maximumSize,
  47124. const double preferredSize)
  47125. {
  47126. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  47127. if (layout == 0)
  47128. {
  47129. layout = new ItemLayoutProperties();
  47130. layout->itemIndex = itemIndex;
  47131. int i;
  47132. for (i = 0; i < items.size(); ++i)
  47133. if (items.getUnchecked (i)->itemIndex > itemIndex)
  47134. break;
  47135. items.insert (i, layout);
  47136. }
  47137. layout->minSize = minimumSize;
  47138. layout->maxSize = maximumSize;
  47139. layout->preferredSize = preferredSize;
  47140. layout->currentSize = 0;
  47141. }
  47142. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  47143. double& minimumSize,
  47144. double& maximumSize,
  47145. double& preferredSize) const
  47146. {
  47147. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47148. if (layout != 0)
  47149. {
  47150. minimumSize = layout->minSize;
  47151. maximumSize = layout->maxSize;
  47152. preferredSize = layout->preferredSize;
  47153. return true;
  47154. }
  47155. return false;
  47156. }
  47157. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  47158. {
  47159. totalSize = newTotalSize;
  47160. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  47161. }
  47162. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  47163. {
  47164. int pos = 0;
  47165. for (int i = 0; i < itemIndex; ++i)
  47166. {
  47167. const ItemLayoutProperties* const layout = getInfoFor (i);
  47168. if (layout != 0)
  47169. pos += layout->currentSize;
  47170. }
  47171. return pos;
  47172. }
  47173. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  47174. {
  47175. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47176. if (layout != 0)
  47177. return layout->currentSize;
  47178. return 0;
  47179. }
  47180. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  47181. {
  47182. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47183. if (layout != 0)
  47184. return -layout->currentSize / (double) totalSize;
  47185. return 0;
  47186. }
  47187. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  47188. int newPosition)
  47189. {
  47190. for (int i = items.size(); --i >= 0;)
  47191. {
  47192. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  47193. if (layout->itemIndex == itemIndex)
  47194. {
  47195. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  47196. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  47197. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  47198. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  47199. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  47200. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  47201. endPos += layout->currentSize;
  47202. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  47203. updatePrefSizesToMatchCurrentPositions();
  47204. break;
  47205. }
  47206. }
  47207. }
  47208. void StretchableLayoutManager::layOutComponents (Component** const components,
  47209. int numComponents,
  47210. int x, int y, int w, int h,
  47211. const bool vertically,
  47212. const bool resizeOtherDimension)
  47213. {
  47214. setTotalSize (vertically ? h : w);
  47215. int pos = vertically ? y : x;
  47216. for (int i = 0; i < numComponents; ++i)
  47217. {
  47218. const ItemLayoutProperties* const layout = getInfoFor (i);
  47219. if (layout != 0)
  47220. {
  47221. Component* const c = components[i];
  47222. if (c != 0)
  47223. {
  47224. if (i == numComponents - 1)
  47225. {
  47226. // if it's the last item, crop it to exactly fit the available space..
  47227. if (resizeOtherDimension)
  47228. {
  47229. if (vertically)
  47230. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  47231. else
  47232. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  47233. }
  47234. else
  47235. {
  47236. if (vertically)
  47237. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  47238. else
  47239. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  47240. }
  47241. }
  47242. else
  47243. {
  47244. if (resizeOtherDimension)
  47245. {
  47246. if (vertically)
  47247. c->setBounds (x, pos, w, layout->currentSize);
  47248. else
  47249. c->setBounds (pos, y, layout->currentSize, h);
  47250. }
  47251. else
  47252. {
  47253. if (vertically)
  47254. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  47255. else
  47256. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  47257. }
  47258. }
  47259. }
  47260. pos += layout->currentSize;
  47261. }
  47262. }
  47263. }
  47264. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  47265. {
  47266. for (int i = items.size(); --i >= 0;)
  47267. if (items.getUnchecked(i)->itemIndex == itemIndex)
  47268. return items.getUnchecked(i);
  47269. return 0;
  47270. }
  47271. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  47272. const int endIndex,
  47273. const int availableSpace,
  47274. int startPos)
  47275. {
  47276. // calculate the total sizes
  47277. int i;
  47278. double totalIdealSize = 0.0;
  47279. int totalMinimums = 0;
  47280. for (i = startIndex; i < endIndex; ++i)
  47281. {
  47282. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47283. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  47284. totalMinimums += layout->currentSize;
  47285. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  47286. }
  47287. if (totalIdealSize <= 0)
  47288. totalIdealSize = 1.0;
  47289. // now calc the best sizes..
  47290. int extraSpace = availableSpace - totalMinimums;
  47291. while (extraSpace > 0)
  47292. {
  47293. int numWantingMoreSpace = 0;
  47294. int numHavingTakenExtraSpace = 0;
  47295. // first figure out how many comps want a slice of the extra space..
  47296. for (i = startIndex; i < endIndex; ++i)
  47297. {
  47298. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47299. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  47300. const int bestSize = jlimit (layout->currentSize,
  47301. jmax (layout->currentSize,
  47302. sizeToRealSize (layout->maxSize, totalSize)),
  47303. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  47304. if (bestSize > layout->currentSize)
  47305. ++numWantingMoreSpace;
  47306. }
  47307. // ..share out the extra space..
  47308. for (i = startIndex; i < endIndex; ++i)
  47309. {
  47310. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47311. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  47312. int bestSize = jlimit (layout->currentSize,
  47313. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  47314. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  47315. const int extraWanted = bestSize - layout->currentSize;
  47316. if (extraWanted > 0)
  47317. {
  47318. const int extraAllowed = jmin (extraWanted,
  47319. extraSpace / jmax (1, numWantingMoreSpace));
  47320. if (extraAllowed > 0)
  47321. {
  47322. ++numHavingTakenExtraSpace;
  47323. --numWantingMoreSpace;
  47324. layout->currentSize += extraAllowed;
  47325. extraSpace -= extraAllowed;
  47326. }
  47327. }
  47328. }
  47329. if (numHavingTakenExtraSpace <= 0)
  47330. break;
  47331. }
  47332. // ..and calculate the end position
  47333. for (i = startIndex; i < endIndex; ++i)
  47334. {
  47335. ItemLayoutProperties* const layout = items.getUnchecked(i);
  47336. startPos += layout->currentSize;
  47337. }
  47338. return startPos;
  47339. }
  47340. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  47341. const int endIndex) const
  47342. {
  47343. int totalMinimums = 0;
  47344. for (int i = startIndex; i < endIndex; ++i)
  47345. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  47346. return totalMinimums;
  47347. }
  47348. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  47349. {
  47350. int totalMaximums = 0;
  47351. for (int i = startIndex; i < endIndex; ++i)
  47352. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  47353. return totalMaximums;
  47354. }
  47355. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  47356. {
  47357. for (int i = 0; i < items.size(); ++i)
  47358. {
  47359. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47360. layout->preferredSize
  47361. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  47362. : getItemCurrentAbsoluteSize (i);
  47363. }
  47364. }
  47365. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  47366. {
  47367. if (size < 0)
  47368. size *= -totalSpace;
  47369. return roundDoubleToInt (size);
  47370. }
  47371. END_JUCE_NAMESPACE
  47372. /********* End of inlined file: juce_StretchableLayoutManager.cpp *********/
  47373. /********* Start of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  47374. BEGIN_JUCE_NAMESPACE
  47375. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  47376. const int itemIndex_,
  47377. const bool isVertical_)
  47378. : layout (layout_),
  47379. itemIndex (itemIndex_),
  47380. isVertical (isVertical_)
  47381. {
  47382. setRepaintsOnMouseActivity (true);
  47383. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  47384. : MouseCursor::UpDownResizeCursor));
  47385. }
  47386. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  47387. {
  47388. }
  47389. void StretchableLayoutResizerBar::paint (Graphics& g)
  47390. {
  47391. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  47392. getWidth(), getHeight(),
  47393. isVertical,
  47394. isMouseOver(),
  47395. isMouseButtonDown());
  47396. }
  47397. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  47398. {
  47399. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  47400. }
  47401. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  47402. {
  47403. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  47404. : e.getDistanceFromDragStartY());
  47405. layout->setItemPosition (itemIndex, desiredPos);
  47406. hasBeenMoved();
  47407. }
  47408. void StretchableLayoutResizerBar::hasBeenMoved()
  47409. {
  47410. if (getParentComponent() != 0)
  47411. getParentComponent()->resized();
  47412. }
  47413. END_JUCE_NAMESPACE
  47414. /********* End of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  47415. /********* Start of inlined file: juce_StretchableObjectResizer.cpp *********/
  47416. BEGIN_JUCE_NAMESPACE
  47417. StretchableObjectResizer::StretchableObjectResizer()
  47418. {
  47419. }
  47420. StretchableObjectResizer::~StretchableObjectResizer()
  47421. {
  47422. }
  47423. void StretchableObjectResizer::addItem (const double size,
  47424. const double minSize, const double maxSize,
  47425. const int order)
  47426. {
  47427. jassert (order >= 0 && order < INT_MAX); // the order must be >= 0 and less than INT_MAX
  47428. Item* const item = new Item();
  47429. item->size = size;
  47430. item->minSize = minSize;
  47431. item->maxSize = maxSize;
  47432. item->order = order;
  47433. items.add (item);
  47434. }
  47435. double StretchableObjectResizer::getItemSize (const int index) const throw()
  47436. {
  47437. const Item* const it = items [index];
  47438. return it != 0 ? it->size : 0;
  47439. }
  47440. void StretchableObjectResizer::resizeToFit (const double targetSize)
  47441. {
  47442. int order = 0;
  47443. for (;;)
  47444. {
  47445. double currentSize = 0;
  47446. double minSize = 0;
  47447. double maxSize = 0;
  47448. int nextHighestOrder = INT_MAX;
  47449. for (int i = 0; i < items.size(); ++i)
  47450. {
  47451. const Item* const it = items.getUnchecked(i);
  47452. currentSize += it->size;
  47453. if (it->order <= order)
  47454. {
  47455. minSize += it->minSize;
  47456. maxSize += it->maxSize;
  47457. }
  47458. else
  47459. {
  47460. minSize += it->size;
  47461. maxSize += it->size;
  47462. nextHighestOrder = jmin (nextHighestOrder, it->order);
  47463. }
  47464. }
  47465. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  47466. if (thisIterationTarget >= currentSize)
  47467. {
  47468. const double availableExtraSpace = maxSize - currentSize;
  47469. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  47470. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  47471. for (int i = 0; i < items.size(); ++i)
  47472. {
  47473. Item* const it = items.getUnchecked(i);
  47474. if (it->order <= order)
  47475. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  47476. }
  47477. }
  47478. else
  47479. {
  47480. const double amountOfSlack = currentSize - minSize;
  47481. const double targetAmountOfSlack = thisIterationTarget - minSize;
  47482. const double scale = targetAmountOfSlack / amountOfSlack;
  47483. for (int i = 0; i < items.size(); ++i)
  47484. {
  47485. Item* const it = items.getUnchecked(i);
  47486. if (it->order <= order)
  47487. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  47488. }
  47489. }
  47490. if (nextHighestOrder < INT_MAX)
  47491. order = nextHighestOrder;
  47492. else
  47493. break;
  47494. }
  47495. }
  47496. END_JUCE_NAMESPACE
  47497. /********* End of inlined file: juce_StretchableObjectResizer.cpp *********/
  47498. /********* Start of inlined file: juce_TabbedButtonBar.cpp *********/
  47499. BEGIN_JUCE_NAMESPACE
  47500. TabBarButton::TabBarButton (const String& name,
  47501. TabbedButtonBar* const owner_,
  47502. const int index)
  47503. : Button (name),
  47504. owner (owner_),
  47505. tabIndex (index),
  47506. overlapPixels (0)
  47507. {
  47508. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  47509. setComponentEffect (&shadow);
  47510. setWantsKeyboardFocus (false);
  47511. }
  47512. TabBarButton::~TabBarButton()
  47513. {
  47514. }
  47515. void TabBarButton::paintButton (Graphics& g,
  47516. bool isMouseOverButton,
  47517. bool isButtonDown)
  47518. {
  47519. int x, y, w, h;
  47520. getActiveArea (x, y, w, h);
  47521. g.setOrigin (x, y);
  47522. getLookAndFeel()
  47523. .drawTabButton (g, w, h,
  47524. owner->getTabBackgroundColour (tabIndex),
  47525. tabIndex, getButtonText(), *this,
  47526. owner->getOrientation(),
  47527. isMouseOverButton, isButtonDown,
  47528. getToggleState());
  47529. }
  47530. void TabBarButton::clicked (const ModifierKeys& mods)
  47531. {
  47532. if (mods.isPopupMenu())
  47533. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  47534. else
  47535. owner->setCurrentTabIndex (tabIndex);
  47536. }
  47537. bool TabBarButton::hitTest (int mx, int my)
  47538. {
  47539. int x, y, w, h;
  47540. getActiveArea (x, y, w, h);
  47541. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  47542. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  47543. {
  47544. if (((unsigned int) mx) < (unsigned int) getWidth()
  47545. && my >= y + overlapPixels
  47546. && my < y + h - overlapPixels)
  47547. return true;
  47548. }
  47549. else
  47550. {
  47551. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  47552. && ((unsigned int) my) < (unsigned int) getHeight())
  47553. return true;
  47554. }
  47555. Path p;
  47556. getLookAndFeel()
  47557. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  47558. owner->getOrientation(),
  47559. false, false, getToggleState());
  47560. return p.contains ((float) (mx - x),
  47561. (float) (my - y));
  47562. }
  47563. int TabBarButton::getBestTabLength (const int depth)
  47564. {
  47565. return jlimit (depth * 2,
  47566. depth * 7,
  47567. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  47568. }
  47569. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  47570. {
  47571. x = 0;
  47572. y = 0;
  47573. int r = getWidth();
  47574. int b = getHeight();
  47575. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  47576. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  47577. r -= spaceAroundImage;
  47578. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  47579. x += spaceAroundImage;
  47580. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  47581. y += spaceAroundImage;
  47582. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  47583. b -= spaceAroundImage;
  47584. w = r - x;
  47585. h = b - y;
  47586. }
  47587. class TabAreaBehindFrontButtonComponent : public Component
  47588. {
  47589. public:
  47590. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  47591. : owner (owner_)
  47592. {
  47593. setInterceptsMouseClicks (false, false);
  47594. }
  47595. ~TabAreaBehindFrontButtonComponent()
  47596. {
  47597. }
  47598. void paint (Graphics& g)
  47599. {
  47600. getLookAndFeel()
  47601. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  47602. *owner, owner->getOrientation());
  47603. }
  47604. void enablementChanged()
  47605. {
  47606. repaint();
  47607. }
  47608. private:
  47609. TabbedButtonBar* const owner;
  47610. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  47611. const TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  47612. };
  47613. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  47614. : orientation (orientation_),
  47615. currentTabIndex (-1),
  47616. extraTabsButton (0)
  47617. {
  47618. setInterceptsMouseClicks (false, true);
  47619. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  47620. setFocusContainer (true);
  47621. }
  47622. TabbedButtonBar::~TabbedButtonBar()
  47623. {
  47624. deleteAllChildren();
  47625. }
  47626. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  47627. {
  47628. orientation = newOrientation;
  47629. for (int i = getNumChildComponents(); --i >= 0;)
  47630. getChildComponent (i)->resized();
  47631. resized();
  47632. }
  47633. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  47634. {
  47635. return new TabBarButton (name, this, index);
  47636. }
  47637. void TabbedButtonBar::clearTabs()
  47638. {
  47639. tabs.clear();
  47640. tabColours.clear();
  47641. currentTabIndex = -1;
  47642. deleteAndZero (extraTabsButton);
  47643. removeChildComponent (behindFrontTab);
  47644. deleteAllChildren();
  47645. addChildComponent (behindFrontTab);
  47646. setCurrentTabIndex (-1);
  47647. }
  47648. void TabbedButtonBar::addTab (const String& tabName,
  47649. const Colour& tabBackgroundColour,
  47650. int insertIndex)
  47651. {
  47652. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  47653. if (tabName.isNotEmpty())
  47654. {
  47655. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  47656. insertIndex = tabs.size();
  47657. for (int i = tabs.size(); --i >= insertIndex;)
  47658. {
  47659. TabBarButton* const tb = getTabButton (i);
  47660. if (tb != 0)
  47661. tb->tabIndex++;
  47662. }
  47663. tabs.insert (insertIndex, tabName);
  47664. tabColours.insert (insertIndex, tabBackgroundColour);
  47665. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  47666. jassert (tb != 0); // your createTabButton() mustn't return zero!
  47667. addAndMakeVisible (tb, insertIndex);
  47668. resized();
  47669. if (currentTabIndex < 0)
  47670. setCurrentTabIndex (0);
  47671. }
  47672. }
  47673. void TabbedButtonBar::setTabName (const int tabIndex,
  47674. const String& newName)
  47675. {
  47676. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  47677. && tabs[tabIndex] != newName)
  47678. {
  47679. tabs.set (tabIndex, newName);
  47680. TabBarButton* const tb = getTabButton (tabIndex);
  47681. if (tb != 0)
  47682. tb->setButtonText (newName);
  47683. resized();
  47684. }
  47685. }
  47686. void TabbedButtonBar::removeTab (const int tabIndex)
  47687. {
  47688. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  47689. {
  47690. const int oldTabIndex = currentTabIndex;
  47691. if (currentTabIndex == tabIndex)
  47692. currentTabIndex = -1;
  47693. tabs.remove (tabIndex);
  47694. tabColours.remove (tabIndex);
  47695. TabBarButton* const tb = getTabButton (tabIndex);
  47696. if (tb != 0)
  47697. delete tb;
  47698. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  47699. {
  47700. TabBarButton* const tb = getTabButton (i);
  47701. if (tb != 0)
  47702. tb->tabIndex--;
  47703. }
  47704. resized();
  47705. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  47706. }
  47707. }
  47708. void TabbedButtonBar::moveTab (const int currentIndex,
  47709. const int newIndex)
  47710. {
  47711. tabs.move (currentIndex, newIndex);
  47712. tabColours.move (currentIndex, newIndex);
  47713. resized();
  47714. }
  47715. int TabbedButtonBar::getNumTabs() const
  47716. {
  47717. return tabs.size();
  47718. }
  47719. const StringArray TabbedButtonBar::getTabNames() const
  47720. {
  47721. return tabs;
  47722. }
  47723. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  47724. {
  47725. if (currentTabIndex != newIndex)
  47726. {
  47727. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  47728. newIndex = -1;
  47729. currentTabIndex = newIndex;
  47730. for (int i = 0; i < getNumChildComponents(); ++i)
  47731. {
  47732. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  47733. if (tb != 0)
  47734. tb->setToggleState (tb->tabIndex == newIndex, false);
  47735. }
  47736. resized();
  47737. if (sendChangeMessage_)
  47738. sendChangeMessage (this);
  47739. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  47740. }
  47741. }
  47742. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  47743. {
  47744. for (int i = getNumChildComponents(); --i >= 0;)
  47745. {
  47746. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  47747. if (tb != 0 && tb->tabIndex == index)
  47748. return tb;
  47749. }
  47750. return 0;
  47751. }
  47752. void TabbedButtonBar::lookAndFeelChanged()
  47753. {
  47754. deleteAndZero (extraTabsButton);
  47755. resized();
  47756. }
  47757. void TabbedButtonBar::resized()
  47758. {
  47759. const double minimumScale = 0.7;
  47760. int depth = getWidth();
  47761. int length = getHeight();
  47762. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  47763. swapVariables (depth, length);
  47764. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  47765. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  47766. int i, totalLength = overlap;
  47767. int numVisibleButtons = tabs.size();
  47768. for (i = 0; i < getNumChildComponents(); ++i)
  47769. {
  47770. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  47771. if (tb != 0)
  47772. {
  47773. totalLength += tb->getBestTabLength (depth) - overlap;
  47774. tb->overlapPixels = overlap / 2;
  47775. }
  47776. }
  47777. double scale = 1.0;
  47778. if (totalLength > length)
  47779. scale = jmax (minimumScale, length / (double) totalLength);
  47780. const bool isTooBig = totalLength * scale > length;
  47781. int tabsButtonPos = 0;
  47782. if (isTooBig)
  47783. {
  47784. if (extraTabsButton == 0)
  47785. {
  47786. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  47787. extraTabsButton->addButtonListener (this);
  47788. extraTabsButton->setAlwaysOnTop (true);
  47789. extraTabsButton->setTriggeredOnMouseDown (true);
  47790. }
  47791. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  47792. extraTabsButton->setSize (buttonSize, buttonSize);
  47793. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  47794. {
  47795. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  47796. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  47797. }
  47798. else
  47799. {
  47800. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  47801. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  47802. }
  47803. totalLength = 0;
  47804. for (i = 0; i < tabs.size(); ++i)
  47805. {
  47806. TabBarButton* const tb = getTabButton (i);
  47807. if (tb != 0)
  47808. {
  47809. const int newLength = totalLength + tb->getBestTabLength (depth);
  47810. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  47811. {
  47812. totalLength += overlap;
  47813. break;
  47814. }
  47815. numVisibleButtons = i + 1;
  47816. totalLength = newLength - overlap;
  47817. }
  47818. }
  47819. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  47820. }
  47821. else
  47822. {
  47823. deleteAndZero (extraTabsButton);
  47824. }
  47825. int pos = 0;
  47826. TabBarButton* frontTab = 0;
  47827. for (i = 0; i < tabs.size(); ++i)
  47828. {
  47829. TabBarButton* const tb = getTabButton (i);
  47830. if (tb != 0)
  47831. {
  47832. const int bestLength = roundDoubleToInt (scale * tb->getBestTabLength (depth));
  47833. if (i < numVisibleButtons)
  47834. {
  47835. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  47836. tb->setBounds (pos, 0, bestLength, getHeight());
  47837. else
  47838. tb->setBounds (0, pos, getWidth(), bestLength);
  47839. tb->toBack();
  47840. if (tb->tabIndex == currentTabIndex)
  47841. frontTab = tb;
  47842. tb->setVisible (true);
  47843. }
  47844. else
  47845. {
  47846. tb->setVisible (false);
  47847. }
  47848. pos += bestLength - overlap;
  47849. }
  47850. }
  47851. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  47852. if (frontTab != 0)
  47853. {
  47854. frontTab->toFront (false);
  47855. behindFrontTab->toBehind (frontTab);
  47856. }
  47857. }
  47858. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  47859. {
  47860. return tabColours [tabIndex];
  47861. }
  47862. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  47863. {
  47864. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  47865. && tabColours [tabIndex] != newColour)
  47866. {
  47867. tabColours.set (tabIndex, newColour);
  47868. repaint();
  47869. }
  47870. }
  47871. void TabbedButtonBar::buttonClicked (Button* button)
  47872. {
  47873. if (extraTabsButton == button)
  47874. {
  47875. PopupMenu m;
  47876. for (int i = 0; i < tabs.size(); ++i)
  47877. {
  47878. TabBarButton* const tb = getTabButton (i);
  47879. if (tb != 0 && ! tb->isVisible())
  47880. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  47881. }
  47882. const int res = m.showAt (extraTabsButton);
  47883. if (res != 0)
  47884. setCurrentTabIndex (res - 1);
  47885. }
  47886. }
  47887. void TabbedButtonBar::currentTabChanged (const int, const String&)
  47888. {
  47889. }
  47890. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  47891. {
  47892. }
  47893. END_JUCE_NAMESPACE
  47894. /********* End of inlined file: juce_TabbedButtonBar.cpp *********/
  47895. /********* Start of inlined file: juce_TabbedComponent.cpp *********/
  47896. BEGIN_JUCE_NAMESPACE
  47897. class TabCompButtonBar : public TabbedButtonBar
  47898. {
  47899. public:
  47900. TabCompButtonBar (TabbedComponent* const owner_,
  47901. const TabbedButtonBar::Orientation orientation)
  47902. : TabbedButtonBar (orientation),
  47903. owner (owner_)
  47904. {
  47905. }
  47906. ~TabCompButtonBar()
  47907. {
  47908. }
  47909. void currentTabChanged (const int newCurrentTabIndex,
  47910. const String& newTabName)
  47911. {
  47912. owner->changeCallback (newCurrentTabIndex, newTabName);
  47913. }
  47914. void popupMenuClickOnTab (const int tabIndex,
  47915. const String& tabName)
  47916. {
  47917. owner->popupMenuClickOnTab (tabIndex, tabName);
  47918. }
  47919. const Colour getTabBackgroundColour (const int tabIndex)
  47920. {
  47921. return owner->tabs->getTabBackgroundColour (tabIndex);
  47922. }
  47923. TabBarButton* createTabButton (const String& tabName, const int tabIndex)
  47924. {
  47925. return owner->createTabButton (tabName, tabIndex);
  47926. }
  47927. juce_UseDebuggingNewOperator
  47928. private:
  47929. TabbedComponent* const owner;
  47930. TabCompButtonBar (const TabCompButtonBar&);
  47931. const TabCompButtonBar& operator= (const TabCompButtonBar&);
  47932. };
  47933. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  47934. : panelComponent (0),
  47935. tabDepth (30),
  47936. outlineThickness (1),
  47937. edgeIndent (0)
  47938. {
  47939. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  47940. }
  47941. TabbedComponent::~TabbedComponent()
  47942. {
  47943. clearTabs();
  47944. delete tabs;
  47945. }
  47946. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  47947. {
  47948. tabs->setOrientation (orientation);
  47949. resized();
  47950. }
  47951. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  47952. {
  47953. return tabs->getOrientation();
  47954. }
  47955. void TabbedComponent::setTabBarDepth (const int newDepth)
  47956. {
  47957. if (tabDepth != newDepth)
  47958. {
  47959. tabDepth = newDepth;
  47960. resized();
  47961. }
  47962. }
  47963. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  47964. {
  47965. return new TabBarButton (tabName, tabs, tabIndex);
  47966. }
  47967. void TabbedComponent::clearTabs()
  47968. {
  47969. if (panelComponent != 0)
  47970. {
  47971. panelComponent->setVisible (false);
  47972. removeChildComponent (panelComponent);
  47973. panelComponent = 0;
  47974. }
  47975. tabs->clearTabs();
  47976. for (int i = contentComponents.size(); --i >= 0;)
  47977. {
  47978. Component* const c = contentComponents.getUnchecked(i);
  47979. // be careful not to delete these components until they've been removed from the tab component
  47980. jassert (c == 0 || c->isValidComponent());
  47981. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  47982. delete c;
  47983. }
  47984. contentComponents.clear();
  47985. }
  47986. void TabbedComponent::addTab (const String& tabName,
  47987. const Colour& tabBackgroundColour,
  47988. Component* const contentComponent,
  47989. const bool deleteComponentWhenNotNeeded,
  47990. const int insertIndex)
  47991. {
  47992. contentComponents.insert (insertIndex, contentComponent);
  47993. if (contentComponent != 0)
  47994. contentComponent->setComponentProperty (T("deleteByTabComp_"), deleteComponentWhenNotNeeded);
  47995. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  47996. }
  47997. void TabbedComponent::setTabName (const int tabIndex,
  47998. const String& newName)
  47999. {
  48000. tabs->setTabName (tabIndex, newName);
  48001. }
  48002. void TabbedComponent::removeTab (const int tabIndex)
  48003. {
  48004. Component* const c = contentComponents [tabIndex];
  48005. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  48006. {
  48007. if (c == panelComponent)
  48008. panelComponent = 0;
  48009. delete c;
  48010. }
  48011. contentComponents.remove (tabIndex);
  48012. tabs->removeTab (tabIndex);
  48013. }
  48014. int TabbedComponent::getNumTabs() const
  48015. {
  48016. return tabs->getNumTabs();
  48017. }
  48018. const StringArray TabbedComponent::getTabNames() const
  48019. {
  48020. return tabs->getTabNames();
  48021. }
  48022. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  48023. {
  48024. return contentComponents [tabIndex];
  48025. }
  48026. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  48027. {
  48028. return tabs->getTabBackgroundColour (tabIndex);
  48029. }
  48030. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  48031. {
  48032. tabs->setTabBackgroundColour (tabIndex, newColour);
  48033. if (getCurrentTabIndex() == tabIndex)
  48034. repaint();
  48035. }
  48036. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  48037. {
  48038. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  48039. }
  48040. int TabbedComponent::getCurrentTabIndex() const
  48041. {
  48042. return tabs->getCurrentTabIndex();
  48043. }
  48044. const String& TabbedComponent::getCurrentTabName() const
  48045. {
  48046. return tabs->getCurrentTabName();
  48047. }
  48048. void TabbedComponent::setOutline (int thickness)
  48049. {
  48050. outlineThickness = thickness;
  48051. repaint();
  48052. }
  48053. void TabbedComponent::setIndent (const int indentThickness)
  48054. {
  48055. edgeIndent = indentThickness;
  48056. }
  48057. void TabbedComponent::paint (Graphics& g)
  48058. {
  48059. g.fillAll (findColour (backgroundColourId));
  48060. const TabbedButtonBar::Orientation o = getOrientation();
  48061. int x = 0;
  48062. int y = 0;
  48063. int r = getWidth();
  48064. int b = getHeight();
  48065. if (o == TabbedButtonBar::TabsAtTop)
  48066. y += tabDepth;
  48067. else if (o == TabbedButtonBar::TabsAtBottom)
  48068. b -= tabDepth;
  48069. else if (o == TabbedButtonBar::TabsAtLeft)
  48070. x += tabDepth;
  48071. else if (o == TabbedButtonBar::TabsAtRight)
  48072. r -= tabDepth;
  48073. g.reduceClipRegion (x, y, r - x, b - y);
  48074. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  48075. if (outlineThickness > 0)
  48076. {
  48077. if (o == TabbedButtonBar::TabsAtTop)
  48078. --y;
  48079. else if (o == TabbedButtonBar::TabsAtBottom)
  48080. ++b;
  48081. else if (o == TabbedButtonBar::TabsAtLeft)
  48082. --x;
  48083. else if (o == TabbedButtonBar::TabsAtRight)
  48084. ++r;
  48085. g.setColour (findColour (outlineColourId));
  48086. g.drawRect (x, y, r - x, b - y, outlineThickness);
  48087. }
  48088. }
  48089. void TabbedComponent::resized()
  48090. {
  48091. const TabbedButtonBar::Orientation o = getOrientation();
  48092. const int indent = edgeIndent + outlineThickness;
  48093. BorderSize indents (indent);
  48094. if (o == TabbedButtonBar::TabsAtTop)
  48095. {
  48096. tabs->setBounds (0, 0, getWidth(), tabDepth);
  48097. indents.setTop (tabDepth + edgeIndent);
  48098. }
  48099. else if (o == TabbedButtonBar::TabsAtBottom)
  48100. {
  48101. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  48102. indents.setBottom (tabDepth + edgeIndent);
  48103. }
  48104. else if (o == TabbedButtonBar::TabsAtLeft)
  48105. {
  48106. tabs->setBounds (0, 0, tabDepth, getHeight());
  48107. indents.setLeft (tabDepth + edgeIndent);
  48108. }
  48109. else if (o == TabbedButtonBar::TabsAtRight)
  48110. {
  48111. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  48112. indents.setRight (tabDepth + edgeIndent);
  48113. }
  48114. const Rectangle bounds (indents.subtractedFrom (Rectangle (0, 0, getWidth(), getHeight())));
  48115. for (int i = contentComponents.size(); --i >= 0;)
  48116. if (contentComponents.getUnchecked (i) != 0)
  48117. contentComponents.getUnchecked (i)->setBounds (bounds);
  48118. }
  48119. void TabbedComponent::lookAndFeelChanged()
  48120. {
  48121. for (int i = contentComponents.size(); --i >= 0;)
  48122. if (contentComponents.getUnchecked (i) != 0)
  48123. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  48124. }
  48125. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  48126. const String& newTabName)
  48127. {
  48128. if (panelComponent != 0)
  48129. {
  48130. panelComponent->setVisible (false);
  48131. removeChildComponent (panelComponent);
  48132. panelComponent = 0;
  48133. }
  48134. if (getCurrentTabIndex() >= 0)
  48135. {
  48136. panelComponent = contentComponents [getCurrentTabIndex()];
  48137. if (panelComponent != 0)
  48138. {
  48139. // do these ops as two stages instead of addAndMakeVisible() so that the
  48140. // component has always got a parent when it gets the visibilityChanged() callback
  48141. addChildComponent (panelComponent);
  48142. panelComponent->setVisible (true);
  48143. panelComponent->toFront (true);
  48144. }
  48145. repaint();
  48146. }
  48147. resized();
  48148. currentTabChanged (newCurrentTabIndex, newTabName);
  48149. }
  48150. void TabbedComponent::currentTabChanged (const int, const String&)
  48151. {
  48152. }
  48153. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  48154. {
  48155. }
  48156. END_JUCE_NAMESPACE
  48157. /********* End of inlined file: juce_TabbedComponent.cpp *********/
  48158. /********* Start of inlined file: juce_Viewport.cpp *********/
  48159. BEGIN_JUCE_NAMESPACE
  48160. Viewport::Viewport (const String& componentName)
  48161. : Component (componentName),
  48162. contentComp (0),
  48163. lastVX (0),
  48164. lastVY (0),
  48165. lastVW (0),
  48166. lastVH (0),
  48167. scrollBarThickness (0),
  48168. singleStepX (16),
  48169. singleStepY (16),
  48170. showHScrollbar (true),
  48171. showVScrollbar (true)
  48172. {
  48173. // content holder is used to clip the contents so they don't overlap the scrollbars
  48174. addAndMakeVisible (contentHolder = new Component());
  48175. contentHolder->setInterceptsMouseClicks (false, true);
  48176. verticalScrollBar = new ScrollBar (true);
  48177. horizontalScrollBar = new ScrollBar (false);
  48178. addChildComponent (verticalScrollBar);
  48179. addChildComponent (horizontalScrollBar);
  48180. verticalScrollBar->addListener (this);
  48181. horizontalScrollBar->addListener (this);
  48182. setInterceptsMouseClicks (false, true);
  48183. setWantsKeyboardFocus (true);
  48184. }
  48185. Viewport::~Viewport()
  48186. {
  48187. contentHolder->deleteAllChildren();
  48188. deleteAllChildren();
  48189. }
  48190. void Viewport::visibleAreaChanged (int, int, int, int)
  48191. {
  48192. }
  48193. void Viewport::setViewedComponent (Component* const newViewedComponent)
  48194. {
  48195. if (contentComp != newViewedComponent)
  48196. {
  48197. if (contentComp->isValidComponent())
  48198. {
  48199. Component* const oldComp = contentComp;
  48200. contentComp = 0;
  48201. delete oldComp;
  48202. }
  48203. contentComp = newViewedComponent;
  48204. if (contentComp != 0)
  48205. {
  48206. contentComp->setTopLeftPosition (0, 0);
  48207. contentHolder->addAndMakeVisible (contentComp);
  48208. contentComp->addComponentListener (this);
  48209. }
  48210. updateVisibleRegion();
  48211. }
  48212. }
  48213. int Viewport::getMaximumVisibleWidth() const throw()
  48214. {
  48215. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  48216. }
  48217. int Viewport::getMaximumVisibleHeight() const throw()
  48218. {
  48219. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  48220. }
  48221. void Viewport::setViewPosition (const int xPixelsOffset,
  48222. const int yPixelsOffset)
  48223. {
  48224. if (contentComp != 0)
  48225. contentComp->setTopLeftPosition (-xPixelsOffset,
  48226. -yPixelsOffset);
  48227. }
  48228. void Viewport::setViewPositionProportionately (const double x,
  48229. const double y)
  48230. {
  48231. if (contentComp != 0)
  48232. setViewPosition (jmax (0, roundDoubleToInt (x * (contentComp->getWidth() - getWidth()))),
  48233. jmax (0, roundDoubleToInt (y * (contentComp->getHeight() - getHeight()))));
  48234. }
  48235. void Viewport::componentMovedOrResized (Component&, bool, bool)
  48236. {
  48237. updateVisibleRegion();
  48238. }
  48239. void Viewport::resized()
  48240. {
  48241. updateVisibleRegion();
  48242. }
  48243. void Viewport::updateVisibleRegion()
  48244. {
  48245. if (contentComp != 0)
  48246. {
  48247. const int newVX = -contentComp->getX();
  48248. const int newVY = -contentComp->getY();
  48249. if (newVX == 0 && newVY == 0
  48250. && contentComp->getWidth() <= getWidth()
  48251. && contentComp->getHeight() <= getHeight())
  48252. {
  48253. horizontalScrollBar->setVisible (false);
  48254. verticalScrollBar->setVisible (false);
  48255. }
  48256. if ((contentComp->getWidth() > 0) && showHScrollbar
  48257. && getHeight() > getScrollBarThickness())
  48258. {
  48259. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  48260. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48261. horizontalScrollBar->setSingleStepSize (singleStepX);
  48262. }
  48263. else
  48264. {
  48265. horizontalScrollBar->setVisible (false);
  48266. }
  48267. if ((contentComp->getHeight() > 0) && showVScrollbar
  48268. && getWidth() > getScrollBarThickness())
  48269. {
  48270. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  48271. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  48272. verticalScrollBar->setSingleStepSize (singleStepY);
  48273. }
  48274. else
  48275. {
  48276. verticalScrollBar->setVisible (false);
  48277. }
  48278. if (verticalScrollBar->isVisible())
  48279. {
  48280. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48281. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  48282. verticalScrollBar
  48283. ->setBounds (getMaximumVisibleWidth(), 0,
  48284. getScrollBarThickness(), getMaximumVisibleHeight());
  48285. }
  48286. if (horizontalScrollBar->isVisible())
  48287. {
  48288. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48289. horizontalScrollBar
  48290. ->setBounds (0, getMaximumVisibleHeight(),
  48291. getMaximumVisibleWidth(), getScrollBarThickness());
  48292. }
  48293. contentHolder->setSize (getMaximumVisibleWidth(),
  48294. getMaximumVisibleHeight());
  48295. const int newVW = jmin (contentComp->getRight(), getMaximumVisibleWidth());
  48296. const int newVH = jmin (contentComp->getBottom(), getMaximumVisibleHeight());
  48297. if (newVX != lastVX
  48298. || newVY != lastVY
  48299. || newVW != lastVW
  48300. || newVH != lastVH)
  48301. {
  48302. lastVX = newVX;
  48303. lastVY = newVY;
  48304. lastVW = newVW;
  48305. lastVH = newVH;
  48306. visibleAreaChanged (newVX, newVY, newVW, newVH);
  48307. }
  48308. horizontalScrollBar->handleUpdateNowIfNeeded();
  48309. verticalScrollBar->handleUpdateNowIfNeeded();
  48310. }
  48311. else
  48312. {
  48313. horizontalScrollBar->setVisible (false);
  48314. verticalScrollBar->setVisible (false);
  48315. }
  48316. }
  48317. void Viewport::setSingleStepSizes (const int stepX,
  48318. const int stepY)
  48319. {
  48320. singleStepX = stepX;
  48321. singleStepY = stepY;
  48322. updateVisibleRegion();
  48323. }
  48324. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  48325. const bool showHorizontalScrollbarIfNeeded)
  48326. {
  48327. showVScrollbar = showVerticalScrollbarIfNeeded;
  48328. showHScrollbar = showHorizontalScrollbarIfNeeded;
  48329. updateVisibleRegion();
  48330. }
  48331. void Viewport::setScrollBarThickness (const int thickness)
  48332. {
  48333. scrollBarThickness = thickness;
  48334. updateVisibleRegion();
  48335. }
  48336. int Viewport::getScrollBarThickness() const throw()
  48337. {
  48338. return (scrollBarThickness > 0) ? scrollBarThickness
  48339. : getLookAndFeel().getDefaultScrollbarWidth();
  48340. }
  48341. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  48342. {
  48343. verticalScrollBar->setButtonVisibility (buttonsVisible);
  48344. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  48345. }
  48346. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart)
  48347. {
  48348. if (scrollBarThatHasMoved == horizontalScrollBar)
  48349. {
  48350. setViewPosition (roundDoubleToInt (newRangeStart), getViewPositionY());
  48351. }
  48352. else if (scrollBarThatHasMoved == verticalScrollBar)
  48353. {
  48354. setViewPosition (getViewPositionX(), roundDoubleToInt (newRangeStart));
  48355. }
  48356. }
  48357. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  48358. {
  48359. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  48360. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  48361. }
  48362. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  48363. {
  48364. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  48365. {
  48366. const bool hasVertBar = verticalScrollBar->isVisible();
  48367. const bool hasHorzBar = horizontalScrollBar->isVisible();
  48368. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  48369. {
  48370. if (wheelIncrementX == 0 && ! hasVertBar)
  48371. wheelIncrementX = wheelIncrementY;
  48372. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  48373. wheelIncrementX, wheelIncrementY);
  48374. return true;
  48375. }
  48376. else if (hasVertBar && wheelIncrementY != 0)
  48377. {
  48378. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  48379. wheelIncrementX, wheelIncrementY);
  48380. return true;
  48381. }
  48382. }
  48383. return false;
  48384. }
  48385. bool Viewport::keyPressed (const KeyPress& key)
  48386. {
  48387. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  48388. || key.isKeyCode (KeyPress::downKey)
  48389. || key.isKeyCode (KeyPress::pageUpKey)
  48390. || key.isKeyCode (KeyPress::pageDownKey)
  48391. || key.isKeyCode (KeyPress::homeKey)
  48392. || key.isKeyCode (KeyPress::endKey);
  48393. if (verticalScrollBar->isVisible() && isUpDownKey)
  48394. return verticalScrollBar->keyPressed (key);
  48395. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  48396. || key.isKeyCode (KeyPress::rightKey);
  48397. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  48398. return horizontalScrollBar->keyPressed (key);
  48399. return false;
  48400. }
  48401. END_JUCE_NAMESPACE
  48402. /********* End of inlined file: juce_Viewport.cpp *********/
  48403. /********* Start of inlined file: juce_LookAndFeel.cpp *********/
  48404. BEGIN_JUCE_NAMESPACE
  48405. static const Colour createBaseColour (const Colour& buttonColour,
  48406. const bool hasKeyboardFocus,
  48407. const bool isMouseOverButton,
  48408. const bool isButtonDown) throw()
  48409. {
  48410. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  48411. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  48412. if (isButtonDown)
  48413. return baseColour.contrasting (0.2f);
  48414. else if (isMouseOverButton)
  48415. return baseColour.contrasting (0.1f);
  48416. return baseColour;
  48417. }
  48418. static String defaultSansName, defaultSerifName, defaultFixedName;
  48419. void clearUpDefaultFontNames() throw()
  48420. {
  48421. defaultSansName = String::empty;
  48422. defaultSerifName = String::empty;
  48423. defaultFixedName = String::empty;
  48424. }
  48425. LookAndFeel::LookAndFeel()
  48426. {
  48427. /* if this fails it means you're trying to create a LookAndFeel object before
  48428. the static Colours have been initialised. That ain't gonna work. It probably
  48429. means that you're using a static LookAndFeel object and that your compiler has
  48430. decided to intialise it before the Colours class.
  48431. */
  48432. jassert (Colours::white == Colour (0xffffffff));
  48433. // set up the standard set of colours..
  48434. #define textButtonColour 0xffbbbbff
  48435. #define textHighlightColour 0x401111ee
  48436. #define standardOutlineColour 0xb2808080
  48437. static const int standardColours[] =
  48438. {
  48439. TextButton::buttonColourId, textButtonColour,
  48440. TextButton::buttonOnColourId, 0xff4444ff,
  48441. TextButton::textColourId, 0xff000000,
  48442. ComboBox::buttonColourId, 0xffbbbbff,
  48443. ComboBox::outlineColourId, standardOutlineColour,
  48444. ToggleButton::textColourId, 0xff000000,
  48445. TextEditor::backgroundColourId, 0xffffffff,
  48446. TextEditor::textColourId, 0xff000000,
  48447. TextEditor::highlightColourId, textHighlightColour,
  48448. TextEditor::highlightedTextColourId, 0xff000000,
  48449. TextEditor::caretColourId, 0xff000000,
  48450. TextEditor::outlineColourId, 0x00000000,
  48451. TextEditor::focusedOutlineColourId, textButtonColour,
  48452. TextEditor::shadowColourId, 0x38000000,
  48453. Label::backgroundColourId, 0x00000000,
  48454. Label::textColourId, 0xff000000,
  48455. Label::outlineColourId, 0x00000000,
  48456. ScrollBar::backgroundColourId, 0x00000000,
  48457. ScrollBar::thumbColourId, 0xffffffff,
  48458. ScrollBar::trackColourId, 0xffffffff,
  48459. TreeView::linesColourId, 0x4c000000,
  48460. TreeView::backgroundColourId, 0x00000000,
  48461. PopupMenu::backgroundColourId, 0xffffffff,
  48462. PopupMenu::textColourId, 0xff000000,
  48463. PopupMenu::headerTextColourId, 0xff000000,
  48464. PopupMenu::highlightedTextColourId, 0xffffffff,
  48465. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  48466. ComboBox::textColourId, 0xff000000,
  48467. ComboBox::backgroundColourId, 0xffffffff,
  48468. ComboBox::arrowColourId, 0x99000000,
  48469. ListBox::backgroundColourId, 0xffffffff,
  48470. ListBox::outlineColourId, standardOutlineColour,
  48471. ListBox::textColourId, 0xff000000,
  48472. Slider::backgroundColourId, 0x00000000,
  48473. Slider::thumbColourId, textButtonColour,
  48474. Slider::trackColourId, 0x7fffffff,
  48475. Slider::rotarySliderFillColourId, 0x7f0000ff,
  48476. Slider::rotarySliderOutlineColourId, 0x66000000,
  48477. Slider::textBoxTextColourId, 0xff000000,
  48478. Slider::textBoxBackgroundColourId, 0xffffffff,
  48479. Slider::textBoxHighlightColourId, textHighlightColour,
  48480. Slider::textBoxOutlineColourId, standardOutlineColour,
  48481. ResizableWindow::backgroundColourId, 0xff777777,
  48482. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  48483. AlertWindow::backgroundColourId, 0xffededed,
  48484. AlertWindow::textColourId, 0xff000000,
  48485. AlertWindow::outlineColourId, 0xff666666,
  48486. ProgressBar::backgroundColourId, 0xffeeeeee,
  48487. ProgressBar::foregroundColourId, 0xffaaaaee,
  48488. TooltipWindow::backgroundColourId, 0xffeeeebb,
  48489. TooltipWindow::textColourId, 0xff000000,
  48490. TooltipWindow::outlineColourId, 0x4c000000,
  48491. TabbedComponent::backgroundColourId, 0x00000000,
  48492. TabbedComponent::outlineColourId, 0xff777777,
  48493. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  48494. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  48495. Toolbar::backgroundColourId, 0xfff6f8f9,
  48496. Toolbar::separatorColourId, 0x4c000000,
  48497. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  48498. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  48499. Toolbar::labelTextColourId, 0xff000000,
  48500. Toolbar::editingModeOutlineColourId, 0xffff0000,
  48501. HyperlinkButton::textColourId, 0xcc1111ee,
  48502. GroupComponent::outlineColourId, 0x66000000,
  48503. GroupComponent::textColourId, 0xff000000,
  48504. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  48505. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  48506. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  48507. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  48508. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  48509. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  48510. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  48511. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  48512. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  48513. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  48514. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  48515. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  48516. ColourSelector::backgroundColourId, 0xffe5e5e5,
  48517. ColourSelector::labelTextColourId, 0xff000000,
  48518. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  48519. };
  48520. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  48521. setColour (standardColours [i], Colour (standardColours [i + 1]));
  48522. if (defaultSansName.isEmpty())
  48523. Typeface::getDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  48524. defaultSans = defaultSansName;
  48525. defaultSerif = defaultSerifName;
  48526. defaultFixed = defaultFixedName;
  48527. }
  48528. LookAndFeel::~LookAndFeel()
  48529. {
  48530. }
  48531. const Colour LookAndFeel::findColour (const int colourId) const throw()
  48532. {
  48533. const int index = colourIds.indexOf (colourId);
  48534. if (index >= 0)
  48535. return colours [index];
  48536. jassertfalse
  48537. return Colours::black;
  48538. }
  48539. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  48540. {
  48541. const int index = colourIds.indexOf (colourId);
  48542. if (index >= 0)
  48543. colours.set (index, colour);
  48544. colourIds.add (colourId);
  48545. colours.add (colour);
  48546. }
  48547. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  48548. {
  48549. return colourIds.contains (colourId);
  48550. }
  48551. static LookAndFeel* defaultLF = 0;
  48552. static LookAndFeel* currentDefaultLF = 0;
  48553. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  48554. {
  48555. // if this happens, your app hasn't initialised itself properly.. if you're
  48556. // trying to hack your own main() function, have a look at
  48557. // JUCEApplication::initialiseForGUI()
  48558. jassert (currentDefaultLF != 0);
  48559. return *currentDefaultLF;
  48560. }
  48561. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  48562. {
  48563. if (newDefaultLookAndFeel == 0)
  48564. {
  48565. if (defaultLF == 0)
  48566. defaultLF = new LookAndFeel();
  48567. newDefaultLookAndFeel = defaultLF;
  48568. }
  48569. currentDefaultLF = newDefaultLookAndFeel;
  48570. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  48571. {
  48572. Component* const c = Desktop::getInstance().getComponent (i);
  48573. if (c != 0)
  48574. c->sendLookAndFeelChange();
  48575. }
  48576. }
  48577. void LookAndFeel::clearDefaultLookAndFeel() throw()
  48578. {
  48579. if (currentDefaultLF == defaultLF)
  48580. currentDefaultLF = 0;
  48581. deleteAndZero (defaultLF);
  48582. }
  48583. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  48584. {
  48585. String faceName (font.getTypefaceName());
  48586. if (faceName == Typeface::defaultTypefaceNameSans)
  48587. faceName = defaultSans;
  48588. else if (faceName == Typeface::defaultTypefaceNameSerif)
  48589. faceName = defaultSerif;
  48590. else if (faceName == Typeface::defaultTypefaceNameMono)
  48591. faceName = defaultFixed;
  48592. return new Typeface (faceName, font.isBold(), font.isItalic());
  48593. }
  48594. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  48595. {
  48596. defaultSans = newName;
  48597. }
  48598. void LookAndFeel::drawButtonBackground (Graphics& g,
  48599. Button& button,
  48600. const Colour& backgroundColour,
  48601. bool isMouseOverButton,
  48602. bool isButtonDown)
  48603. {
  48604. const int width = button.getWidth();
  48605. const int height = button.getHeight();
  48606. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  48607. const float halfThickness = outlineThickness * 0.5f;
  48608. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  48609. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  48610. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  48611. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  48612. const Colour baseColour (createBaseColour (backgroundColour,
  48613. button.hasKeyboardFocus (true),
  48614. isMouseOverButton, isButtonDown)
  48615. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  48616. drawGlassLozenge (g,
  48617. indentL,
  48618. indentT,
  48619. width - indentL - indentR,
  48620. height - indentT - indentB,
  48621. baseColour, outlineThickness, -1.0f,
  48622. button.isConnectedOnLeft(),
  48623. button.isConnectedOnRight(),
  48624. button.isConnectedOnTop(),
  48625. button.isConnectedOnBottom());
  48626. }
  48627. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  48628. {
  48629. return button.getFont();
  48630. }
  48631. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  48632. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  48633. {
  48634. g.setFont (getFontForTextButton (button));
  48635. g.setColour (button.findColour (TextButton::textColourId)
  48636. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  48637. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  48638. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  48639. const int fontHeight = roundFloatToInt (g.getCurrentFont().getHeight() * 0.6f);
  48640. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  48641. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  48642. g.drawFittedText (button.getButtonText(),
  48643. leftIndent,
  48644. yIndent,
  48645. button.getWidth() - leftIndent - rightIndent,
  48646. button.getHeight() - yIndent * 2,
  48647. Justification::centred, 2);
  48648. }
  48649. void LookAndFeel::drawTickBox (Graphics& g,
  48650. Component& component,
  48651. int x, int y, int w, int h,
  48652. const bool ticked,
  48653. const bool isEnabled,
  48654. const bool isMouseOverButton,
  48655. const bool isButtonDown)
  48656. {
  48657. const float boxSize = w * 0.7f;
  48658. drawGlassSphere (g, (float) x, y + (h - boxSize) * 0.5f, boxSize,
  48659. createBaseColour (component.findColour (TextButton::buttonColourId)
  48660. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  48661. true,
  48662. isMouseOverButton,
  48663. isButtonDown),
  48664. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  48665. if (ticked)
  48666. {
  48667. Path tick;
  48668. tick.startNewSubPath (1.5f, 3.0f);
  48669. tick.lineTo (3.0f, 6.0f);
  48670. tick.lineTo (6.0f, 0.0f);
  48671. g.setColour (isEnabled ? Colours::black : Colours::grey);
  48672. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  48673. .translated ((float) x, (float) y));
  48674. g.strokePath (tick, PathStrokeType (2.5f), trans);
  48675. }
  48676. }
  48677. void LookAndFeel::drawToggleButton (Graphics& g,
  48678. ToggleButton& button,
  48679. bool isMouseOverButton,
  48680. bool isButtonDown)
  48681. {
  48682. if (button.hasKeyboardFocus (true))
  48683. {
  48684. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  48685. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  48686. }
  48687. const int tickWidth = jmin (20, button.getHeight() - 4);
  48688. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  48689. tickWidth, tickWidth,
  48690. button.getToggleState(),
  48691. button.isEnabled(),
  48692. isMouseOverButton,
  48693. isButtonDown);
  48694. g.setColour (button.findColour (ToggleButton::textColourId));
  48695. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  48696. if (! button.isEnabled())
  48697. g.setOpacity (0.5f);
  48698. const int textX = tickWidth + 5;
  48699. g.drawFittedText (button.getButtonText(),
  48700. textX, 4,
  48701. button.getWidth() - textX - 2, button.getHeight() - 8,
  48702. Justification::centredLeft, 10);
  48703. }
  48704. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  48705. {
  48706. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  48707. const int tickWidth = jmin (24, button.getHeight());
  48708. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  48709. button.getHeight());
  48710. }
  48711. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  48712. const String& message,
  48713. const String& button1,
  48714. const String& button2,
  48715. const String& button3,
  48716. AlertWindow::AlertIconType iconType,
  48717. int numButtons,
  48718. Component* associatedComponent)
  48719. {
  48720. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  48721. if (numButtons == 1)
  48722. {
  48723. aw->addButton (button1, 0,
  48724. KeyPress (KeyPress::escapeKey, 0, 0),
  48725. KeyPress (KeyPress::returnKey, 0, 0));
  48726. }
  48727. else
  48728. {
  48729. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  48730. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  48731. if (button1ShortCut == button2ShortCut)
  48732. button2ShortCut = KeyPress();
  48733. if (numButtons == 2)
  48734. {
  48735. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  48736. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  48737. }
  48738. else if (numButtons == 3)
  48739. {
  48740. aw->addButton (button1, 1, button1ShortCut);
  48741. aw->addButton (button2, 2, button2ShortCut);
  48742. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  48743. }
  48744. }
  48745. return aw;
  48746. }
  48747. void LookAndFeel::drawAlertBox (Graphics& g,
  48748. AlertWindow& alert,
  48749. const Rectangle& textArea,
  48750. TextLayout& textLayout)
  48751. {
  48752. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  48753. int iconSpaceUsed = 0;
  48754. Justification alignment (Justification::horizontallyCentred);
  48755. const int iconWidth = 80;
  48756. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  48757. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  48758. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  48759. const Rectangle iconRect (iconSize / -10, iconSize / -10,
  48760. iconSize, iconSize);
  48761. if (alert.getAlertType() != AlertWindow::NoIcon)
  48762. {
  48763. Path icon;
  48764. uint32 colour;
  48765. char character;
  48766. if (alert.getAlertType() == AlertWindow::WarningIcon)
  48767. {
  48768. colour = 0x55ff5555;
  48769. character = '!';
  48770. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  48771. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  48772. (float) iconRect.getX(), (float) iconRect.getBottom());
  48773. icon = icon.createPathWithRoundedCorners (5.0f);
  48774. }
  48775. else
  48776. {
  48777. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  48778. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  48779. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  48780. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  48781. }
  48782. GlyphArrangement ga;
  48783. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  48784. String::charToString (character),
  48785. (float) iconRect.getX(), (float) iconRect.getY(),
  48786. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  48787. Justification::centred, false);
  48788. ga.createPath (icon);
  48789. icon.setUsingNonZeroWinding (false);
  48790. g.setColour (Colour (colour));
  48791. g.fillPath (icon);
  48792. iconSpaceUsed = iconWidth;
  48793. alignment = Justification::left;
  48794. }
  48795. g.setColour (alert.findColour (AlertWindow::textColourId));
  48796. textLayout.drawWithin (g,
  48797. textArea.getX() + iconSpaceUsed, textArea.getY(),
  48798. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  48799. alignment.getFlags() | Justification::top);
  48800. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  48801. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  48802. }
  48803. int LookAndFeel::getAlertBoxWindowFlags()
  48804. {
  48805. return ComponentPeer::windowAppearsOnTaskbar
  48806. | ComponentPeer::windowHasDropShadow;
  48807. }
  48808. int LookAndFeel::getAlertWindowButtonHeight()
  48809. {
  48810. return 28;
  48811. }
  48812. const Font LookAndFeel::getAlertWindowFont()
  48813. {
  48814. return Font (12.0f);
  48815. }
  48816. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  48817. int width, int height,
  48818. double progress, const String& textToShow)
  48819. {
  48820. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  48821. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  48822. g.fillAll (background);
  48823. if (progress >= 0.0f && progress < 1.0f)
  48824. {
  48825. drawGlassLozenge (g, 1.0f, 1.0f,
  48826. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  48827. (float) (height - 2),
  48828. foreground,
  48829. 0.5f, 0.0f,
  48830. true, true, true, true);
  48831. }
  48832. else
  48833. {
  48834. // spinning bar..
  48835. g.setColour (foreground);
  48836. const int stripeWidth = height * 2;
  48837. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  48838. Path p;
  48839. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  48840. p.addQuadrilateral (x, 0.0f,
  48841. x + stripeWidth * 0.5f, 0.0f,
  48842. x, (float) height,
  48843. x - stripeWidth * 0.5f, (float) height);
  48844. Image im (Image::ARGB, width, height, true);
  48845. {
  48846. Graphics g (im);
  48847. drawGlassLozenge (g, 1.0f, 1.0f,
  48848. (float) (width - 2),
  48849. (float) (height - 2),
  48850. foreground,
  48851. 0.5f, 0.0f,
  48852. true, true, true, true);
  48853. }
  48854. ImageBrush ib (&im, 0, 0, 0.85f);
  48855. g.setBrush (&ib);
  48856. g.fillPath (p);
  48857. }
  48858. if (textToShow.isNotEmpty())
  48859. {
  48860. g.setColour (Colour::contrasting (background, foreground));
  48861. g.setFont (height * 0.6f);
  48862. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  48863. }
  48864. }
  48865. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, int x, int y, int w, int h)
  48866. {
  48867. const float radius = jmin (w, h) * 0.4f;
  48868. const float thickness = radius * 0.15f;
  48869. Path p;
  48870. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  48871. radius * 0.6f, thickness,
  48872. thickness * 0.5f);
  48873. const float cx = x + w * 0.5f;
  48874. const float cy = y + h * 0.5f;
  48875. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  48876. const Colour col (g.getCurrentColour());
  48877. for (int i = 0; i < 12; ++i)
  48878. {
  48879. const int n = (i + 12 - animationIndex) % 12;
  48880. g.setColour (col.withMultipliedAlpha ((n + 1) / 12.0f));
  48881. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  48882. .translated (cx, cy));
  48883. }
  48884. }
  48885. void LookAndFeel::drawScrollbarButton (Graphics& g,
  48886. ScrollBar& scrollbar,
  48887. int width, int height,
  48888. int buttonDirection,
  48889. bool /*isScrollbarVertical*/,
  48890. bool /*isMouseOverButton*/,
  48891. bool isButtonDown)
  48892. {
  48893. Path p;
  48894. if (buttonDirection == 0)
  48895. p.addTriangle (width * 0.5f, height * 0.2f,
  48896. width * 0.1f, height * 0.7f,
  48897. width * 0.9f, height * 0.7f);
  48898. else if (buttonDirection == 1)
  48899. p.addTriangle (width * 0.8f, height * 0.5f,
  48900. width * 0.3f, height * 0.1f,
  48901. width * 0.3f, height * 0.9f);
  48902. else if (buttonDirection == 2)
  48903. p.addTriangle (width * 0.5f, height * 0.8f,
  48904. width * 0.1f, height * 0.3f,
  48905. width * 0.9f, height * 0.3f);
  48906. else if (buttonDirection == 3)
  48907. p.addTriangle (width * 0.2f, height * 0.5f,
  48908. width * 0.7f, height * 0.1f,
  48909. width * 0.7f, height * 0.9f);
  48910. if (isButtonDown)
  48911. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  48912. else
  48913. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  48914. g.fillPath (p);
  48915. g.setColour (Colour (0x80000000));
  48916. g.strokePath (p, PathStrokeType (0.5f));
  48917. }
  48918. void LookAndFeel::drawScrollbar (Graphics& g,
  48919. ScrollBar& scrollbar,
  48920. int x, int y,
  48921. int width, int height,
  48922. bool isScrollbarVertical,
  48923. int thumbStartPosition,
  48924. int thumbSize,
  48925. bool /*isMouseOver*/,
  48926. bool /*isMouseDown*/)
  48927. {
  48928. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  48929. Path slotPath, thumbPath;
  48930. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  48931. const float slotIndentx2 = slotIndent * 2.0f;
  48932. const float thumbIndent = slotIndent + 1.0f;
  48933. const float thumbIndentx2 = thumbIndent * 2.0f;
  48934. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  48935. if (isScrollbarVertical)
  48936. {
  48937. slotPath.addRoundedRectangle (x + slotIndent,
  48938. y + slotIndent,
  48939. width - slotIndentx2,
  48940. height - slotIndentx2,
  48941. (width - slotIndentx2) * 0.5f);
  48942. if (thumbSize > 0)
  48943. thumbPath.addRoundedRectangle (x + thumbIndent,
  48944. thumbStartPosition + thumbIndent,
  48945. width - thumbIndentx2,
  48946. thumbSize - thumbIndentx2,
  48947. (width - thumbIndentx2) * 0.5f);
  48948. gx1 = (float) x;
  48949. gx2 = x + width * 0.7f;
  48950. }
  48951. else
  48952. {
  48953. slotPath.addRoundedRectangle (x + slotIndent,
  48954. y + slotIndent,
  48955. width - slotIndentx2,
  48956. height - slotIndentx2,
  48957. (height - slotIndentx2) * 0.5f);
  48958. if (thumbSize > 0)
  48959. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  48960. y + thumbIndent,
  48961. thumbSize - thumbIndentx2,
  48962. height - thumbIndentx2,
  48963. (height - thumbIndentx2) * 0.5f);
  48964. gy1 = (float) y;
  48965. gy2 = y + height * 0.7f;
  48966. }
  48967. const Colour thumbColour (scrollbar.findColour (ScrollBar::trackColourId));
  48968. GradientBrush gb (thumbColour.overlaidWith (Colour (0x44000000)),
  48969. gx1, gy1,
  48970. thumbColour.overlaidWith (Colour (0x19000000)),
  48971. gx2, gy2, false);
  48972. g.setBrush (&gb);
  48973. g.fillPath (slotPath);
  48974. if (isScrollbarVertical)
  48975. {
  48976. gx1 = x + width * 0.6f;
  48977. gx2 = (float) x + width;
  48978. }
  48979. else
  48980. {
  48981. gy1 = y + height * 0.6f;
  48982. gy2 = (float) y + height;
  48983. }
  48984. GradientBrush gb2 (Colours::transparentBlack,
  48985. gx1, gy1,
  48986. Colour (0x19000000),
  48987. gx2, gy2, false);
  48988. g.setBrush (&gb2);
  48989. g.fillPath (slotPath);
  48990. g.setColour (thumbColour);
  48991. g.fillPath (thumbPath);
  48992. GradientBrush gb3 (Colour (0x10000000),
  48993. gx1, gy1,
  48994. Colours::transparentBlack,
  48995. gx2, gy2, false);
  48996. g.saveState();
  48997. g.setBrush (&gb3);
  48998. if (isScrollbarVertical)
  48999. g.reduceClipRegion (x + width / 2, y, width, height);
  49000. else
  49001. g.reduceClipRegion (x, y + height / 2, width, height);
  49002. g.fillPath (thumbPath);
  49003. g.restoreState();
  49004. g.setColour (Colour (0x4c000000));
  49005. g.strokePath (thumbPath, PathStrokeType (0.4f));
  49006. }
  49007. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  49008. {
  49009. return 0;
  49010. }
  49011. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  49012. {
  49013. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  49014. }
  49015. int LookAndFeel::getDefaultScrollbarWidth()
  49016. {
  49017. return 18;
  49018. }
  49019. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  49020. {
  49021. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  49022. : scrollbar.getHeight());
  49023. }
  49024. const Path LookAndFeel::getTickShape (const float height)
  49025. {
  49026. static const unsigned char tickShapeData[] =
  49027. {
  49028. 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,
  49029. 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,
  49030. 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,
  49031. 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,
  49032. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  49033. };
  49034. Path p;
  49035. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  49036. p.scaleToFit (0, 0, height * 2.0f, height, true);
  49037. return p;
  49038. }
  49039. const Path LookAndFeel::getCrossShape (const float height)
  49040. {
  49041. static const unsigned char crossShapeData[] =
  49042. {
  49043. 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,
  49044. 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,
  49045. 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,
  49046. 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,
  49047. 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,
  49048. 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,
  49049. 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
  49050. };
  49051. Path p;
  49052. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  49053. p.scaleToFit (0, 0, height * 2.0f, height, true);
  49054. return p;
  49055. }
  49056. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  49057. {
  49058. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  49059. x += (w - boxSize) >> 1;
  49060. y += (h - boxSize) >> 1;
  49061. w = boxSize;
  49062. h = boxSize;
  49063. g.setColour (Colour (0xe5ffffff));
  49064. g.fillRect (x, y, w, h);
  49065. g.setColour (Colour (0x80000000));
  49066. g.drawRect (x, y, w, h);
  49067. const float size = boxSize / 2 + 1.0f;
  49068. const float centre = (float) (boxSize / 2);
  49069. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  49070. if (isPlus)
  49071. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  49072. }
  49073. void LookAndFeel::drawBubble (Graphics& g,
  49074. float tipX, float tipY,
  49075. float boxX, float boxY,
  49076. float boxW, float boxH)
  49077. {
  49078. int side = 0;
  49079. if (tipX < boxX)
  49080. side = 1;
  49081. else if (tipX > boxX + boxW)
  49082. side = 3;
  49083. else if (tipY > boxY + boxH)
  49084. side = 2;
  49085. const float indent = 2.0f;
  49086. Path p;
  49087. p.addBubble (boxX + indent,
  49088. boxY + indent,
  49089. boxW - indent * 2.0f,
  49090. boxH - indent * 2.0f,
  49091. 5.0f,
  49092. tipX, tipY,
  49093. side,
  49094. 0.5f,
  49095. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  49096. //xxx need to take comp as param for colour
  49097. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  49098. g.fillPath (p);
  49099. //xxx as above
  49100. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  49101. g.strokePath (p, PathStrokeType (1.33f));
  49102. }
  49103. const Font LookAndFeel::getPopupMenuFont()
  49104. {
  49105. return Font (17.0f);
  49106. }
  49107. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  49108. const bool isSeparator,
  49109. int standardMenuItemHeight,
  49110. int& idealWidth,
  49111. int& idealHeight)
  49112. {
  49113. if (isSeparator)
  49114. {
  49115. idealWidth = 50;
  49116. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  49117. }
  49118. else
  49119. {
  49120. Font font (getPopupMenuFont());
  49121. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  49122. font.setHeight (standardMenuItemHeight / 1.3f);
  49123. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundFloatToInt (font.getHeight() * 1.3f);
  49124. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  49125. }
  49126. }
  49127. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  49128. {
  49129. const Colour background (findColour (PopupMenu::backgroundColourId));
  49130. g.fillAll (background);
  49131. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  49132. for (int i = 0; i < height; i += 3)
  49133. g.fillRect (0, i, width, 1);
  49134. #if ! JUCE_MAC
  49135. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  49136. g.drawRect (0, 0, width, height);
  49137. #endif
  49138. }
  49139. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  49140. int width, int height,
  49141. bool isScrollUpArrow)
  49142. {
  49143. const Colour background (findColour (PopupMenu::backgroundColourId));
  49144. GradientBrush gb (background,
  49145. 0.0f, height * 0.5f,
  49146. background.withAlpha (0.0f),
  49147. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  49148. false);
  49149. g.setBrush (&gb);
  49150. g.fillRect (1, 1, width - 2, height - 2);
  49151. const float hw = width * 0.5f;
  49152. const float arrowW = height * 0.3f;
  49153. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  49154. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  49155. Path p;
  49156. p.addTriangle (hw - arrowW, y1,
  49157. hw + arrowW, y1,
  49158. hw, y2);
  49159. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  49160. g.fillPath (p);
  49161. }
  49162. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  49163. int width, int height,
  49164. const bool isSeparator,
  49165. const bool isActive,
  49166. const bool isHighlighted,
  49167. const bool isTicked,
  49168. const bool hasSubMenu,
  49169. const String& text,
  49170. const String& shortcutKeyText,
  49171. Image* image,
  49172. const Colour* const textColourToUse)
  49173. {
  49174. const float halfH = height * 0.5f;
  49175. if (isSeparator)
  49176. {
  49177. const float separatorIndent = 5.5f;
  49178. g.setColour (Colour (0x33000000));
  49179. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  49180. g.setColour (Colour (0x66ffffff));
  49181. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  49182. }
  49183. else
  49184. {
  49185. Colour textColour (findColour (PopupMenu::textColourId));
  49186. if (textColourToUse != 0)
  49187. textColour = *textColourToUse;
  49188. if (isHighlighted)
  49189. {
  49190. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  49191. g.fillRect (1, 1, width - 2, height - 2);
  49192. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  49193. }
  49194. else
  49195. {
  49196. g.setColour (textColour);
  49197. }
  49198. if (! isActive)
  49199. g.setOpacity (0.3f);
  49200. Font font (getPopupMenuFont());
  49201. if (font.getHeight() > height / 1.3f)
  49202. font.setHeight (height / 1.3f);
  49203. g.setFont (font);
  49204. const int leftBorder = (height * 5) / 4;
  49205. const int rightBorder = 4;
  49206. if (image != 0)
  49207. {
  49208. g.drawImageWithin (image,
  49209. 2, 1, leftBorder - 4, height - 2,
  49210. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  49211. }
  49212. else if (isTicked)
  49213. {
  49214. const Path tick (getTickShape (1.0f));
  49215. const float th = font.getAscent();
  49216. const float ty = halfH - th * 0.5f;
  49217. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  49218. th, true));
  49219. }
  49220. g.drawFittedText (text,
  49221. leftBorder, 0,
  49222. width - (leftBorder + rightBorder), height,
  49223. Justification::centredLeft, 1);
  49224. if (shortcutKeyText.isNotEmpty())
  49225. {
  49226. Font f2 (g.getCurrentFont());
  49227. f2.setHeight (f2.getHeight() * 0.75f);
  49228. f2.setHorizontalScale (0.95f);
  49229. g.setFont (f2);
  49230. g.drawText (shortcutKeyText,
  49231. leftBorder,
  49232. 0,
  49233. width - (leftBorder + rightBorder + 4),
  49234. height,
  49235. Justification::centredRight,
  49236. true);
  49237. }
  49238. if (hasSubMenu)
  49239. {
  49240. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  49241. const float x = width - height * 0.6f;
  49242. Path p;
  49243. p.addTriangle (x, halfH - arrowH * 0.5f,
  49244. x, halfH + arrowH * 0.5f,
  49245. x + arrowH * 0.6f, halfH);
  49246. g.fillPath (p);
  49247. }
  49248. }
  49249. }
  49250. int LookAndFeel::getMenuWindowFlags()
  49251. {
  49252. return ComponentPeer::windowHasDropShadow;
  49253. }
  49254. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  49255. bool, MenuBarComponent& menuBar)
  49256. {
  49257. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  49258. if (menuBar.isEnabled())
  49259. {
  49260. drawShinyButtonShape (g,
  49261. -4.0f, 0.0f,
  49262. width + 8.0f, (float) height,
  49263. 0.0f,
  49264. baseColour,
  49265. 0.4f,
  49266. true, true, true, true);
  49267. }
  49268. else
  49269. {
  49270. g.fillAll (baseColour);
  49271. }
  49272. }
  49273. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  49274. {
  49275. return Font (menuBar.getHeight() * 0.7f);
  49276. }
  49277. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  49278. {
  49279. return getMenuBarFont (menuBar, itemIndex, itemText)
  49280. .getStringWidth (itemText) + menuBar.getHeight();
  49281. }
  49282. void LookAndFeel::drawMenuBarItem (Graphics& g,
  49283. int width, int height,
  49284. int itemIndex,
  49285. const String& itemText,
  49286. bool isMouseOverItem,
  49287. bool isMenuOpen,
  49288. bool /*isMouseOverBar*/,
  49289. MenuBarComponent& menuBar)
  49290. {
  49291. if (! menuBar.isEnabled())
  49292. {
  49293. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  49294. .withMultipliedAlpha (0.5f));
  49295. }
  49296. else if (isMenuOpen || isMouseOverItem)
  49297. {
  49298. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  49299. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  49300. }
  49301. else
  49302. {
  49303. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  49304. }
  49305. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  49306. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  49307. }
  49308. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  49309. TextEditor& textEditor)
  49310. {
  49311. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  49312. }
  49313. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  49314. {
  49315. if (textEditor.isEnabled())
  49316. {
  49317. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  49318. {
  49319. const int border = 2;
  49320. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  49321. g.drawRect (0, 0, width, height, border);
  49322. g.setOpacity (1.0f);
  49323. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  49324. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  49325. }
  49326. else
  49327. {
  49328. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  49329. g.drawRect (0, 0, width, height);
  49330. g.setOpacity (1.0f);
  49331. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  49332. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  49333. }
  49334. }
  49335. }
  49336. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  49337. const bool isButtonDown,
  49338. int buttonX, int buttonY,
  49339. int buttonW, int buttonH,
  49340. ComboBox& box)
  49341. {
  49342. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  49343. if (box.isEnabled() && box.hasKeyboardFocus (false))
  49344. {
  49345. g.setColour (box.findColour (TextButton::buttonColourId));
  49346. g.drawRect (0, 0, width, height, 2);
  49347. }
  49348. else
  49349. {
  49350. g.setColour (box.findColour (ComboBox::outlineColourId));
  49351. g.drawRect (0, 0, width, height);
  49352. }
  49353. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  49354. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  49355. box.hasKeyboardFocus (true),
  49356. false, isButtonDown)
  49357. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  49358. drawGlassLozenge (g,
  49359. buttonX + outlineThickness, buttonY + outlineThickness,
  49360. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  49361. baseColour, outlineThickness, -1.0f,
  49362. true, true, true, true);
  49363. if (box.isEnabled())
  49364. {
  49365. const float arrowX = 0.3f;
  49366. const float arrowH = 0.2f;
  49367. Path p;
  49368. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  49369. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  49370. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  49371. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  49372. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  49373. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  49374. g.setColour (box.findColour (ComboBox::arrowColourId));
  49375. g.fillPath (p);
  49376. }
  49377. }
  49378. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  49379. {
  49380. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  49381. }
  49382. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  49383. {
  49384. return new Label (String::empty, String::empty);
  49385. }
  49386. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  49387. {
  49388. label.setBounds (1, 1,
  49389. box.getWidth() + 3 - box.getHeight(),
  49390. box.getHeight() - 2);
  49391. label.setFont (getComboBoxFont (box));
  49392. }
  49393. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  49394. {
  49395. g.fillAll (label.findColour (Label::backgroundColourId));
  49396. if (! label.isBeingEdited())
  49397. {
  49398. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  49399. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  49400. g.setFont (label.getFont());
  49401. g.drawFittedText (label.getText(),
  49402. label.getHorizontalBorderSize(),
  49403. label.getVerticalBorderSize(),
  49404. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  49405. label.getHeight() - 2 * label.getVerticalBorderSize(),
  49406. label.getJustificationType(),
  49407. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  49408. label.getMinimumHorizontalScale());
  49409. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  49410. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  49411. }
  49412. else if (label.isEnabled())
  49413. {
  49414. g.setColour (label.findColour (Label::outlineColourId));
  49415. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  49416. }
  49417. }
  49418. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  49419. int x, int y,
  49420. int width, int height,
  49421. float /*sliderPos*/,
  49422. float /*minSliderPos*/,
  49423. float /*maxSliderPos*/,
  49424. const Slider::SliderStyle /*style*/,
  49425. Slider& slider)
  49426. {
  49427. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  49428. const Colour trackColour (slider.findColour (Slider::trackColourId));
  49429. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  49430. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  49431. Path indent;
  49432. if (slider.isHorizontal())
  49433. {
  49434. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  49435. const float ih = sliderRadius;
  49436. GradientBrush gb (gradCol1, 0.0f, iy,
  49437. gradCol2, 0.0f, iy + ih, false);
  49438. g.setBrush (&gb);
  49439. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  49440. width + sliderRadius, ih,
  49441. 5.0f);
  49442. g.fillPath (indent);
  49443. }
  49444. else
  49445. {
  49446. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  49447. const float iw = sliderRadius;
  49448. GradientBrush gb (gradCol1, ix, 0.0f,
  49449. gradCol2, ix + iw, 0.0f, false);
  49450. g.setBrush (&gb);
  49451. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  49452. iw, height + sliderRadius,
  49453. 5.0f);
  49454. g.fillPath (indent);
  49455. }
  49456. g.setColour (Colour (0x4c000000));
  49457. g.strokePath (indent, PathStrokeType (0.5f));
  49458. }
  49459. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  49460. int x, int y,
  49461. int width, int height,
  49462. float sliderPos,
  49463. float minSliderPos,
  49464. float maxSliderPos,
  49465. const Slider::SliderStyle style,
  49466. Slider& slider)
  49467. {
  49468. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  49469. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  49470. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  49471. slider.isMouseOverOrDragging() && slider.isEnabled(),
  49472. slider.isMouseButtonDown() && slider.isEnabled()));
  49473. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  49474. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  49475. {
  49476. float kx, ky;
  49477. if (style == Slider::LinearVertical)
  49478. {
  49479. kx = x + width * 0.5f;
  49480. ky = sliderPos;
  49481. }
  49482. else
  49483. {
  49484. kx = sliderPos;
  49485. ky = y + height * 0.5f;
  49486. }
  49487. drawGlassSphere (g,
  49488. kx - sliderRadius,
  49489. ky - sliderRadius,
  49490. sliderRadius * 2.0f,
  49491. knobColour, outlineThickness);
  49492. }
  49493. else
  49494. {
  49495. if (style == Slider::ThreeValueVertical)
  49496. {
  49497. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  49498. sliderPos - sliderRadius,
  49499. sliderRadius * 2.0f,
  49500. knobColour, outlineThickness);
  49501. }
  49502. else if (style == Slider::ThreeValueHorizontal)
  49503. {
  49504. drawGlassSphere (g,sliderPos - sliderRadius,
  49505. y + height * 0.5f - sliderRadius,
  49506. sliderRadius * 2.0f,
  49507. knobColour, outlineThickness);
  49508. }
  49509. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  49510. {
  49511. const float sr = jmin (sliderRadius, width * 0.4f);
  49512. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  49513. minSliderPos - sliderRadius,
  49514. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  49515. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  49516. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  49517. }
  49518. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  49519. {
  49520. const float sr = jmin (sliderRadius, height * 0.4f);
  49521. drawGlassPointer (g, minSliderPos - sr,
  49522. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  49523. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  49524. drawGlassPointer (g, maxSliderPos - sliderRadius,
  49525. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  49526. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  49527. }
  49528. }
  49529. }
  49530. void LookAndFeel::drawLinearSlider (Graphics& g,
  49531. int x, int y,
  49532. int width, int height,
  49533. float sliderPos,
  49534. float minSliderPos,
  49535. float maxSliderPos,
  49536. const Slider::SliderStyle style,
  49537. Slider& slider)
  49538. {
  49539. g.fillAll (slider.findColour (Slider::backgroundColourId));
  49540. if (style == Slider::LinearBar)
  49541. {
  49542. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  49543. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  49544. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  49545. false,
  49546. isMouseOver,
  49547. isMouseOver || slider.isMouseButtonDown()));
  49548. drawShinyButtonShape (g,
  49549. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  49550. baseColour,
  49551. slider.isEnabled() ? 0.9f : 0.3f,
  49552. true, true, true, true);
  49553. }
  49554. else
  49555. {
  49556. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  49557. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  49558. }
  49559. }
  49560. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  49561. {
  49562. return jmin (7,
  49563. slider.getHeight() / 2,
  49564. slider.getWidth() / 2) + 2;
  49565. }
  49566. void LookAndFeel::drawRotarySlider (Graphics& g,
  49567. int x, int y,
  49568. int width, int height,
  49569. float sliderPos,
  49570. const float rotaryStartAngle,
  49571. const float rotaryEndAngle,
  49572. Slider& slider)
  49573. {
  49574. const float radius = jmin (width / 2, height / 2) - 2.0f;
  49575. const float centreX = x + width * 0.5f;
  49576. const float centreY = y + height * 0.5f;
  49577. const float rx = centreX - radius;
  49578. const float ry = centreY - radius;
  49579. const float rw = radius * 2.0f;
  49580. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  49581. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  49582. if (radius > 12.0f)
  49583. {
  49584. if (slider.isEnabled())
  49585. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  49586. else
  49587. g.setColour (Colour (0x80808080));
  49588. const float thickness = 0.7f;
  49589. {
  49590. Path filledArc;
  49591. filledArc.addPieSegment (rx, ry, rw, rw,
  49592. rotaryStartAngle,
  49593. angle,
  49594. thickness);
  49595. g.fillPath (filledArc);
  49596. }
  49597. if (thickness > 0)
  49598. {
  49599. const float innerRadius = radius * 0.2f;
  49600. Path p;
  49601. p.addTriangle (-innerRadius, 0.0f,
  49602. 0.0f, -radius * thickness * 1.1f,
  49603. innerRadius, 0.0f);
  49604. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  49605. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  49606. }
  49607. if (slider.isEnabled())
  49608. {
  49609. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  49610. Path outlineArc;
  49611. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  49612. outlineArc.closeSubPath();
  49613. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  49614. }
  49615. }
  49616. else
  49617. {
  49618. if (slider.isEnabled())
  49619. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  49620. else
  49621. g.setColour (Colour (0x80808080));
  49622. Path p;
  49623. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  49624. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  49625. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  49626. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  49627. }
  49628. }
  49629. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  49630. {
  49631. return new TextButton (isIncrement ? "+" : "-", String::empty);
  49632. }
  49633. class SliderLabelComp : public Label
  49634. {
  49635. public:
  49636. SliderLabelComp() : Label (String::empty, String::empty) {}
  49637. ~SliderLabelComp() {}
  49638. void mouseWheelMove (const MouseEvent&, float, float) {}
  49639. };
  49640. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  49641. {
  49642. Label* const l = new SliderLabelComp();
  49643. l->setJustificationType (Justification::centred);
  49644. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  49645. l->setColour (Label::backgroundColourId,
  49646. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  49647. : slider.findColour (Slider::textBoxBackgroundColourId));
  49648. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  49649. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  49650. l->setColour (TextEditor::backgroundColourId,
  49651. slider.findColour (Slider::textBoxBackgroundColourId)
  49652. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  49653. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  49654. return l;
  49655. }
  49656. ImageEffectFilter* LookAndFeel::getSliderEffect()
  49657. {
  49658. return 0;
  49659. }
  49660. static const TextLayout layoutTooltipText (const String& text) throw()
  49661. {
  49662. const float tooltipFontSize = 12.0f;
  49663. const int maxToolTipWidth = 400;
  49664. const Font f (tooltipFontSize, Font::bold);
  49665. TextLayout tl (text, f);
  49666. tl.layout (maxToolTipWidth, Justification::left, true);
  49667. return tl;
  49668. }
  49669. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  49670. {
  49671. const TextLayout tl (layoutTooltipText (tipText));
  49672. width = tl.getWidth() + 14;
  49673. height = tl.getHeight() + 6;
  49674. }
  49675. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  49676. {
  49677. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  49678. const Colour textCol (findColour (TooltipWindow::textColourId));
  49679. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  49680. g.setColour (findColour (TooltipWindow::outlineColourId));
  49681. g.drawRect (0, 0, width, height, 1);
  49682. #endif
  49683. const TextLayout tl (layoutTooltipText (text));
  49684. g.setColour (findColour (TooltipWindow::textColourId));
  49685. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  49686. }
  49687. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  49688. {
  49689. return new TextButton (text, TRANS("click to browse for a different file"));
  49690. }
  49691. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  49692. ComboBox* filenameBox,
  49693. Button* browseButton)
  49694. {
  49695. browseButton->setSize (80, filenameComp.getHeight());
  49696. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  49697. if (tb != 0)
  49698. tb->changeWidthToFitText();
  49699. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  49700. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  49701. }
  49702. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  49703. int imageX, int imageY, int imageW, int imageH,
  49704. const Colour& overlayColour,
  49705. float imageOpacity,
  49706. ImageButton& button)
  49707. {
  49708. if (! button.isEnabled())
  49709. imageOpacity *= 0.3f;
  49710. if (! overlayColour.isOpaque())
  49711. {
  49712. g.setOpacity (imageOpacity);
  49713. g.drawImage (image, imageX, imageY, imageW, imageH,
  49714. 0, 0, image->getWidth(), image->getHeight(), false);
  49715. }
  49716. if (! overlayColour.isTransparent())
  49717. {
  49718. g.setColour (overlayColour);
  49719. g.drawImage (image, imageX, imageY, imageW, imageH,
  49720. 0, 0, image->getWidth(), image->getHeight(), true);
  49721. }
  49722. }
  49723. void LookAndFeel::drawCornerResizer (Graphics& g,
  49724. int w, int h,
  49725. bool /*isMouseOver*/,
  49726. bool /*isMouseDragging*/)
  49727. {
  49728. const float lineThickness = jmin (w, h) * 0.075f;
  49729. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  49730. {
  49731. g.setColour (Colours::lightgrey);
  49732. g.drawLine (w * i,
  49733. h + 1.0f,
  49734. w + 1.0f,
  49735. h * i,
  49736. lineThickness);
  49737. g.setColour (Colours::darkgrey);
  49738. g.drawLine (w * i + lineThickness,
  49739. h + 1.0f,
  49740. w + 1.0f,
  49741. h * i + lineThickness,
  49742. lineThickness);
  49743. }
  49744. }
  49745. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  49746. const BorderSize& /*borders*/)
  49747. {
  49748. }
  49749. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  49750. const BorderSize& /*border*/, ResizableWindow& window)
  49751. {
  49752. g.fillAll (window.getBackgroundColour());
  49753. }
  49754. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  49755. const BorderSize& border, ResizableWindow&)
  49756. {
  49757. g.setColour (Colour (0x80000000));
  49758. g.drawRect (0, 0, w, h);
  49759. g.setColour (Colour (0x19000000));
  49760. g.drawRect (border.getLeft() - 1,
  49761. border.getTop() - 1,
  49762. w + 2 - border.getLeftAndRight(),
  49763. h + 2 - border.getTopAndBottom());
  49764. }
  49765. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  49766. Graphics& g, int w, int h,
  49767. int titleSpaceX, int titleSpaceW,
  49768. const Image* icon,
  49769. bool drawTitleTextOnLeft)
  49770. {
  49771. const bool isActive = window.isActiveWindow();
  49772. GradientBrush gb (window.getBackgroundColour(),
  49773. 0.0f, 0.0f,
  49774. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  49775. 0.0f, (float) h, false);
  49776. g.setBrush (&gb);
  49777. g.fillAll();
  49778. g.setFont (h * 0.65f, Font::bold);
  49779. int textW = g.getCurrentFont().getStringWidth (window.getName());
  49780. int iconW = 0;
  49781. int iconH = 0;
  49782. if (icon != 0)
  49783. {
  49784. iconH = (int) g.getCurrentFont().getHeight();
  49785. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  49786. }
  49787. textW = jmin (titleSpaceW, textW + iconW);
  49788. int textX = drawTitleTextOnLeft ? titleSpaceX
  49789. : jmax (titleSpaceX, (w - textW) / 2);
  49790. if (textX + textW > titleSpaceX + titleSpaceW)
  49791. textX = titleSpaceX + titleSpaceW - textW;
  49792. if (icon != 0)
  49793. {
  49794. g.setOpacity (isActive ? 1.0f : 0.6f);
  49795. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  49796. RectanglePlacement::centred, false);
  49797. textX += iconW;
  49798. textW -= iconW;
  49799. }
  49800. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  49801. g.setColour (findColour (DocumentWindow::textColourId));
  49802. else
  49803. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  49804. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  49805. }
  49806. class GlassWindowButton : public Button
  49807. {
  49808. public:
  49809. GlassWindowButton (const String& name, const Colour& col,
  49810. const Path& normalShape_,
  49811. const Path& toggledShape_) throw()
  49812. : Button (name),
  49813. colour (col),
  49814. normalShape (normalShape_),
  49815. toggledShape (toggledShape_)
  49816. {
  49817. }
  49818. ~GlassWindowButton()
  49819. {
  49820. }
  49821. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  49822. {
  49823. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  49824. if (! isEnabled())
  49825. alpha *= 0.5f;
  49826. float x = 0, y = 0, diam;
  49827. if (getWidth() < getHeight())
  49828. {
  49829. diam = (float) getWidth();
  49830. y = (getHeight() - getWidth()) * 0.5f;
  49831. }
  49832. else
  49833. {
  49834. diam = (float) getHeight();
  49835. y = (getWidth() - getHeight()) * 0.5f;
  49836. }
  49837. x += diam * 0.05f;
  49838. y += diam * 0.05f;
  49839. diam *= 0.9f;
  49840. GradientBrush gb1 (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  49841. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false);
  49842. g.setBrush (&gb1);
  49843. g.fillEllipse (x, y, diam, diam);
  49844. x += 2.0f;
  49845. y += 2.0f;
  49846. diam -= 4.0f;
  49847. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  49848. Path& p = getToggleState() ? toggledShape : normalShape;
  49849. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  49850. diam * 0.4f, diam * 0.4f, true));
  49851. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  49852. g.fillPath (p, t);
  49853. }
  49854. juce_UseDebuggingNewOperator
  49855. private:
  49856. Colour colour;
  49857. Path normalShape, toggledShape;
  49858. GlassWindowButton (const GlassWindowButton&);
  49859. const GlassWindowButton& operator= (const GlassWindowButton&);
  49860. };
  49861. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  49862. {
  49863. Path shape;
  49864. const float crossThickness = 0.25f;
  49865. if (buttonType == DocumentWindow::closeButton)
  49866. {
  49867. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  49868. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  49869. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  49870. }
  49871. else if (buttonType == DocumentWindow::minimiseButton)
  49872. {
  49873. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  49874. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  49875. }
  49876. else if (buttonType == DocumentWindow::maximiseButton)
  49877. {
  49878. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  49879. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  49880. Path fullscreenShape;
  49881. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  49882. fullscreenShape.lineTo (0.0f, 100.0f);
  49883. fullscreenShape.lineTo (0.0f, 0.0f);
  49884. fullscreenShape.lineTo (100.0f, 0.0f);
  49885. fullscreenShape.lineTo (100.0f, 45.0f);
  49886. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  49887. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  49888. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  49889. }
  49890. jassertfalse
  49891. return 0;
  49892. }
  49893. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  49894. int titleBarX,
  49895. int titleBarY,
  49896. int titleBarW,
  49897. int titleBarH,
  49898. Button* minimiseButton,
  49899. Button* maximiseButton,
  49900. Button* closeButton,
  49901. bool positionTitleBarButtonsOnLeft)
  49902. {
  49903. const int buttonW = titleBarH - titleBarH / 8;
  49904. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  49905. : titleBarX + titleBarW - buttonW - buttonW / 4;
  49906. if (closeButton != 0)
  49907. {
  49908. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  49909. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  49910. }
  49911. if (positionTitleBarButtonsOnLeft)
  49912. swapVariables (minimiseButton, maximiseButton);
  49913. if (maximiseButton != 0)
  49914. {
  49915. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  49916. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  49917. }
  49918. if (minimiseButton != 0)
  49919. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  49920. }
  49921. int LookAndFeel::getDefaultMenuBarHeight()
  49922. {
  49923. return 24;
  49924. }
  49925. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  49926. {
  49927. return new DropShadower (0.4f, 1, 5, 10);
  49928. }
  49929. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  49930. int w, int h,
  49931. bool /*isVerticalBar*/,
  49932. bool isMouseOver,
  49933. bool isMouseDragging)
  49934. {
  49935. float alpha = 0.5f;
  49936. if (isMouseOver || isMouseDragging)
  49937. {
  49938. g.fillAll (Colour (0x190000ff));
  49939. alpha = 1.0f;
  49940. }
  49941. const float cx = w * 0.5f;
  49942. const float cy = h * 0.5f;
  49943. const float cr = jmin (w, h) * 0.4f;
  49944. GradientBrush gb (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  49945. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  49946. true);
  49947. g.setBrush (&gb);
  49948. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  49949. }
  49950. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  49951. const String& text,
  49952. const Justification& position,
  49953. GroupComponent& group)
  49954. {
  49955. const float textH = 15.0f;
  49956. const float indent = 3.0f;
  49957. const float textEdgeGap = 4.0f;
  49958. float cs = 5.0f;
  49959. Font f (textH);
  49960. Path p;
  49961. float x = indent;
  49962. float y = f.getAscent() - 3.0f;
  49963. float w = jmax (0.0f, width - x * 2.0f);
  49964. float h = jmax (0.0f, height - y - indent);
  49965. cs = jmin (cs, w * 0.5f, h * 0.5f);
  49966. const float cs2 = 2.0f * cs;
  49967. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  49968. float textX = cs + textEdgeGap;
  49969. if (position.testFlags (Justification::horizontallyCentred))
  49970. textX = cs + (w - cs2 - textW) * 0.5f;
  49971. else if (position.testFlags (Justification::right))
  49972. textX = w - cs - textW - textEdgeGap;
  49973. p.startNewSubPath (x + textX + textW, y);
  49974. p.lineTo (x + w - cs, y);
  49975. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  49976. p.lineTo (x + w, y + h - cs);
  49977. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  49978. p.lineTo (x + cs, y + h);
  49979. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  49980. p.lineTo (x, y + cs);
  49981. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  49982. p.lineTo (x + textX, y);
  49983. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  49984. g.setColour (group.findColour (GroupComponent::outlineColourId)
  49985. .withMultipliedAlpha (alpha));
  49986. g.strokePath (p, PathStrokeType (2.0f));
  49987. g.setColour (group.findColour (GroupComponent::textColourId)
  49988. .withMultipliedAlpha (alpha));
  49989. g.setFont (f);
  49990. g.drawText (text,
  49991. roundFloatToInt (x + textX), 0,
  49992. roundFloatToInt (textW),
  49993. roundFloatToInt (textH),
  49994. Justification::centred, true);
  49995. }
  49996. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  49997. {
  49998. return 1 + tabDepth / 3;
  49999. }
  50000. int LookAndFeel::getTabButtonSpaceAroundImage()
  50001. {
  50002. return 4;
  50003. }
  50004. void LookAndFeel::createTabButtonShape (Path& p,
  50005. int width, int height,
  50006. int /*tabIndex*/,
  50007. const String& /*text*/,
  50008. Button& /*button*/,
  50009. TabbedButtonBar::Orientation orientation,
  50010. const bool /*isMouseOver*/,
  50011. const bool /*isMouseDown*/,
  50012. const bool /*isFrontTab*/)
  50013. {
  50014. const float w = (float) width;
  50015. const float h = (float) height;
  50016. float length = w;
  50017. float depth = h;
  50018. if (orientation == TabbedButtonBar::TabsAtLeft
  50019. || orientation == TabbedButtonBar::TabsAtRight)
  50020. {
  50021. swapVariables (length, depth);
  50022. }
  50023. const float indent = (float) getTabButtonOverlap ((int) depth);
  50024. const float overhang = 4.0f;
  50025. if (orientation == TabbedButtonBar::TabsAtLeft)
  50026. {
  50027. p.startNewSubPath (w, 0.0f);
  50028. p.lineTo (0.0f, indent);
  50029. p.lineTo (0.0f, h - indent);
  50030. p.lineTo (w, h);
  50031. p.lineTo (w + overhang, h + overhang);
  50032. p.lineTo (w + overhang, -overhang);
  50033. }
  50034. else if (orientation == TabbedButtonBar::TabsAtRight)
  50035. {
  50036. p.startNewSubPath (0.0f, 0.0f);
  50037. p.lineTo (w, indent);
  50038. p.lineTo (w, h - indent);
  50039. p.lineTo (0.0f, h);
  50040. p.lineTo (-overhang, h + overhang);
  50041. p.lineTo (-overhang, -overhang);
  50042. }
  50043. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50044. {
  50045. p.startNewSubPath (0.0f, 0.0f);
  50046. p.lineTo (indent, h);
  50047. p.lineTo (w - indent, h);
  50048. p.lineTo (w, 0.0f);
  50049. p.lineTo (w + overhang, -overhang);
  50050. p.lineTo (-overhang, -overhang);
  50051. }
  50052. else
  50053. {
  50054. p.startNewSubPath (0.0f, h);
  50055. p.lineTo (indent, 0.0f);
  50056. p.lineTo (w - indent, 0.0f);
  50057. p.lineTo (w, h);
  50058. p.lineTo (w + overhang, h + overhang);
  50059. p.lineTo (-overhang, h + overhang);
  50060. }
  50061. p.closeSubPath();
  50062. p = p.createPathWithRoundedCorners (3.0f);
  50063. }
  50064. void LookAndFeel::fillTabButtonShape (Graphics& g,
  50065. const Path& path,
  50066. const Colour& preferredColour,
  50067. int /*tabIndex*/,
  50068. const String& /*text*/,
  50069. Button& button,
  50070. TabbedButtonBar::Orientation /*orientation*/,
  50071. const bool /*isMouseOver*/,
  50072. const bool /*isMouseDown*/,
  50073. const bool isFrontTab)
  50074. {
  50075. g.setColour (isFrontTab ? preferredColour
  50076. : preferredColour.withMultipliedAlpha (0.9f));
  50077. g.fillPath (path);
  50078. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  50079. : TabbedButtonBar::tabOutlineColourId, false)
  50080. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  50081. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  50082. }
  50083. void LookAndFeel::drawTabButtonText (Graphics& g,
  50084. int x, int y, int w, int h,
  50085. const Colour& preferredBackgroundColour,
  50086. int /*tabIndex*/,
  50087. const String& text,
  50088. Button& button,
  50089. TabbedButtonBar::Orientation orientation,
  50090. const bool isMouseOver,
  50091. const bool isMouseDown,
  50092. const bool isFrontTab)
  50093. {
  50094. int length = w;
  50095. int depth = h;
  50096. if (orientation == TabbedButtonBar::TabsAtLeft
  50097. || orientation == TabbedButtonBar::TabsAtRight)
  50098. {
  50099. swapVariables (length, depth);
  50100. }
  50101. Font font (depth * 0.6f);
  50102. font.setUnderline (button.hasKeyboardFocus (false));
  50103. GlyphArrangement textLayout;
  50104. textLayout.addFittedText (font, text.trim(),
  50105. 0.0f, 0.0f, (float) length, (float) depth,
  50106. Justification::centred,
  50107. jmax (1, depth / 12));
  50108. AffineTransform transform;
  50109. if (orientation == TabbedButtonBar::TabsAtLeft)
  50110. {
  50111. transform = transform.rotated (float_Pi * -0.5f)
  50112. .translated ((float) x, (float) (y + h));
  50113. }
  50114. else if (orientation == TabbedButtonBar::TabsAtRight)
  50115. {
  50116. transform = transform.rotated (float_Pi * 0.5f)
  50117. .translated ((float) (x + w), (float) y);
  50118. }
  50119. else
  50120. {
  50121. transform = transform.translated ((float) x, (float) y);
  50122. }
  50123. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  50124. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  50125. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  50126. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  50127. else
  50128. g.setColour (preferredBackgroundColour.contrasting());
  50129. if (! (isMouseOver || isMouseDown))
  50130. g.setOpacity (0.8f);
  50131. if (! button.isEnabled())
  50132. g.setOpacity (0.3f);
  50133. textLayout.draw (g, transform);
  50134. }
  50135. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  50136. const String& text,
  50137. int tabDepth,
  50138. Button&)
  50139. {
  50140. Font f (tabDepth * 0.6f);
  50141. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  50142. }
  50143. void LookAndFeel::drawTabButton (Graphics& g,
  50144. int w, int h,
  50145. const Colour& preferredColour,
  50146. int tabIndex,
  50147. const String& text,
  50148. Button& button,
  50149. TabbedButtonBar::Orientation orientation,
  50150. const bool isMouseOver,
  50151. const bool isMouseDown,
  50152. const bool isFrontTab)
  50153. {
  50154. int length = w;
  50155. int depth = h;
  50156. if (orientation == TabbedButtonBar::TabsAtLeft
  50157. || orientation == TabbedButtonBar::TabsAtRight)
  50158. {
  50159. swapVariables (length, depth);
  50160. }
  50161. Path tabShape;
  50162. createTabButtonShape (tabShape, w, h,
  50163. tabIndex, text, button, orientation,
  50164. isMouseOver, isMouseDown, isFrontTab);
  50165. fillTabButtonShape (g, tabShape, preferredColour,
  50166. tabIndex, text, button, orientation,
  50167. isMouseOver, isMouseDown, isFrontTab);
  50168. const int indent = getTabButtonOverlap (depth);
  50169. int x = 0, y = 0;
  50170. if (orientation == TabbedButtonBar::TabsAtLeft
  50171. || orientation == TabbedButtonBar::TabsAtRight)
  50172. {
  50173. y += indent;
  50174. h -= indent * 2;
  50175. }
  50176. else
  50177. {
  50178. x += indent;
  50179. w -= indent * 2;
  50180. }
  50181. drawTabButtonText (g, x, y, w, h, preferredColour,
  50182. tabIndex, text, button, orientation,
  50183. isMouseOver, isMouseDown, isFrontTab);
  50184. }
  50185. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  50186. int w, int h,
  50187. TabbedButtonBar& tabBar,
  50188. TabbedButtonBar::Orientation orientation)
  50189. {
  50190. const float shadowSize = 0.2f;
  50191. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  50192. Rectangle shadowRect;
  50193. if (orientation == TabbedButtonBar::TabsAtLeft)
  50194. {
  50195. x1 = (float) w;
  50196. x2 = w * (1.0f - shadowSize);
  50197. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  50198. }
  50199. else if (orientation == TabbedButtonBar::TabsAtRight)
  50200. {
  50201. x2 = w * shadowSize;
  50202. shadowRect.setBounds (0, 0, (int) x2, h);
  50203. }
  50204. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50205. {
  50206. y2 = h * shadowSize;
  50207. shadowRect.setBounds (0, 0, w, (int) y2);
  50208. }
  50209. else
  50210. {
  50211. y1 = (float) h;
  50212. y2 = h * (1.0f - shadowSize);
  50213. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  50214. }
  50215. GradientBrush gb (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  50216. Colours::transparentBlack, x2, y2,
  50217. false);
  50218. g.setBrush (&gb);
  50219. shadowRect.expand (2, 2);
  50220. g.fillRect (shadowRect);
  50221. g.setColour (Colour (0x80000000));
  50222. if (orientation == TabbedButtonBar::TabsAtLeft)
  50223. {
  50224. g.fillRect (w - 1, 0, 1, h);
  50225. }
  50226. else if (orientation == TabbedButtonBar::TabsAtRight)
  50227. {
  50228. g.fillRect (0, 0, 1, h);
  50229. }
  50230. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50231. {
  50232. g.fillRect (0, 0, w, 1);
  50233. }
  50234. else
  50235. {
  50236. g.fillRect (0, h - 1, w, 1);
  50237. }
  50238. }
  50239. Button* LookAndFeel::createTabBarExtrasButton()
  50240. {
  50241. const float thickness = 7.0f;
  50242. const float indent = 22.0f;
  50243. Path p;
  50244. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  50245. DrawablePath ellipse;
  50246. ellipse.setPath (p);
  50247. ellipse.setSolidFill (Colour (0x99ffffff));
  50248. p.clear();
  50249. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  50250. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  50251. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  50252. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  50253. p.setUsingNonZeroWinding (false);
  50254. DrawablePath dp;
  50255. dp.setPath (p);
  50256. dp.setSolidFill (Colour (0x59000000));
  50257. DrawableComposite normalImage;
  50258. normalImage.insertDrawable (ellipse);
  50259. normalImage.insertDrawable (dp);
  50260. dp.setSolidFill (Colour (0xcc000000));
  50261. DrawableComposite overImage;
  50262. overImage.insertDrawable (ellipse);
  50263. overImage.insertDrawable (dp);
  50264. DrawableButton* db = new DrawableButton (T("tabs"), DrawableButton::ImageFitted);
  50265. db->setImages (&normalImage, &overImage, 0);
  50266. return db;
  50267. }
  50268. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  50269. {
  50270. g.fillAll (Colours::white);
  50271. const int w = header.getWidth();
  50272. const int h = header.getHeight();
  50273. GradientBrush gb (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  50274. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  50275. false);
  50276. g.setBrush (&gb);
  50277. g.fillRect (0, h / 2, w, h);
  50278. g.setColour (Colour (0x33000000));
  50279. g.fillRect (0, h - 1, w, 1);
  50280. for (int i = header.getNumColumns (true); --i >= 0;)
  50281. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  50282. }
  50283. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  50284. int width, int height,
  50285. bool isMouseOver, bool isMouseDown,
  50286. int columnFlags)
  50287. {
  50288. if (isMouseDown)
  50289. g.fillAll (Colour (0x8899aadd));
  50290. else if (isMouseOver)
  50291. g.fillAll (Colour (0x5599aadd));
  50292. int rightOfText = width - 4;
  50293. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  50294. {
  50295. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  50296. const float bottom = height - top;
  50297. const float w = height * 0.5f;
  50298. const float x = rightOfText - (w * 1.25f);
  50299. rightOfText = (int) x;
  50300. Path sortArrow;
  50301. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  50302. g.setColour (Colour (0x99000000));
  50303. g.fillPath (sortArrow);
  50304. }
  50305. g.setColour (Colours::black);
  50306. g.setFont (height * 0.5f, Font::bold);
  50307. const int textX = 4;
  50308. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  50309. }
  50310. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  50311. {
  50312. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  50313. GradientBrush gb (background, 0.0f, 0.0f,
  50314. background.darker (0.1f),
  50315. toolbar.isVertical() ? w - 1.0f : 0.0f,
  50316. toolbar.isVertical() ? 0.0f : h - 1.0f,
  50317. false);
  50318. g.setBrush (&gb);
  50319. g.fillAll();
  50320. }
  50321. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  50322. {
  50323. return createTabBarExtrasButton();
  50324. }
  50325. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  50326. bool isMouseOver, bool isMouseDown,
  50327. ToolbarItemComponent& component)
  50328. {
  50329. if (isMouseDown)
  50330. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  50331. else if (isMouseOver)
  50332. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  50333. }
  50334. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  50335. const String& text, ToolbarItemComponent& component)
  50336. {
  50337. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  50338. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  50339. const float fontHeight = jmin (14.0f, height * 0.85f);
  50340. g.setFont (fontHeight);
  50341. g.drawFittedText (text,
  50342. x, y, width, height,
  50343. Justification::centred,
  50344. jmax (1, height / (int) fontHeight));
  50345. }
  50346. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  50347. bool isOpen, int width, int height)
  50348. {
  50349. const int buttonSize = (height * 3) / 4;
  50350. const int buttonIndent = (height - buttonSize) / 2;
  50351. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen);
  50352. const int textX = buttonIndent * 2 + buttonSize + 2;
  50353. g.setColour (Colours::black);
  50354. g.setFont (height * 0.7f, Font::bold);
  50355. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  50356. }
  50357. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  50358. PropertyComponent&)
  50359. {
  50360. g.setColour (Colour (0x66ffffff));
  50361. g.fillRect (0, 0, width, height - 1);
  50362. }
  50363. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  50364. PropertyComponent& component)
  50365. {
  50366. g.setColour (Colours::black);
  50367. if (! component.isEnabled())
  50368. g.setOpacity (g.getCurrentColour().getFloatAlpha() * 0.6f);
  50369. g.setFont (jmin (height, 24) * 0.65f);
  50370. const Rectangle r (getPropertyComponentContentPosition (component));
  50371. g.drawFittedText (component.getName(),
  50372. 3, r.getY(), r.getX() - 5, r.getHeight(),
  50373. Justification::centredLeft, 2);
  50374. }
  50375. const Rectangle LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  50376. {
  50377. return Rectangle (component.getWidth() / 3, 1,
  50378. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  50379. }
  50380. void LookAndFeel::createFileChooserHeaderText (const String& title,
  50381. const String& instructions,
  50382. GlyphArrangement& text,
  50383. int width)
  50384. {
  50385. text.clear();
  50386. text.addJustifiedText (Font (17.0f, Font::bold), title,
  50387. 8.0f, 22.0f, width - 16.0f,
  50388. Justification::centred);
  50389. text.addJustifiedText (Font (14.0f), instructions,
  50390. 8.0f, 24.0f + 16.0f, width - 16.0f,
  50391. Justification::centred);
  50392. }
  50393. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  50394. const String& filename, Image* icon,
  50395. const String& fileSizeDescription,
  50396. const String& fileTimeDescription,
  50397. const bool isDirectory,
  50398. const bool isItemSelected,
  50399. const int /*itemIndex*/)
  50400. {
  50401. if (isItemSelected)
  50402. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  50403. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  50404. g.setFont (height * 0.7f);
  50405. Image* im = icon;
  50406. Image* toRelease = 0;
  50407. if (im == 0)
  50408. {
  50409. toRelease = im = (isDirectory ? getDefaultFolderImage()
  50410. : getDefaultDocumentFileImage());
  50411. }
  50412. const int x = 32;
  50413. if (im != 0)
  50414. {
  50415. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  50416. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  50417. false);
  50418. ImageCache::release (toRelease);
  50419. }
  50420. if (width > 450 && ! isDirectory)
  50421. {
  50422. const int sizeX = roundFloatToInt (width * 0.7f);
  50423. const int dateX = roundFloatToInt (width * 0.8f);
  50424. g.drawFittedText (filename,
  50425. x, 0, sizeX - x, height,
  50426. Justification::centredLeft, 1);
  50427. g.setFont (height * 0.5f);
  50428. g.setColour (Colours::darkgrey);
  50429. if (! isDirectory)
  50430. {
  50431. g.drawFittedText (fileSizeDescription,
  50432. sizeX, 0, dateX - sizeX - 8, height,
  50433. Justification::centredRight, 1);
  50434. g.drawFittedText (fileTimeDescription,
  50435. dateX, 0, width - 8 - dateX, height,
  50436. Justification::centredRight, 1);
  50437. }
  50438. }
  50439. else
  50440. {
  50441. g.drawFittedText (filename,
  50442. x, 0, width - x, height,
  50443. Justification::centredLeft, 1);
  50444. }
  50445. }
  50446. Button* LookAndFeel::createFileBrowserGoUpButton()
  50447. {
  50448. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  50449. Path arrowPath;
  50450. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  50451. DrawablePath arrowImage;
  50452. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  50453. arrowImage.setPath (arrowPath);
  50454. goUpButton->setImages (&arrowImage);
  50455. return goUpButton;
  50456. }
  50457. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  50458. DirectoryContentsDisplayComponent* fileListComponent,
  50459. FilePreviewComponent* previewComp,
  50460. ComboBox* currentPathBox,
  50461. TextEditor* filenameBox,
  50462. Button* goUpButton)
  50463. {
  50464. const int x = 8;
  50465. int w = browserComp.getWidth() - x - x;
  50466. if (previewComp != 0)
  50467. {
  50468. const int previewWidth = w / 3;
  50469. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  50470. w -= previewWidth + 4;
  50471. }
  50472. int y = 4;
  50473. const int controlsHeight = 22;
  50474. const int bottomSectionHeight = controlsHeight + 8;
  50475. const int upButtonWidth = 50;
  50476. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  50477. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  50478. y += controlsHeight + 4;
  50479. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  50480. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  50481. y = listAsComp->getBottom() + 4;
  50482. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  50483. }
  50484. Image* LookAndFeel::getDefaultFolderImage()
  50485. {
  50486. static const unsigned char foldericon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,28,8,6,0,0,0,0,194,189,34,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  50487. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,9,46,73,68,65,84,120,218,98,252,255,255,63,3,50,240,41,95,192,
  50488. 197,205,198,32,202,204,202,33,241,254,235,47,133,47,191,24,180,213,164,133,152,69,24,222,44,234,42,77,188,245,31,170,129,145,145,145,1,29,128,164,226,91,86,113,252,248,207,200,171,37,39,204,239,170,43,
  50489. 254,206,218,88,231,61,62,61,0,1,196,2,149,96,116,200,158,102,194,202,201,227,197,193,206,166,194,204,193,33,195,202,204,38,42,197,197,42,196,193,202,33,240,241,231,15,134,151,95,127,9,2,149,22,0,241,47,
  50490. 152,230,128,134,245,204,63,191,188,103,83,144,16,16,228,229,102,151,76,239,217,32,199,204,198,169,205,254,159,65,245,203,79,6,169,131,151,30,47,1,42,91,10,196,127,208,236,101,76,235,90,43,101,160,40,242,
  50491. 19,32,128,64,78,98,52,12,41,149,145,215,52,89,162,38,35,107,39,196,203,203,192,206,194,206,192,197,198,202,192,203,197,198,192,205,193,206,240,252,227,103,134,139,55,175,191,127,243,242,78,219,187,207,
  50492. 63,215,255,98,23,48,228,227,96,83,98,102,102,85,225,224,228,80,20,224,230,86,226,225,228,150,103,101,97,101,230,227,228,96,224,0,234,191,243,252,5,195,222,19,199,38,191,127,112,161,83,66,199,86,141,131,
  50493. 149,69,146,133,153,69,137,149,133,89,157,141,131,77,83,140,143,243,219,255,31,159,123,0,2,136,69,90,207,129,157,71,68,42,66,71,73,209,210,81,91,27,24,142,140,12,127,255,253,103,0,185,236,31,3,144,6,50,
  50494. 148,68,216,25,216,24,117,4,239,11,243,214,49,50,51,84,178,48,114,240,112,177,114,177,240,115,113,49,241,112,112,48,176,179,178,51,176,48,49,3,85,255,99,248,253,247,15,195,247,159,191,25,30,191,126,253,
  50495. 71,74,76,200,66,75,197,119,138,168,144,160,150,168,0,183,160,152,32,15,175,188,184,32,199,175,191,127,25,214,31,184,120,247,236,209,253,159,0,2,136,133,95,70,93,74,88,80,196,83,69,66,130,149,9,104,219,
  50496. 151,31,191,193,150,194,146,6,136,102,102,98,100,16,227,231,103,16,23,210,230,101,101,102,100,248,255,143,137,225,223,63,6,6,22,102,38,134,239,191,126,49,220,123,241,134,225,227,247,175,64,7,252,101,96,
  50497. 97,249,207,192,193,198,200,160,171,34,192,108,165,235,104,42,204,207,101,42,194,199,197,192,199,201,198,192,197,193,202,192,198,202,194,176,247,194,3,134,155,183,110,61,188,127,124,221,19,128,0,92,146,
  50498. 49,14,64,64,16,69,63,153,85,16,52,18,74,71,112,6,87,119,0,165,160,86,138,32,172,216,29,49,182,84,253,169,94,94,230,127,17,87,133,34,146,174,3,88,126,240,219,164,147,113,31,145,244,152,112,179,211,130,
  50499. 34,31,203,113,162,233,6,36,49,163,174,74,124,140,60,141,144,165,161,220,228,25,3,24,105,255,17,168,101,1,139,245,188,93,104,251,73,239,235,50,90,189,111,175,0,98,249,254,254,249,175,239,223,190,126,6,
  50500. 5,27,19,47,90,170,102,0,249,158,129,129,141,133,25,228,20,6,38,38,72,74,7,185,243,243,247,239,12,23,31,60,98,228,231,253,207,144,227,107,206,32,202,199,193,240,249,251,127,134,95,191,255,49,124,249,250,
  50501. 159,225,237,239,95,12,63,127,1,35,229,31,194,71,32,71,63,123,251,245,223,197,27,183,159,189,187,178,103,61,80,232,59,64,0,177,48,252,5,134,225,255,191,223,126,254,250,13,182,132,1,41,167,176,3,53,128,
  50502. 188,254,226,253,103,96,212,252,96,120,247,249,203,255,79,223,191,254,255,250,235,199,191,239,63,191,255,87,145,17,100,73,116,181,100,252,249,243,63,195,149,123,223,193,14,132,101,55,96,52,3,125,255,15,
  50503. 204,254,15,132,160,232,253,13,20,124,248,226,227,223,23,207,30,221,120,119,255,226,109,160,210,31,0,1,196,242,231,219,135,175,140,255,126,190,7,197,37,35,19,34,216,65,248,211,143,111,255,79,223,121,240,
  50504. 255,211,183,79,76,220,156,172,12,236,204,140,140,252,124,28,140,250,226,82,140,106,82,34,140,124,156,156,12,175,222,253,1,90,4,137,162,63,127,33,161,6,178,242,215,239,255,224,160,255,15,198,12,64,7,48,
  50505. 128,211,200,253,151,111,254,254,248,240,236,44,80,217,71,80,246,4,8,32,160,31,255,255,100,102,248,243,238,199,159,63,16,221,16,19,128,248,31,195,181,199,207,254,255,253,247,133,49,212,78,27,104,8,11,40,
  50506. 94,25,184,216,89,129,108,38,70,144,242,183,31,17,105,230,63,148,248,15,97,49,252,248,249,15,20,85,72,105,9,148,187,254,49,220,127,254,242,207,243,75,135,14,128,130,31,84,64,1,4,16,203,247,143,175,127,
  50507. 48,253,254,246,234,7,48,206,96,137,13,4,64,65,248,234,195,7,6,7,3,57,70,33,46,97,134,111,63,254,50,252,5,250,244,51,216,103,255,192,185,0,150,91,80,44,135,242,127,253,129,164,23,24,96,102,250,207,112,
  50508. 255,213,219,255,247,31,63,188,251,246,201,173,199,176,2,13,32,128,88,62,188,121,241,243,211,231,207,31,126,2,147,236,63,168,6,144,193,223,190,255,254,207,198,198,192,40,35,44,206,240,252,205,79,6,132,
  50509. 223,24,224,150,32,251,28,25,128,211,29,19,170,24,51,48,88,111,61,127,206,248,254,245,179,139,192,18,247,219,239,239,95,192,249,9,32,128,88,126,124,249,248,231,203,183,111,159,128,33,240,15,24,68,160,180,
  50510. 2,204,223,140,12,111,63,127,102,16,228,229,4,6,53,35,195,31,176,119,25,112,3,70,84,55,0,203,50,112,33,134,108,249,103,160,7,159,189,126,253,235,235,227,203,7,255,255,251,247,13,86,63,0,4,16,168,46,248,
  50511. 199,250,231,243,235,159,191,126,254,248,245,251,47,23,11,51,51,48,184,152,24,94,127,250,248,95,68,136,151,241,243,55,96,208,51,160,218,255,31,139,27,144,197,254,98,201,202,79,223,124,96,120,245,232,250,
  50512. 185,119,143,174,95,250,243,243,219,119,152,60,64,0,129,2,234,223,183,215,15,95,48,254,255,253,3,146,109,192,229,5,195,135,47,159,25,248,184,121,24,126,0,227,29,88,240,49,252,101,36,14,255,1,90,249,7,156,
  50513. 222,17,24,24,164,12,207,223,189,99,248,250,252,230,97,96,229,245,2,104,231,111,152,3,0,2,8,228,128,191,15,239,220,120,255,255,223,159,47,160,116,0,42,44,222,124,250,244,239,207,255,63,12,236,108,236,64,
  50514. 67,65,81,0,52,244,63,113,248,47,52,10,96,14,98,2,230,191,119,223,127,48,60,121,254,248,235,151,55,207,46,1,163,252,35,114,128,1,4,16,40,10,254,191,121,249,252,199,175,159,63,191,254,2,230,45,118,22,22,
  50515. 134,219,207,94,252,231,224,100,103,250,247,15,148,32,64,85,12,34,14,254,227,72,6,255,225,9,240,63,138,26,46,96,214,189,249,244,37,195,139,167,143,30,124,253,246,253,9,40,245,255,71,202,30,0,1,196,2,226,
  50516. 0,243,232,159,239,63,127,124,253,11,202,94,64,169,23,31,62,50,138,137,242,49,50,0,211,195,223,255,80,7,252,199,159,6,224,137,145,9,146,231,153,160,165,218,23,96,29,240,244,237,59,134,111,175,31,95,250,
  50517. 252,230,241,83,244,182,1,64,0,177,192,28,14,76,132,31,128,169,19,88,220,126,253,207,206,198,196,32,38,36,0,244,61,11,176,148,251,139,145,3,208,29,0,178,16,82,228,66,42,174,223,192,26,8,152,162,25,222,
  50518. 125,248,200,240,242,253,39,134,151,79,238,126,254,242,242,238,177,15,47,30,190,5,215,242,72,0,32,128,224,14,96,254,255,231,61,168,92,123,241,254,253,127,1,62,78,6,78,110,78,134,223,64,195,254,50,98,183,
  50519. 24,36,12,202,179,224,202,9,88,228,253,132,90,250,246,211,71,134,55,175,94,254,122,255,250,249,247,15,175,159,126,249,251,237,195,135,95,175,110,31,122,117,251,244,49,160,150,111,255,209,218,128,0,1,152,
  50520. 44,183,21,0,65,32,136,110,247,254,255,243,122,9,187,64,105,174,74,22,138,25,173,80,208,194,188,238,156,151,217,217,15,32,182,197,37,83,201,4,31,243,178,169,232,242,214,224,223,252,103,175,35,85,1,41,129,
  50521. 228,148,142,8,214,30,32,149,6,161,204,109,182,53,236,184,156,78,142,147,195,153,89,35,198,3,87,166,249,220,227,198,59,218,48,252,223,185,111,30,1,132,228,128,127,31,222,124,248,248,27,24,152,28,60,220,
  50522. 220,12,44,172,172,224,224,103,5,102,98,144,133,160,236,244,229,231,47,134,239,223,127,49,188,121,251,158,225,241,179,103,12,31,223,189,254,251,227,221,139,55,191,62,188,120,246,235,205,189,59,207,238,
  50523. 94,58,241,228,254,109,144,101,159,128,248,51,40,9,32,97,80,217,255,15,221,1,0,1,4,143,130,207,159,191,126,252,246,234,213,111,94,126,94,118,73,94,9,198,127,64,223,126,252,246,147,225,243,215,239,12,223,
  50524. 128,229,198,251,15,239,24,62,189,126,249,227,203,171,135,47,63,189,122,252,228,235,155,199,247,95,63,188,118,227,197,227,123,247,127,255,250,249,30,104,198,7,32,126,11,181,252,7,212,183,160,4,247,7,155,
  50525. 197,48,0,16,64,112,7,60,121,241,238,189,16,207,15,134,63,63,216,25,95,125,248,198,112,227,241,27,134,15,239,223,50,124,126,245,228,253,143,55,143,158,191,123,116,237,226,171,135,55,175,126,253,252,225,
  50526. 229,183,47,159,95,254,253,245,227,253,175,159,223,223,193,124,7,181,20,84,105,252,70,143,103,124,0,32,128,224,14,224,102,253,251,81,144,253,223,235,167,207,30,254,124,127,231,252,155,143,175,159,188,250,
  50527. 246,254,249,125,96,60,62,248,250,233,253,147,119,207,238,221,6,150,214,175,129,106,191,130,18,19,146,133,120,125,72,8,0,4,16,34,27,190,121,112,251,3,211,159,69,143,110,223,229,120,255,232,230,221,215,
  50528. 79,239,62,4,102,203,207,72,241,9,11,218,63,72,89,137,20,207,98,100,93,16,0,8,32,70,144,1,64,14,168,209,199,7,196,194,160,166,27,212,135,95,96,65,10,173,95,254,34,219,6,51,128,88,7,96,235,21,129,0,64,0,
  50529. 193,28,192,8,174,53,33,152,1,155,133,184,12,196,165,4,151,133,232,0,32,192,0,151,97,210,163,246,134,208,52,0,0,0,0,73,69,78,68,174,66,96,130,0,0};
  50530. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  50531. }
  50532. Image* LookAndFeel::getDefaultDocumentFileImage()
  50533. {
  50534. static const unsigned char fileicon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,32,8,6,0,0,0,115,122,122,244,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  50535. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,4,99,73,68,65,84,120,218,98,252,255,255,63,3,12,48,50,50,50,1,
  50536. 169,127,200,98,148,2,160,153,204,64,243,254,226,146,7,8,32,22,52,203,255,107,233,233,91,76,93,176,184,232,239,239,95,127,24,40,112,8,19,51,203,255,179,23,175,108,1,90,190,28,104,54,43,80,232,207,127,44,
  50537. 62,3,8,32,6,144,24,84,156,25,132,189,252,3,146,255,83,9,220,127,254,242,134,162,138,170,10,208,92,144,3,152,97,118,33,99,128,0,98,66,114,11,200,1,92,255,254,252,225,32,215,215,32,127,64,240,127,80,60,
  50538. 50,40,72,136,169,47,95,179,118,130,136,148,140,0,40,80,128,33,193,136,174,7,32,128,144,29,192,8,117,41,59,209,22,66,241,191,255,16,12,244,19,195,63,48,134,240,255,0,9,115,125,93,239,252,130,130,108,168,
  50539. 249,44,232,102,0,4,16,19,22,62,51,33,11,255,195,44,4,211,255,25,96,16,33,6,117,24,56,226,25,24,202,139,10,75,226,51,115,66,160,105,13,197,17,0,1,196,68,172,79,255,33,91,206,192,192,128,176,22,17,10,200,
  50540. 234,32,161,240,31,24,10,255,24,152,153,153,184,39,244,247,117,107,234,234,105,131,66,1,154,224,193,0,32,128,240,58,0,22,180,255,144,18,13,40,136,33,113,140,36,255,15,17,26,48,12,81,15,145,255,254,251,
  50541. 31,131,0,59,171,84,81,73,105,33,208,216,191,200,161,12,16,64,44,248,131,251,63,10,31,198,253,143,38,6,83,7,11,33,228,232,2,123,4,202,226,228,96,151,132,166,49,144,35,126,131,196,0,2,136,5,103,60,51,252,
  50542. 71,49,12,213,130,255,168,226,232,150,254,255,15,143,6,80,202,3,133,16,200,198,63,127,193,229,17,39,16,127,135,217,7,16,64,88,67,0,28,143,255,25,225,46,135,249,18,155,133,240,178,4,205,145,8,62,52,186,
  50543. 32,234,152,160,118,194,179,35,64,0,177,96,11,123,144,236,95,104,92,162,228,113,36,11,81,125,140,112,56,186,131,96,226,176,172,137,148,229,193,0,32,128,88,112,167,248,255,112,223,48,34,165,110,6,124,190,
  50544. 253,143,61,106,192,9,19,73,28,25,0,4,16,206,40,248,251,15,45,104,209,130,21,51,222,145,18,238,127,180,68,8,244,250,95,164,16,66,6,0,1,196,130,45,253,195,12,250,135,53,206,255,195,131,18,213,98,236,81,
  50545. 243,31,154,11,144,115,8,50,0,8,32,156,81,0,203,227,12,80,223,98,230,4,68,72,96,38,78,84,11,65,9,250,47,146,3,145,1,64,0,97,117,192,95,112,34,68,138,130,255,176,224,251,143,226,51,6,6,68,29,192,136,20,
  50546. 77,200,69,54,35,3,36,49,255,69,77,132,112,0,16,64,44,56,139,94,36,7,96,102,59,164,108,249,31,181,82,98,64,203,174,255,144,234,142,127,88,146,33,64,0,97,205,134,240,120,67,75,76,136,224,198,140,22,6,44,
  50547. 142,66,201,41,255,177,231,2,128,0,194,25,5,255,254,161,134,192,127,6,28,229,0,129,242,1,150,56,33,81,138,209,28,96,0,8,32,172,81,0,78,3,104,190,68,182,224,31,146,197,224,56,6,146,140,176,202,135,17,169,
  50548. 96,130,40,64,56,0,139,93,0,1,132,61,10,64,248,31,106,156,162,199,55,204,65,255,144,178,38,74,84,252,71,51,239,63,246,68,8,16,64,44,216,74,1,88,217,13,203,191,32,1,80,58,7,133,224,127,6,68,114,6,241,65,
  50549. 81,197,8,101,255,71,114,33,92,237,127,228,52,128,233,2,128,0,98,193,149,3,64,117,193,255,127,255,81,75,191,127,168,5,18,136,255,31,45,161,49,32,151,134,72,252,127,12,216,203,98,128,0,98,193,210,144,135,
  50550. 248,30,201,242,127,208,252,140,145,27,160,113,206,136,148,197,192,121,159,17,53,184,225,149,17,22,23,0,4,16,11,182,150,237,63,168,207,96,142,248,143,163,72,6,203,253,67,13,61,6,104,14,66,46,17,254,65,
  50551. 19,40,182,16,0,8,32,22,108,109,235,255,176,234,24,35,79,255,199,222,30,64,81,135,90,35,194,211,4,142,92,0,16,64,88,29,0,107,7,254,251,247,31,53,78,241,54,207,80,29,135,209,96,249,143,189,46,0,8,32,116,
  50552. 7,252,101,102,103,103,228,103,99,96,248,193,198,137,53,248,49,125,204,128,225,227,255,88,18,54,47,176,25,202,205,195,205,6,109,11,194,149,0,4,16,35,204,85,208,254,27,159,128,176,176,142,166,182,142,21,
  50553. 48,4,248,129,41,143,13,217,16,70,52,95,147,0,254,0,187,69,95,223,188,122,125,235,206,141,107,7,129,252,247,64,123,193,237,66,128,0,66,118,0,168,189,198,3,196,252,32,135,64,105,54,228,230,19,185,29,100,
  50554. 168,175,191,0,241,7,32,254,4,196,159,129,246,254,2,73,2,4,16,11,90,72,125,135,210,63,161,138,153,169,212,75,255,15,117,196,15,40,134,119,215,1,2,12,0,187,0,132,247,216,161,197,124,0,0,0,0,73,69,78,68,
  50555. 174,66,96,130,0,0};
  50556. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  50557. }
  50558. void LookAndFeel::playAlertSound()
  50559. {
  50560. PlatformUtilities::beep();
  50561. }
  50562. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  50563. {
  50564. g.setColour (Colours::white.withAlpha (0.7f));
  50565. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  50566. g.setColour (Colours::black.withAlpha (0.2f));
  50567. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  50568. const int totalBlocks = 7;
  50569. const int numBlocks = roundDoubleToInt (totalBlocks * level);
  50570. const float w = (width - 6.0f) / (float) totalBlocks;
  50571. for (int i = 0; i < totalBlocks; ++i)
  50572. {
  50573. if (i >= numBlocks)
  50574. g.setColour (Colours::lightblue.withAlpha (0.6f));
  50575. else
  50576. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  50577. : Colours::red);
  50578. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  50579. }
  50580. }
  50581. static void createRoundedPath (Path& p,
  50582. const float x, const float y,
  50583. const float w, const float h,
  50584. const float cs,
  50585. const bool curveTopLeft, const bool curveTopRight,
  50586. const bool curveBottomLeft, const bool curveBottomRight) throw()
  50587. {
  50588. const float cs2 = 2.0f * cs;
  50589. if (curveTopLeft)
  50590. {
  50591. p.startNewSubPath (x, y + cs);
  50592. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  50593. }
  50594. else
  50595. {
  50596. p.startNewSubPath (x, y);
  50597. }
  50598. if (curveTopRight)
  50599. {
  50600. p.lineTo (x + w - cs, y);
  50601. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  50602. }
  50603. else
  50604. {
  50605. p.lineTo (x + w, y);
  50606. }
  50607. if (curveBottomRight)
  50608. {
  50609. p.lineTo (x + w, y + h - cs);
  50610. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  50611. }
  50612. else
  50613. {
  50614. p.lineTo (x + w, y + h);
  50615. }
  50616. if (curveBottomLeft)
  50617. {
  50618. p.lineTo (x + cs, y + h);
  50619. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  50620. }
  50621. else
  50622. {
  50623. p.lineTo (x, y + h);
  50624. }
  50625. p.closeSubPath();
  50626. }
  50627. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  50628. float x, float y, float w, float h,
  50629. float maxCornerSize,
  50630. const Colour& baseColour,
  50631. const float strokeWidth,
  50632. const bool flatOnLeft,
  50633. const bool flatOnRight,
  50634. const bool flatOnTop,
  50635. const bool flatOnBottom) throw()
  50636. {
  50637. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  50638. return;
  50639. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  50640. Path outline;
  50641. createRoundedPath (outline, x, y, w, h, cs,
  50642. ! (flatOnLeft || flatOnTop),
  50643. ! (flatOnRight || flatOnTop),
  50644. ! (flatOnLeft || flatOnBottom),
  50645. ! (flatOnRight || flatOnBottom));
  50646. ColourGradient cg (baseColour, 0.0f, y,
  50647. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  50648. false);
  50649. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  50650. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  50651. GradientBrush gb (cg);
  50652. g.setBrush (&gb);
  50653. g.fillPath (outline);
  50654. g.setColour (Colour (0x80000000));
  50655. g.strokePath (outline, PathStrokeType (strokeWidth));
  50656. }
  50657. void LookAndFeel::drawGlassSphere (Graphics& g,
  50658. const float x, const float y,
  50659. const float diameter,
  50660. const Colour& colour,
  50661. const float outlineThickness) throw()
  50662. {
  50663. if (diameter <= outlineThickness)
  50664. return;
  50665. Path p;
  50666. p.addEllipse (x, y, diameter, diameter);
  50667. {
  50668. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  50669. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  50670. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  50671. GradientBrush gb (cg);
  50672. g.setBrush (&gb);
  50673. g.fillPath (p);
  50674. }
  50675. {
  50676. GradientBrush gb (Colours::white, 0, y + diameter * 0.06f,
  50677. Colours::transparentWhite, 0, y + diameter * 0.3f, false);
  50678. g.setBrush (&gb);
  50679. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  50680. }
  50681. {
  50682. ColourGradient cg (Colours::transparentBlack,
  50683. x + diameter * 0.5f, y + diameter * 0.5f,
  50684. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  50685. x, y + diameter * 0.5f, true);
  50686. cg.addColour (0.7, Colours::transparentBlack);
  50687. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  50688. GradientBrush gb (cg);
  50689. g.setBrush (&gb);
  50690. g.fillPath (p);
  50691. }
  50692. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  50693. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  50694. }
  50695. void LookAndFeel::drawGlassPointer (Graphics& g,
  50696. const float x, const float y,
  50697. const float diameter,
  50698. const Colour& colour, const float outlineThickness,
  50699. const int direction) throw()
  50700. {
  50701. if (diameter <= outlineThickness)
  50702. return;
  50703. Path p;
  50704. p.startNewSubPath (x + diameter * 0.5f, y);
  50705. p.lineTo (x + diameter, y + diameter * 0.6f);
  50706. p.lineTo (x + diameter, y + diameter);
  50707. p.lineTo (x, y + diameter);
  50708. p.lineTo (x, y + diameter * 0.6f);
  50709. p.closeSubPath();
  50710. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  50711. {
  50712. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  50713. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  50714. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  50715. GradientBrush gb (cg);
  50716. g.setBrush (&gb);
  50717. g.fillPath (p);
  50718. }
  50719. {
  50720. ColourGradient cg (Colours::transparentBlack,
  50721. x + diameter * 0.5f, y + diameter * 0.5f,
  50722. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  50723. x - diameter * 0.2f, y + diameter * 0.5f, true);
  50724. cg.addColour (0.5, Colours::transparentBlack);
  50725. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  50726. GradientBrush gb (cg);
  50727. g.setBrush (&gb);
  50728. g.fillPath (p);
  50729. }
  50730. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  50731. g.strokePath (p, PathStrokeType (outlineThickness));
  50732. }
  50733. void LookAndFeel::drawGlassLozenge (Graphics& g,
  50734. const float x, const float y,
  50735. const float width, const float height,
  50736. const Colour& colour,
  50737. const float outlineThickness,
  50738. const float cornerSize,
  50739. const bool flatOnLeft,
  50740. const bool flatOnRight,
  50741. const bool flatOnTop,
  50742. const bool flatOnBottom) throw()
  50743. {
  50744. if (width <= outlineThickness || height <= outlineThickness)
  50745. return;
  50746. const int intX = (int) x;
  50747. const int intY = (int) y;
  50748. const int intW = (int) width;
  50749. const int intH = (int) height;
  50750. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  50751. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  50752. const int intEdge = (int) edgeBlurRadius;
  50753. Path outline;
  50754. createRoundedPath (outline, x, y, width, height, cs,
  50755. ! (flatOnLeft || flatOnTop),
  50756. ! (flatOnRight || flatOnTop),
  50757. ! (flatOnLeft || flatOnBottom),
  50758. ! (flatOnRight || flatOnBottom));
  50759. {
  50760. ColourGradient cg (colour.darker (0.2f), 0, y,
  50761. colour.darker (0.2f), 0, y + height, false);
  50762. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  50763. cg.addColour (0.4, colour);
  50764. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  50765. GradientBrush gb (cg);
  50766. g.setBrush (&gb);
  50767. g.fillPath (outline);
  50768. }
  50769. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  50770. colour.darker (0.2f), x, y + height * 0.5f, true);
  50771. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  50772. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  50773. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  50774. {
  50775. GradientBrush gb (cg);
  50776. g.saveState();
  50777. g.setBrush (&gb);
  50778. g.reduceClipRegion (intX, intY, intEdge, intH);
  50779. g.fillPath (outline);
  50780. g.restoreState();
  50781. }
  50782. if (! (flatOnRight || flatOnTop || flatOnBottom))
  50783. {
  50784. cg.x1 = x + width - edgeBlurRadius;
  50785. cg.x2 = x + width;
  50786. GradientBrush gb (cg);
  50787. g.saveState();
  50788. g.setBrush (&gb);
  50789. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  50790. g.fillPath (outline);
  50791. g.restoreState();
  50792. }
  50793. {
  50794. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  50795. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  50796. Path highlight;
  50797. createRoundedPath (highlight,
  50798. x + leftIndent,
  50799. y + cs * 0.1f,
  50800. width - (leftIndent + rightIndent),
  50801. height * 0.4f, cs * 0.4f,
  50802. ! (flatOnLeft || flatOnTop),
  50803. ! (flatOnRight || flatOnTop),
  50804. ! (flatOnLeft || flatOnBottom),
  50805. ! (flatOnRight || flatOnBottom));
  50806. GradientBrush gb (colour.brighter (10.0f), 0, y + height * 0.06f,
  50807. Colours::transparentWhite, 0, y + height * 0.4f, false);
  50808. g.setBrush (&gb);
  50809. g.fillPath (highlight);
  50810. }
  50811. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  50812. g.strokePath (outline, PathStrokeType (outlineThickness));
  50813. }
  50814. END_JUCE_NAMESPACE
  50815. /********* End of inlined file: juce_LookAndFeel.cpp *********/
  50816. /********* Start of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  50817. BEGIN_JUCE_NAMESPACE
  50818. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  50819. {
  50820. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  50821. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  50822. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  50823. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  50824. setColour (Slider::thumbColourId, Colours::white);
  50825. setColour (Slider::trackColourId, Colour (0x7f000000));
  50826. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  50827. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  50828. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  50829. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  50830. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  50831. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  50832. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  50833. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  50834. }
  50835. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  50836. {
  50837. }
  50838. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  50839. Button& button,
  50840. const Colour& backgroundColour,
  50841. bool isMouseOverButton,
  50842. bool isButtonDown)
  50843. {
  50844. const int width = button.getWidth();
  50845. const int height = button.getHeight();
  50846. const float indent = 2.0f;
  50847. const int cornerSize = jmin (roundFloatToInt (width * 0.4f),
  50848. roundFloatToInt (height * 0.4f));
  50849. Path p;
  50850. p.addRoundedRectangle (indent, indent,
  50851. width - indent * 2.0f,
  50852. height - indent * 2.0f,
  50853. (float) cornerSize);
  50854. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  50855. if (isMouseOverButton)
  50856. {
  50857. if (isButtonDown)
  50858. bc = bc.brighter();
  50859. else if (bc.getBrightness() > 0.5f)
  50860. bc = bc.darker (0.1f);
  50861. else
  50862. bc = bc.brighter (0.1f);
  50863. }
  50864. g.setColour (bc);
  50865. g.fillPath (p);
  50866. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  50867. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  50868. }
  50869. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  50870. Component& /*component*/,
  50871. int x, int y, int w, int h,
  50872. const bool ticked,
  50873. const bool isEnabled,
  50874. const bool /*isMouseOverButton*/,
  50875. const bool isButtonDown)
  50876. {
  50877. Path box;
  50878. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  50879. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  50880. : Colours::lightgrey.withAlpha (0.1f));
  50881. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  50882. .translated ((float) x, (float) y));
  50883. g.fillPath (box, trans);
  50884. g.setColour (Colours::black.withAlpha (0.6f));
  50885. g.strokePath (box, PathStrokeType (0.9f), trans);
  50886. if (ticked)
  50887. {
  50888. Path tick;
  50889. tick.startNewSubPath (1.5f, 3.0f);
  50890. tick.lineTo (3.0f, 6.0f);
  50891. tick.lineTo (6.0f, 0.0f);
  50892. g.setColour (isEnabled ? Colours::black : Colours::grey);
  50893. g.strokePath (tick, PathStrokeType (2.5f), trans);
  50894. }
  50895. }
  50896. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  50897. ToggleButton& button,
  50898. bool isMouseOverButton,
  50899. bool isButtonDown)
  50900. {
  50901. if (button.hasKeyboardFocus (true))
  50902. {
  50903. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  50904. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  50905. }
  50906. const int tickWidth = jmin (20, button.getHeight() - 4);
  50907. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  50908. tickWidth, tickWidth,
  50909. button.getToggleState(),
  50910. button.isEnabled(),
  50911. isMouseOverButton,
  50912. isButtonDown);
  50913. g.setColour (button.findColour (ToggleButton::textColourId));
  50914. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  50915. if (! button.isEnabled())
  50916. g.setOpacity (0.5f);
  50917. const int textX = tickWidth + 5;
  50918. g.drawFittedText (button.getButtonText(),
  50919. textX, 4,
  50920. button.getWidth() - textX - 2, button.getHeight() - 8,
  50921. Justification::centredLeft, 10);
  50922. }
  50923. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  50924. int width, int height,
  50925. double progress, const String& textToShow)
  50926. {
  50927. if (progress < 0 || progress >= 1.0)
  50928. {
  50929. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  50930. }
  50931. else
  50932. {
  50933. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  50934. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  50935. g.fillAll (background);
  50936. g.setColour (foreground);
  50937. g.fillRect (1, 1,
  50938. jlimit (0, width - 2, roundDoubleToInt (progress * (width - 2))),
  50939. height - 2);
  50940. if (textToShow.isNotEmpty())
  50941. {
  50942. g.setColour (Colour::contrasting (background, foreground));
  50943. g.setFont (height * 0.6f);
  50944. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  50945. }
  50946. }
  50947. }
  50948. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  50949. ScrollBar& bar,
  50950. int width, int height,
  50951. int buttonDirection,
  50952. bool isScrollbarVertical,
  50953. bool isMouseOverButton,
  50954. bool isButtonDown)
  50955. {
  50956. if (isScrollbarVertical)
  50957. width -= 2;
  50958. else
  50959. height -= 2;
  50960. Path p;
  50961. if (buttonDirection == 0)
  50962. p.addTriangle (width * 0.5f, height * 0.2f,
  50963. width * 0.1f, height * 0.7f,
  50964. width * 0.9f, height * 0.7f);
  50965. else if (buttonDirection == 1)
  50966. p.addTriangle (width * 0.8f, height * 0.5f,
  50967. width * 0.3f, height * 0.1f,
  50968. width * 0.3f, height * 0.9f);
  50969. else if (buttonDirection == 2)
  50970. p.addTriangle (width * 0.5f, height * 0.8f,
  50971. width * 0.1f, height * 0.3f,
  50972. width * 0.9f, height * 0.3f);
  50973. else if (buttonDirection == 3)
  50974. p.addTriangle (width * 0.2f, height * 0.5f,
  50975. width * 0.7f, height * 0.1f,
  50976. width * 0.7f, height * 0.9f);
  50977. if (isButtonDown)
  50978. g.setColour (Colours::white);
  50979. else if (isMouseOverButton)
  50980. g.setColour (Colours::white.withAlpha (0.7f));
  50981. else
  50982. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  50983. g.fillPath (p);
  50984. g.setColour (Colours::black.withAlpha (0.5f));
  50985. g.strokePath (p, PathStrokeType (0.5f));
  50986. }
  50987. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  50988. ScrollBar& bar,
  50989. int x, int y,
  50990. int width, int height,
  50991. bool isScrollbarVertical,
  50992. int thumbStartPosition,
  50993. int thumbSize,
  50994. bool isMouseOver,
  50995. bool isMouseDown)
  50996. {
  50997. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  50998. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  50999. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  51000. if (thumbSize > 0.0f)
  51001. {
  51002. Rectangle thumb;
  51003. if (isScrollbarVertical)
  51004. {
  51005. width -= 2;
  51006. g.fillRect (x + roundFloatToInt (width * 0.35f), y,
  51007. roundFloatToInt (width * 0.3f), height);
  51008. thumb.setBounds (x + 1, thumbStartPosition,
  51009. width - 2, thumbSize);
  51010. }
  51011. else
  51012. {
  51013. height -= 2;
  51014. g.fillRect (x, y + roundFloatToInt (height * 0.35f),
  51015. width, roundFloatToInt (height * 0.3f));
  51016. thumb.setBounds (thumbStartPosition, y + 1,
  51017. thumbSize, height - 2);
  51018. }
  51019. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  51020. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  51021. g.fillRect (thumb);
  51022. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  51023. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  51024. if (thumbSize > 16)
  51025. {
  51026. for (int i = 3; --i >= 0;)
  51027. {
  51028. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  51029. g.setColour (Colours::black.withAlpha (0.15f));
  51030. if (isScrollbarVertical)
  51031. {
  51032. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  51033. g.setColour (Colours::white.withAlpha (0.15f));
  51034. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  51035. }
  51036. else
  51037. {
  51038. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  51039. g.setColour (Colours::white.withAlpha (0.15f));
  51040. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  51041. }
  51042. }
  51043. }
  51044. }
  51045. }
  51046. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  51047. {
  51048. return &scrollbarShadow;
  51049. }
  51050. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  51051. {
  51052. g.fillAll (findColour (PopupMenu::backgroundColourId));
  51053. g.setColour (Colours::black.withAlpha (0.6f));
  51054. g.drawRect (0, 0, width, height);
  51055. }
  51056. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  51057. bool, MenuBarComponent& menuBar)
  51058. {
  51059. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  51060. }
  51061. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  51062. {
  51063. if (textEditor.isEnabled())
  51064. {
  51065. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  51066. g.drawRect (0, 0, width, height);
  51067. }
  51068. }
  51069. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  51070. const bool isButtonDown,
  51071. int buttonX, int buttonY,
  51072. int buttonW, int buttonH,
  51073. ComboBox& box)
  51074. {
  51075. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  51076. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  51077. : ComboBox::backgroundColourId));
  51078. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  51079. g.setColour (box.findColour (ComboBox::outlineColourId));
  51080. g.drawRect (0, 0, width, height);
  51081. const float arrowX = 0.2f;
  51082. const float arrowH = 0.3f;
  51083. if (box.isEnabled())
  51084. {
  51085. Path p;
  51086. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  51087. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  51088. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  51089. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  51090. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  51091. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  51092. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  51093. : ComboBox::buttonColourId));
  51094. g.fillPath (p);
  51095. }
  51096. }
  51097. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  51098. {
  51099. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  51100. f.setHorizontalScale (0.9f);
  51101. return f;
  51102. }
  51103. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  51104. {
  51105. Path p;
  51106. p.addTriangle (x1, y1, x2, y2, x3, y3);
  51107. g.setColour (fill);
  51108. g.fillPath (p);
  51109. g.setColour (outline);
  51110. g.strokePath (p, PathStrokeType (0.3f));
  51111. }
  51112. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  51113. int x, int y,
  51114. int w, int h,
  51115. float sliderPos,
  51116. float minSliderPos,
  51117. float maxSliderPos,
  51118. const Slider::SliderStyle style,
  51119. Slider& slider)
  51120. {
  51121. g.fillAll (slider.findColour (Slider::backgroundColourId));
  51122. if (style == Slider::LinearBar)
  51123. {
  51124. g.setColour (slider.findColour (Slider::thumbColourId));
  51125. g.fillRect (x, y, (int) sliderPos - x, h);
  51126. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  51127. g.drawRect (x, y, (int) sliderPos - x, h);
  51128. }
  51129. else
  51130. {
  51131. g.setColour (slider.findColour (Slider::trackColourId)
  51132. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  51133. if (slider.isHorizontal())
  51134. {
  51135. g.fillRect (x, y + roundFloatToInt (h * 0.6f),
  51136. w, roundFloatToInt (h * 0.2f));
  51137. }
  51138. else
  51139. {
  51140. g.fillRect (x + roundFloatToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  51141. jmin (4, roundFloatToInt (w * 0.2f)), h);
  51142. }
  51143. float alpha = 0.35f;
  51144. if (slider.isEnabled())
  51145. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  51146. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  51147. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  51148. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  51149. {
  51150. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  51151. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  51152. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  51153. fill, outline);
  51154. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  51155. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  51156. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  51157. fill, outline);
  51158. }
  51159. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  51160. {
  51161. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  51162. minSliderPos - 7.0f, y + h * 0.9f ,
  51163. minSliderPos, y + h * 0.9f,
  51164. fill, outline);
  51165. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  51166. maxSliderPos, y + h * 0.9f,
  51167. maxSliderPos + 7.0f, y + h * 0.9f,
  51168. fill, outline);
  51169. }
  51170. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  51171. {
  51172. drawTriangle (g, sliderPos, y + h * 0.9f,
  51173. sliderPos - 7.0f, y + h * 0.2f,
  51174. sliderPos + 7.0f, y + h * 0.2f,
  51175. fill, outline);
  51176. }
  51177. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  51178. {
  51179. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  51180. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  51181. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  51182. fill, outline);
  51183. }
  51184. }
  51185. }
  51186. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  51187. {
  51188. if (isIncrement)
  51189. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  51190. else
  51191. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  51192. }
  51193. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  51194. {
  51195. return &scrollbarShadow;
  51196. }
  51197. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  51198. {
  51199. return 8;
  51200. }
  51201. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  51202. int w, int h,
  51203. bool isMouseOver,
  51204. bool isMouseDragging)
  51205. {
  51206. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  51207. : Colours::darkgrey);
  51208. const float lineThickness = jmin (w, h) * 0.1f;
  51209. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  51210. {
  51211. g.drawLine (w * i,
  51212. h + 1.0f,
  51213. w + 1.0f,
  51214. h * i,
  51215. lineThickness);
  51216. }
  51217. }
  51218. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  51219. {
  51220. Path shape;
  51221. if (buttonType == DocumentWindow::closeButton)
  51222. {
  51223. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  51224. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  51225. ShapeButton* const b = new ShapeButton ("close",
  51226. Colour (0x7fff3333),
  51227. Colour (0xd7ff3333),
  51228. Colour (0xf7ff3333));
  51229. b->setShape (shape, true, true, true);
  51230. return b;
  51231. }
  51232. else if (buttonType == DocumentWindow::minimiseButton)
  51233. {
  51234. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  51235. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  51236. DrawablePath dp;
  51237. dp.setPath (shape);
  51238. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  51239. b->setImages (&dp);
  51240. return b;
  51241. }
  51242. else if (buttonType == DocumentWindow::maximiseButton)
  51243. {
  51244. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  51245. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  51246. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  51247. DrawablePath dp;
  51248. dp.setPath (shape);
  51249. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  51250. b->setImages (&dp);
  51251. return b;
  51252. }
  51253. jassertfalse
  51254. return 0;
  51255. }
  51256. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  51257. int titleBarX,
  51258. int titleBarY,
  51259. int titleBarW,
  51260. int titleBarH,
  51261. Button* minimiseButton,
  51262. Button* maximiseButton,
  51263. Button* closeButton,
  51264. bool positionTitleBarButtonsOnLeft)
  51265. {
  51266. titleBarY += titleBarH / 8;
  51267. titleBarH -= titleBarH / 4;
  51268. const int buttonW = titleBarH;
  51269. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  51270. : titleBarX + titleBarW - buttonW - 4;
  51271. if (closeButton != 0)
  51272. {
  51273. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  51274. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  51275. : -(buttonW + buttonW / 5);
  51276. }
  51277. if (positionTitleBarButtonsOnLeft)
  51278. swapVariables (minimiseButton, maximiseButton);
  51279. if (maximiseButton != 0)
  51280. {
  51281. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  51282. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  51283. }
  51284. if (minimiseButton != 0)
  51285. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  51286. }
  51287. END_JUCE_NAMESPACE
  51288. /********* End of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  51289. /********* Start of inlined file: juce_MenuBarComponent.cpp *********/
  51290. BEGIN_JUCE_NAMESPACE
  51291. class DummyMenuComponent : public Component
  51292. {
  51293. DummyMenuComponent (const DummyMenuComponent&);
  51294. const DummyMenuComponent& operator= (const DummyMenuComponent&);
  51295. public:
  51296. DummyMenuComponent() {}
  51297. ~DummyMenuComponent() {}
  51298. void inputAttemptWhenModal()
  51299. {
  51300. exitModalState (0);
  51301. }
  51302. };
  51303. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  51304. : model (0),
  51305. itemUnderMouse (-1),
  51306. currentPopupIndex (-1),
  51307. indexToShowAgain (-1),
  51308. lastMouseX (0),
  51309. lastMouseY (0),
  51310. inModalState (false),
  51311. currentPopup (0)
  51312. {
  51313. setRepaintsOnMouseActivity (true);
  51314. setWantsKeyboardFocus (false);
  51315. setMouseClickGrabsKeyboardFocus (false);
  51316. setModel (model_);
  51317. }
  51318. MenuBarComponent::~MenuBarComponent()
  51319. {
  51320. setModel (0);
  51321. Desktop::getInstance().removeGlobalMouseListener (this);
  51322. deleteAndZero (currentPopup);
  51323. }
  51324. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  51325. {
  51326. if (model != newModel)
  51327. {
  51328. if (model != 0)
  51329. model->removeListener (this);
  51330. model = newModel;
  51331. if (model != 0)
  51332. model->addListener (this);
  51333. repaint();
  51334. menuBarItemsChanged (0);
  51335. }
  51336. }
  51337. void MenuBarComponent::paint (Graphics& g)
  51338. {
  51339. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  51340. getLookAndFeel().drawMenuBarBackground (g,
  51341. getWidth(),
  51342. getHeight(),
  51343. isMouseOverBar,
  51344. *this);
  51345. if (model != 0)
  51346. {
  51347. for (int i = 0; i < menuNames.size(); ++i)
  51348. {
  51349. g.saveState();
  51350. g.setOrigin (xPositions [i], 0);
  51351. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  51352. getLookAndFeel().drawMenuBarItem (g,
  51353. xPositions[i + 1] - xPositions[i],
  51354. getHeight(),
  51355. i,
  51356. menuNames[i],
  51357. i == itemUnderMouse,
  51358. i == currentPopupIndex,
  51359. isMouseOverBar,
  51360. *this);
  51361. g.restoreState();
  51362. }
  51363. }
  51364. }
  51365. void MenuBarComponent::resized()
  51366. {
  51367. xPositions.clear();
  51368. int x = 2;
  51369. xPositions.add (x);
  51370. for (int i = 0; i < menuNames.size(); ++i)
  51371. {
  51372. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  51373. xPositions.add (x);
  51374. }
  51375. }
  51376. int MenuBarComponent::getItemAt (const int x, const int y)
  51377. {
  51378. for (int i = 0; i < xPositions.size(); ++i)
  51379. if (x >= xPositions[i] && x < xPositions[i + 1])
  51380. return reallyContains (x, y, true) ? i : -1;
  51381. return -1;
  51382. }
  51383. void MenuBarComponent::repaintMenuItem (int index)
  51384. {
  51385. if (((unsigned int) index) < (unsigned int) xPositions.size())
  51386. {
  51387. const int x1 = xPositions [index];
  51388. const int x2 = xPositions [index + 1];
  51389. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  51390. }
  51391. }
  51392. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  51393. {
  51394. const int newItem = getItemAt (x, y);
  51395. if (itemUnderMouse != newItem)
  51396. {
  51397. repaintMenuItem (itemUnderMouse);
  51398. itemUnderMouse = newItem;
  51399. repaintMenuItem (itemUnderMouse);
  51400. }
  51401. }
  51402. void MenuBarComponent::hideCurrentMenu()
  51403. {
  51404. deleteAndZero (currentPopup);
  51405. repaint();
  51406. }
  51407. void MenuBarComponent::showMenu (int index)
  51408. {
  51409. if (index != currentPopupIndex)
  51410. {
  51411. if (inModalState)
  51412. {
  51413. hideCurrentMenu();
  51414. indexToShowAgain = index;
  51415. return;
  51416. }
  51417. indexToShowAgain = -1;
  51418. currentPopupIndex = -1;
  51419. itemUnderMouse = index;
  51420. deleteAndZero (currentPopup);
  51421. menuBarItemsChanged (0);
  51422. Component* const prevFocused = getCurrentlyFocusedComponent();
  51423. ComponentDeletionWatcher* prevCompDeletionChecker = 0;
  51424. if (prevFocused != 0)
  51425. prevCompDeletionChecker = new ComponentDeletionWatcher (prevFocused);
  51426. ComponentDeletionWatcher deletionChecker (this);
  51427. enterModalState (false);
  51428. inModalState = true;
  51429. int result = 0;
  51430. ApplicationCommandManager* managerOfChosenCommand = 0;
  51431. Desktop::getInstance().addGlobalMouseListener (this);
  51432. for (;;)
  51433. {
  51434. const int x = getScreenX() + xPositions [itemUnderMouse];
  51435. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  51436. currentPopupIndex = itemUnderMouse;
  51437. indexToShowAgain = -1;
  51438. repaint();
  51439. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  51440. {
  51441. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  51442. menuNames [itemUnderMouse]));
  51443. currentPopup = m.createMenuComponent (x, getScreenY(),
  51444. w, getHeight(),
  51445. 0, w, 0, 0,
  51446. true, this,
  51447. &managerOfChosenCommand,
  51448. this);
  51449. }
  51450. if (currentPopup == 0)
  51451. {
  51452. currentPopup = new DummyMenuComponent();
  51453. addAndMakeVisible (currentPopup);
  51454. }
  51455. currentPopup->enterModalState (false);
  51456. currentPopup->toFront (false); // need to do this after making it modal, or it could
  51457. // be stuck behind other comps that are already modal..
  51458. result = currentPopup->runModalLoop();
  51459. if (deletionChecker.hasBeenDeleted())
  51460. {
  51461. delete prevCompDeletionChecker;
  51462. return;
  51463. }
  51464. const int lastPopupIndex = currentPopupIndex;
  51465. deleteAndZero (currentPopup);
  51466. currentPopupIndex = -1;
  51467. if (result != 0)
  51468. {
  51469. topLevelIndexClicked = lastPopupIndex;
  51470. break;
  51471. }
  51472. else if (indexToShowAgain >= 0)
  51473. {
  51474. menuBarItemsChanged (0);
  51475. repaint();
  51476. itemUnderMouse = indexToShowAgain;
  51477. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  51478. break;
  51479. }
  51480. else
  51481. {
  51482. break;
  51483. }
  51484. }
  51485. Desktop::getInstance().removeGlobalMouseListener (this);
  51486. inModalState = false;
  51487. exitModalState (0);
  51488. if (prevCompDeletionChecker != 0)
  51489. {
  51490. if (! prevCompDeletionChecker->hasBeenDeleted())
  51491. prevFocused->grabKeyboardFocus();
  51492. delete prevCompDeletionChecker;
  51493. }
  51494. int mx, my;
  51495. getMouseXYRelative (mx, my);
  51496. updateItemUnderMouse (mx, my);
  51497. repaint();
  51498. if (result != 0)
  51499. {
  51500. if (managerOfChosenCommand != 0)
  51501. {
  51502. ApplicationCommandTarget::InvocationInfo info (result);
  51503. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  51504. managerOfChosenCommand->invoke (info, true);
  51505. }
  51506. postCommandMessage (result);
  51507. }
  51508. }
  51509. }
  51510. void MenuBarComponent::handleCommandMessage (int commandId)
  51511. {
  51512. if (model != 0)
  51513. model->menuItemSelected (commandId, topLevelIndexClicked);
  51514. }
  51515. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  51516. {
  51517. if (e.eventComponent == this)
  51518. updateItemUnderMouse (e.x, e.y);
  51519. }
  51520. void MenuBarComponent::mouseExit (const MouseEvent& e)
  51521. {
  51522. if (e.eventComponent == this)
  51523. updateItemUnderMouse (e.x, e.y);
  51524. }
  51525. void MenuBarComponent::mouseDown (const MouseEvent& e)
  51526. {
  51527. const MouseEvent e2 (e.getEventRelativeTo (this));
  51528. if (currentPopupIndex < 0)
  51529. {
  51530. updateItemUnderMouse (e2.x, e2.y);
  51531. currentPopupIndex = -2;
  51532. showMenu (itemUnderMouse);
  51533. }
  51534. }
  51535. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  51536. {
  51537. const MouseEvent e2 (e.getEventRelativeTo (this));
  51538. const int item = getItemAt (e2.x, e2.y);
  51539. if (item >= 0)
  51540. showMenu (item);
  51541. }
  51542. void MenuBarComponent::mouseUp (const MouseEvent& e)
  51543. {
  51544. const MouseEvent e2 (e.getEventRelativeTo (this));
  51545. updateItemUnderMouse (e2.x, e2.y);
  51546. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (currentPopup) != 0)
  51547. hideCurrentMenu();
  51548. }
  51549. void MenuBarComponent::mouseMove (const MouseEvent& e)
  51550. {
  51551. const MouseEvent e2 (e.getEventRelativeTo (this));
  51552. if (lastMouseX != e2.x || lastMouseY != e2.y)
  51553. {
  51554. if (currentPopupIndex >= 0)
  51555. {
  51556. const int item = getItemAt (e2.x, e2.y);
  51557. if (item >= 0)
  51558. showMenu (item);
  51559. }
  51560. else
  51561. {
  51562. updateItemUnderMouse (e2.x, e2.y);
  51563. }
  51564. lastMouseX = e2.x;
  51565. lastMouseY = e2.y;
  51566. }
  51567. }
  51568. bool MenuBarComponent::keyPressed (const KeyPress& key)
  51569. {
  51570. bool used = false;
  51571. const int numMenus = menuNames.size();
  51572. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  51573. if (key.isKeyCode (KeyPress::leftKey))
  51574. {
  51575. showMenu ((currentIndex + numMenus - 1) % numMenus);
  51576. used = true;
  51577. }
  51578. else if (key.isKeyCode (KeyPress::rightKey))
  51579. {
  51580. showMenu ((currentIndex + 1) % numMenus);
  51581. used = true;
  51582. }
  51583. return used;
  51584. }
  51585. void MenuBarComponent::inputAttemptWhenModal()
  51586. {
  51587. hideCurrentMenu();
  51588. }
  51589. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  51590. {
  51591. StringArray newNames;
  51592. if (model != 0)
  51593. newNames = model->getMenuBarNames();
  51594. if (newNames != menuNames)
  51595. {
  51596. menuNames = newNames;
  51597. repaint();
  51598. resized();
  51599. }
  51600. }
  51601. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  51602. const ApplicationCommandTarget::InvocationInfo& info)
  51603. {
  51604. if (model == 0
  51605. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  51606. return;
  51607. for (int i = 0; i < menuNames.size(); ++i)
  51608. {
  51609. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  51610. if (menu.containsCommandItem (info.commandID))
  51611. {
  51612. itemUnderMouse = i;
  51613. repaintMenuItem (i);
  51614. startTimer (200);
  51615. break;
  51616. }
  51617. }
  51618. }
  51619. void MenuBarComponent::timerCallback()
  51620. {
  51621. stopTimer();
  51622. int mx, my;
  51623. getMouseXYRelative (mx, my);
  51624. updateItemUnderMouse (mx, my);
  51625. }
  51626. END_JUCE_NAMESPACE
  51627. /********* End of inlined file: juce_MenuBarComponent.cpp *********/
  51628. /********* Start of inlined file: juce_MenuBarModel.cpp *********/
  51629. BEGIN_JUCE_NAMESPACE
  51630. MenuBarModel::MenuBarModel() throw()
  51631. : manager (0)
  51632. {
  51633. }
  51634. MenuBarModel::~MenuBarModel()
  51635. {
  51636. setApplicationCommandManagerToWatch (0);
  51637. }
  51638. void MenuBarModel::menuItemsChanged()
  51639. {
  51640. triggerAsyncUpdate();
  51641. }
  51642. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  51643. {
  51644. if (manager != newManager)
  51645. {
  51646. if (manager != 0)
  51647. manager->removeListener (this);
  51648. manager = newManager;
  51649. if (manager != 0)
  51650. manager->addListener (this);
  51651. }
  51652. }
  51653. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  51654. {
  51655. jassert (newListener != 0);
  51656. jassert (! listeners.contains (newListener)); // trying to add a listener to the list twice!
  51657. if (newListener != 0)
  51658. listeners.add (newListener);
  51659. }
  51660. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  51661. {
  51662. // Trying to remove a listener that isn't on the list!
  51663. // If this assertion happens because this object is a dangling pointer, make sure you've not
  51664. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  51665. jassert (listeners.contains (listenerToRemove));
  51666. listeners.removeValue (listenerToRemove);
  51667. }
  51668. void MenuBarModel::handleAsyncUpdate()
  51669. {
  51670. for (int i = listeners.size(); --i >= 0;)
  51671. {
  51672. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuBarItemsChanged (this);
  51673. i = jmin (i, listeners.size());
  51674. }
  51675. }
  51676. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  51677. {
  51678. for (int i = listeners.size(); --i >= 0;)
  51679. {
  51680. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuCommandInvoked (this, info);
  51681. i = jmin (i, listeners.size());
  51682. }
  51683. }
  51684. void MenuBarModel::applicationCommandListChanged()
  51685. {
  51686. menuItemsChanged();
  51687. }
  51688. END_JUCE_NAMESPACE
  51689. /********* End of inlined file: juce_MenuBarModel.cpp *********/
  51690. /********* Start of inlined file: juce_PopupMenu.cpp *********/
  51691. BEGIN_JUCE_NAMESPACE
  51692. static VoidArray activeMenuWindows;
  51693. class MenuItemInfo
  51694. {
  51695. public:
  51696. const int itemId;
  51697. String text;
  51698. const Colour textColour;
  51699. const bool active, isSeparator, isTicked, usesColour;
  51700. Image* image;
  51701. PopupMenuCustomComponent* const customComp;
  51702. PopupMenu* subMenu;
  51703. ApplicationCommandManager* const commandManager;
  51704. MenuItemInfo() throw()
  51705. : itemId (0),
  51706. active (true),
  51707. isSeparator (true),
  51708. isTicked (false),
  51709. usesColour (false),
  51710. image (0),
  51711. customComp (0),
  51712. subMenu (0),
  51713. commandManager (0)
  51714. {
  51715. }
  51716. MenuItemInfo (const int itemId_,
  51717. const String& text_,
  51718. const bool active_,
  51719. const bool isTicked_,
  51720. const Image* im,
  51721. const Colour& textColour_,
  51722. const bool usesColour_,
  51723. PopupMenuCustomComponent* const customComp_,
  51724. const PopupMenu* const subMenu_,
  51725. ApplicationCommandManager* const commandManager_) throw()
  51726. : itemId (itemId_),
  51727. text (text_),
  51728. textColour (textColour_),
  51729. active (active_),
  51730. isSeparator (false),
  51731. isTicked (isTicked_),
  51732. usesColour (usesColour_),
  51733. image (0),
  51734. customComp (customComp_),
  51735. commandManager (commandManager_)
  51736. {
  51737. subMenu = (subMenu_ != 0) ? new PopupMenu (*subMenu_) : 0;
  51738. if (customComp != 0)
  51739. customComp->refCount_++;
  51740. if (im != 0)
  51741. image = im->createCopy();
  51742. if (commandManager_ != 0 && itemId_ != 0)
  51743. {
  51744. String shortcutKey;
  51745. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  51746. ->getKeyPressesAssignedToCommand (itemId_));
  51747. for (int i = 0; i < keyPresses.size(); ++i)
  51748. {
  51749. const String key (keyPresses.getReference(i).getTextDescription());
  51750. if (shortcutKey.isNotEmpty())
  51751. shortcutKey << ", ";
  51752. if (key.length() == 1)
  51753. shortcutKey << "shortcut: '" << key << '\'';
  51754. else
  51755. shortcutKey << key;
  51756. }
  51757. shortcutKey = shortcutKey.trim();
  51758. if (shortcutKey.isNotEmpty())
  51759. text << "<end>" << shortcutKey;
  51760. }
  51761. }
  51762. MenuItemInfo (const MenuItemInfo& other) throw()
  51763. : itemId (other.itemId),
  51764. text (other.text),
  51765. textColour (other.textColour),
  51766. active (other.active),
  51767. isSeparator (other.isSeparator),
  51768. isTicked (other.isTicked),
  51769. usesColour (other.usesColour),
  51770. customComp (other.customComp),
  51771. commandManager (other.commandManager)
  51772. {
  51773. if (other.subMenu != 0)
  51774. subMenu = new PopupMenu (*(other.subMenu));
  51775. else
  51776. subMenu = 0;
  51777. if (other.image != 0)
  51778. image = other.image->createCopy();
  51779. else
  51780. image = 0;
  51781. if (customComp != 0)
  51782. customComp->refCount_++;
  51783. }
  51784. ~MenuItemInfo() throw()
  51785. {
  51786. delete subMenu;
  51787. delete image;
  51788. if (customComp != 0 && --(customComp->refCount_) == 0)
  51789. delete customComp;
  51790. }
  51791. bool canBeTriggered() const throw()
  51792. {
  51793. return active && ! (isSeparator || (subMenu != 0));
  51794. }
  51795. bool hasActiveSubMenu() const throw()
  51796. {
  51797. return active && (subMenu != 0);
  51798. }
  51799. juce_UseDebuggingNewOperator
  51800. private:
  51801. const MenuItemInfo& operator= (const MenuItemInfo&);
  51802. };
  51803. class MenuItemComponent : public Component
  51804. {
  51805. bool isHighlighted;
  51806. public:
  51807. MenuItemInfo itemInfo;
  51808. MenuItemComponent (const MenuItemInfo& itemInfo_)
  51809. : isHighlighted (false),
  51810. itemInfo (itemInfo_)
  51811. {
  51812. if (itemInfo.customComp != 0)
  51813. addAndMakeVisible (itemInfo.customComp);
  51814. }
  51815. ~MenuItemComponent()
  51816. {
  51817. if (itemInfo.customComp != 0)
  51818. removeChildComponent (itemInfo.customComp);
  51819. }
  51820. void getIdealSize (int& idealWidth,
  51821. int& idealHeight,
  51822. const int standardItemHeight)
  51823. {
  51824. if (itemInfo.customComp != 0)
  51825. {
  51826. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  51827. }
  51828. else
  51829. {
  51830. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  51831. itemInfo.isSeparator,
  51832. standardItemHeight,
  51833. idealWidth,
  51834. idealHeight);
  51835. }
  51836. }
  51837. void paint (Graphics& g)
  51838. {
  51839. if (itemInfo.customComp == 0)
  51840. {
  51841. String mainText (itemInfo.text);
  51842. String endText;
  51843. const int endIndex = mainText.indexOf (T("<end>"));
  51844. if (endIndex >= 0)
  51845. {
  51846. endText = mainText.substring (endIndex + 5).trim();
  51847. mainText = mainText.substring (0, endIndex);
  51848. }
  51849. getLookAndFeel()
  51850. .drawPopupMenuItem (g, getWidth(), getHeight(),
  51851. itemInfo.isSeparator,
  51852. itemInfo.active,
  51853. isHighlighted,
  51854. itemInfo.isTicked,
  51855. itemInfo.subMenu != 0,
  51856. mainText, endText,
  51857. itemInfo.image,
  51858. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  51859. }
  51860. }
  51861. void resized()
  51862. {
  51863. if (getNumChildComponents() > 0)
  51864. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  51865. }
  51866. void setHighlighted (bool shouldBeHighlighted)
  51867. {
  51868. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  51869. if (isHighlighted != shouldBeHighlighted)
  51870. {
  51871. isHighlighted = shouldBeHighlighted;
  51872. if (itemInfo.customComp != 0)
  51873. {
  51874. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  51875. itemInfo.customComp->repaint();
  51876. }
  51877. repaint();
  51878. }
  51879. }
  51880. private:
  51881. MenuItemComponent (const MenuItemComponent&);
  51882. const MenuItemComponent& operator= (const MenuItemComponent&);
  51883. };
  51884. static const int scrollZone = 24;
  51885. static const int borderSize = 2;
  51886. static const int timerInterval = 50;
  51887. static const int dismissCommandId = 0x6287345f;
  51888. static bool wasHiddenBecauseOfAppChange = false;
  51889. class PopupMenuWindow : public Component,
  51890. private Timer
  51891. {
  51892. public:
  51893. PopupMenuWindow() throw()
  51894. : Component (T("menu")),
  51895. owner (0),
  51896. currentChild (0),
  51897. activeSubMenu (0),
  51898. menuBarComponent (0),
  51899. managerOfChosenCommand (0),
  51900. componentAttachedTo (0),
  51901. attachedCompWatcher (0),
  51902. lastMouseX (0),
  51903. lastMouseY (0),
  51904. minimumWidth (0),
  51905. maximumNumColumns (7),
  51906. standardItemHeight (0),
  51907. isOver (false),
  51908. hasBeenOver (false),
  51909. isDown (false),
  51910. needsToScroll (false),
  51911. hideOnExit (false),
  51912. disableMouseMoves (false),
  51913. hasAnyJuceCompHadFocus (false),
  51914. numColumns (0),
  51915. contentHeight (0),
  51916. childYOffset (0),
  51917. timeEnteredCurrentChildComp (0),
  51918. scrollAcceleration (1.0)
  51919. {
  51920. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  51921. setWantsKeyboardFocus (true);
  51922. setMouseClickGrabsKeyboardFocus (false);
  51923. setOpaque (true);
  51924. setAlwaysOnTop (true);
  51925. Desktop::getInstance().addGlobalMouseListener (this);
  51926. activeMenuWindows.add (this);
  51927. }
  51928. ~PopupMenuWindow()
  51929. {
  51930. activeMenuWindows.removeValue (this);
  51931. Desktop::getInstance().removeGlobalMouseListener (this);
  51932. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  51933. delete activeSubMenu;
  51934. deleteAllChildren();
  51935. delete attachedCompWatcher;
  51936. }
  51937. static PopupMenuWindow* create (const PopupMenu& menu,
  51938. const bool dismissOnMouseUp,
  51939. PopupMenuWindow* const owner_,
  51940. const int minX, const int maxX,
  51941. const int minY, const int maxY,
  51942. const int minimumWidth,
  51943. const int maximumNumColumns,
  51944. const int standardItemHeight,
  51945. const bool alignToRectangle,
  51946. const int itemIdThatMustBeVisible,
  51947. Component* const menuBarComponent,
  51948. ApplicationCommandManager** managerOfChosenCommand,
  51949. Component* const componentAttachedTo) throw()
  51950. {
  51951. if (menu.items.size() > 0)
  51952. {
  51953. int totalItems = 0;
  51954. PopupMenuWindow* const mw = new PopupMenuWindow();
  51955. mw->setLookAndFeel (menu.lookAndFeel);
  51956. mw->setWantsKeyboardFocus (false);
  51957. mw->minimumWidth = minimumWidth;
  51958. mw->maximumNumColumns = maximumNumColumns;
  51959. mw->standardItemHeight = standardItemHeight;
  51960. mw->dismissOnMouseUp = dismissOnMouseUp;
  51961. for (int i = 0; i < menu.items.size(); ++i)
  51962. {
  51963. MenuItemInfo* const item = (MenuItemInfo*) menu.items.getUnchecked(i);
  51964. mw->addItem (*item);
  51965. ++totalItems;
  51966. }
  51967. if (totalItems == 0)
  51968. {
  51969. delete mw;
  51970. }
  51971. else
  51972. {
  51973. mw->owner = owner_;
  51974. mw->menuBarComponent = menuBarComponent;
  51975. mw->managerOfChosenCommand = managerOfChosenCommand;
  51976. mw->componentAttachedTo = componentAttachedTo;
  51977. delete mw->attachedCompWatcher;
  51978. mw->attachedCompWatcher = componentAttachedTo != 0 ? new ComponentDeletionWatcher (componentAttachedTo) : 0;
  51979. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  51980. mw->setTopLeftPosition (mw->windowPos.getX(),
  51981. mw->windowPos.getY());
  51982. mw->updateYPositions();
  51983. if (itemIdThatMustBeVisible != 0)
  51984. {
  51985. const int y = minY - mw->windowPos.getY();
  51986. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  51987. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  51988. }
  51989. mw->resizeToBestWindowPos();
  51990. mw->addToDesktop (ComponentPeer::windowIsTemporary
  51991. | mw->getLookAndFeel().getMenuWindowFlags());
  51992. return mw;
  51993. }
  51994. }
  51995. return 0;
  51996. }
  51997. void paint (Graphics& g)
  51998. {
  51999. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  52000. }
  52001. void paintOverChildren (Graphics& g)
  52002. {
  52003. if (isScrolling())
  52004. {
  52005. LookAndFeel& lf = getLookAndFeel();
  52006. if (isScrollZoneActive (false))
  52007. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, true);
  52008. if (isScrollZoneActive (true))
  52009. {
  52010. g.setOrigin (0, getHeight() - scrollZone);
  52011. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, false);
  52012. }
  52013. }
  52014. }
  52015. bool isScrollZoneActive (bool bottomOne) const
  52016. {
  52017. return isScrolling()
  52018. && (bottomOne
  52019. ? childYOffset < contentHeight - windowPos.getHeight()
  52020. : childYOffset > 0);
  52021. }
  52022. void addItem (const MenuItemInfo& item) throw()
  52023. {
  52024. MenuItemComponent* const mic = new MenuItemComponent (item);
  52025. addAndMakeVisible (mic);
  52026. int itemW = 80;
  52027. int itemH = 16;
  52028. mic->getIdealSize (itemW, itemH, standardItemHeight);
  52029. mic->setSize (itemW, jlimit (2, 600, itemH));
  52030. mic->addMouseListener (this, false);
  52031. }
  52032. // hide this and all sub-comps
  52033. void hide (const MenuItemInfo* const item) throw()
  52034. {
  52035. if (isVisible())
  52036. {
  52037. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52038. deleteAndZero (activeSubMenu);
  52039. currentChild = 0;
  52040. exitModalState (item != 0 ? item->itemId : 0);
  52041. setVisible (false);
  52042. if (item != 0
  52043. && item->commandManager != 0
  52044. && item->itemId != 0)
  52045. {
  52046. *managerOfChosenCommand = item->commandManager;
  52047. }
  52048. }
  52049. }
  52050. void dismissMenu (const MenuItemInfo* const item) throw()
  52051. {
  52052. if (owner != 0)
  52053. {
  52054. owner->dismissMenu (item);
  52055. }
  52056. else
  52057. {
  52058. if (item != 0)
  52059. {
  52060. // need a copy of this on the stack as the one passed in will get deleted during this call
  52061. const MenuItemInfo mi (*item);
  52062. hide (&mi);
  52063. }
  52064. else
  52065. {
  52066. hide (0);
  52067. }
  52068. }
  52069. }
  52070. void mouseMove (const MouseEvent&)
  52071. {
  52072. timerCallback();
  52073. }
  52074. void mouseDown (const MouseEvent&)
  52075. {
  52076. timerCallback();
  52077. }
  52078. void mouseDrag (const MouseEvent&)
  52079. {
  52080. timerCallback();
  52081. }
  52082. void mouseUp (const MouseEvent&)
  52083. {
  52084. timerCallback();
  52085. }
  52086. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  52087. {
  52088. alterChildYPos (roundFloatToInt (-10.0f * amountY * scrollZone));
  52089. lastMouseX = -1;
  52090. }
  52091. bool keyPressed (const KeyPress& key)
  52092. {
  52093. if (key.isKeyCode (KeyPress::downKey))
  52094. {
  52095. selectNextItem (1);
  52096. }
  52097. else if (key.isKeyCode (KeyPress::upKey))
  52098. {
  52099. selectNextItem (-1);
  52100. }
  52101. else if (key.isKeyCode (KeyPress::leftKey))
  52102. {
  52103. PopupMenuWindow* parentWindow = owner;
  52104. if (parentWindow != 0)
  52105. {
  52106. MenuItemComponent* currentChildOfParent
  52107. = (parentWindow != 0) ? parentWindow->currentChild : 0;
  52108. hide (0);
  52109. if (parentWindow->isValidComponent())
  52110. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  52111. disableTimerUntilMouseMoves();
  52112. }
  52113. else if (menuBarComponent != 0)
  52114. {
  52115. menuBarComponent->keyPressed (key);
  52116. }
  52117. }
  52118. else if (key.isKeyCode (KeyPress::rightKey))
  52119. {
  52120. disableTimerUntilMouseMoves();
  52121. if (showSubMenuFor (currentChild))
  52122. {
  52123. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52124. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  52125. activeSubMenu->selectNextItem (1);
  52126. }
  52127. else if (menuBarComponent != 0)
  52128. {
  52129. menuBarComponent->keyPressed (key);
  52130. }
  52131. }
  52132. else if (key.isKeyCode (KeyPress::returnKey))
  52133. {
  52134. triggerCurrentlyHighlightedItem();
  52135. }
  52136. else if (key.isKeyCode (KeyPress::escapeKey))
  52137. {
  52138. dismissMenu (0);
  52139. }
  52140. else
  52141. {
  52142. return false;
  52143. }
  52144. return true;
  52145. }
  52146. void inputAttemptWhenModal()
  52147. {
  52148. timerCallback();
  52149. if (! isOverAnyMenu())
  52150. {
  52151. if (componentAttachedTo != 0 && ! attachedCompWatcher->hasBeenDeleted())
  52152. {
  52153. // we want to dismiss the menu, but if we do it synchronously, then
  52154. // the mouse-click will be allowed to pass through. That's good, except
  52155. // when the user clicks on the button that orginally popped the menu up,
  52156. // as they'll expect the menu to go away, and in fact it'll just
  52157. // come back. So only dismiss synchronously if they're not on the original
  52158. // comp that we're attached to.
  52159. int mx, my;
  52160. componentAttachedTo->getMouseXYRelative (mx, my);
  52161. if (componentAttachedTo->reallyContains (mx, my, true))
  52162. {
  52163. postCommandMessage (dismissCommandId); // dismiss asynchrounously
  52164. return;
  52165. }
  52166. }
  52167. dismissMenu (0);
  52168. }
  52169. }
  52170. void handleCommandMessage (int commandId)
  52171. {
  52172. Component::handleCommandMessage (commandId);
  52173. if (commandId == dismissCommandId)
  52174. dismissMenu (0);
  52175. }
  52176. void timerCallback()
  52177. {
  52178. if (! isVisible())
  52179. return;
  52180. if (attachedCompWatcher != 0 && attachedCompWatcher->hasBeenDeleted())
  52181. {
  52182. dismissMenu (0);
  52183. return;
  52184. }
  52185. PopupMenuWindow* currentlyModalWindow = dynamic_cast <PopupMenuWindow*> (Component::getCurrentlyModalComponent());
  52186. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  52187. return;
  52188. startTimer (timerInterval); // do this in case it was called from a mouse
  52189. // move rather than a real timer callback
  52190. int mx, my;
  52191. Desktop::getMousePosition (mx, my);
  52192. int x = mx, y = my;
  52193. globalPositionToRelative (x, y);
  52194. const uint32 now = Time::getMillisecondCounter();
  52195. if (now > timeEnteredCurrentChildComp + 100
  52196. && reallyContains (x, y, true)
  52197. && currentChild->isValidComponent()
  52198. && (! disableMouseMoves)
  52199. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  52200. {
  52201. showSubMenuFor (currentChild);
  52202. }
  52203. if (mx != lastMouseX || my != lastMouseY || now > lastMouseMoveTime + 350)
  52204. {
  52205. highlightItemUnderMouse (mx, my, x, y);
  52206. }
  52207. bool overScrollArea = false;
  52208. if (isScrolling()
  52209. && (isOver || (isDown && ((unsigned int) x) < (unsigned int) getWidth()))
  52210. && ((isScrollZoneActive (false) && y < scrollZone)
  52211. || (isScrollZoneActive (true) && y > getHeight() - scrollZone)))
  52212. {
  52213. if (now > lastScroll + 20)
  52214. {
  52215. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  52216. int amount = 0;
  52217. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  52218. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  52219. alterChildYPos (y < scrollZone ? -amount : amount);
  52220. lastScroll = now;
  52221. }
  52222. overScrollArea = true;
  52223. lastMouseX = -1; // trigger a mouse-move
  52224. }
  52225. else
  52226. {
  52227. scrollAcceleration = 1.0;
  52228. }
  52229. const bool wasDown = isDown;
  52230. bool isOverAny = isOverAnyMenu();
  52231. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  52232. {
  52233. activeSubMenu->updateMouseOverStatus (mx, my);
  52234. isOverAny = isOverAnyMenu();
  52235. }
  52236. if (hideOnExit && hasBeenOver && ! isOverAny)
  52237. {
  52238. hide (0);
  52239. }
  52240. else
  52241. {
  52242. isDown = hasBeenOver
  52243. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  52244. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  52245. bool anyFocused = Process::isForegroundProcess();
  52246. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  52247. {
  52248. // because no component at all may have focus, our test here will
  52249. // only be triggered when something has focus and then loses it.
  52250. anyFocused = ! hasAnyJuceCompHadFocus;
  52251. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  52252. {
  52253. if (ComponentPeer::getPeer (i)->isFocused())
  52254. {
  52255. anyFocused = true;
  52256. hasAnyJuceCompHadFocus = true;
  52257. break;
  52258. }
  52259. }
  52260. }
  52261. if (! anyFocused)
  52262. {
  52263. if (now > lastFocused + 10)
  52264. {
  52265. wasHiddenBecauseOfAppChange = true;
  52266. dismissMenu (0);
  52267. return; // may have been deleted by the previous call..
  52268. }
  52269. }
  52270. else if (wasDown && now > menuCreationTime + 250
  52271. && ! (isDown || overScrollArea))
  52272. {
  52273. isOver = reallyContains (x, y, true);
  52274. if (isOver)
  52275. {
  52276. triggerCurrentlyHighlightedItem();
  52277. }
  52278. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  52279. {
  52280. dismissMenu (0);
  52281. }
  52282. return; // may have been deleted by the previous calls..
  52283. }
  52284. else
  52285. {
  52286. lastFocused = now;
  52287. }
  52288. }
  52289. }
  52290. juce_UseDebuggingNewOperator
  52291. private:
  52292. PopupMenuWindow* owner;
  52293. MenuItemComponent* currentChild;
  52294. PopupMenuWindow* activeSubMenu;
  52295. Component* menuBarComponent;
  52296. ApplicationCommandManager** managerOfChosenCommand;
  52297. Component* componentAttachedTo;
  52298. ComponentDeletionWatcher* attachedCompWatcher;
  52299. Rectangle windowPos;
  52300. int lastMouseX, lastMouseY;
  52301. int minimumWidth, maximumNumColumns, standardItemHeight;
  52302. bool isOver, hasBeenOver, isDown, needsToScroll;
  52303. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  52304. int numColumns, contentHeight, childYOffset;
  52305. Array <int> columnWidths;
  52306. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  52307. double scrollAcceleration;
  52308. bool overlaps (const Rectangle& r) const throw()
  52309. {
  52310. return r.intersects (getBounds())
  52311. || (owner != 0 && owner->overlaps (r));
  52312. }
  52313. bool isOverAnyMenu() const throw()
  52314. {
  52315. return (owner != 0) ? owner->isOverAnyMenu()
  52316. : isOverChildren();
  52317. }
  52318. bool isOverChildren() const throw()
  52319. {
  52320. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52321. return isVisible()
  52322. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  52323. }
  52324. void updateMouseOverStatus (const int mx, const int my) throw()
  52325. {
  52326. int rx = mx, ry = my;
  52327. globalPositionToRelative (rx, ry);
  52328. isOver = reallyContains (rx, ry, true);
  52329. if (activeSubMenu != 0)
  52330. activeSubMenu->updateMouseOverStatus (mx, my);
  52331. }
  52332. bool treeContains (const PopupMenuWindow* const window) const throw()
  52333. {
  52334. const PopupMenuWindow* mw = this;
  52335. while (mw->owner != 0)
  52336. mw = mw->owner;
  52337. while (mw != 0)
  52338. {
  52339. if (mw == window)
  52340. return true;
  52341. mw = mw->activeSubMenu;
  52342. }
  52343. return false;
  52344. }
  52345. void calculateWindowPos (const int minX, const int maxX,
  52346. const int minY, const int maxY,
  52347. const bool alignToRectangle)
  52348. {
  52349. const Rectangle mon (Desktop::getInstance()
  52350. .getMonitorAreaContaining ((minX + maxX) / 2,
  52351. (minY + maxY) / 2,
  52352. #if JUCE_MAC
  52353. true));
  52354. #else
  52355. false)); // on windows, don't stop the menu overlapping the taskbar
  52356. #endif
  52357. int x, y, widthToUse, heightToUse;
  52358. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  52359. if (alignToRectangle)
  52360. {
  52361. x = minX;
  52362. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  52363. const int spaceOver = minY - mon.getY();
  52364. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  52365. y = maxY;
  52366. else
  52367. y = minY - heightToUse;
  52368. }
  52369. else
  52370. {
  52371. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  52372. if (owner != 0)
  52373. {
  52374. if (owner->owner != 0)
  52375. {
  52376. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  52377. > owner->owner->getX() + owner->owner->getWidth() / 2);
  52378. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  52379. tendTowardsRight = true;
  52380. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  52381. tendTowardsRight = false;
  52382. }
  52383. else if (maxX + widthToUse < mon.getRight() - 32)
  52384. {
  52385. tendTowardsRight = true;
  52386. }
  52387. }
  52388. const int biggestSpace = jmax (mon.getRight() - maxX,
  52389. minX - mon.getX()) - 32;
  52390. if (biggestSpace < widthToUse)
  52391. {
  52392. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  52393. if (numColumns > 1)
  52394. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  52395. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  52396. }
  52397. if (tendTowardsRight)
  52398. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  52399. else
  52400. x = jmax (mon.getX() + 4, minX - widthToUse);
  52401. y = minY;
  52402. if ((minY + maxY) / 2 > mon.getCentreY())
  52403. y = jmax (mon.getY(), maxY - heightToUse);
  52404. }
  52405. x = jlimit (mon.getX() + 1, mon.getRight() - (widthToUse + 6), x);
  52406. y = jlimit (mon.getY() + 1, mon.getBottom() - (heightToUse + 6), y);
  52407. windowPos.setBounds (x, y, widthToUse, heightToUse);
  52408. // sets this flag if it's big enough to obscure any of its parent menus
  52409. hideOnExit = (owner != 0)
  52410. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  52411. }
  52412. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  52413. {
  52414. numColumns = 0;
  52415. contentHeight = 0;
  52416. const int maxMenuH = getParentHeight() - 24;
  52417. int totalW;
  52418. do
  52419. {
  52420. ++numColumns;
  52421. totalW = workOutBestSize (numColumns, maxMenuW);
  52422. if (totalW > maxMenuW)
  52423. {
  52424. numColumns = jmax (1, numColumns - 1);
  52425. totalW = workOutBestSize (numColumns, maxMenuW); // to update col widths
  52426. break;
  52427. }
  52428. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  52429. {
  52430. break;
  52431. }
  52432. } while (numColumns < maximumNumColumns);
  52433. const int actualH = jmin (contentHeight, maxMenuH);
  52434. needsToScroll = contentHeight > actualH;
  52435. width = updateYPositions();
  52436. height = actualH + borderSize * 2;
  52437. }
  52438. int workOutBestSize (const int numColumns, const int maxMenuW)
  52439. {
  52440. int totalW = 0;
  52441. contentHeight = 0;
  52442. int childNum = 0;
  52443. for (int col = 0; col < numColumns; ++col)
  52444. {
  52445. int i, colW = 50, colH = 0;
  52446. const int numChildren = jmin (getNumChildComponents() - childNum,
  52447. (getNumChildComponents() + numColumns - 1) / numColumns);
  52448. for (i = numChildren; --i >= 0;)
  52449. {
  52450. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  52451. colH += getChildComponent (childNum + i)->getHeight();
  52452. }
  52453. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + borderSize * 2);
  52454. columnWidths.set (col, colW);
  52455. totalW += colW;
  52456. contentHeight = jmax (contentHeight, colH);
  52457. childNum += numChildren;
  52458. }
  52459. if (totalW < minimumWidth)
  52460. {
  52461. totalW = minimumWidth;
  52462. for (int col = 0; col < numColumns; ++col)
  52463. columnWidths.set (0, totalW / numColumns);
  52464. }
  52465. return totalW;
  52466. }
  52467. void ensureItemIsVisible (const int itemId, int wantedY)
  52468. {
  52469. jassert (itemId != 0)
  52470. for (int i = getNumChildComponents(); --i >= 0;)
  52471. {
  52472. MenuItemComponent* const m = (MenuItemComponent*) getChildComponent (i);
  52473. if (m != 0
  52474. && m->itemInfo.itemId == itemId
  52475. && windowPos.getHeight() > scrollZone * 4)
  52476. {
  52477. const int currentY = m->getY();
  52478. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  52479. {
  52480. if (wantedY < 0)
  52481. wantedY = jlimit (scrollZone,
  52482. jmax (scrollZone, windowPos.getHeight() - (scrollZone + m->getHeight())),
  52483. currentY);
  52484. const Rectangle mon (Desktop::getInstance()
  52485. .getMonitorAreaContaining (windowPos.getX(),
  52486. windowPos.getY(),
  52487. true));
  52488. int deltaY = wantedY - currentY;
  52489. const int newY = jlimit (mon.getY(),
  52490. mon.getBottom() - windowPos.getHeight(),
  52491. windowPos.getY() + deltaY);
  52492. deltaY -= newY - windowPos.getY();
  52493. childYOffset -= deltaY;
  52494. windowPos.setPosition (windowPos.getX(), newY);
  52495. updateYPositions();
  52496. }
  52497. break;
  52498. }
  52499. }
  52500. }
  52501. void resizeToBestWindowPos()
  52502. {
  52503. Rectangle r (windowPos);
  52504. if (childYOffset < 0)
  52505. {
  52506. r.setBounds (r.getX(), r.getY() - childYOffset,
  52507. r.getWidth(), r.getHeight() + childYOffset);
  52508. }
  52509. else if (childYOffset > 0)
  52510. {
  52511. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  52512. if (spaceAtBottom > 0)
  52513. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  52514. }
  52515. setBounds (r);
  52516. updateYPositions();
  52517. }
  52518. void alterChildYPos (const int delta)
  52519. {
  52520. if (isScrolling())
  52521. {
  52522. childYOffset += delta;
  52523. if (delta < 0)
  52524. {
  52525. childYOffset = jmax (childYOffset, 0);
  52526. }
  52527. else if (delta > 0)
  52528. {
  52529. childYOffset = jmin (childYOffset,
  52530. contentHeight - windowPos.getHeight() + borderSize);
  52531. }
  52532. updateYPositions();
  52533. }
  52534. else
  52535. {
  52536. childYOffset = 0;
  52537. }
  52538. resizeToBestWindowPos();
  52539. repaint();
  52540. }
  52541. int updateYPositions()
  52542. {
  52543. int x = 0;
  52544. int childNum = 0;
  52545. for (int col = 0; col < numColumns; ++col)
  52546. {
  52547. const int numChildren = jmin (getNumChildComponents() - childNum,
  52548. (getNumChildComponents() + numColumns - 1) / numColumns);
  52549. const int colW = columnWidths [col];
  52550. int y = borderSize - (childYOffset + (getY() - windowPos.getY()));
  52551. for (int i = 0; i < numChildren; ++i)
  52552. {
  52553. Component* const c = getChildComponent (childNum + i);
  52554. c->setBounds (x, y, colW, c->getHeight());
  52555. y += c->getHeight();
  52556. }
  52557. x += colW;
  52558. childNum += numChildren;
  52559. }
  52560. return x;
  52561. }
  52562. bool isScrolling() const throw()
  52563. {
  52564. return childYOffset != 0 || needsToScroll;
  52565. }
  52566. void setCurrentlyHighlightedChild (MenuItemComponent* const child) throw()
  52567. {
  52568. if (currentChild->isValidComponent())
  52569. currentChild->setHighlighted (false);
  52570. currentChild = child;
  52571. if (currentChild != 0)
  52572. {
  52573. currentChild->setHighlighted (true);
  52574. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  52575. }
  52576. }
  52577. bool showSubMenuFor (MenuItemComponent* const childComp)
  52578. {
  52579. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52580. deleteAndZero (activeSubMenu);
  52581. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  52582. {
  52583. int left = 0, top = 0;
  52584. childComp->relativePositionToGlobal (left, top);
  52585. int right = childComp->getWidth(), bottom = childComp->getHeight();
  52586. childComp->relativePositionToGlobal (right, bottom);
  52587. activeSubMenu = PopupMenuWindow::create (*(childComp->itemInfo.subMenu),
  52588. dismissOnMouseUp,
  52589. this,
  52590. left, right, top, bottom,
  52591. 0, maximumNumColumns,
  52592. standardItemHeight,
  52593. false, 0, menuBarComponent,
  52594. managerOfChosenCommand,
  52595. componentAttachedTo);
  52596. if (activeSubMenu != 0)
  52597. {
  52598. activeSubMenu->setVisible (true);
  52599. activeSubMenu->enterModalState (false);
  52600. activeSubMenu->toFront (false);
  52601. return true;
  52602. }
  52603. }
  52604. return false;
  52605. }
  52606. void highlightItemUnderMouse (const int mx, const int my, const int x, const int y)
  52607. {
  52608. isOver = reallyContains (x, y, true);
  52609. if (isOver)
  52610. hasBeenOver = true;
  52611. if (abs (lastMouseX - mx) > 2 || abs (lastMouseY - my) > 2)
  52612. {
  52613. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  52614. if (disableMouseMoves && isOver)
  52615. disableMouseMoves = false;
  52616. }
  52617. if (disableMouseMoves)
  52618. return;
  52619. bool isMovingTowardsMenu = false;
  52620. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  52621. if (isOver && (activeSubMenu != 0) && (mx != lastMouseX || my != lastMouseY))
  52622. {
  52623. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  52624. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  52625. // extends from the last mouse pos to the submenu's rectangle..
  52626. float subX = (float) activeSubMenu->getScreenX();
  52627. if (activeSubMenu->getX() > getX())
  52628. {
  52629. lastMouseX -= 2; // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  52630. }
  52631. else
  52632. {
  52633. lastMouseX += 2;
  52634. subX += activeSubMenu->getWidth();
  52635. }
  52636. Path areaTowardsSubMenu;
  52637. areaTowardsSubMenu.addTriangle ((float) lastMouseX,
  52638. (float) lastMouseY,
  52639. subX,
  52640. (float) activeSubMenu->getScreenY(),
  52641. subX,
  52642. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  52643. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) mx, (float) my);
  52644. }
  52645. lastMouseX = mx;
  52646. lastMouseY = my;
  52647. if (! isMovingTowardsMenu)
  52648. {
  52649. Component* c = getComponentAt (x, y);
  52650. if (c == this)
  52651. c = 0;
  52652. MenuItemComponent* mic = dynamic_cast <MenuItemComponent*> (c);
  52653. if (mic == 0 && c != 0)
  52654. mic = c->findParentComponentOfClass ((MenuItemComponent*) 0);
  52655. if (mic != currentChild
  52656. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  52657. {
  52658. if (isOver && (c != 0) && (activeSubMenu != 0))
  52659. {
  52660. activeSubMenu->hide (0);
  52661. }
  52662. if (! isOver)
  52663. mic = 0;
  52664. setCurrentlyHighlightedChild (mic);
  52665. }
  52666. }
  52667. }
  52668. void triggerCurrentlyHighlightedItem()
  52669. {
  52670. if (currentChild->isValidComponent()
  52671. && currentChild->itemInfo.canBeTriggered()
  52672. && (currentChild->itemInfo.customComp == 0
  52673. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  52674. {
  52675. dismissMenu (&currentChild->itemInfo);
  52676. }
  52677. }
  52678. void selectNextItem (const int delta)
  52679. {
  52680. disableTimerUntilMouseMoves();
  52681. MenuItemComponent* mic = 0;
  52682. bool wasLastOne = (currentChild == 0);
  52683. const int numItems = getNumChildComponents();
  52684. for (int i = 0; i < numItems + 1; ++i)
  52685. {
  52686. int index = (delta > 0) ? i : (numItems - 1 - i);
  52687. index = (index + numItems) % numItems;
  52688. mic = dynamic_cast <MenuItemComponent*> (getChildComponent (index));
  52689. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  52690. && wasLastOne)
  52691. break;
  52692. if (mic == currentChild)
  52693. wasLastOne = true;
  52694. }
  52695. setCurrentlyHighlightedChild (mic);
  52696. }
  52697. void disableTimerUntilMouseMoves() throw()
  52698. {
  52699. disableMouseMoves = true;
  52700. if (owner != 0)
  52701. owner->disableTimerUntilMouseMoves();
  52702. }
  52703. PopupMenuWindow (const PopupMenuWindow&);
  52704. const PopupMenuWindow& operator= (const PopupMenuWindow&);
  52705. };
  52706. PopupMenu::PopupMenu() throw()
  52707. : items (8),
  52708. lookAndFeel (0),
  52709. separatorPending (false)
  52710. {
  52711. }
  52712. PopupMenu::PopupMenu (const PopupMenu& other) throw()
  52713. : items (8),
  52714. lookAndFeel (other.lookAndFeel),
  52715. separatorPending (false)
  52716. {
  52717. items.ensureStorageAllocated (other.items.size());
  52718. for (int i = 0; i < other.items.size(); ++i)
  52719. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  52720. }
  52721. const PopupMenu& PopupMenu::operator= (const PopupMenu& other) throw()
  52722. {
  52723. if (this != &other)
  52724. {
  52725. lookAndFeel = other.lookAndFeel;
  52726. clear();
  52727. items.ensureStorageAllocated (other.items.size());
  52728. for (int i = 0; i < other.items.size(); ++i)
  52729. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  52730. }
  52731. return *this;
  52732. }
  52733. PopupMenu::~PopupMenu() throw()
  52734. {
  52735. clear();
  52736. }
  52737. void PopupMenu::clear() throw()
  52738. {
  52739. for (int i = items.size(); --i >= 0;)
  52740. {
  52741. MenuItemInfo* const mi = (MenuItemInfo*) items.getUnchecked(i);
  52742. delete mi;
  52743. }
  52744. items.clear();
  52745. separatorPending = false;
  52746. }
  52747. void PopupMenu::addSeparatorIfPending()
  52748. {
  52749. if (separatorPending)
  52750. {
  52751. separatorPending = false;
  52752. if (items.size() > 0)
  52753. items.add (new MenuItemInfo());
  52754. }
  52755. }
  52756. void PopupMenu::addItem (const int itemResultId,
  52757. const String& itemText,
  52758. const bool isActive,
  52759. const bool isTicked,
  52760. const Image* const iconToUse) throw()
  52761. {
  52762. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  52763. // didn't pick anything, so you shouldn't use it as the id
  52764. // for an item..
  52765. addSeparatorIfPending();
  52766. items.add (new MenuItemInfo (itemResultId,
  52767. itemText,
  52768. isActive,
  52769. isTicked,
  52770. iconToUse,
  52771. Colours::black,
  52772. false,
  52773. 0, 0, 0));
  52774. }
  52775. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  52776. const int commandID,
  52777. const String& displayName) throw()
  52778. {
  52779. jassert (commandManager != 0 && commandID != 0);
  52780. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  52781. if (registeredInfo != 0)
  52782. {
  52783. ApplicationCommandInfo info (*registeredInfo);
  52784. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  52785. addSeparatorIfPending();
  52786. items.add (new MenuItemInfo (commandID,
  52787. displayName.isNotEmpty() ? displayName
  52788. : info.shortName,
  52789. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  52790. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  52791. 0,
  52792. Colours::black,
  52793. false,
  52794. 0, 0,
  52795. commandManager));
  52796. }
  52797. }
  52798. void PopupMenu::addColouredItem (const int itemResultId,
  52799. const String& itemText,
  52800. const Colour& itemTextColour,
  52801. const bool isActive,
  52802. const bool isTicked,
  52803. const Image* const iconToUse) throw()
  52804. {
  52805. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  52806. // didn't pick anything, so you shouldn't use it as the id
  52807. // for an item..
  52808. addSeparatorIfPending();
  52809. items.add (new MenuItemInfo (itemResultId,
  52810. itemText,
  52811. isActive,
  52812. isTicked,
  52813. iconToUse,
  52814. itemTextColour,
  52815. true,
  52816. 0, 0, 0));
  52817. }
  52818. void PopupMenu::addCustomItem (const int itemResultId,
  52819. PopupMenuCustomComponent* const customComponent) throw()
  52820. {
  52821. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  52822. // didn't pick anything, so you shouldn't use it as the id
  52823. // for an item..
  52824. addSeparatorIfPending();
  52825. items.add (new MenuItemInfo (itemResultId,
  52826. String::empty,
  52827. true,
  52828. false,
  52829. 0,
  52830. Colours::black,
  52831. false,
  52832. customComponent,
  52833. 0, 0));
  52834. }
  52835. class NormalComponentWrapper : public PopupMenuCustomComponent
  52836. {
  52837. public:
  52838. NormalComponentWrapper (Component* const comp,
  52839. const int w, const int h,
  52840. const bool triggerMenuItemAutomaticallyWhenClicked)
  52841. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  52842. width (w),
  52843. height (h)
  52844. {
  52845. addAndMakeVisible (comp);
  52846. }
  52847. ~NormalComponentWrapper() {}
  52848. void getIdealSize (int& idealWidth, int& idealHeight)
  52849. {
  52850. idealWidth = width;
  52851. idealHeight = height;
  52852. }
  52853. void resized()
  52854. {
  52855. if (getChildComponent(0) != 0)
  52856. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  52857. }
  52858. juce_UseDebuggingNewOperator
  52859. private:
  52860. const int width, height;
  52861. NormalComponentWrapper (const NormalComponentWrapper&);
  52862. const NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  52863. };
  52864. void PopupMenu::addCustomItem (const int itemResultId,
  52865. Component* customComponent,
  52866. int idealWidth, int idealHeight,
  52867. const bool triggerMenuItemAutomaticallyWhenClicked) throw()
  52868. {
  52869. addCustomItem (itemResultId,
  52870. new NormalComponentWrapper (customComponent,
  52871. idealWidth, idealHeight,
  52872. triggerMenuItemAutomaticallyWhenClicked));
  52873. }
  52874. void PopupMenu::addSubMenu (const String& subMenuName,
  52875. const PopupMenu& subMenu,
  52876. const bool isActive,
  52877. Image* const iconToUse,
  52878. const bool isTicked) throw()
  52879. {
  52880. addSeparatorIfPending();
  52881. items.add (new MenuItemInfo (0,
  52882. subMenuName,
  52883. isActive && (subMenu.getNumItems() > 0),
  52884. isTicked,
  52885. iconToUse,
  52886. Colours::black,
  52887. false,
  52888. 0,
  52889. &subMenu,
  52890. 0));
  52891. }
  52892. void PopupMenu::addSeparator() throw()
  52893. {
  52894. separatorPending = true;
  52895. }
  52896. class HeaderItemComponent : public PopupMenuCustomComponent
  52897. {
  52898. public:
  52899. HeaderItemComponent (const String& name)
  52900. : PopupMenuCustomComponent (false)
  52901. {
  52902. setName (name);
  52903. }
  52904. ~HeaderItemComponent()
  52905. {
  52906. }
  52907. void paint (Graphics& g)
  52908. {
  52909. Font f (getLookAndFeel().getPopupMenuFont());
  52910. f.setBold (true);
  52911. g.setFont (f);
  52912. g.setColour (findColour (PopupMenu::headerTextColourId));
  52913. g.drawFittedText (getName(),
  52914. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  52915. Justification::bottomLeft, 1);
  52916. }
  52917. void getIdealSize (int& idealWidth,
  52918. int& idealHeight)
  52919. {
  52920. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  52921. idealHeight += idealHeight / 2;
  52922. idealWidth += idealWidth / 4;
  52923. }
  52924. juce_UseDebuggingNewOperator
  52925. };
  52926. void PopupMenu::addSectionHeader (const String& title) throw()
  52927. {
  52928. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  52929. }
  52930. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  52931. const int itemIdThatMustBeVisible,
  52932. const int minimumWidth,
  52933. const int maximumNumColumns,
  52934. const int standardItemHeight,
  52935. const bool alignToRectangle,
  52936. Component* menuBarComponent,
  52937. ApplicationCommandManager** managerOfChosenCommand,
  52938. Component* const componentAttachedTo) throw()
  52939. {
  52940. PopupMenuWindow* const pw
  52941. = PopupMenuWindow::create (*this,
  52942. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  52943. 0,
  52944. x, x + w,
  52945. y, y + h,
  52946. minimumWidth,
  52947. maximumNumColumns,
  52948. standardItemHeight,
  52949. alignToRectangle,
  52950. itemIdThatMustBeVisible,
  52951. menuBarComponent,
  52952. managerOfChosenCommand,
  52953. componentAttachedTo);
  52954. if (pw != 0)
  52955. pw->setVisible (true);
  52956. return pw;
  52957. }
  52958. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  52959. const int itemIdThatMustBeVisible,
  52960. const int minimumWidth,
  52961. const int maximumNumColumns,
  52962. const int standardItemHeight,
  52963. const bool alignToRectangle,
  52964. Component* const componentAttachedTo) throw()
  52965. {
  52966. Component* const prevFocused = Component::getCurrentlyFocusedComponent();
  52967. ComponentDeletionWatcher* deletionChecker1 = 0;
  52968. if (prevFocused != 0)
  52969. deletionChecker1 = new ComponentDeletionWatcher (prevFocused);
  52970. Component* const prevTopLevel = (prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0;
  52971. ComponentDeletionWatcher* deletionChecker2 = 0;
  52972. if (prevTopLevel != 0)
  52973. deletionChecker2 = new ComponentDeletionWatcher (prevTopLevel);
  52974. wasHiddenBecauseOfAppChange = false;
  52975. int result = 0;
  52976. ApplicationCommandManager* managerOfChosenCommand = 0;
  52977. Component* const popupComp = createMenuComponent (x, y, w, h,
  52978. itemIdThatMustBeVisible,
  52979. minimumWidth,
  52980. maximumNumColumns > 0 ? maximumNumColumns : 7,
  52981. standardItemHeight,
  52982. alignToRectangle, 0,
  52983. &managerOfChosenCommand,
  52984. componentAttachedTo);
  52985. if (popupComp != 0)
  52986. {
  52987. popupComp->enterModalState (false);
  52988. popupComp->toFront (false); // need to do this after making it modal, or it could
  52989. // be stuck behind other comps that are already modal..
  52990. result = popupComp->runModalLoop();
  52991. delete popupComp;
  52992. if (! wasHiddenBecauseOfAppChange)
  52993. {
  52994. if (deletionChecker2 != 0 && ! deletionChecker2->hasBeenDeleted())
  52995. prevTopLevel->toFront (true);
  52996. if (deletionChecker1 != 0 && ! deletionChecker1->hasBeenDeleted())
  52997. prevFocused->grabKeyboardFocus();
  52998. }
  52999. }
  53000. delete deletionChecker1;
  53001. delete deletionChecker2;
  53002. if (managerOfChosenCommand != 0 && result != 0)
  53003. {
  53004. ApplicationCommandTarget::InvocationInfo info (result);
  53005. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  53006. managerOfChosenCommand->invoke (info, true);
  53007. }
  53008. return result;
  53009. }
  53010. int PopupMenu::show (const int itemIdThatMustBeVisible,
  53011. const int minimumWidth,
  53012. const int maximumNumColumns,
  53013. const int standardItemHeight)
  53014. {
  53015. int x, y;
  53016. Desktop::getMousePosition (x, y);
  53017. return showAt (x, y,
  53018. itemIdThatMustBeVisible,
  53019. minimumWidth,
  53020. maximumNumColumns,
  53021. standardItemHeight);
  53022. }
  53023. int PopupMenu::showAt (const int screenX,
  53024. const int screenY,
  53025. const int itemIdThatMustBeVisible,
  53026. const int minimumWidth,
  53027. const int maximumNumColumns,
  53028. const int standardItemHeight)
  53029. {
  53030. return showMenu (screenX, screenY, 1, 1,
  53031. itemIdThatMustBeVisible,
  53032. minimumWidth, maximumNumColumns,
  53033. standardItemHeight,
  53034. false, 0);
  53035. }
  53036. int PopupMenu::showAt (Component* componentToAttachTo,
  53037. const int itemIdThatMustBeVisible,
  53038. const int minimumWidth,
  53039. const int maximumNumColumns,
  53040. const int standardItemHeight)
  53041. {
  53042. if (componentToAttachTo != 0)
  53043. {
  53044. return showMenu (componentToAttachTo->getScreenX(),
  53045. componentToAttachTo->getScreenY(),
  53046. componentToAttachTo->getWidth(),
  53047. componentToAttachTo->getHeight(),
  53048. itemIdThatMustBeVisible,
  53049. minimumWidth,
  53050. maximumNumColumns,
  53051. standardItemHeight,
  53052. true, componentToAttachTo);
  53053. }
  53054. else
  53055. {
  53056. return show (itemIdThatMustBeVisible,
  53057. minimumWidth,
  53058. maximumNumColumns,
  53059. standardItemHeight);
  53060. }
  53061. }
  53062. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus() throw()
  53063. {
  53064. for (int i = activeMenuWindows.size(); --i >= 0;)
  53065. {
  53066. PopupMenuWindow* const pmw = (PopupMenuWindow*) activeMenuWindows[i];
  53067. if (pmw != 0)
  53068. pmw->dismissMenu (0);
  53069. }
  53070. }
  53071. int PopupMenu::getNumItems() const throw()
  53072. {
  53073. int num = 0;
  53074. for (int i = items.size(); --i >= 0;)
  53075. if (! ((MenuItemInfo*) items.getUnchecked(i))->isSeparator)
  53076. ++num;
  53077. return num;
  53078. }
  53079. bool PopupMenu::containsCommandItem (const int commandID) const throw()
  53080. {
  53081. for (int i = items.size(); --i >= 0;)
  53082. {
  53083. const MenuItemInfo* mi = (const MenuItemInfo*) items.getUnchecked (i);
  53084. if ((mi->itemId == commandID && mi->commandManager != 0)
  53085. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  53086. {
  53087. return true;
  53088. }
  53089. }
  53090. return false;
  53091. }
  53092. bool PopupMenu::containsAnyActiveItems() const throw()
  53093. {
  53094. for (int i = items.size(); --i >= 0;)
  53095. {
  53096. const MenuItemInfo* const mi = (const MenuItemInfo*) items.getUnchecked (i);
  53097. if (mi->subMenu != 0)
  53098. {
  53099. if (mi->subMenu->containsAnyActiveItems())
  53100. return true;
  53101. }
  53102. else if (mi->active)
  53103. {
  53104. return true;
  53105. }
  53106. }
  53107. return false;
  53108. }
  53109. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel) throw()
  53110. {
  53111. lookAndFeel = newLookAndFeel;
  53112. }
  53113. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  53114. : refCount_ (0),
  53115. isHighlighted (false),
  53116. isTriggeredAutomatically (isTriggeredAutomatically_)
  53117. {
  53118. }
  53119. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  53120. {
  53121. jassert (refCount_ == 0); // should be deleted only by the menu component, as they keep a ref-count.
  53122. }
  53123. void PopupMenuCustomComponent::triggerMenuItem()
  53124. {
  53125. MenuItemComponent* const mic = dynamic_cast<MenuItemComponent*> (getParentComponent());
  53126. if (mic != 0)
  53127. {
  53128. PopupMenuWindow* const pmw = dynamic_cast<PopupMenuWindow*> (mic->getParentComponent());
  53129. if (pmw != 0)
  53130. {
  53131. pmw->dismissMenu (&mic->itemInfo);
  53132. }
  53133. else
  53134. {
  53135. // something must have gone wrong with the component hierarchy if this happens..
  53136. jassertfalse
  53137. }
  53138. }
  53139. else
  53140. {
  53141. // why isn't this component inside a menu? Not much point triggering the item if
  53142. // there's no menu.
  53143. jassertfalse
  53144. }
  53145. }
  53146. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_) throw()
  53147. : subMenu (0),
  53148. itemId (0),
  53149. isSeparator (false),
  53150. isTicked (false),
  53151. isEnabled (false),
  53152. isCustomComponent (false),
  53153. isSectionHeader (false),
  53154. customColour (0),
  53155. customImage (0),
  53156. menu (menu_),
  53157. index (0)
  53158. {
  53159. }
  53160. PopupMenu::MenuItemIterator::~MenuItemIterator() throw()
  53161. {
  53162. }
  53163. bool PopupMenu::MenuItemIterator::next() throw()
  53164. {
  53165. if (index >= menu.items.size())
  53166. return false;
  53167. const MenuItemInfo* const item = (const MenuItemInfo*) menu.items.getUnchecked (index);
  53168. ++index;
  53169. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  53170. subMenu = item->subMenu;
  53171. itemId = item->itemId;
  53172. isSeparator = item->isSeparator;
  53173. isTicked = item->isTicked;
  53174. isEnabled = item->active;
  53175. isSectionHeader = dynamic_cast <HeaderItemComponent*> (item->customComp) != 0;
  53176. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  53177. customColour = item->usesColour ? &(item->textColour) : 0;
  53178. customImage = item->image;
  53179. commandManager = item->commandManager;
  53180. return true;
  53181. }
  53182. END_JUCE_NAMESPACE
  53183. /********* End of inlined file: juce_PopupMenu.cpp *********/
  53184. /********* Start of inlined file: juce_ComponentDragger.cpp *********/
  53185. BEGIN_JUCE_NAMESPACE
  53186. ComponentDragger::ComponentDragger()
  53187. : constrainer (0),
  53188. originalX (0),
  53189. originalY (0)
  53190. {
  53191. }
  53192. ComponentDragger::~ComponentDragger()
  53193. {
  53194. }
  53195. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  53196. ComponentBoundsConstrainer* const constrainer_)
  53197. {
  53198. jassert (componentToDrag->isValidComponent());
  53199. if (componentToDrag->isValidComponent())
  53200. {
  53201. constrainer = constrainer_;
  53202. originalX = 0;
  53203. originalY = 0;
  53204. componentToDrag->relativePositionToGlobal (originalX, originalY);
  53205. }
  53206. }
  53207. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  53208. {
  53209. jassert (componentToDrag->isValidComponent());
  53210. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  53211. if (componentToDrag->isValidComponent())
  53212. {
  53213. int x = originalX;
  53214. int y = originalY;
  53215. int w = componentToDrag->getWidth();
  53216. int h = componentToDrag->getHeight();
  53217. const Component* const parentComp = componentToDrag->getParentComponent();
  53218. if (parentComp != 0)
  53219. parentComp->globalPositionToRelative (x, y);
  53220. x += e.getDistanceFromDragStartX();
  53221. y += e.getDistanceFromDragStartY();
  53222. if (constrainer != 0)
  53223. constrainer->setBoundsForComponent (componentToDrag, x, y, w, h,
  53224. false, false, false, false);
  53225. else
  53226. componentToDrag->setBounds (x, y, w, h);
  53227. }
  53228. }
  53229. END_JUCE_NAMESPACE
  53230. /********* End of inlined file: juce_ComponentDragger.cpp *********/
  53231. /********* Start of inlined file: juce_DragAndDropContainer.cpp *********/
  53232. BEGIN_JUCE_NAMESPACE
  53233. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  53234. bool juce_performDragDropText (const String& text, bool& shouldStop);
  53235. class DragImageComponent : public Component,
  53236. public Timer
  53237. {
  53238. private:
  53239. Image* image;
  53240. Component* const source;
  53241. DragAndDropContainer* const owner;
  53242. ComponentDeletionWatcher* sourceWatcher;
  53243. Component* mouseDragSource;
  53244. ComponentDeletionWatcher* mouseDragSourceWatcher;
  53245. DragAndDropTarget* currentlyOver;
  53246. ComponentDeletionWatcher* currentlyOverWatcher;
  53247. String dragDesc;
  53248. int xOff, yOff;
  53249. bool hasCheckedForExternalDrag, drawImage;
  53250. DragImageComponent (const DragImageComponent&);
  53251. const DragImageComponent& operator= (const DragImageComponent&);
  53252. public:
  53253. DragImageComponent (Image* const im,
  53254. const String& desc,
  53255. Component* const s,
  53256. DragAndDropContainer* const o)
  53257. : image (im),
  53258. source (s),
  53259. owner (o),
  53260. currentlyOver (0),
  53261. currentlyOverWatcher (0),
  53262. dragDesc (desc),
  53263. hasCheckedForExternalDrag (false),
  53264. drawImage (true)
  53265. {
  53266. setSize (im->getWidth(), im->getHeight());
  53267. sourceWatcher = new ComponentDeletionWatcher (source);
  53268. mouseDragSource = Component::getComponentUnderMouse();
  53269. if (mouseDragSource == 0)
  53270. mouseDragSource = source;
  53271. mouseDragSourceWatcher = new ComponentDeletionWatcher (mouseDragSource);
  53272. mouseDragSource->addMouseListener (this, false);
  53273. int mx, my;
  53274. Desktop::getLastMouseDownPosition (mx, my);
  53275. source->globalPositionToRelative (mx, my);
  53276. xOff = jlimit (0, im->getWidth(), mx);
  53277. yOff = jlimit (0, im->getHeight(), my);
  53278. startTimer (200);
  53279. setInterceptsMouseClicks (false, false);
  53280. setAlwaysOnTop (true);
  53281. }
  53282. ~DragImageComponent()
  53283. {
  53284. if (owner->dragImageComponent == this)
  53285. owner->dragImageComponent = 0;
  53286. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53287. {
  53288. mouseDragSource->removeMouseListener (this);
  53289. if (currentlyOverWatcher != 0 && ! currentlyOverWatcher->hasBeenDeleted())
  53290. if (currentlyOver->isInterestedInDragSource (dragDesc, source))
  53291. currentlyOver->itemDragExit (dragDesc, source);
  53292. }
  53293. delete mouseDragSourceWatcher;
  53294. delete sourceWatcher;
  53295. delete image;
  53296. delete currentlyOverWatcher;
  53297. }
  53298. void paint (Graphics& g)
  53299. {
  53300. if (isOpaque())
  53301. g.fillAll (Colours::white);
  53302. if (drawImage)
  53303. {
  53304. g.setOpacity (1.0f);
  53305. g.drawImageAt (image, 0, 0);
  53306. }
  53307. }
  53308. DragAndDropTarget* findTarget (const int screenX, const int screenY,
  53309. int& relX, int& relY) const throw()
  53310. {
  53311. Component* hit = getParentComponent();
  53312. if (hit == 0)
  53313. {
  53314. hit = Desktop::getInstance().findComponentAt (screenX, screenY);
  53315. }
  53316. else
  53317. {
  53318. int rx = screenX, ry = screenY;
  53319. hit->globalPositionToRelative (rx, ry);
  53320. hit = hit->getComponentAt (rx, ry);
  53321. }
  53322. // (note: use a local copy of the dragDesc member in case the callback runs
  53323. // a modal loop and deletes this object before the method completes)
  53324. const String dragDescLocal (dragDesc);
  53325. while (hit != 0)
  53326. {
  53327. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  53328. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  53329. {
  53330. relX = screenX;
  53331. relY = screenY;
  53332. hit->globalPositionToRelative (relX, relY);
  53333. return ddt;
  53334. }
  53335. hit = hit->getParentComponent();
  53336. }
  53337. return 0;
  53338. }
  53339. void mouseUp (const MouseEvent& e)
  53340. {
  53341. if (e.originalComponent != this)
  53342. {
  53343. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53344. mouseDragSource->removeMouseListener (this);
  53345. bool dropAccepted = false;
  53346. DragAndDropTarget* ddt = 0;
  53347. int relX = 0, relY = 0;
  53348. if (isVisible())
  53349. {
  53350. setVisible (false);
  53351. ddt = findTarget (e.getScreenX(),
  53352. e.getScreenY(),
  53353. relX, relY);
  53354. // fade this component and remove it - it'll be deleted later by the timer callback
  53355. dropAccepted = ddt != 0;
  53356. setVisible (true);
  53357. if (dropAccepted || sourceWatcher->hasBeenDeleted())
  53358. {
  53359. fadeOutComponent (120);
  53360. }
  53361. else
  53362. {
  53363. int targetX = source->getWidth() / 2;
  53364. int targetY = source->getHeight() / 2;
  53365. source->relativePositionToGlobal (targetX, targetY);
  53366. int ourCentreX = getWidth() / 2;
  53367. int ourCentreY = getHeight() / 2;
  53368. relativePositionToGlobal (ourCentreX, ourCentreY);
  53369. fadeOutComponent (120,
  53370. targetX - ourCentreX,
  53371. targetY - ourCentreY);
  53372. }
  53373. }
  53374. if (getParentComponent() != 0)
  53375. getParentComponent()->removeChildComponent (this);
  53376. if (dropAccepted && ddt != 0)
  53377. {
  53378. // (note: use a local copy of the dragDesc member in case the callback runs
  53379. // a modal loop and deletes this object before the method completes)
  53380. const String dragDescLocal (dragDesc);
  53381. currentlyOver = 0;
  53382. deleteAndZero (currentlyOverWatcher);
  53383. ddt->itemDropped (dragDescLocal, source, relX, relY);
  53384. }
  53385. // careful - this object could now be deleted..
  53386. }
  53387. }
  53388. void updateLocation (const bool canDoExternalDrag, int x, int y)
  53389. {
  53390. // (note: use a local copy of the dragDesc member in case the callback runs
  53391. // a modal loop and deletes this object before it returns)
  53392. const String dragDescLocal (dragDesc);
  53393. int newX = x - xOff;
  53394. int newY = y - yOff;
  53395. if (getParentComponent() != 0)
  53396. getParentComponent()->globalPositionToRelative (newX, newY);
  53397. if (newX != getX() || newY != getY())
  53398. {
  53399. setTopLeftPosition (newX, newY);
  53400. int relX = 0, relY = 0;
  53401. DragAndDropTarget* const ddt = findTarget (x, y, relX, relY);
  53402. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  53403. if (ddt != currentlyOver)
  53404. {
  53405. if (currentlyOverWatcher != 0 && ! currentlyOverWatcher->hasBeenDeleted())
  53406. {
  53407. Component* const over = dynamic_cast <Component*> (currentlyOver);
  53408. if (over != 0
  53409. && over->isValidComponent()
  53410. && ! (sourceWatcher->hasBeenDeleted())
  53411. && currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53412. {
  53413. currentlyOver->itemDragExit (dragDescLocal, source);
  53414. }
  53415. }
  53416. currentlyOver = ddt;
  53417. deleteAndZero (currentlyOverWatcher);
  53418. if (ddt != 0)
  53419. {
  53420. currentlyOverWatcher = new ComponentDeletionWatcher (dynamic_cast <Component*> (ddt));
  53421. if (currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53422. currentlyOver->itemDragEnter (dragDescLocal, source, relX, relY);
  53423. }
  53424. }
  53425. else if (currentlyOverWatcher != 0 && currentlyOverWatcher->hasBeenDeleted())
  53426. {
  53427. currentlyOver = 0;
  53428. deleteAndZero (currentlyOverWatcher);
  53429. }
  53430. if (currentlyOver != 0
  53431. && currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53432. currentlyOver->itemDragMove (dragDescLocal, source, relX, relY);
  53433. if (currentlyOver == 0
  53434. && canDoExternalDrag
  53435. && ! hasCheckedForExternalDrag)
  53436. {
  53437. if (Desktop::getInstance().findComponentAt (x, y) == 0)
  53438. {
  53439. hasCheckedForExternalDrag = true;
  53440. StringArray files;
  53441. bool canMoveFiles = false;
  53442. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  53443. && files.size() > 0)
  53444. {
  53445. ComponentDeletionWatcher cdw (this);
  53446. setVisible (false);
  53447. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  53448. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  53449. if (! cdw.hasBeenDeleted())
  53450. delete this;
  53451. return;
  53452. }
  53453. }
  53454. }
  53455. }
  53456. }
  53457. void mouseDrag (const MouseEvent& e)
  53458. {
  53459. if (e.originalComponent != this)
  53460. updateLocation (true, e.getScreenX(), e.getScreenY());
  53461. }
  53462. void timerCallback()
  53463. {
  53464. if (sourceWatcher->hasBeenDeleted())
  53465. {
  53466. delete this;
  53467. }
  53468. else if (! isMouseButtonDownAnywhere())
  53469. {
  53470. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53471. mouseDragSource->removeMouseListener (this);
  53472. delete this;
  53473. }
  53474. }
  53475. };
  53476. DragAndDropContainer::DragAndDropContainer()
  53477. : dragImageComponent (0)
  53478. {
  53479. }
  53480. DragAndDropContainer::~DragAndDropContainer()
  53481. {
  53482. if (dragImageComponent != 0)
  53483. delete dragImageComponent;
  53484. }
  53485. void DragAndDropContainer::startDragging (const String& sourceDescription,
  53486. Component* sourceComponent,
  53487. Image* im,
  53488. const bool allowDraggingToExternalWindows)
  53489. {
  53490. if (dragImageComponent != 0)
  53491. {
  53492. if (im != 0)
  53493. delete im;
  53494. }
  53495. else
  53496. {
  53497. Component* const thisComp = dynamic_cast <Component*> (this);
  53498. if (thisComp != 0)
  53499. {
  53500. int mx, my;
  53501. Desktop::getLastMouseDownPosition (mx, my);
  53502. if (im == 0)
  53503. {
  53504. im = sourceComponent->createComponentSnapshot (Rectangle (0, 0, sourceComponent->getWidth(), sourceComponent->getHeight()));
  53505. if (im->getFormat() != Image::ARGB)
  53506. {
  53507. Image* newIm = new Image (Image::ARGB, im->getWidth(), im->getHeight(), true);
  53508. Graphics g2 (*newIm);
  53509. g2.drawImageAt (im, 0, 0);
  53510. delete im;
  53511. im = newIm;
  53512. }
  53513. im->multiplyAllAlphas (0.6f);
  53514. const int lo = 150;
  53515. const int hi = 400;
  53516. int rx = mx, ry = my;
  53517. sourceComponent->globalPositionToRelative (rx, ry);
  53518. const int cx = jlimit (0, im->getWidth(), rx);
  53519. const int cy = jlimit (0, im->getHeight(), ry);
  53520. for (int y = im->getHeight(); --y >= 0;)
  53521. {
  53522. const double dy = (y - cy) * (y - cy);
  53523. for (int x = im->getWidth(); --x >= 0;)
  53524. {
  53525. const int dx = x - cx;
  53526. const int distance = roundDoubleToInt (sqrt (dx * dx + dy));
  53527. if (distance > lo)
  53528. {
  53529. const float alpha = (distance > hi) ? 0
  53530. : (hi - distance) / (float) (hi - lo)
  53531. + Random::getSystemRandom().nextFloat() * 0.008f;
  53532. im->multiplyAlphaAt (x, y, alpha);
  53533. }
  53534. }
  53535. }
  53536. }
  53537. DragImageComponent* const dic
  53538. = new DragImageComponent (im,
  53539. sourceDescription,
  53540. sourceComponent,
  53541. this);
  53542. dragImageComponent = dic;
  53543. currentDragDesc = sourceDescription;
  53544. if (allowDraggingToExternalWindows)
  53545. {
  53546. if (! Desktop::canUseSemiTransparentWindows())
  53547. dic->setOpaque (true);
  53548. dic->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  53549. | ComponentPeer::windowIsTemporary);
  53550. }
  53551. else
  53552. thisComp->addChildComponent (dic);
  53553. dic->updateLocation (false, mx, my);
  53554. dic->setVisible (true);
  53555. }
  53556. else
  53557. {
  53558. // this class must only be implemented by an object that
  53559. // is also a Component.
  53560. jassertfalse
  53561. if (im != 0)
  53562. delete im;
  53563. }
  53564. }
  53565. }
  53566. bool DragAndDropContainer::isDragAndDropActive() const
  53567. {
  53568. return dragImageComponent != 0;
  53569. }
  53570. const String DragAndDropContainer::getCurrentDragDescription() const
  53571. {
  53572. return (dragImageComponent != 0) ? currentDragDesc
  53573. : String::empty;
  53574. }
  53575. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  53576. {
  53577. if (c == 0)
  53578. return 0;
  53579. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  53580. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  53581. }
  53582. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  53583. {
  53584. return false;
  53585. }
  53586. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  53587. {
  53588. }
  53589. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  53590. {
  53591. }
  53592. void DragAndDropTarget::itemDragExit (const String&, Component*)
  53593. {
  53594. }
  53595. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  53596. {
  53597. return true;
  53598. }
  53599. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  53600. {
  53601. }
  53602. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  53603. {
  53604. }
  53605. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  53606. {
  53607. }
  53608. END_JUCE_NAMESPACE
  53609. /********* End of inlined file: juce_DragAndDropContainer.cpp *********/
  53610. /********* Start of inlined file: juce_MouseCursor.cpp *********/
  53611. BEGIN_JUCE_NAMESPACE
  53612. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw();
  53613. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw();
  53614. // isStandard set depending on which interface was used to create the cursor
  53615. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw();
  53616. static CriticalSection mouseCursorLock;
  53617. static VoidArray standardCursors (2);
  53618. class RefCountedMouseCursor
  53619. {
  53620. public:
  53621. RefCountedMouseCursor (const MouseCursor::StandardCursorType t) throw()
  53622. : refCount (1),
  53623. standardType (t),
  53624. isStandard (true)
  53625. {
  53626. handle = juce_createStandardMouseCursor (standardType);
  53627. standardCursors.add (this);
  53628. }
  53629. RefCountedMouseCursor (Image& image,
  53630. const int hotSpotX,
  53631. const int hotSpotY) throw()
  53632. : refCount (1),
  53633. standardType (MouseCursor::NormalCursor),
  53634. isStandard (false)
  53635. {
  53636. handle = juce_createMouseCursorFromImage (image, hotSpotX, hotSpotY);
  53637. }
  53638. ~RefCountedMouseCursor() throw()
  53639. {
  53640. juce_deleteMouseCursor (handle, isStandard);
  53641. standardCursors.removeValue (this);
  53642. }
  53643. void decRef() throw()
  53644. {
  53645. if (--refCount == 0)
  53646. delete this;
  53647. }
  53648. void incRef() throw()
  53649. {
  53650. ++refCount;
  53651. }
  53652. void* getHandle() const throw()
  53653. {
  53654. return handle;
  53655. }
  53656. static RefCountedMouseCursor* findInstance (MouseCursor::StandardCursorType type) throw()
  53657. {
  53658. const ScopedLock sl (mouseCursorLock);
  53659. for (int i = 0; i < standardCursors.size(); i++)
  53660. {
  53661. RefCountedMouseCursor* const r = (RefCountedMouseCursor*) standardCursors.getUnchecked(i);
  53662. if (r->standardType == type)
  53663. {
  53664. r->incRef();
  53665. return r;
  53666. }
  53667. }
  53668. return new RefCountedMouseCursor (type);
  53669. }
  53670. juce_UseDebuggingNewOperator
  53671. private:
  53672. void* handle;
  53673. int refCount;
  53674. const MouseCursor::StandardCursorType standardType;
  53675. const bool isStandard;
  53676. const RefCountedMouseCursor& operator= (const RefCountedMouseCursor&);
  53677. };
  53678. MouseCursor::MouseCursor() throw()
  53679. {
  53680. cursorHandle = RefCountedMouseCursor::findInstance (NormalCursor);
  53681. }
  53682. MouseCursor::MouseCursor (const StandardCursorType type) throw()
  53683. {
  53684. cursorHandle = RefCountedMouseCursor::findInstance (type);
  53685. }
  53686. MouseCursor::MouseCursor (Image& image,
  53687. const int hotSpotX,
  53688. const int hotSpotY) throw()
  53689. {
  53690. cursorHandle = new RefCountedMouseCursor (image, hotSpotX, hotSpotY);
  53691. }
  53692. MouseCursor::MouseCursor (const MouseCursor& other) throw()
  53693. : cursorHandle (other.cursorHandle)
  53694. {
  53695. const ScopedLock sl (mouseCursorLock);
  53696. cursorHandle->incRef();
  53697. }
  53698. MouseCursor::~MouseCursor() throw()
  53699. {
  53700. const ScopedLock sl (mouseCursorLock);
  53701. cursorHandle->decRef();
  53702. }
  53703. const MouseCursor& MouseCursor::operator= (const MouseCursor& other) throw()
  53704. {
  53705. if (this != &other)
  53706. {
  53707. const ScopedLock sl (mouseCursorLock);
  53708. cursorHandle->decRef();
  53709. cursorHandle = other.cursorHandle;
  53710. cursorHandle->incRef();
  53711. }
  53712. return *this;
  53713. }
  53714. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  53715. {
  53716. return cursorHandle == other.cursorHandle;
  53717. }
  53718. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  53719. {
  53720. return cursorHandle != other.cursorHandle;
  53721. }
  53722. void* MouseCursor::getHandle() const throw()
  53723. {
  53724. return cursorHandle->getHandle();
  53725. }
  53726. void MouseCursor::showWaitCursor() throw()
  53727. {
  53728. const MouseCursor mc (MouseCursor::WaitCursor);
  53729. mc.showInAllWindows();
  53730. }
  53731. void MouseCursor::hideWaitCursor() throw()
  53732. {
  53733. if (Component::getComponentUnderMouse()->isValidComponent())
  53734. {
  53735. Component::getComponentUnderMouse()->getMouseCursor().showInAllWindows();
  53736. }
  53737. else
  53738. {
  53739. const MouseCursor mc (MouseCursor::NormalCursor);
  53740. mc.showInAllWindows();
  53741. }
  53742. }
  53743. END_JUCE_NAMESPACE
  53744. /********* End of inlined file: juce_MouseCursor.cpp *********/
  53745. /********* Start of inlined file: juce_MouseEvent.cpp *********/
  53746. BEGIN_JUCE_NAMESPACE
  53747. MouseEvent::MouseEvent (const int x_,
  53748. const int y_,
  53749. const ModifierKeys& mods_,
  53750. Component* const originator,
  53751. const Time& eventTime_,
  53752. const int mouseDownX_,
  53753. const int mouseDownY_,
  53754. const Time& mouseDownTime_,
  53755. const int numberOfClicks_,
  53756. const bool mouseWasDragged) throw()
  53757. : x (x_),
  53758. y (y_),
  53759. mods (mods_),
  53760. eventComponent (originator),
  53761. originalComponent (originator),
  53762. eventTime (eventTime_),
  53763. mouseDownX (mouseDownX_),
  53764. mouseDownY (mouseDownY_),
  53765. mouseDownTime (mouseDownTime_),
  53766. numberOfClicks (numberOfClicks_),
  53767. wasMovedSinceMouseDown (mouseWasDragged)
  53768. {
  53769. }
  53770. MouseEvent::~MouseEvent() throw()
  53771. {
  53772. }
  53773. bool MouseEvent::mouseWasClicked() const throw()
  53774. {
  53775. return ! wasMovedSinceMouseDown;
  53776. }
  53777. int MouseEvent::getMouseDownX() const throw()
  53778. {
  53779. return mouseDownX;
  53780. }
  53781. int MouseEvent::getMouseDownY() const throw()
  53782. {
  53783. return mouseDownY;
  53784. }
  53785. int MouseEvent::getDistanceFromDragStartX() const throw()
  53786. {
  53787. return x - mouseDownX;
  53788. }
  53789. int MouseEvent::getDistanceFromDragStartY() const throw()
  53790. {
  53791. return y - mouseDownY;
  53792. }
  53793. int MouseEvent::getDistanceFromDragStart() const throw()
  53794. {
  53795. return roundDoubleToInt (juce_hypot (getDistanceFromDragStartX(),
  53796. getDistanceFromDragStartY()));
  53797. }
  53798. int MouseEvent::getLengthOfMousePress() const throw()
  53799. {
  53800. if (mouseDownTime.toMilliseconds() > 0)
  53801. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  53802. return 0;
  53803. }
  53804. int MouseEvent::getScreenX() const throw()
  53805. {
  53806. int sx = x, sy = y;
  53807. eventComponent->relativePositionToGlobal (sx, sy);
  53808. return sx;
  53809. }
  53810. int MouseEvent::getScreenY() const throw()
  53811. {
  53812. int sx = x, sy = y;
  53813. eventComponent->relativePositionToGlobal (sx, sy);
  53814. return sy;
  53815. }
  53816. int MouseEvent::getMouseDownScreenX() const throw()
  53817. {
  53818. int sx = mouseDownX, sy = mouseDownY;
  53819. eventComponent->relativePositionToGlobal (sx, sy);
  53820. return sx;
  53821. }
  53822. int MouseEvent::getMouseDownScreenY() const throw()
  53823. {
  53824. int sx = mouseDownX, sy = mouseDownY;
  53825. eventComponent->relativePositionToGlobal (sx, sy);
  53826. return sy;
  53827. }
  53828. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  53829. {
  53830. if (otherComponent == 0)
  53831. {
  53832. jassertfalse
  53833. return *this;
  53834. }
  53835. MouseEvent me (*this);
  53836. eventComponent->relativePositionToOtherComponent (otherComponent, me.x, me.y);
  53837. eventComponent->relativePositionToOtherComponent (otherComponent, me.mouseDownX, me.mouseDownY);
  53838. me.eventComponent = otherComponent;
  53839. return me;
  53840. }
  53841. static int doubleClickTimeOutMs = 400;
  53842. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  53843. {
  53844. doubleClickTimeOutMs = newTime;
  53845. }
  53846. int MouseEvent::getDoubleClickTimeout() throw()
  53847. {
  53848. return doubleClickTimeOutMs;
  53849. }
  53850. END_JUCE_NAMESPACE
  53851. /********* End of inlined file: juce_MouseEvent.cpp *********/
  53852. /********* Start of inlined file: juce_MouseHoverDetector.cpp *********/
  53853. BEGIN_JUCE_NAMESPACE
  53854. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  53855. : source (0),
  53856. hoverTimeMillisecs (hoverTimeMillisecs_),
  53857. hasJustHovered (false)
  53858. {
  53859. internalTimer.owner = this;
  53860. }
  53861. MouseHoverDetector::~MouseHoverDetector()
  53862. {
  53863. setHoverComponent (0);
  53864. }
  53865. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  53866. {
  53867. hoverTimeMillisecs = newTimeInMillisecs;
  53868. }
  53869. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  53870. {
  53871. if (source != newSourceComponent)
  53872. {
  53873. internalTimer.stopTimer();
  53874. hasJustHovered = false;
  53875. if (source != 0)
  53876. {
  53877. // ! you need to delete the hover detector before deleting its component
  53878. jassert (source->isValidComponent());
  53879. source->removeMouseListener (&internalTimer);
  53880. }
  53881. source = newSourceComponent;
  53882. if (newSourceComponent != 0)
  53883. newSourceComponent->addMouseListener (&internalTimer, false);
  53884. }
  53885. }
  53886. void MouseHoverDetector::hoverTimerCallback()
  53887. {
  53888. internalTimer.stopTimer();
  53889. if (source != 0)
  53890. {
  53891. int mx, my;
  53892. source->getMouseXYRelative (mx, my);
  53893. if (source->reallyContains (mx, my, false))
  53894. {
  53895. hasJustHovered = true;
  53896. mouseHovered (mx, my);
  53897. }
  53898. }
  53899. }
  53900. void MouseHoverDetector::checkJustHoveredCallback()
  53901. {
  53902. if (hasJustHovered)
  53903. {
  53904. hasJustHovered = false;
  53905. mouseMovedAfterHover();
  53906. }
  53907. }
  53908. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  53909. {
  53910. owner->hoverTimerCallback();
  53911. }
  53912. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  53913. {
  53914. stopTimer();
  53915. owner->checkJustHoveredCallback();
  53916. }
  53917. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  53918. {
  53919. stopTimer();
  53920. owner->checkJustHoveredCallback();
  53921. }
  53922. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  53923. {
  53924. stopTimer();
  53925. owner->checkJustHoveredCallback();
  53926. }
  53927. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  53928. {
  53929. stopTimer();
  53930. owner->checkJustHoveredCallback();
  53931. }
  53932. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  53933. {
  53934. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  53935. {
  53936. lastX = e.x;
  53937. lastY = e.y;
  53938. if (owner->source != 0)
  53939. startTimer (owner->hoverTimeMillisecs);
  53940. owner->checkJustHoveredCallback();
  53941. }
  53942. }
  53943. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  53944. {
  53945. stopTimer();
  53946. owner->checkJustHoveredCallback();
  53947. }
  53948. END_JUCE_NAMESPACE
  53949. /********* End of inlined file: juce_MouseHoverDetector.cpp *********/
  53950. /********* Start of inlined file: juce_MouseListener.cpp *********/
  53951. BEGIN_JUCE_NAMESPACE
  53952. void MouseListener::mouseEnter (const MouseEvent&)
  53953. {
  53954. }
  53955. void MouseListener::mouseExit (const MouseEvent&)
  53956. {
  53957. }
  53958. void MouseListener::mouseDown (const MouseEvent&)
  53959. {
  53960. }
  53961. void MouseListener::mouseUp (const MouseEvent&)
  53962. {
  53963. }
  53964. void MouseListener::mouseDrag (const MouseEvent&)
  53965. {
  53966. }
  53967. void MouseListener::mouseMove (const MouseEvent&)
  53968. {
  53969. }
  53970. void MouseListener::mouseDoubleClick (const MouseEvent&)
  53971. {
  53972. }
  53973. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  53974. {
  53975. }
  53976. END_JUCE_NAMESPACE
  53977. /********* End of inlined file: juce_MouseListener.cpp *********/
  53978. /********* Start of inlined file: juce_BooleanPropertyComponent.cpp *********/
  53979. BEGIN_JUCE_NAMESPACE
  53980. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  53981. const String& buttonTextWhenTrue,
  53982. const String& buttonTextWhenFalse)
  53983. : PropertyComponent (name),
  53984. onText (buttonTextWhenTrue),
  53985. offText (buttonTextWhenFalse)
  53986. {
  53987. addAndMakeVisible (button = new ToggleButton (String::empty));
  53988. button->setClickingTogglesState (false);
  53989. button->addButtonListener (this);
  53990. }
  53991. BooleanPropertyComponent::~BooleanPropertyComponent()
  53992. {
  53993. deleteAllChildren();
  53994. }
  53995. void BooleanPropertyComponent::paint (Graphics& g)
  53996. {
  53997. PropertyComponent::paint (g);
  53998. const Rectangle r (button->getBounds());
  53999. g.setColour (Colours::white);
  54000. g.fillRect (r);
  54001. g.setColour (findColour (ComboBox::outlineColourId));
  54002. g.drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  54003. }
  54004. void BooleanPropertyComponent::refresh()
  54005. {
  54006. button->setToggleState (getState(), false);
  54007. button->setButtonText (button->getToggleState() ? onText : offText);
  54008. }
  54009. void BooleanPropertyComponent::buttonClicked (Button*)
  54010. {
  54011. setState (! getState());
  54012. }
  54013. END_JUCE_NAMESPACE
  54014. /********* End of inlined file: juce_BooleanPropertyComponent.cpp *********/
  54015. /********* Start of inlined file: juce_ButtonPropertyComponent.cpp *********/
  54016. BEGIN_JUCE_NAMESPACE
  54017. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  54018. const bool triggerOnMouseDown)
  54019. : PropertyComponent (name)
  54020. {
  54021. addAndMakeVisible (button = new TextButton (String::empty));
  54022. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  54023. button->addButtonListener (this);
  54024. }
  54025. ButtonPropertyComponent::~ButtonPropertyComponent()
  54026. {
  54027. deleteAllChildren();
  54028. }
  54029. void ButtonPropertyComponent::refresh()
  54030. {
  54031. button->setButtonText (getButtonText());
  54032. }
  54033. void ButtonPropertyComponent::buttonClicked (Button*)
  54034. {
  54035. buttonClicked();
  54036. }
  54037. END_JUCE_NAMESPACE
  54038. /********* End of inlined file: juce_ButtonPropertyComponent.cpp *********/
  54039. /********* Start of inlined file: juce_ChoicePropertyComponent.cpp *********/
  54040. BEGIN_JUCE_NAMESPACE
  54041. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  54042. : PropertyComponent (name),
  54043. comboBox (0)
  54044. {
  54045. }
  54046. ChoicePropertyComponent::~ChoicePropertyComponent()
  54047. {
  54048. deleteAllChildren();
  54049. }
  54050. const StringArray& ChoicePropertyComponent::getChoices() const throw()
  54051. {
  54052. return choices;
  54053. }
  54054. void ChoicePropertyComponent::refresh()
  54055. {
  54056. if (comboBox == 0)
  54057. {
  54058. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  54059. for (int i = 0; i < choices.size(); ++i)
  54060. {
  54061. if (choices[i].isNotEmpty())
  54062. comboBox->addItem (choices[i], i + 1);
  54063. else
  54064. comboBox->addSeparator();
  54065. }
  54066. comboBox->setEditableText (false);
  54067. comboBox->addListener (this);
  54068. }
  54069. comboBox->setSelectedId (getIndex() + 1, true);
  54070. }
  54071. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  54072. {
  54073. const int newIndex = comboBox->getSelectedId() - 1;
  54074. if (newIndex != getIndex())
  54075. setIndex (newIndex);
  54076. }
  54077. END_JUCE_NAMESPACE
  54078. /********* End of inlined file: juce_ChoicePropertyComponent.cpp *********/
  54079. /********* Start of inlined file: juce_PropertyComponent.cpp *********/
  54080. BEGIN_JUCE_NAMESPACE
  54081. PropertyComponent::PropertyComponent (const String& name,
  54082. const int preferredHeight_)
  54083. : Component (name),
  54084. preferredHeight (preferredHeight_)
  54085. {
  54086. jassert (name.isNotEmpty());
  54087. }
  54088. PropertyComponent::~PropertyComponent()
  54089. {
  54090. }
  54091. void PropertyComponent::paint (Graphics& g)
  54092. {
  54093. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  54094. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  54095. }
  54096. void PropertyComponent::resized()
  54097. {
  54098. if (getNumChildComponents() > 0)
  54099. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  54100. }
  54101. void PropertyComponent::enablementChanged()
  54102. {
  54103. repaint();
  54104. }
  54105. END_JUCE_NAMESPACE
  54106. /********* End of inlined file: juce_PropertyComponent.cpp *********/
  54107. /********* Start of inlined file: juce_PropertyPanel.cpp *********/
  54108. BEGIN_JUCE_NAMESPACE
  54109. class PropertyHolderComponent : public Component
  54110. {
  54111. public:
  54112. PropertyHolderComponent()
  54113. {
  54114. }
  54115. ~PropertyHolderComponent()
  54116. {
  54117. deleteAllChildren();
  54118. }
  54119. void paint (Graphics&)
  54120. {
  54121. }
  54122. void updateLayout (const int width);
  54123. void refreshAll() const;
  54124. };
  54125. class PropertySectionComponent : public Component
  54126. {
  54127. public:
  54128. PropertySectionComponent (const String& sectionTitle,
  54129. const Array <PropertyComponent*>& newProperties,
  54130. const bool open)
  54131. : Component (sectionTitle),
  54132. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  54133. isOpen_ (open)
  54134. {
  54135. for (int i = newProperties.size(); --i >= 0;)
  54136. {
  54137. addAndMakeVisible (newProperties.getUnchecked(i));
  54138. newProperties.getUnchecked(i)->refresh();
  54139. }
  54140. }
  54141. ~PropertySectionComponent()
  54142. {
  54143. deleteAllChildren();
  54144. }
  54145. void paint (Graphics& g)
  54146. {
  54147. if (titleHeight > 0)
  54148. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  54149. }
  54150. void resized()
  54151. {
  54152. int y = titleHeight;
  54153. for (int i = getNumChildComponents(); --i >= 0;)
  54154. {
  54155. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54156. if (pec != 0)
  54157. {
  54158. const int prefH = pec->getPreferredHeight();
  54159. pec->setBounds (1, y, getWidth() - 2, prefH);
  54160. y += prefH;
  54161. }
  54162. }
  54163. }
  54164. int getPreferredHeight() const
  54165. {
  54166. int y = titleHeight;
  54167. if (isOpen())
  54168. {
  54169. for (int i = 0; i < getNumChildComponents(); ++i)
  54170. {
  54171. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54172. if (pec != 0)
  54173. y += pec->getPreferredHeight();
  54174. }
  54175. }
  54176. return y;
  54177. }
  54178. void setOpen (const bool open)
  54179. {
  54180. if (isOpen_ != open)
  54181. {
  54182. isOpen_ = open;
  54183. for (int i = 0; i < getNumChildComponents(); ++i)
  54184. {
  54185. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54186. if (pec != 0)
  54187. pec->setVisible (open);
  54188. }
  54189. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  54190. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  54191. if (pp != 0)
  54192. pp->resized();
  54193. }
  54194. }
  54195. bool isOpen() const throw()
  54196. {
  54197. return isOpen_;
  54198. }
  54199. void refreshAll() const
  54200. {
  54201. for (int i = 0; i < getNumChildComponents(); ++i)
  54202. {
  54203. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54204. if (pec != 0)
  54205. pec->refresh();
  54206. }
  54207. }
  54208. void mouseDown (const MouseEvent&)
  54209. {
  54210. }
  54211. void mouseUp (const MouseEvent& e)
  54212. {
  54213. if (e.getMouseDownX() < titleHeight
  54214. && e.x < titleHeight
  54215. && e.y < titleHeight
  54216. && e.getNumberOfClicks() != 2)
  54217. {
  54218. setOpen (! isOpen());
  54219. }
  54220. }
  54221. void mouseDoubleClick (const MouseEvent& e)
  54222. {
  54223. if (e.y < titleHeight)
  54224. setOpen (! isOpen());
  54225. }
  54226. private:
  54227. int titleHeight;
  54228. bool isOpen_;
  54229. };
  54230. void PropertyHolderComponent::updateLayout (const int width)
  54231. {
  54232. int y = 0;
  54233. for (int i = getNumChildComponents(); --i >= 0;)
  54234. {
  54235. PropertySectionComponent* const section
  54236. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  54237. if (section != 0)
  54238. {
  54239. const int prefH = section->getPreferredHeight();
  54240. section->setBounds (0, y, width, prefH);
  54241. y += prefH;
  54242. }
  54243. }
  54244. setSize (width, y);
  54245. repaint();
  54246. }
  54247. void PropertyHolderComponent::refreshAll() const
  54248. {
  54249. for (int i = getNumChildComponents(); --i >= 0;)
  54250. {
  54251. PropertySectionComponent* const section
  54252. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  54253. if (section != 0)
  54254. section->refreshAll();
  54255. }
  54256. }
  54257. PropertyPanel::PropertyPanel()
  54258. {
  54259. messageWhenEmpty = TRANS("(nothing selected)");
  54260. addAndMakeVisible (viewport = new Viewport());
  54261. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  54262. viewport->setFocusContainer (true);
  54263. }
  54264. PropertyPanel::~PropertyPanel()
  54265. {
  54266. clear();
  54267. deleteAllChildren();
  54268. }
  54269. void PropertyPanel::paint (Graphics& g)
  54270. {
  54271. if (propertyHolderComponent->getNumChildComponents() == 0)
  54272. {
  54273. g.setColour (Colours::black.withAlpha (0.5f));
  54274. g.setFont (14.0f);
  54275. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  54276. Justification::centred, true);
  54277. }
  54278. }
  54279. void PropertyPanel::resized()
  54280. {
  54281. viewport->setBounds (0, 0, getWidth(), getHeight());
  54282. updatePropHolderLayout();
  54283. }
  54284. void PropertyPanel::clear()
  54285. {
  54286. if (propertyHolderComponent->getNumChildComponents() > 0)
  54287. {
  54288. propertyHolderComponent->deleteAllChildren();
  54289. repaint();
  54290. }
  54291. }
  54292. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  54293. {
  54294. if (propertyHolderComponent->getNumChildComponents() == 0)
  54295. repaint();
  54296. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  54297. newProperties,
  54298. true), 0);
  54299. updatePropHolderLayout();
  54300. }
  54301. void PropertyPanel::addSection (const String& sectionTitle,
  54302. const Array <PropertyComponent*>& newProperties,
  54303. const bool shouldBeOpen)
  54304. {
  54305. jassert (sectionTitle.isNotEmpty());
  54306. if (propertyHolderComponent->getNumChildComponents() == 0)
  54307. repaint();
  54308. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  54309. newProperties,
  54310. shouldBeOpen), 0);
  54311. updatePropHolderLayout();
  54312. }
  54313. void PropertyPanel::updatePropHolderLayout() const
  54314. {
  54315. const int maxWidth = viewport->getMaximumVisibleWidth();
  54316. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (maxWidth);
  54317. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  54318. if (maxWidth != newMaxWidth)
  54319. {
  54320. // need to do this twice because of scrollbars changing the size, etc.
  54321. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (newMaxWidth);
  54322. }
  54323. }
  54324. void PropertyPanel::refreshAll() const
  54325. {
  54326. ((PropertyHolderComponent*) propertyHolderComponent)->refreshAll();
  54327. }
  54328. const StringArray PropertyPanel::getSectionNames() const
  54329. {
  54330. StringArray s;
  54331. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54332. {
  54333. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54334. if (section != 0 && section->getName().isNotEmpty())
  54335. s.add (section->getName());
  54336. }
  54337. return s;
  54338. }
  54339. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  54340. {
  54341. int index = 0;
  54342. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54343. {
  54344. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54345. if (section != 0 && section->getName().isNotEmpty())
  54346. {
  54347. if (index == sectionIndex)
  54348. return section->isOpen();
  54349. ++index;
  54350. }
  54351. }
  54352. return false;
  54353. }
  54354. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  54355. {
  54356. int index = 0;
  54357. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54358. {
  54359. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54360. if (section != 0 && section->getName().isNotEmpty())
  54361. {
  54362. if (index == sectionIndex)
  54363. {
  54364. section->setOpen (shouldBeOpen);
  54365. break;
  54366. }
  54367. ++index;
  54368. }
  54369. }
  54370. }
  54371. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  54372. {
  54373. int index = 0;
  54374. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54375. {
  54376. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54377. if (section != 0 && section->getName().isNotEmpty())
  54378. {
  54379. if (index == sectionIndex)
  54380. {
  54381. section->setEnabled (shouldBeEnabled);
  54382. break;
  54383. }
  54384. ++index;
  54385. }
  54386. }
  54387. }
  54388. XmlElement* PropertyPanel::getOpennessState() const
  54389. {
  54390. XmlElement* const xml = new XmlElement (T("PROPERTYPANELSTATE"));
  54391. const StringArray sections (getSectionNames());
  54392. for (int i = 0; i < sections.size(); ++i)
  54393. {
  54394. if (sections[i].isNotEmpty())
  54395. {
  54396. XmlElement* const e = new XmlElement (T("SECTION"));
  54397. e->setAttribute (T("name"), sections[i]);
  54398. e->setAttribute (T("open"), isSectionOpen (i) ? 1 : 0);
  54399. xml->addChildElement (e);
  54400. }
  54401. }
  54402. return xml;
  54403. }
  54404. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  54405. {
  54406. if (xml.hasTagName (T("PROPERTYPANELSTATE")))
  54407. {
  54408. const StringArray sections (getSectionNames());
  54409. forEachXmlChildElementWithTagName (xml, e, T("SECTION"))
  54410. {
  54411. setSectionOpen (sections.indexOf (e->getStringAttribute (T("name"))),
  54412. e->getBoolAttribute (T("open")));
  54413. }
  54414. }
  54415. }
  54416. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  54417. {
  54418. if (messageWhenEmpty != newMessage)
  54419. {
  54420. messageWhenEmpty = newMessage;
  54421. repaint();
  54422. }
  54423. }
  54424. const String& PropertyPanel::getMessageWhenEmpty() const throw()
  54425. {
  54426. return messageWhenEmpty;
  54427. }
  54428. END_JUCE_NAMESPACE
  54429. /********* End of inlined file: juce_PropertyPanel.cpp *********/
  54430. /********* Start of inlined file: juce_SliderPropertyComponent.cpp *********/
  54431. BEGIN_JUCE_NAMESPACE
  54432. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  54433. const double rangeMin,
  54434. const double rangeMax,
  54435. const double interval,
  54436. const double skewFactor)
  54437. : PropertyComponent (name)
  54438. {
  54439. addAndMakeVisible (slider = new Slider (name));
  54440. slider->setRange (rangeMin, rangeMax, interval);
  54441. slider->setSkewFactor (skewFactor);
  54442. slider->setSliderStyle (Slider::LinearBar);
  54443. slider->addListener (this);
  54444. }
  54445. SliderPropertyComponent::~SliderPropertyComponent()
  54446. {
  54447. deleteAllChildren();
  54448. }
  54449. void SliderPropertyComponent::refresh()
  54450. {
  54451. slider->setValue (getValue(), false);
  54452. }
  54453. void SliderPropertyComponent::sliderValueChanged (Slider*)
  54454. {
  54455. if (getValue() != slider->getValue())
  54456. setValue (slider->getValue());
  54457. }
  54458. END_JUCE_NAMESPACE
  54459. /********* End of inlined file: juce_SliderPropertyComponent.cpp *********/
  54460. /********* Start of inlined file: juce_TextPropertyComponent.cpp *********/
  54461. BEGIN_JUCE_NAMESPACE
  54462. class TextPropLabel : public Label
  54463. {
  54464. TextPropertyComponent& owner;
  54465. int maxChars;
  54466. bool isMultiline;
  54467. public:
  54468. TextPropLabel (TextPropertyComponent& owner_,
  54469. const int maxChars_, const bool isMultiline_)
  54470. : Label (String::empty, String::empty),
  54471. owner (owner_),
  54472. maxChars (maxChars_),
  54473. isMultiline (isMultiline_)
  54474. {
  54475. setEditable (true, true, false);
  54476. setColour (backgroundColourId, Colours::white);
  54477. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  54478. }
  54479. ~TextPropLabel()
  54480. {
  54481. }
  54482. TextEditor* createEditorComponent()
  54483. {
  54484. TextEditor* const textEditor = Label::createEditorComponent();
  54485. textEditor->setInputRestrictions (maxChars);
  54486. if (isMultiline)
  54487. {
  54488. textEditor->setMultiLine (true, true);
  54489. textEditor->setReturnKeyStartsNewLine (true);
  54490. }
  54491. return textEditor;
  54492. }
  54493. void textWasEdited()
  54494. {
  54495. owner.textWasEdited();
  54496. }
  54497. };
  54498. TextPropertyComponent::TextPropertyComponent (const String& name,
  54499. const int maxNumChars,
  54500. const bool isMultiLine)
  54501. : PropertyComponent (name)
  54502. {
  54503. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  54504. if (isMultiLine)
  54505. {
  54506. textEditor->setJustificationType (Justification::topLeft);
  54507. preferredHeight = 120;
  54508. }
  54509. }
  54510. TextPropertyComponent::~TextPropertyComponent()
  54511. {
  54512. deleteAllChildren();
  54513. }
  54514. void TextPropertyComponent::refresh()
  54515. {
  54516. textEditor->setText (getText(), false);
  54517. }
  54518. void TextPropertyComponent::textWasEdited()
  54519. {
  54520. const String newText (textEditor->getText());
  54521. if (getText() != newText)
  54522. setText (newText);
  54523. }
  54524. END_JUCE_NAMESPACE
  54525. /********* End of inlined file: juce_TextPropertyComponent.cpp *********/
  54526. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  54527. BEGIN_JUCE_NAMESPACE
  54528. class SimpleDeviceManagerInputLevelMeter : public Component,
  54529. public Timer
  54530. {
  54531. public:
  54532. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  54533. : manager (manager_),
  54534. level (0)
  54535. {
  54536. startTimer (50);
  54537. manager->enableInputLevelMeasurement (true);
  54538. }
  54539. ~SimpleDeviceManagerInputLevelMeter()
  54540. {
  54541. manager->enableInputLevelMeasurement (false);
  54542. }
  54543. void timerCallback()
  54544. {
  54545. const float newLevel = (float) manager->getCurrentInputLevel();
  54546. if (fabsf (level - newLevel) > 0.005f)
  54547. {
  54548. level = newLevel;
  54549. repaint();
  54550. }
  54551. }
  54552. void paint (Graphics& g)
  54553. {
  54554. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(), level);
  54555. }
  54556. private:
  54557. AudioDeviceManager* const manager;
  54558. float level;
  54559. };
  54560. class MidiInputSelectorComponentListBox : public ListBox,
  54561. public ListBoxModel
  54562. {
  54563. public:
  54564. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  54565. const String& noItemsMessage_,
  54566. const int minNumber_,
  54567. const int maxNumber_)
  54568. : ListBox (String::empty, 0),
  54569. deviceManager (deviceManager_),
  54570. noItemsMessage (noItemsMessage_),
  54571. minNumber (minNumber_),
  54572. maxNumber (maxNumber_)
  54573. {
  54574. items = MidiInput::getDevices();
  54575. setModel (this);
  54576. setOutlineThickness (1);
  54577. }
  54578. ~MidiInputSelectorComponentListBox()
  54579. {
  54580. }
  54581. int getNumRows()
  54582. {
  54583. return items.size();
  54584. }
  54585. void paintListBoxItem (int row,
  54586. Graphics& g,
  54587. int width, int height,
  54588. bool rowIsSelected)
  54589. {
  54590. if (((unsigned int) row) < (unsigned int) items.size())
  54591. {
  54592. if (rowIsSelected)
  54593. g.fillAll (findColour (TextEditor::highlightColourId)
  54594. .withMultipliedAlpha (0.3f));
  54595. const String item (items [row]);
  54596. bool enabled = deviceManager.isMidiInputEnabled (item);
  54597. const int x = getTickX();
  54598. const int tickW = height - height / 4;
  54599. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  54600. enabled, true, true, false);
  54601. g.setFont (height * 0.6f);
  54602. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  54603. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  54604. }
  54605. }
  54606. void listBoxItemClicked (int row, const MouseEvent& e)
  54607. {
  54608. selectRow (row);
  54609. if (e.x < getTickX())
  54610. flipEnablement (row);
  54611. }
  54612. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  54613. {
  54614. flipEnablement (row);
  54615. }
  54616. void returnKeyPressed (int row)
  54617. {
  54618. flipEnablement (row);
  54619. }
  54620. void paint (Graphics& g)
  54621. {
  54622. ListBox::paint (g);
  54623. if (items.size() == 0)
  54624. {
  54625. g.setColour (Colours::grey);
  54626. g.setFont (13.0f);
  54627. g.drawText (noItemsMessage,
  54628. 0, 0, getWidth(), getHeight() / 2,
  54629. Justification::centred, true);
  54630. }
  54631. }
  54632. int getBestHeight (const int preferredHeight)
  54633. {
  54634. const int extra = getOutlineThickness() * 2;
  54635. return jmax (getRowHeight() * 2 + extra,
  54636. jmin (getRowHeight() * getNumRows() + extra,
  54637. preferredHeight));
  54638. }
  54639. juce_UseDebuggingNewOperator
  54640. private:
  54641. AudioDeviceManager& deviceManager;
  54642. const String noItemsMessage;
  54643. StringArray items;
  54644. int minNumber, maxNumber;
  54645. void flipEnablement (const int row)
  54646. {
  54647. if (((unsigned int) row) < (unsigned int) items.size())
  54648. {
  54649. const String item (items [row]);
  54650. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  54651. }
  54652. }
  54653. int getTickX() const throw()
  54654. {
  54655. return getRowHeight() + 5;
  54656. }
  54657. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  54658. const MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  54659. };
  54660. class AudioDeviceSettingsPanel : public Component,
  54661. public ComboBoxListener,
  54662. public ChangeListener,
  54663. public ButtonListener
  54664. {
  54665. public:
  54666. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  54667. AudioIODeviceType::DeviceSetupDetails& setup_,
  54668. const bool hideAdvancedOptionsWithButton)
  54669. : type (type_),
  54670. setup (setup_)
  54671. {
  54672. sampleRateDropDown = 0;
  54673. sampleRateLabel = 0;
  54674. bufferSizeDropDown = 0;
  54675. bufferSizeLabel = 0;
  54676. outputDeviceDropDown = 0;
  54677. outputDeviceLabel = 0;
  54678. inputDeviceDropDown = 0;
  54679. inputDeviceLabel = 0;
  54680. testButton = 0;
  54681. inputLevelMeter = 0;
  54682. showUIButton = 0;
  54683. inputChanList = 0;
  54684. outputChanList = 0;
  54685. inputChanLabel = 0;
  54686. outputChanLabel = 0;
  54687. showAdvancedSettingsButton = 0;
  54688. if (hideAdvancedOptionsWithButton)
  54689. {
  54690. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  54691. showAdvancedSettingsButton->addButtonListener (this);
  54692. }
  54693. type->scanForDevices();
  54694. setup.manager->addChangeListener (this);
  54695. changeListenerCallback (0);
  54696. }
  54697. ~AudioDeviceSettingsPanel()
  54698. {
  54699. setup.manager->removeChangeListener (this);
  54700. deleteAndZero (outputDeviceLabel);
  54701. deleteAndZero (inputDeviceLabel);
  54702. deleteAndZero (sampleRateLabel);
  54703. deleteAndZero (bufferSizeLabel);
  54704. deleteAndZero (showUIButton);
  54705. deleteAndZero (inputChanLabel);
  54706. deleteAndZero (outputChanLabel);
  54707. deleteAndZero (showAdvancedSettingsButton);
  54708. deleteAllChildren();
  54709. }
  54710. void resized()
  54711. {
  54712. const int lx = proportionOfWidth (0.35f);
  54713. const int w = proportionOfWidth (0.4f);
  54714. const int h = 24;
  54715. const int space = 6;
  54716. const int dh = h + space;
  54717. int y = 0;
  54718. if (outputDeviceDropDown != 0)
  54719. {
  54720. outputDeviceDropDown->setBounds (lx, y, w, h);
  54721. if (testButton != 0)
  54722. testButton->setBounds (proportionOfWidth (0.77f),
  54723. outputDeviceDropDown->getY(),
  54724. proportionOfWidth (0.18f),
  54725. h);
  54726. y += dh;
  54727. }
  54728. if (inputDeviceDropDown != 0)
  54729. {
  54730. inputDeviceDropDown->setBounds (lx, y, w, h);
  54731. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  54732. inputDeviceDropDown->getY(),
  54733. proportionOfWidth (0.18f),
  54734. h);
  54735. y += dh;
  54736. }
  54737. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  54738. if (outputChanList != 0)
  54739. {
  54740. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  54741. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  54742. y += bh + space;
  54743. }
  54744. if (inputChanList != 0)
  54745. {
  54746. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  54747. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  54748. y += bh + space;
  54749. }
  54750. y += space * 2;
  54751. if (showAdvancedSettingsButton != 0)
  54752. {
  54753. showAdvancedSettingsButton->changeWidthToFitText (h);
  54754. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  54755. }
  54756. if (sampleRateDropDown != 0)
  54757. {
  54758. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  54759. || ! showAdvancedSettingsButton->isVisible());
  54760. sampleRateDropDown->setBounds (lx, y, w, h);
  54761. y += dh;
  54762. }
  54763. if (bufferSizeDropDown != 0)
  54764. {
  54765. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  54766. || ! showAdvancedSettingsButton->isVisible());
  54767. bufferSizeDropDown->setBounds (lx, y, w, h);
  54768. y += dh;
  54769. }
  54770. if (showUIButton != 0)
  54771. {
  54772. showUIButton->setVisible (showAdvancedSettingsButton == 0
  54773. || ! showAdvancedSettingsButton->isVisible());
  54774. showUIButton->changeWidthToFitText (h);
  54775. showUIButton->setTopLeftPosition (lx, y);
  54776. }
  54777. }
  54778. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  54779. {
  54780. if (comboBoxThatHasChanged == 0)
  54781. return;
  54782. AudioDeviceManager::AudioDeviceSetup config;
  54783. setup.manager->getAudioDeviceSetup (config);
  54784. String error;
  54785. if (comboBoxThatHasChanged == outputDeviceDropDown
  54786. || comboBoxThatHasChanged == inputDeviceDropDown)
  54787. {
  54788. if (outputDeviceDropDown != 0)
  54789. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  54790. : outputDeviceDropDown->getText();
  54791. if (inputDeviceDropDown != 0)
  54792. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  54793. : inputDeviceDropDown->getText();
  54794. if (! type->hasSeparateInputsAndOutputs())
  54795. config.inputDeviceName = config.outputDeviceName;
  54796. if (comboBoxThatHasChanged == inputDeviceDropDown)
  54797. config.useDefaultInputChannels = true;
  54798. else
  54799. config.useDefaultOutputChannels = true;
  54800. error = setup.manager->setAudioDeviceSetup (config, true);
  54801. showCorrectDeviceName (inputDeviceDropDown, true);
  54802. showCorrectDeviceName (outputDeviceDropDown, false);
  54803. updateControlPanelButton();
  54804. resized();
  54805. }
  54806. else if (comboBoxThatHasChanged == sampleRateDropDown)
  54807. {
  54808. if (sampleRateDropDown->getSelectedId() > 0)
  54809. {
  54810. config.sampleRate = sampleRateDropDown->getSelectedId();
  54811. error = setup.manager->setAudioDeviceSetup (config, true);
  54812. }
  54813. }
  54814. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  54815. {
  54816. if (bufferSizeDropDown->getSelectedId() > 0)
  54817. {
  54818. config.bufferSize = bufferSizeDropDown->getSelectedId();
  54819. error = setup.manager->setAudioDeviceSetup (config, true);
  54820. }
  54821. }
  54822. if (error.isNotEmpty())
  54823. {
  54824. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  54825. T("Error when trying to open audio device!"),
  54826. error);
  54827. }
  54828. }
  54829. void buttonClicked (Button* button)
  54830. {
  54831. if (button == showAdvancedSettingsButton)
  54832. {
  54833. showAdvancedSettingsButton->setVisible (false);
  54834. resized();
  54835. }
  54836. else if (button == showUIButton)
  54837. {
  54838. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  54839. if (device != 0 && device->showControlPanel())
  54840. {
  54841. setup.manager->closeAudioDevice();
  54842. setup.manager->restartLastAudioDevice();
  54843. getTopLevelComponent()->toFront (true);
  54844. }
  54845. }
  54846. else if (button == testButton && testButton != 0)
  54847. {
  54848. setup.manager->playTestSound();
  54849. }
  54850. }
  54851. void updateControlPanelButton()
  54852. {
  54853. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  54854. deleteAndZero (showUIButton);
  54855. if (currentDevice != 0 && currentDevice->hasControlPanel())
  54856. {
  54857. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  54858. TRANS ("opens the device's own control panel")));
  54859. showUIButton->addButtonListener (this);
  54860. }
  54861. resized();
  54862. }
  54863. void changeListenerCallback (void*)
  54864. {
  54865. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  54866. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  54867. {
  54868. if (outputDeviceDropDown == 0)
  54869. {
  54870. outputDeviceDropDown = new ComboBox (String::empty);
  54871. outputDeviceDropDown->addListener (this);
  54872. addAndMakeVisible (outputDeviceDropDown);
  54873. outputDeviceLabel = new Label (String::empty,
  54874. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  54875. : TRANS ("device:"));
  54876. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  54877. if (setup.maxNumOutputChannels > 0)
  54878. {
  54879. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  54880. testButton->addButtonListener (this);
  54881. }
  54882. }
  54883. addNamesToDeviceBox (*outputDeviceDropDown, false);
  54884. }
  54885. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  54886. {
  54887. if (inputDeviceDropDown == 0)
  54888. {
  54889. inputDeviceDropDown = new ComboBox (String::empty);
  54890. inputDeviceDropDown->addListener (this);
  54891. addAndMakeVisible (inputDeviceDropDown);
  54892. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  54893. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  54894. addAndMakeVisible (inputLevelMeter
  54895. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  54896. }
  54897. addNamesToDeviceBox (*inputDeviceDropDown, true);
  54898. }
  54899. updateControlPanelButton();
  54900. showCorrectDeviceName (inputDeviceDropDown, true);
  54901. showCorrectDeviceName (outputDeviceDropDown, false);
  54902. if (currentDevice != 0)
  54903. {
  54904. if (setup.maxNumOutputChannels > 0
  54905. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  54906. {
  54907. if (outputChanList == 0)
  54908. {
  54909. addAndMakeVisible (outputChanList
  54910. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  54911. TRANS ("(no audio output channels found)")));
  54912. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  54913. outputChanLabel->attachToComponent (outputChanList, true);
  54914. }
  54915. outputChanList->refresh();
  54916. }
  54917. else
  54918. {
  54919. deleteAndZero (outputChanLabel);
  54920. deleteAndZero (outputChanList);
  54921. }
  54922. if (setup.maxNumInputChannels > 0
  54923. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  54924. {
  54925. if (inputChanList == 0)
  54926. {
  54927. addAndMakeVisible (inputChanList
  54928. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  54929. TRANS ("(no audio input channels found)")));
  54930. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  54931. inputChanLabel->attachToComponent (inputChanList, true);
  54932. }
  54933. inputChanList->refresh();
  54934. }
  54935. else
  54936. {
  54937. deleteAndZero (inputChanLabel);
  54938. deleteAndZero (inputChanList);
  54939. }
  54940. // sample rate..
  54941. {
  54942. if (sampleRateDropDown == 0)
  54943. {
  54944. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  54945. sampleRateDropDown->addListener (this);
  54946. delete sampleRateLabel;
  54947. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  54948. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  54949. }
  54950. else
  54951. {
  54952. sampleRateDropDown->clear();
  54953. sampleRateDropDown->removeListener (this);
  54954. }
  54955. const int numRates = currentDevice->getNumSampleRates();
  54956. for (int i = 0; i < numRates; ++i)
  54957. {
  54958. const int rate = roundDoubleToInt (currentDevice->getSampleRate (i));
  54959. sampleRateDropDown->addItem (String (rate) + T(" Hz"), rate);
  54960. }
  54961. sampleRateDropDown->setSelectedId (roundDoubleToInt (currentDevice->getCurrentSampleRate()), true);
  54962. sampleRateDropDown->addListener (this);
  54963. }
  54964. // buffer size
  54965. {
  54966. if (bufferSizeDropDown == 0)
  54967. {
  54968. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  54969. bufferSizeDropDown->addListener (this);
  54970. delete bufferSizeLabel;
  54971. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  54972. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  54973. }
  54974. else
  54975. {
  54976. bufferSizeDropDown->clear();
  54977. }
  54978. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  54979. double currentRate = currentDevice->getCurrentSampleRate();
  54980. if (currentRate == 0)
  54981. currentRate = 48000.0;
  54982. for (int i = 0; i < numBufferSizes; ++i)
  54983. {
  54984. const int bs = currentDevice->getBufferSizeSamples (i);
  54985. bufferSizeDropDown->addItem (String (bs)
  54986. + T(" samples (")
  54987. + String (bs * 1000.0 / currentRate, 1)
  54988. + T(" ms)"),
  54989. bs);
  54990. }
  54991. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  54992. }
  54993. }
  54994. else
  54995. {
  54996. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  54997. deleteAndZero (sampleRateLabel);
  54998. deleteAndZero (bufferSizeLabel);
  54999. deleteAndZero (sampleRateDropDown);
  55000. deleteAndZero (bufferSizeDropDown);
  55001. if (outputDeviceDropDown != 0)
  55002. outputDeviceDropDown->setSelectedId (-1, true);
  55003. if (inputDeviceDropDown != 0)
  55004. inputDeviceDropDown->setSelectedId (-1, true);
  55005. }
  55006. resized();
  55007. setSize (getWidth(), getLowestY() + 4);
  55008. }
  55009. private:
  55010. AudioIODeviceType* const type;
  55011. const AudioIODeviceType::DeviceSetupDetails setup;
  55012. ComboBox* outputDeviceDropDown;
  55013. ComboBox* inputDeviceDropDown;
  55014. ComboBox* sampleRateDropDown;
  55015. ComboBox* bufferSizeDropDown;
  55016. Label* outputDeviceLabel;
  55017. Label* inputDeviceLabel;
  55018. Label* sampleRateLabel;
  55019. Label* bufferSizeLabel;
  55020. Label* inputChanLabel;
  55021. Label* outputChanLabel;
  55022. TextButton* testButton;
  55023. Component* inputLevelMeter;
  55024. TextButton* showUIButton;
  55025. TextButton* showAdvancedSettingsButton;
  55026. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  55027. {
  55028. if (box != 0)
  55029. {
  55030. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  55031. const int index = type->getIndexOfDevice (currentDevice, isInput);
  55032. box->setSelectedId (index + 1, true);
  55033. if (testButton != 0 && ! isInput)
  55034. testButton->setEnabled (index >= 0);
  55035. }
  55036. }
  55037. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  55038. {
  55039. const StringArray devs (type->getDeviceNames (isInputs));
  55040. combo.clear (true);
  55041. for (int i = 0; i < devs.size(); ++i)
  55042. combo.addItem (devs[i], i + 1);
  55043. combo.addItem (TRANS("<< none >>"), -1);
  55044. combo.setSelectedId (-1, true);
  55045. }
  55046. int getLowestY() const
  55047. {
  55048. int y = 0;
  55049. for (int i = getNumChildComponents(); --i >= 0;)
  55050. y = jmax (y, getChildComponent (i)->getBottom());
  55051. return y;
  55052. }
  55053. class ChannelSelectorListBox : public ListBox,
  55054. public ListBoxModel
  55055. {
  55056. public:
  55057. enum BoxType
  55058. {
  55059. audioInputType,
  55060. audioOutputType
  55061. };
  55062. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  55063. const BoxType type_,
  55064. const String& noItemsMessage_)
  55065. : ListBox (String::empty, 0),
  55066. setup (setup_),
  55067. type (type_),
  55068. noItemsMessage (noItemsMessage_)
  55069. {
  55070. refresh();
  55071. setModel (this);
  55072. setOutlineThickness (1);
  55073. }
  55074. ~ChannelSelectorListBox()
  55075. {
  55076. }
  55077. void refresh()
  55078. {
  55079. items.clear();
  55080. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55081. if (currentDevice != 0)
  55082. {
  55083. if (type == audioInputType)
  55084. items = currentDevice->getInputChannelNames();
  55085. else if (type == audioOutputType)
  55086. items = currentDevice->getOutputChannelNames();
  55087. if (setup.useStereoPairs)
  55088. {
  55089. StringArray pairs;
  55090. for (int i = 0; i < items.size(); i += 2)
  55091. {
  55092. String name (items[i]);
  55093. String name2 (items[i + 1]);
  55094. String commonBit;
  55095. for (int j = 0; j < name.length(); ++j)
  55096. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  55097. commonBit = name.substring (0, j);
  55098. pairs.add (name.trim()
  55099. + " + "
  55100. + name2.substring (commonBit.length()).trim());
  55101. }
  55102. items = pairs;
  55103. }
  55104. }
  55105. updateContent();
  55106. repaint();
  55107. }
  55108. int getNumRows()
  55109. {
  55110. return items.size();
  55111. }
  55112. void paintListBoxItem (int row,
  55113. Graphics& g,
  55114. int width, int height,
  55115. bool rowIsSelected)
  55116. {
  55117. if (((unsigned int) row) < (unsigned int) items.size())
  55118. {
  55119. if (rowIsSelected)
  55120. g.fillAll (findColour (TextEditor::highlightColourId)
  55121. .withMultipliedAlpha (0.3f));
  55122. const String item (items [row]);
  55123. bool enabled = false;
  55124. AudioDeviceManager::AudioDeviceSetup config;
  55125. setup.manager->getAudioDeviceSetup (config);
  55126. if (setup.useStereoPairs)
  55127. {
  55128. if (type == audioInputType)
  55129. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  55130. else if (type == audioOutputType)
  55131. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  55132. }
  55133. else
  55134. {
  55135. if (type == audioInputType)
  55136. enabled = config.inputChannels [row];
  55137. else if (type == audioOutputType)
  55138. enabled = config.outputChannels [row];
  55139. }
  55140. const int x = getTickX();
  55141. const int tickW = height - height / 4;
  55142. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  55143. enabled, true, true, false);
  55144. g.setFont (height * 0.6f);
  55145. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  55146. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  55147. }
  55148. }
  55149. void listBoxItemClicked (int row, const MouseEvent& e)
  55150. {
  55151. selectRow (row);
  55152. if (e.x < getTickX())
  55153. flipEnablement (row);
  55154. }
  55155. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  55156. {
  55157. flipEnablement (row);
  55158. }
  55159. void returnKeyPressed (int row)
  55160. {
  55161. flipEnablement (row);
  55162. }
  55163. void paint (Graphics& g)
  55164. {
  55165. ListBox::paint (g);
  55166. if (items.size() == 0)
  55167. {
  55168. g.setColour (Colours::grey);
  55169. g.setFont (13.0f);
  55170. g.drawText (noItemsMessage,
  55171. 0, 0, getWidth(), getHeight() / 2,
  55172. Justification::centred, true);
  55173. }
  55174. }
  55175. int getBestHeight (int maxHeight)
  55176. {
  55177. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  55178. getNumRows())
  55179. + getOutlineThickness() * 2;
  55180. }
  55181. juce_UseDebuggingNewOperator
  55182. private:
  55183. const AudioIODeviceType::DeviceSetupDetails setup;
  55184. const BoxType type;
  55185. const String noItemsMessage;
  55186. StringArray items;
  55187. void flipEnablement (const int row)
  55188. {
  55189. jassert (type == audioInputType || type == audioOutputType);
  55190. if (((unsigned int) row) < (unsigned int) items.size())
  55191. {
  55192. AudioDeviceManager::AudioDeviceSetup config;
  55193. setup.manager->getAudioDeviceSetup (config);
  55194. if (setup.useStereoPairs)
  55195. {
  55196. BitArray bits;
  55197. BitArray& original = (type == audioInputType ? config.inputChannels
  55198. : config.outputChannels);
  55199. int i;
  55200. for (i = 0; i < 256; i += 2)
  55201. bits.setBit (i / 2, original [i] || original [i + 1]);
  55202. if (type == audioInputType)
  55203. {
  55204. config.useDefaultInputChannels = false;
  55205. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  55206. }
  55207. else
  55208. {
  55209. config.useDefaultOutputChannels = false;
  55210. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  55211. }
  55212. for (i = 0; i < 256; ++i)
  55213. original.setBit (i, bits [i / 2]);
  55214. }
  55215. else
  55216. {
  55217. if (type == audioInputType)
  55218. {
  55219. config.useDefaultInputChannels = false;
  55220. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  55221. }
  55222. else
  55223. {
  55224. config.useDefaultOutputChannels = false;
  55225. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  55226. }
  55227. }
  55228. String error (setup.manager->setAudioDeviceSetup (config, true));
  55229. if (! error.isEmpty())
  55230. {
  55231. //xxx
  55232. }
  55233. }
  55234. }
  55235. static void flipBit (BitArray& chans, int index, int minNumber, int maxNumber)
  55236. {
  55237. const int numActive = chans.countNumberOfSetBits();
  55238. if (chans [index])
  55239. {
  55240. if (numActive > minNumber)
  55241. chans.setBit (index, false);
  55242. }
  55243. else
  55244. {
  55245. if (numActive >= maxNumber)
  55246. {
  55247. const int firstActiveChan = chans.findNextSetBit();
  55248. chans.setBit (index > firstActiveChan
  55249. ? firstActiveChan : chans.getHighestBit(),
  55250. false);
  55251. }
  55252. chans.setBit (index, true);
  55253. }
  55254. }
  55255. int getTickX() const throw()
  55256. {
  55257. return getRowHeight() + 5;
  55258. }
  55259. ChannelSelectorListBox (const ChannelSelectorListBox&);
  55260. const ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  55261. };
  55262. ChannelSelectorListBox* inputChanList;
  55263. ChannelSelectorListBox* outputChanList;
  55264. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  55265. const AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  55266. };
  55267. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  55268. const int minInputChannels_,
  55269. const int maxInputChannels_,
  55270. const int minOutputChannels_,
  55271. const int maxOutputChannels_,
  55272. const bool showMidiInputOptions,
  55273. const bool showMidiOutputSelector,
  55274. const bool showChannelsAsStereoPairs_,
  55275. const bool hideAdvancedOptionsWithButton_)
  55276. : deviceManager (deviceManager_),
  55277. deviceTypeDropDown (0),
  55278. deviceTypeDropDownLabel (0),
  55279. audioDeviceSettingsComp (0),
  55280. minOutputChannels (minOutputChannels_),
  55281. maxOutputChannels (maxOutputChannels_),
  55282. minInputChannels (minInputChannels_),
  55283. maxInputChannels (maxInputChannels_),
  55284. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  55285. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  55286. {
  55287. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  55288. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  55289. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  55290. {
  55291. deviceTypeDropDown = new ComboBox (String::empty);
  55292. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  55293. {
  55294. deviceTypeDropDown
  55295. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  55296. i + 1);
  55297. }
  55298. addAndMakeVisible (deviceTypeDropDown);
  55299. deviceTypeDropDown->addListener (this);
  55300. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  55301. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  55302. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  55303. }
  55304. if (showMidiInputOptions)
  55305. {
  55306. addAndMakeVisible (midiInputsList
  55307. = new MidiInputSelectorComponentListBox (deviceManager,
  55308. TRANS("(no midi inputs available)"),
  55309. 0, 0));
  55310. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  55311. midiInputsLabel->setJustificationType (Justification::topRight);
  55312. midiInputsLabel->attachToComponent (midiInputsList, true);
  55313. }
  55314. else
  55315. {
  55316. midiInputsList = 0;
  55317. midiInputsLabel = 0;
  55318. }
  55319. if (showMidiOutputSelector)
  55320. {
  55321. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  55322. midiOutputSelector->addListener (this);
  55323. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  55324. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  55325. }
  55326. else
  55327. {
  55328. midiOutputSelector = 0;
  55329. midiOutputLabel = 0;
  55330. }
  55331. deviceManager_.addChangeListener (this);
  55332. changeListenerCallback (0);
  55333. }
  55334. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  55335. {
  55336. deviceManager.removeChangeListener (this);
  55337. deleteAllChildren();
  55338. }
  55339. void AudioDeviceSelectorComponent::resized()
  55340. {
  55341. const int lx = proportionOfWidth (0.35f);
  55342. const int w = proportionOfWidth (0.4f);
  55343. const int h = 24;
  55344. const int space = 6;
  55345. const int dh = h + space;
  55346. int y = 15;
  55347. if (deviceTypeDropDown != 0)
  55348. {
  55349. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  55350. y += dh + space * 2;
  55351. }
  55352. if (audioDeviceSettingsComp != 0)
  55353. {
  55354. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  55355. y += audioDeviceSettingsComp->getHeight() + space;
  55356. }
  55357. if (midiInputsList != 0)
  55358. {
  55359. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  55360. midiInputsList->setBounds (lx, y, w, bh);
  55361. y += bh + space;
  55362. }
  55363. if (midiOutputSelector != 0)
  55364. midiOutputSelector->setBounds (lx, y, w, h);
  55365. }
  55366. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  55367. {
  55368. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  55369. if (device != 0 && device->hasControlPanel())
  55370. {
  55371. if (device->showControlPanel())
  55372. deviceManager.restartLastAudioDevice();
  55373. getTopLevelComponent()->toFront (true);
  55374. }
  55375. }
  55376. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  55377. {
  55378. if (comboBoxThatHasChanged == deviceTypeDropDown)
  55379. {
  55380. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  55381. if (type != 0)
  55382. {
  55383. deleteAndZero (audioDeviceSettingsComp);
  55384. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  55385. changeListenerCallback (0); // needed in case the type hasn't actally changed
  55386. }
  55387. }
  55388. else if (comboBoxThatHasChanged == midiOutputSelector)
  55389. {
  55390. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  55391. }
  55392. }
  55393. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  55394. {
  55395. if (deviceTypeDropDown != 0)
  55396. {
  55397. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  55398. }
  55399. if (audioDeviceSettingsComp == 0
  55400. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  55401. {
  55402. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  55403. deleteAndZero (audioDeviceSettingsComp);
  55404. AudioIODeviceType* const type
  55405. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  55406. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  55407. if (type != 0)
  55408. {
  55409. AudioIODeviceType::DeviceSetupDetails details;
  55410. details.manager = &deviceManager;
  55411. details.minNumInputChannels = minInputChannels;
  55412. details.maxNumInputChannels = maxInputChannels;
  55413. details.minNumOutputChannels = minOutputChannels;
  55414. details.maxNumOutputChannels = maxOutputChannels;
  55415. details.useStereoPairs = showChannelsAsStereoPairs;
  55416. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  55417. if (audioDeviceSettingsComp != 0)
  55418. {
  55419. addAndMakeVisible (audioDeviceSettingsComp);
  55420. audioDeviceSettingsComp->resized();
  55421. }
  55422. }
  55423. }
  55424. if (midiInputsList != 0)
  55425. {
  55426. midiInputsList->updateContent();
  55427. midiInputsList->repaint();
  55428. }
  55429. if (midiOutputSelector != 0)
  55430. {
  55431. midiOutputSelector->clear();
  55432. const StringArray midiOuts (MidiOutput::getDevices());
  55433. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  55434. midiOutputSelector->addSeparator();
  55435. for (int i = 0; i < midiOuts.size(); ++i)
  55436. midiOutputSelector->addItem (midiOuts[i], i + 1);
  55437. int current = -1;
  55438. if (deviceManager.getDefaultMidiOutput() != 0)
  55439. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  55440. midiOutputSelector->setSelectedId (current, true);
  55441. }
  55442. resized();
  55443. }
  55444. END_JUCE_NAMESPACE
  55445. /********* End of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  55446. /********* Start of inlined file: juce_BubbleComponent.cpp *********/
  55447. BEGIN_JUCE_NAMESPACE
  55448. BubbleComponent::BubbleComponent()
  55449. : side (0),
  55450. allowablePlacements (above | below | left | right),
  55451. arrowTipX (0.0f),
  55452. arrowTipY (0.0f)
  55453. {
  55454. setInterceptsMouseClicks (false, false);
  55455. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  55456. setComponentEffect (&shadow);
  55457. }
  55458. BubbleComponent::~BubbleComponent()
  55459. {
  55460. }
  55461. void BubbleComponent::paint (Graphics& g)
  55462. {
  55463. int x = content.getX();
  55464. int y = content.getY();
  55465. int w = content.getWidth();
  55466. int h = content.getHeight();
  55467. int cw, ch;
  55468. getContentSize (cw, ch);
  55469. if (side == 3)
  55470. x += w - cw;
  55471. else if (side != 1)
  55472. x += (w - cw) / 2;
  55473. w = cw;
  55474. if (side == 2)
  55475. y += h - ch;
  55476. else if (side != 0)
  55477. y += (h - ch) / 2;
  55478. h = ch;
  55479. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  55480. (float) x, (float) y,
  55481. (float) w, (float) h);
  55482. const int cx = x + (w - cw) / 2;
  55483. const int cy = y + (h - ch) / 2;
  55484. const int indent = 3;
  55485. g.setOrigin (cx + indent, cy + indent);
  55486. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  55487. paintContent (g, cw - indent * 2, ch - indent * 2);
  55488. }
  55489. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  55490. {
  55491. allowablePlacements = newPlacement;
  55492. }
  55493. void BubbleComponent::setPosition (Component* componentToPointTo)
  55494. {
  55495. jassert (componentToPointTo->isValidComponent());
  55496. int tx = 0;
  55497. int ty = 0;
  55498. if (getParentComponent() != 0)
  55499. componentToPointTo->relativePositionToOtherComponent (getParentComponent(), tx, ty);
  55500. else
  55501. componentToPointTo->relativePositionToGlobal (tx, ty);
  55502. setPosition (Rectangle (tx, ty, componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  55503. }
  55504. void BubbleComponent::setPosition (const int arrowTipX,
  55505. const int arrowTipY)
  55506. {
  55507. setPosition (Rectangle (arrowTipX, arrowTipY, 1, 1));
  55508. }
  55509. void BubbleComponent::setPosition (const Rectangle& rectangleToPointTo)
  55510. {
  55511. Rectangle availableSpace;
  55512. if (getParentComponent() != 0)
  55513. {
  55514. availableSpace.setSize (getParentComponent()->getWidth(),
  55515. getParentComponent()->getHeight());
  55516. }
  55517. else
  55518. {
  55519. availableSpace = getParentMonitorArea();
  55520. }
  55521. int x = 0;
  55522. int y = 0;
  55523. int w = 150;
  55524. int h = 30;
  55525. getContentSize (w, h);
  55526. w += 30;
  55527. h += 30;
  55528. const float edgeIndent = 2.0f;
  55529. const int arrowLength = jmin (10, h / 3, w / 3);
  55530. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  55531. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  55532. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  55533. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  55534. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  55535. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  55536. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  55537. {
  55538. spaceLeft = spaceRight = 0;
  55539. }
  55540. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  55541. && (spaceLeft > w + 20 || spaceRight > w + 20))
  55542. {
  55543. spaceAbove = spaceBelow = 0;
  55544. }
  55545. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  55546. {
  55547. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  55548. arrowTipX = w * 0.5f;
  55549. content.setSize (w, h - arrowLength);
  55550. if (spaceAbove >= spaceBelow)
  55551. {
  55552. // above
  55553. y = rectangleToPointTo.getY() - h;
  55554. content.setPosition (0, 0);
  55555. arrowTipY = h - edgeIndent;
  55556. side = 2;
  55557. }
  55558. else
  55559. {
  55560. // below
  55561. y = rectangleToPointTo.getBottom();
  55562. content.setPosition (0, arrowLength);
  55563. arrowTipY = edgeIndent;
  55564. side = 0;
  55565. }
  55566. }
  55567. else
  55568. {
  55569. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  55570. arrowTipY = h * 0.5f;
  55571. content.setSize (w - arrowLength, h);
  55572. if (spaceLeft > spaceRight)
  55573. {
  55574. // on the left
  55575. x = rectangleToPointTo.getX() - w;
  55576. content.setPosition (0, 0);
  55577. arrowTipX = w - edgeIndent;
  55578. side = 3;
  55579. }
  55580. else
  55581. {
  55582. // on the right
  55583. x = rectangleToPointTo.getRight();
  55584. content.setPosition (arrowLength, 0);
  55585. arrowTipX = edgeIndent;
  55586. side = 1;
  55587. }
  55588. }
  55589. setBounds (x, y, w, h);
  55590. }
  55591. END_JUCE_NAMESPACE
  55592. /********* End of inlined file: juce_BubbleComponent.cpp *********/
  55593. /********* Start of inlined file: juce_BubbleMessageComponent.cpp *********/
  55594. BEGIN_JUCE_NAMESPACE
  55595. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  55596. : fadeOutLength (fadeOutLengthMs),
  55597. deleteAfterUse (false)
  55598. {
  55599. }
  55600. BubbleMessageComponent::~BubbleMessageComponent()
  55601. {
  55602. fadeOutComponent (fadeOutLength);
  55603. }
  55604. void BubbleMessageComponent::showAt (int x, int y,
  55605. const String& text,
  55606. const int numMillisecondsBeforeRemoving,
  55607. const bool removeWhenMouseClicked,
  55608. const bool deleteSelfAfterUse)
  55609. {
  55610. textLayout.clear();
  55611. textLayout.setText (text, Font (14.0f));
  55612. textLayout.layout (256, Justification::centredLeft, true);
  55613. setPosition (x, y);
  55614. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  55615. }
  55616. void BubbleMessageComponent::showAt (Component* const component,
  55617. const String& text,
  55618. const int numMillisecondsBeforeRemoving,
  55619. const bool removeWhenMouseClicked,
  55620. const bool deleteSelfAfterUse)
  55621. {
  55622. textLayout.clear();
  55623. textLayout.setText (text, Font (14.0f));
  55624. textLayout.layout (256, Justification::centredLeft, true);
  55625. setPosition (component);
  55626. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  55627. }
  55628. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  55629. const bool removeWhenMouseClicked,
  55630. const bool deleteSelfAfterUse)
  55631. {
  55632. setVisible (true);
  55633. deleteAfterUse = deleteSelfAfterUse;
  55634. if (numMillisecondsBeforeRemoving > 0)
  55635. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  55636. else
  55637. expiryTime = 0;
  55638. startTimer (77);
  55639. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  55640. if (! (removeWhenMouseClicked && isShowing()))
  55641. mouseClickCounter += 0xfffff;
  55642. repaint();
  55643. }
  55644. void BubbleMessageComponent::getContentSize (int& w, int& h)
  55645. {
  55646. w = textLayout.getWidth() + 16;
  55647. h = textLayout.getHeight() + 16;
  55648. }
  55649. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  55650. {
  55651. g.setColour (findColour (TooltipWindow::textColourId));
  55652. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  55653. }
  55654. void BubbleMessageComponent::timerCallback()
  55655. {
  55656. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  55657. {
  55658. stopTimer();
  55659. setVisible (false);
  55660. if (deleteAfterUse)
  55661. delete this;
  55662. }
  55663. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  55664. {
  55665. stopTimer();
  55666. fadeOutComponent (fadeOutLength);
  55667. if (deleteAfterUse)
  55668. delete this;
  55669. }
  55670. }
  55671. END_JUCE_NAMESPACE
  55672. /********* End of inlined file: juce_BubbleMessageComponent.cpp *********/
  55673. /********* Start of inlined file: juce_ColourSelector.cpp *********/
  55674. BEGIN_JUCE_NAMESPACE
  55675. static const int swatchesPerRow = 8;
  55676. static const int swatchHeight = 22;
  55677. class ColourComponentSlider : public Slider
  55678. {
  55679. public:
  55680. ColourComponentSlider (const String& name)
  55681. : Slider (name)
  55682. {
  55683. setRange (0.0, 255.0, 1.0);
  55684. }
  55685. ~ColourComponentSlider()
  55686. {
  55687. }
  55688. const String getTextFromValue (double currentValue)
  55689. {
  55690. return String::formatted (T("%02X"), (int)currentValue);
  55691. }
  55692. double getValueFromText (const String& text)
  55693. {
  55694. return (double) text.getHexValue32();
  55695. }
  55696. private:
  55697. ColourComponentSlider (const ColourComponentSlider&);
  55698. const ColourComponentSlider& operator= (const ColourComponentSlider&);
  55699. };
  55700. class ColourSpaceMarker : public Component
  55701. {
  55702. public:
  55703. ColourSpaceMarker()
  55704. {
  55705. setInterceptsMouseClicks (false, false);
  55706. }
  55707. ~ColourSpaceMarker()
  55708. {
  55709. }
  55710. void paint (Graphics& g)
  55711. {
  55712. g.setColour (Colour::greyLevel (0.1f));
  55713. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  55714. g.setColour (Colour::greyLevel (0.9f));
  55715. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  55716. }
  55717. private:
  55718. ColourSpaceMarker (const ColourSpaceMarker&);
  55719. const ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  55720. };
  55721. class ColourSpaceView : public Component
  55722. {
  55723. ColourSelector* const owner;
  55724. float& h;
  55725. float& s;
  55726. float& v;
  55727. float lastHue;
  55728. ColourSpaceMarker* marker;
  55729. const int edge;
  55730. public:
  55731. ColourSpaceView (ColourSelector* owner_,
  55732. float& h_, float& s_, float& v_,
  55733. const int edgeSize)
  55734. : owner (owner_),
  55735. h (h_), s (s_), v (v_),
  55736. lastHue (0.0f),
  55737. edge (edgeSize)
  55738. {
  55739. addAndMakeVisible (marker = new ColourSpaceMarker());
  55740. setMouseCursor (MouseCursor::CrosshairCursor);
  55741. }
  55742. ~ColourSpaceView()
  55743. {
  55744. deleteAllChildren();
  55745. }
  55746. void paint (Graphics& g)
  55747. {
  55748. const float hue = h;
  55749. const float xScale = 1.0f / (getWidth() - edge * 2);
  55750. const float yScale = 1.0f / (getHeight() - edge * 2);
  55751. const Rectangle clip (g.getClipBounds());
  55752. const int x1 = jmax (clip.getX(), edge) & ~1;
  55753. const int x2 = jmin (clip.getRight(), getWidth() - edge) | 1;
  55754. const int y1 = jmax (clip.getY(), edge) & ~1;
  55755. const int y2 = jmin (clip.getBottom(), getHeight() - edge) | 1;
  55756. for (int y = y1; y < y2; y += 2)
  55757. {
  55758. const float v = jlimit (0.0f, 1.0f, 1.0f - (y - edge) * yScale);
  55759. for (int x = x1; x < x2; x += 2)
  55760. {
  55761. const float s = jlimit (0.0f, 1.0f, (x - edge) * xScale);
  55762. g.setColour (Colour (hue, s, v, 1.0f));
  55763. g.fillRect (x, y, 2, 2);
  55764. }
  55765. }
  55766. }
  55767. void mouseDown (const MouseEvent& e)
  55768. {
  55769. mouseDrag (e);
  55770. }
  55771. void mouseDrag (const MouseEvent& e)
  55772. {
  55773. const float s = (e.x - edge) / (float) (getWidth() - edge * 2);
  55774. const float v = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  55775. owner->setSV (s, v);
  55776. }
  55777. void updateIfNeeded()
  55778. {
  55779. if (lastHue != h)
  55780. {
  55781. lastHue = h;
  55782. repaint();
  55783. }
  55784. resized();
  55785. }
  55786. void resized()
  55787. {
  55788. marker->setBounds (roundFloatToInt ((getWidth() - edge * 2) * s),
  55789. roundFloatToInt ((getHeight() - edge * 2) * (1.0f - v)),
  55790. edge * 2, edge * 2);
  55791. }
  55792. private:
  55793. ColourSpaceView (const ColourSpaceView&);
  55794. const ColourSpaceView& operator= (const ColourSpaceView&);
  55795. };
  55796. class HueSelectorMarker : public Component
  55797. {
  55798. public:
  55799. HueSelectorMarker()
  55800. {
  55801. setInterceptsMouseClicks (false, false);
  55802. }
  55803. ~HueSelectorMarker()
  55804. {
  55805. }
  55806. void paint (Graphics& g)
  55807. {
  55808. Path p;
  55809. p.addTriangle (1.0f, 1.0f,
  55810. getWidth() * 0.3f, getHeight() * 0.5f,
  55811. 1.0f, getHeight() - 1.0f);
  55812. p.addTriangle (getWidth() - 1.0f, 1.0f,
  55813. getWidth() * 0.7f, getHeight() * 0.5f,
  55814. getWidth() - 1.0f, getHeight() - 1.0f);
  55815. g.setColour (Colours::white.withAlpha (0.75f));
  55816. g.fillPath (p);
  55817. g.setColour (Colours::black.withAlpha (0.75f));
  55818. g.strokePath (p, PathStrokeType (1.2f));
  55819. }
  55820. private:
  55821. HueSelectorMarker (const HueSelectorMarker&);
  55822. const HueSelectorMarker& operator= (const HueSelectorMarker&);
  55823. };
  55824. class HueSelectorComp : public Component
  55825. {
  55826. public:
  55827. HueSelectorComp (ColourSelector* owner_,
  55828. float& h_, float& s_, float& v_,
  55829. const int edgeSize)
  55830. : owner (owner_),
  55831. h (h_), s (s_), v (v_),
  55832. lastHue (0.0f),
  55833. edge (edgeSize)
  55834. {
  55835. addAndMakeVisible (marker = new HueSelectorMarker());
  55836. }
  55837. ~HueSelectorComp()
  55838. {
  55839. deleteAllChildren();
  55840. }
  55841. void paint (Graphics& g)
  55842. {
  55843. const float yScale = 1.0f / (getHeight() - edge * 2);
  55844. const Rectangle clip (g.getClipBounds());
  55845. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  55846. {
  55847. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  55848. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  55849. }
  55850. }
  55851. void resized()
  55852. {
  55853. marker->setBounds (0, roundFloatToInt ((getHeight() - edge * 2) * h),
  55854. getWidth(), edge * 2);
  55855. }
  55856. void mouseDown (const MouseEvent& e)
  55857. {
  55858. mouseDrag (e);
  55859. }
  55860. void mouseDrag (const MouseEvent& e)
  55861. {
  55862. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  55863. owner->setHue (hue);
  55864. }
  55865. void updateIfNeeded()
  55866. {
  55867. resized();
  55868. }
  55869. private:
  55870. ColourSelector* const owner;
  55871. float& h;
  55872. float& s;
  55873. float& v;
  55874. float lastHue;
  55875. HueSelectorMarker* marker;
  55876. const int edge;
  55877. HueSelectorComp (const HueSelectorComp&);
  55878. const HueSelectorComp& operator= (const HueSelectorComp&);
  55879. };
  55880. class SwatchComponent : public Component
  55881. {
  55882. public:
  55883. SwatchComponent (ColourSelector* owner_, int index_)
  55884. : owner (owner_),
  55885. index (index_)
  55886. {
  55887. }
  55888. ~SwatchComponent()
  55889. {
  55890. }
  55891. void paint (Graphics& g)
  55892. {
  55893. const Colour colour (owner->getSwatchColour (index));
  55894. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  55895. 6, 6,
  55896. Colour (0xffdddddd).overlaidWith (colour),
  55897. Colour (0xffffffff).overlaidWith (colour));
  55898. }
  55899. void mouseDown (const MouseEvent&)
  55900. {
  55901. PopupMenu m;
  55902. m.addItem (1, TRANS("Use this swatch as the current colour"));
  55903. m.addSeparator();
  55904. m.addItem (2, TRANS("Set this swatch to the current colour"));
  55905. const int r = m.showAt (this);
  55906. if (r == 1)
  55907. {
  55908. owner->setCurrentColour (owner->getSwatchColour (index));
  55909. }
  55910. else if (r == 2)
  55911. {
  55912. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  55913. {
  55914. owner->setSwatchColour (index, owner->getCurrentColour());
  55915. repaint();
  55916. }
  55917. }
  55918. }
  55919. private:
  55920. ColourSelector* const owner;
  55921. const int index;
  55922. SwatchComponent (const SwatchComponent&);
  55923. const SwatchComponent& operator= (const SwatchComponent&);
  55924. };
  55925. ColourSelector::ColourSelector (const int flags_,
  55926. const int edgeGap_,
  55927. const int gapAroundColourSpaceComponent)
  55928. : colour (Colours::white),
  55929. flags (flags_),
  55930. topSpace (0),
  55931. edgeGap (edgeGap_)
  55932. {
  55933. // not much point having a selector with no components in it!
  55934. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  55935. updateHSV();
  55936. if ((flags & showSliders) != 0)
  55937. {
  55938. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  55939. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  55940. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  55941. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  55942. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  55943. for (int i = 4; --i >= 0;)
  55944. sliders[i]->addListener (this);
  55945. }
  55946. else
  55947. {
  55948. zeromem (sliders, sizeof (sliders));
  55949. }
  55950. if ((flags & showColourspace) != 0)
  55951. {
  55952. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  55953. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  55954. }
  55955. else
  55956. {
  55957. colourSpace = 0;
  55958. hueSelector = 0;
  55959. }
  55960. update();
  55961. }
  55962. ColourSelector::~ColourSelector()
  55963. {
  55964. dispatchPendingMessages();
  55965. deleteAllChildren();
  55966. }
  55967. const Colour ColourSelector::getCurrentColour() const
  55968. {
  55969. return ((flags & showAlphaChannel) != 0) ? colour
  55970. : colour.withAlpha ((uint8) 0xff);
  55971. }
  55972. void ColourSelector::setCurrentColour (const Colour& c)
  55973. {
  55974. if (c != colour)
  55975. {
  55976. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  55977. updateHSV();
  55978. update();
  55979. }
  55980. }
  55981. void ColourSelector::setHue (float newH)
  55982. {
  55983. newH = jlimit (0.0f, 1.0f, newH);
  55984. if (h != newH)
  55985. {
  55986. h = newH;
  55987. colour = Colour (h, s, v, colour.getFloatAlpha());
  55988. update();
  55989. }
  55990. }
  55991. void ColourSelector::setSV (float newS, float newV)
  55992. {
  55993. newS = jlimit (0.0f, 1.0f, newS);
  55994. newV = jlimit (0.0f, 1.0f, newV);
  55995. if (s != newS || v != newV)
  55996. {
  55997. s = newS;
  55998. v = newV;
  55999. colour = Colour (h, s, v, colour.getFloatAlpha());
  56000. update();
  56001. }
  56002. }
  56003. void ColourSelector::updateHSV()
  56004. {
  56005. colour.getHSB (h, s, v);
  56006. }
  56007. void ColourSelector::update()
  56008. {
  56009. if (sliders[0] != 0)
  56010. {
  56011. sliders[0]->setValue ((int) colour.getRed());
  56012. sliders[1]->setValue ((int) colour.getGreen());
  56013. sliders[2]->setValue ((int) colour.getBlue());
  56014. sliders[3]->setValue ((int) colour.getAlpha());
  56015. }
  56016. if (colourSpace != 0)
  56017. {
  56018. ((ColourSpaceView*) colourSpace)->updateIfNeeded();
  56019. ((HueSelectorComp*) hueSelector)->updateIfNeeded();
  56020. }
  56021. if ((flags & showColourAtTop) != 0)
  56022. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  56023. sendChangeMessage (this);
  56024. }
  56025. void ColourSelector::paint (Graphics& g)
  56026. {
  56027. g.fillAll (findColour (backgroundColourId));
  56028. if ((flags & showColourAtTop) != 0)
  56029. {
  56030. const Colour colour (getCurrentColour());
  56031. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  56032. 10, 10,
  56033. Colour (0xffdddddd).overlaidWith (colour),
  56034. Colour (0xffffffff).overlaidWith (colour));
  56035. g.setColour (Colours::white.overlaidWith (colour).contrasting());
  56036. g.setFont (14.0f, true);
  56037. g.drawText (((flags & showAlphaChannel) != 0)
  56038. ? String::formatted (T("#%02X%02X%02X%02X"),
  56039. (int) colour.getAlpha(),
  56040. (int) colour.getRed(),
  56041. (int) colour.getGreen(),
  56042. (int) colour.getBlue())
  56043. : String::formatted (T("#%02X%02X%02X"),
  56044. (int) colour.getRed(),
  56045. (int) colour.getGreen(),
  56046. (int) colour.getBlue()),
  56047. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  56048. Justification::centred, false);
  56049. }
  56050. if ((flags & showSliders) != 0)
  56051. {
  56052. g.setColour (findColour (labelTextColourId));
  56053. g.setFont (11.0f);
  56054. for (int i = 4; --i >= 0;)
  56055. {
  56056. if (sliders[i]->isVisible())
  56057. g.drawText (sliders[i]->getName() + T(":"),
  56058. 0, sliders[i]->getY(),
  56059. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  56060. Justification::centredRight, false);
  56061. }
  56062. }
  56063. }
  56064. void ColourSelector::resized()
  56065. {
  56066. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  56067. const int numSwatches = getNumSwatches();
  56068. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  56069. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  56070. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  56071. int y = topSpace;
  56072. if ((flags & showColourspace) != 0)
  56073. {
  56074. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  56075. colourSpace->setBounds (edgeGap, y,
  56076. getWidth() - hueWidth - edgeGap - 4,
  56077. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  56078. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  56079. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  56080. colourSpace->getHeight());
  56081. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  56082. }
  56083. if ((flags & showSliders) != 0)
  56084. {
  56085. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  56086. for (int i = 0; i < numSliders; ++i)
  56087. {
  56088. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  56089. proportionOfWidth (0.72f), sliderHeight - 2);
  56090. y += sliderHeight;
  56091. }
  56092. }
  56093. if (numSwatches > 0)
  56094. {
  56095. const int startX = 8;
  56096. const int xGap = 4;
  56097. const int yGap = 4;
  56098. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  56099. y += edgeGap;
  56100. if (swatchComponents.size() != numSwatches)
  56101. {
  56102. int i;
  56103. for (i = swatchComponents.size(); --i >= 0;)
  56104. {
  56105. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  56106. delete sc;
  56107. }
  56108. for (i = 0; i < numSwatches; ++i)
  56109. {
  56110. SwatchComponent* const sc = new SwatchComponent (this, i);
  56111. swatchComponents.add (sc);
  56112. addAndMakeVisible (sc);
  56113. }
  56114. }
  56115. int x = startX;
  56116. for (int i = 0; i < swatchComponents.size(); ++i)
  56117. {
  56118. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  56119. sc->setBounds (x + xGap / 2,
  56120. y + yGap / 2,
  56121. swatchWidth - xGap,
  56122. swatchHeight - yGap);
  56123. if (((i + 1) % swatchesPerRow) == 0)
  56124. {
  56125. x = startX;
  56126. y += swatchHeight;
  56127. }
  56128. else
  56129. {
  56130. x += swatchWidth;
  56131. }
  56132. }
  56133. }
  56134. }
  56135. void ColourSelector::sliderValueChanged (Slider*)
  56136. {
  56137. if (sliders[0] != 0)
  56138. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  56139. (uint8) sliders[1]->getValue(),
  56140. (uint8) sliders[2]->getValue(),
  56141. (uint8) sliders[3]->getValue()));
  56142. }
  56143. int ColourSelector::getNumSwatches() const
  56144. {
  56145. return 0;
  56146. }
  56147. const Colour ColourSelector::getSwatchColour (const int) const
  56148. {
  56149. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  56150. return Colours::black;
  56151. }
  56152. void ColourSelector::setSwatchColour (const int, const Colour&) const
  56153. {
  56154. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  56155. }
  56156. END_JUCE_NAMESPACE
  56157. /********* End of inlined file: juce_ColourSelector.cpp *********/
  56158. /********* Start of inlined file: juce_DropShadower.cpp *********/
  56159. BEGIN_JUCE_NAMESPACE
  56160. class ShadowWindow : public Component
  56161. {
  56162. Component* owner;
  56163. Image** shadowImageSections;
  56164. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  56165. public:
  56166. ShadowWindow (Component* const owner_,
  56167. const int type_,
  56168. Image** const shadowImageSections_)
  56169. : owner (owner_),
  56170. shadowImageSections (shadowImageSections_),
  56171. type (type_)
  56172. {
  56173. setInterceptsMouseClicks (false, false);
  56174. if (owner_->isOnDesktop())
  56175. {
  56176. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  56177. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56178. | ComponentPeer::windowIsTemporary);
  56179. }
  56180. else if (owner_->getParentComponent() != 0)
  56181. {
  56182. owner_->getParentComponent()->addChildComponent (this);
  56183. }
  56184. }
  56185. ~ShadowWindow()
  56186. {
  56187. }
  56188. void paint (Graphics& g)
  56189. {
  56190. Image* const topLeft = shadowImageSections [type * 3];
  56191. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  56192. Image* const filler = shadowImageSections [type * 3 + 2];
  56193. ImageBrush fillBrush (filler, 0, 0, 1.0f);
  56194. g.setOpacity (1.0f);
  56195. if (type < 2)
  56196. {
  56197. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  56198. g.drawImage (topLeft,
  56199. 0, 0, topLeft->getWidth(), imH,
  56200. 0, 0, topLeft->getWidth(), imH);
  56201. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  56202. g.drawImage (bottomRight,
  56203. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  56204. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  56205. g.setBrush (&fillBrush);
  56206. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  56207. }
  56208. else
  56209. {
  56210. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  56211. g.drawImage (topLeft,
  56212. 0, 0, imW, topLeft->getHeight(),
  56213. 0, 0, imW, topLeft->getHeight());
  56214. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  56215. g.drawImage (bottomRight,
  56216. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  56217. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  56218. g.setBrush (&fillBrush);
  56219. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  56220. }
  56221. }
  56222. void resized()
  56223. {
  56224. repaint(); // (needed for correct repainting)
  56225. }
  56226. private:
  56227. ShadowWindow (const ShadowWindow&);
  56228. const ShadowWindow& operator= (const ShadowWindow&);
  56229. };
  56230. DropShadower::DropShadower (const float alpha_,
  56231. const int xOffset_,
  56232. const int yOffset_,
  56233. const float blurRadius_)
  56234. : owner (0),
  56235. numShadows (0),
  56236. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  56237. xOffset (xOffset_),
  56238. yOffset (yOffset_),
  56239. alpha (alpha_),
  56240. blurRadius (blurRadius_),
  56241. inDestructor (false),
  56242. reentrant (false)
  56243. {
  56244. }
  56245. DropShadower::~DropShadower()
  56246. {
  56247. if (owner != 0)
  56248. owner->removeComponentListener (this);
  56249. inDestructor = true;
  56250. deleteShadowWindows();
  56251. }
  56252. void DropShadower::deleteShadowWindows()
  56253. {
  56254. if (numShadows > 0)
  56255. {
  56256. int i;
  56257. for (i = numShadows; --i >= 0;)
  56258. delete shadowWindows[i];
  56259. for (i = 12; --i >= 0;)
  56260. delete shadowImageSections[i];
  56261. numShadows = 0;
  56262. }
  56263. }
  56264. void DropShadower::setOwner (Component* componentToFollow)
  56265. {
  56266. if (componentToFollow != owner)
  56267. {
  56268. if (owner != 0)
  56269. owner->removeComponentListener (this);
  56270. // (the component can't be null)
  56271. jassert (componentToFollow != 0);
  56272. owner = componentToFollow;
  56273. jassert (owner != 0);
  56274. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  56275. owner->addComponentListener (this);
  56276. updateShadows();
  56277. }
  56278. }
  56279. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  56280. {
  56281. updateShadows();
  56282. }
  56283. void DropShadower::componentBroughtToFront (Component&)
  56284. {
  56285. bringShadowWindowsToFront();
  56286. }
  56287. void DropShadower::componentChildrenChanged (Component&)
  56288. {
  56289. }
  56290. void DropShadower::componentParentHierarchyChanged (Component&)
  56291. {
  56292. deleteShadowWindows();
  56293. updateShadows();
  56294. }
  56295. void DropShadower::componentVisibilityChanged (Component&)
  56296. {
  56297. updateShadows();
  56298. }
  56299. void DropShadower::updateShadows()
  56300. {
  56301. if (reentrant || inDestructor || (owner == 0))
  56302. return;
  56303. reentrant = true;
  56304. ComponentPeer* const nw = owner->getPeer();
  56305. const bool isOwnerVisible = owner->isVisible()
  56306. && (nw == 0 || ! nw->isMinimised());
  56307. const bool createShadowWindows = numShadows == 0
  56308. && owner->getWidth() > 0
  56309. && owner->getHeight() > 0
  56310. && isOwnerVisible
  56311. && (Desktop::canUseSemiTransparentWindows()
  56312. || owner->getParentComponent() != 0);
  56313. if (createShadowWindows)
  56314. {
  56315. // keep a cached version of the image to save doing the gaussian too often
  56316. String imageId;
  56317. imageId << shadowEdge << T(',')
  56318. << xOffset << T(',')
  56319. << yOffset << T(',')
  56320. << alpha;
  56321. const int hash = imageId.hashCode();
  56322. Image* bigIm = ImageCache::getFromHashCode (hash);
  56323. if (bigIm == 0)
  56324. {
  56325. bigIm = new Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  56326. Graphics bigG (*bigIm);
  56327. bigG.setColour (Colours::black.withAlpha (alpha));
  56328. bigG.fillRect (shadowEdge + xOffset,
  56329. shadowEdge + yOffset,
  56330. bigIm->getWidth() - (shadowEdge * 2),
  56331. bigIm->getHeight() - (shadowEdge * 2));
  56332. ImageConvolutionKernel blurKernel (roundFloatToInt (blurRadius * 2.0f));
  56333. blurKernel.createGaussianBlur (blurRadius);
  56334. blurKernel.applyToImage (*bigIm, 0,
  56335. xOffset,
  56336. yOffset,
  56337. bigIm->getWidth(),
  56338. bigIm->getHeight());
  56339. ImageCache::addImageToCache (bigIm, hash);
  56340. }
  56341. const int iw = bigIm->getWidth();
  56342. const int ih = bigIm->getHeight();
  56343. const int shadowEdge2 = shadowEdge * 2;
  56344. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  56345. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  56346. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  56347. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  56348. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  56349. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  56350. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  56351. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  56352. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  56353. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  56354. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  56355. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  56356. ImageCache::release (bigIm);
  56357. for (int i = 0; i < 4; ++i)
  56358. {
  56359. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  56360. ++numShadows;
  56361. }
  56362. }
  56363. if (numShadows > 0)
  56364. {
  56365. for (int i = numShadows; --i >= 0;)
  56366. {
  56367. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  56368. shadowWindows[i]->setVisible (isOwnerVisible);
  56369. }
  56370. const int x = owner->getX();
  56371. const int y = owner->getY() - shadowEdge;
  56372. const int w = owner->getWidth();
  56373. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  56374. shadowWindows[0]->setBounds (x - shadowEdge,
  56375. y,
  56376. shadowEdge,
  56377. h);
  56378. shadowWindows[1]->setBounds (x + w,
  56379. y,
  56380. shadowEdge,
  56381. h);
  56382. shadowWindows[2]->setBounds (x,
  56383. y,
  56384. w,
  56385. shadowEdge);
  56386. shadowWindows[3]->setBounds (x,
  56387. owner->getBottom(),
  56388. w,
  56389. shadowEdge);
  56390. }
  56391. reentrant = false;
  56392. if (createShadowWindows)
  56393. bringShadowWindowsToFront();
  56394. }
  56395. void DropShadower::setShadowImage (Image* const src,
  56396. const int num,
  56397. const int w,
  56398. const int h,
  56399. const int sx,
  56400. const int sy) throw()
  56401. {
  56402. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  56403. Graphics g (*shadowImageSections[num]);
  56404. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  56405. }
  56406. void DropShadower::bringShadowWindowsToFront()
  56407. {
  56408. if (! (inDestructor || reentrant))
  56409. {
  56410. updateShadows();
  56411. reentrant = true;
  56412. for (int i = numShadows; --i >= 0;)
  56413. shadowWindows[i]->toBehind (owner);
  56414. reentrant = false;
  56415. }
  56416. }
  56417. END_JUCE_NAMESPACE
  56418. /********* End of inlined file: juce_DropShadower.cpp *********/
  56419. /********* Start of inlined file: juce_MagnifierComponent.cpp *********/
  56420. BEGIN_JUCE_NAMESPACE
  56421. class MagnifyingPeer : public ComponentPeer
  56422. {
  56423. public:
  56424. MagnifyingPeer (Component* const component_,
  56425. MagnifierComponent* const magnifierComp_)
  56426. : ComponentPeer (component_, 0),
  56427. magnifierComp (magnifierComp_)
  56428. {
  56429. }
  56430. ~MagnifyingPeer()
  56431. {
  56432. }
  56433. void* getNativeHandle() const { return 0; }
  56434. void setVisible (bool) {}
  56435. void setTitle (const String&) {}
  56436. void setPosition (int, int) {}
  56437. void setSize (int, int) {}
  56438. void setBounds (int, int, int, int, const bool) {}
  56439. void setMinimised (bool) {}
  56440. bool isMinimised() const { return false; }
  56441. void setFullScreen (bool) {}
  56442. bool isFullScreen() const { return false; }
  56443. const BorderSize getFrameSize() const { return BorderSize (0); }
  56444. bool setAlwaysOnTop (bool) { return true; }
  56445. void toFront (bool) {}
  56446. void toBehind (ComponentPeer*) {}
  56447. void setIcon (const Image&) {}
  56448. bool isFocused() const
  56449. {
  56450. return magnifierComp->hasKeyboardFocus (true);
  56451. }
  56452. void grabFocus()
  56453. {
  56454. ComponentPeer* peer = magnifierComp->getPeer();
  56455. if (peer != 0)
  56456. peer->grabFocus();
  56457. }
  56458. void textInputRequired (int x, int y)
  56459. {
  56460. ComponentPeer* peer = magnifierComp->getPeer();
  56461. if (peer != 0)
  56462. peer->textInputRequired (x, y);
  56463. }
  56464. void getBounds (int& x, int& y, int& w, int& h) const
  56465. {
  56466. x = magnifierComp->getScreenX();
  56467. y = magnifierComp->getScreenY();
  56468. w = component->getWidth();
  56469. h = component->getHeight();
  56470. }
  56471. int getScreenX() const { return magnifierComp->getScreenX(); }
  56472. int getScreenY() const { return magnifierComp->getScreenY(); }
  56473. void relativePositionToGlobal (int& x, int& y)
  56474. {
  56475. const double zoom = magnifierComp->getScaleFactor();
  56476. x = roundDoubleToInt (x * zoom);
  56477. y = roundDoubleToInt (y * zoom);
  56478. magnifierComp->relativePositionToGlobal (x, y);
  56479. }
  56480. void globalPositionToRelative (int& x, int& y)
  56481. {
  56482. magnifierComp->globalPositionToRelative (x, y);
  56483. const double zoom = magnifierComp->getScaleFactor();
  56484. x = roundDoubleToInt (x / zoom);
  56485. y = roundDoubleToInt (y / zoom);
  56486. }
  56487. bool contains (int x, int y, bool) const
  56488. {
  56489. return ((unsigned int) x) < (unsigned int) magnifierComp->getWidth()
  56490. && ((unsigned int) y) < (unsigned int) magnifierComp->getHeight();
  56491. }
  56492. void repaint (int x, int y, int w, int h)
  56493. {
  56494. const double zoom = magnifierComp->getScaleFactor();
  56495. magnifierComp->repaint ((int) (x * zoom),
  56496. (int) (y * zoom),
  56497. roundDoubleToInt (w * zoom) + 1,
  56498. roundDoubleToInt (h * zoom) + 1);
  56499. }
  56500. void performAnyPendingRepaintsNow()
  56501. {
  56502. }
  56503. juce_UseDebuggingNewOperator
  56504. private:
  56505. MagnifierComponent* const magnifierComp;
  56506. MagnifyingPeer (const MagnifyingPeer&);
  56507. const MagnifyingPeer& operator= (const MagnifyingPeer&);
  56508. };
  56509. class PeerHolderComp : public Component
  56510. {
  56511. public:
  56512. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  56513. : magnifierComp (magnifierComp_)
  56514. {
  56515. setVisible (true);
  56516. }
  56517. ~PeerHolderComp()
  56518. {
  56519. }
  56520. ComponentPeer* createNewPeer (int, void*)
  56521. {
  56522. return new MagnifyingPeer (this, magnifierComp);
  56523. }
  56524. void childBoundsChanged (Component* c)
  56525. {
  56526. if (c != 0)
  56527. {
  56528. setSize (c->getWidth(), c->getHeight());
  56529. magnifierComp->childBoundsChanged (this);
  56530. }
  56531. }
  56532. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  56533. {
  56534. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  56535. Component* const p = magnifierComp->getParentComponent();
  56536. if (p != 0)
  56537. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  56538. }
  56539. private:
  56540. MagnifierComponent* const magnifierComp;
  56541. PeerHolderComp (const PeerHolderComp&);
  56542. const PeerHolderComp& operator= (const PeerHolderComp&);
  56543. };
  56544. MagnifierComponent::MagnifierComponent (Component* const content_,
  56545. const bool deleteContentCompWhenNoLongerNeeded)
  56546. : content (content_),
  56547. scaleFactor (0.0),
  56548. peer (0),
  56549. deleteContent (deleteContentCompWhenNoLongerNeeded),
  56550. quality (Graphics::lowResamplingQuality)
  56551. {
  56552. holderComp = new PeerHolderComp (this);
  56553. setScaleFactor (1.0);
  56554. }
  56555. MagnifierComponent::~MagnifierComponent()
  56556. {
  56557. delete holderComp;
  56558. if (deleteContent)
  56559. delete content;
  56560. }
  56561. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  56562. {
  56563. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  56564. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  56565. if (scaleFactor != newScaleFactor)
  56566. {
  56567. scaleFactor = newScaleFactor;
  56568. if (scaleFactor == 1.0)
  56569. {
  56570. holderComp->removeFromDesktop();
  56571. peer = 0;
  56572. addChildComponent (content);
  56573. childBoundsChanged (content);
  56574. }
  56575. else
  56576. {
  56577. holderComp->addAndMakeVisible (content);
  56578. holderComp->childBoundsChanged (content);
  56579. childBoundsChanged (holderComp);
  56580. holderComp->addToDesktop (0);
  56581. peer = holderComp->getPeer();
  56582. }
  56583. repaint();
  56584. }
  56585. }
  56586. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  56587. {
  56588. quality = newQuality;
  56589. }
  56590. void MagnifierComponent::paint (Graphics& g)
  56591. {
  56592. const int w = holderComp->getWidth();
  56593. const int h = holderComp->getHeight();
  56594. if (w == 0 || h == 0)
  56595. return;
  56596. const Rectangle r (g.getClipBounds());
  56597. const int srcX = (int) (r.getX() / scaleFactor);
  56598. const int srcY = (int) (r.getY() / scaleFactor);
  56599. int srcW = roundDoubleToInt (r.getRight() / scaleFactor) - srcX;
  56600. int srcH = roundDoubleToInt (r.getBottom() / scaleFactor) - srcY;
  56601. if (scaleFactor >= 1.0)
  56602. {
  56603. ++srcW;
  56604. ++srcH;
  56605. }
  56606. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  56607. temp.clear (srcX, srcY, srcW, srcH);
  56608. Graphics g2 (temp);
  56609. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  56610. holderComp->paintEntireComponent (g2);
  56611. g.setImageResamplingQuality (quality);
  56612. g.drawImage (&temp,
  56613. 0, 0, (int) (w * scaleFactor), (int) (h * scaleFactor),
  56614. 0, 0, w, h,
  56615. false);
  56616. }
  56617. void MagnifierComponent::childBoundsChanged (Component* c)
  56618. {
  56619. if (c != 0)
  56620. setSize (roundDoubleToInt (c->getWidth() * scaleFactor),
  56621. roundDoubleToInt (c->getHeight() * scaleFactor));
  56622. }
  56623. void MagnifierComponent::mouseDown (const MouseEvent& e)
  56624. {
  56625. if (peer != 0)
  56626. peer->handleMouseDown (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56627. }
  56628. void MagnifierComponent::mouseUp (const MouseEvent& e)
  56629. {
  56630. if (peer != 0)
  56631. peer->handleMouseUp (e.mods.getRawFlags(), scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56632. }
  56633. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  56634. {
  56635. if (peer != 0)
  56636. peer->handleMouseDrag (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56637. }
  56638. void MagnifierComponent::mouseMove (const MouseEvent& e)
  56639. {
  56640. if (peer != 0)
  56641. peer->handleMouseMove (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56642. }
  56643. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  56644. {
  56645. if (peer != 0)
  56646. peer->handleMouseEnter (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56647. }
  56648. void MagnifierComponent::mouseExit (const MouseEvent& e)
  56649. {
  56650. if (peer != 0)
  56651. peer->handleMouseExit (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56652. }
  56653. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  56654. {
  56655. if (peer != 0)
  56656. peer->handleMouseWheel (roundFloatToInt (ix * 256.0f),
  56657. roundFloatToInt (iy * 256.0f),
  56658. e.eventTime.toMilliseconds());
  56659. else
  56660. Component::mouseWheelMove (e, ix, iy);
  56661. }
  56662. int MagnifierComponent::scaleInt (const int n) const throw()
  56663. {
  56664. return roundDoubleToInt (n / scaleFactor);
  56665. }
  56666. END_JUCE_NAMESPACE
  56667. /********* End of inlined file: juce_MagnifierComponent.cpp *********/
  56668. /********* Start of inlined file: juce_MidiKeyboardComponent.cpp *********/
  56669. BEGIN_JUCE_NAMESPACE
  56670. class MidiKeyboardUpDownButton : public Button
  56671. {
  56672. public:
  56673. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  56674. const int delta_)
  56675. : Button (String::empty),
  56676. owner (owner_),
  56677. delta (delta_)
  56678. {
  56679. setOpaque (true);
  56680. }
  56681. ~MidiKeyboardUpDownButton()
  56682. {
  56683. }
  56684. void clicked()
  56685. {
  56686. int note = owner->getLowestVisibleKey();
  56687. if (delta < 0)
  56688. note = (note - 1) / 12;
  56689. else
  56690. note = note / 12 + 1;
  56691. owner->setLowestVisibleKey (note * 12);
  56692. }
  56693. void paintButton (Graphics& g,
  56694. bool isMouseOverButton,
  56695. bool isButtonDown)
  56696. {
  56697. owner->drawUpDownButton (g, getWidth(), getHeight(),
  56698. isMouseOverButton, isButtonDown,
  56699. delta > 0);
  56700. }
  56701. private:
  56702. MidiKeyboardComponent* const owner;
  56703. const int delta;
  56704. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  56705. const MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  56706. };
  56707. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  56708. const Orientation orientation_)
  56709. : state (state_),
  56710. xOffset (0),
  56711. blackNoteLength (1),
  56712. keyWidth (16.0f),
  56713. orientation (orientation_),
  56714. midiChannel (1),
  56715. midiInChannelMask (0xffff),
  56716. velocity (1.0f),
  56717. noteUnderMouse (-1),
  56718. mouseDownNote (-1),
  56719. rangeStart (0),
  56720. rangeEnd (127),
  56721. firstKey (12 * 4),
  56722. canScroll (true),
  56723. mouseDragging (false),
  56724. keyPresses (4),
  56725. keyPressNotes (16),
  56726. keyMappingOctave (6),
  56727. octaveNumForMiddleC (3)
  56728. {
  56729. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  56730. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  56731. // initialise with a default set of querty key-mappings..
  56732. const char* const keymap = "awsedftgyhujkolp;";
  56733. for (int i = String (keymap).length(); --i >= 0;)
  56734. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  56735. setOpaque (true);
  56736. setWantsKeyboardFocus (true);
  56737. state.addListener (this);
  56738. }
  56739. MidiKeyboardComponent::~MidiKeyboardComponent()
  56740. {
  56741. state.removeListener (this);
  56742. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  56743. deleteAllChildren();
  56744. }
  56745. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  56746. {
  56747. keyWidth = widthInPixels;
  56748. resized();
  56749. }
  56750. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  56751. {
  56752. if (orientation != newOrientation)
  56753. {
  56754. orientation = newOrientation;
  56755. resized();
  56756. }
  56757. }
  56758. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  56759. const int highestNote)
  56760. {
  56761. jassert (lowestNote >= 0 && lowestNote <= 127);
  56762. jassert (highestNote >= 0 && highestNote <= 127);
  56763. jassert (lowestNote <= highestNote);
  56764. if (rangeStart != lowestNote || rangeEnd != highestNote)
  56765. {
  56766. rangeStart = jlimit (0, 127, lowestNote);
  56767. rangeEnd = jlimit (0, 127, highestNote);
  56768. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  56769. resized();
  56770. }
  56771. }
  56772. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  56773. {
  56774. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  56775. if (noteNumber != firstKey)
  56776. {
  56777. firstKey = noteNumber;
  56778. sendChangeMessage (this);
  56779. resized();
  56780. }
  56781. }
  56782. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  56783. {
  56784. if (canScroll != canScroll_)
  56785. {
  56786. canScroll = canScroll_;
  56787. resized();
  56788. }
  56789. }
  56790. void MidiKeyboardComponent::colourChanged()
  56791. {
  56792. repaint();
  56793. }
  56794. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  56795. {
  56796. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  56797. if (midiChannel != midiChannelNumber)
  56798. {
  56799. resetAnyKeysInUse();
  56800. midiChannel = jlimit (1, 16, midiChannelNumber);
  56801. }
  56802. }
  56803. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  56804. {
  56805. midiInChannelMask = midiChannelMask;
  56806. triggerAsyncUpdate();
  56807. }
  56808. void MidiKeyboardComponent::setVelocity (const float velocity_)
  56809. {
  56810. velocity = jlimit (0.0f, 1.0f, velocity_);
  56811. }
  56812. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth, int& x, int& w) const
  56813. {
  56814. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  56815. static const float blackNoteWidth = 0.7f;
  56816. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  56817. 1.0f, 2 - blackNoteWidth * 0.4f,
  56818. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  56819. 4.0f, 5 - blackNoteWidth * 0.5f,
  56820. 5.0f, 6 - blackNoteWidth * 0.3f,
  56821. 6.0f };
  56822. static const float widths[] = { 1.0f, blackNoteWidth,
  56823. 1.0f, blackNoteWidth,
  56824. 1.0f, 1.0f, blackNoteWidth,
  56825. 1.0f, blackNoteWidth,
  56826. 1.0f, blackNoteWidth,
  56827. 1.0f };
  56828. const int octave = midiNoteNumber / 12;
  56829. const int note = midiNoteNumber % 12;
  56830. x = roundFloatToInt (octave * 7.0f * keyWidth + notePos [note] * keyWidth);
  56831. w = roundFloatToInt (widths [note] * keyWidth);
  56832. }
  56833. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  56834. {
  56835. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  56836. int rx, rw;
  56837. getKeyPosition (rangeStart, keyWidth, rx, rw);
  56838. x -= xOffset + rx;
  56839. }
  56840. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  56841. {
  56842. int x, y;
  56843. getKeyPos (midiNoteNumber, x, y);
  56844. return x;
  56845. }
  56846. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  56847. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  56848. int MidiKeyboardComponent::xyToNote (int x, int y)
  56849. {
  56850. if (! reallyContains (x, y, false))
  56851. return -1;
  56852. if (orientation != horizontalKeyboard)
  56853. {
  56854. swapVariables (x, y);
  56855. if (orientation == verticalKeyboardFacingLeft)
  56856. y = getWidth() - y;
  56857. else
  56858. x = getHeight() - x;
  56859. }
  56860. return remappedXYToNote (x + xOffset, y);
  56861. }
  56862. int MidiKeyboardComponent::remappedXYToNote (int x, int y) const
  56863. {
  56864. if (y < blackNoteLength)
  56865. {
  56866. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  56867. {
  56868. for (int i = 0; i < 5; ++i)
  56869. {
  56870. const int note = octaveStart + blackNotes [i];
  56871. if (note >= rangeStart && note <= rangeEnd)
  56872. {
  56873. int kx, kw;
  56874. getKeyPos (note, kx, kw);
  56875. kx += xOffset;
  56876. if (x >= kx && x < kx + kw)
  56877. return note;
  56878. }
  56879. }
  56880. }
  56881. }
  56882. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  56883. {
  56884. for (int i = 0; i < 7; ++i)
  56885. {
  56886. const int note = octaveStart + whiteNotes [i];
  56887. if (note >= rangeStart && note <= rangeEnd)
  56888. {
  56889. int kx, kw;
  56890. getKeyPos (note, kx, kw);
  56891. kx += xOffset;
  56892. if (x >= kx && x < kx + kw)
  56893. return note;
  56894. }
  56895. }
  56896. }
  56897. return -1;
  56898. }
  56899. void MidiKeyboardComponent::repaintNote (const int noteNum)
  56900. {
  56901. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  56902. {
  56903. int x, w;
  56904. getKeyPos (noteNum, x, w);
  56905. if (orientation == horizontalKeyboard)
  56906. repaint (x, 0, w, getHeight());
  56907. else if (orientation == verticalKeyboardFacingLeft)
  56908. repaint (0, x, getWidth(), w);
  56909. else if (orientation == verticalKeyboardFacingRight)
  56910. repaint (0, getHeight() - x - w, getWidth(), w);
  56911. }
  56912. }
  56913. void MidiKeyboardComponent::paint (Graphics& g)
  56914. {
  56915. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  56916. const Colour lineColour (findColour (keySeparatorLineColourId));
  56917. const Colour textColour (findColour (textLabelColourId));
  56918. int x, w, octave;
  56919. for (octave = 0; octave < 128; octave += 12)
  56920. {
  56921. for (int white = 0; white < 7; ++white)
  56922. {
  56923. const int noteNum = octave + whiteNotes [white];
  56924. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  56925. {
  56926. getKeyPos (noteNum, x, w);
  56927. if (orientation == horizontalKeyboard)
  56928. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  56929. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  56930. noteUnderMouse == noteNum,
  56931. lineColour, textColour);
  56932. else if (orientation == verticalKeyboardFacingLeft)
  56933. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  56934. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  56935. noteUnderMouse == noteNum,
  56936. lineColour, textColour);
  56937. else if (orientation == verticalKeyboardFacingRight)
  56938. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  56939. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  56940. noteUnderMouse == noteNum,
  56941. lineColour, textColour);
  56942. }
  56943. }
  56944. }
  56945. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  56946. if (orientation == verticalKeyboardFacingLeft)
  56947. {
  56948. x1 = getWidth() - 1.0f;
  56949. x2 = getWidth() - 5.0f;
  56950. }
  56951. else if (orientation == verticalKeyboardFacingRight)
  56952. x2 = 5.0f;
  56953. else
  56954. y2 = 5.0f;
  56955. GradientBrush gb (Colours::black.withAlpha (0.3f), x1, y1,
  56956. Colours::transparentBlack, x2, y2, false);
  56957. g.setBrush (&gb);
  56958. getKeyPos (rangeEnd, x, w);
  56959. x += w;
  56960. if (orientation == verticalKeyboardFacingLeft)
  56961. g.fillRect (getWidth() - 5, 0, 5, x);
  56962. else if (orientation == verticalKeyboardFacingRight)
  56963. g.fillRect (0, 0, 5, x);
  56964. else
  56965. g.fillRect (0, 0, x, 5);
  56966. g.setColour (lineColour);
  56967. if (orientation == verticalKeyboardFacingLeft)
  56968. g.fillRect (0, 0, 1, x);
  56969. else if (orientation == verticalKeyboardFacingRight)
  56970. g.fillRect (getWidth() - 1, 0, 1, x);
  56971. else
  56972. g.fillRect (0, getHeight() - 1, x, 1);
  56973. const Colour blackNoteColour (findColour (blackNoteColourId));
  56974. for (octave = 0; octave < 128; octave += 12)
  56975. {
  56976. for (int black = 0; black < 5; ++black)
  56977. {
  56978. const int noteNum = octave + blackNotes [black];
  56979. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  56980. {
  56981. getKeyPos (noteNum, x, w);
  56982. if (orientation == horizontalKeyboard)
  56983. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  56984. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  56985. noteUnderMouse == noteNum,
  56986. blackNoteColour);
  56987. else if (orientation == verticalKeyboardFacingLeft)
  56988. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  56989. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  56990. noteUnderMouse == noteNum,
  56991. blackNoteColour);
  56992. else if (orientation == verticalKeyboardFacingRight)
  56993. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  56994. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  56995. noteUnderMouse == noteNum,
  56996. blackNoteColour);
  56997. }
  56998. }
  56999. }
  57000. }
  57001. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  57002. Graphics& g, int x, int y, int w, int h,
  57003. bool isDown, bool isOver,
  57004. const Colour& lineColour,
  57005. const Colour& textColour)
  57006. {
  57007. Colour c (Colours::transparentWhite);
  57008. if (isDown)
  57009. c = findColour (keyDownOverlayColourId);
  57010. if (isOver)
  57011. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  57012. g.setColour (c);
  57013. g.fillRect (x, y, w, h);
  57014. const String text (getWhiteNoteText (midiNoteNumber));
  57015. if (! text.isEmpty())
  57016. {
  57017. g.setColour (textColour);
  57018. Font f (jmin (12.0f, keyWidth * 0.9f));
  57019. f.setHorizontalScale (0.8f);
  57020. g.setFont (f);
  57021. Justification justification (Justification::centredBottom);
  57022. if (orientation == verticalKeyboardFacingLeft)
  57023. justification = Justification::centredLeft;
  57024. else if (orientation == verticalKeyboardFacingRight)
  57025. justification = Justification::centredRight;
  57026. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  57027. }
  57028. g.setColour (lineColour);
  57029. if (orientation == horizontalKeyboard)
  57030. g.fillRect (x, y, 1, h);
  57031. else if (orientation == verticalKeyboardFacingLeft)
  57032. g.fillRect (x, y, w, 1);
  57033. else if (orientation == verticalKeyboardFacingRight)
  57034. g.fillRect (x, y + h - 1, w, 1);
  57035. if (midiNoteNumber == rangeEnd)
  57036. {
  57037. if (orientation == horizontalKeyboard)
  57038. g.fillRect (x + w, y, 1, h);
  57039. else if (orientation == verticalKeyboardFacingLeft)
  57040. g.fillRect (x, y + h, w, 1);
  57041. else if (orientation == verticalKeyboardFacingRight)
  57042. g.fillRect (x, y - 1, w, 1);
  57043. }
  57044. }
  57045. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  57046. Graphics& g, int x, int y, int w, int h,
  57047. bool isDown, bool isOver,
  57048. const Colour& noteFillColour)
  57049. {
  57050. Colour c (noteFillColour);
  57051. if (isDown)
  57052. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  57053. if (isOver)
  57054. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  57055. g.setColour (c);
  57056. g.fillRect (x, y, w, h);
  57057. if (isDown)
  57058. {
  57059. g.setColour (noteFillColour);
  57060. g.drawRect (x, y, w, h);
  57061. }
  57062. else
  57063. {
  57064. const int xIndent = jmax (1, jmin (w, h) / 8);
  57065. g.setColour (c.brighter());
  57066. if (orientation == horizontalKeyboard)
  57067. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  57068. else if (orientation == verticalKeyboardFacingLeft)
  57069. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  57070. else if (orientation == verticalKeyboardFacingRight)
  57071. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  57072. }
  57073. }
  57074. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_) throw()
  57075. {
  57076. octaveNumForMiddleC = octaveNumForMiddleC_;
  57077. repaint();
  57078. }
  57079. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  57080. {
  57081. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  57082. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  57083. return String::empty;
  57084. }
  57085. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  57086. const bool isMouseOver,
  57087. const bool isButtonDown,
  57088. const bool movesOctavesUp)
  57089. {
  57090. g.fillAll (findColour (upDownButtonBackgroundColourId));
  57091. float angle;
  57092. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  57093. angle = movesOctavesUp ? 0.0f : 0.5f;
  57094. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  57095. angle = movesOctavesUp ? 0.25f : 0.75f;
  57096. else
  57097. angle = movesOctavesUp ? 0.75f : 0.25f;
  57098. Path path;
  57099. path.lineTo (0.0f, 1.0f);
  57100. path.lineTo (1.0f, 0.5f);
  57101. path.closeSubPath();
  57102. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  57103. g.setColour (findColour (upDownButtonArrowColourId)
  57104. .withAlpha (isButtonDown ? 1.0f : (isMouseOver ? 0.6f : 0.4f)));
  57105. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  57106. w - 2.0f,
  57107. h - 2.0f,
  57108. true));
  57109. }
  57110. void MidiKeyboardComponent::resized()
  57111. {
  57112. int w = getWidth();
  57113. int h = getHeight();
  57114. if (w > 0 && h > 0)
  57115. {
  57116. if (orientation != horizontalKeyboard)
  57117. swapVariables (w, h);
  57118. blackNoteLength = roundFloatToInt (h * 0.7f);
  57119. int kx2, kw2;
  57120. getKeyPos (rangeEnd, kx2, kw2);
  57121. kx2 += kw2;
  57122. if (firstKey != rangeStart)
  57123. {
  57124. int kx1, kw1;
  57125. getKeyPos (rangeStart, kx1, kw1);
  57126. if (kx2 - kx1 <= w)
  57127. {
  57128. firstKey = rangeStart;
  57129. sendChangeMessage (this);
  57130. repaint();
  57131. }
  57132. }
  57133. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  57134. scrollDown->setVisible (showScrollButtons);
  57135. scrollUp->setVisible (showScrollButtons);
  57136. xOffset = 0;
  57137. if (showScrollButtons)
  57138. {
  57139. const int scrollButtonW = jmin (12, w / 2);
  57140. if (orientation == horizontalKeyboard)
  57141. {
  57142. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  57143. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  57144. }
  57145. else if (orientation == verticalKeyboardFacingLeft)
  57146. {
  57147. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  57148. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  57149. }
  57150. else if (orientation == verticalKeyboardFacingRight)
  57151. {
  57152. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  57153. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  57154. }
  57155. int endOfLastKey, kw;
  57156. getKeyPos (rangeEnd, endOfLastKey, kw);
  57157. endOfLastKey += kw;
  57158. const int spaceAvailable = w - scrollButtonW * 2;
  57159. const int lastStartKey = remappedXYToNote (endOfLastKey - spaceAvailable, 0) + 1;
  57160. if (lastStartKey >= 0 && firstKey > lastStartKey)
  57161. {
  57162. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  57163. sendChangeMessage (this);
  57164. }
  57165. int newOffset = 0;
  57166. getKeyPos (firstKey, newOffset, kw);
  57167. xOffset = newOffset - scrollButtonW;
  57168. }
  57169. else
  57170. {
  57171. firstKey = rangeStart;
  57172. }
  57173. timerCallback();
  57174. repaint();
  57175. }
  57176. }
  57177. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  57178. {
  57179. triggerAsyncUpdate();
  57180. }
  57181. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  57182. {
  57183. triggerAsyncUpdate();
  57184. }
  57185. void MidiKeyboardComponent::handleAsyncUpdate()
  57186. {
  57187. for (int i = rangeStart; i <= rangeEnd; ++i)
  57188. {
  57189. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  57190. {
  57191. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  57192. repaintNote (i);
  57193. }
  57194. }
  57195. }
  57196. void MidiKeyboardComponent::resetAnyKeysInUse()
  57197. {
  57198. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  57199. {
  57200. state.allNotesOff (midiChannel);
  57201. keysPressed.clear();
  57202. mouseDownNote = -1;
  57203. }
  57204. }
  57205. void MidiKeyboardComponent::updateNoteUnderMouse (int x, int y)
  57206. {
  57207. const int newNote = (mouseDragging || isMouseOver())
  57208. ? xyToNote (x, y) : -1;
  57209. if (noteUnderMouse != newNote)
  57210. {
  57211. if (mouseDownNote >= 0)
  57212. {
  57213. state.noteOff (midiChannel, mouseDownNote);
  57214. mouseDownNote = -1;
  57215. }
  57216. if (mouseDragging && newNote >= 0)
  57217. {
  57218. state.noteOn (midiChannel, newNote, velocity);
  57219. mouseDownNote = newNote;
  57220. }
  57221. repaintNote (noteUnderMouse);
  57222. noteUnderMouse = newNote;
  57223. repaintNote (noteUnderMouse);
  57224. }
  57225. else if (mouseDownNote >= 0 && ! mouseDragging)
  57226. {
  57227. state.noteOff (midiChannel, mouseDownNote);
  57228. mouseDownNote = -1;
  57229. }
  57230. }
  57231. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  57232. {
  57233. updateNoteUnderMouse (e.x, e.y);
  57234. stopTimer();
  57235. }
  57236. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  57237. {
  57238. const int newNote = xyToNote (e.x, e.y);
  57239. if (newNote >= 0)
  57240. mouseDraggedToKey (newNote, e);
  57241. updateNoteUnderMouse (e.x, e.y);
  57242. }
  57243. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  57244. {
  57245. return true;
  57246. }
  57247. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  57248. {
  57249. }
  57250. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  57251. {
  57252. const int newNote = xyToNote (e.x, e.y);
  57253. mouseDragging = false;
  57254. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  57255. {
  57256. repaintNote (noteUnderMouse);
  57257. noteUnderMouse = -1;
  57258. mouseDragging = true;
  57259. updateNoteUnderMouse (e.x, e.y);
  57260. startTimer (500);
  57261. }
  57262. }
  57263. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  57264. {
  57265. mouseDragging = false;
  57266. updateNoteUnderMouse (e.x, e.y);
  57267. stopTimer();
  57268. }
  57269. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  57270. {
  57271. updateNoteUnderMouse (e.x, e.y);
  57272. }
  57273. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  57274. {
  57275. updateNoteUnderMouse (e.x, e.y);
  57276. }
  57277. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  57278. {
  57279. setLowestVisibleKey (getLowestVisibleKey() + roundFloatToInt ((ix != 0 ? ix : iy) * 5.0f));
  57280. }
  57281. void MidiKeyboardComponent::timerCallback()
  57282. {
  57283. int mx, my;
  57284. getMouseXYRelative (mx, my);
  57285. updateNoteUnderMouse (mx, my);
  57286. }
  57287. void MidiKeyboardComponent::clearKeyMappings()
  57288. {
  57289. resetAnyKeysInUse();
  57290. keyPressNotes.clear();
  57291. keyPresses.clear();
  57292. }
  57293. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  57294. const int midiNoteOffsetFromC)
  57295. {
  57296. removeKeyPressForNote (midiNoteOffsetFromC);
  57297. keyPressNotes.add (midiNoteOffsetFromC);
  57298. keyPresses.add (key);
  57299. }
  57300. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  57301. {
  57302. for (int i = keyPressNotes.size(); --i >= 0;)
  57303. {
  57304. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  57305. {
  57306. keyPressNotes.remove (i);
  57307. keyPresses.remove (i);
  57308. }
  57309. }
  57310. }
  57311. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  57312. {
  57313. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  57314. keyMappingOctave = newOctaveNumber;
  57315. }
  57316. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  57317. {
  57318. bool keyPressUsed = false;
  57319. for (int i = keyPresses.size(); --i >= 0;)
  57320. {
  57321. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  57322. if (keyPresses.getReference(i).isCurrentlyDown())
  57323. {
  57324. if (! keysPressed [note])
  57325. {
  57326. keysPressed.setBit (note);
  57327. state.noteOn (midiChannel, note, velocity);
  57328. keyPressUsed = true;
  57329. }
  57330. }
  57331. else
  57332. {
  57333. if (keysPressed [note])
  57334. {
  57335. keysPressed.clearBit (note);
  57336. state.noteOff (midiChannel, note);
  57337. keyPressUsed = true;
  57338. }
  57339. }
  57340. }
  57341. return keyPressUsed;
  57342. }
  57343. void MidiKeyboardComponent::focusLost (FocusChangeType)
  57344. {
  57345. resetAnyKeysInUse();
  57346. }
  57347. END_JUCE_NAMESPACE
  57348. /********* End of inlined file: juce_MidiKeyboardComponent.cpp *********/
  57349. /********* Start of inlined file: juce_OpenGLComponent.cpp *********/
  57350. #if JUCE_OPENGL
  57351. BEGIN_JUCE_NAMESPACE
  57352. extern void juce_glViewport (const int w, const int h);
  57353. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  57354. const int alphaBits_,
  57355. const int depthBufferBits_,
  57356. const int stencilBufferBits_) throw()
  57357. : redBits (bitsPerRGBComponent),
  57358. greenBits (bitsPerRGBComponent),
  57359. blueBits (bitsPerRGBComponent),
  57360. alphaBits (alphaBits_),
  57361. depthBufferBits (depthBufferBits_),
  57362. stencilBufferBits (stencilBufferBits_),
  57363. accumulationBufferRedBits (0),
  57364. accumulationBufferGreenBits (0),
  57365. accumulationBufferBlueBits (0),
  57366. accumulationBufferAlphaBits (0),
  57367. fullSceneAntiAliasingNumSamples (0)
  57368. {
  57369. }
  57370. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const throw()
  57371. {
  57372. return memcmp (this, &other, sizeof (other)) == 0;
  57373. }
  57374. static VoidArray knownContexts;
  57375. OpenGLContext::OpenGLContext() throw()
  57376. {
  57377. knownContexts.add (this);
  57378. }
  57379. OpenGLContext::~OpenGLContext()
  57380. {
  57381. knownContexts.removeValue (this);
  57382. }
  57383. OpenGLContext* OpenGLContext::getCurrentContext()
  57384. {
  57385. for (int i = knownContexts.size(); --i >= 0;)
  57386. {
  57387. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  57388. if (oglc->isActive())
  57389. return oglc;
  57390. }
  57391. return 0;
  57392. }
  57393. class OpenGLComponentWatcher : public ComponentMovementWatcher
  57394. {
  57395. public:
  57396. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  57397. : ComponentMovementWatcher (owner_),
  57398. owner (owner_),
  57399. wasShowing (false)
  57400. {
  57401. }
  57402. ~OpenGLComponentWatcher() {}
  57403. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  57404. {
  57405. owner->updateContextPosition();
  57406. }
  57407. void componentPeerChanged()
  57408. {
  57409. const ScopedLock sl (owner->getContextLock());
  57410. owner->deleteContext();
  57411. }
  57412. void componentVisibilityChanged (Component&)
  57413. {
  57414. const bool isShowingNow = owner->isShowing();
  57415. if (wasShowing != isShowingNow)
  57416. {
  57417. wasShowing = isShowingNow;
  57418. owner->updateContextPosition();
  57419. }
  57420. }
  57421. juce_UseDebuggingNewOperator
  57422. private:
  57423. OpenGLComponent* const owner;
  57424. bool wasShowing;
  57425. };
  57426. OpenGLComponent::OpenGLComponent()
  57427. : context (0),
  57428. contextToShareListsWith (0),
  57429. needToUpdateViewport (true)
  57430. {
  57431. setOpaque (true);
  57432. componentWatcher = new OpenGLComponentWatcher (this);
  57433. }
  57434. OpenGLComponent::~OpenGLComponent()
  57435. {
  57436. deleteContext();
  57437. delete componentWatcher;
  57438. }
  57439. void OpenGLComponent::deleteContext()
  57440. {
  57441. const ScopedLock sl (contextLock);
  57442. deleteAndZero (context);
  57443. }
  57444. void OpenGLComponent::updateContextPosition()
  57445. {
  57446. needToUpdateViewport = true;
  57447. if (getWidth() > 0 && getHeight() > 0)
  57448. {
  57449. Component* const topComp = getTopLevelComponent();
  57450. if (topComp->getPeer() != 0)
  57451. {
  57452. const ScopedLock sl (contextLock);
  57453. if (context != 0)
  57454. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  57455. getScreenY() - topComp->getScreenY(),
  57456. getWidth(),
  57457. getHeight(),
  57458. topComp->getHeight());
  57459. }
  57460. }
  57461. }
  57462. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  57463. {
  57464. OpenGLPixelFormat pf;
  57465. const ScopedLock sl (contextLock);
  57466. if (context != 0)
  57467. pf = context->getPixelFormat();
  57468. return pf;
  57469. }
  57470. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  57471. {
  57472. if (! (preferredPixelFormat == formatToUse))
  57473. {
  57474. const ScopedLock sl (contextLock);
  57475. deleteContext();
  57476. preferredPixelFormat = formatToUse;
  57477. }
  57478. }
  57479. void OpenGLComponent::shareWith (OpenGLContext* context)
  57480. {
  57481. if (contextToShareListsWith != context)
  57482. {
  57483. const ScopedLock sl (contextLock);
  57484. deleteContext();
  57485. contextToShareListsWith = context;
  57486. }
  57487. }
  57488. bool OpenGLComponent::makeCurrentContextActive()
  57489. {
  57490. if (context == 0)
  57491. {
  57492. const ScopedLock sl (contextLock);
  57493. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  57494. {
  57495. context = OpenGLContext::createContextForWindow (this,
  57496. preferredPixelFormat,
  57497. contextToShareListsWith);
  57498. if (context != 0)
  57499. {
  57500. updateContextPosition();
  57501. if (context->makeActive())
  57502. newOpenGLContextCreated();
  57503. }
  57504. }
  57505. }
  57506. return context != 0 && context->makeActive();
  57507. }
  57508. void OpenGLComponent::makeCurrentContextInactive()
  57509. {
  57510. if (context != 0)
  57511. context->makeInactive();
  57512. }
  57513. bool OpenGLComponent::isActiveContext() const throw()
  57514. {
  57515. return context != 0 && context->isActive();
  57516. }
  57517. void OpenGLComponent::swapBuffers()
  57518. {
  57519. if (context != 0)
  57520. context->swapBuffers();
  57521. }
  57522. void OpenGLComponent::paint (Graphics&)
  57523. {
  57524. if (renderAndSwapBuffers())
  57525. {
  57526. ComponentPeer* const peer = getPeer();
  57527. if (peer != 0)
  57528. {
  57529. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  57530. getScreenY() - peer->getScreenY(),
  57531. getWidth(), getHeight());
  57532. }
  57533. }
  57534. }
  57535. bool OpenGLComponent::renderAndSwapBuffers()
  57536. {
  57537. const ScopedLock sl (contextLock);
  57538. if (! makeCurrentContextActive())
  57539. return false;
  57540. if (needToUpdateViewport)
  57541. {
  57542. needToUpdateViewport = false;
  57543. juce_glViewport (getWidth(), getHeight());
  57544. }
  57545. renderOpenGL();
  57546. swapBuffers();
  57547. return true;
  57548. }
  57549. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  57550. {
  57551. Component::internalRepaint (x, y, w, h);
  57552. if (context != 0)
  57553. context->repaint();
  57554. }
  57555. END_JUCE_NAMESPACE
  57556. #endif
  57557. /********* End of inlined file: juce_OpenGLComponent.cpp *********/
  57558. /********* Start of inlined file: juce_PreferencesPanel.cpp *********/
  57559. BEGIN_JUCE_NAMESPACE
  57560. PreferencesPanel::PreferencesPanel()
  57561. : currentPage (0),
  57562. buttonSize (70)
  57563. {
  57564. }
  57565. PreferencesPanel::~PreferencesPanel()
  57566. {
  57567. deleteAllChildren();
  57568. }
  57569. void PreferencesPanel::addSettingsPage (const String& title,
  57570. const Drawable* icon,
  57571. const Drawable* overIcon,
  57572. const Drawable* downIcon)
  57573. {
  57574. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  57575. button->setImages (icon, overIcon, downIcon);
  57576. button->setRadioGroupId (1);
  57577. button->addButtonListener (this);
  57578. button->setClickingTogglesState (true);
  57579. button->setWantsKeyboardFocus (false);
  57580. addAndMakeVisible (button);
  57581. resized();
  57582. if (currentPage == 0)
  57583. setCurrentPage (title);
  57584. }
  57585. void PreferencesPanel::addSettingsPage (const String& title,
  57586. const char* imageData,
  57587. const int imageDataSize)
  57588. {
  57589. DrawableImage icon, iconOver, iconDown;
  57590. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57591. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57592. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  57593. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57594. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  57595. addSettingsPage (title, &icon, &iconOver, &iconDown);
  57596. }
  57597. class PrefsDialogWindow : public DialogWindow
  57598. {
  57599. public:
  57600. PrefsDialogWindow (const String& dialogtitle,
  57601. const Colour& backgroundColour)
  57602. : DialogWindow (dialogtitle, backgroundColour, true)
  57603. {
  57604. }
  57605. ~PrefsDialogWindow()
  57606. {
  57607. }
  57608. void closeButtonPressed()
  57609. {
  57610. exitModalState (0);
  57611. }
  57612. private:
  57613. PrefsDialogWindow (const PrefsDialogWindow&);
  57614. const PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  57615. };
  57616. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  57617. int dialogWidth,
  57618. int dialogHeight,
  57619. const Colour& backgroundColour)
  57620. {
  57621. setSize (dialogWidth, dialogHeight);
  57622. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  57623. dw.setContentComponent (this, true, true);
  57624. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  57625. dw.runModalLoop();
  57626. dw.setContentComponent (0, false, false);
  57627. }
  57628. void PreferencesPanel::resized()
  57629. {
  57630. int x = 0;
  57631. for (int i = 0; i < getNumChildComponents(); ++i)
  57632. {
  57633. Component* c = getChildComponent (i);
  57634. if (dynamic_cast <DrawableButton*> (c) == 0)
  57635. {
  57636. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  57637. }
  57638. else
  57639. {
  57640. c->setBounds (x, 0, buttonSize, buttonSize);
  57641. x += buttonSize;
  57642. }
  57643. }
  57644. }
  57645. void PreferencesPanel::paint (Graphics& g)
  57646. {
  57647. g.setColour (Colours::grey);
  57648. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  57649. }
  57650. void PreferencesPanel::setCurrentPage (const String& pageName)
  57651. {
  57652. if (currentPageName != pageName)
  57653. {
  57654. currentPageName = pageName;
  57655. deleteAndZero (currentPage);
  57656. currentPage = createComponentForPage (pageName);
  57657. if (currentPage != 0)
  57658. {
  57659. addAndMakeVisible (currentPage);
  57660. currentPage->toBack();
  57661. resized();
  57662. }
  57663. for (int i = 0; i < getNumChildComponents(); ++i)
  57664. {
  57665. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  57666. if (db != 0 && db->getName() == pageName)
  57667. {
  57668. db->setToggleState (true, false);
  57669. break;
  57670. }
  57671. }
  57672. }
  57673. }
  57674. void PreferencesPanel::buttonClicked (Button*)
  57675. {
  57676. for (int i = 0; i < getNumChildComponents(); ++i)
  57677. {
  57678. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  57679. if (db != 0 && db->getToggleState())
  57680. {
  57681. setCurrentPage (db->getName());
  57682. break;
  57683. }
  57684. }
  57685. }
  57686. END_JUCE_NAMESPACE
  57687. /********* End of inlined file: juce_PreferencesPanel.cpp *********/
  57688. /********* Start of inlined file: juce_SystemTrayIconComponent.cpp *********/
  57689. #if JUCE_WIN32 || JUCE_LINUX
  57690. BEGIN_JUCE_NAMESPACE
  57691. SystemTrayIconComponent::SystemTrayIconComponent()
  57692. {
  57693. addToDesktop (0);
  57694. }
  57695. SystemTrayIconComponent::~SystemTrayIconComponent()
  57696. {
  57697. }
  57698. END_JUCE_NAMESPACE
  57699. #endif
  57700. /********* End of inlined file: juce_SystemTrayIconComponent.cpp *********/
  57701. /********* Start of inlined file: juce_AlertWindow.cpp *********/
  57702. BEGIN_JUCE_NAMESPACE
  57703. static const int titleH = 24;
  57704. static const int iconWidth = 80;
  57705. class AlertWindowTextEditor : public TextEditor
  57706. {
  57707. public:
  57708. #if JUCE_LINUX
  57709. #define PASSWORD_CHAR 0x2022
  57710. #else
  57711. #define PASSWORD_CHAR 0x25cf
  57712. #endif
  57713. AlertWindowTextEditor (const String& name,
  57714. const bool isPasswordBox)
  57715. : TextEditor (name,
  57716. isPasswordBox ? (const tchar) PASSWORD_CHAR
  57717. : (const tchar) 0)
  57718. {
  57719. setSelectAllWhenFocused (true);
  57720. }
  57721. ~AlertWindowTextEditor()
  57722. {
  57723. }
  57724. void returnPressed()
  57725. {
  57726. // pass these up the component hierarchy to be trigger the buttons
  57727. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, T('\n')));
  57728. }
  57729. void escapePressed()
  57730. {
  57731. // pass these up the component hierarchy to be trigger the buttons
  57732. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  57733. }
  57734. private:
  57735. AlertWindowTextEditor (const AlertWindowTextEditor&);
  57736. const AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  57737. };
  57738. AlertWindow::AlertWindow (const String& title,
  57739. const String& message,
  57740. AlertIconType iconType,
  57741. Component* associatedComponent_)
  57742. : TopLevelWindow (title, true),
  57743. alertIconType (iconType),
  57744. associatedComponent (associatedComponent_)
  57745. {
  57746. if (message.isEmpty())
  57747. text = T(" "); // to force an update if the message is empty
  57748. setMessage (message);
  57749. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  57750. {
  57751. Component* const c = Desktop::getInstance().getComponent (i);
  57752. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  57753. {
  57754. setAlwaysOnTop (true);
  57755. break;
  57756. }
  57757. }
  57758. if (JUCEApplication::getInstance() == 0)
  57759. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  57760. lookAndFeelChanged();
  57761. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  57762. }
  57763. AlertWindow::~AlertWindow()
  57764. {
  57765. for (int i = customComps.size(); --i >= 0;)
  57766. removeChildComponent ((Component*) customComps[i]);
  57767. deleteAllChildren();
  57768. }
  57769. void AlertWindow::userTriedToCloseWindow()
  57770. {
  57771. exitModalState (0);
  57772. }
  57773. void AlertWindow::setMessage (const String& message)
  57774. {
  57775. const String newMessage (message.substring (0, 2048));
  57776. if (text != newMessage)
  57777. {
  57778. text = newMessage;
  57779. font.setHeight (15.0f);
  57780. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  57781. textLayout.setText (getName() + T("\n\n"), titleFont);
  57782. textLayout.appendText (text, font);
  57783. updateLayout (true);
  57784. repaint();
  57785. }
  57786. }
  57787. void AlertWindow::buttonClicked (Button* button)
  57788. {
  57789. for (int i = 0; i < buttons.size(); i++)
  57790. {
  57791. TextButton* const c = (TextButton*) buttons[i];
  57792. if (button->getName() == c->getName())
  57793. {
  57794. if (c->getParentComponent() != 0)
  57795. c->getParentComponent()->exitModalState (c->getCommandID());
  57796. break;
  57797. }
  57798. }
  57799. }
  57800. void AlertWindow::addButton (const String& name,
  57801. const int returnValue,
  57802. const KeyPress& shortcutKey1,
  57803. const KeyPress& shortcutKey2)
  57804. {
  57805. TextButton* const b = new TextButton (name, String::empty);
  57806. b->setWantsKeyboardFocus (true);
  57807. b->setMouseClickGrabsKeyboardFocus (false);
  57808. b->setCommandToTrigger (0, returnValue, false);
  57809. b->addShortcut (shortcutKey1);
  57810. b->addShortcut (shortcutKey2);
  57811. b->addButtonListener (this);
  57812. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  57813. addAndMakeVisible (b, 0);
  57814. buttons.add (b);
  57815. updateLayout (false);
  57816. }
  57817. int AlertWindow::getNumButtons() const
  57818. {
  57819. return buttons.size();
  57820. }
  57821. void AlertWindow::addTextEditor (const String& name,
  57822. const String& initialContents,
  57823. const String& onScreenLabel,
  57824. const bool isPasswordBox)
  57825. {
  57826. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  57827. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  57828. tc->setFont (font);
  57829. tc->setText (initialContents);
  57830. tc->setCaretPosition (initialContents.length());
  57831. addAndMakeVisible (tc);
  57832. textBoxes.add (tc);
  57833. allComps.add (tc);
  57834. textboxNames.add (onScreenLabel);
  57835. updateLayout (false);
  57836. }
  57837. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  57838. {
  57839. for (int i = textBoxes.size(); --i >= 0;)
  57840. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  57841. return ((TextEditor*)textBoxes[i])->getText();
  57842. return String::empty;
  57843. }
  57844. void AlertWindow::addComboBox (const String& name,
  57845. const StringArray& items,
  57846. const String& onScreenLabel)
  57847. {
  57848. ComboBox* const cb = new ComboBox (name);
  57849. for (int i = 0; i < items.size(); ++i)
  57850. cb->addItem (items[i], i + 1);
  57851. addAndMakeVisible (cb);
  57852. cb->setSelectedItemIndex (0);
  57853. comboBoxes.add (cb);
  57854. allComps.add (cb);
  57855. comboBoxNames.add (onScreenLabel);
  57856. updateLayout (false);
  57857. }
  57858. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  57859. {
  57860. for (int i = comboBoxes.size(); --i >= 0;)
  57861. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  57862. return (ComboBox*) comboBoxes[i];
  57863. return 0;
  57864. }
  57865. class AlertTextComp : public TextEditor
  57866. {
  57867. AlertTextComp (const AlertTextComp&);
  57868. const AlertTextComp& operator= (const AlertTextComp&);
  57869. int bestWidth;
  57870. public:
  57871. AlertTextComp (const String& message,
  57872. const Font& font)
  57873. {
  57874. setReadOnly (true);
  57875. setMultiLine (true, true);
  57876. setCaretVisible (false);
  57877. setScrollbarsShown (true);
  57878. lookAndFeelChanged();
  57879. setWantsKeyboardFocus (false);
  57880. setFont (font);
  57881. setText (message, false);
  57882. bestWidth = 2 * (int) sqrt (font.getHeight() * font.getStringWidth (message));
  57883. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  57884. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  57885. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  57886. }
  57887. ~AlertTextComp()
  57888. {
  57889. }
  57890. int getPreferredWidth() const throw() { return bestWidth; }
  57891. void updateLayout (const int width)
  57892. {
  57893. TextLayout text;
  57894. text.appendText (getText(), getFont());
  57895. text.layout (width - 8, Justification::topLeft, true);
  57896. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  57897. }
  57898. };
  57899. void AlertWindow::addTextBlock (const String& text)
  57900. {
  57901. AlertTextComp* const c = new AlertTextComp (text, font);
  57902. textBlocks.add (c);
  57903. allComps.add (c);
  57904. addAndMakeVisible (c);
  57905. updateLayout (false);
  57906. }
  57907. void AlertWindow::addProgressBarComponent (double& progressValue)
  57908. {
  57909. ProgressBar* const pb = new ProgressBar (progressValue);
  57910. progressBars.add (pb);
  57911. allComps.add (pb);
  57912. addAndMakeVisible (pb);
  57913. updateLayout (false);
  57914. }
  57915. void AlertWindow::addCustomComponent (Component* const component)
  57916. {
  57917. customComps.add (component);
  57918. allComps.add (component);
  57919. addAndMakeVisible (component);
  57920. updateLayout (false);
  57921. }
  57922. int AlertWindow::getNumCustomComponents() const
  57923. {
  57924. return customComps.size();
  57925. }
  57926. Component* AlertWindow::getCustomComponent (const int index) const
  57927. {
  57928. return (Component*) customComps [index];
  57929. }
  57930. Component* AlertWindow::removeCustomComponent (const int index)
  57931. {
  57932. Component* const c = getCustomComponent (index);
  57933. if (c != 0)
  57934. {
  57935. customComps.removeValue (c);
  57936. allComps.removeValue (c);
  57937. removeChildComponent (c);
  57938. updateLayout (false);
  57939. }
  57940. return c;
  57941. }
  57942. void AlertWindow::paint (Graphics& g)
  57943. {
  57944. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  57945. g.setColour (findColour (textColourId));
  57946. g.setFont (getLookAndFeel().getAlertWindowFont());
  57947. int i;
  57948. for (i = textBoxes.size(); --i >= 0;)
  57949. {
  57950. if (textboxNames[i].isNotEmpty())
  57951. {
  57952. const TextEditor* const te = (TextEditor*) textBoxes[i];
  57953. g.drawFittedText (textboxNames[i],
  57954. te->getX(), te->getY() - 14,
  57955. te->getWidth(), 14,
  57956. Justification::centredLeft, 1);
  57957. }
  57958. }
  57959. for (i = comboBoxNames.size(); --i >= 0;)
  57960. {
  57961. if (comboBoxNames[i].isNotEmpty())
  57962. {
  57963. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  57964. g.drawFittedText (comboBoxNames[i],
  57965. cb->getX(), cb->getY() - 14,
  57966. cb->getWidth(), 14,
  57967. Justification::centredLeft, 1);
  57968. }
  57969. }
  57970. }
  57971. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  57972. {
  57973. const int wid = jmax (font.getStringWidth (text),
  57974. font.getStringWidth (getName()));
  57975. const int sw = (int) sqrt (font.getHeight() * wid);
  57976. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  57977. const int edgeGap = 10;
  57978. int iconSpace;
  57979. if (alertIconType == NoIcon)
  57980. {
  57981. textLayout.layout (w, Justification::horizontallyCentred, true);
  57982. iconSpace = 0;
  57983. }
  57984. else
  57985. {
  57986. textLayout.layout (w, Justification::left, true);
  57987. iconSpace = iconWidth;
  57988. }
  57989. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  57990. w = jmin (w, (int) (getParentWidth() * 0.7f));
  57991. const int textLayoutH = textLayout.getHeight();
  57992. const int textBottom = 16 + titleH + textLayoutH;
  57993. int h = textBottom;
  57994. int buttonW = 40;
  57995. int i;
  57996. for (i = 0; i < buttons.size(); ++i)
  57997. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  57998. w = jmax (buttonW, w);
  57999. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  58000. if (buttons.size() > 0)
  58001. h += 20 + ((TextButton*) buttons[0])->getHeight();
  58002. for (i = customComps.size(); --i >= 0;)
  58003. {
  58004. w = jmax (w, ((Component*) customComps[i])->getWidth() + 40);
  58005. h += 10 + ((Component*) customComps[i])->getHeight();
  58006. }
  58007. for (i = textBlocks.size(); --i >= 0;)
  58008. {
  58009. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  58010. w = jmax (w, ac->getPreferredWidth());
  58011. }
  58012. w = jmin (w, (int) (getParentWidth() * 0.7f));
  58013. for (i = textBlocks.size(); --i >= 0;)
  58014. {
  58015. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  58016. ac->updateLayout ((int) (w * 0.8f));
  58017. h += ac->getHeight() + 10;
  58018. }
  58019. h = jmin (getParentHeight() - 50, h);
  58020. if (onlyIncreaseSize)
  58021. {
  58022. w = jmax (w, getWidth());
  58023. h = jmax (h, getHeight());
  58024. }
  58025. if (! isVisible())
  58026. {
  58027. centreAroundComponent (associatedComponent, w, h);
  58028. }
  58029. else
  58030. {
  58031. const int cx = getX() + getWidth() / 2;
  58032. const int cy = getY() + getHeight() / 2;
  58033. setBounds (cx - w / 2,
  58034. cy - h / 2,
  58035. w, h);
  58036. }
  58037. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  58038. const int spacer = 16;
  58039. int totalWidth = -spacer;
  58040. for (i = buttons.size(); --i >= 0;)
  58041. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  58042. int x = (w - totalWidth) / 2;
  58043. int y = (int) (getHeight() * 0.95f);
  58044. for (i = 0; i < buttons.size(); ++i)
  58045. {
  58046. TextButton* const c = (TextButton*) buttons[i];
  58047. int ny = proportionOfHeight (0.95f) - c->getHeight();
  58048. c->setTopLeftPosition (x, ny);
  58049. if (ny < y)
  58050. y = ny;
  58051. x += c->getWidth() + spacer;
  58052. c->toFront (false);
  58053. }
  58054. y = textBottom;
  58055. for (i = 0; i < allComps.size(); ++i)
  58056. {
  58057. Component* const c = (Component*) allComps[i];
  58058. const int h = 22;
  58059. const int comboIndex = comboBoxes.indexOf (c);
  58060. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  58061. y += 18;
  58062. const int tbIndex = textBoxes.indexOf (c);
  58063. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  58064. y += 18;
  58065. if (customComps.contains (c) || textBlocks.contains (c))
  58066. {
  58067. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  58068. y += c->getHeight() + 10;
  58069. }
  58070. else
  58071. {
  58072. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  58073. y += h + 10;
  58074. }
  58075. }
  58076. setWantsKeyboardFocus (getNumChildComponents() == 0);
  58077. }
  58078. bool AlertWindow::containsAnyExtraComponents() const
  58079. {
  58080. return textBoxes.size()
  58081. + comboBoxes.size()
  58082. + progressBars.size()
  58083. + customComps.size() > 0;
  58084. }
  58085. void AlertWindow::mouseDown (const MouseEvent&)
  58086. {
  58087. dragger.startDraggingComponent (this, &constrainer);
  58088. }
  58089. void AlertWindow::mouseDrag (const MouseEvent& e)
  58090. {
  58091. dragger.dragComponent (this, e);
  58092. }
  58093. bool AlertWindow::keyPressed (const KeyPress& key)
  58094. {
  58095. for (int i = buttons.size(); --i >= 0;)
  58096. {
  58097. TextButton* const b = (TextButton*) buttons[i];
  58098. if (b->isRegisteredForShortcut (key))
  58099. {
  58100. b->triggerClick();
  58101. return true;
  58102. }
  58103. }
  58104. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  58105. {
  58106. exitModalState (0);
  58107. return true;
  58108. }
  58109. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  58110. {
  58111. ((TextButton*) buttons.getFirst())->triggerClick();
  58112. return true;
  58113. }
  58114. return false;
  58115. }
  58116. void AlertWindow::lookAndFeelChanged()
  58117. {
  58118. const int flags = getLookAndFeel().getAlertBoxWindowFlags();
  58119. setUsingNativeTitleBar ((flags & ComponentPeer::windowHasTitleBar) != 0);
  58120. setDropShadowEnabled (isOpaque() && (flags & ComponentPeer::windowHasDropShadow) != 0);
  58121. }
  58122. int AlertWindow::getDesktopWindowStyleFlags() const
  58123. {
  58124. return getLookAndFeel().getAlertBoxWindowFlags();
  58125. }
  58126. struct AlertWindowInfo
  58127. {
  58128. String title, message, button1, button2, button3;
  58129. AlertWindow::AlertIconType iconType;
  58130. int numButtons;
  58131. Component* associatedComponent;
  58132. int run() const
  58133. {
  58134. return (int) (pointer_sized_int)
  58135. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  58136. }
  58137. private:
  58138. int show() const
  58139. {
  58140. jassert (associatedComponent == 0 || associatedComponent->isValidComponent()); // has your comp been deleted?
  58141. LookAndFeel& lf = associatedComponent->isValidComponent() ? associatedComponent->getLookAndFeel()
  58142. : LookAndFeel::getDefaultLookAndFeel();
  58143. Component* const alertBox = lf.createAlertWindow (title, message, button1, button2, button3,
  58144. iconType, numButtons, associatedComponent);
  58145. jassert (alertBox != 0); // you have to return one of these!
  58146. const int result = alertBox->runModalLoop();
  58147. delete alertBox;
  58148. return result;
  58149. }
  58150. static void* showCallback (void* userData)
  58151. {
  58152. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  58153. }
  58154. };
  58155. void AlertWindow::showMessageBox (AlertIconType iconType,
  58156. const String& title,
  58157. const String& message,
  58158. const String& buttonText,
  58159. Component* associatedComponent)
  58160. {
  58161. AlertWindowInfo info;
  58162. info.title = title;
  58163. info.message = message;
  58164. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  58165. info.iconType = iconType;
  58166. info.numButtons = 1;
  58167. info.associatedComponent = associatedComponent;
  58168. info.run();
  58169. }
  58170. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  58171. const String& title,
  58172. const String& message,
  58173. const String& button1Text,
  58174. const String& button2Text,
  58175. Component* associatedComponent)
  58176. {
  58177. AlertWindowInfo info;
  58178. info.title = title;
  58179. info.message = message;
  58180. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  58181. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  58182. info.iconType = iconType;
  58183. info.numButtons = 2;
  58184. info.associatedComponent = associatedComponent;
  58185. return info.run() != 0;
  58186. }
  58187. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  58188. const String& title,
  58189. const String& message,
  58190. const String& button1Text,
  58191. const String& button2Text,
  58192. const String& button3Text,
  58193. Component* associatedComponent)
  58194. {
  58195. AlertWindowInfo info;
  58196. info.title = title;
  58197. info.message = message;
  58198. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  58199. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  58200. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  58201. info.iconType = iconType;
  58202. info.numButtons = 3;
  58203. info.associatedComponent = associatedComponent;
  58204. return info.run();
  58205. }
  58206. END_JUCE_NAMESPACE
  58207. /********* End of inlined file: juce_AlertWindow.cpp *********/
  58208. /********* Start of inlined file: juce_ComponentPeer.cpp *********/
  58209. BEGIN_JUCE_NAMESPACE
  58210. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  58211. // these are over in juce_component.cpp
  58212. extern int64 juce_recentMouseDownTimes[4];
  58213. extern int juce_recentMouseDownX [4];
  58214. extern int juce_recentMouseDownY [4];
  58215. extern Component* juce_recentMouseDownComponent [4];
  58216. extern int juce_LastMousePosX;
  58217. extern int juce_LastMousePosY;
  58218. extern int juce_MouseClickCounter;
  58219. extern bool juce_MouseHasMovedSignificantlySincePressed;
  58220. static const int fakeMouseMoveMessage = 0x7fff00ff;
  58221. static VoidArray heavyweightPeers (4);
  58222. ComponentPeer::ComponentPeer (Component* const component_,
  58223. const int styleFlags_) throw()
  58224. : component (component_),
  58225. styleFlags (styleFlags_),
  58226. lastPaintTime (0),
  58227. constrainer (0),
  58228. lastFocusedComponent (0),
  58229. dragAndDropTargetComponent (0),
  58230. lastDragAndDropCompUnderMouse (0),
  58231. fakeMouseMessageSent (false),
  58232. isWindowMinimised (false)
  58233. {
  58234. heavyweightPeers.add (this);
  58235. }
  58236. ComponentPeer::~ComponentPeer()
  58237. {
  58238. heavyweightPeers.removeValue (this);
  58239. delete dragAndDropTargetComponent;
  58240. Desktop::getInstance().triggerFocusCallback();
  58241. }
  58242. int ComponentPeer::getNumPeers() throw()
  58243. {
  58244. return heavyweightPeers.size();
  58245. }
  58246. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  58247. {
  58248. return (ComponentPeer*) heavyweightPeers [index];
  58249. }
  58250. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  58251. {
  58252. for (int i = heavyweightPeers.size(); --i >= 0;)
  58253. {
  58254. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  58255. if (peer->getComponent() == component)
  58256. return peer;
  58257. }
  58258. return 0;
  58259. }
  58260. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  58261. {
  58262. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  58263. }
  58264. void ComponentPeer::updateCurrentModifiers() throw()
  58265. {
  58266. ModifierKeys::updateCurrentModifiers();
  58267. }
  58268. void ComponentPeer::handleMouseEnter (int x, int y, const int64 time)
  58269. {
  58270. jassert (component->isValidComponent());
  58271. updateCurrentModifiers();
  58272. Component* c = component->getComponentAt (x, y);
  58273. const ComponentDeletionWatcher deletionChecker (component);
  58274. if (c != Component::componentUnderMouse && Component::componentUnderMouse != 0)
  58275. {
  58276. jassert (Component::componentUnderMouse->isValidComponent());
  58277. const int oldX = x;
  58278. const int oldY = y;
  58279. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58280. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58281. Component::componentUnderMouse = 0;
  58282. if (deletionChecker.hasBeenDeleted())
  58283. return;
  58284. c = component->getComponentAt (oldX, oldY);
  58285. }
  58286. Component::componentUnderMouse = c;
  58287. if (Component::componentUnderMouse != 0)
  58288. {
  58289. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58290. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  58291. }
  58292. }
  58293. void ComponentPeer::handleMouseMove (int x, int y, const int64 time)
  58294. {
  58295. jassert (component->isValidComponent());
  58296. updateCurrentModifiers();
  58297. fakeMouseMessageSent = false;
  58298. const ComponentDeletionWatcher deletionChecker (component);
  58299. Component* c = component->getComponentAt (x, y);
  58300. if (c != Component::componentUnderMouse)
  58301. {
  58302. const int oldX = x;
  58303. const int oldY = y;
  58304. if (Component::componentUnderMouse != 0)
  58305. {
  58306. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58307. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58308. x = oldX;
  58309. y = oldY;
  58310. Component::componentUnderMouse = 0;
  58311. if (deletionChecker.hasBeenDeleted())
  58312. return; // if this window has just been deleted..
  58313. c = component->getComponentAt (x, y);
  58314. }
  58315. Component::componentUnderMouse = c;
  58316. if (c != 0)
  58317. {
  58318. component->relativePositionToOtherComponent (c, x, y);
  58319. c->internalMouseEnter (x, y, time);
  58320. x = oldX;
  58321. y = oldY;
  58322. if (deletionChecker.hasBeenDeleted())
  58323. return; // if this window has just been deleted..
  58324. }
  58325. }
  58326. if (Component::componentUnderMouse != 0)
  58327. {
  58328. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58329. Component::componentUnderMouse->internalMouseMove (x, y, time);
  58330. }
  58331. }
  58332. void ComponentPeer::handleMouseDown (int x, int y, const int64 time)
  58333. {
  58334. ++juce_MouseClickCounter;
  58335. updateCurrentModifiers();
  58336. int numMouseButtonsDown = 0;
  58337. if (ModifierKeys::getCurrentModifiers().isLeftButtonDown())
  58338. ++numMouseButtonsDown;
  58339. if (ModifierKeys::getCurrentModifiers().isRightButtonDown())
  58340. ++numMouseButtonsDown;
  58341. if (ModifierKeys::getCurrentModifiers().isMiddleButtonDown())
  58342. ++numMouseButtonsDown;
  58343. if (numMouseButtonsDown == 1)
  58344. {
  58345. Component::componentUnderMouse = component->getComponentAt (x, y);
  58346. if (Component::componentUnderMouse != 0)
  58347. {
  58348. // can't set these in the mouseDownInt() method, because it's re-entrant, so do it here..
  58349. for (int i = numElementsInArray (juce_recentMouseDownTimes); --i > 0;)
  58350. {
  58351. juce_recentMouseDownTimes [i] = juce_recentMouseDownTimes [i - 1];
  58352. juce_recentMouseDownX [i] = juce_recentMouseDownX [i - 1];
  58353. juce_recentMouseDownY [i] = juce_recentMouseDownY [i - 1];
  58354. juce_recentMouseDownComponent [i] = juce_recentMouseDownComponent [i - 1];
  58355. }
  58356. juce_recentMouseDownTimes[0] = time;
  58357. juce_recentMouseDownX[0] = x;
  58358. juce_recentMouseDownY[0] = y;
  58359. juce_recentMouseDownComponent[0] = Component::componentUnderMouse;
  58360. relativePositionToGlobal (juce_recentMouseDownX[0], juce_recentMouseDownY[0]);
  58361. juce_MouseHasMovedSignificantlySincePressed = false;
  58362. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58363. Component::componentUnderMouse->internalMouseDown (x, y);
  58364. }
  58365. }
  58366. }
  58367. void ComponentPeer::handleMouseDrag (int x, int y, const int64 time)
  58368. {
  58369. updateCurrentModifiers();
  58370. if (Component::componentUnderMouse != 0)
  58371. {
  58372. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58373. Component::componentUnderMouse->internalMouseDrag (x, y, time);
  58374. }
  58375. }
  58376. void ComponentPeer::handleMouseUp (const int oldModifiers, int x, int y, const int64 time)
  58377. {
  58378. updateCurrentModifiers();
  58379. int numMouseButtonsDown = 0;
  58380. if ((oldModifiers & ModifierKeys::leftButtonModifier) != 0)
  58381. ++numMouseButtonsDown;
  58382. if ((oldModifiers & ModifierKeys::rightButtonModifier) != 0)
  58383. ++numMouseButtonsDown;
  58384. if ((oldModifiers & ModifierKeys::middleButtonModifier) != 0)
  58385. ++numMouseButtonsDown;
  58386. if (numMouseButtonsDown == 1)
  58387. {
  58388. const ComponentDeletionWatcher deletionChecker (component);
  58389. Component* c = component->getComponentAt (x, y);
  58390. if (c != Component::componentUnderMouse)
  58391. {
  58392. const int oldX = x;
  58393. const int oldY = y;
  58394. if (Component::componentUnderMouse != 0)
  58395. {
  58396. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58397. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  58398. x = oldX;
  58399. y = oldY;
  58400. if (Component::componentUnderMouse != 0)
  58401. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58402. if (deletionChecker.hasBeenDeleted())
  58403. return;
  58404. c = component->getComponentAt (oldX, oldY);
  58405. }
  58406. Component::componentUnderMouse = c;
  58407. if (Component::componentUnderMouse != 0)
  58408. {
  58409. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58410. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  58411. }
  58412. }
  58413. else
  58414. {
  58415. if (Component::componentUnderMouse != 0)
  58416. {
  58417. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58418. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  58419. }
  58420. }
  58421. }
  58422. }
  58423. void ComponentPeer::handleMouseExit (int x, int y, const int64 time)
  58424. {
  58425. jassert (component->isValidComponent());
  58426. updateCurrentModifiers();
  58427. if (Component::componentUnderMouse != 0)
  58428. {
  58429. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58430. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58431. Component::componentUnderMouse = 0;
  58432. }
  58433. }
  58434. void ComponentPeer::handleMouseWheel (const int amountX, const int amountY, const int64 time)
  58435. {
  58436. updateCurrentModifiers();
  58437. if (Component::componentUnderMouse != 0)
  58438. Component::componentUnderMouse->internalMouseWheel (amountX, amountY, time);
  58439. }
  58440. void ComponentPeer::sendFakeMouseMove() throw()
  58441. {
  58442. if ((! fakeMouseMessageSent)
  58443. && component->flags.hasHeavyweightPeerFlag
  58444. && ! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  58445. {
  58446. if (! isMinimised())
  58447. {
  58448. int realX, realY, realW, realH;
  58449. getBounds (realX, realY, realW, realH);
  58450. component->bounds_.setBounds (realX, realY, realW, realH);
  58451. }
  58452. int x, y;
  58453. component->getMouseXYRelative (x, y);
  58454. if (((unsigned int) x) < (unsigned int) component->getWidth()
  58455. && ((unsigned int) y) < (unsigned int) component->getHeight()
  58456. && contains (x, y, false))
  58457. {
  58458. postMessage (new Message (fakeMouseMoveMessage, x, y, 0));
  58459. }
  58460. fakeMouseMessageSent = true;
  58461. }
  58462. }
  58463. void ComponentPeer::handleMessage (const Message& message)
  58464. {
  58465. if (message.intParameter1 == fakeMouseMoveMessage)
  58466. {
  58467. if (! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  58468. handleMouseMove (message.intParameter2,
  58469. message.intParameter3,
  58470. Time::currentTimeMillis());
  58471. }
  58472. }
  58473. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  58474. {
  58475. Graphics g (&contextToPaintTo);
  58476. #if JUCE_ENABLE_REPAINT_DEBUGGING
  58477. g.saveState();
  58478. #endif
  58479. JUCE_TRY
  58480. {
  58481. component->paintEntireComponent (g);
  58482. }
  58483. JUCE_CATCH_EXCEPTION
  58484. #if JUCE_ENABLE_REPAINT_DEBUGGING
  58485. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  58486. // clearly when things are being repainted.
  58487. {
  58488. g.restoreState();
  58489. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  58490. (uint8) Random::getSystemRandom().nextInt (255),
  58491. (uint8) Random::getSystemRandom().nextInt (255),
  58492. (uint8) 0x50));
  58493. }
  58494. #endif
  58495. }
  58496. bool ComponentPeer::handleKeyPress (const int keyCode,
  58497. const juce_wchar textCharacter)
  58498. {
  58499. updateCurrentModifiers();
  58500. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  58501. ? Component::currentlyFocusedComponent
  58502. : component;
  58503. if (target->isCurrentlyBlockedByAnotherModalComponent())
  58504. {
  58505. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  58506. if (currentModalComp != 0)
  58507. target = currentModalComp;
  58508. }
  58509. const KeyPress keyInfo (keyCode,
  58510. ModifierKeys::getCurrentModifiers().getRawFlags()
  58511. & ModifierKeys::allKeyboardModifiers,
  58512. textCharacter);
  58513. bool keyWasUsed = false;
  58514. while (target != 0)
  58515. {
  58516. const ComponentDeletionWatcher deletionChecker (target);
  58517. if (target->keyListeners_ != 0)
  58518. {
  58519. for (int i = target->keyListeners_->size(); --i >= 0;)
  58520. {
  58521. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  58522. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58523. return keyWasUsed;
  58524. i = jmin (i, target->keyListeners_->size());
  58525. }
  58526. }
  58527. keyWasUsed = target->keyPressed (keyInfo);
  58528. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58529. break;
  58530. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  58531. {
  58532. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  58533. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  58534. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  58535. break;
  58536. }
  58537. target = target->parentComponent_;
  58538. }
  58539. return keyWasUsed;
  58540. }
  58541. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  58542. {
  58543. updateCurrentModifiers();
  58544. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  58545. ? Component::currentlyFocusedComponent
  58546. : component;
  58547. if (target->isCurrentlyBlockedByAnotherModalComponent())
  58548. {
  58549. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  58550. if (currentModalComp != 0)
  58551. target = currentModalComp;
  58552. }
  58553. bool keyWasUsed = false;
  58554. while (target != 0)
  58555. {
  58556. const ComponentDeletionWatcher deletionChecker (target);
  58557. keyWasUsed = target->keyStateChanged (isKeyDown);
  58558. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58559. break;
  58560. if (target->keyListeners_ != 0)
  58561. {
  58562. for (int i = target->keyListeners_->size(); --i >= 0;)
  58563. {
  58564. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (isKeyDown, target);
  58565. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58566. return keyWasUsed;
  58567. i = jmin (i, target->keyListeners_->size());
  58568. }
  58569. }
  58570. target = target->parentComponent_;
  58571. }
  58572. return keyWasUsed;
  58573. }
  58574. void ComponentPeer::handleModifierKeysChange()
  58575. {
  58576. updateCurrentModifiers();
  58577. Component* target = Component::getComponentUnderMouse();
  58578. if (target == 0)
  58579. target = Component::getCurrentlyFocusedComponent();
  58580. if (target == 0)
  58581. target = component;
  58582. if (target->isValidComponent())
  58583. target->internalModifierKeysChanged();
  58584. }
  58585. void ComponentPeer::handleBroughtToFront()
  58586. {
  58587. updateCurrentModifiers();
  58588. if (component != 0)
  58589. component->internalBroughtToFront();
  58590. }
  58591. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  58592. {
  58593. constrainer = newConstrainer;
  58594. }
  58595. void ComponentPeer::handleMovedOrResized()
  58596. {
  58597. jassert (component->isValidComponent());
  58598. updateCurrentModifiers();
  58599. const bool nowMinimised = isMinimised();
  58600. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  58601. {
  58602. const ComponentDeletionWatcher deletionChecker (component);
  58603. int realX, realY, realW, realH;
  58604. getBounds (realX, realY, realW, realH);
  58605. const bool wasMoved = (component->getX() != realX || component->getY() != realY);
  58606. const bool wasResized = (component->getWidth() != realW || component->getHeight() != realH);
  58607. if (wasMoved || wasResized)
  58608. {
  58609. component->bounds_.setBounds (realX, realY, realW, realH);
  58610. if (wasResized)
  58611. component->repaint();
  58612. component->sendMovedResizedMessages (wasMoved, wasResized);
  58613. if (deletionChecker.hasBeenDeleted())
  58614. return;
  58615. }
  58616. }
  58617. if (isWindowMinimised != nowMinimised)
  58618. {
  58619. isWindowMinimised = nowMinimised;
  58620. component->minimisationStateChanged (nowMinimised);
  58621. component->sendVisibilityChangeMessage();
  58622. }
  58623. if (! isFullScreen())
  58624. lastNonFullscreenBounds = component->getBounds();
  58625. }
  58626. void ComponentPeer::handleFocusGain()
  58627. {
  58628. updateCurrentModifiers();
  58629. if (component->isParentOf (lastFocusedComponent))
  58630. {
  58631. Component::currentlyFocusedComponent = lastFocusedComponent;
  58632. Desktop::getInstance().triggerFocusCallback();
  58633. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  58634. }
  58635. else
  58636. {
  58637. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  58638. component->grabKeyboardFocus();
  58639. else
  58640. Component::bringModalComponentToFront();
  58641. }
  58642. }
  58643. void ComponentPeer::handleFocusLoss()
  58644. {
  58645. updateCurrentModifiers();
  58646. if (component->hasKeyboardFocus (true))
  58647. {
  58648. lastFocusedComponent = Component::currentlyFocusedComponent;
  58649. if (lastFocusedComponent != 0)
  58650. {
  58651. Component::currentlyFocusedComponent = 0;
  58652. Desktop::getInstance().triggerFocusCallback();
  58653. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  58654. }
  58655. }
  58656. }
  58657. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  58658. {
  58659. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  58660. ? lastFocusedComponent
  58661. : component;
  58662. }
  58663. void ComponentPeer::handleScreenSizeChange()
  58664. {
  58665. updateCurrentModifiers();
  58666. component->parentSizeChanged();
  58667. handleMovedOrResized();
  58668. }
  58669. void ComponentPeer::setNonFullScreenBounds (const Rectangle& newBounds) throw()
  58670. {
  58671. lastNonFullscreenBounds = newBounds;
  58672. }
  58673. const Rectangle& ComponentPeer::getNonFullScreenBounds() const throw()
  58674. {
  58675. return lastNonFullscreenBounds;
  58676. }
  58677. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  58678. const StringArray& files,
  58679. FileDragAndDropTarget* const lastOne)
  58680. {
  58681. while (c != 0)
  58682. {
  58683. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  58684. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  58685. return t;
  58686. c = c->getParentComponent();
  58687. }
  58688. return 0;
  58689. }
  58690. void ComponentPeer::handleFileDragMove (const StringArray& files, int x, int y)
  58691. {
  58692. updateCurrentModifiers();
  58693. FileDragAndDropTarget* lastTarget = 0;
  58694. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  58695. lastTarget = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  58696. FileDragAndDropTarget* newTarget = 0;
  58697. Component* const compUnderMouse = component->getComponentAt (x, y);
  58698. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  58699. {
  58700. lastDragAndDropCompUnderMouse = compUnderMouse;
  58701. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  58702. if (newTarget != lastTarget)
  58703. {
  58704. if (lastTarget != 0)
  58705. lastTarget->fileDragExit (files);
  58706. deleteAndZero (dragAndDropTargetComponent);
  58707. if (newTarget != 0)
  58708. {
  58709. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  58710. int mx = x, my = y;
  58711. component->relativePositionToOtherComponent (targetComp, mx, my);
  58712. dragAndDropTargetComponent = new ComponentDeletionWatcher (dynamic_cast <Component*> (newTarget));
  58713. newTarget->fileDragEnter (files, mx, my);
  58714. }
  58715. }
  58716. }
  58717. else
  58718. {
  58719. newTarget = lastTarget;
  58720. }
  58721. if (newTarget != 0)
  58722. {
  58723. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  58724. component->relativePositionToOtherComponent (targetComp, x, y);
  58725. newTarget->fileDragMove (files, x, y);
  58726. }
  58727. }
  58728. void ComponentPeer::handleFileDragExit (const StringArray& files)
  58729. {
  58730. handleFileDragMove (files, -1, -1);
  58731. jassert (dragAndDropTargetComponent == 0);
  58732. lastDragAndDropCompUnderMouse = 0;
  58733. }
  58734. void ComponentPeer::handleFileDragDrop (const StringArray& files, int x, int y)
  58735. {
  58736. handleFileDragMove (files, x, y);
  58737. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  58738. {
  58739. FileDragAndDropTarget* const target = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  58740. deleteAndZero (dragAndDropTargetComponent);
  58741. lastDragAndDropCompUnderMouse = 0;
  58742. if (target != 0)
  58743. {
  58744. Component* const targetComp = dynamic_cast <Component*> (target);
  58745. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  58746. {
  58747. targetComp->internalModalInputAttempt();
  58748. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  58749. return;
  58750. }
  58751. component->relativePositionToOtherComponent (targetComp, x, y);
  58752. target->filesDropped (files, x, y);
  58753. }
  58754. }
  58755. }
  58756. void ComponentPeer::handleUserClosingWindow()
  58757. {
  58758. updateCurrentModifiers();
  58759. component->userTriedToCloseWindow();
  58760. }
  58761. void ComponentPeer::bringModalComponentToFront()
  58762. {
  58763. Component::bringModalComponentToFront();
  58764. }
  58765. void ComponentPeer::clearMaskedRegion() throw()
  58766. {
  58767. maskedRegion.clear();
  58768. }
  58769. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h) throw()
  58770. {
  58771. maskedRegion.add (x, y, w, h);
  58772. }
  58773. END_JUCE_NAMESPACE
  58774. /********* End of inlined file: juce_ComponentPeer.cpp *********/
  58775. /********* Start of inlined file: juce_DialogWindow.cpp *********/
  58776. BEGIN_JUCE_NAMESPACE
  58777. DialogWindow::DialogWindow (const String& name,
  58778. const Colour& backgroundColour_,
  58779. const bool escapeKeyTriggersCloseButton_,
  58780. const bool addToDesktop_)
  58781. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  58782. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  58783. {
  58784. }
  58785. DialogWindow::~DialogWindow()
  58786. {
  58787. }
  58788. void DialogWindow::resized()
  58789. {
  58790. DocumentWindow::resized();
  58791. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  58792. if (escapeKeyTriggersCloseButton
  58793. && getCloseButton() != 0
  58794. && ! getCloseButton()->isRegisteredForShortcut (esc))
  58795. {
  58796. getCloseButton()->addShortcut (esc);
  58797. }
  58798. }
  58799. class TempDialogWindow : public DialogWindow
  58800. {
  58801. public:
  58802. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  58803. : DialogWindow (title, colour, escapeCloses, true)
  58804. {
  58805. }
  58806. ~TempDialogWindow()
  58807. {
  58808. }
  58809. void closeButtonPressed()
  58810. {
  58811. setVisible (false);
  58812. }
  58813. private:
  58814. TempDialogWindow (const TempDialogWindow&);
  58815. const TempDialogWindow& operator= (const TempDialogWindow&);
  58816. };
  58817. int DialogWindow::showModalDialog (const String& dialogTitle,
  58818. Component* contentComponent,
  58819. Component* componentToCentreAround,
  58820. const Colour& colour,
  58821. const bool escapeKeyTriggersCloseButton,
  58822. const bool shouldBeResizable,
  58823. const bool useBottomRightCornerResizer)
  58824. {
  58825. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  58826. dw.setContentComponent (contentComponent, true, true);
  58827. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  58828. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  58829. const int result = dw.runModalLoop();
  58830. dw.setContentComponent (0, false);
  58831. return result;
  58832. }
  58833. END_JUCE_NAMESPACE
  58834. /********* End of inlined file: juce_DialogWindow.cpp *********/
  58835. /********* Start of inlined file: juce_DocumentWindow.cpp *********/
  58836. BEGIN_JUCE_NAMESPACE
  58837. DocumentWindow::DocumentWindow (const String& title,
  58838. const Colour& backgroundColour,
  58839. const int requiredButtons_,
  58840. const bool addToDesktop_)
  58841. : ResizableWindow (title, backgroundColour, addToDesktop_),
  58842. titleBarHeight (26),
  58843. menuBarHeight (24),
  58844. requiredButtons (requiredButtons_),
  58845. #if JUCE_MAC
  58846. positionTitleBarButtonsOnLeft (true),
  58847. #else
  58848. positionTitleBarButtonsOnLeft (false),
  58849. #endif
  58850. drawTitleTextCentred (true),
  58851. titleBarIcon (0),
  58852. menuBar (0),
  58853. menuBarModel (0)
  58854. {
  58855. zeromem (titleBarButtons, sizeof (titleBarButtons));
  58856. setResizeLimits (128, 128, 32768, 32768);
  58857. lookAndFeelChanged();
  58858. }
  58859. DocumentWindow::~DocumentWindow()
  58860. {
  58861. for (int i = 0; i < 3; ++i)
  58862. delete titleBarButtons[i];
  58863. delete titleBarIcon;
  58864. delete menuBar;
  58865. }
  58866. void DocumentWindow::repaintTitleBar()
  58867. {
  58868. const int border = getBorderSize();
  58869. repaint (border, border, getWidth() - border * 2, getTitleBarHeight());
  58870. }
  58871. void DocumentWindow::setName (const String& newName)
  58872. {
  58873. if (newName != getName())
  58874. {
  58875. Component::setName (newName);
  58876. repaintTitleBar();
  58877. }
  58878. }
  58879. void DocumentWindow::setIcon (const Image* imageToUse)
  58880. {
  58881. deleteAndZero (titleBarIcon);
  58882. if (imageToUse != 0)
  58883. titleBarIcon = imageToUse->createCopy();
  58884. repaintTitleBar();
  58885. }
  58886. void DocumentWindow::setTitleBarHeight (const int newHeight)
  58887. {
  58888. titleBarHeight = newHeight;
  58889. resized();
  58890. repaintTitleBar();
  58891. }
  58892. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  58893. const bool positionTitleBarButtonsOnLeft_)
  58894. {
  58895. requiredButtons = requiredButtons_;
  58896. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  58897. lookAndFeelChanged();
  58898. }
  58899. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  58900. {
  58901. drawTitleTextCentred = textShouldBeCentred;
  58902. repaintTitleBar();
  58903. }
  58904. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  58905. const int menuBarHeight_)
  58906. {
  58907. if (menuBarModel != menuBarModel_)
  58908. {
  58909. delete menuBar;
  58910. menuBar = 0;
  58911. menuBarModel = menuBarModel_;
  58912. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  58913. : getLookAndFeel().getDefaultMenuBarHeight();
  58914. if (menuBarModel != 0)
  58915. {
  58916. // (call the Component method directly to avoid the assertion in ResizableWindow)
  58917. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  58918. menuBar->setEnabled (isActiveWindow());
  58919. }
  58920. resized();
  58921. }
  58922. }
  58923. void DocumentWindow::closeButtonPressed()
  58924. {
  58925. /* If you've got a close button, you have to override this method to get
  58926. rid of your window!
  58927. If the window is just a pop-up, you should override this method and make
  58928. it delete the window in whatever way is appropriate for your app. E.g. you
  58929. might just want to call "delete this".
  58930. If your app is centred around this window such that the whole app should quit when
  58931. the window is closed, then you will probably want to use this method as an opportunity
  58932. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  58933. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  58934. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  58935. or closing it via the taskbar icon on Windows).
  58936. */
  58937. jassertfalse
  58938. }
  58939. void DocumentWindow::minimiseButtonPressed()
  58940. {
  58941. setMinimised (true);
  58942. }
  58943. void DocumentWindow::maximiseButtonPressed()
  58944. {
  58945. setFullScreen (! isFullScreen());
  58946. }
  58947. void DocumentWindow::paint (Graphics& g)
  58948. {
  58949. ResizableWindow::paint (g);
  58950. if (resizableBorder == 0 && getBorderSize() == 1)
  58951. {
  58952. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  58953. g.drawRect (0, 0, getWidth(), getHeight());
  58954. }
  58955. const int border = getBorderSize();
  58956. g.setOrigin (border, border);
  58957. g.reduceClipRegion (0, 0, getWidth() - border * 2, getTitleBarHeight());
  58958. int titleSpaceX1 = 6;
  58959. int titleSpaceX2 = getWidth() - 6;
  58960. for (int i = 0; i < 3; ++i)
  58961. {
  58962. if (titleBarButtons[i] != 0)
  58963. {
  58964. if (positionTitleBarButtonsOnLeft)
  58965. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  58966. else
  58967. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  58968. }
  58969. }
  58970. getLookAndFeel()
  58971. .drawDocumentWindowTitleBar (*this, g,
  58972. getWidth() - border * 2,
  58973. getTitleBarHeight(),
  58974. titleSpaceX1, jmax (1, titleSpaceX2 - titleSpaceX1),
  58975. titleBarIcon, ! drawTitleTextCentred);
  58976. }
  58977. void DocumentWindow::resized()
  58978. {
  58979. ResizableWindow::resized();
  58980. if (titleBarButtons[1] != 0)
  58981. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  58982. const int border = getBorderSize();
  58983. getLookAndFeel()
  58984. .positionDocumentWindowButtons (*this,
  58985. border, border,
  58986. getWidth() - border * 2, getTitleBarHeight(),
  58987. titleBarButtons[0],
  58988. titleBarButtons[1],
  58989. titleBarButtons[2],
  58990. positionTitleBarButtonsOnLeft);
  58991. if (menuBar != 0)
  58992. menuBar->setBounds (border, border + getTitleBarHeight(),
  58993. getWidth() - border * 2, menuBarHeight);
  58994. }
  58995. Button* DocumentWindow::getCloseButton() const throw()
  58996. {
  58997. return titleBarButtons[2];
  58998. }
  58999. Button* DocumentWindow::getMinimiseButton() const throw()
  59000. {
  59001. return titleBarButtons[0];
  59002. }
  59003. Button* DocumentWindow::getMaximiseButton() const throw()
  59004. {
  59005. return titleBarButtons[1];
  59006. }
  59007. int DocumentWindow::getDesktopWindowStyleFlags() const
  59008. {
  59009. int flags = ResizableWindow::getDesktopWindowStyleFlags();
  59010. if ((requiredButtons & minimiseButton) != 0)
  59011. flags |= ComponentPeer::windowHasMinimiseButton;
  59012. if ((requiredButtons & maximiseButton) != 0)
  59013. flags |= ComponentPeer::windowHasMaximiseButton;
  59014. if ((requiredButtons & closeButton) != 0)
  59015. flags |= ComponentPeer::windowHasCloseButton;
  59016. return flags;
  59017. }
  59018. void DocumentWindow::lookAndFeelChanged()
  59019. {
  59020. int i;
  59021. for (i = 0; i < 3; ++i)
  59022. deleteAndZero (titleBarButtons[i]);
  59023. if (! isUsingNativeTitleBar())
  59024. {
  59025. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  59026. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  59027. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  59028. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  59029. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  59030. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  59031. for (i = 0; i < 3; ++i)
  59032. {
  59033. if (titleBarButtons[i] != 0)
  59034. {
  59035. buttonListener.owner = this;
  59036. titleBarButtons[i]->addButtonListener (&buttonListener);
  59037. titleBarButtons[i]->setWantsKeyboardFocus (false);
  59038. // (call the Component method directly to avoid the assertion in ResizableWindow)
  59039. Component::addAndMakeVisible (titleBarButtons[i]);
  59040. }
  59041. }
  59042. if (getCloseButton() != 0)
  59043. {
  59044. #if JUCE_MAC
  59045. getCloseButton()->addShortcut (KeyPress (T('w'), ModifierKeys::commandModifier, 0));
  59046. #else
  59047. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  59048. #endif
  59049. }
  59050. }
  59051. activeWindowStatusChanged();
  59052. ResizableWindow::lookAndFeelChanged();
  59053. }
  59054. void DocumentWindow::parentHierarchyChanged()
  59055. {
  59056. lookAndFeelChanged();
  59057. }
  59058. void DocumentWindow::activeWindowStatusChanged()
  59059. {
  59060. ResizableWindow::activeWindowStatusChanged();
  59061. for (int i = 0; i < 3; ++i)
  59062. if (titleBarButtons[i] != 0)
  59063. titleBarButtons[i]->setEnabled (isActiveWindow());
  59064. if (menuBar != 0)
  59065. menuBar->setEnabled (isActiveWindow());
  59066. }
  59067. const BorderSize DocumentWindow::getBorderThickness()
  59068. {
  59069. return BorderSize (getBorderSize());
  59070. }
  59071. const BorderSize DocumentWindow::getContentComponentBorder()
  59072. {
  59073. const int size = getBorderSize();
  59074. return BorderSize (size
  59075. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  59076. + (menuBar != 0 ? menuBarHeight : 0),
  59077. size, size, size);
  59078. }
  59079. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  59080. {
  59081. const int border = getBorderSize();
  59082. if (e.x >= border
  59083. && e.y >= border
  59084. && e.x < getWidth() - border
  59085. && e.y < border + getTitleBarHeight()
  59086. && getMaximiseButton() != 0)
  59087. {
  59088. getMaximiseButton()->triggerClick();
  59089. }
  59090. }
  59091. void DocumentWindow::userTriedToCloseWindow()
  59092. {
  59093. closeButtonPressed();
  59094. }
  59095. int DocumentWindow::getTitleBarHeight() const
  59096. {
  59097. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  59098. }
  59099. int DocumentWindow::getBorderSize() const
  59100. {
  59101. return (isFullScreen() || isUsingNativeTitleBar()) ? 0 : (resizableBorder != 0 ? 4 : 1);
  59102. }
  59103. DocumentWindow::ButtonListenerProxy::ButtonListenerProxy()
  59104. {
  59105. }
  59106. void DocumentWindow::ButtonListenerProxy::buttonClicked (Button* button)
  59107. {
  59108. if (button == owner->getMinimiseButton())
  59109. {
  59110. owner->minimiseButtonPressed();
  59111. }
  59112. else if (button == owner->getMaximiseButton())
  59113. {
  59114. owner->maximiseButtonPressed();
  59115. }
  59116. else if (button == owner->getCloseButton())
  59117. {
  59118. owner->closeButtonPressed();
  59119. }
  59120. }
  59121. END_JUCE_NAMESPACE
  59122. /********* End of inlined file: juce_DocumentWindow.cpp *********/
  59123. /********* Start of inlined file: juce_ResizableWindow.cpp *********/
  59124. BEGIN_JUCE_NAMESPACE
  59125. ResizableWindow::ResizableWindow (const String& name,
  59126. const bool addToDesktop_)
  59127. : TopLevelWindow (name, addToDesktop_),
  59128. resizableCorner (0),
  59129. resizableBorder (0),
  59130. contentComponent (0),
  59131. resizeToFitContent (false),
  59132. fullscreen (false),
  59133. lastNonFullScreenPos (50, 50, 256, 256),
  59134. constrainer (0)
  59135. #ifdef JUCE_DEBUG
  59136. , hasBeenResized (false)
  59137. #endif
  59138. {
  59139. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  59140. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  59141. if (addToDesktop_)
  59142. Component::addToDesktop (getDesktopWindowStyleFlags());
  59143. }
  59144. ResizableWindow::ResizableWindow (const String& name,
  59145. const Colour& backgroundColour_,
  59146. const bool addToDesktop_)
  59147. : TopLevelWindow (name, addToDesktop_),
  59148. resizableCorner (0),
  59149. resizableBorder (0),
  59150. contentComponent (0),
  59151. resizeToFitContent (false),
  59152. fullscreen (false),
  59153. lastNonFullScreenPos (50, 50, 256, 256),
  59154. constrainer (0)
  59155. #ifdef JUCE_DEBUG
  59156. , hasBeenResized (false)
  59157. #endif
  59158. {
  59159. setBackgroundColour (backgroundColour_);
  59160. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  59161. if (addToDesktop_)
  59162. Component::addToDesktop (getDesktopWindowStyleFlags());
  59163. }
  59164. ResizableWindow::~ResizableWindow()
  59165. {
  59166. deleteAndZero (resizableCorner);
  59167. deleteAndZero (resizableBorder);
  59168. deleteAndZero (contentComponent);
  59169. // have you been adding your own components directly to this window..? tut tut tut.
  59170. // Read the instructions for using a ResizableWindow!
  59171. jassert (getNumChildComponents() == 0);
  59172. }
  59173. int ResizableWindow::getDesktopWindowStyleFlags() const
  59174. {
  59175. int flags = TopLevelWindow::getDesktopWindowStyleFlags();
  59176. if (isResizable() && (flags & ComponentPeer::windowHasTitleBar) != 0)
  59177. flags |= ComponentPeer::windowIsResizable;
  59178. return flags;
  59179. }
  59180. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  59181. const bool deleteOldOne,
  59182. const bool resizeToFit)
  59183. {
  59184. resizeToFitContent = resizeToFit;
  59185. if (contentComponent != newContentComponent)
  59186. {
  59187. if (deleteOldOne)
  59188. delete contentComponent;
  59189. else
  59190. removeChildComponent (contentComponent);
  59191. contentComponent = newContentComponent;
  59192. Component::addAndMakeVisible (contentComponent);
  59193. }
  59194. if (resizeToFit)
  59195. childBoundsChanged (contentComponent);
  59196. resized(); // must always be called to position the new content comp
  59197. }
  59198. void ResizableWindow::setContentComponentSize (int width, int height)
  59199. {
  59200. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  59201. const BorderSize border (getContentComponentBorder());
  59202. setSize (width + border.getLeftAndRight(),
  59203. height + border.getTopAndBottom());
  59204. }
  59205. const BorderSize ResizableWindow::getBorderThickness()
  59206. {
  59207. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  59208. }
  59209. const BorderSize ResizableWindow::getContentComponentBorder()
  59210. {
  59211. return getBorderThickness();
  59212. }
  59213. void ResizableWindow::moved()
  59214. {
  59215. updateLastPos();
  59216. }
  59217. void ResizableWindow::visibilityChanged()
  59218. {
  59219. TopLevelWindow::visibilityChanged();
  59220. updateLastPos();
  59221. }
  59222. void ResizableWindow::resized()
  59223. {
  59224. if (resizableBorder != 0)
  59225. {
  59226. resizableBorder->setVisible (! isFullScreen());
  59227. resizableBorder->setBorderThickness (getBorderThickness());
  59228. resizableBorder->setSize (getWidth(), getHeight());
  59229. resizableBorder->toBack();
  59230. }
  59231. if (resizableCorner != 0)
  59232. {
  59233. resizableCorner->setVisible (! isFullScreen());
  59234. const int resizerSize = 18;
  59235. resizableCorner->setBounds (getWidth() - resizerSize,
  59236. getHeight() - resizerSize,
  59237. resizerSize, resizerSize);
  59238. }
  59239. if (contentComponent != 0)
  59240. contentComponent->setBoundsInset (getContentComponentBorder());
  59241. updateLastPos();
  59242. #ifdef JUCE_DEBUG
  59243. hasBeenResized = true;
  59244. #endif
  59245. }
  59246. void ResizableWindow::childBoundsChanged (Component* child)
  59247. {
  59248. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  59249. {
  59250. // not going to look very good if this component has a zero size..
  59251. jassert (child->getWidth() > 0);
  59252. jassert (child->getHeight() > 0);
  59253. const BorderSize borders (getContentComponentBorder());
  59254. setSize (child->getWidth() + borders.getLeftAndRight(),
  59255. child->getHeight() + borders.getTopAndBottom());
  59256. }
  59257. }
  59258. void ResizableWindow::activeWindowStatusChanged()
  59259. {
  59260. const BorderSize borders (getContentComponentBorder());
  59261. repaint (0, 0, getWidth(), borders.getTop());
  59262. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  59263. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  59264. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  59265. }
  59266. void ResizableWindow::setResizable (const bool shouldBeResizable,
  59267. const bool useBottomRightCornerResizer)
  59268. {
  59269. if (shouldBeResizable)
  59270. {
  59271. if (useBottomRightCornerResizer)
  59272. {
  59273. deleteAndZero (resizableBorder);
  59274. if (resizableCorner == 0)
  59275. {
  59276. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  59277. resizableCorner->setAlwaysOnTop (true);
  59278. }
  59279. }
  59280. else
  59281. {
  59282. deleteAndZero (resizableCorner);
  59283. if (resizableBorder == 0)
  59284. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  59285. }
  59286. }
  59287. else
  59288. {
  59289. deleteAndZero (resizableCorner);
  59290. deleteAndZero (resizableBorder);
  59291. }
  59292. if (isUsingNativeTitleBar())
  59293. recreateDesktopWindow();
  59294. childBoundsChanged (contentComponent);
  59295. resized();
  59296. }
  59297. bool ResizableWindow::isResizable() const throw()
  59298. {
  59299. return resizableCorner != 0
  59300. || resizableBorder != 0;
  59301. }
  59302. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  59303. const int newMinimumHeight,
  59304. const int newMaximumWidth,
  59305. const int newMaximumHeight) throw()
  59306. {
  59307. // if you've set up a custom constrainer then these settings won't have any effect..
  59308. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  59309. if (constrainer == 0)
  59310. setConstrainer (&defaultConstrainer);
  59311. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  59312. newMaximumWidth, newMaximumHeight);
  59313. setBoundsConstrained (getX(), getY(), getWidth(), getHeight());
  59314. }
  59315. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  59316. {
  59317. if (constrainer != newConstrainer)
  59318. {
  59319. constrainer = newConstrainer;
  59320. const bool useBottomRightCornerResizer = resizableCorner != 0;
  59321. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  59322. deleteAndZero (resizableCorner);
  59323. deleteAndZero (resizableBorder);
  59324. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  59325. ComponentPeer* const peer = getPeer();
  59326. if (peer != 0)
  59327. peer->setConstrainer (newConstrainer);
  59328. }
  59329. }
  59330. void ResizableWindow::setBoundsConstrained (int x, int y, int w, int h)
  59331. {
  59332. if (constrainer != 0)
  59333. constrainer->setBoundsForComponent (this, x, y, w, h, false, false, false, false);
  59334. else
  59335. setBounds (x, y, w, h);
  59336. }
  59337. void ResizableWindow::paint (Graphics& g)
  59338. {
  59339. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  59340. getBorderThickness(), *this);
  59341. if (! isFullScreen())
  59342. {
  59343. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  59344. getBorderThickness(), *this);
  59345. }
  59346. #ifdef JUCE_DEBUG
  59347. /* If this fails, then you've probably written a subclass with a resized()
  59348. callback but forgotten to make it call its parent class's resized() method.
  59349. It's important when you override methods like resized(), moved(),
  59350. etc., that you make sure the base class methods also get called.
  59351. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  59352. because your content should all be inside the content component - and it's the
  59353. content component's resized() method that you should be using to do your
  59354. layout.
  59355. */
  59356. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  59357. #endif
  59358. }
  59359. void ResizableWindow::lookAndFeelChanged()
  59360. {
  59361. resized();
  59362. if (isOnDesktop())
  59363. {
  59364. Component::addToDesktop (getDesktopWindowStyleFlags());
  59365. ComponentPeer* const peer = getPeer();
  59366. if (peer != 0)
  59367. peer->setConstrainer (constrainer);
  59368. }
  59369. }
  59370. const Colour ResizableWindow::getBackgroundColour() const throw()
  59371. {
  59372. return findColour (backgroundColourId, false);
  59373. }
  59374. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  59375. {
  59376. Colour backgroundColour (newColour);
  59377. if (! Desktop::canUseSemiTransparentWindows())
  59378. backgroundColour = newColour.withAlpha (1.0f);
  59379. setColour (backgroundColourId, backgroundColour);
  59380. setOpaque (backgroundColour.isOpaque());
  59381. repaint();
  59382. }
  59383. bool ResizableWindow::isFullScreen() const
  59384. {
  59385. if (isOnDesktop())
  59386. {
  59387. ComponentPeer* const peer = getPeer();
  59388. return peer != 0 && peer->isFullScreen();
  59389. }
  59390. return fullscreen;
  59391. }
  59392. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  59393. {
  59394. if (shouldBeFullScreen != isFullScreen())
  59395. {
  59396. updateLastPos();
  59397. fullscreen = shouldBeFullScreen;
  59398. if (isOnDesktop())
  59399. {
  59400. ComponentPeer* const peer = getPeer();
  59401. if (peer != 0)
  59402. {
  59403. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  59404. const Rectangle lastPos (lastNonFullScreenPos);
  59405. peer->setFullScreen (shouldBeFullScreen);
  59406. if (! shouldBeFullScreen)
  59407. setBounds (lastPos);
  59408. }
  59409. else
  59410. {
  59411. jassertfalse
  59412. }
  59413. }
  59414. else
  59415. {
  59416. if (shouldBeFullScreen)
  59417. setBounds (0, 0, getParentWidth(), getParentHeight());
  59418. else
  59419. setBounds (lastNonFullScreenPos);
  59420. }
  59421. resized();
  59422. }
  59423. }
  59424. bool ResizableWindow::isMinimised() const
  59425. {
  59426. ComponentPeer* const peer = getPeer();
  59427. return (peer != 0) && peer->isMinimised();
  59428. }
  59429. void ResizableWindow::setMinimised (const bool shouldMinimise)
  59430. {
  59431. if (shouldMinimise != isMinimised())
  59432. {
  59433. ComponentPeer* const peer = getPeer();
  59434. if (peer != 0)
  59435. {
  59436. updateLastPos();
  59437. peer->setMinimised (shouldMinimise);
  59438. }
  59439. else
  59440. {
  59441. jassertfalse
  59442. }
  59443. }
  59444. }
  59445. void ResizableWindow::updateLastPos()
  59446. {
  59447. if (isShowing() && ! (isFullScreen() || isMinimised()))
  59448. {
  59449. lastNonFullScreenPos = getBounds();
  59450. }
  59451. }
  59452. void ResizableWindow::parentSizeChanged()
  59453. {
  59454. if (isFullScreen() && getParentComponent() != 0)
  59455. {
  59456. setBounds (0, 0, getParentWidth(), getParentHeight());
  59457. }
  59458. }
  59459. const String ResizableWindow::getWindowStateAsString()
  59460. {
  59461. updateLastPos();
  59462. String s;
  59463. if (isFullScreen())
  59464. s << "fs ";
  59465. s << lastNonFullScreenPos.getX() << T(' ')
  59466. << lastNonFullScreenPos.getY() << T(' ')
  59467. << lastNonFullScreenPos.getWidth() << T(' ')
  59468. << lastNonFullScreenPos.getHeight();
  59469. return s;
  59470. }
  59471. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  59472. {
  59473. StringArray tokens;
  59474. tokens.addTokens (s, false);
  59475. tokens.removeEmptyStrings();
  59476. tokens.trim();
  59477. const bool fs = tokens[0].startsWithIgnoreCase (T("fs"));
  59478. const int n = fs ? 1 : 0;
  59479. if (tokens.size() != 4 + n)
  59480. return false;
  59481. Rectangle r (tokens[n].getIntValue(),
  59482. tokens[n + 1].getIntValue(),
  59483. tokens[n + 2].getIntValue(),
  59484. tokens[n + 3].getIntValue());
  59485. if (r.isEmpty())
  59486. return false;
  59487. const Rectangle screen (Desktop::getInstance().getMonitorAreaContaining (r.getX(), r.getY()));
  59488. if (! screen.contains (r))
  59489. {
  59490. r.setSize (jmin (r.getWidth(), screen.getWidth()),
  59491. jmin (r.getHeight(), screen.getHeight()));
  59492. r.setPosition (jlimit (screen.getX(), screen.getRight() - r.getWidth(), r.getX()),
  59493. jlimit (screen.getY(), screen.getBottom() - r.getHeight(), r.getY()));
  59494. }
  59495. lastNonFullScreenPos = r;
  59496. if (isOnDesktop())
  59497. {
  59498. ComponentPeer* const peer = getPeer();
  59499. if (peer != 0)
  59500. peer->setNonFullScreenBounds (r);
  59501. }
  59502. setFullScreen (fs);
  59503. if (! fs)
  59504. setBoundsConstrained (r.getX(),
  59505. r.getY(),
  59506. r.getWidth(),
  59507. r.getHeight());
  59508. return true;
  59509. }
  59510. void ResizableWindow::mouseDown (const MouseEvent&)
  59511. {
  59512. if (! isFullScreen())
  59513. dragger.startDraggingComponent (this, constrainer);
  59514. }
  59515. void ResizableWindow::mouseDrag (const MouseEvent& e)
  59516. {
  59517. if (! isFullScreen())
  59518. dragger.dragComponent (this, e);
  59519. }
  59520. #ifdef JUCE_DEBUG
  59521. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  59522. {
  59523. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  59524. manages its child components automatically, and if you add your own it'll cause
  59525. trouble. Instead, use setContentComponent() to give it a component which
  59526. will be automatically resized and kept in the right place - then you can add
  59527. subcomponents to the content comp. See the notes for the ResizableWindow class
  59528. for more info.
  59529. If you really know what you're doing and want to avoid this assertion, just call
  59530. Component::addChildComponent directly.
  59531. */
  59532. jassertfalse
  59533. Component::addChildComponent (child, zOrder);
  59534. }
  59535. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  59536. {
  59537. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  59538. manages its child components automatically, and if you add your own it'll cause
  59539. trouble. Instead, use setContentComponent() to give it a component which
  59540. will be automatically resized and kept in the right place - then you can add
  59541. subcomponents to the content comp. See the notes for the ResizableWindow class
  59542. for more info.
  59543. If you really know what you're doing and want to avoid this assertion, just call
  59544. Component::addAndMakeVisible directly.
  59545. */
  59546. jassertfalse
  59547. Component::addAndMakeVisible (child, zOrder);
  59548. }
  59549. #endif
  59550. END_JUCE_NAMESPACE
  59551. /********* End of inlined file: juce_ResizableWindow.cpp *********/
  59552. /********* Start of inlined file: juce_SplashScreen.cpp *********/
  59553. BEGIN_JUCE_NAMESPACE
  59554. SplashScreen::SplashScreen()
  59555. : backgroundImage (0),
  59556. isImageInCache (false)
  59557. {
  59558. setOpaque (true);
  59559. }
  59560. SplashScreen::~SplashScreen()
  59561. {
  59562. if (isImageInCache)
  59563. ImageCache::release (backgroundImage);
  59564. else
  59565. delete backgroundImage;
  59566. }
  59567. void SplashScreen::show (const String& title,
  59568. Image* const backgroundImage_,
  59569. const int minimumTimeToDisplayFor,
  59570. const bool useDropShadow,
  59571. const bool removeOnMouseClick)
  59572. {
  59573. backgroundImage = backgroundImage_;
  59574. jassert (backgroundImage_ != 0);
  59575. if (backgroundImage_ != 0)
  59576. {
  59577. isImageInCache = ImageCache::isImageInCache (backgroundImage_);
  59578. setOpaque (! backgroundImage_->hasAlphaChannel());
  59579. show (title,
  59580. backgroundImage_->getWidth(),
  59581. backgroundImage_->getHeight(),
  59582. minimumTimeToDisplayFor,
  59583. useDropShadow,
  59584. removeOnMouseClick);
  59585. }
  59586. }
  59587. void SplashScreen::show (const String& title,
  59588. const int width,
  59589. const int height,
  59590. const int minimumTimeToDisplayFor,
  59591. const bool useDropShadow,
  59592. const bool removeOnMouseClick)
  59593. {
  59594. setName (title);
  59595. setAlwaysOnTop (true);
  59596. setVisible (true);
  59597. centreWithSize (width, height);
  59598. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  59599. toFront (false);
  59600. MessageManager::getInstance()->runDispatchLoopUntil (300);
  59601. repaint();
  59602. originalClickCounter = removeOnMouseClick
  59603. ? Desktop::getMouseButtonClickCounter()
  59604. : INT_MAX;
  59605. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  59606. startTimer (50);
  59607. }
  59608. void SplashScreen::paint (Graphics& g)
  59609. {
  59610. if (backgroundImage != 0)
  59611. {
  59612. g.setOpacity (1.0f);
  59613. g.drawImage (backgroundImage,
  59614. 0, 0, getWidth(), getHeight(),
  59615. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  59616. }
  59617. }
  59618. void SplashScreen::timerCallback()
  59619. {
  59620. if (Time::getCurrentTime() > earliestTimeToDelete
  59621. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  59622. {
  59623. delete this;
  59624. }
  59625. }
  59626. END_JUCE_NAMESPACE
  59627. /********* End of inlined file: juce_SplashScreen.cpp *********/
  59628. /********* Start of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  59629. BEGIN_JUCE_NAMESPACE
  59630. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  59631. const bool hasProgressBar,
  59632. const bool hasCancelButton,
  59633. const int timeOutMsWhenCancelling_,
  59634. const String& cancelButtonText)
  59635. : Thread ("Juce Progress Window"),
  59636. progress (0.0),
  59637. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  59638. {
  59639. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  59640. .createAlertWindow (title, String::empty, cancelButtonText,
  59641. String::empty, String::empty,
  59642. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  59643. if (hasProgressBar)
  59644. alertWindow->addProgressBarComponent (progress);
  59645. }
  59646. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  59647. {
  59648. stopThread (timeOutMsWhenCancelling);
  59649. delete alertWindow;
  59650. }
  59651. bool ThreadWithProgressWindow::runThread (const int priority)
  59652. {
  59653. startThread (priority);
  59654. startTimer (100);
  59655. {
  59656. const ScopedLock sl (messageLock);
  59657. alertWindow->setMessage (message);
  59658. }
  59659. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  59660. stopThread (timeOutMsWhenCancelling);
  59661. alertWindow->setVisible (false);
  59662. return finishedNaturally;
  59663. }
  59664. void ThreadWithProgressWindow::setProgress (const double newProgress)
  59665. {
  59666. progress = newProgress;
  59667. }
  59668. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  59669. {
  59670. const ScopedLock sl (messageLock);
  59671. message = newStatusMessage;
  59672. }
  59673. void ThreadWithProgressWindow::timerCallback()
  59674. {
  59675. if (! isThreadRunning())
  59676. {
  59677. // thread has finished normally..
  59678. alertWindow->exitModalState (1);
  59679. alertWindow->setVisible (false);
  59680. }
  59681. else
  59682. {
  59683. const ScopedLock sl (messageLock);
  59684. alertWindow->setMessage (message);
  59685. }
  59686. }
  59687. END_JUCE_NAMESPACE
  59688. /********* End of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  59689. /********* Start of inlined file: juce_TooltipWindow.cpp *********/
  59690. BEGIN_JUCE_NAMESPACE
  59691. TooltipWindow::TooltipWindow (Component* const parentComponent,
  59692. const int millisecondsBeforeTipAppears_)
  59693. : Component ("tooltip"),
  59694. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  59695. mouseX (0),
  59696. mouseY (0),
  59697. lastHideTime (0),
  59698. lastComponentUnderMouse (0),
  59699. changedCompsSinceShown (true)
  59700. {
  59701. startTimer (123);
  59702. setAlwaysOnTop (true);
  59703. setOpaque (true);
  59704. if (parentComponent != 0)
  59705. parentComponent->addChildComponent (this);
  59706. }
  59707. TooltipWindow::~TooltipWindow()
  59708. {
  59709. hide();
  59710. }
  59711. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  59712. {
  59713. millisecondsBeforeTipAppears = newTimeMs;
  59714. }
  59715. void TooltipWindow::paint (Graphics& g)
  59716. {
  59717. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  59718. }
  59719. void TooltipWindow::mouseEnter (const MouseEvent&)
  59720. {
  59721. hide();
  59722. }
  59723. void TooltipWindow::showFor (Component* const c, const String& tip)
  59724. {
  59725. jassert (tip.isNotEmpty());
  59726. tipShowing = tip;
  59727. int mx, my;
  59728. Desktop::getMousePosition (mx, my);
  59729. if (getParentComponent() != 0)
  59730. getParentComponent()->globalPositionToRelative (mx, my);
  59731. int x, y, w, h;
  59732. getLookAndFeel().getTooltipSize (tip, w, h);
  59733. if (mx > getParentWidth() / 2)
  59734. x = mx - (w + 12);
  59735. else
  59736. x = mx + 24;
  59737. if (my > getParentHeight() / 2)
  59738. y = my - (h + 6);
  59739. else
  59740. y = my + 6;
  59741. setBounds (x, y, w, h);
  59742. setVisible (true);
  59743. if (getParentComponent() == 0)
  59744. {
  59745. addToDesktop (ComponentPeer::windowHasDropShadow
  59746. | ComponentPeer::windowIsTemporary);
  59747. }
  59748. toFront (false);
  59749. }
  59750. const String TooltipWindow::getTipFor (Component* const c)
  59751. {
  59752. if (c->isValidComponent()
  59753. && Process::isForegroundProcess()
  59754. && ! Component::isMouseButtonDownAnywhere())
  59755. {
  59756. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  59757. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  59758. return ttc->getTooltip();
  59759. }
  59760. return String::empty;
  59761. }
  59762. void TooltipWindow::hide()
  59763. {
  59764. tipShowing = String::empty;
  59765. removeFromDesktop();
  59766. setVisible (false);
  59767. }
  59768. void TooltipWindow::timerCallback()
  59769. {
  59770. const unsigned int now = Time::getApproximateMillisecondCounter();
  59771. Component* const newComp = Component::getComponentUnderMouse();
  59772. const String newTip (getTipFor (newComp));
  59773. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  59774. lastComponentUnderMouse = newComp;
  59775. lastTipUnderMouse = newTip;
  59776. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  59777. const bool mouseWasClicked = clickCount > mouseClicks;
  59778. mouseClicks = clickCount;
  59779. int mx, my;
  59780. Desktop::getMousePosition (mx, my);
  59781. const bool mouseMovedQuickly = (abs (mx - mouseX) + abs (my - mouseY) > 12);
  59782. mouseX = mx;
  59783. mouseY = my;
  59784. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  59785. lastCompChangeTime = now;
  59786. if (isVisible() || now < lastHideTime + 500)
  59787. {
  59788. // if a tip is currently visible (or has just disappeared), update to a new one
  59789. // immediately if needed..
  59790. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  59791. {
  59792. if (isVisible())
  59793. {
  59794. lastHideTime = now;
  59795. hide();
  59796. }
  59797. }
  59798. else if (tipChanged)
  59799. {
  59800. showFor (newComp, newTip);
  59801. }
  59802. }
  59803. else
  59804. {
  59805. // if there isn't currently a tip, but one is needed, only let it
  59806. // appear after a timeout..
  59807. if (newTip.isNotEmpty()
  59808. && newTip != tipShowing
  59809. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  59810. {
  59811. showFor (newComp, newTip);
  59812. }
  59813. }
  59814. }
  59815. END_JUCE_NAMESPACE
  59816. /********* End of inlined file: juce_TooltipWindow.cpp *********/
  59817. /********* Start of inlined file: juce_TopLevelWindow.cpp *********/
  59818. BEGIN_JUCE_NAMESPACE
  59819. /** Keeps track of the active top level window.
  59820. */
  59821. class TopLevelWindowManager : public Timer,
  59822. public DeletedAtShutdown
  59823. {
  59824. public:
  59825. TopLevelWindowManager()
  59826. : windows (8),
  59827. currentActive (0)
  59828. {
  59829. }
  59830. ~TopLevelWindowManager()
  59831. {
  59832. clearSingletonInstance();
  59833. }
  59834. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  59835. void timerCallback()
  59836. {
  59837. startTimer (jmin (1731, getTimerInterval() * 2));
  59838. TopLevelWindow* active = 0;
  59839. if (Process::isForegroundProcess())
  59840. {
  59841. active = currentActive;
  59842. Component* const c = Component::getCurrentlyFocusedComponent();
  59843. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  59844. if (tlw == 0 && c != 0)
  59845. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  59846. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  59847. if (tlw != 0)
  59848. active = tlw;
  59849. }
  59850. if (active != currentActive)
  59851. {
  59852. currentActive = active;
  59853. for (int i = windows.size(); --i >= 0;)
  59854. {
  59855. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  59856. tlw->setWindowActive (isWindowActive (tlw));
  59857. i = jmin (i, windows.size() - 1);
  59858. }
  59859. Desktop::getInstance().triggerFocusCallback();
  59860. }
  59861. }
  59862. bool addWindow (TopLevelWindow* const w) throw()
  59863. {
  59864. windows.add (w);
  59865. startTimer (10);
  59866. return isWindowActive (w);
  59867. }
  59868. void removeWindow (TopLevelWindow* const w) throw()
  59869. {
  59870. startTimer (10);
  59871. if (currentActive == w)
  59872. currentActive = 0;
  59873. windows.removeValue (w);
  59874. if (windows.size() == 0)
  59875. deleteInstance();
  59876. }
  59877. VoidArray windows;
  59878. private:
  59879. TopLevelWindow* currentActive;
  59880. bool isWindowActive (TopLevelWindow* const tlw) const throw()
  59881. {
  59882. return (tlw == currentActive
  59883. || tlw->isParentOf (currentActive)
  59884. || tlw->hasKeyboardFocus (true))
  59885. && tlw->isShowing();
  59886. }
  59887. TopLevelWindowManager (const TopLevelWindowManager&);
  59888. const TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  59889. };
  59890. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  59891. void juce_CheckCurrentlyFocusedTopLevelWindow() throw()
  59892. {
  59893. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  59894. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  59895. }
  59896. TopLevelWindow::TopLevelWindow (const String& name,
  59897. const bool addToDesktop_)
  59898. : Component (name),
  59899. useDropShadow (true),
  59900. useNativeTitleBar (false),
  59901. windowIsActive_ (false),
  59902. shadower (0)
  59903. {
  59904. setOpaque (true);
  59905. if (addToDesktop_)
  59906. Component::addToDesktop (getDesktopWindowStyleFlags());
  59907. else
  59908. setDropShadowEnabled (true);
  59909. setWantsKeyboardFocus (true);
  59910. setBroughtToFrontOnMouseClick (true);
  59911. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  59912. }
  59913. TopLevelWindow::~TopLevelWindow()
  59914. {
  59915. deleteAndZero (shadower);
  59916. TopLevelWindowManager::getInstance()->removeWindow (this);
  59917. }
  59918. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  59919. {
  59920. if (hasKeyboardFocus (true))
  59921. TopLevelWindowManager::getInstance()->timerCallback();
  59922. else
  59923. TopLevelWindowManager::getInstance()->startTimer (10);
  59924. }
  59925. void TopLevelWindow::setWindowActive (const bool isNowActive) throw()
  59926. {
  59927. if (windowIsActive_ != isNowActive)
  59928. {
  59929. windowIsActive_ = isNowActive;
  59930. activeWindowStatusChanged();
  59931. }
  59932. }
  59933. void TopLevelWindow::activeWindowStatusChanged()
  59934. {
  59935. }
  59936. void TopLevelWindow::parentHierarchyChanged()
  59937. {
  59938. setDropShadowEnabled (useDropShadow);
  59939. }
  59940. void TopLevelWindow::visibilityChanged()
  59941. {
  59942. if (isShowing())
  59943. toFront (true);
  59944. }
  59945. int TopLevelWindow::getDesktopWindowStyleFlags() const
  59946. {
  59947. int flags = ComponentPeer::windowAppearsOnTaskbar;
  59948. if (useDropShadow)
  59949. flags |= ComponentPeer::windowHasDropShadow;
  59950. if (useNativeTitleBar)
  59951. flags |= ComponentPeer::windowHasTitleBar;
  59952. return flags;
  59953. }
  59954. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  59955. {
  59956. useDropShadow = useShadow;
  59957. if (isOnDesktop())
  59958. {
  59959. deleteAndZero (shadower);
  59960. Component::addToDesktop (getDesktopWindowStyleFlags());
  59961. }
  59962. else
  59963. {
  59964. if (useShadow && isOpaque())
  59965. {
  59966. if (shadower == 0)
  59967. {
  59968. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  59969. if (shadower != 0)
  59970. shadower->setOwner (this);
  59971. }
  59972. }
  59973. else
  59974. {
  59975. deleteAndZero (shadower);
  59976. }
  59977. }
  59978. }
  59979. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  59980. {
  59981. if (useNativeTitleBar != useNativeTitleBar_)
  59982. {
  59983. useNativeTitleBar = useNativeTitleBar_;
  59984. recreateDesktopWindow();
  59985. sendLookAndFeelChange();
  59986. }
  59987. }
  59988. void TopLevelWindow::recreateDesktopWindow()
  59989. {
  59990. if (isOnDesktop())
  59991. {
  59992. Component::addToDesktop (getDesktopWindowStyleFlags());
  59993. toFront (true);
  59994. }
  59995. }
  59996. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  59997. {
  59998. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  59999. because this class needs to make sure its layout corresponds with settings like whether
  60000. it's got a native title bar or not.
  60001. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  60002. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  60003. method, then add or remove whatever flags are necessary from this value before returning it.
  60004. */
  60005. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  60006. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  60007. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  60008. if (windowStyleFlags != getDesktopWindowStyleFlags())
  60009. sendLookAndFeelChange();
  60010. }
  60011. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  60012. {
  60013. if (c == 0)
  60014. c = TopLevelWindow::getActiveTopLevelWindow();
  60015. if (c == 0)
  60016. {
  60017. centreWithSize (width, height);
  60018. }
  60019. else
  60020. {
  60021. int x = (c->getWidth() - width) / 2;
  60022. int y = (c->getHeight() - height) / 2;
  60023. c->relativePositionToGlobal (x, y);
  60024. Rectangle parentArea (c->getParentMonitorArea());
  60025. if (getParentComponent() != 0)
  60026. {
  60027. getParentComponent()->globalPositionToRelative (x, y);
  60028. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  60029. }
  60030. parentArea.reduce (12, 12);
  60031. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), x),
  60032. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), y),
  60033. width, height);
  60034. }
  60035. }
  60036. int TopLevelWindow::getNumTopLevelWindows() throw()
  60037. {
  60038. return TopLevelWindowManager::getInstance()->windows.size();
  60039. }
  60040. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  60041. {
  60042. return (TopLevelWindow*) TopLevelWindowManager::getInstance()->windows [index];
  60043. }
  60044. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  60045. {
  60046. TopLevelWindow* best = 0;
  60047. int bestNumTWLParents = -1;
  60048. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  60049. {
  60050. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  60051. if (tlw->isActiveWindow())
  60052. {
  60053. int numTWLParents = 0;
  60054. const Component* c = tlw->getParentComponent();
  60055. while (c != 0)
  60056. {
  60057. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  60058. ++numTWLParents;
  60059. c = c->getParentComponent();
  60060. }
  60061. if (bestNumTWLParents < numTWLParents)
  60062. {
  60063. best = tlw;
  60064. bestNumTWLParents = numTWLParents;
  60065. }
  60066. }
  60067. }
  60068. return best;
  60069. }
  60070. END_JUCE_NAMESPACE
  60071. /********* End of inlined file: juce_TopLevelWindow.cpp *********/
  60072. /********* Start of inlined file: juce_Brush.cpp *********/
  60073. BEGIN_JUCE_NAMESPACE
  60074. Brush::Brush() throw()
  60075. {
  60076. }
  60077. Brush::~Brush() throw()
  60078. {
  60079. }
  60080. void Brush::paintVerticalLine (LowLevelGraphicsContext& context,
  60081. int x, float y1, float y2) throw()
  60082. {
  60083. Path p;
  60084. p.addRectangle ((float) x, y1, 1.0f, y2 - y1);
  60085. paintPath (context, p, AffineTransform::identity);
  60086. }
  60087. void Brush::paintHorizontalLine (LowLevelGraphicsContext& context,
  60088. int y, float x1, float x2) throw()
  60089. {
  60090. Path p;
  60091. p.addRectangle (x1, (float) y, x2 - x1, 1.0f);
  60092. paintPath (context, p, AffineTransform::identity);
  60093. }
  60094. void Brush::paintLine (LowLevelGraphicsContext& context,
  60095. float x1, float y1, float x2, float y2) throw()
  60096. {
  60097. Path p;
  60098. p.addLineSegment (x1, y1, x2, y2, 1.0f);
  60099. paintPath (context, p, AffineTransform::identity);
  60100. }
  60101. END_JUCE_NAMESPACE
  60102. /********* End of inlined file: juce_Brush.cpp *********/
  60103. /********* Start of inlined file: juce_GradientBrush.cpp *********/
  60104. BEGIN_JUCE_NAMESPACE
  60105. GradientBrush::GradientBrush (const Colour& colour1,
  60106. const float x1,
  60107. const float y1,
  60108. const Colour& colour2,
  60109. const float x2,
  60110. const float y2,
  60111. const bool isRadial) throw()
  60112. : gradient (colour1, x1, y1,
  60113. colour2, x2, y2,
  60114. isRadial)
  60115. {
  60116. }
  60117. GradientBrush::GradientBrush (const ColourGradient& gradient_) throw()
  60118. : gradient (gradient_)
  60119. {
  60120. }
  60121. GradientBrush::~GradientBrush() throw()
  60122. {
  60123. }
  60124. Brush* GradientBrush::createCopy() const throw()
  60125. {
  60126. return new GradientBrush (gradient);
  60127. }
  60128. void GradientBrush::applyTransform (const AffineTransform& transform) throw()
  60129. {
  60130. gradient.transform = gradient.transform.followedBy (transform);
  60131. }
  60132. void GradientBrush::multiplyOpacity (const float multiple) throw()
  60133. {
  60134. gradient.multiplyOpacity (multiple);
  60135. }
  60136. bool GradientBrush::isInvisible() const throw()
  60137. {
  60138. return gradient.isInvisible();
  60139. }
  60140. void GradientBrush::paintPath (LowLevelGraphicsContext& context,
  60141. const Path& path, const AffineTransform& transform) throw()
  60142. {
  60143. context.fillPathWithGradient (path, transform, gradient, EdgeTable::Oversampling_4times);
  60144. }
  60145. void GradientBrush::paintRectangle (LowLevelGraphicsContext& context,
  60146. int x, int y, int w, int h) throw()
  60147. {
  60148. context.fillRectWithGradient (x, y, w, h, gradient);
  60149. }
  60150. void GradientBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60151. const Image& alphaChannelImage, int imageX, int imageY,
  60152. int x, int y, int w, int h) throw()
  60153. {
  60154. context.saveState();
  60155. if (context.reduceClipRegion (x, y, w, h))
  60156. context.fillAlphaChannelWithGradient (alphaChannelImage, imageX, imageY, gradient);
  60157. context.restoreState();
  60158. }
  60159. END_JUCE_NAMESPACE
  60160. /********* End of inlined file: juce_GradientBrush.cpp *********/
  60161. /********* Start of inlined file: juce_ImageBrush.cpp *********/
  60162. BEGIN_JUCE_NAMESPACE
  60163. ImageBrush::ImageBrush (Image* const image_,
  60164. const int anchorX_,
  60165. const int anchorY_,
  60166. const float opacity_) throw()
  60167. : image (image_),
  60168. anchorX (anchorX_),
  60169. anchorY (anchorY_),
  60170. opacity (opacity_)
  60171. {
  60172. jassert (image != 0); // not much point creating a brush without an image, is there?
  60173. if (image != 0)
  60174. {
  60175. if (image->getWidth() == 0 || image->getHeight() == 0)
  60176. {
  60177. jassertfalse // you've passed in an empty image - not exactly brilliant for tiling.
  60178. image = 0;
  60179. }
  60180. }
  60181. }
  60182. ImageBrush::~ImageBrush() throw()
  60183. {
  60184. }
  60185. Brush* ImageBrush::createCopy() const throw()
  60186. {
  60187. return new ImageBrush (image, anchorX, anchorY, opacity);
  60188. }
  60189. void ImageBrush::multiplyOpacity (const float multiple) throw()
  60190. {
  60191. opacity *= multiple;
  60192. }
  60193. bool ImageBrush::isInvisible() const throw()
  60194. {
  60195. return opacity == 0.0f;
  60196. }
  60197. void ImageBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  60198. {
  60199. //xxx should probably be smarter and warp the image
  60200. }
  60201. void ImageBrush::getStartXY (int& x, int& y) const throw()
  60202. {
  60203. x -= anchorX;
  60204. y -= anchorY;
  60205. const int iw = image->getWidth();
  60206. const int ih = image->getHeight();
  60207. if (x < 0)
  60208. x = ((x / iw) - 1) * iw;
  60209. else
  60210. x = (x / iw) * iw;
  60211. if (y < 0)
  60212. y = ((y / ih) - 1) * ih;
  60213. else
  60214. y = (y / ih) * ih;
  60215. x += anchorX;
  60216. y += anchorY;
  60217. }
  60218. void ImageBrush::paintRectangle (LowLevelGraphicsContext& context,
  60219. int x, int y, int w, int h) throw()
  60220. {
  60221. context.saveState();
  60222. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  60223. {
  60224. const int right = x + w;
  60225. const int bottom = y + h;
  60226. const int iw = image->getWidth();
  60227. const int ih = image->getHeight();
  60228. int startX = x;
  60229. getStartXY (startX, y);
  60230. while (y < bottom)
  60231. {
  60232. x = startX;
  60233. while (x < right)
  60234. {
  60235. context.blendImage (*image, x, y, iw, ih, 0, 0, opacity);
  60236. x += iw;
  60237. }
  60238. y += ih;
  60239. }
  60240. }
  60241. context.restoreState();
  60242. }
  60243. void ImageBrush::paintPath (LowLevelGraphicsContext& context,
  60244. const Path& path, const AffineTransform& transform) throw()
  60245. {
  60246. if (image != 0)
  60247. {
  60248. Rectangle clip (context.getClipBounds());
  60249. {
  60250. float x, y, w, h;
  60251. path.getBoundsTransformed (transform, x, y, w, h);
  60252. clip = clip.getIntersection (Rectangle ((int) floorf (x),
  60253. (int) floorf (y),
  60254. 2 + (int) floorf (w),
  60255. 2 + (int) floorf (h)));
  60256. }
  60257. int x = clip.getX();
  60258. int y = clip.getY();
  60259. const int right = clip.getRight();
  60260. const int bottom = clip.getBottom();
  60261. const int iw = image->getWidth();
  60262. const int ih = image->getHeight();
  60263. int startX = x;
  60264. getStartXY (startX, y);
  60265. while (y < bottom)
  60266. {
  60267. x = startX;
  60268. while (x < right)
  60269. {
  60270. context.fillPathWithImage (path, transform, *image, x, y, opacity, EdgeTable::Oversampling_4times);
  60271. x += iw;
  60272. }
  60273. y += ih;
  60274. }
  60275. }
  60276. }
  60277. void ImageBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60278. const Image& alphaChannelImage, int imageX, int imageY,
  60279. int x, int y, int w, int h) throw()
  60280. {
  60281. context.saveState();
  60282. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  60283. {
  60284. const Rectangle clip (context.getClipBounds());
  60285. x = clip.getX();
  60286. y = clip.getY();
  60287. const int right = clip.getRight();
  60288. const int bottom = clip.getBottom();
  60289. const int iw = image->getWidth();
  60290. const int ih = image->getHeight();
  60291. int startX = x;
  60292. getStartXY (startX, y);
  60293. while (y < bottom)
  60294. {
  60295. x = startX;
  60296. while (x < right)
  60297. {
  60298. context.fillAlphaChannelWithImage (alphaChannelImage,
  60299. imageX, imageY, *image,
  60300. x, y, opacity);
  60301. x += iw;
  60302. }
  60303. y += ih;
  60304. }
  60305. }
  60306. context.restoreState();
  60307. }
  60308. END_JUCE_NAMESPACE
  60309. /********* End of inlined file: juce_ImageBrush.cpp *********/
  60310. /********* Start of inlined file: juce_SolidColourBrush.cpp *********/
  60311. BEGIN_JUCE_NAMESPACE
  60312. SolidColourBrush::SolidColourBrush() throw()
  60313. : colour (0xff000000)
  60314. {
  60315. }
  60316. SolidColourBrush::SolidColourBrush (const Colour& colour_) throw()
  60317. : colour (colour_)
  60318. {
  60319. }
  60320. SolidColourBrush::~SolidColourBrush() throw()
  60321. {
  60322. }
  60323. Brush* SolidColourBrush::createCopy() const throw()
  60324. {
  60325. return new SolidColourBrush (colour);
  60326. }
  60327. void SolidColourBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  60328. {
  60329. }
  60330. void SolidColourBrush::multiplyOpacity (const float multiple) throw()
  60331. {
  60332. colour = colour.withMultipliedAlpha (multiple);
  60333. }
  60334. bool SolidColourBrush::isInvisible() const throw()
  60335. {
  60336. return colour.isTransparent();
  60337. }
  60338. void SolidColourBrush::paintPath (LowLevelGraphicsContext& context,
  60339. const Path& path, const AffineTransform& transform) throw()
  60340. {
  60341. if (! colour.isTransparent())
  60342. context.fillPathWithColour (path, transform, colour, EdgeTable::Oversampling_4times);
  60343. }
  60344. void SolidColourBrush::paintRectangle (LowLevelGraphicsContext& context,
  60345. int x, int y, int w, int h) throw()
  60346. {
  60347. if (! colour.isTransparent())
  60348. context.fillRectWithColour (x, y, w, h, colour, false);
  60349. }
  60350. void SolidColourBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60351. const Image& alphaChannelImage, int imageX, int imageY,
  60352. int x, int y, int w, int h) throw()
  60353. {
  60354. if (! colour.isTransparent())
  60355. {
  60356. context.saveState();
  60357. if (context.reduceClipRegion (x, y, w, h))
  60358. context.fillAlphaChannelWithColour (alphaChannelImage, imageX, imageY, colour);
  60359. context.restoreState();
  60360. }
  60361. }
  60362. void SolidColourBrush::paintVerticalLine (LowLevelGraphicsContext& context,
  60363. int x, float y1, float y2) throw()
  60364. {
  60365. context.drawVerticalLine (x, y1, y2, colour);
  60366. }
  60367. void SolidColourBrush::paintHorizontalLine (LowLevelGraphicsContext& context,
  60368. int y, float x1, float x2) throw()
  60369. {
  60370. context.drawHorizontalLine (y, x1, x2, colour);
  60371. }
  60372. void SolidColourBrush::paintLine (LowLevelGraphicsContext& context,
  60373. float x1, float y1, float x2, float y2) throw()
  60374. {
  60375. context.drawLine (x1, y1, x2, y2, colour);
  60376. }
  60377. END_JUCE_NAMESPACE
  60378. /********* End of inlined file: juce_SolidColourBrush.cpp *********/
  60379. /********* Start of inlined file: juce_Colour.cpp *********/
  60380. BEGIN_JUCE_NAMESPACE
  60381. static forcedinline uint8 floatAlphaToInt (const float alpha)
  60382. {
  60383. return (uint8) jlimit (0, 0xff, roundFloatToInt (alpha * 255.0f));
  60384. }
  60385. static const float oneOver255 = 1.0f / 255.0f;
  60386. Colour::Colour() throw()
  60387. : argb (0)
  60388. {
  60389. }
  60390. Colour::Colour (const Colour& other) throw()
  60391. : argb (other.argb)
  60392. {
  60393. }
  60394. const Colour& Colour::operator= (const Colour& other) throw()
  60395. {
  60396. argb = other.argb;
  60397. return *this;
  60398. }
  60399. bool Colour::operator== (const Colour& other) const throw()
  60400. {
  60401. return argb.getARGB() == other.argb.getARGB();
  60402. }
  60403. bool Colour::operator!= (const Colour& other) const throw()
  60404. {
  60405. return argb.getARGB() != other.argb.getARGB();
  60406. }
  60407. Colour::Colour (const uint32 argb_) throw()
  60408. : argb (argb_)
  60409. {
  60410. }
  60411. Colour::Colour (const uint8 red,
  60412. const uint8 green,
  60413. const uint8 blue) throw()
  60414. {
  60415. argb.setARGB (0xff, red, green, blue);
  60416. }
  60417. const Colour Colour::fromRGB (const uint8 red,
  60418. const uint8 green,
  60419. const uint8 blue) throw()
  60420. {
  60421. return Colour (red, green, blue);
  60422. }
  60423. Colour::Colour (const uint8 red,
  60424. const uint8 green,
  60425. const uint8 blue,
  60426. const uint8 alpha) throw()
  60427. {
  60428. argb.setARGB (alpha, red, green, blue);
  60429. }
  60430. const Colour Colour::fromRGBA (const uint8 red,
  60431. const uint8 green,
  60432. const uint8 blue,
  60433. const uint8 alpha) throw()
  60434. {
  60435. return Colour (red, green, blue, alpha);
  60436. }
  60437. Colour::Colour (const uint8 red,
  60438. const uint8 green,
  60439. const uint8 blue,
  60440. const float alpha) throw()
  60441. {
  60442. argb.setARGB (floatAlphaToInt (alpha), red, green, blue);
  60443. }
  60444. const Colour Colour::fromRGBAFloat (const uint8 red,
  60445. const uint8 green,
  60446. const uint8 blue,
  60447. const float alpha) throw()
  60448. {
  60449. return Colour (red, green, blue, alpha);
  60450. }
  60451. static void convertHSBtoRGB (float h, const float s, float v,
  60452. uint8& r, uint8& g, uint8& b) throw()
  60453. {
  60454. v *= 255.0f;
  60455. const uint8 intV = (uint8) roundFloatToInt (v);
  60456. if (s == 0)
  60457. {
  60458. r = intV;
  60459. g = intV;
  60460. b = intV;
  60461. }
  60462. else
  60463. {
  60464. h = (h - floorf (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  60465. const float f = h - floorf (h);
  60466. const uint8 x = (uint8) roundFloatToInt (v * (1.0f - s));
  60467. const float y = v * (1.0f - s * f);
  60468. const float z = v * (1.0f - (s * (1.0f - f)));
  60469. if (h < 1.0f)
  60470. {
  60471. r = intV;
  60472. g = (uint8) roundFloatToInt (z);
  60473. b = x;
  60474. }
  60475. else if (h < 2.0f)
  60476. {
  60477. r = (uint8) roundFloatToInt (y);
  60478. g = intV;
  60479. b = x;
  60480. }
  60481. else if (h < 3.0f)
  60482. {
  60483. r = x;
  60484. g = intV;
  60485. b = (uint8) roundFloatToInt (z);
  60486. }
  60487. else if (h < 4.0f)
  60488. {
  60489. r = x;
  60490. g = (uint8) roundFloatToInt (y);
  60491. b = intV;
  60492. }
  60493. else if (h < 5.0f)
  60494. {
  60495. r = (uint8) roundFloatToInt (z);
  60496. g = x;
  60497. b = intV;
  60498. }
  60499. else if (h < 6.0f)
  60500. {
  60501. r = intV;
  60502. g = x;
  60503. b = (uint8) roundFloatToInt (y);
  60504. }
  60505. else
  60506. {
  60507. r = 0;
  60508. g = 0;
  60509. b = 0;
  60510. }
  60511. }
  60512. }
  60513. Colour::Colour (const float hue,
  60514. const float saturation,
  60515. const float brightness,
  60516. const float alpha) throw()
  60517. {
  60518. uint8 r = getRed(), g = getGreen(), b = getBlue();
  60519. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  60520. argb.setARGB (floatAlphaToInt (alpha), r, g, b);
  60521. }
  60522. const Colour Colour::fromHSV (const float hue,
  60523. const float saturation,
  60524. const float brightness,
  60525. const float alpha) throw()
  60526. {
  60527. return Colour (hue, saturation, brightness, alpha);
  60528. }
  60529. Colour::Colour (const float hue,
  60530. const float saturation,
  60531. const float brightness,
  60532. const uint8 alpha) throw()
  60533. {
  60534. uint8 r = getRed(), g = getGreen(), b = getBlue();
  60535. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  60536. argb.setARGB (alpha, r, g, b);
  60537. }
  60538. Colour::~Colour() throw()
  60539. {
  60540. }
  60541. const PixelARGB Colour::getPixelARGB() const throw()
  60542. {
  60543. PixelARGB p (argb);
  60544. p.premultiply();
  60545. return p;
  60546. }
  60547. uint32 Colour::getARGB() const throw()
  60548. {
  60549. return argb.getARGB();
  60550. }
  60551. bool Colour::isTransparent() const throw()
  60552. {
  60553. return getAlpha() == 0;
  60554. }
  60555. bool Colour::isOpaque() const throw()
  60556. {
  60557. return getAlpha() == 0xff;
  60558. }
  60559. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  60560. {
  60561. PixelARGB newCol (argb);
  60562. newCol.setAlpha (newAlpha);
  60563. return Colour (newCol.getARGB());
  60564. }
  60565. const Colour Colour::withAlpha (const float newAlpha) const throw()
  60566. {
  60567. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  60568. PixelARGB newCol (argb);
  60569. newCol.setAlpha (floatAlphaToInt (newAlpha));
  60570. return Colour (newCol.getARGB());
  60571. }
  60572. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  60573. {
  60574. jassert (alphaMultiplier >= 0);
  60575. PixelARGB newCol (argb);
  60576. newCol.setAlpha ((uint8) jmin (0xff, roundFloatToInt (alphaMultiplier * newCol.getAlpha())));
  60577. return Colour (newCol.getARGB());
  60578. }
  60579. const Colour Colour::overlaidWith (const Colour& src) const throw()
  60580. {
  60581. const int destAlpha = getAlpha();
  60582. if (destAlpha > 0)
  60583. {
  60584. const int invA = 0xff - (int) src.getAlpha();
  60585. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  60586. if (resA > 0)
  60587. {
  60588. const int da = (invA * destAlpha) / resA;
  60589. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  60590. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  60591. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  60592. (uint8) resA);
  60593. }
  60594. return *this;
  60595. }
  60596. else
  60597. {
  60598. return src;
  60599. }
  60600. }
  60601. float Colour::getFloatRed() const throw()
  60602. {
  60603. return getRed() * oneOver255;
  60604. }
  60605. float Colour::getFloatGreen() const throw()
  60606. {
  60607. return getGreen() * oneOver255;
  60608. }
  60609. float Colour::getFloatBlue() const throw()
  60610. {
  60611. return getBlue() * oneOver255;
  60612. }
  60613. float Colour::getFloatAlpha() const throw()
  60614. {
  60615. return getAlpha() * oneOver255;
  60616. }
  60617. void Colour::getHSB (float& h, float& s, float& v) const throw()
  60618. {
  60619. const int r = getRed();
  60620. const int g = getGreen();
  60621. const int b = getBlue();
  60622. const int hi = jmax (r, g, b);
  60623. const int lo = jmin (r, g, b);
  60624. if (hi != 0)
  60625. {
  60626. s = (hi - lo) / (float) hi;
  60627. if (s != 0)
  60628. {
  60629. const float invDiff = 1.0f / (hi - lo);
  60630. const float red = (hi - r) * invDiff;
  60631. const float green = (hi - g) * invDiff;
  60632. const float blue = (hi - b) * invDiff;
  60633. if (r == hi)
  60634. h = blue - green;
  60635. else if (g == hi)
  60636. h = 2.0f + red - blue;
  60637. else
  60638. h = 4.0f + green - red;
  60639. h *= 1.0f / 6.0f;
  60640. if (h < 0)
  60641. ++h;
  60642. }
  60643. else
  60644. {
  60645. h = 0;
  60646. }
  60647. }
  60648. else
  60649. {
  60650. s = 0;
  60651. h = 0;
  60652. }
  60653. v = hi * oneOver255;
  60654. }
  60655. float Colour::getHue() const throw()
  60656. {
  60657. float h, s, b;
  60658. getHSB (h, s, b);
  60659. return h;
  60660. }
  60661. const Colour Colour::withHue (const float hue) const throw()
  60662. {
  60663. float h, s, b;
  60664. getHSB (h, s, b);
  60665. return Colour (hue, s, b, getAlpha());
  60666. }
  60667. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  60668. {
  60669. float h, s, b;
  60670. getHSB (h, s, b);
  60671. h += amountToRotate;
  60672. h -= floorf (h);
  60673. return Colour (h, s, b, getAlpha());
  60674. }
  60675. float Colour::getSaturation() const throw()
  60676. {
  60677. float h, s, b;
  60678. getHSB (h, s, b);
  60679. return s;
  60680. }
  60681. const Colour Colour::withSaturation (const float saturation) const throw()
  60682. {
  60683. float h, s, b;
  60684. getHSB (h, s, b);
  60685. return Colour (h, saturation, b, getAlpha());
  60686. }
  60687. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  60688. {
  60689. float h, s, b;
  60690. getHSB (h, s, b);
  60691. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  60692. }
  60693. float Colour::getBrightness() const throw()
  60694. {
  60695. float h, s, b;
  60696. getHSB (h, s, b);
  60697. return b;
  60698. }
  60699. const Colour Colour::withBrightness (const float brightness) const throw()
  60700. {
  60701. float h, s, b;
  60702. getHSB (h, s, b);
  60703. return Colour (h, s, brightness, getAlpha());
  60704. }
  60705. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  60706. {
  60707. float h, s, b;
  60708. getHSB (h, s, b);
  60709. b *= amount;
  60710. if (b > 1.0f)
  60711. b = 1.0f;
  60712. return Colour (h, s, b, getAlpha());
  60713. }
  60714. const Colour Colour::brighter (float amount) const throw()
  60715. {
  60716. amount = 1.0f / (1.0f + amount);
  60717. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  60718. (uint8) (255 - (amount * (255 - getGreen()))),
  60719. (uint8) (255 - (amount * (255 - getBlue()))),
  60720. getAlpha());
  60721. }
  60722. const Colour Colour::darker (float amount) const throw()
  60723. {
  60724. amount = 1.0f / (1.0f + amount);
  60725. return Colour ((uint8) (amount * getRed()),
  60726. (uint8) (amount * getGreen()),
  60727. (uint8) (amount * getBlue()),
  60728. getAlpha());
  60729. }
  60730. const Colour Colour::greyLevel (const float brightness) throw()
  60731. {
  60732. const uint8 level
  60733. = (uint8) jlimit (0x00, 0xff, roundFloatToInt (brightness * 255.0f));
  60734. return Colour (level, level, level);
  60735. }
  60736. const Colour Colour::contrasting (const float amount) const throw()
  60737. {
  60738. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  60739. ? Colours::black
  60740. : Colours::white).withAlpha (amount));
  60741. }
  60742. const Colour Colour::contrasting (const Colour& colour1,
  60743. const Colour& colour2) throw()
  60744. {
  60745. const float b1 = colour1.getBrightness();
  60746. const float b2 = colour2.getBrightness();
  60747. float best = 0.0f;
  60748. float bestDist = 0.0f;
  60749. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  60750. {
  60751. const float d1 = fabsf (i - b1);
  60752. const float d2 = fabsf (i - b2);
  60753. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  60754. if (dist > bestDist)
  60755. {
  60756. best = i;
  60757. bestDist = dist;
  60758. }
  60759. }
  60760. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  60761. .withBrightness (best);
  60762. }
  60763. const String Colour::toString() const throw()
  60764. {
  60765. return String::toHexString ((int) argb.getARGB());
  60766. }
  60767. const Colour Colour::fromString (const String& encodedColourString)
  60768. {
  60769. return Colour ((uint32) encodedColourString.getHexValue32());
  60770. }
  60771. END_JUCE_NAMESPACE
  60772. /********* End of inlined file: juce_Colour.cpp *********/
  60773. /********* Start of inlined file: juce_ColourGradient.cpp *********/
  60774. BEGIN_JUCE_NAMESPACE
  60775. ColourGradient::ColourGradient() throw()
  60776. : colours (4)
  60777. {
  60778. #ifdef JUCE_DEBUG
  60779. x1 = 987654.0f;
  60780. #endif
  60781. }
  60782. ColourGradient::ColourGradient (const Colour& colour1,
  60783. const float x1_,
  60784. const float y1_,
  60785. const Colour& colour2,
  60786. const float x2_,
  60787. const float y2_,
  60788. const bool isRadial_) throw()
  60789. : x1 (x1_),
  60790. y1 (y1_),
  60791. x2 (x2_),
  60792. y2 (y2_),
  60793. isRadial (isRadial_),
  60794. colours (4)
  60795. {
  60796. colours.add (0);
  60797. colours.add (colour1.getPixelARGB().getARGB());
  60798. colours.add (1 << 16);
  60799. colours.add (colour2.getPixelARGB().getARGB());
  60800. }
  60801. ColourGradient::~ColourGradient() throw()
  60802. {
  60803. }
  60804. void ColourGradient::clearColours() throw()
  60805. {
  60806. colours.clear();
  60807. }
  60808. void ColourGradient::addColour (const double proportionAlongGradient,
  60809. const Colour& colour) throw()
  60810. {
  60811. // must be within the two end-points
  60812. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  60813. const uint32 pos = jlimit (0, 65535, roundDoubleToInt (proportionAlongGradient * 65536.0));
  60814. int i;
  60815. for (i = 0; i < colours.size(); i += 2)
  60816. if (colours.getUnchecked(i) > pos)
  60817. break;
  60818. colours.insert (i, pos);
  60819. colours.insert (i + 1, colour.getPixelARGB().getARGB());
  60820. }
  60821. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  60822. {
  60823. for (int i = 1; i < colours.size(); i += 2)
  60824. {
  60825. PixelARGB pix (colours.getUnchecked(i));
  60826. pix.multiplyAlpha (multiplier);
  60827. colours.set (i, pix.getARGB());
  60828. }
  60829. }
  60830. int ColourGradient::getNumColours() const throw()
  60831. {
  60832. return colours.size() >> 1;
  60833. }
  60834. double ColourGradient::getColourPosition (const int index) const throw()
  60835. {
  60836. return colours [index << 1];
  60837. }
  60838. const Colour ColourGradient::getColour (const int index) const throw()
  60839. {
  60840. PixelARGB pix (colours [(index << 1) + 1]);
  60841. pix.unpremultiply();
  60842. return Colour (pix.getARGB());
  60843. }
  60844. PixelARGB* ColourGradient::createLookupTable (int& numEntries) const throw()
  60845. {
  60846. #ifdef JUCE_DEBUG
  60847. // trying to use the object without setting its co-ordinates? Have a careful read of
  60848. // the comments for the constructors.
  60849. jassert (x1 != 987654.0f);
  60850. #endif
  60851. const int numColours = colours.size() >> 1;
  60852. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  60853. transform.transformPoint (tx1, ty1);
  60854. transform.transformPoint (tx2, ty2);
  60855. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  60856. numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  60857. PixelARGB* const lookupTable = (PixelARGB*) juce_calloc (numEntries * sizeof (PixelARGB));
  60858. if (numColours >= 2)
  60859. {
  60860. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  60861. PixelARGB pix1 (colours.getUnchecked (1));
  60862. int index = 0;
  60863. for (int j = 2; j < colours.size(); j += 2)
  60864. {
  60865. const int numToDo = ((colours.getUnchecked (j) * (numEntries - 1)) >> 16) - index;
  60866. const PixelARGB pix2 (colours.getUnchecked (j + 1));
  60867. for (int i = 0; i < numToDo; ++i)
  60868. {
  60869. jassert (index >= 0 && index < numEntries);
  60870. lookupTable[index] = pix1;
  60871. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  60872. ++index;
  60873. }
  60874. pix1 = pix2;
  60875. }
  60876. while (index < numEntries)
  60877. lookupTable [index++] = pix1;
  60878. }
  60879. else
  60880. {
  60881. jassertfalse // no colours specified!
  60882. }
  60883. return lookupTable;
  60884. }
  60885. bool ColourGradient::isOpaque() const throw()
  60886. {
  60887. for (int i = 1; i < colours.size(); i += 2)
  60888. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  60889. return false;
  60890. return true;
  60891. }
  60892. bool ColourGradient::isInvisible() const throw()
  60893. {
  60894. for (int i = 1; i < colours.size(); i += 2)
  60895. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  60896. return false;
  60897. return true;
  60898. }
  60899. END_JUCE_NAMESPACE
  60900. /********* End of inlined file: juce_ColourGradient.cpp *********/
  60901. /********* Start of inlined file: juce_Colours.cpp *********/
  60902. BEGIN_JUCE_NAMESPACE
  60903. const Colour Colours::transparentBlack (0);
  60904. const Colour Colours::transparentWhite (0x00ffffff);
  60905. const Colour Colours::aliceblue (0xfff0f8ff);
  60906. const Colour Colours::antiquewhite (0xfffaebd7);
  60907. const Colour Colours::aqua (0xff00ffff);
  60908. const Colour Colours::aquamarine (0xff7fffd4);
  60909. const Colour Colours::azure (0xfff0ffff);
  60910. const Colour Colours::beige (0xfff5f5dc);
  60911. const Colour Colours::bisque (0xffffe4c4);
  60912. const Colour Colours::black (0xff000000);
  60913. const Colour Colours::blanchedalmond (0xffffebcd);
  60914. const Colour Colours::blue (0xff0000ff);
  60915. const Colour Colours::blueviolet (0xff8a2be2);
  60916. const Colour Colours::brown (0xffa52a2a);
  60917. const Colour Colours::burlywood (0xffdeb887);
  60918. const Colour Colours::cadetblue (0xff5f9ea0);
  60919. const Colour Colours::chartreuse (0xff7fff00);
  60920. const Colour Colours::chocolate (0xffd2691e);
  60921. const Colour Colours::coral (0xffff7f50);
  60922. const Colour Colours::cornflowerblue (0xff6495ed);
  60923. const Colour Colours::cornsilk (0xfffff8dc);
  60924. const Colour Colours::crimson (0xffdc143c);
  60925. const Colour Colours::cyan (0xff00ffff);
  60926. const Colour Colours::darkblue (0xff00008b);
  60927. const Colour Colours::darkcyan (0xff008b8b);
  60928. const Colour Colours::darkgoldenrod (0xffb8860b);
  60929. const Colour Colours::darkgrey (0xff555555);
  60930. const Colour Colours::darkgreen (0xff006400);
  60931. const Colour Colours::darkkhaki (0xffbdb76b);
  60932. const Colour Colours::darkmagenta (0xff8b008b);
  60933. const Colour Colours::darkolivegreen (0xff556b2f);
  60934. const Colour Colours::darkorange (0xffff8c00);
  60935. const Colour Colours::darkorchid (0xff9932cc);
  60936. const Colour Colours::darkred (0xff8b0000);
  60937. const Colour Colours::darksalmon (0xffe9967a);
  60938. const Colour Colours::darkseagreen (0xff8fbc8f);
  60939. const Colour Colours::darkslateblue (0xff483d8b);
  60940. const Colour Colours::darkslategrey (0xff2f4f4f);
  60941. const Colour Colours::darkturquoise (0xff00ced1);
  60942. const Colour Colours::darkviolet (0xff9400d3);
  60943. const Colour Colours::deeppink (0xffff1493);
  60944. const Colour Colours::deepskyblue (0xff00bfff);
  60945. const Colour Colours::dimgrey (0xff696969);
  60946. const Colour Colours::dodgerblue (0xff1e90ff);
  60947. const Colour Colours::firebrick (0xffb22222);
  60948. const Colour Colours::floralwhite (0xfffffaf0);
  60949. const Colour Colours::forestgreen (0xff228b22);
  60950. const Colour Colours::fuchsia (0xffff00ff);
  60951. const Colour Colours::gainsboro (0xffdcdcdc);
  60952. const Colour Colours::gold (0xffffd700);
  60953. const Colour Colours::goldenrod (0xffdaa520);
  60954. const Colour Colours::grey (0xff808080);
  60955. const Colour Colours::green (0xff008000);
  60956. const Colour Colours::greenyellow (0xffadff2f);
  60957. const Colour Colours::honeydew (0xfff0fff0);
  60958. const Colour Colours::hotpink (0xffff69b4);
  60959. const Colour Colours::indianred (0xffcd5c5c);
  60960. const Colour Colours::indigo (0xff4b0082);
  60961. const Colour Colours::ivory (0xfffffff0);
  60962. const Colour Colours::khaki (0xfff0e68c);
  60963. const Colour Colours::lavender (0xffe6e6fa);
  60964. const Colour Colours::lavenderblush (0xfffff0f5);
  60965. const Colour Colours::lemonchiffon (0xfffffacd);
  60966. const Colour Colours::lightblue (0xffadd8e6);
  60967. const Colour Colours::lightcoral (0xfff08080);
  60968. const Colour Colours::lightcyan (0xffe0ffff);
  60969. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  60970. const Colour Colours::lightgreen (0xff90ee90);
  60971. const Colour Colours::lightgrey (0xffd3d3d3);
  60972. const Colour Colours::lightpink (0xffffb6c1);
  60973. const Colour Colours::lightsalmon (0xffffa07a);
  60974. const Colour Colours::lightseagreen (0xff20b2aa);
  60975. const Colour Colours::lightskyblue (0xff87cefa);
  60976. const Colour Colours::lightslategrey (0xff778899);
  60977. const Colour Colours::lightsteelblue (0xffb0c4de);
  60978. const Colour Colours::lightyellow (0xffffffe0);
  60979. const Colour Colours::lime (0xff00ff00);
  60980. const Colour Colours::limegreen (0xff32cd32);
  60981. const Colour Colours::linen (0xfffaf0e6);
  60982. const Colour Colours::magenta (0xffff00ff);
  60983. const Colour Colours::maroon (0xff800000);
  60984. const Colour Colours::mediumaquamarine (0xff66cdaa);
  60985. const Colour Colours::mediumblue (0xff0000cd);
  60986. const Colour Colours::mediumorchid (0xffba55d3);
  60987. const Colour Colours::mediumpurple (0xff9370db);
  60988. const Colour Colours::mediumseagreen (0xff3cb371);
  60989. const Colour Colours::mediumslateblue (0xff7b68ee);
  60990. const Colour Colours::mediumspringgreen (0xff00fa9a);
  60991. const Colour Colours::mediumturquoise (0xff48d1cc);
  60992. const Colour Colours::mediumvioletred (0xffc71585);
  60993. const Colour Colours::midnightblue (0xff191970);
  60994. const Colour Colours::mintcream (0xfff5fffa);
  60995. const Colour Colours::mistyrose (0xffffe4e1);
  60996. const Colour Colours::navajowhite (0xffffdead);
  60997. const Colour Colours::navy (0xff000080);
  60998. const Colour Colours::oldlace (0xfffdf5e6);
  60999. const Colour Colours::olive (0xff808000);
  61000. const Colour Colours::olivedrab (0xff6b8e23);
  61001. const Colour Colours::orange (0xffffa500);
  61002. const Colour Colours::orangered (0xffff4500);
  61003. const Colour Colours::orchid (0xffda70d6);
  61004. const Colour Colours::palegoldenrod (0xffeee8aa);
  61005. const Colour Colours::palegreen (0xff98fb98);
  61006. const Colour Colours::paleturquoise (0xffafeeee);
  61007. const Colour Colours::palevioletred (0xffdb7093);
  61008. const Colour Colours::papayawhip (0xffffefd5);
  61009. const Colour Colours::peachpuff (0xffffdab9);
  61010. const Colour Colours::peru (0xffcd853f);
  61011. const Colour Colours::pink (0xffffc0cb);
  61012. const Colour Colours::plum (0xffdda0dd);
  61013. const Colour Colours::powderblue (0xffb0e0e6);
  61014. const Colour Colours::purple (0xff800080);
  61015. const Colour Colours::red (0xffff0000);
  61016. const Colour Colours::rosybrown (0xffbc8f8f);
  61017. const Colour Colours::royalblue (0xff4169e1);
  61018. const Colour Colours::saddlebrown (0xff8b4513);
  61019. const Colour Colours::salmon (0xfffa8072);
  61020. const Colour Colours::sandybrown (0xfff4a460);
  61021. const Colour Colours::seagreen (0xff2e8b57);
  61022. const Colour Colours::seashell (0xfffff5ee);
  61023. const Colour Colours::sienna (0xffa0522d);
  61024. const Colour Colours::silver (0xffc0c0c0);
  61025. const Colour Colours::skyblue (0xff87ceeb);
  61026. const Colour Colours::slateblue (0xff6a5acd);
  61027. const Colour Colours::slategrey (0xff708090);
  61028. const Colour Colours::snow (0xfffffafa);
  61029. const Colour Colours::springgreen (0xff00ff7f);
  61030. const Colour Colours::steelblue (0xff4682b4);
  61031. const Colour Colours::tan (0xffd2b48c);
  61032. const Colour Colours::teal (0xff008080);
  61033. const Colour Colours::thistle (0xffd8bfd8);
  61034. const Colour Colours::tomato (0xffff6347);
  61035. const Colour Colours::turquoise (0xff40e0d0);
  61036. const Colour Colours::violet (0xffee82ee);
  61037. const Colour Colours::wheat (0xfff5deb3);
  61038. const Colour Colours::white (0xffffffff);
  61039. const Colour Colours::whitesmoke (0xfff5f5f5);
  61040. const Colour Colours::yellow (0xffffff00);
  61041. const Colour Colours::yellowgreen (0xff9acd32);
  61042. const Colour Colours::findColourForName (const String& colourName,
  61043. const Colour& defaultColour)
  61044. {
  61045. static const int presets[] =
  61046. {
  61047. // (first value is the string's hashcode, second is ARGB)
  61048. 0x05978fff, 0xff000000, /* black */
  61049. 0x06bdcc29, 0xffffffff, /* white */
  61050. 0x002e305a, 0xff0000ff, /* blue */
  61051. 0x00308adf, 0xff808080, /* grey */
  61052. 0x05e0cf03, 0xff008000, /* green */
  61053. 0x0001b891, 0xffff0000, /* red */
  61054. 0xd43c6474, 0xffffff00, /* yellow */
  61055. 0x620886da, 0xfff0f8ff, /* aliceblue */
  61056. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  61057. 0x002dcebc, 0xff00ffff, /* aqua */
  61058. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  61059. 0x0590228f, 0xfff0ffff, /* azure */
  61060. 0x05947fe4, 0xfff5f5dc, /* beige */
  61061. 0xad388e35, 0xffffe4c4, /* bisque */
  61062. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  61063. 0x39129959, 0xff8a2be2, /* blueviolet */
  61064. 0x059a8136, 0xffa52a2a, /* brown */
  61065. 0x89cea8f9, 0xffdeb887, /* burlywood */
  61066. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  61067. 0x6b748956, 0xff7fff00, /* chartreuse */
  61068. 0x2903623c, 0xffd2691e, /* chocolate */
  61069. 0x05a74431, 0xffff7f50, /* coral */
  61070. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  61071. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  61072. 0x3d8c4edf, 0xffdc143c, /* crimson */
  61073. 0x002ed323, 0xff00ffff, /* cyan */
  61074. 0x67cc74d0, 0xff00008b, /* darkblue */
  61075. 0x67cd1799, 0xff008b8b, /* darkcyan */
  61076. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  61077. 0x67cecf55, 0xff555555, /* darkgrey */
  61078. 0x920b194d, 0xff006400, /* darkgreen */
  61079. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  61080. 0x5c293873, 0xff8b008b, /* darkmagenta */
  61081. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  61082. 0xbcfd2524, 0xffff8c00, /* darkorange */
  61083. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  61084. 0x55ee0d5b, 0xff8b0000, /* darkred */
  61085. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  61086. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  61087. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  61088. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  61089. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  61090. 0xc8769375, 0xff9400d3, /* darkviolet */
  61091. 0x25832862, 0xffff1493, /* deeppink */
  61092. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  61093. 0x634c8b67, 0xff696969, /* dimgrey */
  61094. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  61095. 0xef19e3cb, 0xffb22222, /* firebrick */
  61096. 0xb852b195, 0xfffffaf0, /* floralwhite */
  61097. 0xd086fd06, 0xff228b22, /* forestgreen */
  61098. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  61099. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  61100. 0x00308060, 0xffffd700, /* gold */
  61101. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  61102. 0xbab8a537, 0xffadff2f, /* greenyellow */
  61103. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  61104. 0x41892743, 0xffff69b4, /* hotpink */
  61105. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  61106. 0xb969fed2, 0xff4b0082, /* indigo */
  61107. 0x05fef6a9, 0xfffffff0, /* ivory */
  61108. 0x06149302, 0xfff0e68c, /* khaki */
  61109. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  61110. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  61111. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  61112. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  61113. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  61114. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  61115. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  61116. 0xf40157ad, 0xff90ee90, /* lightgreen */
  61117. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  61118. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  61119. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  61120. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  61121. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  61122. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  61123. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  61124. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  61125. 0x0032afd5, 0xff00ff00, /* lime */
  61126. 0x607bbc4e, 0xff32cd32, /* limegreen */
  61127. 0x06234efa, 0xfffaf0e6, /* linen */
  61128. 0x316858a9, 0xffff00ff, /* magenta */
  61129. 0xbf8ca470, 0xff800000, /* maroon */
  61130. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  61131. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  61132. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  61133. 0x07556b71, 0xff9370db, /* mediumpurple */
  61134. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  61135. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  61136. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  61137. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  61138. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  61139. 0x168eb32a, 0xff191970, /* midnightblue */
  61140. 0x4306b960, 0xfff5fffa, /* mintcream */
  61141. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  61142. 0xe97218a6, 0xffffdead, /* navajowhite */
  61143. 0x00337bb6, 0xff000080, /* navy */
  61144. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  61145. 0x064ee1db, 0xff808000, /* olive */
  61146. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  61147. 0xc3de262e, 0xffffa500, /* orange */
  61148. 0x58bebba3, 0xffff4500, /* orangered */
  61149. 0xc3def8a3, 0xffda70d6, /* orchid */
  61150. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  61151. 0x3d9dd619, 0xff98fb98, /* palegreen */
  61152. 0x74022737, 0xffafeeee, /* paleturquoise */
  61153. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  61154. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  61155. 0x93e1b776, 0xffffdab9, /* peachpuff */
  61156. 0x003472f8, 0xffcd853f, /* peru */
  61157. 0x00348176, 0xffffc0cb, /* pink */
  61158. 0x00348d94, 0xffdda0dd, /* plum */
  61159. 0xd036be93, 0xffb0e0e6, /* powderblue */
  61160. 0xc5c507bc, 0xff800080, /* purple */
  61161. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  61162. 0xbd9413e1, 0xff4169e1, /* royalblue */
  61163. 0xf456044f, 0xff8b4513, /* saddlebrown */
  61164. 0xc9c6f66e, 0xfffa8072, /* salmon */
  61165. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  61166. 0x34636c14, 0xff2e8b57, /* seagreen */
  61167. 0x3507fb41, 0xfffff5ee, /* seashell */
  61168. 0xca348772, 0xffa0522d, /* sienna */
  61169. 0xca37d30d, 0xffc0c0c0, /* silver */
  61170. 0x80da74fb, 0xff87ceeb, /* skyblue */
  61171. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  61172. 0x44ab37f8, 0xff708090, /* slategrey */
  61173. 0x0035f183, 0xfffffafa, /* snow */
  61174. 0xd5440d16, 0xff00ff7f, /* springgreen */
  61175. 0x3e1524a5, 0xff4682b4, /* steelblue */
  61176. 0x0001bfa1, 0xffd2b48c, /* tan */
  61177. 0x0036425c, 0xff008080, /* teal */
  61178. 0xafc8858f, 0xffd8bfd8, /* thistle */
  61179. 0xcc41600a, 0xffff6347, /* tomato */
  61180. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  61181. 0xcf57947f, 0xffee82ee, /* violet */
  61182. 0x06bdbae7, 0xfff5deb3, /* wheat */
  61183. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  61184. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  61185. };
  61186. const int hash = colourName.trim().toLowerCase().hashCode();
  61187. for (int i = 0; i < numElementsInArray (presets); i += 2)
  61188. if (presets [i] == hash)
  61189. return Colour (presets [i + 1]);
  61190. return defaultColour;
  61191. }
  61192. END_JUCE_NAMESPACE
  61193. /********* End of inlined file: juce_Colours.cpp *********/
  61194. /********* Start of inlined file: juce_EdgeTable.cpp *********/
  61195. BEGIN_JUCE_NAMESPACE
  61196. EdgeTable::EdgeTable (const int top_,
  61197. const int height_,
  61198. const OversamplingLevel oversampling_,
  61199. const int expectedEdgesPerLine) throw()
  61200. : top (top_),
  61201. height (height_),
  61202. maxEdgesPerLine (expectedEdgesPerLine),
  61203. lineStrideElements ((expectedEdgesPerLine << 1) + 1),
  61204. oversampling (oversampling_)
  61205. {
  61206. table = (int*) juce_calloc ((height << (int)oversampling_)
  61207. * lineStrideElements * sizeof (int));
  61208. }
  61209. EdgeTable::EdgeTable (const EdgeTable& other) throw()
  61210. : table (0)
  61211. {
  61212. operator= (other);
  61213. }
  61214. const EdgeTable& EdgeTable::operator= (const EdgeTable& other) throw()
  61215. {
  61216. juce_free (table);
  61217. top = other.top;
  61218. height = other.height;
  61219. maxEdgesPerLine = other.maxEdgesPerLine;
  61220. lineStrideElements = other.lineStrideElements;
  61221. oversampling = other.oversampling;
  61222. const int tableSize = (height << (int)oversampling)
  61223. * lineStrideElements * sizeof (int);
  61224. table = (int*) juce_malloc (tableSize);
  61225. memcpy (table, other.table, tableSize);
  61226. return *this;
  61227. }
  61228. EdgeTable::~EdgeTable() throw()
  61229. {
  61230. juce_free (table);
  61231. }
  61232. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  61233. {
  61234. if (newNumEdgesPerLine != maxEdgesPerLine)
  61235. {
  61236. maxEdgesPerLine = newNumEdgesPerLine;
  61237. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  61238. int* const newTable = (int*) juce_malloc ((height << (int) oversampling)
  61239. * newLineStrideElements * sizeof (int));
  61240. for (int i = 0; i < (height << (int) oversampling); ++i)
  61241. {
  61242. const int* srcLine = table + lineStrideElements * i;
  61243. int* dstLine = newTable + newLineStrideElements * i;
  61244. int num = *srcLine++;
  61245. *dstLine++ = num;
  61246. num <<= 1;
  61247. while (--num >= 0)
  61248. *dstLine++ = *srcLine++;
  61249. }
  61250. juce_free (table);
  61251. table = newTable;
  61252. lineStrideElements = newLineStrideElements;
  61253. }
  61254. }
  61255. void EdgeTable::optimiseTable() throw()
  61256. {
  61257. int maxLineElements = 0;
  61258. for (int i = height; --i >= 0;)
  61259. maxLineElements = jmax (maxLineElements,
  61260. table [i * lineStrideElements]);
  61261. remapTableForNumEdges (maxLineElements);
  61262. }
  61263. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  61264. {
  61265. jassert (y >= 0 && y < (height << oversampling))
  61266. int* lineStart = table + lineStrideElements * y;
  61267. int n = lineStart[0];
  61268. if (n >= maxEdgesPerLine)
  61269. {
  61270. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  61271. jassert (n < maxEdgesPerLine);
  61272. lineStart = table + lineStrideElements * y;
  61273. }
  61274. n <<= 1;
  61275. int* const line = lineStart + 1;
  61276. while (n > 0)
  61277. {
  61278. const int cx = line [n - 2];
  61279. if (cx <= x)
  61280. break;
  61281. line [n] = cx;
  61282. line [n + 1] = line [n - 1];
  61283. n -= 2;
  61284. }
  61285. line [n] = x;
  61286. line [n + 1] = winding;
  61287. lineStart[0]++;
  61288. }
  61289. void EdgeTable::addPath (const Path& path,
  61290. const AffineTransform& transform) throw()
  61291. {
  61292. const int windingAmount = 256 / (1 << (int) oversampling);
  61293. const float timesOversampling = (float) (1 << (int) oversampling);
  61294. const int bottomLimit = (height << (int) oversampling);
  61295. PathFlatteningIterator iter (path, transform);
  61296. while (iter.next())
  61297. {
  61298. int y1 = roundFloatToInt (iter.y1 * timesOversampling) - (top << (int) oversampling);
  61299. int y2 = roundFloatToInt (iter.y2 * timesOversampling) - (top << (int) oversampling);
  61300. if (y1 != y2)
  61301. {
  61302. const double x1 = 256.0 * iter.x1;
  61303. const double x2 = 256.0 * iter.x2;
  61304. const double multiplier = (x2 - x1) / (y2 - y1);
  61305. const int oldY1 = y1;
  61306. int winding;
  61307. if (y1 > y2)
  61308. {
  61309. swapVariables (y1, y2);
  61310. winding = windingAmount;
  61311. }
  61312. else
  61313. {
  61314. winding = -windingAmount;
  61315. }
  61316. jassert (y1 < y2);
  61317. if (y1 < 0)
  61318. y1 = 0;
  61319. if (y2 > bottomLimit)
  61320. y2 = bottomLimit;
  61321. while (y1 < y2)
  61322. {
  61323. addEdgePoint (roundDoubleToInt (x1 + multiplier * (y1 - oldY1)),
  61324. y1,
  61325. winding);
  61326. ++y1;
  61327. }
  61328. }
  61329. }
  61330. if (! path.isUsingNonZeroWinding())
  61331. {
  61332. // if it's an alternate-winding path, we need to go through and
  61333. // make sure all the windings are alternating.
  61334. int* lineStart = table;
  61335. for (int i = height << (int) oversampling; --i >= 0;)
  61336. {
  61337. int* line = lineStart;
  61338. lineStart += lineStrideElements;
  61339. int num = *line;
  61340. while (--num >= 0)
  61341. {
  61342. line += 2;
  61343. *line = abs (*line);
  61344. if (--num >= 0)
  61345. {
  61346. line += 2;
  61347. *line = -abs (*line);
  61348. }
  61349. }
  61350. }
  61351. }
  61352. }
  61353. END_JUCE_NAMESPACE
  61354. /********* End of inlined file: juce_EdgeTable.cpp *********/
  61355. /********* Start of inlined file: juce_Graphics.cpp *********/
  61356. BEGIN_JUCE_NAMESPACE
  61357. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  61358. #define MINIMUM_COORD -0x3fffffff
  61359. #define MAXIMUM_COORD 0x3fffffff
  61360. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  61361. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  61362. jassert ((int) x >= MINIMUM_COORD \
  61363. && (int) x <= MAXIMUM_COORD \
  61364. && (int) y >= MINIMUM_COORD \
  61365. && (int) y <= MAXIMUM_COORD \
  61366. && (int) w >= MINIMUM_COORD \
  61367. && (int) w <= MAXIMUM_COORD \
  61368. && (int) h >= MINIMUM_COORD \
  61369. && (int) h <= MAXIMUM_COORD);
  61370. LowLevelGraphicsContext::LowLevelGraphicsContext()
  61371. {
  61372. }
  61373. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  61374. {
  61375. }
  61376. Graphics::Graphics (Image& imageToDrawOnto) throw()
  61377. : context (imageToDrawOnto.createLowLevelContext()),
  61378. ownsContext (true),
  61379. state (new GraphicsState()),
  61380. saveStatePending (false)
  61381. {
  61382. }
  61383. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  61384. : context (internalContext),
  61385. ownsContext (false),
  61386. state (new GraphicsState()),
  61387. saveStatePending (false)
  61388. {
  61389. }
  61390. Graphics::~Graphics() throw()
  61391. {
  61392. delete state;
  61393. if (ownsContext)
  61394. delete context;
  61395. }
  61396. void Graphics::resetToDefaultState() throw()
  61397. {
  61398. setColour (Colours::black);
  61399. state->font.resetToDefaultState();
  61400. state->quality = defaultQuality;
  61401. }
  61402. bool Graphics::isVectorDevice() const throw()
  61403. {
  61404. return context->isVectorDevice();
  61405. }
  61406. bool Graphics::reduceClipRegion (const int x, const int y,
  61407. const int w, const int h) throw()
  61408. {
  61409. saveStateIfPending();
  61410. return context->reduceClipRegion (x, y, w, h);
  61411. }
  61412. bool Graphics::reduceClipRegion (const RectangleList& clipRegion) throw()
  61413. {
  61414. saveStateIfPending();
  61415. return context->reduceClipRegion (clipRegion);
  61416. }
  61417. void Graphics::excludeClipRegion (const int x, const int y,
  61418. const int w, const int h) throw()
  61419. {
  61420. saveStateIfPending();
  61421. context->excludeClipRegion (x, y, w, h);
  61422. }
  61423. bool Graphics::isClipEmpty() const throw()
  61424. {
  61425. return context->isClipEmpty();
  61426. }
  61427. const Rectangle Graphics::getClipBounds() const throw()
  61428. {
  61429. return context->getClipBounds();
  61430. }
  61431. void Graphics::saveState() throw()
  61432. {
  61433. saveStateIfPending();
  61434. saveStatePending = true;
  61435. }
  61436. void Graphics::restoreState() throw()
  61437. {
  61438. if (saveStatePending)
  61439. {
  61440. saveStatePending = false;
  61441. }
  61442. else
  61443. {
  61444. const int stackSize = stateStack.size();
  61445. if (stackSize > 0)
  61446. {
  61447. context->restoreState();
  61448. delete state;
  61449. state = stateStack.getUnchecked (stackSize - 1);
  61450. stateStack.removeLast (1, false);
  61451. }
  61452. else
  61453. {
  61454. // Trying to call restoreState() more times than you've called saveState() !
  61455. // Be careful to correctly match each saveState() with exactly one call to restoreState().
  61456. jassertfalse
  61457. }
  61458. }
  61459. }
  61460. void Graphics::saveStateIfPending() throw()
  61461. {
  61462. if (saveStatePending)
  61463. {
  61464. saveStatePending = false;
  61465. context->saveState();
  61466. stateStack.add (new GraphicsState (*state));
  61467. }
  61468. }
  61469. void Graphics::setOrigin (const int newOriginX,
  61470. const int newOriginY) throw()
  61471. {
  61472. saveStateIfPending();
  61473. context->setOrigin (newOriginX, newOriginY);
  61474. }
  61475. bool Graphics::clipRegionIntersects (const int x, const int y,
  61476. const int w, const int h) const throw()
  61477. {
  61478. return context->clipRegionIntersects (x, y, w, h);
  61479. }
  61480. void Graphics::setColour (const Colour& newColour) throw()
  61481. {
  61482. saveStateIfPending();
  61483. state->colour = newColour;
  61484. deleteAndZero (state->brush);
  61485. }
  61486. const Colour& Graphics::getCurrentColour() const throw()
  61487. {
  61488. return state->colour;
  61489. }
  61490. void Graphics::setOpacity (const float newOpacity) throw()
  61491. {
  61492. saveStateIfPending();
  61493. state->colour = state->colour.withAlpha (newOpacity);
  61494. }
  61495. void Graphics::setBrush (const Brush* const newBrush) throw()
  61496. {
  61497. saveStateIfPending();
  61498. delete state->brush;
  61499. if (newBrush != 0)
  61500. state->brush = newBrush->createCopy();
  61501. else
  61502. state->brush = 0;
  61503. }
  61504. Graphics::GraphicsState::GraphicsState() throw()
  61505. : colour (Colours::black),
  61506. brush (0),
  61507. quality (defaultQuality)
  61508. {
  61509. }
  61510. Graphics::GraphicsState::GraphicsState (const GraphicsState& other) throw()
  61511. : colour (other.colour),
  61512. brush (other.brush != 0 ? other.brush->createCopy() : 0),
  61513. font (other.font),
  61514. quality (other.quality)
  61515. {
  61516. }
  61517. Graphics::GraphicsState::~GraphicsState() throw()
  61518. {
  61519. delete brush;
  61520. }
  61521. void Graphics::setFont (const Font& newFont) throw()
  61522. {
  61523. saveStateIfPending();
  61524. state->font = newFont;
  61525. }
  61526. void Graphics::setFont (const float newFontHeight,
  61527. const int newFontStyleFlags) throw()
  61528. {
  61529. saveStateIfPending();
  61530. state->font.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0.0f);
  61531. }
  61532. const Font& Graphics::getCurrentFont() const throw()
  61533. {
  61534. return state->font;
  61535. }
  61536. void Graphics::drawSingleLineText (const String& text,
  61537. const int startX,
  61538. const int baselineY) const throw()
  61539. {
  61540. if (text.isNotEmpty()
  61541. && startX < context->getClipBounds().getRight())
  61542. {
  61543. GlyphArrangement arr;
  61544. arr.addLineOfText (state->font, text, (float) startX, (float) baselineY);
  61545. arr.draw (*this);
  61546. }
  61547. }
  61548. void Graphics::drawTextAsPath (const String& text,
  61549. const AffineTransform& transform) const throw()
  61550. {
  61551. if (text.isNotEmpty())
  61552. {
  61553. GlyphArrangement arr;
  61554. arr.addLineOfText (state->font, text, 0.0f, 0.0f);
  61555. arr.draw (*this, transform);
  61556. }
  61557. }
  61558. void Graphics::drawMultiLineText (const String& text,
  61559. const int startX,
  61560. const int baselineY,
  61561. const int maximumLineWidth) const throw()
  61562. {
  61563. if (text.isNotEmpty()
  61564. && startX < context->getClipBounds().getRight())
  61565. {
  61566. GlyphArrangement arr;
  61567. arr.addJustifiedText (state->font, text,
  61568. (float) startX, (float) baselineY, (float) maximumLineWidth,
  61569. Justification::left);
  61570. arr.draw (*this);
  61571. }
  61572. }
  61573. void Graphics::drawText (const String& text,
  61574. const int x,
  61575. const int y,
  61576. const int width,
  61577. const int height,
  61578. const Justification& justificationType,
  61579. const bool useEllipsesIfTooBig) const throw()
  61580. {
  61581. if (text.isNotEmpty() && context->clipRegionIntersects (x, y, width, height))
  61582. {
  61583. GlyphArrangement arr;
  61584. arr.addCurtailedLineOfText (state->font, text,
  61585. 0.0f, 0.0f, (float)width,
  61586. useEllipsesIfTooBig);
  61587. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  61588. (float) x, (float) y,
  61589. (float) width, (float) height,
  61590. justificationType);
  61591. arr.draw (*this);
  61592. }
  61593. }
  61594. void Graphics::drawFittedText (const String& text,
  61595. const int x,
  61596. const int y,
  61597. const int width,
  61598. const int height,
  61599. const Justification& justification,
  61600. const int maximumNumberOfLines,
  61601. const float minimumHorizontalScale) const throw()
  61602. {
  61603. if (text.isNotEmpty()
  61604. && width > 0 && height > 0
  61605. && context->clipRegionIntersects (x, y, width, height))
  61606. {
  61607. GlyphArrangement arr;
  61608. arr.addFittedText (state->font, text,
  61609. (float) x, (float) y,
  61610. (float) width, (float) height,
  61611. justification,
  61612. maximumNumberOfLines,
  61613. minimumHorizontalScale);
  61614. arr.draw (*this);
  61615. }
  61616. }
  61617. void Graphics::fillRect (int x,
  61618. int y,
  61619. int width,
  61620. int height) const throw()
  61621. {
  61622. // passing in a silly number can cause maths problems in rendering!
  61623. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61624. SolidColourBrush colourBrush (state->colour);
  61625. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, width, height);
  61626. }
  61627. void Graphics::fillRect (const Rectangle& r) const throw()
  61628. {
  61629. fillRect (r.getX(),
  61630. r.getY(),
  61631. r.getWidth(),
  61632. r.getHeight());
  61633. }
  61634. void Graphics::fillRect (const float x,
  61635. const float y,
  61636. const float width,
  61637. const float height) const throw()
  61638. {
  61639. // passing in a silly number can cause maths problems in rendering!
  61640. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61641. Path p;
  61642. p.addRectangle (x, y, width, height);
  61643. fillPath (p);
  61644. }
  61645. void Graphics::setPixel (int x, int y) const throw()
  61646. {
  61647. if (context->clipRegionIntersects (x, y, 1, 1))
  61648. {
  61649. SolidColourBrush colourBrush (state->colour);
  61650. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, 1, 1);
  61651. }
  61652. }
  61653. void Graphics::fillAll() const throw()
  61654. {
  61655. fillRect (context->getClipBounds());
  61656. }
  61657. void Graphics::fillAll (const Colour& colourToUse) const throw()
  61658. {
  61659. if (! colourToUse.isTransparent())
  61660. {
  61661. const Rectangle clip (context->getClipBounds());
  61662. context->fillRectWithColour (clip.getX(), clip.getY(), clip.getWidth(), clip.getHeight(),
  61663. colourToUse, false);
  61664. }
  61665. }
  61666. void Graphics::fillPath (const Path& path,
  61667. const AffineTransform& transform) const throw()
  61668. {
  61669. if ((! context->isClipEmpty()) && ! path.isEmpty())
  61670. {
  61671. SolidColourBrush colourBrush (state->colour);
  61672. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintPath (*context, path, transform);
  61673. }
  61674. }
  61675. void Graphics::strokePath (const Path& path,
  61676. const PathStrokeType& strokeType,
  61677. const AffineTransform& transform) const throw()
  61678. {
  61679. if ((! state->colour.isTransparent()) || state->brush != 0)
  61680. {
  61681. Path stroke;
  61682. strokeType.createStrokedPath (stroke, path, transform);
  61683. fillPath (stroke);
  61684. }
  61685. }
  61686. void Graphics::drawRect (const int x,
  61687. const int y,
  61688. const int width,
  61689. const int height,
  61690. const int lineThickness) const throw()
  61691. {
  61692. // passing in a silly number can cause maths problems in rendering!
  61693. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61694. SolidColourBrush colourBrush (state->colour);
  61695. Brush& b = (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush);
  61696. b.paintRectangle (*context, x, y, width, lineThickness);
  61697. b.paintRectangle (*context, x, y + lineThickness, lineThickness, height - lineThickness * 2);
  61698. b.paintRectangle (*context, x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2);
  61699. b.paintRectangle (*context, x, y + height - lineThickness, width, lineThickness);
  61700. }
  61701. void Graphics::drawRect (const float x,
  61702. const float y,
  61703. const float width,
  61704. const float height,
  61705. const float lineThickness) const throw()
  61706. {
  61707. // passing in a silly number can cause maths problems in rendering!
  61708. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61709. Path p;
  61710. p.addRectangle (x, y, width, lineThickness);
  61711. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  61712. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  61713. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  61714. fillPath (p);
  61715. }
  61716. void Graphics::drawRect (const Rectangle& r,
  61717. const int lineThickness) const throw()
  61718. {
  61719. drawRect (r.getX(), r.getY(),
  61720. r.getWidth(), r.getHeight(),
  61721. lineThickness);
  61722. }
  61723. void Graphics::drawBevel (const int x,
  61724. const int y,
  61725. const int width,
  61726. const int height,
  61727. const int bevelThickness,
  61728. const Colour& topLeftColour,
  61729. const Colour& bottomRightColour,
  61730. const bool useGradient,
  61731. const bool sharpEdgeOnOutside) const throw()
  61732. {
  61733. // passing in a silly number can cause maths problems in rendering!
  61734. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61735. if (clipRegionIntersects (x, y, width, height))
  61736. {
  61737. const float oldOpacity = state->colour.getFloatAlpha();
  61738. const float ramp = oldOpacity / bevelThickness;
  61739. for (int i = bevelThickness; --i >= 0;)
  61740. {
  61741. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  61742. : oldOpacity;
  61743. context->fillRectWithColour (x + i, y + i, width - i * 2, 1, topLeftColour.withMultipliedAlpha (op), false);
  61744. context->fillRectWithColour (x + i, y + i + 1, 1, height - i * 2 - 2, topLeftColour.withMultipliedAlpha (op * 0.75f), false);
  61745. context->fillRectWithColour (x + i, y + height - i - 1, width - i * 2, 1, bottomRightColour.withMultipliedAlpha (op), false);
  61746. context->fillRectWithColour (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2, bottomRightColour.withMultipliedAlpha (op * 0.75f), false);
  61747. }
  61748. }
  61749. }
  61750. void Graphics::fillEllipse (const float x,
  61751. const float y,
  61752. const float width,
  61753. const float height) const throw()
  61754. {
  61755. // passing in a silly number can cause maths problems in rendering!
  61756. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61757. Path p;
  61758. p.addEllipse (x, y, width, height);
  61759. fillPath (p);
  61760. }
  61761. void Graphics::drawEllipse (const float x,
  61762. const float y,
  61763. const float width,
  61764. const float height,
  61765. const float lineThickness) const throw()
  61766. {
  61767. // passing in a silly number can cause maths problems in rendering!
  61768. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61769. Path p;
  61770. p.addEllipse (x, y, width, height);
  61771. strokePath (p, PathStrokeType (lineThickness));
  61772. }
  61773. void Graphics::fillRoundedRectangle (const float x,
  61774. const float y,
  61775. const float width,
  61776. const float height,
  61777. const float cornerSize) const throw()
  61778. {
  61779. // passing in a silly number can cause maths problems in rendering!
  61780. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61781. Path p;
  61782. p.addRoundedRectangle (x, y, width, height, cornerSize);
  61783. fillPath (p);
  61784. }
  61785. void Graphics::fillRoundedRectangle (const Rectangle& r,
  61786. const float cornerSize) const throw()
  61787. {
  61788. fillRoundedRectangle ((float) r.getX(),
  61789. (float) r.getY(),
  61790. (float) r.getWidth(),
  61791. (float) r.getHeight(),
  61792. cornerSize);
  61793. }
  61794. void Graphics::drawRoundedRectangle (const float x,
  61795. const float y,
  61796. const float width,
  61797. const float height,
  61798. const float cornerSize,
  61799. const float lineThickness) const throw()
  61800. {
  61801. // passing in a silly number can cause maths problems in rendering!
  61802. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61803. Path p;
  61804. p.addRoundedRectangle (x, y, width, height, cornerSize);
  61805. strokePath (p, PathStrokeType (lineThickness));
  61806. }
  61807. void Graphics::drawRoundedRectangle (const Rectangle& r,
  61808. const float cornerSize,
  61809. const float lineThickness) const throw()
  61810. {
  61811. drawRoundedRectangle ((float) r.getX(),
  61812. (float) r.getY(),
  61813. (float) r.getWidth(),
  61814. (float) r.getHeight(),
  61815. cornerSize, lineThickness);
  61816. }
  61817. void Graphics::drawArrow (const float startX,
  61818. const float startY,
  61819. const float endX,
  61820. const float endY,
  61821. const float lineThickness,
  61822. const float arrowheadWidth,
  61823. const float arrowheadLength) const throw()
  61824. {
  61825. Path p;
  61826. p.addArrow (startX, startY, endX, endY,
  61827. lineThickness, arrowheadWidth, arrowheadLength);
  61828. fillPath (p);
  61829. }
  61830. void Graphics::fillCheckerBoard (int x, int y,
  61831. int width, int height,
  61832. const int checkWidth,
  61833. const int checkHeight,
  61834. const Colour& colour1,
  61835. const Colour& colour2) const throw()
  61836. {
  61837. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  61838. if (checkWidth > 0 && checkHeight > 0)
  61839. {
  61840. if (colour1 == colour2)
  61841. {
  61842. context->fillRectWithColour (x, y, width, height, colour1, false);
  61843. }
  61844. else
  61845. {
  61846. const Rectangle clip (context->getClipBounds());
  61847. const int right = jmin (x + width, clip.getRight());
  61848. const int bottom = jmin (y + height, clip.getBottom());
  61849. int cy = 0;
  61850. while (y < bottom)
  61851. {
  61852. int cx = cy;
  61853. for (int xx = x; xx < right; xx += checkWidth)
  61854. context->fillRectWithColour (xx, y,
  61855. jmin (checkWidth, right - xx),
  61856. jmin (checkHeight, bottom - y),
  61857. ((cx++ & 1) == 0) ? colour1 : colour2,
  61858. false);
  61859. ++cy;
  61860. y += checkHeight;
  61861. }
  61862. }
  61863. }
  61864. }
  61865. void Graphics::drawVerticalLine (const int x, float top, float bottom) const throw()
  61866. {
  61867. SolidColourBrush colourBrush (state->colour);
  61868. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintVerticalLine (*context, x, top, bottom);
  61869. }
  61870. void Graphics::drawHorizontalLine (const int y, float left, float right) const throw()
  61871. {
  61872. SolidColourBrush colourBrush (state->colour);
  61873. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintHorizontalLine (*context, y, left, right);
  61874. }
  61875. void Graphics::drawLine (float x1, float y1,
  61876. float x2, float y2) const throw()
  61877. {
  61878. if (! context->isClipEmpty())
  61879. {
  61880. SolidColourBrush colourBrush (state->colour);
  61881. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintLine (*context, x1, y1, x2, y2);
  61882. }
  61883. }
  61884. void Graphics::drawLine (const float startX,
  61885. const float startY,
  61886. const float endX,
  61887. const float endY,
  61888. const float lineThickness) const throw()
  61889. {
  61890. Path p;
  61891. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  61892. fillPath (p);
  61893. }
  61894. void Graphics::drawLine (const Line& line) const throw()
  61895. {
  61896. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  61897. }
  61898. void Graphics::drawLine (const Line& line,
  61899. const float lineThickness) const throw()
  61900. {
  61901. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  61902. }
  61903. void Graphics::drawDashedLine (const float startX,
  61904. const float startY,
  61905. const float endX,
  61906. const float endY,
  61907. const float* const dashLengths,
  61908. const int numDashLengths,
  61909. const float lineThickness) const throw()
  61910. {
  61911. const double dx = endX - startX;
  61912. const double dy = endY - startY;
  61913. const double totalLen = juce_hypot (dx, dy);
  61914. if (totalLen >= 0.5)
  61915. {
  61916. const double onePixAlpha = 1.0 / totalLen;
  61917. double alpha = 0.0;
  61918. float x = startX;
  61919. float y = startY;
  61920. int n = 0;
  61921. while (alpha < 1.0f)
  61922. {
  61923. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  61924. n = n % numDashLengths;
  61925. const float oldX = x;
  61926. const float oldY = y;
  61927. x = (float) (startX + dx * alpha);
  61928. y = (float) (startY + dy * alpha);
  61929. if ((n & 1) != 0)
  61930. {
  61931. if (lineThickness != 1.0f)
  61932. drawLine (oldX, oldY, x, y, lineThickness);
  61933. else
  61934. drawLine (oldX, oldY, x, y);
  61935. }
  61936. }
  61937. }
  61938. }
  61939. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality) throw()
  61940. {
  61941. saveStateIfPending();
  61942. state->quality = newQuality;
  61943. }
  61944. void Graphics::drawImageAt (const Image* const imageToDraw,
  61945. const int topLeftX,
  61946. const int topLeftY,
  61947. const bool fillAlphaChannelWithCurrentBrush) const throw()
  61948. {
  61949. if (imageToDraw != 0)
  61950. {
  61951. const int imageW = imageToDraw->getWidth();
  61952. const int imageH = imageToDraw->getHeight();
  61953. drawImage (imageToDraw,
  61954. topLeftX, topLeftY, imageW, imageH,
  61955. 0, 0, imageW, imageH,
  61956. fillAlphaChannelWithCurrentBrush);
  61957. }
  61958. }
  61959. void Graphics::drawImageWithin (const Image* const imageToDraw,
  61960. const int destX,
  61961. const int destY,
  61962. const int destW,
  61963. const int destH,
  61964. const RectanglePlacement& placementWithinTarget,
  61965. const bool fillAlphaChannelWithCurrentBrush) const throw()
  61966. {
  61967. // passing in a silly number can cause maths problems in rendering!
  61968. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (destX, destY, destW, destH);
  61969. if (imageToDraw != 0)
  61970. {
  61971. const int imageW = imageToDraw->getWidth();
  61972. const int imageH = imageToDraw->getHeight();
  61973. if (imageW > 0 && imageH > 0)
  61974. {
  61975. double newX = 0.0, newY = 0.0;
  61976. double newW = imageW;
  61977. double newH = imageH;
  61978. placementWithinTarget.applyTo (newX, newY, newW, newH,
  61979. destX, destY, destW, destH);
  61980. if (newW > 0 && newH > 0)
  61981. {
  61982. drawImage (imageToDraw,
  61983. roundDoubleToInt (newX), roundDoubleToInt (newY),
  61984. roundDoubleToInt (newW), roundDoubleToInt (newH),
  61985. 0, 0, imageW, imageH,
  61986. fillAlphaChannelWithCurrentBrush);
  61987. }
  61988. }
  61989. }
  61990. }
  61991. void Graphics::drawImage (const Image* const imageToDraw,
  61992. int dx, int dy, int dw, int dh,
  61993. int sx, int sy, int sw, int sh,
  61994. const bool fillAlphaChannelWithCurrentBrush) const throw()
  61995. {
  61996. // passing in a silly number can cause maths problems in rendering!
  61997. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (dx, dy, dw, dh);
  61998. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (sx, sy, sw, sh);
  61999. if (imageToDraw == 0 || ! context->clipRegionIntersects (dx, dy, dw, dh))
  62000. return;
  62001. if (sw == dw && sh == dh)
  62002. {
  62003. if (sx < 0)
  62004. {
  62005. dx -= sx;
  62006. dw += sx;
  62007. sw += sx;
  62008. sx = 0;
  62009. }
  62010. if (sx + sw > imageToDraw->getWidth())
  62011. {
  62012. const int amount = sx + sw - imageToDraw->getWidth();
  62013. dw -= amount;
  62014. sw -= amount;
  62015. }
  62016. if (sy < 0)
  62017. {
  62018. dy -= sy;
  62019. dh += sy;
  62020. sh += sy;
  62021. sy = 0;
  62022. }
  62023. if (sy + sh > imageToDraw->getHeight())
  62024. {
  62025. const int amount = sy + sh - imageToDraw->getHeight();
  62026. dh -= amount;
  62027. sh -= amount;
  62028. }
  62029. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  62030. return;
  62031. if (fillAlphaChannelWithCurrentBrush)
  62032. {
  62033. SolidColourBrush colourBrush (state->colour);
  62034. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  62035. .paintAlphaChannel (*context, *imageToDraw,
  62036. dx - sx, dy - sy,
  62037. dx, dy,
  62038. dw, dh);
  62039. }
  62040. else
  62041. {
  62042. context->blendImage (*imageToDraw,
  62043. dx, dy, dw, dh, sx, sy,
  62044. state->colour.getFloatAlpha());
  62045. }
  62046. }
  62047. else
  62048. {
  62049. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  62050. return;
  62051. if (fillAlphaChannelWithCurrentBrush)
  62052. {
  62053. if (imageToDraw->isRGB())
  62054. {
  62055. fillRect (dx, dy, dw, dh);
  62056. }
  62057. else
  62058. {
  62059. int tx = dx;
  62060. int ty = dy;
  62061. int tw = dw;
  62062. int th = dh;
  62063. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  62064. {
  62065. Image temp (imageToDraw->getFormat(), tw, th, true);
  62066. Graphics g (temp);
  62067. g.setImageResamplingQuality (state->quality);
  62068. g.setOrigin (dx - tx, dy - ty);
  62069. g.drawImage (imageToDraw,
  62070. 0, 0, dw, dh,
  62071. sx, sy, sw, sh,
  62072. false);
  62073. SolidColourBrush colourBrush (state->colour);
  62074. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  62075. .paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  62076. }
  62077. }
  62078. }
  62079. else
  62080. {
  62081. context->blendImageRescaling (*imageToDraw,
  62082. dx, dy, dw, dh,
  62083. sx, sy, sw, sh,
  62084. state->colour.getFloatAlpha(),
  62085. state->quality);
  62086. }
  62087. }
  62088. }
  62089. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  62090. int sourceClipX,
  62091. int sourceClipY,
  62092. int sourceClipWidth,
  62093. int sourceClipHeight,
  62094. const AffineTransform& transform,
  62095. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62096. {
  62097. if (imageToDraw != 0
  62098. && (! context->isClipEmpty())
  62099. && ! transform.isSingularity())
  62100. {
  62101. if (transform.isIdentity())
  62102. {
  62103. drawImage (imageToDraw,
  62104. sourceClipX, sourceClipY, sourceClipWidth, sourceClipHeight,
  62105. sourceClipX, sourceClipY, sourceClipWidth, sourceClipHeight,
  62106. fillAlphaChannelWithCurrentBrush);
  62107. }
  62108. else if (fillAlphaChannelWithCurrentBrush)
  62109. {
  62110. Path p;
  62111. p.addRectangle ((float) sourceClipX, (float) sourceClipY,
  62112. (float) sourceClipWidth, (float) sourceClipHeight);
  62113. p.applyTransform (transform);
  62114. float dx, dy, dw, dh;
  62115. p.getBounds (dx, dy, dw, dh);
  62116. int tx = (int) dx;
  62117. int ty = (int) dy;
  62118. int tw = roundFloatToInt (dw) + 2;
  62119. int th = roundFloatToInt (dh) + 2;
  62120. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  62121. {
  62122. Image temp (imageToDraw->getFormat(), tw, th, true);
  62123. Graphics g (temp);
  62124. g.setImageResamplingQuality (state->quality);
  62125. g.drawImageTransformed (imageToDraw,
  62126. sourceClipX,
  62127. sourceClipY,
  62128. sourceClipWidth,
  62129. sourceClipHeight,
  62130. transform.translated ((float) -tx, (float) -ty),
  62131. false);
  62132. SolidColourBrush colourBrush (state->colour);
  62133. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  62134. }
  62135. }
  62136. else
  62137. {
  62138. context->blendImageWarping (*imageToDraw,
  62139. sourceClipX,
  62140. sourceClipY,
  62141. sourceClipWidth,
  62142. sourceClipHeight,
  62143. transform,
  62144. state->colour.getFloatAlpha(),
  62145. state->quality);
  62146. }
  62147. }
  62148. }
  62149. END_JUCE_NAMESPACE
  62150. /********* End of inlined file: juce_Graphics.cpp *********/
  62151. /********* Start of inlined file: juce_Justification.cpp *********/
  62152. BEGIN_JUCE_NAMESPACE
  62153. Justification::Justification (const Justification& other) throw()
  62154. : flags (other.flags)
  62155. {
  62156. }
  62157. const Justification& Justification::operator= (const Justification& other) throw()
  62158. {
  62159. flags = other.flags;
  62160. return *this;
  62161. }
  62162. int Justification::getOnlyVerticalFlags() const throw()
  62163. {
  62164. return flags & (top | bottom | verticallyCentred);
  62165. }
  62166. int Justification::getOnlyHorizontalFlags() const throw()
  62167. {
  62168. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  62169. }
  62170. void Justification::applyToRectangle (int& x, int& y,
  62171. const int w, const int h,
  62172. const int spaceX, const int spaceY,
  62173. const int spaceW, const int spaceH) const throw()
  62174. {
  62175. if ((flags & horizontallyCentred) != 0)
  62176. {
  62177. x = spaceX + ((spaceW - w) >> 1);
  62178. }
  62179. else if ((flags & right) != 0)
  62180. {
  62181. x = spaceX + spaceW - w;
  62182. }
  62183. else
  62184. {
  62185. x = spaceX;
  62186. }
  62187. if ((flags & verticallyCentred) != 0)
  62188. {
  62189. y = spaceY + ((spaceH - h) >> 1);
  62190. }
  62191. else if ((flags & bottom) != 0)
  62192. {
  62193. y = spaceY + spaceH - h;
  62194. }
  62195. else
  62196. {
  62197. y = spaceY;
  62198. }
  62199. }
  62200. END_JUCE_NAMESPACE
  62201. /********* End of inlined file: juce_Justification.cpp *********/
  62202. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  62203. BEGIN_JUCE_NAMESPACE
  62204. #if JUCE_MSVC
  62205. #pragma warning (disable: 4996) // deprecated sprintf warning
  62206. #endif
  62207. // this will throw an assertion if you try to draw something that's not
  62208. // possible in postscript
  62209. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  62210. #if defined (JUCE_DEBUG) && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  62211. #define notPossibleInPostscriptAssert jassertfalse
  62212. #else
  62213. #define notPossibleInPostscriptAssert
  62214. #endif
  62215. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  62216. const String& documentTitle,
  62217. const int totalWidth_,
  62218. const int totalHeight_)
  62219. : out (resultingPostScript),
  62220. totalWidth (totalWidth_),
  62221. totalHeight (totalHeight_),
  62222. xOffset (0),
  62223. yOffset (0),
  62224. needToClip (true)
  62225. {
  62226. clip = new RectangleList (Rectangle (0, 0, totalWidth_, totalHeight_));
  62227. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  62228. out << "%!PS-Adobe-3.0 EPSF-3.0"
  62229. "\n%%BoundingBox: 0 0 600 824"
  62230. "\n%%Pages: 0"
  62231. "\n%%Creator: Raw Material Software JUCE"
  62232. "\n%%Title: " << documentTitle <<
  62233. "\n%%CreationDate: none"
  62234. "\n%%LanguageLevel: 2"
  62235. "\n%%EndComments"
  62236. "\n%%BeginProlog"
  62237. "\n%%BeginResource: JRes"
  62238. "\n/bd {bind def} bind def"
  62239. "\n/c {setrgbcolor} bd"
  62240. "\n/m {moveto} bd"
  62241. "\n/l {lineto} bd"
  62242. "\n/rl {rlineto} bd"
  62243. "\n/ct {curveto} bd"
  62244. "\n/cp {closepath} bd"
  62245. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  62246. "\n/doclip {initclip newpath} bd"
  62247. "\n/endclip {clip newpath} bd"
  62248. "\n%%EndResource"
  62249. "\n%%EndProlog"
  62250. "\n%%BeginSetup"
  62251. "\n%%EndSetup"
  62252. "\n%%Page: 1 1"
  62253. "\n%%BeginPageSetup"
  62254. "\n%%EndPageSetup\n\n"
  62255. << "40 800 translate\n"
  62256. << scale << ' ' << scale << " scale\n\n";
  62257. }
  62258. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  62259. {
  62260. delete clip;
  62261. }
  62262. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  62263. {
  62264. return true;
  62265. }
  62266. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  62267. {
  62268. if (x != 0 || y != 0)
  62269. {
  62270. xOffset += x;
  62271. yOffset += y;
  62272. needToClip = true;
  62273. }
  62274. }
  62275. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (int x, int y, int w, int h)
  62276. {
  62277. needToClip = true;
  62278. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  62279. }
  62280. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (const RectangleList& clipRegion)
  62281. {
  62282. needToClip = true;
  62283. return clip->clipTo (clipRegion);
  62284. }
  62285. void LowLevelGraphicsPostScriptRenderer::excludeClipRegion (int x, int y, int w, int h)
  62286. {
  62287. needToClip = true;
  62288. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  62289. }
  62290. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (int x, int y, int w, int h)
  62291. {
  62292. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  62293. }
  62294. const Rectangle LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  62295. {
  62296. return clip->getBounds().translated (-xOffset, -yOffset);
  62297. }
  62298. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  62299. {
  62300. return clip->isEmpty();
  62301. }
  62302. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState (RectangleList* const clip_,
  62303. const int xOffset_, const int yOffset_)
  62304. : clip (clip_),
  62305. xOffset (xOffset_),
  62306. yOffset (yOffset_)
  62307. {
  62308. }
  62309. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  62310. {
  62311. delete clip;
  62312. }
  62313. void LowLevelGraphicsPostScriptRenderer::saveState()
  62314. {
  62315. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  62316. }
  62317. void LowLevelGraphicsPostScriptRenderer::restoreState()
  62318. {
  62319. SavedState* const top = stateStack.getLast();
  62320. if (top != 0)
  62321. {
  62322. clip->swapWith (*top->clip);
  62323. xOffset = top->xOffset;
  62324. yOffset = top->yOffset;
  62325. stateStack.removeLast();
  62326. needToClip = true;
  62327. }
  62328. else
  62329. {
  62330. jassertfalse // trying to pop with an empty stack!
  62331. }
  62332. }
  62333. void LowLevelGraphicsPostScriptRenderer::writeClip()
  62334. {
  62335. if (needToClip)
  62336. {
  62337. needToClip = false;
  62338. out << "doclip ";
  62339. int itemsOnLine = 0;
  62340. for (RectangleList::Iterator i (*clip); i.next();)
  62341. {
  62342. if (++itemsOnLine == 6)
  62343. {
  62344. itemsOnLine = 0;
  62345. out << '\n';
  62346. }
  62347. const Rectangle& r = *i.getRectangle();
  62348. out << r.getX() << ' ' << -r.getY() << ' '
  62349. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  62350. }
  62351. out << "endclip\n";
  62352. }
  62353. }
  62354. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  62355. {
  62356. Colour c (Colours::white.overlaidWith (colour));
  62357. if (lastColour != c)
  62358. {
  62359. lastColour = c;
  62360. out << String (c.getFloatRed(), 3) << ' '
  62361. << String (c.getFloatGreen(), 3) << ' '
  62362. << String (c.getFloatBlue(), 3) << " c\n";
  62363. }
  62364. }
  62365. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  62366. {
  62367. out << String (x, 2) << ' '
  62368. << String (-y, 2) << ' ';
  62369. }
  62370. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  62371. {
  62372. out << "newpath ";
  62373. float lastX = 0.0f;
  62374. float lastY = 0.0f;
  62375. int itemsOnLine = 0;
  62376. Path::Iterator i (path);
  62377. while (i.next())
  62378. {
  62379. if (++itemsOnLine == 4)
  62380. {
  62381. itemsOnLine = 0;
  62382. out << '\n';
  62383. }
  62384. switch (i.elementType)
  62385. {
  62386. case Path::Iterator::startNewSubPath:
  62387. writeXY (i.x1, i.y1);
  62388. lastX = i.x1;
  62389. lastY = i.y1;
  62390. out << "m ";
  62391. break;
  62392. case Path::Iterator::lineTo:
  62393. writeXY (i.x1, i.y1);
  62394. lastX = i.x1;
  62395. lastY = i.y1;
  62396. out << "l ";
  62397. break;
  62398. case Path::Iterator::quadraticTo:
  62399. {
  62400. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  62401. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  62402. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  62403. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  62404. writeXY (cp1x, cp1y);
  62405. writeXY (cp2x, cp2y);
  62406. writeXY (i.x2, i.y2);
  62407. out << "ct ";
  62408. lastX = i.x2;
  62409. lastY = i.y2;
  62410. }
  62411. break;
  62412. case Path::Iterator::cubicTo:
  62413. writeXY (i.x1, i.y1);
  62414. writeXY (i.x2, i.y2);
  62415. writeXY (i.x3, i.y3);
  62416. out << "ct ";
  62417. lastX = i.x3;
  62418. lastY = i.y3;
  62419. break;
  62420. case Path::Iterator::closePath:
  62421. out << "cp ";
  62422. break;
  62423. default:
  62424. jassertfalse
  62425. break;
  62426. }
  62427. }
  62428. out << '\n';
  62429. }
  62430. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  62431. {
  62432. out << "[ "
  62433. << trans.mat00 << ' '
  62434. << trans.mat10 << ' '
  62435. << trans.mat01 << ' '
  62436. << trans.mat11 << ' '
  62437. << trans.mat02 << ' '
  62438. << trans.mat12 << " ] concat ";
  62439. }
  62440. void LowLevelGraphicsPostScriptRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool /*replaceExistingContents*/)
  62441. {
  62442. writeClip();
  62443. writeColour (colour);
  62444. x += xOffset;
  62445. y += yOffset;
  62446. out << x << ' ' << -(y + h) << ' ' << w << ' ' << h << " rectfill\n";
  62447. }
  62448. void LowLevelGraphicsPostScriptRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  62449. {
  62450. Path p;
  62451. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  62452. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_256times);
  62453. }
  62454. void LowLevelGraphicsPostScriptRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  62455. const Colour& colour, EdgeTable::OversamplingLevel /*quality*/)
  62456. {
  62457. writeClip();
  62458. Path p (path);
  62459. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  62460. writePath (p);
  62461. writeColour (colour);
  62462. out << "fill\n";
  62463. }
  62464. void LowLevelGraphicsPostScriptRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel /*quality*/)
  62465. {
  62466. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  62467. // postscript can't do semi-transparent ones.
  62468. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62469. writeClip();
  62470. out << "gsave ";
  62471. {
  62472. Path p (path);
  62473. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  62474. writePath (p);
  62475. out << "clip\n";
  62476. }
  62477. int numColours = 256;
  62478. PixelARGB* const colours = gradient.createLookupTable (numColours);
  62479. for (int i = numColours; --i >= 0;)
  62480. colours[i].unpremultiply();
  62481. const Rectangle bounds (clip->getBounds());
  62482. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  62483. // time-being, this just fills it with the average colour..
  62484. writeColour (Colour (colours [numColours / 2].getARGB()));
  62485. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  62486. juce_free (colours);
  62487. out << "grestore\n";
  62488. }
  62489. void LowLevelGraphicsPostScriptRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  62490. const Image& sourceImage,
  62491. int imageX, int imageY,
  62492. float opacity, EdgeTable::OversamplingLevel /*quality*/)
  62493. {
  62494. writeClip();
  62495. out << "gsave ";
  62496. Path p (path);
  62497. p.applyTransform (transform.translated ((float) xOffset, (float) yOffset));
  62498. writePath (p);
  62499. out << "clip\n";
  62500. blendImage (sourceImage, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight(), 0, 0, opacity);
  62501. out << "grestore\n";
  62502. }
  62503. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithColour (const Image& /*clipImage*/, int x, int y, const Colour& colour)
  62504. {
  62505. x += xOffset;
  62506. y += yOffset;
  62507. writeClip();
  62508. writeColour (colour);
  62509. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62510. }
  62511. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithGradient (const Image& /*alphaChannelImage*/, int imageX, int imageY, const ColourGradient& /*gradient*/)
  62512. {
  62513. imageX += xOffset;
  62514. imageY += yOffset;
  62515. writeClip();
  62516. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62517. }
  62518. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithImage (const Image& /*alphaImage*/, int alphaImageX, int alphaImageY,
  62519. const Image& /*fillerImage*/, int fillerImageX, int fillerImageY, float /*opacity*/)
  62520. {
  62521. alphaImageX += xOffset;
  62522. alphaImageY += yOffset;
  62523. fillerImageX += xOffset;
  62524. fillerImageY += yOffset;
  62525. writeClip();
  62526. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62527. }
  62528. void LowLevelGraphicsPostScriptRenderer::blendImageRescaling (const Image& sourceImage,
  62529. int dx, int dy, int dw, int dh,
  62530. int sx, int sy, int sw, int sh,
  62531. float alpha,
  62532. const Graphics::ResamplingQuality quality)
  62533. {
  62534. if (sw > 0 && sh > 0)
  62535. {
  62536. jassert (sx >= 0 && sx + sw <= sourceImage.getWidth());
  62537. jassert (sy >= 0 && sy + sh <= sourceImage.getHeight());
  62538. if (sw == dw && sh == dh)
  62539. {
  62540. blendImage (sourceImage,
  62541. dx, dy, dw, dh,
  62542. sx, sy, alpha);
  62543. }
  62544. else
  62545. {
  62546. blendImageWarping (sourceImage,
  62547. sx, sy, sw, sh,
  62548. AffineTransform::scale (dw / (float) sw,
  62549. dh / (float) sh)
  62550. .translated ((float) (dx - sx),
  62551. (float) (dy - sy)),
  62552. alpha,
  62553. quality);
  62554. }
  62555. }
  62556. }
  62557. void LowLevelGraphicsPostScriptRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  62558. {
  62559. blendImageWarping (sourceImage,
  62560. sx, sy, dw, dh,
  62561. AffineTransform::translation ((float) dx, (float) dy),
  62562. opacity, Graphics::highResamplingQuality);
  62563. }
  62564. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  62565. const int sx, const int sy,
  62566. const int maxW, const int maxH) const
  62567. {
  62568. out << "{<\n";
  62569. const int w = jmin (maxW, im.getWidth());
  62570. const int h = jmin (maxH, im.getHeight());
  62571. int charsOnLine = 0;
  62572. int lineStride, pixelStride;
  62573. const uint8* data = im.lockPixelDataReadOnly (0, 0, w, h, lineStride, pixelStride);
  62574. Colour pixel;
  62575. for (int y = h; --y >= 0;)
  62576. {
  62577. for (int x = 0; x < w; ++x)
  62578. {
  62579. const uint8* pixelData = data + lineStride * y + pixelStride * x;
  62580. if (x >= sx && y >= sy)
  62581. {
  62582. if (im.isARGB())
  62583. {
  62584. PixelARGB p (*(const PixelARGB*) pixelData);
  62585. p.unpremultiply();
  62586. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  62587. }
  62588. else if (im.isRGB())
  62589. {
  62590. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  62591. }
  62592. else
  62593. {
  62594. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  62595. }
  62596. }
  62597. else
  62598. {
  62599. pixel = Colours::transparentWhite;
  62600. }
  62601. char colourString [16];
  62602. sprintf (colourString, "%x%x%x", pixel.getRed(), pixel.getGreen(), pixel.getBlue());
  62603. out << (const char*) colourString;
  62604. charsOnLine += 3;
  62605. if (charsOnLine > 100)
  62606. {
  62607. out << '\n';
  62608. charsOnLine = 0;
  62609. }
  62610. }
  62611. }
  62612. im.releasePixelDataReadOnly (data);
  62613. out << "\n>}\n";
  62614. }
  62615. void LowLevelGraphicsPostScriptRenderer::blendImageWarping (const Image& sourceImage,
  62616. int srcClipX, int srcClipY,
  62617. int srcClipW, int srcClipH,
  62618. const AffineTransform& t,
  62619. float /*opacity*/,
  62620. const Graphics::ResamplingQuality /*quality*/)
  62621. {
  62622. const int w = jmin (sourceImage.getWidth(), srcClipX + srcClipW);
  62623. const int h = jmin (sourceImage.getHeight(), srcClipY + srcClipH);
  62624. writeClip();
  62625. out << "gsave ";
  62626. writeTransform (t.translated ((float) xOffset, (float) yOffset)
  62627. .scaled (1.0f, -1.0f));
  62628. RectangleList imageClip;
  62629. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  62630. imageClip.clipTo (Rectangle (srcClipX, srcClipY, srcClipW, srcClipH));
  62631. out << "newpath ";
  62632. int itemsOnLine = 0;
  62633. for (RectangleList::Iterator i (imageClip); i.next();)
  62634. {
  62635. if (++itemsOnLine == 6)
  62636. {
  62637. out << '\n';
  62638. itemsOnLine = 0;
  62639. }
  62640. const Rectangle& r = *i.getRectangle();
  62641. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  62642. }
  62643. out << " clip newpath\n";
  62644. out << w << ' ' << h << " scale\n";
  62645. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  62646. writeImage (sourceImage, srcClipX, srcClipY, srcClipW, srcClipH);
  62647. out << "false 3 colorimage grestore\n";
  62648. needToClip = true;
  62649. }
  62650. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  62651. {
  62652. Path p;
  62653. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  62654. fillPathWithColour (p, AffineTransform::identity, colour, EdgeTable::Oversampling_256times);
  62655. }
  62656. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  62657. {
  62658. drawLine (x, top, x, bottom, col);
  62659. }
  62660. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  62661. {
  62662. drawLine (left, y, right, y, col);
  62663. }
  62664. END_JUCE_NAMESPACE
  62665. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  62666. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  62667. BEGIN_JUCE_NAMESPACE
  62668. #if ! (defined (JUCE_MAC) || (defined (JUCE_WIN32) && defined (JUCE_64BIT)))
  62669. #define JUCE_USE_SSE_INSTRUCTIONS 1
  62670. #endif
  62671. #if defined (JUCE_DEBUG) && JUCE_MSVC
  62672. #pragma warning (disable: 4714)
  62673. #endif
  62674. #define MINIMUM_COORD -0x3fffffff
  62675. #define MAXIMUM_COORD 0x3fffffff
  62676. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  62677. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  62678. jassert ((int) x >= MINIMUM_COORD \
  62679. && (int) x <= MAXIMUM_COORD \
  62680. && (int) y >= MINIMUM_COORD \
  62681. && (int) y <= MAXIMUM_COORD \
  62682. && (int) w >= 0 \
  62683. && (int) w < MAXIMUM_COORD \
  62684. && (int) h >= 0 \
  62685. && (int) h < MAXIMUM_COORD);
  62686. static void replaceRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  62687. {
  62688. const PixelARGB blendColour (colour.getPixelARGB());
  62689. if (w < 32)
  62690. {
  62691. while (--h >= 0)
  62692. {
  62693. PixelRGB* dest = (PixelRGB*) pixels;
  62694. for (int i = w; --i >= 0;)
  62695. (dest++)->set (blendColour);
  62696. pixels += stride;
  62697. }
  62698. }
  62699. else
  62700. {
  62701. // for wider fills, it's worth using some optimisations..
  62702. const uint8 r = blendColour.getRed();
  62703. const uint8 g = blendColour.getGreen();
  62704. const uint8 b = blendColour.getBlue();
  62705. if (r == g && r == b) // if all the component values are the same, we can cheat..
  62706. {
  62707. while (--h >= 0)
  62708. {
  62709. memset (pixels, r, w * 3);
  62710. pixels += stride;
  62711. }
  62712. }
  62713. else
  62714. {
  62715. PixelRGB filler [4];
  62716. filler[0].set (blendColour);
  62717. filler[1].set (blendColour);
  62718. filler[2].set (blendColour);
  62719. filler[3].set (blendColour);
  62720. const int* const intFiller = (const int*) filler;
  62721. while (--h >= 0)
  62722. {
  62723. uint8* dest = (uint8*) pixels;
  62724. int i = w;
  62725. while ((i > 8) && (((pointer_sized_int) dest & 7) != 0))
  62726. {
  62727. ((PixelRGB*) dest)->set (blendColour);
  62728. dest += 3;
  62729. --i;
  62730. }
  62731. while (i >= 4)
  62732. {
  62733. ((int*) dest) [0] = intFiller[0];
  62734. ((int*) dest) [1] = intFiller[1];
  62735. ((int*) dest) [2] = intFiller[2];
  62736. dest += 12;
  62737. i -= 4;
  62738. }
  62739. while (--i >= 0)
  62740. {
  62741. ((PixelRGB*) dest)->set (blendColour);
  62742. dest += 3;
  62743. }
  62744. pixels += stride;
  62745. }
  62746. }
  62747. }
  62748. }
  62749. static void replaceRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  62750. {
  62751. const PixelARGB blendColour (colour.getPixelARGB());
  62752. while (--h >= 0)
  62753. {
  62754. PixelARGB* const dest = (PixelARGB*) pixels;
  62755. for (int i = 0; i < w; ++i)
  62756. dest[i] = blendColour;
  62757. pixels += stride;
  62758. }
  62759. }
  62760. static void blendRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  62761. {
  62762. if (colour.isOpaque())
  62763. {
  62764. replaceRectRGB (pixels, w, h, stride, colour);
  62765. }
  62766. else
  62767. {
  62768. const PixelARGB blendColour (colour.getPixelARGB());
  62769. const int alpha = blendColour.getAlpha();
  62770. if (alpha <= 0)
  62771. return;
  62772. #if defined (JUCE_USE_SSE_INSTRUCTIONS) && ! JUCE_64BIT
  62773. if (SystemStats::hasSSE())
  62774. {
  62775. int64 rgb0 = (((int64) blendColour.getRed()) << 32)
  62776. | (int64) ((blendColour.getGreen() << 16)
  62777. | blendColour.getBlue());
  62778. const int invAlpha = 0xff - alpha;
  62779. int64 aaaa = (invAlpha << 16) | invAlpha;
  62780. aaaa = (aaaa << 16) | aaaa;
  62781. #ifndef JUCE_GCC
  62782. __asm
  62783. {
  62784. movq mm1, aaaa
  62785. movq mm2, rgb0
  62786. pxor mm7, mm7
  62787. }
  62788. while (--h >= 0)
  62789. {
  62790. __asm
  62791. {
  62792. mov edx, pixels
  62793. mov ebx, w
  62794. pixloop:
  62795. prefetchnta [edx]
  62796. mov ax, [edx + 1]
  62797. shl eax, 8
  62798. mov al, [edx]
  62799. movd mm0, eax
  62800. punpcklbw mm0, mm7
  62801. pmullw mm0, mm1
  62802. psrlw mm0, 8
  62803. paddw mm0, mm2
  62804. packuswb mm0, mm7
  62805. movd eax, mm0
  62806. mov [edx], al
  62807. inc edx
  62808. shr eax, 8
  62809. mov [edx], ax
  62810. add edx, 2
  62811. dec ebx
  62812. jg pixloop
  62813. }
  62814. pixels += stride;
  62815. }
  62816. __asm emms
  62817. #else
  62818. __asm__ __volatile__ (
  62819. "\tpush %%ebx \n"
  62820. "\tmovq %[aaaa], %%mm1 \n"
  62821. "\tmovq %[rgb0], %%mm2 \n"
  62822. "\tpxor %%mm7, %%mm7 \n"
  62823. ".lineLoop2: \n"
  62824. "\tmovl %%esi,%%edx \n"
  62825. "\tmovl %[w], %%ebx \n"
  62826. ".pixLoop2: \n"
  62827. "\tprefetchnta (%%edx) \n"
  62828. "\tmov (%%edx), %%ax \n"
  62829. "\tshl $8, %%eax \n"
  62830. "\tmov 2(%%edx), %%al \n"
  62831. "\tmovd %%eax, %%mm0 \n"
  62832. "\tpunpcklbw %%mm7, %%mm0 \n"
  62833. "\tpmullw %%mm1, %%mm0 \n"
  62834. "\tpsrlw $8, %%mm0 \n"
  62835. "\tpaddw %%mm2, %%mm0 \n"
  62836. "\tpackuswb %%mm7, %%mm0 \n"
  62837. "\tmovd %%mm0, %%eax \n"
  62838. "\tmovb %%al, (%%edx) \n"
  62839. "\tinc %%edx \n"
  62840. "\tshr $8, %%eax \n"
  62841. "\tmovw %%ax, (%%edx) \n"
  62842. "\tadd $2, %%edx \n"
  62843. "\tdec %%ebx \n"
  62844. "\tjg .pixLoop2 \n"
  62845. "\tadd %%edi, %%esi \n"
  62846. "\tdec %%ecx \n"
  62847. "\tjg .lineLoop2 \n"
  62848. "\tpop %%ebx \n"
  62849. "\temms \n"
  62850. : /* No output registers */
  62851. : [aaaa] "m" (aaaa), /* Input registers */
  62852. [rgb0] "m" (rgb0),
  62853. [w] "m" (w),
  62854. "c" (h),
  62855. [stride] "D" (stride),
  62856. [pixels] "S" (pixels)
  62857. : "cc", "eax", "edx", "memory" /* Clobber list */
  62858. );
  62859. #endif
  62860. }
  62861. else
  62862. #endif
  62863. {
  62864. while (--h >= 0)
  62865. {
  62866. PixelRGB* dest = (PixelRGB*) pixels;
  62867. for (int i = w; --i >= 0;)
  62868. (dest++)->blend (blendColour);
  62869. pixels += stride;
  62870. }
  62871. }
  62872. }
  62873. }
  62874. static void blendRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  62875. {
  62876. if (colour.isOpaque())
  62877. {
  62878. replaceRectARGB (pixels, w, h, stride, colour);
  62879. }
  62880. else
  62881. {
  62882. const PixelARGB blendColour (colour.getPixelARGB());
  62883. const int alpha = blendColour.getAlpha();
  62884. if (alpha <= 0)
  62885. return;
  62886. while (--h >= 0)
  62887. {
  62888. PixelARGB* dest = (PixelARGB*) pixels;
  62889. for (int i = w; --i >= 0;)
  62890. (dest++)->blend (blendColour);
  62891. pixels += stride;
  62892. }
  62893. }
  62894. }
  62895. static void blendAlphaMapARGB (uint8* destPixel, const int imageStride,
  62896. const uint8* alphaValues, const int w, int h,
  62897. const int pixelStride, const int lineStride,
  62898. const Colour& colour) throw()
  62899. {
  62900. const PixelARGB srcPix (colour.getPixelARGB());
  62901. while (--h >= 0)
  62902. {
  62903. PixelARGB* dest = (PixelARGB*) destPixel;
  62904. const uint8* src = alphaValues;
  62905. int i = w;
  62906. while (--i >= 0)
  62907. {
  62908. unsigned int srcAlpha = *src;
  62909. src += pixelStride;
  62910. if (srcAlpha > 0)
  62911. dest->blend (srcPix, srcAlpha);
  62912. ++dest;
  62913. }
  62914. alphaValues += lineStride;
  62915. destPixel += imageStride;
  62916. }
  62917. }
  62918. static void blendAlphaMapRGB (uint8* destPixel, const int imageStride,
  62919. const uint8* alphaValues, int const width, int height,
  62920. const int pixelStride, const int lineStride,
  62921. const Colour& colour) throw()
  62922. {
  62923. const PixelARGB srcPix (colour.getPixelARGB());
  62924. while (--height >= 0)
  62925. {
  62926. PixelRGB* dest = (PixelRGB*) destPixel;
  62927. const uint8* src = alphaValues;
  62928. int i = width;
  62929. while (--i >= 0)
  62930. {
  62931. unsigned int srcAlpha = *src;
  62932. src += pixelStride;
  62933. if (srcAlpha > 0)
  62934. dest->blend (srcPix, srcAlpha);
  62935. ++dest;
  62936. }
  62937. alphaValues += lineStride;
  62938. destPixel += imageStride;
  62939. }
  62940. }
  62941. template <class PixelType>
  62942. class SolidColourEdgeTableRenderer
  62943. {
  62944. uint8* const data;
  62945. const int stride;
  62946. PixelType* linePixels;
  62947. PixelARGB sourceColour;
  62948. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  62949. const SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  62950. public:
  62951. SolidColourEdgeTableRenderer (uint8* const data_,
  62952. const int stride_,
  62953. const Colour& colour) throw()
  62954. : data (data_),
  62955. stride (stride_),
  62956. sourceColour (colour.getPixelARGB())
  62957. {
  62958. }
  62959. forcedinline void setEdgeTableYPos (const int y) throw()
  62960. {
  62961. linePixels = (PixelType*) (data + stride * y);
  62962. }
  62963. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  62964. {
  62965. linePixels[x].blend (sourceColour, alphaLevel);
  62966. }
  62967. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  62968. {
  62969. PixelARGB p (sourceColour);
  62970. p.multiplyAlpha (alphaLevel);
  62971. PixelType* dest = linePixels + x;
  62972. if (p.getAlpha() < 0xff)
  62973. {
  62974. do
  62975. {
  62976. dest->blend (p);
  62977. ++dest;
  62978. } while (--width > 0);
  62979. }
  62980. else
  62981. {
  62982. do
  62983. {
  62984. dest->set (p);
  62985. ++dest;
  62986. } while (--width > 0);
  62987. }
  62988. }
  62989. };
  62990. class AlphaBitmapRenderer
  62991. {
  62992. uint8* data;
  62993. int stride;
  62994. uint8* lineStart;
  62995. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  62996. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  62997. public:
  62998. AlphaBitmapRenderer (uint8* const data_,
  62999. const int stride_) throw()
  63000. : data (data_),
  63001. stride (stride_)
  63002. {
  63003. }
  63004. forcedinline void setEdgeTableYPos (const int y) throw()
  63005. {
  63006. lineStart = data + (stride * y);
  63007. }
  63008. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63009. {
  63010. lineStart [x] = (uint8) alphaLevel;
  63011. }
  63012. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  63013. {
  63014. uint8* d = lineStart + x;
  63015. while (--width >= 0)
  63016. *d++ = (uint8) alphaLevel;
  63017. }
  63018. };
  63019. static const int numScaleBits = 12;
  63020. class LinearGradientPixelGenerator
  63021. {
  63022. const PixelARGB* const lookupTable;
  63023. const int numEntries;
  63024. PixelARGB linePix;
  63025. int start, scale;
  63026. double grad, yTerm;
  63027. bool vertical, horizontal;
  63028. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  63029. const LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  63030. public:
  63031. LinearGradientPixelGenerator (const ColourGradient& gradient,
  63032. const PixelARGB* const lookupTable_, const int numEntries_)
  63033. : lookupTable (lookupTable_),
  63034. numEntries (numEntries_)
  63035. {
  63036. jassert (numEntries_ >= 0);
  63037. float x1 = gradient.x1;
  63038. float y1 = gradient.y1;
  63039. float x2 = gradient.x2;
  63040. float y2 = gradient.y2;
  63041. if (! gradient.transform.isIdentity())
  63042. {
  63043. Line l (x2, y2, x1, y1);
  63044. const Point p3 = l.getPointAlongLine (0.0, 100.0f);
  63045. float x3 = p3.getX();
  63046. float y3 = p3.getY();
  63047. gradient.transform.transformPoint (x1, y1);
  63048. gradient.transform.transformPoint (x2, y2);
  63049. gradient.transform.transformPoint (x3, y3);
  63050. Line l2 (x2, y2, x3, y3);
  63051. float prop = l2.findNearestPointTo (x1, y1);
  63052. const Point newP2 (l2.getPointAlongLineProportionally (prop));
  63053. x2 = newP2.getX();
  63054. y2 = newP2.getY();
  63055. }
  63056. vertical = fabs (x1 - x2) < 0.001f;
  63057. horizontal = fabs (y1 - y2) < 0.001f;
  63058. if (vertical)
  63059. {
  63060. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (y2 - y1));
  63061. start = roundDoubleToInt (y1 * scale);
  63062. }
  63063. else if (horizontal)
  63064. {
  63065. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (x2 - x1));
  63066. start = roundDoubleToInt (x1 * scale);
  63067. }
  63068. else
  63069. {
  63070. grad = (y2 - y1) / (double) (x1 - x2);
  63071. yTerm = y1 - x1 / grad;
  63072. scale = roundDoubleToInt ((numEntries << numScaleBits) / (yTerm * grad - (y2 * grad - x2)));
  63073. grad *= scale;
  63074. }
  63075. }
  63076. forcedinline void setY (const int y) throw()
  63077. {
  63078. if (vertical)
  63079. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> numScaleBits)];
  63080. else if (! horizontal)
  63081. start = roundDoubleToInt ((y - yTerm) * grad);
  63082. }
  63083. forcedinline const PixelARGB getPixel (const int x) const throw()
  63084. {
  63085. if (vertical)
  63086. return linePix;
  63087. return lookupTable [jlimit (0, numEntries, (x * scale - start) >> numScaleBits)];
  63088. }
  63089. };
  63090. class RadialGradientPixelGenerator
  63091. {
  63092. protected:
  63093. const PixelARGB* const lookupTable;
  63094. const int numEntries;
  63095. const double gx1, gy1;
  63096. double maxDist, invScale;
  63097. double dy;
  63098. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  63099. const RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  63100. public:
  63101. RadialGradientPixelGenerator (const ColourGradient& gradient,
  63102. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  63103. : lookupTable (lookupTable_),
  63104. numEntries (numEntries_),
  63105. gx1 (gradient.x1),
  63106. gy1 (gradient.y1)
  63107. {
  63108. jassert (numEntries_ >= 0);
  63109. const float dx = gradient.x1 - gradient.x2;
  63110. const float dy = gradient.y1 - gradient.y2;
  63111. maxDist = dx * dx + dy * dy;
  63112. invScale = (numEntries + 1) / sqrt (maxDist);
  63113. }
  63114. forcedinline void setY (const int y) throw()
  63115. {
  63116. dy = y - gy1;
  63117. dy *= dy;
  63118. }
  63119. forcedinline const PixelARGB getPixel (const int px) const throw()
  63120. {
  63121. double x = px - gx1;
  63122. x *= x;
  63123. x += dy;
  63124. if (x >= maxDist)
  63125. return lookupTable [numEntries];
  63126. else
  63127. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  63128. }
  63129. };
  63130. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  63131. {
  63132. double tM10, tM00, lineYM01, lineYM11;
  63133. AffineTransform inverseTransform;
  63134. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  63135. const TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  63136. public:
  63137. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient,
  63138. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  63139. : RadialGradientPixelGenerator (gradient, lookupTable_, numEntries_),
  63140. inverseTransform (gradient.transform.inverted())
  63141. {
  63142. tM10 = inverseTransform.mat10;
  63143. tM00 = inverseTransform.mat00;
  63144. }
  63145. forcedinline void setY (const int y) throw()
  63146. {
  63147. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  63148. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  63149. }
  63150. forcedinline const PixelARGB getPixel (const int px) const throw()
  63151. {
  63152. double x = px;
  63153. const double y = tM10 * x + lineYM11;
  63154. x = tM00 * x + lineYM01;
  63155. x *= x;
  63156. x += y * y;
  63157. if (x >= maxDist)
  63158. return lookupTable [numEntries];
  63159. else
  63160. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  63161. }
  63162. };
  63163. template <class PixelType, class GradientType>
  63164. class GradientEdgeTableRenderer : public GradientType
  63165. {
  63166. uint8* const data;
  63167. const int stride;
  63168. PixelType* linePixels;
  63169. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  63170. const GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  63171. public:
  63172. GradientEdgeTableRenderer (uint8* const data_,
  63173. const int stride_,
  63174. const ColourGradient& gradient,
  63175. const PixelARGB* const lookupTable, const int numEntries) throw()
  63176. : GradientType (gradient, lookupTable, numEntries - 1),
  63177. data (data_),
  63178. stride (stride_)
  63179. {
  63180. }
  63181. forcedinline void setEdgeTableYPos (const int y) throw()
  63182. {
  63183. linePixels = (PixelType*) (data + stride * y);
  63184. GradientType::setY (y);
  63185. }
  63186. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63187. {
  63188. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  63189. }
  63190. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  63191. {
  63192. PixelType* dest = linePixels + x;
  63193. if (alphaLevel < 0xff)
  63194. {
  63195. do
  63196. {
  63197. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  63198. } while (--width > 0);
  63199. }
  63200. else
  63201. {
  63202. do
  63203. {
  63204. (dest++)->blend (GradientType::getPixel (x++));
  63205. } while (--width > 0);
  63206. }
  63207. }
  63208. };
  63209. template <class DestPixelType, class SrcPixelType>
  63210. class ImageFillEdgeTableRenderer
  63211. {
  63212. uint8* const destImageData;
  63213. const uint8* srcImageData;
  63214. int stride, srcStride, extraAlpha;
  63215. DestPixelType* linePixels;
  63216. SrcPixelType* sourceLineStart;
  63217. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  63218. const ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  63219. public:
  63220. ImageFillEdgeTableRenderer (uint8* const destImageData_,
  63221. const int stride_,
  63222. const uint8* srcImageData_,
  63223. const int srcStride_,
  63224. int extraAlpha_,
  63225. SrcPixelType*) throw() // dummy param to avoid compiler error
  63226. : destImageData (destImageData_),
  63227. srcImageData (srcImageData_),
  63228. stride (stride_),
  63229. srcStride (srcStride_),
  63230. extraAlpha (extraAlpha_)
  63231. {
  63232. }
  63233. forcedinline void setEdgeTableYPos (int y) throw()
  63234. {
  63235. linePixels = (DestPixelType*) (destImageData + stride * y);
  63236. sourceLineStart = (SrcPixelType*) (srcImageData + srcStride * y);
  63237. }
  63238. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  63239. {
  63240. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  63241. linePixels[x].blend (sourceLineStart [x], alphaLevel);
  63242. }
  63243. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  63244. {
  63245. DestPixelType* dest = linePixels + x;
  63246. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  63247. if (alphaLevel < 0xfe)
  63248. {
  63249. do
  63250. {
  63251. dest++ ->blend (sourceLineStart [x++], alphaLevel);
  63252. } while (--width > 0);
  63253. }
  63254. else
  63255. {
  63256. do
  63257. {
  63258. dest++ ->blend (sourceLineStart [x++]);
  63259. } while (--width > 0);
  63260. }
  63261. }
  63262. };
  63263. static void blendRowOfPixels (PixelARGB* dst,
  63264. const PixelRGB* src,
  63265. int width) throw()
  63266. {
  63267. while (--width >= 0)
  63268. (dst++)->set (*src++);
  63269. }
  63270. static void blendRowOfPixels (PixelRGB* dst,
  63271. const PixelRGB* src,
  63272. int width) throw()
  63273. {
  63274. memcpy (dst, src, 3 * width);
  63275. }
  63276. static void blendRowOfPixels (PixelRGB* dst,
  63277. const PixelARGB* src,
  63278. int width) throw()
  63279. {
  63280. while (--width >= 0)
  63281. (dst++)->blend (*src++);
  63282. }
  63283. static void blendRowOfPixels (PixelARGB* dst,
  63284. const PixelARGB* src,
  63285. int width) throw()
  63286. {
  63287. while (--width >= 0)
  63288. (dst++)->blend (*src++);
  63289. }
  63290. static void blendRowOfPixels (PixelARGB* dst,
  63291. const PixelRGB* src,
  63292. int width,
  63293. const uint8 alpha) throw()
  63294. {
  63295. while (--width >= 0)
  63296. (dst++)->blend (*src++, alpha);
  63297. }
  63298. static void blendRowOfPixels (PixelRGB* dst,
  63299. const PixelRGB* src,
  63300. int width,
  63301. const uint8 alpha) throw()
  63302. {
  63303. uint8* d = (uint8*) dst;
  63304. const uint8* s = (const uint8*) src;
  63305. const int inverseAlpha = 0xff - alpha;
  63306. while (--width >= 0)
  63307. {
  63308. d[0] = (uint8) (s[0] + (((d[0] - s[0]) * inverseAlpha) >> 8));
  63309. d[1] = (uint8) (s[1] + (((d[1] - s[1]) * inverseAlpha) >> 8));
  63310. d[2] = (uint8) (s[2] + (((d[2] - s[2]) * inverseAlpha) >> 8));
  63311. d += 3;
  63312. s += 3;
  63313. }
  63314. }
  63315. static void blendRowOfPixels (PixelRGB* dst,
  63316. const PixelARGB* src,
  63317. int width,
  63318. const uint8 alpha) throw()
  63319. {
  63320. while (--width >= 0)
  63321. (dst++)->blend (*src++, alpha);
  63322. }
  63323. static void blendRowOfPixels (PixelARGB* dst,
  63324. const PixelARGB* src,
  63325. int width,
  63326. const uint8 alpha) throw()
  63327. {
  63328. while (--width >= 0)
  63329. (dst++)->blend (*src++, alpha);
  63330. }
  63331. template <class DestPixelType, class SrcPixelType>
  63332. static void overlayImage (DestPixelType* dest,
  63333. const int destStride,
  63334. const SrcPixelType* src,
  63335. const int srcStride,
  63336. const int width,
  63337. int height,
  63338. const uint8 alpha) throw()
  63339. {
  63340. if (alpha < 0xff)
  63341. {
  63342. while (--height >= 0)
  63343. {
  63344. blendRowOfPixels (dest, src, width, alpha);
  63345. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  63346. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63347. }
  63348. }
  63349. else
  63350. {
  63351. while (--height >= 0)
  63352. {
  63353. blendRowOfPixels (dest, src, width);
  63354. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  63355. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63356. }
  63357. }
  63358. }
  63359. template <class DestPixelType, class SrcPixelType>
  63360. static void transformedImageRender (Image& destImage,
  63361. const Image& sourceImage,
  63362. const int destClipX, const int destClipY,
  63363. const int destClipW, const int destClipH,
  63364. const int srcClipX, const int srcClipY,
  63365. const int srcClipWidth, const int srcClipHeight,
  63366. double srcX, double srcY,
  63367. const double lineDX, const double lineDY,
  63368. const double pixelDX, const double pixelDY,
  63369. const uint8 alpha,
  63370. const Graphics::ResamplingQuality quality,
  63371. DestPixelType*,
  63372. SrcPixelType*) throw() // forced by a compiler bug to include dummy
  63373. // parameters of the templated classes to
  63374. // make it use the correct instance of this function..
  63375. {
  63376. int destStride, destPixelStride;
  63377. uint8* const destPixels = destImage.lockPixelDataReadWrite (destClipX, destClipY, destClipW, destClipH, destStride, destPixelStride);
  63378. int srcStride, srcPixelStride;
  63379. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (srcClipX, srcClipY, srcClipWidth, srcClipHeight, srcStride, srcPixelStride);
  63380. if (quality == Graphics::lowResamplingQuality) // nearest-neighbour..
  63381. {
  63382. if (alpha == 255)
  63383. {
  63384. for (int y = 0; y < destClipH; ++y)
  63385. {
  63386. double sx = srcX;
  63387. double sy = srcY;
  63388. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63389. for (int x = destClipW; --x >= 0;)
  63390. {
  63391. const int ix = ((int) sx) - srcClipX;
  63392. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  63393. {
  63394. const int iy = ((int) sy) - srcClipY;
  63395. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  63396. {
  63397. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63398. dest->set (*src);
  63399. }
  63400. }
  63401. ++dest;
  63402. sx += pixelDX;
  63403. sy += pixelDY;
  63404. }
  63405. srcX += lineDX;
  63406. srcY += lineDY;
  63407. }
  63408. }
  63409. else
  63410. {
  63411. for (int y = 0; y < destClipH; ++y)
  63412. {
  63413. double sx = srcX;
  63414. double sy = srcY;
  63415. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63416. for (int x = destClipW; --x >= 0;)
  63417. {
  63418. const int ix = ((int) sx) - srcClipX;
  63419. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  63420. {
  63421. const int iy = ((int) sy) - srcClipY;
  63422. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  63423. {
  63424. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63425. dest->blend (*src, alpha);
  63426. }
  63427. }
  63428. ++dest;
  63429. sx += pixelDX;
  63430. sy += pixelDY;
  63431. }
  63432. srcX += lineDX;
  63433. srcY += lineDY;
  63434. }
  63435. }
  63436. }
  63437. else
  63438. {
  63439. jassert (quality == Graphics::mediumResamplingQuality); // (only bilinear is implemented, so that's what you'll get here..)
  63440. for (int y = 0; y < destClipH; ++y)
  63441. {
  63442. double sx = srcX - (srcClipWidth == destClipW ? 0.0 : 0.5);
  63443. double sy = srcY - (srcClipHeight == destClipH ? 0.0 : 0.5);
  63444. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63445. for (int x = 0; x < destClipW; ++x)
  63446. {
  63447. const double fx = floor (sx);
  63448. const double fy = floor (sy);
  63449. const int ix = roundDoubleToInt (fx) - srcClipX;
  63450. const int iy = roundDoubleToInt (fy) - srcClipY;
  63451. if (ix < srcClipWidth && iy < srcClipHeight)
  63452. {
  63453. PixelARGB p1 (0), p2 (0), p3 (0), p4 (0);
  63454. const SrcPixelType* src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63455. if (iy >= 0)
  63456. {
  63457. if (ix >= 0)
  63458. p1.set (src[0]);
  63459. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  63460. p2.set (src[1]);
  63461. }
  63462. if (((unsigned int) (iy + 1)) < (unsigned int) srcClipHeight)
  63463. {
  63464. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63465. if (ix >= 0)
  63466. p3.set (src[0]);
  63467. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  63468. p4.set (src[1]);
  63469. }
  63470. const int dx = roundDoubleToInt ((sx - fx) * 255.0);
  63471. p1.tween (p2, dx);
  63472. p3.tween (p4, dx);
  63473. p1.tween (p3, roundDoubleToInt ((sy - fy) * 255.0));
  63474. if (p1.getAlpha() > 0)
  63475. dest->blend (p1, alpha);
  63476. }
  63477. ++dest;
  63478. sx += pixelDX;
  63479. sy += pixelDY;
  63480. }
  63481. srcX += lineDX;
  63482. srcY += lineDY;
  63483. }
  63484. }
  63485. destImage.releasePixelDataReadWrite (destPixels);
  63486. sourceImage.releasePixelDataReadOnly (srcPixels);
  63487. }
  63488. template <class SrcPixelType, class DestPixelType>
  63489. static void renderAlphaMap (DestPixelType* destPixels,
  63490. int destStride,
  63491. SrcPixelType* srcPixels,
  63492. int srcStride,
  63493. const uint8* alphaValues,
  63494. const int lineStride, const int pixelStride,
  63495. int width, int height,
  63496. const int extraAlpha) throw()
  63497. {
  63498. while (--height >= 0)
  63499. {
  63500. SrcPixelType* srcPix = srcPixels;
  63501. srcPixels = (SrcPixelType*) (((const uint8*) srcPixels) + srcStride);
  63502. DestPixelType* destPix = destPixels;
  63503. destPixels = (DestPixelType*) (((uint8*) destPixels) + destStride);
  63504. const uint8* alpha = alphaValues;
  63505. alphaValues += lineStride;
  63506. if (extraAlpha < 0x100)
  63507. {
  63508. for (int i = width; --i >= 0;)
  63509. {
  63510. destPix++ ->blend (*srcPix++, (extraAlpha * *alpha) >> 8);
  63511. alpha += pixelStride;
  63512. }
  63513. }
  63514. else
  63515. {
  63516. for (int i = width; --i >= 0;)
  63517. {
  63518. destPix++ ->blend (*srcPix++, *alpha);
  63519. alpha += pixelStride;
  63520. }
  63521. }
  63522. }
  63523. }
  63524. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  63525. : image (image_),
  63526. xOffset (0),
  63527. yOffset (0),
  63528. stateStack (20)
  63529. {
  63530. clip = new RectangleList (Rectangle (0, 0, image_.getWidth(), image_.getHeight()));
  63531. }
  63532. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  63533. {
  63534. delete clip;
  63535. }
  63536. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  63537. {
  63538. return false;
  63539. }
  63540. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  63541. {
  63542. xOffset += x;
  63543. yOffset += y;
  63544. }
  63545. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (int x, int y, int w, int h)
  63546. {
  63547. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  63548. }
  63549. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (const RectangleList& clipRegion)
  63550. {
  63551. RectangleList temp (clipRegion);
  63552. temp.offsetAll (xOffset, yOffset);
  63553. return clip->clipTo (temp);
  63554. }
  63555. void LowLevelGraphicsSoftwareRenderer::excludeClipRegion (int x, int y, int w, int h)
  63556. {
  63557. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  63558. }
  63559. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (int x, int y, int w, int h)
  63560. {
  63561. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  63562. }
  63563. const Rectangle LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  63564. {
  63565. return clip->getBounds().translated (-xOffset, -yOffset);
  63566. }
  63567. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  63568. {
  63569. return clip->isEmpty();
  63570. }
  63571. LowLevelGraphicsSoftwareRenderer::SavedState::SavedState (RectangleList* const clip_,
  63572. const int xOffset_, const int yOffset_)
  63573. : clip (clip_),
  63574. xOffset (xOffset_),
  63575. yOffset (yOffset_)
  63576. {
  63577. }
  63578. LowLevelGraphicsSoftwareRenderer::SavedState::~SavedState()
  63579. {
  63580. delete clip;
  63581. }
  63582. void LowLevelGraphicsSoftwareRenderer::saveState()
  63583. {
  63584. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  63585. }
  63586. void LowLevelGraphicsSoftwareRenderer::restoreState()
  63587. {
  63588. SavedState* const top = stateStack.getLast();
  63589. if (top != 0)
  63590. {
  63591. clip->swapWith (*top->clip);
  63592. xOffset = top->xOffset;
  63593. yOffset = top->yOffset;
  63594. stateStack.removeLast();
  63595. }
  63596. else
  63597. {
  63598. jassertfalse // trying to pop with an empty stack!
  63599. }
  63600. }
  63601. void LowLevelGraphicsSoftwareRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  63602. {
  63603. x += xOffset;
  63604. y += yOffset;
  63605. for (RectangleList::Iterator i (*clip); i.next();)
  63606. {
  63607. clippedFillRectWithColour (*i.getRectangle(), x, y, w, h, colour, replaceExistingContents);
  63608. }
  63609. }
  63610. void LowLevelGraphicsSoftwareRenderer::clippedFillRectWithColour (const Rectangle& clipRect,
  63611. int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  63612. {
  63613. if (clipRect.intersectRectangle (x, y, w, h))
  63614. {
  63615. int stride, pixelStride;
  63616. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  63617. if (image.getFormat() == Image::RGB)
  63618. {
  63619. if (replaceExistingContents)
  63620. replaceRectRGB (pixels, w, h, stride, colour);
  63621. else
  63622. blendRectRGB (pixels, w, h, stride, colour);
  63623. }
  63624. else if (image.getFormat() == Image::ARGB)
  63625. {
  63626. if (replaceExistingContents)
  63627. replaceRectARGB (pixels, w, h, stride, colour);
  63628. else
  63629. blendRectARGB (pixels, w, h, stride, colour);
  63630. }
  63631. else
  63632. {
  63633. jassertfalse // not done!
  63634. }
  63635. image.releasePixelDataReadWrite (pixels);
  63636. }
  63637. }
  63638. void LowLevelGraphicsSoftwareRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  63639. {
  63640. Path p;
  63641. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  63642. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_none);
  63643. }
  63644. bool LowLevelGraphicsSoftwareRenderer::getPathBounds (int clipX, int clipY, int clipW, int clipH,
  63645. const Path& path, const AffineTransform& transform,
  63646. int& x, int& y, int& w, int& h) const
  63647. {
  63648. float tx, ty, tw, th;
  63649. path.getBoundsTransformed (transform, tx, ty, tw, th);
  63650. x = roundDoubleToInt (tx) - 1;
  63651. y = roundDoubleToInt (ty) - 1;
  63652. w = roundDoubleToInt (tw) + 2;
  63653. h = roundDoubleToInt (th) + 2;
  63654. // seems like this operation is using some crazy out-of-range numbers..
  63655. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, w, h);
  63656. return Rectangle::intersectRectangles (x, y, w, h, clipX, clipY, clipW, clipH);
  63657. }
  63658. void LowLevelGraphicsSoftwareRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  63659. const Colour& colour, EdgeTable::OversamplingLevel quality)
  63660. {
  63661. for (RectangleList::Iterator i (*clip); i.next();)
  63662. {
  63663. const Rectangle& r = *i.getRectangle();
  63664. clippedFillPathWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(), path, t, colour, quality);
  63665. }
  63666. }
  63667. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  63668. const Colour& colour, EdgeTable::OversamplingLevel quality)
  63669. {
  63670. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  63671. int cx, cy, cw, ch;
  63672. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  63673. {
  63674. EdgeTable edgeTable (0, ch, quality);
  63675. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  63676. int stride, pixelStride;
  63677. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  63678. if (image.getFormat() == Image::RGB)
  63679. {
  63680. jassert (pixelStride == 3);
  63681. SolidColourEdgeTableRenderer <PixelRGB> renderer (pixels, stride, colour);
  63682. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63683. }
  63684. else if (image.getFormat() == Image::ARGB)
  63685. {
  63686. jassert (pixelStride == 4);
  63687. SolidColourEdgeTableRenderer <PixelARGB> renderer (pixels, stride, colour);
  63688. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63689. }
  63690. else if (image.getFormat() == Image::SingleChannel)
  63691. {
  63692. jassert (pixelStride == 1);
  63693. AlphaBitmapRenderer renderer (pixels, stride);
  63694. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63695. }
  63696. image.releasePixelDataReadWrite (pixels);
  63697. }
  63698. }
  63699. void LowLevelGraphicsSoftwareRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  63700. {
  63701. for (RectangleList::Iterator i (*clip); i.next();)
  63702. {
  63703. const Rectangle& r = *i.getRectangle();
  63704. clippedFillPathWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  63705. path, t, gradient, quality);
  63706. }
  63707. }
  63708. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  63709. const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  63710. {
  63711. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  63712. int cx, cy, cw, ch;
  63713. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  63714. {
  63715. int stride, pixelStride;
  63716. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  63717. ColourGradient g2 (gradient);
  63718. const bool isIdentity = g2.transform.isIdentity();
  63719. if (isIdentity)
  63720. {
  63721. g2.x1 += xOffset - cx;
  63722. g2.x2 += xOffset - cx;
  63723. g2.y1 += yOffset - cy;
  63724. g2.y2 += yOffset - cy;
  63725. }
  63726. else
  63727. {
  63728. g2.transform = g2.transform.translated ((float) (xOffset - cx),
  63729. (float) (yOffset - cy));
  63730. }
  63731. int numLookupEntries;
  63732. PixelARGB* const lookupTable = g2.createLookupTable (numLookupEntries);
  63733. jassert (numLookupEntries > 0);
  63734. EdgeTable edgeTable (0, ch, quality);
  63735. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  63736. if (image.getFormat() == Image::RGB)
  63737. {
  63738. jassert (pixelStride == 3);
  63739. if (g2.isRadial)
  63740. {
  63741. if (isIdentity)
  63742. {
  63743. GradientEdgeTableRenderer <PixelRGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63744. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63745. }
  63746. else
  63747. {
  63748. GradientEdgeTableRenderer <PixelRGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63749. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63750. }
  63751. }
  63752. else
  63753. {
  63754. GradientEdgeTableRenderer <PixelRGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63755. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63756. }
  63757. }
  63758. else if (image.getFormat() == Image::ARGB)
  63759. {
  63760. jassert (pixelStride == 4);
  63761. if (g2.isRadial)
  63762. {
  63763. if (isIdentity)
  63764. {
  63765. GradientEdgeTableRenderer <PixelARGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63766. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63767. }
  63768. else
  63769. {
  63770. GradientEdgeTableRenderer <PixelARGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63771. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63772. }
  63773. }
  63774. else
  63775. {
  63776. GradientEdgeTableRenderer <PixelARGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63777. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63778. }
  63779. }
  63780. else if (image.getFormat() == Image::SingleChannel)
  63781. {
  63782. jassertfalse // not done!
  63783. }
  63784. juce_free (lookupTable);
  63785. image.releasePixelDataReadWrite (pixels);
  63786. }
  63787. }
  63788. void LowLevelGraphicsSoftwareRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  63789. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  63790. {
  63791. imageX += xOffset;
  63792. imageY += yOffset;
  63793. for (RectangleList::Iterator i (*clip); i.next();)
  63794. {
  63795. const Rectangle& r = *i.getRectangle();
  63796. clippedFillPathWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  63797. path, transform, sourceImage, imageX, imageY, opacity, quality);
  63798. }
  63799. }
  63800. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithImage (int x, int y, int w, int h, const Path& path, const AffineTransform& transform,
  63801. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  63802. {
  63803. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight()))
  63804. {
  63805. EdgeTable edgeTable (0, h, quality);
  63806. edgeTable.addPath (path, transform.translated ((float) (xOffset - x), (float) (yOffset - y)));
  63807. int stride, pixelStride;
  63808. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  63809. int srcStride, srcPixelStride;
  63810. const uint8* const srcPix = (const uint8*) sourceImage.lockPixelDataReadOnly (x - imageX, y - imageY, w, h, srcStride, srcPixelStride);
  63811. const int alpha = jlimit (0, 255, roundDoubleToInt (opacity * 255.0f));
  63812. if (image.getFormat() == Image::RGB)
  63813. {
  63814. if (sourceImage.getFormat() == Image::RGB)
  63815. {
  63816. ImageFillEdgeTableRenderer <PixelRGB, PixelRGB> renderer (pixels, stride,
  63817. srcPix, srcStride,
  63818. alpha, (PixelRGB*) 0);
  63819. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  63820. }
  63821. else if (sourceImage.getFormat() == Image::ARGB)
  63822. {
  63823. ImageFillEdgeTableRenderer <PixelRGB, PixelARGB> renderer (pixels, stride,
  63824. srcPix, srcStride,
  63825. alpha, (PixelARGB*) 0);
  63826. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  63827. }
  63828. else
  63829. {
  63830. jassertfalse // not done!
  63831. }
  63832. }
  63833. else if (image.getFormat() == Image::ARGB)
  63834. {
  63835. if (sourceImage.getFormat() == Image::RGB)
  63836. {
  63837. ImageFillEdgeTableRenderer <PixelARGB, PixelRGB> renderer (pixels, stride,
  63838. srcPix, srcStride,
  63839. alpha, (PixelRGB*) 0);
  63840. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  63841. }
  63842. else if (sourceImage.getFormat() == Image::ARGB)
  63843. {
  63844. ImageFillEdgeTableRenderer <PixelARGB, PixelARGB> renderer (pixels, stride,
  63845. srcPix, srcStride,
  63846. alpha, (PixelARGB*) 0);
  63847. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  63848. }
  63849. else
  63850. {
  63851. jassertfalse // not done!
  63852. }
  63853. }
  63854. else
  63855. {
  63856. jassertfalse // not done!
  63857. }
  63858. sourceImage.releasePixelDataReadOnly (srcPix);
  63859. image.releasePixelDataReadWrite (pixels);
  63860. }
  63861. }
  63862. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithColour (const Image& clipImage, int x, int y, const Colour& colour)
  63863. {
  63864. x += xOffset;
  63865. y += yOffset;
  63866. for (RectangleList::Iterator i (*clip); i.next();)
  63867. {
  63868. const Rectangle& r = *i.getRectangle();
  63869. clippedFillAlphaChannelWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  63870. clipImage, x, y, colour);
  63871. }
  63872. }
  63873. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& clipImage, int x, int y, const Colour& colour)
  63874. {
  63875. int w = clipImage.getWidth();
  63876. int h = clipImage.getHeight();
  63877. int sx = 0;
  63878. int sy = 0;
  63879. if (x < clipX)
  63880. {
  63881. sx = clipX - x;
  63882. w -= clipX - x;
  63883. x = clipX;
  63884. }
  63885. if (y < clipY)
  63886. {
  63887. sy = clipY - y;
  63888. h -= clipY - y;
  63889. y = clipY;
  63890. }
  63891. if (x + w > clipX + clipW)
  63892. w = clipX + clipW - x;
  63893. if (y + h > clipY + clipH)
  63894. h = clipY + clipH - y;
  63895. if (w > 0 && h > 0)
  63896. {
  63897. int stride, alphaStride, pixelStride;
  63898. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  63899. const uint8* const alphaValues
  63900. = clipImage.lockPixelDataReadOnly (sx, sy, w, h, alphaStride, pixelStride);
  63901. #if JUCE_BIG_ENDIAN
  63902. const uint8* const alphas = alphaValues;
  63903. #else
  63904. const uint8* const alphas = alphaValues + (clipImage.getFormat() == Image::ARGB ? 3 : 0);
  63905. #endif
  63906. if (image.getFormat() == Image::RGB)
  63907. {
  63908. blendAlphaMapRGB (pixels, stride,
  63909. alphas, w, h,
  63910. pixelStride, alphaStride,
  63911. colour);
  63912. }
  63913. else if (image.getFormat() == Image::ARGB)
  63914. {
  63915. blendAlphaMapARGB (pixels, stride,
  63916. alphas, w, h,
  63917. pixelStride, alphaStride,
  63918. colour);
  63919. }
  63920. else
  63921. {
  63922. jassertfalse // not done!
  63923. }
  63924. clipImage.releasePixelDataReadOnly (alphaValues);
  63925. image.releasePixelDataReadWrite (pixels);
  63926. }
  63927. }
  63928. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithGradient (const Image& alphaChannelImage, int imageX, int imageY, const ColourGradient& gradient)
  63929. {
  63930. imageX += xOffset;
  63931. imageY += yOffset;
  63932. for (RectangleList::Iterator i (*clip); i.next();)
  63933. {
  63934. const Rectangle& r = *i.getRectangle();
  63935. clippedFillAlphaChannelWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  63936. alphaChannelImage, imageX, imageY, gradient);
  63937. }
  63938. }
  63939. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithGradient (int x, int y, int w, int h,
  63940. const Image& alphaChannelImage,
  63941. int imageX, int imageY, const ColourGradient& gradient)
  63942. {
  63943. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, alphaChannelImage.getWidth(), alphaChannelImage.getHeight()))
  63944. {
  63945. ColourGradient g2 (gradient);
  63946. g2.x1 += xOffset - x;
  63947. g2.x2 += xOffset - x;
  63948. g2.y1 += yOffset - y;
  63949. g2.y2 += yOffset - y;
  63950. Image temp (g2.isOpaque() ? Image::RGB : Image::ARGB, w, h, true);
  63951. LowLevelGraphicsSoftwareRenderer tempG (temp);
  63952. tempG.fillRectWithGradient (0, 0, w, h, g2);
  63953. clippedFillAlphaChannelWithImage (x, y, w, h,
  63954. alphaChannelImage, imageX, imageY,
  63955. temp, x, y, 1.0f);
  63956. }
  63957. }
  63958. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  63959. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  63960. {
  63961. alphaImageX += xOffset;
  63962. alphaImageY += yOffset;
  63963. fillerImageX += xOffset;
  63964. fillerImageY += yOffset;
  63965. for (RectangleList::Iterator i (*clip); i.next();)
  63966. {
  63967. const Rectangle& r = *i.getRectangle();
  63968. clippedFillAlphaChannelWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  63969. alphaImage, alphaImageX, alphaImageY,
  63970. fillerImage, fillerImageX, fillerImageY, opacity);
  63971. }
  63972. }
  63973. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithImage (int x, int y, int w, int h, const Image& alphaImage, int alphaImageX, int alphaImageY,
  63974. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  63975. {
  63976. if (Rectangle::intersectRectangles (x, y, w, h, alphaImageX, alphaImageY, alphaImage.getWidth(), alphaImage.getHeight())
  63977. && Rectangle::intersectRectangles (x, y, w, h, fillerImageX, fillerImageY, fillerImage.getWidth(), fillerImage.getHeight()))
  63978. {
  63979. int dstStride, dstPixStride;
  63980. uint8* const dstPix = image.lockPixelDataReadWrite (x, y, w, h, dstStride, dstPixStride);
  63981. int srcStride, srcPixStride;
  63982. const uint8* const srcPix = fillerImage.lockPixelDataReadOnly (x - fillerImageX, y - fillerImageY, w, h, srcStride, srcPixStride);
  63983. int maskStride, maskPixStride;
  63984. const uint8* const alpha
  63985. = alphaImage.lockPixelDataReadOnly (x - alphaImageX, y - alphaImageY, w, h, maskStride, maskPixStride);
  63986. #if JUCE_BIG_ENDIAN
  63987. const uint8* const alphaValues = alpha;
  63988. #else
  63989. const uint8* const alphaValues = alpha + (alphaImage.getFormat() == Image::ARGB ? 3 : 0);
  63990. #endif
  63991. const int extraAlpha = jlimit (0, 0x100, roundDoubleToInt (opacity * 256.0f));
  63992. if (image.getFormat() == Image::RGB)
  63993. {
  63994. if (fillerImage.getFormat() == Image::RGB)
  63995. {
  63996. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  63997. }
  63998. else if (fillerImage.getFormat() == Image::ARGB)
  63999. {
  64000. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64001. }
  64002. else
  64003. {
  64004. jassertfalse // not done!
  64005. }
  64006. }
  64007. else if (image.getFormat() == Image::ARGB)
  64008. {
  64009. if (fillerImage.getFormat() == Image::RGB)
  64010. {
  64011. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64012. }
  64013. else if (fillerImage.getFormat() == Image::ARGB)
  64014. {
  64015. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64016. }
  64017. else
  64018. {
  64019. jassertfalse // not done!
  64020. }
  64021. }
  64022. else
  64023. {
  64024. jassertfalse // not done!
  64025. }
  64026. alphaImage.releasePixelDataReadOnly (alphaValues);
  64027. fillerImage.releasePixelDataReadOnly (srcPix);
  64028. image.releasePixelDataReadWrite (dstPix);
  64029. }
  64030. }
  64031. void LowLevelGraphicsSoftwareRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  64032. {
  64033. dx += xOffset;
  64034. dy += yOffset;
  64035. for (RectangleList::Iterator i (*clip); i.next();)
  64036. {
  64037. const Rectangle& r = *i.getRectangle();
  64038. clippedBlendImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64039. sourceImage, dx, dy, dw, dh, sx, sy, opacity);
  64040. }
  64041. }
  64042. void LowLevelGraphicsSoftwareRenderer::clippedBlendImage (int clipX, int clipY, int clipW, int clipH,
  64043. const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  64044. {
  64045. if (dx < clipX)
  64046. {
  64047. sx += clipX - dx;
  64048. dw -= clipX - dx;
  64049. dx = clipX;
  64050. }
  64051. if (dy < clipY)
  64052. {
  64053. sy += clipY - dy;
  64054. dh -= clipY - dy;
  64055. dy = clipY;
  64056. }
  64057. if (dx + dw > clipX + clipW)
  64058. dw = clipX + clipW - dx;
  64059. if (dy + dh > clipY + clipH)
  64060. dh = clipY + clipH - dy;
  64061. if (dw <= 0 || dh <= 0)
  64062. return;
  64063. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  64064. if (alpha == 0)
  64065. return;
  64066. int dstStride, dstPixelStride;
  64067. uint8* const dstPixels = image.lockPixelDataReadWrite (dx, dy, dw, dh, dstStride, dstPixelStride);
  64068. int srcStride, srcPixelStride;
  64069. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (sx, sy, dw, dh, srcStride, srcPixelStride);
  64070. if (image.getFormat() == Image::ARGB)
  64071. {
  64072. if (sourceImage.getFormat() == Image::ARGB)
  64073. {
  64074. overlayImage ((PixelARGB*) dstPixels, dstStride,
  64075. (PixelARGB*) srcPixels, srcStride,
  64076. dw, dh, alpha);
  64077. }
  64078. else if (sourceImage.getFormat() == Image::RGB)
  64079. {
  64080. overlayImage ((PixelARGB*) dstPixels, dstStride,
  64081. (PixelRGB*) srcPixels, srcStride,
  64082. dw, dh, alpha);
  64083. }
  64084. else
  64085. {
  64086. jassertfalse
  64087. }
  64088. }
  64089. else if (image.getFormat() == Image::RGB)
  64090. {
  64091. if (sourceImage.getFormat() == Image::ARGB)
  64092. {
  64093. overlayImage ((PixelRGB*) dstPixels, dstStride,
  64094. (PixelARGB*) srcPixels, srcStride,
  64095. dw, dh, alpha);
  64096. }
  64097. else if (sourceImage.getFormat() == Image::RGB)
  64098. {
  64099. overlayImage ((PixelRGB*) dstPixels, dstStride,
  64100. (PixelRGB*) srcPixels, srcStride,
  64101. dw, dh, alpha);
  64102. }
  64103. else
  64104. {
  64105. jassertfalse
  64106. }
  64107. }
  64108. else
  64109. {
  64110. jassertfalse
  64111. }
  64112. image.releasePixelDataReadWrite (dstPixels);
  64113. sourceImage.releasePixelDataReadOnly (srcPixels);
  64114. }
  64115. void LowLevelGraphicsSoftwareRenderer::blendImageRescaling (const Image& sourceImage,
  64116. int dx, int dy, int dw, int dh,
  64117. int sx, int sy, int sw, int sh,
  64118. float alpha,
  64119. const Graphics::ResamplingQuality quality)
  64120. {
  64121. if (sw > 0 && sh > 0)
  64122. {
  64123. if (sw == dw && sh == dh)
  64124. {
  64125. blendImage (sourceImage,
  64126. dx, dy, dw, dh,
  64127. sx, sy, alpha);
  64128. }
  64129. else
  64130. {
  64131. blendImageWarping (sourceImage,
  64132. sx, sy, sw, sh,
  64133. AffineTransform::translation ((float) -sx,
  64134. (float) -sy)
  64135. .scaled (dw / (float) sw,
  64136. dh / (float) sh)
  64137. .translated ((float) dx,
  64138. (float) dy),
  64139. alpha,
  64140. quality);
  64141. }
  64142. }
  64143. }
  64144. void LowLevelGraphicsSoftwareRenderer::blendImageWarping (const Image& sourceImage,
  64145. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  64146. const AffineTransform& t,
  64147. float opacity,
  64148. const Graphics::ResamplingQuality quality)
  64149. {
  64150. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  64151. for (RectangleList::Iterator i (*clip); i.next();)
  64152. {
  64153. const Rectangle& r = *i.getRectangle();
  64154. clippedBlendImageWarping (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64155. sourceImage, srcClipX, srcClipY, srcClipW, srcClipH,
  64156. transform, opacity, quality);
  64157. }
  64158. }
  64159. void LowLevelGraphicsSoftwareRenderer::clippedBlendImageWarping (int destClipX, int destClipY, int destClipW, int destClipH,
  64160. const Image& sourceImage,
  64161. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  64162. const AffineTransform& transform,
  64163. float opacity,
  64164. const Graphics::ResamplingQuality quality)
  64165. {
  64166. if (opacity > 0 && destClipW > 0 && destClipH > 0 && ! transform.isSingularity())
  64167. {
  64168. Rectangle::intersectRectangles (srcClipX, srcClipY, srcClipW, srcClipH,
  64169. 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  64170. if (srcClipW <= 0 || srcClipH <= 0)
  64171. return;
  64172. jassert (srcClipX >= 0 && srcClipY >= 0);
  64173. Path imageBounds;
  64174. imageBounds.addRectangle ((float) srcClipX, (float) srcClipY, (float) srcClipW, (float) srcClipH);
  64175. imageBounds.applyTransform (transform);
  64176. float imX, imY, imW, imH;
  64177. imageBounds.getBounds (imX, imY, imW, imH);
  64178. if (Rectangle::intersectRectangles (destClipX, destClipY, destClipW, destClipH,
  64179. (int) floorf (imX),
  64180. (int) floorf (imY),
  64181. 1 + roundDoubleToInt (imW),
  64182. 1 + roundDoubleToInt (imH)))
  64183. {
  64184. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  64185. float srcX1 = (float) destClipX;
  64186. float srcY1 = (float) destClipY;
  64187. float srcX2 = (float) (destClipX + destClipW);
  64188. float srcY2 = srcY1;
  64189. float srcX3 = srcX1;
  64190. float srcY3 = (float) (destClipY + destClipH);
  64191. AffineTransform inverse (transform.inverted());
  64192. inverse.transformPoint (srcX1, srcY1);
  64193. inverse.transformPoint (srcX2, srcY2);
  64194. inverse.transformPoint (srcX3, srcY3);
  64195. const double lineDX = (double) (srcX3 - srcX1) / destClipH;
  64196. const double lineDY = (double) (srcY3 - srcY1) / destClipH;
  64197. const double pixelDX = (double) (srcX2 - srcX1) / destClipW;
  64198. const double pixelDY = (double) (srcY2 - srcY1) / destClipW;
  64199. if (image.getFormat() == Image::ARGB)
  64200. {
  64201. if (sourceImage.getFormat() == Image::ARGB)
  64202. {
  64203. transformedImageRender (image, sourceImage,
  64204. destClipX, destClipY, destClipW, destClipH,
  64205. srcClipX, srcClipY, srcClipW, srcClipH,
  64206. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64207. alpha, quality, (PixelARGB*)0, (PixelARGB*)0);
  64208. }
  64209. else if (sourceImage.getFormat() == Image::RGB)
  64210. {
  64211. transformedImageRender (image, sourceImage,
  64212. destClipX, destClipY, destClipW, destClipH,
  64213. srcClipX, srcClipY, srcClipW, srcClipH,
  64214. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64215. alpha, quality, (PixelARGB*)0, (PixelRGB*)0);
  64216. }
  64217. else
  64218. {
  64219. jassertfalse
  64220. }
  64221. }
  64222. else if (image.getFormat() == Image::RGB)
  64223. {
  64224. if (sourceImage.getFormat() == Image::ARGB)
  64225. {
  64226. transformedImageRender (image, sourceImage,
  64227. destClipX, destClipY, destClipW, destClipH,
  64228. srcClipX, srcClipY, srcClipW, srcClipH,
  64229. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64230. alpha, quality, (PixelRGB*)0, (PixelARGB*)0);
  64231. }
  64232. else if (sourceImage.getFormat() == Image::RGB)
  64233. {
  64234. transformedImageRender (image, sourceImage,
  64235. destClipX, destClipY, destClipW, destClipH,
  64236. srcClipX, srcClipY, srcClipW, srcClipH,
  64237. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64238. alpha, quality, (PixelRGB*)0, (PixelRGB*)0);
  64239. }
  64240. else
  64241. {
  64242. jassertfalse
  64243. }
  64244. }
  64245. else
  64246. {
  64247. jassertfalse
  64248. }
  64249. }
  64250. }
  64251. }
  64252. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  64253. {
  64254. x1 += xOffset;
  64255. y1 += yOffset;
  64256. x2 += xOffset;
  64257. y2 += yOffset;
  64258. for (RectangleList::Iterator i (*clip); i.next();)
  64259. {
  64260. const Rectangle& r = *i.getRectangle();
  64261. clippedDrawLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64262. x1, y1, x2, y2, colour);
  64263. }
  64264. }
  64265. void LowLevelGraphicsSoftwareRenderer::clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour)
  64266. {
  64267. if (clipW > 0 && clipH > 0)
  64268. {
  64269. if (x1 == x2)
  64270. {
  64271. if (y2 < y1)
  64272. swapVariables (y1, y2);
  64273. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (x1), y1, y2, colour);
  64274. }
  64275. else if (y1 == y2)
  64276. {
  64277. if (x2 < x1)
  64278. swapVariables (x1, x2);
  64279. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (y1), x1, x2, colour);
  64280. }
  64281. else
  64282. {
  64283. double gradient = (y2 - y1) / (x2 - x1);
  64284. if (fabs (gradient) > 1.0)
  64285. {
  64286. gradient = 1.0 / gradient;
  64287. int y = roundDoubleToInt (y1);
  64288. const int startY = y;
  64289. int endY = roundDoubleToInt (y2);
  64290. if (y > endY)
  64291. swapVariables (y, endY);
  64292. while (y < endY)
  64293. {
  64294. const double x = x1 + gradient * (y - startY);
  64295. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, y, x, x + 1.0, colour);
  64296. ++y;
  64297. }
  64298. }
  64299. else
  64300. {
  64301. int x = roundDoubleToInt (x1);
  64302. const int startX = x;
  64303. int endX = roundDoubleToInt (x2);
  64304. if (x > endX)
  64305. swapVariables (x, endX);
  64306. while (x < endX)
  64307. {
  64308. const double y = y1 + gradient * (x - startX);
  64309. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, x, y, y + 1.0, colour);
  64310. ++x;
  64311. }
  64312. }
  64313. }
  64314. }
  64315. }
  64316. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  64317. {
  64318. for (RectangleList::Iterator i (*clip); i.next();)
  64319. {
  64320. const Rectangle& r = *i.getRectangle();
  64321. clippedDrawVerticalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64322. x + xOffset, top + yOffset, bottom + yOffset, col);
  64323. }
  64324. }
  64325. void LowLevelGraphicsSoftwareRenderer::clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH,
  64326. const int x, double top, double bottom, const Colour& col)
  64327. {
  64328. jassert (top <= bottom);
  64329. if (((unsigned int) (x - clipX)) < (unsigned int) clipW
  64330. && top < clipY + clipH
  64331. && bottom > clipY
  64332. && clipW > 0)
  64333. {
  64334. if (top < clipY)
  64335. top = clipY;
  64336. if (bottom > clipY + clipH)
  64337. bottom = clipY + clipH;
  64338. if (bottom > top)
  64339. drawVertical (x, top, bottom, col);
  64340. }
  64341. }
  64342. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  64343. {
  64344. for (RectangleList::Iterator i (*clip); i.next();)
  64345. {
  64346. const Rectangle& r = *i.getRectangle();
  64347. clippedDrawHorizontalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64348. y + yOffset, left + xOffset, right + xOffset, col);
  64349. }
  64350. }
  64351. void LowLevelGraphicsSoftwareRenderer::clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH,
  64352. const int y, double left, double right, const Colour& col)
  64353. {
  64354. jassert (left <= right);
  64355. if (((unsigned int) (y - clipY)) < (unsigned int) clipH
  64356. && left < clipX + clipW
  64357. && right > clipX
  64358. && clipW > 0)
  64359. {
  64360. if (left < clipX)
  64361. left = clipX;
  64362. if (right > clipX + clipW)
  64363. right = clipX + clipW;
  64364. if (right > left)
  64365. drawHorizontal (y, left, right, col);
  64366. }
  64367. }
  64368. void LowLevelGraphicsSoftwareRenderer::drawVertical (const int x,
  64369. const double top,
  64370. const double bottom,
  64371. const Colour& col)
  64372. {
  64373. int wholeStart = (int) top;
  64374. const int wholeEnd = (int) bottom;
  64375. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  64376. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  64377. if (totalPixels <= 0)
  64378. return;
  64379. int lineStride, dstPixelStride;
  64380. uint8* const dstPixels = image.lockPixelDataReadWrite (x, wholeStart, 1, totalPixels, lineStride, dstPixelStride);
  64381. uint8* dest = dstPixels;
  64382. PixelARGB colour (col.getPixelARGB());
  64383. if (wholeEnd == wholeStart)
  64384. {
  64385. if (image.getFormat() == Image::ARGB)
  64386. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64387. else if (image.getFormat() == Image::RGB)
  64388. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64389. else
  64390. {
  64391. jassertfalse
  64392. }
  64393. }
  64394. else
  64395. {
  64396. if (image.getFormat() == Image::ARGB)
  64397. {
  64398. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64399. ++wholeStart;
  64400. dest += lineStride;
  64401. if (colour.getAlpha() == 0xff)
  64402. {
  64403. while (wholeEnd > wholeStart)
  64404. {
  64405. ((PixelARGB*) dest)->set (colour);
  64406. ++wholeStart;
  64407. dest += lineStride;
  64408. }
  64409. }
  64410. else
  64411. {
  64412. while (wholeEnd > wholeStart)
  64413. {
  64414. ((PixelARGB*) dest)->blend (colour);
  64415. ++wholeStart;
  64416. dest += lineStride;
  64417. }
  64418. }
  64419. if (lastAlpha > 0)
  64420. {
  64421. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  64422. }
  64423. }
  64424. else if (image.getFormat() == Image::RGB)
  64425. {
  64426. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64427. ++wholeStart;
  64428. dest += lineStride;
  64429. if (colour.getAlpha() == 0xff)
  64430. {
  64431. while (wholeEnd > wholeStart)
  64432. {
  64433. ((PixelRGB*) dest)->set (colour);
  64434. ++wholeStart;
  64435. dest += lineStride;
  64436. }
  64437. }
  64438. else
  64439. {
  64440. while (wholeEnd > wholeStart)
  64441. {
  64442. ((PixelRGB*) dest)->blend (colour);
  64443. ++wholeStart;
  64444. dest += lineStride;
  64445. }
  64446. }
  64447. if (lastAlpha > 0)
  64448. {
  64449. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  64450. }
  64451. }
  64452. else
  64453. {
  64454. jassertfalse
  64455. }
  64456. }
  64457. image.releasePixelDataReadWrite (dstPixels);
  64458. }
  64459. void LowLevelGraphicsSoftwareRenderer::drawHorizontal (const int y,
  64460. const double top,
  64461. const double bottom,
  64462. const Colour& col)
  64463. {
  64464. int wholeStart = (int) top;
  64465. const int wholeEnd = (int) bottom;
  64466. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  64467. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  64468. if (totalPixels <= 0)
  64469. return;
  64470. int lineStride, dstPixelStride;
  64471. uint8* const dstPixels = image.lockPixelDataReadWrite (wholeStart, y, totalPixels, 1, lineStride, dstPixelStride);
  64472. uint8* dest = dstPixels;
  64473. PixelARGB colour (col.getPixelARGB());
  64474. if (wholeEnd == wholeStart)
  64475. {
  64476. if (image.getFormat() == Image::ARGB)
  64477. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64478. else if (image.getFormat() == Image::RGB)
  64479. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64480. else
  64481. {
  64482. jassertfalse
  64483. }
  64484. }
  64485. else
  64486. {
  64487. if (image.getFormat() == Image::ARGB)
  64488. {
  64489. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64490. dest += dstPixelStride;
  64491. ++wholeStart;
  64492. if (colour.getAlpha() == 0xff)
  64493. {
  64494. while (wholeEnd > wholeStart)
  64495. {
  64496. ((PixelARGB*) dest)->set (colour);
  64497. dest += dstPixelStride;
  64498. ++wholeStart;
  64499. }
  64500. }
  64501. else
  64502. {
  64503. while (wholeEnd > wholeStart)
  64504. {
  64505. ((PixelARGB*) dest)->blend (colour);
  64506. dest += dstPixelStride;
  64507. ++wholeStart;
  64508. }
  64509. }
  64510. if (lastAlpha > 0)
  64511. {
  64512. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  64513. }
  64514. }
  64515. else if (image.getFormat() == Image::RGB)
  64516. {
  64517. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64518. dest += dstPixelStride;
  64519. ++wholeStart;
  64520. if (colour.getAlpha() == 0xff)
  64521. {
  64522. while (wholeEnd > wholeStart)
  64523. {
  64524. ((PixelRGB*) dest)->set (colour);
  64525. dest += dstPixelStride;
  64526. ++wholeStart;
  64527. }
  64528. }
  64529. else
  64530. {
  64531. while (wholeEnd > wholeStart)
  64532. {
  64533. ((PixelRGB*) dest)->blend (colour);
  64534. dest += dstPixelStride;
  64535. ++wholeStart;
  64536. }
  64537. }
  64538. if (lastAlpha > 0)
  64539. {
  64540. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  64541. }
  64542. }
  64543. else
  64544. {
  64545. jassertfalse
  64546. }
  64547. }
  64548. image.releasePixelDataReadWrite (dstPixels);
  64549. }
  64550. END_JUCE_NAMESPACE
  64551. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  64552. /********* Start of inlined file: juce_RectanglePlacement.cpp *********/
  64553. BEGIN_JUCE_NAMESPACE
  64554. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  64555. : flags (other.flags)
  64556. {
  64557. }
  64558. const RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  64559. {
  64560. flags = other.flags;
  64561. return *this;
  64562. }
  64563. void RectanglePlacement::applyTo (double& x, double& y,
  64564. double& w, double& h,
  64565. const double dx, const double dy,
  64566. const double dw, const double dh) const throw()
  64567. {
  64568. if (w == 0 || h == 0)
  64569. return;
  64570. if ((flags & stretchToFit) != 0)
  64571. {
  64572. x = dx;
  64573. y = dy;
  64574. w = dw;
  64575. h = dh;
  64576. }
  64577. else
  64578. {
  64579. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  64580. : jmin (dw / w, dh / h);
  64581. if ((flags & onlyReduceInSize) != 0)
  64582. scale = jmin (scale, 1.0);
  64583. if ((flags & onlyIncreaseInSize) != 0)
  64584. scale = jmax (scale, 1.0);
  64585. w *= scale;
  64586. h *= scale;
  64587. if ((flags & xLeft) != 0)
  64588. x = dx;
  64589. else if ((flags & xRight) != 0)
  64590. x = dx + dw - w;
  64591. else
  64592. x = dx + (dw - w) * 0.5;
  64593. if ((flags & yTop) != 0)
  64594. y = dy;
  64595. else if ((flags & yBottom) != 0)
  64596. y = dy + dh - h;
  64597. else
  64598. y = dy + (dh - h) * 0.5;
  64599. }
  64600. }
  64601. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  64602. float w, float h,
  64603. const float dx, const float dy,
  64604. const float dw, const float dh) const throw()
  64605. {
  64606. if (w == 0 || h == 0)
  64607. return AffineTransform::identity;
  64608. const float scaleX = dw / w;
  64609. const float scaleY = dh / h;
  64610. if ((flags & stretchToFit) != 0)
  64611. return AffineTransform::translation (-x, -y)
  64612. .scaled (scaleX, scaleY)
  64613. .translated (dx, dy);
  64614. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  64615. : jmin (scaleX, scaleY);
  64616. if ((flags & onlyReduceInSize) != 0)
  64617. scale = jmin (scale, 1.0f);
  64618. if ((flags & onlyIncreaseInSize) != 0)
  64619. scale = jmax (scale, 1.0f);
  64620. w *= scale;
  64621. h *= scale;
  64622. float newX = dx;
  64623. if ((flags & xRight) != 0)
  64624. newX += dw - w; // right
  64625. else if ((flags & xLeft) == 0)
  64626. newX += (dw - w) / 2.0f; // centre
  64627. float newY = dy;
  64628. if ((flags & yBottom) != 0)
  64629. newY += dh - h; // bottom
  64630. else if ((flags & yTop) == 0)
  64631. newY += (dh - h) / 2.0f; // centre
  64632. return AffineTransform::translation (-x, -y)
  64633. .scaled (scale, scale)
  64634. .translated (newX, newY);
  64635. }
  64636. END_JUCE_NAMESPACE
  64637. /********* End of inlined file: juce_RectanglePlacement.cpp *********/
  64638. /********* Start of inlined file: juce_Drawable.cpp *********/
  64639. BEGIN_JUCE_NAMESPACE
  64640. Drawable::Drawable()
  64641. {
  64642. }
  64643. Drawable::~Drawable()
  64644. {
  64645. }
  64646. void Drawable::drawAt (Graphics& g, const float x, const float y) const
  64647. {
  64648. draw (g, AffineTransform::translation (x, y));
  64649. }
  64650. void Drawable::drawWithin (Graphics& g,
  64651. const int destX,
  64652. const int destY,
  64653. const int destW,
  64654. const int destH,
  64655. const RectanglePlacement& placement) const
  64656. {
  64657. if (destW > 0 && destH > 0)
  64658. {
  64659. float x, y, w, h;
  64660. getBounds (x, y, w, h);
  64661. draw (g, placement.getTransformToFit (x, y, w, h,
  64662. (float) destX, (float) destY,
  64663. (float) destW, (float) destH));
  64664. }
  64665. }
  64666. Drawable* Drawable::createFromImageData (const void* data, const int numBytes)
  64667. {
  64668. Drawable* result = 0;
  64669. Image* const image = ImageFileFormat::loadFrom (data, numBytes);
  64670. if (image != 0)
  64671. {
  64672. DrawableImage* const di = new DrawableImage();
  64673. di->setImage (image, true);
  64674. result = di;
  64675. }
  64676. else
  64677. {
  64678. const String asString (String::createStringFromData (data, numBytes));
  64679. XmlDocument doc (asString);
  64680. XmlElement* const outer = doc.getDocumentElement (true);
  64681. if (outer != 0 && outer->hasTagName (T("svg")))
  64682. {
  64683. XmlElement* const svg = doc.getDocumentElement();
  64684. if (svg != 0)
  64685. {
  64686. result = Drawable::createFromSVG (*svg);
  64687. delete svg;
  64688. }
  64689. }
  64690. delete outer;
  64691. }
  64692. return result;
  64693. }
  64694. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  64695. {
  64696. MemoryBlock mb;
  64697. dataSource.readIntoMemoryBlock (mb);
  64698. return createFromImageData (mb.getData(), mb.getSize());
  64699. }
  64700. Drawable* Drawable::createFromImageFile (const File& file)
  64701. {
  64702. FileInputStream* fin = file.createInputStream();
  64703. if (fin == 0)
  64704. return 0;
  64705. Drawable* d = createFromImageDataStream (*fin);
  64706. delete fin;
  64707. return d;
  64708. }
  64709. END_JUCE_NAMESPACE
  64710. /********* End of inlined file: juce_Drawable.cpp *********/
  64711. /********* Start of inlined file: juce_DrawableComposite.cpp *********/
  64712. BEGIN_JUCE_NAMESPACE
  64713. DrawableComposite::DrawableComposite()
  64714. {
  64715. }
  64716. DrawableComposite::~DrawableComposite()
  64717. {
  64718. }
  64719. void DrawableComposite::insertDrawable (Drawable* drawable,
  64720. const AffineTransform& transform,
  64721. const int index)
  64722. {
  64723. if (drawable != 0)
  64724. {
  64725. if (! drawables.contains (drawable))
  64726. {
  64727. drawables.insert (index, drawable);
  64728. if (transform.isIdentity())
  64729. transforms.insert (index, 0);
  64730. else
  64731. transforms.insert (index, new AffineTransform (transform));
  64732. }
  64733. else
  64734. {
  64735. jassertfalse // trying to add a drawable that's already in here!
  64736. }
  64737. }
  64738. }
  64739. void DrawableComposite::insertDrawable (const Drawable& drawable,
  64740. const AffineTransform& transform,
  64741. const int index)
  64742. {
  64743. insertDrawable (drawable.createCopy(), transform, index);
  64744. }
  64745. void DrawableComposite::removeDrawable (const int index)
  64746. {
  64747. drawables.remove (index);
  64748. transforms.remove (index);
  64749. }
  64750. void DrawableComposite::bringToFront (const int index)
  64751. {
  64752. if (index >= 0 && index < drawables.size() - 1)
  64753. {
  64754. drawables.move (index, -1);
  64755. transforms.move (index, -1);
  64756. }
  64757. }
  64758. void DrawableComposite::draw (Graphics& g, const AffineTransform& transform) const
  64759. {
  64760. for (int i = 0; i < drawables.size(); ++i)
  64761. {
  64762. const AffineTransform* const t = transforms.getUnchecked(i);
  64763. drawables.getUnchecked(i)->draw (g, t == 0 ? transform
  64764. : t->followedBy (transform));
  64765. }
  64766. }
  64767. void DrawableComposite::getBounds (float& x, float& y, float& width, float& height) const
  64768. {
  64769. Path totalPath;
  64770. for (int i = 0; i < drawables.size(); ++i)
  64771. {
  64772. drawables.getUnchecked(i)->getBounds (x, y, width, height);
  64773. if (width > 0.0f && height > 0.0f)
  64774. {
  64775. Path outline;
  64776. outline.addRectangle (x, y, width, height);
  64777. const AffineTransform* const t = transforms.getUnchecked(i);
  64778. if (t == 0)
  64779. totalPath.addPath (outline);
  64780. else
  64781. totalPath.addPath (outline, *t);
  64782. }
  64783. }
  64784. totalPath.getBounds (x, y, width, height);
  64785. }
  64786. bool DrawableComposite::hitTest (float x, float y) const
  64787. {
  64788. for (int i = 0; i < drawables.size(); ++i)
  64789. {
  64790. float tx = x;
  64791. float ty = y;
  64792. const AffineTransform* const t = transforms.getUnchecked(i);
  64793. if (t != 0)
  64794. t->inverted().transformPoint (tx, ty);
  64795. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  64796. return true;
  64797. }
  64798. return false;
  64799. }
  64800. Drawable* DrawableComposite::createCopy() const
  64801. {
  64802. DrawableComposite* const dc = new DrawableComposite();
  64803. for (int i = 0; i < drawables.size(); ++i)
  64804. {
  64805. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  64806. const AffineTransform* const t = transforms.getUnchecked(i);
  64807. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  64808. }
  64809. return dc;
  64810. }
  64811. END_JUCE_NAMESPACE
  64812. /********* End of inlined file: juce_DrawableComposite.cpp *********/
  64813. /********* Start of inlined file: juce_DrawableImage.cpp *********/
  64814. BEGIN_JUCE_NAMESPACE
  64815. DrawableImage::DrawableImage()
  64816. : image (0),
  64817. canDeleteImage (false),
  64818. opacity (1.0f),
  64819. overlayColour (0x00000000)
  64820. {
  64821. }
  64822. DrawableImage::~DrawableImage()
  64823. {
  64824. clearImage();
  64825. }
  64826. void DrawableImage::clearImage()
  64827. {
  64828. if (canDeleteImage && image != 0)
  64829. {
  64830. if (ImageCache::isImageInCache (image))
  64831. ImageCache::release (image);
  64832. else
  64833. delete image;
  64834. }
  64835. image = 0;
  64836. }
  64837. void DrawableImage::setImage (const Image& imageToCopy)
  64838. {
  64839. clearImage();
  64840. image = new Image (imageToCopy);
  64841. canDeleteImage = true;
  64842. }
  64843. void DrawableImage::setImage (Image* imageToUse,
  64844. const bool releaseWhenNotNeeded)
  64845. {
  64846. clearImage();
  64847. image = imageToUse;
  64848. canDeleteImage = releaseWhenNotNeeded;
  64849. }
  64850. void DrawableImage::setOpacity (const float newOpacity)
  64851. {
  64852. opacity = newOpacity;
  64853. }
  64854. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  64855. {
  64856. overlayColour = newOverlayColour;
  64857. }
  64858. void DrawableImage::draw (Graphics& g, const AffineTransform& transform) const
  64859. {
  64860. if (image != 0)
  64861. {
  64862. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  64863. if (opacity > 0.0f && ! overlayColour.isOpaque())
  64864. {
  64865. g.setColour (oldColour.withMultipliedAlpha (opacity));
  64866. g.drawImageTransformed (image,
  64867. 0, 0, image->getWidth(), image->getHeight(),
  64868. transform, false);
  64869. }
  64870. if (! overlayColour.isTransparent())
  64871. {
  64872. g.setColour (overlayColour.withMultipliedAlpha (oldColour.getFloatAlpha()));
  64873. g.drawImageTransformed (image,
  64874. 0, 0, image->getWidth(), image->getHeight(),
  64875. transform, true);
  64876. }
  64877. g.setColour (oldColour);
  64878. }
  64879. }
  64880. void DrawableImage::getBounds (float& x, float& y, float& width, float& height) const
  64881. {
  64882. x = 0.0f;
  64883. y = 0.0f;
  64884. width = 0.0f;
  64885. height = 0.0f;
  64886. if (image != 0)
  64887. {
  64888. width = (float) image->getWidth();
  64889. height = (float) image->getHeight();
  64890. }
  64891. }
  64892. bool DrawableImage::hitTest (float x, float y) const
  64893. {
  64894. return image != 0
  64895. && x >= 0.0f
  64896. && y >= 0.0f
  64897. && x < image->getWidth()
  64898. && y < image->getHeight()
  64899. && image->getPixelAt (roundFloatToInt (x), roundFloatToInt (y)).getAlpha() >= 127;
  64900. }
  64901. Drawable* DrawableImage::createCopy() const
  64902. {
  64903. DrawableImage* const di = new DrawableImage();
  64904. di->opacity = opacity;
  64905. di->overlayColour = overlayColour;
  64906. if (image != 0)
  64907. {
  64908. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  64909. {
  64910. di->setImage (*image);
  64911. }
  64912. else
  64913. {
  64914. ImageCache::incReferenceCount (image);
  64915. di->setImage (image, true);
  64916. }
  64917. }
  64918. return di;
  64919. }
  64920. END_JUCE_NAMESPACE
  64921. /********* End of inlined file: juce_DrawableImage.cpp *********/
  64922. /********* Start of inlined file: juce_DrawablePath.cpp *********/
  64923. BEGIN_JUCE_NAMESPACE
  64924. DrawablePath::DrawablePath()
  64925. : fillBrush (new SolidColourBrush (Colours::black)),
  64926. strokeBrush (0),
  64927. strokeType (0.0f)
  64928. {
  64929. }
  64930. DrawablePath::~DrawablePath()
  64931. {
  64932. delete fillBrush;
  64933. delete strokeBrush;
  64934. }
  64935. void DrawablePath::setPath (const Path& newPath)
  64936. {
  64937. path = newPath;
  64938. updateOutline();
  64939. }
  64940. void DrawablePath::setSolidFill (const Colour& newColour)
  64941. {
  64942. delete fillBrush;
  64943. fillBrush = new SolidColourBrush (newColour);
  64944. }
  64945. void DrawablePath::setFillBrush (const Brush& newBrush)
  64946. {
  64947. delete fillBrush;
  64948. fillBrush = newBrush.createCopy();
  64949. }
  64950. void DrawablePath::setOutline (const float thickness, const Colour& colour)
  64951. {
  64952. strokeType = PathStrokeType (thickness);
  64953. delete strokeBrush;
  64954. strokeBrush = new SolidColourBrush (colour);
  64955. updateOutline();
  64956. }
  64957. void DrawablePath::setOutline (const PathStrokeType& strokeType_, const Brush& newStrokeBrush)
  64958. {
  64959. strokeType = strokeType_;
  64960. delete strokeBrush;
  64961. strokeBrush = newStrokeBrush.createCopy();
  64962. updateOutline();
  64963. }
  64964. void DrawablePath::draw (Graphics& g, const AffineTransform& transform) const
  64965. {
  64966. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  64967. const float currentOpacity = oldColour.getFloatAlpha();
  64968. {
  64969. Brush* const tempBrush = fillBrush->createCopy();
  64970. tempBrush->applyTransform (transform);
  64971. tempBrush->multiplyOpacity (currentOpacity);
  64972. g.setBrush (tempBrush);
  64973. g.fillPath (path, transform);
  64974. delete tempBrush;
  64975. }
  64976. if (strokeBrush != 0 && strokeType.getStrokeThickness() > 0.0f)
  64977. {
  64978. Brush* const tempBrush = strokeBrush->createCopy();
  64979. tempBrush->applyTransform (transform);
  64980. tempBrush->multiplyOpacity (currentOpacity);
  64981. g.setBrush (tempBrush);
  64982. g.fillPath (outline, transform);
  64983. delete tempBrush;
  64984. }
  64985. g.setColour (oldColour);
  64986. }
  64987. void DrawablePath::updateOutline()
  64988. {
  64989. outline.clear();
  64990. strokeType.createStrokedPath (outline, path, AffineTransform::identity, 4.0f);
  64991. }
  64992. void DrawablePath::getBounds (float& x, float& y, float& width, float& height) const
  64993. {
  64994. if (strokeType.getStrokeThickness() > 0.0f)
  64995. outline.getBounds (x, y, width, height);
  64996. else
  64997. path.getBounds (x, y, width, height);
  64998. }
  64999. bool DrawablePath::hitTest (float x, float y) const
  65000. {
  65001. return path.contains (x, y)
  65002. || outline.contains (x, y);
  65003. }
  65004. Drawable* DrawablePath::createCopy() const
  65005. {
  65006. DrawablePath* const dp = new DrawablePath();
  65007. dp->path = path;
  65008. dp->setFillBrush (*fillBrush);
  65009. if (strokeBrush != 0)
  65010. dp->setOutline (strokeType, *strokeBrush);
  65011. return dp;
  65012. }
  65013. END_JUCE_NAMESPACE
  65014. /********* End of inlined file: juce_DrawablePath.cpp *********/
  65015. /********* Start of inlined file: juce_DrawableText.cpp *********/
  65016. BEGIN_JUCE_NAMESPACE
  65017. DrawableText::DrawableText()
  65018. : colour (Colours::white)
  65019. {
  65020. }
  65021. DrawableText::~DrawableText()
  65022. {
  65023. }
  65024. void DrawableText::setText (const GlyphArrangement& newText)
  65025. {
  65026. text = newText;
  65027. }
  65028. void DrawableText::setText (const String& newText, const Font& fontToUse)
  65029. {
  65030. text.clear();
  65031. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  65032. }
  65033. void DrawableText::setColour (const Colour& newColour)
  65034. {
  65035. colour = newColour;
  65036. }
  65037. void DrawableText::draw (Graphics& g, const AffineTransform& transform) const
  65038. {
  65039. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  65040. g.setColour (colour.withMultipliedAlpha (oldColour.getFloatAlpha()));
  65041. text.draw (g, transform);
  65042. g.setColour (oldColour);
  65043. }
  65044. void DrawableText::getBounds (float& x, float& y, float& width, float& height) const
  65045. {
  65046. text.getBoundingBox (0, -1, x, y, width, height, false); // (really returns top, left, bottom, right)
  65047. width -= x;
  65048. height -= y;
  65049. }
  65050. bool DrawableText::hitTest (float x, float y) const
  65051. {
  65052. return text.findGlyphIndexAt (x, y) >= 0;
  65053. }
  65054. Drawable* DrawableText::createCopy() const
  65055. {
  65056. DrawableText* const dt = new DrawableText();
  65057. dt->text = text;
  65058. dt->colour = colour;
  65059. return dt;
  65060. }
  65061. END_JUCE_NAMESPACE
  65062. /********* End of inlined file: juce_DrawableText.cpp *********/
  65063. /********* Start of inlined file: juce_SVGParser.cpp *********/
  65064. BEGIN_JUCE_NAMESPACE
  65065. class SVGState
  65066. {
  65067. public:
  65068. SVGState (const XmlElement* const topLevel)
  65069. : topLevelXml (topLevel),
  65070. x (0), y (0),
  65071. width (512), height (512),
  65072. viewBoxW (0), viewBoxH (0)
  65073. {
  65074. }
  65075. ~SVGState()
  65076. {
  65077. }
  65078. Drawable* parseSVGElement (const XmlElement& xml)
  65079. {
  65080. if (! xml.hasTagName (T("svg")))
  65081. return 0;
  65082. DrawableComposite* const drawable = new DrawableComposite();
  65083. drawable->setName (xml.getStringAttribute (T("id")));
  65084. SVGState newState (*this);
  65085. if (xml.hasAttribute (T("transform")))
  65086. newState.addTransform (xml);
  65087. newState.x = getCoordLength (xml.getStringAttribute (T("x"), String (newState.x)), viewBoxW);
  65088. newState.y = getCoordLength (xml.getStringAttribute (T("y"), String (newState.y)), viewBoxH);
  65089. newState.width = getCoordLength (xml.getStringAttribute (T("width"), String (newState.width)), viewBoxW);
  65090. newState.height = getCoordLength (xml.getStringAttribute (T("height"), String (newState.height)), viewBoxH);
  65091. if (xml.hasAttribute (T("viewBox")))
  65092. {
  65093. const String viewParams (xml.getStringAttribute (T("viewBox")));
  65094. int i = 0;
  65095. float vx, vy, vw, vh;
  65096. if (parseCoords (viewParams, vx, vy, i, true)
  65097. && parseCoords (viewParams, vw, vh, i, true)
  65098. && vw > 0
  65099. && vh > 0)
  65100. {
  65101. newState.viewBoxW = vw;
  65102. newState.viewBoxH = vh;
  65103. int placementFlags = 0;
  65104. const String aspect (xml.getStringAttribute (T("preserveAspectRatio")));
  65105. if (aspect.containsIgnoreCase (T("none")))
  65106. {
  65107. placementFlags = RectanglePlacement::stretchToFit;
  65108. }
  65109. else
  65110. {
  65111. if (aspect.containsIgnoreCase (T("slice")))
  65112. placementFlags |= RectanglePlacement::fillDestination;
  65113. if (aspect.containsIgnoreCase (T("xMin")))
  65114. placementFlags |= RectanglePlacement::xLeft;
  65115. else if (aspect.containsIgnoreCase (T("xMax")))
  65116. placementFlags |= RectanglePlacement::xRight;
  65117. else
  65118. placementFlags |= RectanglePlacement::xMid;
  65119. if (aspect.containsIgnoreCase (T("yMin")))
  65120. placementFlags |= RectanglePlacement::yTop;
  65121. else if (aspect.containsIgnoreCase (T("yMax")))
  65122. placementFlags |= RectanglePlacement::yBottom;
  65123. else
  65124. placementFlags |= RectanglePlacement::yMid;
  65125. }
  65126. const RectanglePlacement placement (placementFlags);
  65127. newState.transform
  65128. = placement.getTransformToFit (vx, vy, vw, vh,
  65129. 0.0f, 0.0f, newState.width, newState.height)
  65130. .followedBy (newState.transform);
  65131. }
  65132. }
  65133. else
  65134. {
  65135. if (viewBoxW == 0)
  65136. newState.viewBoxW = newState.width;
  65137. if (viewBoxH == 0)
  65138. newState.viewBoxH = newState.height;
  65139. }
  65140. newState.parseSubElements (xml, drawable);
  65141. return drawable;
  65142. }
  65143. private:
  65144. const XmlElement* const topLevelXml;
  65145. float x, y, width, height, viewBoxW, viewBoxH;
  65146. AffineTransform transform;
  65147. String cssStyleText;
  65148. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  65149. {
  65150. forEachXmlChildElement (xml, e)
  65151. {
  65152. Drawable* d = 0;
  65153. if (e->hasTagName (T("g")))
  65154. d = parseGroupElement (*e);
  65155. else if (e->hasTagName (T("svg")))
  65156. d = parseSVGElement (*e);
  65157. else if (e->hasTagName (T("path")))
  65158. d = parsePath (*e);
  65159. else if (e->hasTagName (T("rect")))
  65160. d = parseRect (*e);
  65161. else if (e->hasTagName (T("circle")))
  65162. d = parseCircle (*e);
  65163. else if (e->hasTagName (T("ellipse")))
  65164. d = parseEllipse (*e);
  65165. else if (e->hasTagName (T("line")))
  65166. d = parseLine (*e);
  65167. else if (e->hasTagName (T("polyline")))
  65168. d = parsePolygon (*e, true);
  65169. else if (e->hasTagName (T("polygon")))
  65170. d = parsePolygon (*e, false);
  65171. else if (e->hasTagName (T("text")))
  65172. d = parseText (*e);
  65173. else if (e->hasTagName (T("switch")))
  65174. d = parseSwitch (*e);
  65175. else if (e->hasTagName (T("style")))
  65176. parseCSSStyle (*e);
  65177. parentDrawable->insertDrawable (d);
  65178. }
  65179. }
  65180. DrawableComposite* parseSwitch (const XmlElement& xml)
  65181. {
  65182. const XmlElement* const group = xml.getChildByName (T("g"));
  65183. if (group != 0)
  65184. return parseGroupElement (*group);
  65185. return 0;
  65186. }
  65187. DrawableComposite* parseGroupElement (const XmlElement& xml)
  65188. {
  65189. DrawableComposite* const drawable = new DrawableComposite();
  65190. drawable->setName (xml.getStringAttribute (T("id")));
  65191. if (xml.hasAttribute (T("transform")))
  65192. {
  65193. SVGState newState (*this);
  65194. newState.addTransform (xml);
  65195. newState.parseSubElements (xml, drawable);
  65196. }
  65197. else
  65198. {
  65199. parseSubElements (xml, drawable);
  65200. }
  65201. return drawable;
  65202. }
  65203. Drawable* parsePath (const XmlElement& xml) const
  65204. {
  65205. const String d (xml.getStringAttribute (T("d")).trimStart());
  65206. Path path;
  65207. if (getStyleAttribute (&xml, T("fill-rule")).trim().equalsIgnoreCase (T("evenodd")))
  65208. path.setUsingNonZeroWinding (false);
  65209. int index = 0;
  65210. float lastX = 0, lastY = 0;
  65211. float lastX2 = 0, lastY2 = 0;
  65212. tchar lastCommandChar = 0;
  65213. bool carryOn = true;
  65214. const String validCommandChars (T("MmLlHhVvCcSsQqTtAaZz"));
  65215. for (;;)
  65216. {
  65217. float x, y, x2, y2, x3, y3;
  65218. const bool isRelative = (d[index] >= 'a' && d[index] <= 'z');
  65219. if (validCommandChars.containsChar (d[index]))
  65220. lastCommandChar = d [index++];
  65221. switch (lastCommandChar)
  65222. {
  65223. case T('M'):
  65224. case T('m'):
  65225. case T('L'):
  65226. case T('l'):
  65227. if (parseCoords (d, x, y, index, false))
  65228. {
  65229. if (isRelative)
  65230. {
  65231. x += lastX;
  65232. y += lastY;
  65233. }
  65234. if (lastCommandChar == T('M') || lastCommandChar == T('m'))
  65235. path.startNewSubPath (x, y);
  65236. else
  65237. path.lineTo (x, y);
  65238. lastX2 = lastX;
  65239. lastY2 = lastY;
  65240. lastX = x;
  65241. lastY = y;
  65242. }
  65243. else
  65244. {
  65245. ++index;
  65246. }
  65247. break;
  65248. case T('H'):
  65249. case T('h'):
  65250. if (parseCoord (d, x, index, false, true))
  65251. {
  65252. if (isRelative)
  65253. x += lastX;
  65254. path.lineTo (x, lastY);
  65255. lastX2 = lastX;
  65256. lastX = x;
  65257. }
  65258. else
  65259. {
  65260. ++index;
  65261. }
  65262. break;
  65263. case T('V'):
  65264. case T('v'):
  65265. if (parseCoord (d, y, index, false, false))
  65266. {
  65267. if (isRelative)
  65268. y += lastY;
  65269. path.lineTo (lastX, y);
  65270. lastY2 = lastY;
  65271. lastY = y;
  65272. }
  65273. else
  65274. {
  65275. ++index;
  65276. }
  65277. break;
  65278. case T('C'):
  65279. case T('c'):
  65280. if (parseCoords (d, x, y, index, false)
  65281. && parseCoords (d, x2, y2, index, false)
  65282. && parseCoords (d, x3, y3, index, false))
  65283. {
  65284. if (isRelative)
  65285. {
  65286. x += lastX;
  65287. y += lastY;
  65288. x2 += lastX;
  65289. y2 += lastY;
  65290. x3 += lastX;
  65291. y3 += lastY;
  65292. }
  65293. path.cubicTo (x, y, x2, y2, x3, y3);
  65294. lastX2 = x2;
  65295. lastY2 = y2;
  65296. lastX = x3;
  65297. lastY = y3;
  65298. }
  65299. else
  65300. {
  65301. ++index;
  65302. }
  65303. break;
  65304. case T('S'):
  65305. case T('s'):
  65306. if (parseCoords (d, x, y, index, false)
  65307. && parseCoords (d, x3, y3, index, false))
  65308. {
  65309. if (isRelative)
  65310. {
  65311. x += lastX;
  65312. y += lastY;
  65313. x3 += lastX;
  65314. y3 += lastY;
  65315. }
  65316. x2 = lastX + (lastX - lastX2);
  65317. y2 = lastY + (lastY - lastY2);
  65318. path.cubicTo (x2, y2, x, y, x3, y3);
  65319. lastX2 = x;
  65320. lastY2 = y;
  65321. lastX = x3;
  65322. lastY = y3;
  65323. }
  65324. else
  65325. {
  65326. ++index;
  65327. }
  65328. break;
  65329. case T('Q'):
  65330. case T('q'):
  65331. if (parseCoords (d, x, y, index, false)
  65332. && parseCoords (d, x2, y2, index, false))
  65333. {
  65334. if (isRelative)
  65335. {
  65336. x += lastX;
  65337. y += lastY;
  65338. x2 += lastX;
  65339. y2 += lastY;
  65340. }
  65341. path.quadraticTo (x, y, x2, y2);
  65342. lastX2 = x;
  65343. lastY2 = y;
  65344. lastX = x2;
  65345. lastY = y2;
  65346. }
  65347. else
  65348. {
  65349. ++index;
  65350. }
  65351. break;
  65352. case T('T'):
  65353. case T('t'):
  65354. if (parseCoords (d, x, y, index, false))
  65355. {
  65356. if (isRelative)
  65357. {
  65358. x += lastX;
  65359. y += lastY;
  65360. }
  65361. x2 = lastX + (lastX - lastX2);
  65362. y2 = lastY + (lastY - lastY2);
  65363. path.quadraticTo (x2, y2, x, y);
  65364. lastX2 = x2;
  65365. lastY2 = y2;
  65366. lastX = x;
  65367. lastY = y;
  65368. }
  65369. else
  65370. {
  65371. ++index;
  65372. }
  65373. break;
  65374. case T('A'):
  65375. case T('a'):
  65376. if (parseCoords (d, x, y, index, false))
  65377. {
  65378. String num;
  65379. if (parseNextNumber (d, num, index, false))
  65380. {
  65381. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  65382. if (parseNextNumber (d, num, index, false))
  65383. {
  65384. const bool largeArc = num.getIntValue() != 0;
  65385. if (parseNextNumber (d, num, index, false))
  65386. {
  65387. const bool sweep = num.getIntValue() != 0;
  65388. if (parseCoords (d, x2, y2, index, false))
  65389. {
  65390. if (isRelative)
  65391. {
  65392. x2 += lastX;
  65393. y2 += lastY;
  65394. }
  65395. if (lastX != x2 || lastY != y2)
  65396. {
  65397. double centreX, centreY, startAngle, deltaAngle;
  65398. double rx = x, ry = y;
  65399. endpointToCentreParameters (lastX, lastY, x2, y2,
  65400. angle, largeArc, sweep,
  65401. rx, ry, centreX, centreY,
  65402. startAngle, deltaAngle);
  65403. path.addCentredArc ((float) centreX, (float) centreY,
  65404. (float) rx, (float) ry,
  65405. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  65406. false);
  65407. path.lineTo (x2, y2);
  65408. }
  65409. lastX2 = lastX;
  65410. lastY2 = lastY;
  65411. lastX = x2;
  65412. lastY = y2;
  65413. }
  65414. }
  65415. }
  65416. }
  65417. }
  65418. else
  65419. {
  65420. ++index;
  65421. }
  65422. break;
  65423. case T('Z'):
  65424. case T('z'):
  65425. path.closeSubPath();
  65426. while (CharacterFunctions::isWhitespace (d [index]))
  65427. ++index;
  65428. break;
  65429. default:
  65430. carryOn = false;
  65431. break;
  65432. }
  65433. if (! carryOn)
  65434. break;
  65435. }
  65436. return parseShape (xml, path);
  65437. }
  65438. Drawable* parseRect (const XmlElement& xml) const
  65439. {
  65440. Path rect;
  65441. const bool hasRX = xml.hasAttribute (T("rx"));
  65442. const bool hasRY = xml.hasAttribute (T("ry"));
  65443. if (hasRX || hasRY)
  65444. {
  65445. float rx = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  65446. float ry = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  65447. if (! hasRX)
  65448. rx = ry;
  65449. else if (! hasRY)
  65450. ry = rx;
  65451. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  65452. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  65453. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  65454. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH),
  65455. rx, ry);
  65456. }
  65457. else
  65458. {
  65459. rect.addRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  65460. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  65461. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  65462. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH));
  65463. }
  65464. return parseShape (xml, rect);
  65465. }
  65466. Drawable* parseCircle (const XmlElement& xml) const
  65467. {
  65468. Path circle;
  65469. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  65470. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  65471. const float radius = getCoordLength (xml.getStringAttribute (T("r")), viewBoxW);
  65472. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  65473. return parseShape (xml, circle);
  65474. }
  65475. Drawable* parseEllipse (const XmlElement& xml) const
  65476. {
  65477. Path ellipse;
  65478. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  65479. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  65480. const float radiusX = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  65481. const float radiusY = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  65482. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  65483. return parseShape (xml, ellipse);
  65484. }
  65485. Drawable* parseLine (const XmlElement& xml) const
  65486. {
  65487. Path line;
  65488. const float x1 = getCoordLength (xml.getStringAttribute (T("x1")), viewBoxW);
  65489. const float y1 = getCoordLength (xml.getStringAttribute (T("y1")), viewBoxH);
  65490. const float x2 = getCoordLength (xml.getStringAttribute (T("x2")), viewBoxW);
  65491. const float y2 = getCoordLength (xml.getStringAttribute (T("y2")), viewBoxH);
  65492. line.startNewSubPath (x1, y1);
  65493. line.lineTo (x2, y2);
  65494. return parseShape (xml, line);
  65495. }
  65496. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  65497. {
  65498. const String points (xml.getStringAttribute (T("points")));
  65499. Path path;
  65500. int index = 0;
  65501. float x, y;
  65502. if (parseCoords (points, x, y, index, true))
  65503. {
  65504. float firstX = x;
  65505. float firstY = y;
  65506. float lastX = 0, lastY = 0;
  65507. path.startNewSubPath (x, y);
  65508. while (parseCoords (points, x, y, index, true))
  65509. {
  65510. lastX = x;
  65511. lastY = y;
  65512. path.lineTo (x, y);
  65513. }
  65514. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  65515. path.closeSubPath();
  65516. }
  65517. return parseShape (xml, path);
  65518. }
  65519. Drawable* parseShape (const XmlElement& xml, Path& path,
  65520. const bool parseTransform = true) const
  65521. {
  65522. if (parseTransform && xml.hasAttribute (T("transform")))
  65523. {
  65524. SVGState newState (*this);
  65525. newState.addTransform (xml);
  65526. return newState.parseShape (xml, path, false);
  65527. }
  65528. DrawablePath* dp = new DrawablePath();
  65529. dp->setName (xml.getStringAttribute (T("id")));
  65530. dp->setSolidFill (Colours::transparentBlack);
  65531. path.applyTransform (transform);
  65532. dp->setPath (path);
  65533. Path::Iterator iter (path);
  65534. bool containsClosedSubPath = false;
  65535. while (iter.next())
  65536. {
  65537. if (iter.elementType == Path::Iterator::closePath)
  65538. {
  65539. containsClosedSubPath = true;
  65540. break;
  65541. }
  65542. }
  65543. Brush* const fillBrush
  65544. = getBrushForFill (path,
  65545. getStyleAttribute (&xml, T("fill")),
  65546. getStyleAttribute (&xml, T("fill-opacity")),
  65547. getStyleAttribute (&xml, T("opacity")),
  65548. containsClosedSubPath ? Colours::black
  65549. : Colours::transparentBlack);
  65550. if (fillBrush != 0)
  65551. {
  65552. if (! fillBrush->isInvisible())
  65553. {
  65554. fillBrush->applyTransform (transform);
  65555. dp->setFillBrush (*fillBrush);
  65556. }
  65557. delete fillBrush;
  65558. }
  65559. const String strokeType (getStyleAttribute (&xml, T("stroke")));
  65560. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase (T("none")))
  65561. {
  65562. Brush* const strokeBrush
  65563. = getBrushForFill (path, strokeType,
  65564. getStyleAttribute (&xml, T("stroke-opacity")),
  65565. getStyleAttribute (&xml, T("opacity")),
  65566. Colours::transparentBlack);
  65567. if (strokeBrush != 0)
  65568. {
  65569. const PathStrokeType stroke (getStrokeFor (&xml));
  65570. if (! strokeBrush->isInvisible())
  65571. {
  65572. strokeBrush->applyTransform (transform);
  65573. dp->setOutline (stroke, *strokeBrush);
  65574. }
  65575. delete strokeBrush;
  65576. }
  65577. }
  65578. return dp;
  65579. }
  65580. const XmlElement* findLinkedElement (const XmlElement* e) const
  65581. {
  65582. const String id (e->getStringAttribute (T("xlink:href")));
  65583. if (! id.startsWithChar (T('#')))
  65584. return 0;
  65585. return findElementForId (topLevelXml, id.substring (1));
  65586. }
  65587. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  65588. {
  65589. if (fillXml == 0)
  65590. return;
  65591. forEachXmlChildElementWithTagName (*fillXml, e, T("stop"))
  65592. {
  65593. int index = 0;
  65594. Colour col (parseColour (getStyleAttribute (e, T("stop-color")), index, Colours::black));
  65595. const String opacity (getStyleAttribute (e, T("stop-opacity"), T("1")));
  65596. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  65597. double offset = e->getDoubleAttribute (T("offset"));
  65598. if (e->getStringAttribute (T("offset")).containsChar (T('%')))
  65599. offset *= 0.01;
  65600. cg.addColour (jlimit (0.0, 1.0, offset), col);
  65601. }
  65602. }
  65603. Brush* getBrushForFill (const Path& path,
  65604. const String& fill,
  65605. const String& fillOpacity,
  65606. const String& overallOpacity,
  65607. const Colour& defaultColour) const
  65608. {
  65609. float opacity = 1.0f;
  65610. if (overallOpacity.isNotEmpty())
  65611. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  65612. if (fillOpacity.isNotEmpty())
  65613. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  65614. if (fill.startsWithIgnoreCase (T("url")))
  65615. {
  65616. const String id (fill.fromFirstOccurrenceOf (T("#"), false, false)
  65617. .upToLastOccurrenceOf (T(")"), false, false).trim());
  65618. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  65619. if (fillXml != 0
  65620. && (fillXml->hasTagName (T("linearGradient"))
  65621. || fillXml->hasTagName (T("radialGradient"))))
  65622. {
  65623. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  65624. ColourGradient cg;
  65625. addGradientStopsIn (cg, inheritedFrom);
  65626. addGradientStopsIn (cg, fillXml);
  65627. if (cg.getNumColours() > 0)
  65628. {
  65629. cg.addColour (0.0, cg.getColour (0));
  65630. cg.addColour (1.0, cg.getColour (cg.getNumColours() - 1));
  65631. }
  65632. else
  65633. {
  65634. cg.addColour (0.0, Colours::black);
  65635. cg.addColour (1.0, Colours::black);
  65636. }
  65637. if (overallOpacity.isNotEmpty())
  65638. cg.multiplyOpacity (overallOpacity.getFloatValue());
  65639. jassert (cg.getNumColours() > 0);
  65640. cg.isRadial = fillXml->hasTagName (T("radialGradient"));
  65641. cg.transform = parseTransform (fillXml->getStringAttribute (T("gradientTransform")));
  65642. float width = viewBoxW;
  65643. float height = viewBoxH;
  65644. float dx = 0.0;
  65645. float dy = 0.0;
  65646. const bool userSpace = fillXml->getStringAttribute (T("gradientUnits")).equalsIgnoreCase (T("userSpaceOnUse"));
  65647. if (! userSpace)
  65648. path.getBounds (dx, dy, width, height);
  65649. if (cg.isRadial)
  65650. {
  65651. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("cx"), T("50%")), width);
  65652. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("cy"), T("50%")), height);
  65653. const float radius = getCoordLength (fillXml->getStringAttribute (T("r"), T("50%")), width);
  65654. cg.x2 = cg.x1 + radius;
  65655. cg.y2 = cg.y1;
  65656. //xxx (the fx, fy focal point isn't handled properly here..)
  65657. }
  65658. else
  65659. {
  65660. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("x1"), T("0%")), width);
  65661. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("y1"), T("0%")), height);
  65662. cg.x2 = dx + getCoordLength (fillXml->getStringAttribute (T("x2"), T("100%")), width);
  65663. cg.y2 = dy + getCoordLength (fillXml->getStringAttribute (T("y2"), T("0%")), height);
  65664. if (cg.x1 == cg.x2 && cg.y1 == cg.y2)
  65665. return new SolidColourBrush (cg.getColour (cg.getNumColours() - 1));
  65666. }
  65667. return new GradientBrush (cg);
  65668. }
  65669. }
  65670. if (fill.equalsIgnoreCase (T("none")))
  65671. return new SolidColourBrush (Colours::transparentBlack);
  65672. int i = 0;
  65673. Colour colour (parseColour (fill, i, defaultColour));
  65674. colour = colour.withMultipliedAlpha (opacity);
  65675. return new SolidColourBrush (colour);
  65676. }
  65677. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  65678. {
  65679. const String width (getStyleAttribute (xml, T("stroke-width")));
  65680. const String cap (getStyleAttribute (xml, T("stroke-linecap")));
  65681. const String join (getStyleAttribute (xml, T("stroke-linejoin")));
  65682. //const String mitreLimit (getStyleAttribute (xml, T("stroke-miterlimit")));
  65683. //const String dashArray (getStyleAttribute (xml, T("stroke-dasharray")));
  65684. //const String dashOffset (getStyleAttribute (xml, T("stroke-dashoffset")));
  65685. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  65686. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  65687. if (join.equalsIgnoreCase (T("round")))
  65688. joinStyle = PathStrokeType::curved;
  65689. else if (join.equalsIgnoreCase (T("bevel")))
  65690. joinStyle = PathStrokeType::beveled;
  65691. if (cap.equalsIgnoreCase (T("round")))
  65692. capStyle = PathStrokeType::rounded;
  65693. else if (cap.equalsIgnoreCase (T("square")))
  65694. capStyle = PathStrokeType::square;
  65695. float ox = 0.0f, oy = 0.0f;
  65696. transform.transformPoint (ox, oy);
  65697. float x = getCoordLength (width, viewBoxW), y = 0.0f;
  65698. transform.transformPoint (x, y);
  65699. return PathStrokeType (width.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  65700. joinStyle, capStyle);
  65701. }
  65702. Drawable* parseText (const XmlElement& xml)
  65703. {
  65704. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  65705. getCoordList (xCoords, getInheritedAttribute (&xml, T("x")), true, true);
  65706. getCoordList (yCoords, getInheritedAttribute (&xml, T("y")), true, false);
  65707. getCoordList (dxCoords, getInheritedAttribute (&xml, T("dx")), true, true);
  65708. getCoordList (dyCoords, getInheritedAttribute (&xml, T("dy")), true, false);
  65709. //xxx not done text yet!
  65710. forEachXmlChildElement (xml, e)
  65711. {
  65712. if (e->isTextElement())
  65713. {
  65714. const String text (e->getText());
  65715. Path path;
  65716. Drawable* s = parseShape (*e, path);
  65717. delete s;
  65718. }
  65719. else if (e->hasTagName (T("tspan")))
  65720. {
  65721. Drawable* s = parseText (*e);
  65722. delete s;
  65723. }
  65724. }
  65725. return 0;
  65726. }
  65727. void addTransform (const XmlElement& xml)
  65728. {
  65729. transform = parseTransform (xml.getStringAttribute (T("transform")))
  65730. .followedBy (transform);
  65731. }
  65732. bool parseCoord (const String& s, float& value, int& index,
  65733. const bool allowUnits, const bool isX) const
  65734. {
  65735. String number;
  65736. if (! parseNextNumber (s, number, index, allowUnits))
  65737. {
  65738. value = 0;
  65739. return false;
  65740. }
  65741. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  65742. return true;
  65743. }
  65744. bool parseCoords (const String& s, float& x, float& y,
  65745. int& index, const bool allowUnits) const
  65746. {
  65747. return parseCoord (s, x, index, allowUnits, true)
  65748. && parseCoord (s, y, index, allowUnits, false);
  65749. }
  65750. float getCoordLength (const String& s, const float sizeForProportions) const
  65751. {
  65752. float n = s.getFloatValue();
  65753. const int len = s.length();
  65754. if (len > 2)
  65755. {
  65756. const float dpi = 96.0f;
  65757. const tchar n1 = s [len - 2];
  65758. const tchar n2 = s [len - 1];
  65759. if (n1 == T('i') && n2 == T('n'))
  65760. n *= dpi;
  65761. else if (n1 == T('m') && n2 == T('m'))
  65762. n *= dpi / 25.4f;
  65763. else if (n1 == T('c') && n2 == T('m'))
  65764. n *= dpi / 2.54f;
  65765. else if (n1 == T('p') && n2 == T('c'))
  65766. n *= 15.0f;
  65767. else if (n2 == T('%'))
  65768. n *= 0.01f * sizeForProportions;
  65769. }
  65770. return n;
  65771. }
  65772. void getCoordList (Array <float>& coords, const String& list,
  65773. const bool allowUnits, const bool isX) const
  65774. {
  65775. int index = 0;
  65776. float value;
  65777. while (parseCoord (list, value, index, allowUnits, isX))
  65778. coords.add (value);
  65779. }
  65780. void parseCSSStyle (const XmlElement& xml)
  65781. {
  65782. cssStyleText = xml.getAllSubText() + T("\n") + cssStyleText;
  65783. }
  65784. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  65785. const String& defaultValue = String::empty) const
  65786. {
  65787. if (xml->hasAttribute (attributeName))
  65788. return xml->getStringAttribute (attributeName, defaultValue);
  65789. const String styleAtt (xml->getStringAttribute (T("style")));
  65790. if (styleAtt.isNotEmpty())
  65791. {
  65792. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  65793. if (value.isNotEmpty())
  65794. return value;
  65795. }
  65796. else if (xml->hasAttribute (T("class")))
  65797. {
  65798. const String className (T(".") + xml->getStringAttribute (T("class")));
  65799. int index = cssStyleText.indexOfIgnoreCase (className + T(" "));
  65800. if (index < 0)
  65801. index = cssStyleText.indexOfIgnoreCase (className + T("{"));
  65802. if (index >= 0)
  65803. {
  65804. const int openBracket = cssStyleText.indexOfChar (index, T('{'));
  65805. if (openBracket > index)
  65806. {
  65807. const int closeBracket = cssStyleText.indexOfChar (openBracket, T('}'));
  65808. if (closeBracket > openBracket)
  65809. {
  65810. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  65811. if (value.isNotEmpty())
  65812. return value;
  65813. }
  65814. }
  65815. }
  65816. }
  65817. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  65818. if (xml != 0)
  65819. return getStyleAttribute (xml, attributeName, defaultValue);
  65820. return defaultValue;
  65821. }
  65822. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  65823. {
  65824. if (xml->hasAttribute (attributeName))
  65825. return xml->getStringAttribute (attributeName);
  65826. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  65827. if (xml != 0)
  65828. return getInheritedAttribute (xml, attributeName);
  65829. return String::empty;
  65830. }
  65831. static bool isIdentifierChar (const tchar c)
  65832. {
  65833. return CharacterFunctions::isLetter (c) || c == T('-');
  65834. }
  65835. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  65836. {
  65837. int i = 0;
  65838. for (;;)
  65839. {
  65840. i = list.indexOf (i, attributeName);
  65841. if (i < 0)
  65842. break;
  65843. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  65844. && ! isIdentifierChar (list [i + attributeName.length()]))
  65845. {
  65846. i = list.indexOfChar (i, T(':'));
  65847. if (i < 0)
  65848. break;
  65849. int end = list.indexOfChar (i, T(';'));
  65850. if (end < 0)
  65851. end = 0x7ffff;
  65852. return list.substring (i + 1, end).trim();
  65853. }
  65854. ++i;
  65855. }
  65856. return defaultValue;
  65857. }
  65858. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  65859. {
  65860. const tchar* const s = (const tchar*) source;
  65861. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  65862. ++index;
  65863. int start = index;
  65864. if (CharacterFunctions::isDigit (s[index]) || s[index] == T('.') || s[index] == T('-'))
  65865. ++index;
  65866. while (CharacterFunctions::isDigit (s[index]) || s[index] == T('.'))
  65867. ++index;
  65868. if ((s[index] == T('e') || s[index] == T('E'))
  65869. && (CharacterFunctions::isDigit (s[index + 1])
  65870. || s[index + 1] == T('-')
  65871. || s[index + 1] == T('+')))
  65872. {
  65873. index += 2;
  65874. while (CharacterFunctions::isDigit (s[index]))
  65875. ++index;
  65876. }
  65877. if (allowUnits)
  65878. {
  65879. while (CharacterFunctions::isLetter (s[index]))
  65880. ++index;
  65881. }
  65882. if (index == start)
  65883. return false;
  65884. value = String (s + start, index - start);
  65885. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  65886. ++index;
  65887. return true;
  65888. }
  65889. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  65890. {
  65891. if (s [index] == T('#'))
  65892. {
  65893. uint32 hex [6];
  65894. zeromem (hex, sizeof (hex));
  65895. int numChars = 0;
  65896. for (int i = 6; --i >= 0;)
  65897. {
  65898. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  65899. if (hexValue >= 0)
  65900. hex [numChars++] = hexValue;
  65901. else
  65902. break;
  65903. }
  65904. if (numChars <= 3)
  65905. return Colour ((uint8) (hex [0] * 0x11),
  65906. (uint8) (hex [1] * 0x11),
  65907. (uint8) (hex [2] * 0x11));
  65908. else
  65909. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  65910. (uint8) ((hex [2] << 4) + hex [3]),
  65911. (uint8) ((hex [4] << 4) + hex [5]));
  65912. }
  65913. else if (s [index] == T('r')
  65914. && s [index + 1] == T('g')
  65915. && s [index + 2] == T('b'))
  65916. {
  65917. const int openBracket = s.indexOfChar (index, T('('));
  65918. const int closeBracket = s.indexOfChar (openBracket, T(')'));
  65919. if (openBracket >= 3 && closeBracket > openBracket)
  65920. {
  65921. index = closeBracket;
  65922. StringArray tokens;
  65923. tokens.addTokens (s.substring (openBracket + 1, closeBracket), T(","), T(""));
  65924. tokens.trim();
  65925. tokens.removeEmptyStrings();
  65926. if (tokens[0].containsChar (T('%')))
  65927. return Colour ((uint8) roundDoubleToInt (2.55 * tokens[0].getDoubleValue()),
  65928. (uint8) roundDoubleToInt (2.55 * tokens[1].getDoubleValue()),
  65929. (uint8) roundDoubleToInt (2.55 * tokens[2].getDoubleValue()));
  65930. else
  65931. return Colour ((uint8) tokens[0].getIntValue(),
  65932. (uint8) tokens[1].getIntValue(),
  65933. (uint8) tokens[2].getIntValue());
  65934. }
  65935. }
  65936. return Colours::findColourForName (s, defaultColour);
  65937. }
  65938. static const AffineTransform parseTransform (String t)
  65939. {
  65940. AffineTransform result;
  65941. while (t.isNotEmpty())
  65942. {
  65943. StringArray tokens;
  65944. tokens.addTokens (t.fromFirstOccurrenceOf (T("("), false, false)
  65945. .upToFirstOccurrenceOf (T(")"), false, false),
  65946. T(", "), 0);
  65947. tokens.removeEmptyStrings (true);
  65948. float numbers [6];
  65949. for (int i = 0; i < 6; ++i)
  65950. numbers[i] = tokens[i].getFloatValue();
  65951. AffineTransform trans;
  65952. if (t.startsWithIgnoreCase (T("matrix")))
  65953. {
  65954. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  65955. numbers[1], numbers[3], numbers[5]);
  65956. }
  65957. else if (t.startsWithIgnoreCase (T("translate")))
  65958. {
  65959. trans = trans.translated (numbers[0], numbers[1]);
  65960. }
  65961. else if (t.startsWithIgnoreCase (T("scale")))
  65962. {
  65963. if (tokens.size() == 1)
  65964. trans = trans.scaled (numbers[0], numbers[0]);
  65965. else
  65966. trans = trans.scaled (numbers[0], numbers[1]);
  65967. }
  65968. else if (t.startsWithIgnoreCase (T("rotate")))
  65969. {
  65970. if (tokens.size() != 3)
  65971. trans = trans.rotated (numbers[0] / (180.0f / float_Pi));
  65972. else
  65973. trans = trans.rotated (numbers[0] / (180.0f / float_Pi),
  65974. numbers[1], numbers[2]);
  65975. }
  65976. else if (t.startsWithIgnoreCase (T("skewX")))
  65977. {
  65978. trans = AffineTransform (1.0f, tanf (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  65979. 0.0f, 1.0f, 0.0f);
  65980. }
  65981. else if (t.startsWithIgnoreCase (T("skewY")))
  65982. {
  65983. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  65984. tanf (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  65985. }
  65986. result = trans.followedBy (result);
  65987. t = t.fromFirstOccurrenceOf (T(")"), false, false).trimStart();
  65988. }
  65989. return result;
  65990. }
  65991. static void endpointToCentreParameters (const double x1, const double y1,
  65992. const double x2, const double y2,
  65993. const double angle,
  65994. const bool largeArc, const bool sweep,
  65995. double& rx, double& ry,
  65996. double& centreX, double& centreY,
  65997. double& startAngle, double& deltaAngle)
  65998. {
  65999. const double midX = (x1 - x2) * 0.5;
  66000. const double midY = (y1 - y2) * 0.5;
  66001. const double cosAngle = cos (angle);
  66002. const double sinAngle = sin (angle);
  66003. const double xp = cosAngle * midX + sinAngle * midY;
  66004. const double yp = cosAngle * midY - sinAngle * midX;
  66005. const double xp2 = xp * xp;
  66006. const double yp2 = yp * yp;
  66007. double rx2 = rx * rx;
  66008. double ry2 = ry * ry;
  66009. const double s = (xp2 / rx2) + (yp2 / ry2);
  66010. double c;
  66011. if (s <= 1.0)
  66012. {
  66013. c = sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  66014. / (( rx2 * yp2) + (ry2 * xp2))));
  66015. if (largeArc == sweep)
  66016. c = -c;
  66017. }
  66018. else
  66019. {
  66020. const double s2 = sqrt (s);
  66021. rx *= s2;
  66022. ry *= s2;
  66023. rx2 = rx * rx;
  66024. ry2 = ry * ry;
  66025. c = 0;
  66026. }
  66027. const double cpx = ((rx * yp) / ry) * c;
  66028. const double cpy = ((-ry * xp) / rx) * c;
  66029. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  66030. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  66031. const double ux = (xp - cpx) / rx;
  66032. const double uy = (yp - cpy) / ry;
  66033. const double vx = (-xp - cpx) / rx;
  66034. const double vy = (-yp - cpy) / ry;
  66035. const double length = juce_hypot (ux, uy);
  66036. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  66037. if (uy < 0)
  66038. startAngle = -startAngle;
  66039. startAngle += double_Pi * 0.5;
  66040. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  66041. / (length * juce_hypot (vx, vy))));
  66042. if ((ux * vy) - (uy * vx) < 0)
  66043. deltaAngle = -deltaAngle;
  66044. if (sweep)
  66045. {
  66046. if (deltaAngle < 0)
  66047. deltaAngle += double_Pi * 2.0;
  66048. }
  66049. else
  66050. {
  66051. if (deltaAngle > 0)
  66052. deltaAngle -= double_Pi * 2.0;
  66053. }
  66054. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  66055. }
  66056. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  66057. {
  66058. forEachXmlChildElement (*parent, e)
  66059. {
  66060. if (e->compareAttribute (T("id"), id))
  66061. return e;
  66062. const XmlElement* const found = findElementForId (e, id);
  66063. if (found != 0)
  66064. return found;
  66065. }
  66066. return 0;
  66067. }
  66068. const SVGState& operator= (const SVGState&);
  66069. };
  66070. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  66071. {
  66072. SVGState state (&svgDocument);
  66073. return state.parseSVGElement (svgDocument);
  66074. }
  66075. END_JUCE_NAMESPACE
  66076. /********* End of inlined file: juce_SVGParser.cpp *********/
  66077. /********* Start of inlined file: juce_DropShadowEffect.cpp *********/
  66078. BEGIN_JUCE_NAMESPACE
  66079. #if JUCE_MSVC
  66080. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  66081. #endif
  66082. DropShadowEffect::DropShadowEffect()
  66083. : offsetX (0),
  66084. offsetY (0),
  66085. radius (4),
  66086. opacity (0.6f)
  66087. {
  66088. }
  66089. DropShadowEffect::~DropShadowEffect()
  66090. {
  66091. }
  66092. void DropShadowEffect::setShadowProperties (const float newRadius,
  66093. const float newOpacity,
  66094. const int newShadowOffsetX,
  66095. const int newShadowOffsetY)
  66096. {
  66097. radius = jmax (1.1f, newRadius);
  66098. offsetX = newShadowOffsetX;
  66099. offsetY = newShadowOffsetY;
  66100. opacity = newOpacity;
  66101. }
  66102. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  66103. {
  66104. const int w = image.getWidth();
  66105. const int h = image.getHeight();
  66106. int lineStride, pixelStride;
  66107. const PixelARGB* srcPixels = (const PixelARGB*) image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(), lineStride, pixelStride);
  66108. Image shadowImage (Image::SingleChannel, w, h, false);
  66109. int destStride, destPixelStride;
  66110. uint8* const shadowChannel = (uint8*) shadowImage.lockPixelDataReadWrite (0, 0, w, h, destStride, destPixelStride);
  66111. const int filter = roundFloatToInt (63.0f / radius);
  66112. const int radiusMinus1 = roundFloatToInt ((radius - 1.0f) * 63.0f);
  66113. for (int x = w; --x >= 0;)
  66114. {
  66115. int shadowAlpha = 0;
  66116. const PixelARGB* src = srcPixels + x;
  66117. uint8* shadowPix = shadowChannel + x;
  66118. for (int y = h; --y >= 0;)
  66119. {
  66120. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  66121. *shadowPix = (uint8) shadowAlpha;
  66122. src = (const PixelARGB*) (((const uint8*) src) + lineStride);
  66123. shadowPix += destStride;
  66124. }
  66125. }
  66126. for (int y = h; --y >= 0;)
  66127. {
  66128. int shadowAlpha = 0;
  66129. uint8* shadowPix = shadowChannel + y * destStride;
  66130. for (int x = w; --x >= 0;)
  66131. {
  66132. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  66133. *shadowPix++ = (uint8) shadowAlpha;
  66134. }
  66135. }
  66136. image.releasePixelDataReadOnly (srcPixels);
  66137. shadowImage.releasePixelDataReadWrite (shadowChannel);
  66138. g.setColour (Colours::black.withAlpha (opacity));
  66139. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  66140. g.setOpacity (1.0f);
  66141. g.drawImageAt (&image, 0, 0);
  66142. }
  66143. END_JUCE_NAMESPACE
  66144. /********* End of inlined file: juce_DropShadowEffect.cpp *********/
  66145. /********* Start of inlined file: juce_GlowEffect.cpp *********/
  66146. BEGIN_JUCE_NAMESPACE
  66147. GlowEffect::GlowEffect()
  66148. : radius (2.0f),
  66149. colour (Colours::white)
  66150. {
  66151. }
  66152. GlowEffect::~GlowEffect()
  66153. {
  66154. }
  66155. void GlowEffect::setGlowProperties (const float newRadius,
  66156. const Colour& newColour)
  66157. {
  66158. radius = newRadius;
  66159. colour = newColour;
  66160. }
  66161. void GlowEffect::applyEffect (Image& image, Graphics& g)
  66162. {
  66163. const int w = image.getWidth();
  66164. const int h = image.getHeight();
  66165. Image temp (image.getFormat(), w, h, true);
  66166. ImageConvolutionKernel blurKernel (roundFloatToInt (radius * 2.0f));
  66167. blurKernel.createGaussianBlur (radius);
  66168. blurKernel.rescaleAllValues (radius);
  66169. blurKernel.applyToImage (temp, &image, 0, 0, w, h);
  66170. g.setColour (colour);
  66171. g.drawImageAt (&temp, 0, 0, true);
  66172. g.setOpacity (1.0f);
  66173. g.drawImageAt (&image, 0, 0, false);
  66174. }
  66175. END_JUCE_NAMESPACE
  66176. /********* End of inlined file: juce_GlowEffect.cpp *********/
  66177. /********* Start of inlined file: juce_ReduceOpacityEffect.cpp *********/
  66178. BEGIN_JUCE_NAMESPACE
  66179. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  66180. : opacity (opacity_)
  66181. {
  66182. }
  66183. ReduceOpacityEffect::~ReduceOpacityEffect()
  66184. {
  66185. }
  66186. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  66187. {
  66188. opacity = jlimit (0.0f, 1.0f, newOpacity);
  66189. }
  66190. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  66191. {
  66192. g.setOpacity (opacity);
  66193. g.drawImageAt (&image, 0, 0);
  66194. }
  66195. END_JUCE_NAMESPACE
  66196. /********* End of inlined file: juce_ReduceOpacityEffect.cpp *********/
  66197. /********* Start of inlined file: juce_Font.cpp *********/
  66198. BEGIN_JUCE_NAMESPACE
  66199. static const float minFontHeight = 0.1f;
  66200. static const float maxFontHeight = 10000.0f;
  66201. static const float defaultFontHeight = 14.0f;
  66202. Font::Font() throw()
  66203. : typefaceName (Typeface::defaultTypefaceNameSans),
  66204. height (defaultFontHeight),
  66205. horizontalScale (1.0f),
  66206. kerning (0),
  66207. ascent (0),
  66208. styleFlags (Font::plain)
  66209. {
  66210. }
  66211. void Font::resetToDefaultState() throw()
  66212. {
  66213. typefaceName = Typeface::defaultTypefaceNameSans;
  66214. height = defaultFontHeight;
  66215. horizontalScale = 1.0f;
  66216. kerning = 0;
  66217. ascent = 0;
  66218. styleFlags = Font::plain;
  66219. typeface = 0;
  66220. }
  66221. Font::Font (const float fontHeight,
  66222. const int styleFlags_) throw()
  66223. : typefaceName (Typeface::defaultTypefaceNameSans),
  66224. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  66225. horizontalScale (1.0f),
  66226. kerning (0),
  66227. ascent (0),
  66228. styleFlags (styleFlags_)
  66229. {
  66230. }
  66231. Font::Font (const String& typefaceName_,
  66232. const float fontHeight,
  66233. const int styleFlags_) throw()
  66234. : typefaceName (typefaceName_),
  66235. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  66236. horizontalScale (1.0f),
  66237. kerning (0),
  66238. ascent (0),
  66239. styleFlags (styleFlags_)
  66240. {
  66241. }
  66242. Font::Font (const Font& other) throw()
  66243. : typefaceName (other.typefaceName),
  66244. height (other.height),
  66245. horizontalScale (other.horizontalScale),
  66246. kerning (other.kerning),
  66247. ascent (other.ascent),
  66248. styleFlags (other.styleFlags),
  66249. typeface (other.typeface)
  66250. {
  66251. }
  66252. const Font& Font::operator= (const Font& other) throw()
  66253. {
  66254. if (this != &other)
  66255. {
  66256. typefaceName = other.typefaceName;
  66257. height = other.height;
  66258. styleFlags = other.styleFlags;
  66259. horizontalScale = other.horizontalScale;
  66260. kerning = other.kerning;
  66261. ascent = other.ascent;
  66262. typeface = other.typeface;
  66263. }
  66264. return *this;
  66265. }
  66266. Font::~Font() throw()
  66267. {
  66268. }
  66269. Font::Font (const Typeface& face) throw()
  66270. : height (11.0f),
  66271. horizontalScale (1.0f),
  66272. kerning (0),
  66273. ascent (0),
  66274. styleFlags (plain)
  66275. {
  66276. typefaceName = face.getName();
  66277. setBold (face.isBold());
  66278. setItalic (face.isItalic());
  66279. typeface = new Typeface (face);
  66280. }
  66281. bool Font::operator== (const Font& other) const throw()
  66282. {
  66283. return height == other.height
  66284. && horizontalScale == other.horizontalScale
  66285. && kerning == other.kerning
  66286. && styleFlags == other.styleFlags
  66287. && typefaceName == other.typefaceName;
  66288. }
  66289. bool Font::operator!= (const Font& other) const throw()
  66290. {
  66291. return ! operator== (other);
  66292. }
  66293. void Font::setTypefaceName (const String& faceName) throw()
  66294. {
  66295. typefaceName = faceName;
  66296. typeface = 0;
  66297. ascent = 0;
  66298. }
  66299. static String fallbackFont;
  66300. const String Font::getFallbackFontName() throw()
  66301. {
  66302. return fallbackFont;
  66303. }
  66304. void Font::setFallbackFontName (const String& name) throw()
  66305. {
  66306. fallbackFont = name;
  66307. }
  66308. void Font::setHeight (float newHeight) throw()
  66309. {
  66310. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  66311. }
  66312. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  66313. {
  66314. newHeight = jlimit (minFontHeight, maxFontHeight, newHeight);
  66315. horizontalScale *= (height / newHeight);
  66316. height = newHeight;
  66317. }
  66318. void Font::setStyleFlags (const int newFlags) throw()
  66319. {
  66320. if (styleFlags != newFlags)
  66321. {
  66322. styleFlags = newFlags;
  66323. typeface = 0;
  66324. ascent = 0;
  66325. }
  66326. }
  66327. void Font::setSizeAndStyle (const float newHeight,
  66328. const int newStyleFlags,
  66329. const float newHorizontalScale,
  66330. const float newKerningAmount) throw()
  66331. {
  66332. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  66333. horizontalScale = newHorizontalScale;
  66334. kerning = newKerningAmount;
  66335. setStyleFlags (newStyleFlags);
  66336. }
  66337. void Font::setHorizontalScale (const float scaleFactor) throw()
  66338. {
  66339. horizontalScale = scaleFactor;
  66340. }
  66341. void Font::setExtraKerningFactor (const float extraKerning) throw()
  66342. {
  66343. kerning = extraKerning;
  66344. }
  66345. void Font::setBold (const bool shouldBeBold) throw()
  66346. {
  66347. setStyleFlags (shouldBeBold ? (styleFlags | bold)
  66348. : (styleFlags & ~bold));
  66349. }
  66350. bool Font::isBold() const throw()
  66351. {
  66352. return (styleFlags & bold) != 0;
  66353. }
  66354. void Font::setItalic (const bool shouldBeItalic) throw()
  66355. {
  66356. setStyleFlags (shouldBeItalic ? (styleFlags | italic)
  66357. : (styleFlags & ~italic));
  66358. }
  66359. bool Font::isItalic() const throw()
  66360. {
  66361. return (styleFlags & italic) != 0;
  66362. }
  66363. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  66364. {
  66365. setStyleFlags (shouldBeUnderlined ? (styleFlags | underlined)
  66366. : (styleFlags & ~underlined));
  66367. }
  66368. bool Font::isUnderlined() const throw()
  66369. {
  66370. return (styleFlags & underlined) != 0;
  66371. }
  66372. float Font::getAscent() const throw()
  66373. {
  66374. if (ascent == 0)
  66375. ascent = getTypeface()->getAscent();
  66376. return height * ascent;
  66377. }
  66378. float Font::getDescent() const throw()
  66379. {
  66380. return height - getAscent();
  66381. }
  66382. int Font::getStringWidth (const String& text) const throw()
  66383. {
  66384. return roundFloatToInt (getStringWidthFloat (text));
  66385. }
  66386. float Font::getStringWidthFloat (const String& text) const throw()
  66387. {
  66388. float x = 0.0f;
  66389. if (text.isNotEmpty())
  66390. {
  66391. Typeface* const typeface = getTypeface();
  66392. const juce_wchar* t = (const juce_wchar*) text;
  66393. do
  66394. {
  66395. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (*t++);
  66396. if (glyph != 0)
  66397. x += kerning + glyph->getHorizontalSpacing (*t);
  66398. }
  66399. while (*t != 0);
  66400. x *= height;
  66401. x *= horizontalScale;
  66402. }
  66403. return x;
  66404. }
  66405. Typeface* Font::getTypeface() const throw()
  66406. {
  66407. if (typeface == 0)
  66408. typeface = Typeface::getTypefaceFor (*this);
  66409. return typeface;
  66410. }
  66411. void Font::findFonts (OwnedArray<Font>& destArray) throw()
  66412. {
  66413. const StringArray names (findAllTypefaceNames());
  66414. for (int i = 0; i < names.size(); ++i)
  66415. destArray.add (new Font (names[i], defaultFontHeight, Font::plain));
  66416. }
  66417. END_JUCE_NAMESPACE
  66418. /********* End of inlined file: juce_Font.cpp *********/
  66419. /********* Start of inlined file: juce_GlyphArrangement.cpp *********/
  66420. BEGIN_JUCE_NAMESPACE
  66421. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  66422. class FontGlyphAlphaMap
  66423. {
  66424. public:
  66425. bool draw (const Graphics& g, float x, const float y) const throw()
  66426. {
  66427. if (bitmap1 == 0)
  66428. return false;
  66429. x += xOrigin;
  66430. const float xFloor = floorf (x);
  66431. const int intX = (int) xFloor;
  66432. g.drawImageAt (((x - xFloor) >= 0.5f && bitmap2 != 0) ? bitmap2 : bitmap1,
  66433. intX, (int) floorf (y + yOrigin), true);
  66434. return true;
  66435. }
  66436. juce_UseDebuggingNewOperator
  66437. private:
  66438. Image* bitmap1;
  66439. Image* bitmap2;
  66440. float xOrigin, yOrigin;
  66441. int lastAccessCount;
  66442. Typeface::Ptr typeface;
  66443. float height, horizontalScale;
  66444. juce_wchar character;
  66445. friend class GlyphCache;
  66446. FontGlyphAlphaMap() throw()
  66447. : bitmap1 (0),
  66448. bitmap2 (0),
  66449. lastAccessCount (0),
  66450. height (0),
  66451. horizontalScale (0),
  66452. character (0)
  66453. {
  66454. }
  66455. ~FontGlyphAlphaMap() throw()
  66456. {
  66457. delete bitmap1;
  66458. delete bitmap2;
  66459. }
  66460. class AlphaBitmapRenderer
  66461. {
  66462. uint8* const data;
  66463. const int stride;
  66464. uint8* lineStart;
  66465. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  66466. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  66467. public:
  66468. AlphaBitmapRenderer (uint8* const data_,
  66469. const int stride_) throw()
  66470. : data (data_),
  66471. stride (stride_)
  66472. {
  66473. }
  66474. forcedinline void setEdgeTableYPos (const int y) throw()
  66475. {
  66476. lineStart = data + (stride * y);
  66477. }
  66478. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  66479. {
  66480. lineStart [x] = (uint8) alphaLevel;
  66481. }
  66482. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  66483. {
  66484. uint8* d = lineStart + x;
  66485. while (--width >= 0)
  66486. *d++ = (uint8) alphaLevel;
  66487. }
  66488. };
  66489. Image* createAlphaMapFromPath (const Path& path,
  66490. float& topLeftX, float& topLeftY,
  66491. float xScale, float yScale,
  66492. const float subPixelOffsetX) throw()
  66493. {
  66494. Image* im = 0;
  66495. float px, py, pw, ph;
  66496. path.getBounds (px, py, pw, ph);
  66497. topLeftX = floorf (px * xScale);
  66498. topLeftY = floorf (py * yScale);
  66499. int bitmapWidth = roundFloatToInt (pw * xScale) + 2;
  66500. int bitmapHeight = roundFloatToInt (ph * yScale) + 2;
  66501. im = new Image (Image::SingleChannel, bitmapWidth, bitmapHeight, true);
  66502. EdgeTable edgeTable (0, bitmapHeight, EdgeTable::Oversampling_16times);
  66503. edgeTable.addPath (path, AffineTransform::scale (xScale, yScale)
  66504. .translated (subPixelOffsetX - topLeftX, -topLeftY));
  66505. int stride, pixelStride;
  66506. uint8* const pixels = (uint8*) im->lockPixelDataReadWrite (0, 0, bitmapWidth, bitmapHeight, stride, pixelStride);
  66507. jassert (pixelStride == 1);
  66508. AlphaBitmapRenderer renderer (pixels, stride);
  66509. edgeTable.iterate (renderer, 0, 0, bitmapWidth, bitmapHeight, 0);
  66510. im->releasePixelDataReadWrite (pixels);
  66511. return im;
  66512. }
  66513. void generate (Typeface* const face,
  66514. const juce_wchar character_,
  66515. const float fontHeight,
  66516. const float fontHorizontalScale) throw()
  66517. {
  66518. character = character_;
  66519. typeface = face;
  66520. height = fontHeight;
  66521. horizontalScale = fontHorizontalScale;
  66522. const Path* const glyphPath = face->getOutlineForGlyph (character_);
  66523. deleteAndZero (bitmap1);
  66524. deleteAndZero (bitmap2);
  66525. const float fontHScale = fontHeight * fontHorizontalScale;
  66526. if (glyphPath != 0 && ! glyphPath->isEmpty())
  66527. {
  66528. bitmap1 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.0f);
  66529. if (fontHScale < 24.0f)
  66530. bitmap2 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.5f);
  66531. }
  66532. else
  66533. {
  66534. xOrigin = yOrigin = 0;
  66535. }
  66536. }
  66537. };
  66538. static const int defaultNumGlyphsToCache = 120;
  66539. class GlyphCache;
  66540. static GlyphCache* cacheInstance = 0;
  66541. class GlyphCache : private DeletedAtShutdown
  66542. {
  66543. public:
  66544. static GlyphCache* getInstance() throw()
  66545. {
  66546. if (cacheInstance == 0)
  66547. cacheInstance = new GlyphCache();
  66548. return cacheInstance;
  66549. }
  66550. const FontGlyphAlphaMap& getGlyphFor (Typeface* const typeface,
  66551. const float fontHeight,
  66552. const float fontHorizontalScale,
  66553. const juce_wchar character) throw()
  66554. {
  66555. ++accessCounter;
  66556. int oldestCounter = INT_MAX;
  66557. int oldestIndex = 0;
  66558. for (int i = numGlyphs; --i >= 0;)
  66559. {
  66560. FontGlyphAlphaMap& g = glyphs[i];
  66561. if (g.character == character
  66562. && g.height == fontHeight
  66563. && g.typeface->hashCode() == typeface->hashCode()
  66564. && g.horizontalScale == fontHorizontalScale)
  66565. {
  66566. g.lastAccessCount = accessCounter;
  66567. ++hits;
  66568. return g;
  66569. }
  66570. if (oldestCounter > g.lastAccessCount)
  66571. {
  66572. oldestCounter = g.lastAccessCount;
  66573. oldestIndex = i;
  66574. }
  66575. }
  66576. ++misses;
  66577. if (hits + misses > (numGlyphs << 4))
  66578. {
  66579. if (misses * 2 > hits)
  66580. setCacheSize (numGlyphs + 32);
  66581. hits = 0;
  66582. misses = 0;
  66583. oldestIndex = 0;
  66584. }
  66585. FontGlyphAlphaMap& oldest = glyphs [oldestIndex];
  66586. oldest.lastAccessCount = accessCounter;
  66587. oldest.generate (typeface,
  66588. character,
  66589. fontHeight,
  66590. fontHorizontalScale);
  66591. return oldest;
  66592. }
  66593. void setCacheSize (const int num) throw()
  66594. {
  66595. if (numGlyphs != num)
  66596. {
  66597. numGlyphs = num;
  66598. if (glyphs != 0)
  66599. delete[] glyphs;
  66600. glyphs = new FontGlyphAlphaMap [numGlyphs];
  66601. hits = 0;
  66602. misses = 0;
  66603. }
  66604. }
  66605. juce_UseDebuggingNewOperator
  66606. private:
  66607. FontGlyphAlphaMap* glyphs;
  66608. int numGlyphs, accessCounter;
  66609. int hits, misses;
  66610. GlyphCache() throw()
  66611. : glyphs (0),
  66612. numGlyphs (0),
  66613. accessCounter (0)
  66614. {
  66615. setCacheSize (defaultNumGlyphsToCache);
  66616. }
  66617. ~GlyphCache() throw()
  66618. {
  66619. delete[] glyphs;
  66620. jassert (cacheInstance == this);
  66621. cacheInstance = 0;
  66622. }
  66623. GlyphCache (const GlyphCache&);
  66624. const GlyphCache& operator= (const GlyphCache&);
  66625. };
  66626. PositionedGlyph::PositionedGlyph() throw()
  66627. {
  66628. }
  66629. void PositionedGlyph::draw (const Graphics& g) const throw()
  66630. {
  66631. if (! glyphInfo->isWhitespace())
  66632. {
  66633. if (fontHeight < 100.0f && fontHeight > 0.1f && ! g.isVectorDevice())
  66634. {
  66635. const FontGlyphAlphaMap& alphaMap
  66636. = GlyphCache::getInstance()->getGlyphFor (glyphInfo->getTypeface(),
  66637. fontHeight,
  66638. fontHorizontalScale,
  66639. getCharacter());
  66640. alphaMap.draw (g, x, y);
  66641. }
  66642. else
  66643. {
  66644. // that's a bit of a dodgy size, isn't it??
  66645. jassert (fontHeight > 0.0f && fontHeight < 4000.0f);
  66646. draw (g, AffineTransform::identity);
  66647. }
  66648. }
  66649. }
  66650. void PositionedGlyph::draw (const Graphics& g,
  66651. const AffineTransform& transform) const throw()
  66652. {
  66653. if (! glyphInfo->isWhitespace())
  66654. {
  66655. g.fillPath (glyphInfo->getPath(),
  66656. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  66657. .translated (x, y)
  66658. .followedBy (transform));
  66659. }
  66660. }
  66661. void PositionedGlyph::createPath (Path& path) const throw()
  66662. {
  66663. if (! glyphInfo->isWhitespace())
  66664. {
  66665. path.addPath (glyphInfo->getPath(),
  66666. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  66667. .translated (x, y));
  66668. }
  66669. }
  66670. bool PositionedGlyph::hitTest (float px, float py) const throw()
  66671. {
  66672. if (px >= getLeft() && px < getRight()
  66673. && py >= getTop() && py < getBottom()
  66674. && fontHeight > 0.0f
  66675. && ! glyphInfo->isWhitespace())
  66676. {
  66677. AffineTransform::translation (-x, -y)
  66678. .scaled (1.0f / (fontHeight * fontHorizontalScale), 1.0f / fontHeight)
  66679. .transformPoint (px, py);
  66680. return glyphInfo->getPath().contains (px, py);
  66681. }
  66682. return false;
  66683. }
  66684. void PositionedGlyph::moveBy (const float deltaX,
  66685. const float deltaY) throw()
  66686. {
  66687. x += deltaX;
  66688. y += deltaY;
  66689. }
  66690. GlyphArrangement::GlyphArrangement() throw()
  66691. : numGlyphs (0),
  66692. numAllocated (0),
  66693. glyphs (0)
  66694. {
  66695. }
  66696. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other) throw()
  66697. : numGlyphs (0),
  66698. numAllocated (0),
  66699. glyphs (0)
  66700. {
  66701. addGlyphArrangement (other);
  66702. }
  66703. const GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other) throw()
  66704. {
  66705. if (this != &other)
  66706. {
  66707. clear();
  66708. addGlyphArrangement (other);
  66709. }
  66710. return *this;
  66711. }
  66712. GlyphArrangement::~GlyphArrangement() throw()
  66713. {
  66714. clear();
  66715. juce_free (glyphs);
  66716. }
  66717. void GlyphArrangement::ensureNumGlyphsAllocated (const int minGlyphs) throw()
  66718. {
  66719. if (numAllocated <= minGlyphs)
  66720. {
  66721. numAllocated = minGlyphs + 2;
  66722. if (glyphs == 0)
  66723. glyphs = (PositionedGlyph*) juce_malloc (numAllocated * sizeof (PositionedGlyph));
  66724. else
  66725. glyphs = (PositionedGlyph*) juce_realloc (glyphs, numAllocated * sizeof (PositionedGlyph));
  66726. }
  66727. }
  66728. void GlyphArrangement::incGlyphRefCount (const int i) const throw()
  66729. {
  66730. jassert (((unsigned int) i) < (unsigned int) numGlyphs);
  66731. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  66732. glyphs[i].glyphInfo->getTypeface()->incReferenceCount();
  66733. }
  66734. void GlyphArrangement::decGlyphRefCount (const int i) const throw()
  66735. {
  66736. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  66737. glyphs[i].glyphInfo->getTypeface()->decReferenceCount();
  66738. }
  66739. void GlyphArrangement::clear() throw()
  66740. {
  66741. for (int i = numGlyphs; --i >= 0;)
  66742. decGlyphRefCount (i);
  66743. numGlyphs = 0;
  66744. }
  66745. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const throw()
  66746. {
  66747. jassert (((unsigned int) index) < (unsigned int) numGlyphs);
  66748. return glyphs [index];
  66749. }
  66750. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other) throw()
  66751. {
  66752. ensureNumGlyphsAllocated (numGlyphs + other.numGlyphs);
  66753. memcpy (glyphs + numGlyphs, other.glyphs,
  66754. other.numGlyphs * sizeof (PositionedGlyph));
  66755. for (int i = other.numGlyphs; --i >= 0;)
  66756. incGlyphRefCount (numGlyphs++);
  66757. }
  66758. void GlyphArrangement::removeLast() throw()
  66759. {
  66760. if (numGlyphs > 0)
  66761. decGlyphRefCount (--numGlyphs);
  66762. }
  66763. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num) throw()
  66764. {
  66765. jassert (startIndex >= 0);
  66766. if (startIndex < 0)
  66767. startIndex = 0;
  66768. if (num < 0 || startIndex + num >= numGlyphs)
  66769. {
  66770. while (numGlyphs > startIndex)
  66771. removeLast();
  66772. }
  66773. else if (num > 0)
  66774. {
  66775. int i;
  66776. for (i = startIndex; i < startIndex + num; ++i)
  66777. decGlyphRefCount (i);
  66778. for (i = numGlyphs - (startIndex + num); --i >= 0;)
  66779. {
  66780. glyphs [startIndex] = glyphs [startIndex + num];
  66781. ++startIndex;
  66782. }
  66783. numGlyphs -= num;
  66784. }
  66785. }
  66786. void GlyphArrangement::addLineOfText (const Font& font,
  66787. const String& text,
  66788. const float xOffset,
  66789. const float yOffset) throw()
  66790. {
  66791. addCurtailedLineOfText (font, text,
  66792. xOffset, yOffset,
  66793. 1.0e10f, false);
  66794. }
  66795. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  66796. const String& text,
  66797. float xOffset,
  66798. const float yOffset,
  66799. const float maxWidthPixels,
  66800. const bool useEllipsis) throw()
  66801. {
  66802. const int textLen = text.length();
  66803. if (textLen > 0)
  66804. {
  66805. ensureNumGlyphsAllocated (numGlyphs + textLen + 3); // extra chars for ellipsis
  66806. Typeface* const typeface = font.getTypeface();
  66807. const float fontHeight = font.getHeight();
  66808. const float ascent = font.getAscent();
  66809. const float fontHorizontalScale = font.getHorizontalScale();
  66810. const float heightTimesScale = fontHorizontalScale * fontHeight;
  66811. const float kerningFactor = font.getExtraKerningFactor();
  66812. const float startX = xOffset;
  66813. const juce_wchar* const unicodeText = (const juce_wchar*) text;
  66814. for (int i = 0; i < textLen; ++i)
  66815. {
  66816. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (unicodeText[i]);
  66817. if (glyph != 0)
  66818. {
  66819. jassert (numAllocated > numGlyphs);
  66820. ensureNumGlyphsAllocated (numGlyphs);
  66821. PositionedGlyph& pg = glyphs [numGlyphs];
  66822. pg.glyphInfo = glyph;
  66823. pg.x = xOffset;
  66824. pg.y = yOffset;
  66825. pg.w = heightTimesScale * glyph->getHorizontalSpacing (0);
  66826. pg.fontHeight = fontHeight;
  66827. pg.fontAscent = ascent;
  66828. pg.fontHorizontalScale = fontHorizontalScale;
  66829. pg.isUnderlined = font.isUnderlined();
  66830. xOffset += heightTimesScale * (kerningFactor + glyph->getHorizontalSpacing (unicodeText [i + 1]));
  66831. if (xOffset - startX > maxWidthPixels + 1.0f)
  66832. {
  66833. // curtail the string if it's too wide..
  66834. if (useEllipsis && textLen > 3 && numGlyphs >= 3)
  66835. appendEllipsis (font, startX + maxWidthPixels);
  66836. break;
  66837. }
  66838. else
  66839. {
  66840. if (glyph->getTypeface() != 0)
  66841. glyph->getTypeface()->incReferenceCount();
  66842. ++numGlyphs;
  66843. }
  66844. }
  66845. }
  66846. }
  66847. }
  66848. void GlyphArrangement::appendEllipsis (const Font& font, const float maxXPixels) throw()
  66849. {
  66850. const TypefaceGlyphInfo* const dotGlyph = font.getTypeface()->getGlyph (T('.'));
  66851. if (dotGlyph != 0)
  66852. {
  66853. if (numGlyphs > 0)
  66854. {
  66855. PositionedGlyph& glyph = glyphs [numGlyphs - 1];
  66856. const float fontHeight = glyph.fontHeight;
  66857. const float fontHorizontalScale = glyph.fontHorizontalScale;
  66858. const float fontAscent = glyph.fontAscent;
  66859. const float dx = fontHeight * fontHorizontalScale
  66860. * (font.getExtraKerningFactor() + dotGlyph->getHorizontalSpacing (T('.')));
  66861. float xOffset = 0.0f, yOffset = 0.0f;
  66862. for (int dotPos = 3; --dotPos >= 0 && numGlyphs > 0;)
  66863. {
  66864. removeLast();
  66865. jassert (numAllocated > numGlyphs);
  66866. PositionedGlyph& pg = glyphs [numGlyphs];
  66867. xOffset = pg.x;
  66868. yOffset = pg.y;
  66869. if (numGlyphs == 0 || xOffset + dx * 3 <= maxXPixels)
  66870. break;
  66871. }
  66872. for (int i = 3; --i >= 0;)
  66873. {
  66874. jassert (numAllocated > numGlyphs);
  66875. ensureNumGlyphsAllocated (numGlyphs);
  66876. PositionedGlyph& pg = glyphs [numGlyphs];
  66877. pg.glyphInfo = dotGlyph;
  66878. pg.x = xOffset;
  66879. pg.y = yOffset;
  66880. pg.w = dx;
  66881. pg.fontHeight = fontHeight;
  66882. pg.fontAscent = fontAscent;
  66883. pg.fontHorizontalScale = fontHorizontalScale;
  66884. pg.isUnderlined = font.isUnderlined();
  66885. xOffset += dx;
  66886. if (dotGlyph->getTypeface() != 0)
  66887. dotGlyph->getTypeface()->incReferenceCount();
  66888. ++numGlyphs;
  66889. }
  66890. }
  66891. }
  66892. }
  66893. void GlyphArrangement::addJustifiedText (const Font& font,
  66894. const String& text,
  66895. float x, float y,
  66896. const float maxLineWidth,
  66897. const Justification& horizontalLayout) throw()
  66898. {
  66899. int lineStartIndex = numGlyphs;
  66900. addLineOfText (font, text, x, y);
  66901. const float originalY = y;
  66902. while (lineStartIndex < numGlyphs)
  66903. {
  66904. int i = lineStartIndex;
  66905. if (glyphs[i].getCharacter() != T('\n') && glyphs[i].getCharacter() != T('\r'))
  66906. ++i;
  66907. const float lineMaxX = glyphs [lineStartIndex].getLeft() + maxLineWidth;
  66908. int lastWordBreakIndex = -1;
  66909. while (i < numGlyphs)
  66910. {
  66911. PositionedGlyph& pg = glyphs[i];
  66912. const juce_wchar c = pg.getCharacter();
  66913. if (c == T('\r') || c == T('\n'))
  66914. {
  66915. ++i;
  66916. if (c == T('\r') && i < numGlyphs && glyphs [i].getCharacter() == T('\n'))
  66917. ++i;
  66918. break;
  66919. }
  66920. else if (pg.isWhitespace())
  66921. {
  66922. lastWordBreakIndex = i + 1;
  66923. }
  66924. else if (SHOULD_WRAP (pg.getRight(), lineMaxX))
  66925. {
  66926. if (lastWordBreakIndex >= 0)
  66927. i = lastWordBreakIndex;
  66928. break;
  66929. }
  66930. ++i;
  66931. }
  66932. const float currentLineStartX = glyphs [lineStartIndex].getLeft();
  66933. float currentLineEndX = currentLineStartX;
  66934. for (int j = i; --j >= lineStartIndex;)
  66935. {
  66936. if (! glyphs[j].isWhitespace())
  66937. {
  66938. currentLineEndX = glyphs[j].getRight();
  66939. break;
  66940. }
  66941. }
  66942. float deltaX = 0.0f;
  66943. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  66944. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  66945. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  66946. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  66947. else if (horizontalLayout.testFlags (Justification::right))
  66948. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  66949. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  66950. x + deltaX - currentLineStartX, y - originalY);
  66951. lineStartIndex = i;
  66952. y += font.getHeight();
  66953. }
  66954. }
  66955. void GlyphArrangement::addFittedText (const Font& f,
  66956. const String& text,
  66957. float x, float y,
  66958. float width, float height,
  66959. const Justification& layout,
  66960. int maximumLines,
  66961. const float minimumHorizontalScale) throw()
  66962. {
  66963. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  66964. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  66965. if (text.containsAnyOf (T("\r\n")))
  66966. {
  66967. GlyphArrangement ga;
  66968. ga.addJustifiedText (f, text, x, y, width, layout);
  66969. float l, t, r, b;
  66970. ga.getBoundingBox (0, -1, l, t, r, b, false);
  66971. float dy = y - t;
  66972. if (layout.testFlags (Justification::verticallyCentred))
  66973. dy += (height - (b - t)) * 0.5f;
  66974. else if (layout.testFlags (Justification::bottom))
  66975. dy += height - (b - t);
  66976. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  66977. addGlyphArrangement (ga);
  66978. return;
  66979. }
  66980. int startIndex = numGlyphs;
  66981. addLineOfText (f, text.trim(), x, y);
  66982. if (numGlyphs > startIndex)
  66983. {
  66984. float lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  66985. if (lineWidth <= 0)
  66986. return;
  66987. if (lineWidth * minimumHorizontalScale < width)
  66988. {
  66989. if (lineWidth > width)
  66990. {
  66991. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex,
  66992. width / lineWidth);
  66993. }
  66994. justifyGlyphs (startIndex, numGlyphs - startIndex,
  66995. x, y, width, height, layout);
  66996. }
  66997. else if (maximumLines <= 1)
  66998. {
  66999. const float ratio = jmax (minimumHorizontalScale, width / lineWidth);
  67000. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex, ratio);
  67001. while (numGlyphs > 0 && glyphs [numGlyphs - 1].x + glyphs [numGlyphs - 1].w >= x + width)
  67002. removeLast();
  67003. appendEllipsis (f, x + width);
  67004. justifyGlyphs (startIndex, numGlyphs - startIndex,
  67005. x, y, width, height, layout);
  67006. }
  67007. else
  67008. {
  67009. Font font (f);
  67010. String txt (text.trim());
  67011. const int length = txt.length();
  67012. int numLines = 1;
  67013. const int originalStartIndex = startIndex;
  67014. if (length <= 12 && ! txt.containsAnyOf (T(" -\t\r\n")))
  67015. maximumLines = 1;
  67016. maximumLines = jmin (maximumLines, length);
  67017. while (numLines < maximumLines)
  67018. {
  67019. ++numLines;
  67020. const float newFontHeight = height / (float)numLines;
  67021. if (newFontHeight < 8.0f)
  67022. break;
  67023. if (newFontHeight < font.getHeight())
  67024. {
  67025. font.setHeight (newFontHeight);
  67026. while (numGlyphs > startIndex)
  67027. removeLast();
  67028. addLineOfText (font, txt, x, y);
  67029. lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  67030. }
  67031. if (numLines > lineWidth / width)
  67032. break;
  67033. }
  67034. if (numLines < 1)
  67035. numLines = 1;
  67036. float lineY = y;
  67037. float widthPerLine = lineWidth / numLines;
  67038. int lastLineStartIndex = 0;
  67039. for (int line = 0; line < numLines; ++line)
  67040. {
  67041. int i = startIndex;
  67042. lastLineStartIndex = i;
  67043. float lineStartX = glyphs[startIndex].getLeft();
  67044. while (i < numGlyphs)
  67045. {
  67046. lineWidth = (glyphs[i].getRight() - lineStartX);
  67047. if (lineWidth > widthPerLine)
  67048. {
  67049. // got to a point where the line's too long, so skip forward to find a
  67050. // good place to break it..
  67051. const int searchStartIndex = i;
  67052. while (i < numGlyphs)
  67053. {
  67054. if ((glyphs[i].getRight() - lineStartX) * minimumHorizontalScale < width)
  67055. {
  67056. if (glyphs[i].isWhitespace()
  67057. || glyphs[i].getCharacter() == T('-'))
  67058. {
  67059. ++i;
  67060. break;
  67061. }
  67062. }
  67063. else
  67064. {
  67065. // can't find a suitable break, so try looking backwards..
  67066. i = searchStartIndex;
  67067. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  67068. {
  67069. if (glyphs[i - back].isWhitespace()
  67070. || glyphs[i - back].getCharacter() == T('-'))
  67071. {
  67072. i -= back - 1;
  67073. break;
  67074. }
  67075. }
  67076. break;
  67077. }
  67078. ++i;
  67079. }
  67080. break;
  67081. }
  67082. ++i;
  67083. }
  67084. int wsStart = i;
  67085. while (wsStart > 0 && glyphs[wsStart - 1].isWhitespace())
  67086. --wsStart;
  67087. int wsEnd = i;
  67088. while (wsEnd < numGlyphs && glyphs[wsEnd].isWhitespace())
  67089. ++wsEnd;
  67090. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  67091. i = jmax (wsStart, startIndex + 1);
  67092. lineWidth = glyphs[i - 1].getRight() - lineStartX;
  67093. if (lineWidth > width)
  67094. {
  67095. stretchRangeOfGlyphs (startIndex, i - startIndex,
  67096. width / lineWidth);
  67097. }
  67098. justifyGlyphs (startIndex, i - startIndex,
  67099. x, lineY, width, font.getHeight(),
  67100. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  67101. startIndex = i;
  67102. lineY += font.getHeight();
  67103. if (startIndex >= numGlyphs)
  67104. break;
  67105. }
  67106. if (startIndex < numGlyphs)
  67107. {
  67108. while (numGlyphs > startIndex)
  67109. removeLast();
  67110. if (startIndex - originalStartIndex > 4)
  67111. {
  67112. const float lineStartX = glyphs[lastLineStartIndex].getLeft();
  67113. appendEllipsis (font, lineStartX + width);
  67114. lineWidth = glyphs[startIndex - 1].getRight() - lineStartX;
  67115. if (lineWidth > width)
  67116. {
  67117. stretchRangeOfGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  67118. width / lineWidth);
  67119. }
  67120. justifyGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  67121. x, lineY - font.getHeight(), width, font.getHeight(),
  67122. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  67123. }
  67124. startIndex = numGlyphs;
  67125. }
  67126. justifyGlyphs (originalStartIndex, startIndex - originalStartIndex,
  67127. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  67128. }
  67129. }
  67130. }
  67131. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  67132. const float dx, const float dy) throw()
  67133. {
  67134. jassert (startIndex >= 0);
  67135. if (dx != 0.0f || dy != 0.0f)
  67136. {
  67137. if (num < 0 || startIndex + num > numGlyphs)
  67138. num = numGlyphs - startIndex;
  67139. while (--num >= 0)
  67140. {
  67141. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  67142. glyphs [startIndex++].moveBy (dx, dy);
  67143. }
  67144. }
  67145. }
  67146. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  67147. const float horizontalScaleFactor) throw()
  67148. {
  67149. jassert (startIndex >= 0);
  67150. if (num < 0 || startIndex + num > numGlyphs)
  67151. num = numGlyphs - startIndex;
  67152. if (num > 0)
  67153. {
  67154. const float xAnchor = glyphs[startIndex].getLeft();
  67155. while (--num >= 0)
  67156. {
  67157. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  67158. PositionedGlyph& pg = glyphs[startIndex++];
  67159. pg.x = xAnchor + (pg.x - xAnchor) * horizontalScaleFactor;
  67160. pg.fontHorizontalScale *= horizontalScaleFactor;
  67161. pg.w *= horizontalScaleFactor;
  67162. }
  67163. }
  67164. }
  67165. void GlyphArrangement::getBoundingBox (int startIndex, int num,
  67166. float& left,
  67167. float& top,
  67168. float& right,
  67169. float& bottom,
  67170. const bool includeWhitespace) const throw()
  67171. {
  67172. jassert (startIndex >= 0);
  67173. if (num < 0 || startIndex + num > numGlyphs)
  67174. num = numGlyphs - startIndex;
  67175. left = 0.0f;
  67176. top = 0.0f;
  67177. right = 0.0f;
  67178. bottom = 0.0f;
  67179. bool isFirst = true;
  67180. while (--num >= 0)
  67181. {
  67182. const PositionedGlyph& pg = glyphs [startIndex++];
  67183. if (includeWhitespace || ! pg.isWhitespace())
  67184. {
  67185. if (isFirst)
  67186. {
  67187. isFirst = false;
  67188. left = pg.getLeft();
  67189. top = pg.getTop();
  67190. right = pg.getRight();
  67191. bottom = pg.getBottom();
  67192. }
  67193. else
  67194. {
  67195. left = jmin (left, pg.getLeft());
  67196. top = jmin (top, pg.getTop());
  67197. right = jmax (right, pg.getRight());
  67198. bottom = jmax (bottom, pg.getBottom());
  67199. }
  67200. }
  67201. }
  67202. }
  67203. void GlyphArrangement::justifyGlyphs (const int startIndex,
  67204. const int num,
  67205. const float x, const float y,
  67206. const float width, const float height,
  67207. const Justification& justification) throw()
  67208. {
  67209. jassert (num >= 0 && startIndex >= 0);
  67210. if (numGlyphs > 0 && num > 0)
  67211. {
  67212. float left, top, right, bottom;
  67213. getBoundingBox (startIndex, num, left, top, right, bottom,
  67214. ! justification.testFlags (Justification::horizontallyJustified
  67215. | Justification::horizontallyCentred));
  67216. float deltaX = 0.0f;
  67217. if (justification.testFlags (Justification::horizontallyJustified))
  67218. deltaX = x - left;
  67219. else if (justification.testFlags (Justification::horizontallyCentred))
  67220. deltaX = x + (width - (right - left)) * 0.5f - left;
  67221. else if (justification.testFlags (Justification::right))
  67222. deltaX = (x + width) - right;
  67223. else
  67224. deltaX = x - left;
  67225. float deltaY = 0.0f;
  67226. if (justification.testFlags (Justification::top))
  67227. deltaY = y - top;
  67228. else if (justification.testFlags (Justification::bottom))
  67229. deltaY = (y + height) - bottom;
  67230. else
  67231. deltaY = y + (height - (bottom - top)) * 0.5f - top;
  67232. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  67233. if (justification.testFlags (Justification::horizontallyJustified))
  67234. {
  67235. int lineStart = 0;
  67236. float baseY = glyphs [startIndex].getBaselineY();
  67237. int i;
  67238. for (i = 0; i < num; ++i)
  67239. {
  67240. const float glyphY = glyphs [startIndex + i].getBaselineY();
  67241. if (glyphY != baseY)
  67242. {
  67243. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  67244. lineStart = i;
  67245. baseY = glyphY;
  67246. }
  67247. }
  67248. if (i > lineStart)
  67249. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  67250. }
  67251. }
  67252. }
  67253. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth) throw()
  67254. {
  67255. if (start + num < numGlyphs
  67256. && glyphs [start + num - 1].getCharacter() != T('\r')
  67257. && glyphs [start + num - 1].getCharacter() != T('\n'))
  67258. {
  67259. int numSpaces = 0;
  67260. int spacesAtEnd = 0;
  67261. for (int i = 0; i < num; ++i)
  67262. {
  67263. if (glyphs [start + i].isWhitespace())
  67264. {
  67265. ++spacesAtEnd;
  67266. ++numSpaces;
  67267. }
  67268. else
  67269. {
  67270. spacesAtEnd = 0;
  67271. }
  67272. }
  67273. numSpaces -= spacesAtEnd;
  67274. if (numSpaces > 0)
  67275. {
  67276. const float startX = glyphs [start].getLeft();
  67277. const float endX = glyphs [start + num - 1 - spacesAtEnd].getRight();
  67278. const float extraPaddingBetweenWords
  67279. = (targetWidth - (endX - startX)) / (float) numSpaces;
  67280. float deltaX = 0.0f;
  67281. for (int i = 0; i < num; ++i)
  67282. {
  67283. glyphs [start + i].moveBy (deltaX, 0.0);
  67284. if (glyphs [start + i].isWhitespace())
  67285. deltaX += extraPaddingBetweenWords;
  67286. }
  67287. }
  67288. }
  67289. }
  67290. void GlyphArrangement::draw (const Graphics& g) const throw()
  67291. {
  67292. for (int i = 0; i < numGlyphs; ++i)
  67293. {
  67294. glyphs[i].draw (g);
  67295. if (glyphs[i].isUnderlined)
  67296. {
  67297. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  67298. juce_wchar nextChar = 0;
  67299. if (i < numGlyphs - 1
  67300. && glyphs[i + 1].y == glyphs[i].y)
  67301. {
  67302. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  67303. }
  67304. g.fillRect (glyphs[i].x,
  67305. glyphs[i].y + lineThickness * 2.0f,
  67306. glyphs[i].fontHeight
  67307. * glyphs[i].fontHorizontalScale
  67308. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  67309. lineThickness);
  67310. }
  67311. }
  67312. }
  67313. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const throw()
  67314. {
  67315. for (int i = 0; i < numGlyphs; ++i)
  67316. {
  67317. glyphs[i].draw (g, transform);
  67318. if (glyphs[i].isUnderlined)
  67319. {
  67320. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  67321. juce_wchar nextChar = 0;
  67322. if (i < numGlyphs - 1
  67323. && glyphs[i + 1].y == glyphs[i].y)
  67324. {
  67325. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  67326. }
  67327. Path p;
  67328. p.addLineSegment (glyphs[i].x,
  67329. glyphs[i].y + lineThickness * 2.5f,
  67330. glyphs[i].x + glyphs[i].fontHeight
  67331. * glyphs[i].fontHorizontalScale
  67332. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  67333. glyphs[i].y + lineThickness * 2.5f,
  67334. lineThickness);
  67335. g.fillPath (p, transform);
  67336. }
  67337. }
  67338. }
  67339. void GlyphArrangement::createPath (Path& path) const throw()
  67340. {
  67341. for (int i = 0; i < numGlyphs; ++i)
  67342. glyphs[i].createPath (path);
  67343. }
  67344. int GlyphArrangement::findGlyphIndexAt (float x, float y) const throw()
  67345. {
  67346. for (int i = 0; i < numGlyphs; ++i)
  67347. if (glyphs[i].hitTest (x, y))
  67348. return i;
  67349. return -1;
  67350. }
  67351. END_JUCE_NAMESPACE
  67352. /********* End of inlined file: juce_GlyphArrangement.cpp *********/
  67353. /********* Start of inlined file: juce_TextLayout.cpp *********/
  67354. BEGIN_JUCE_NAMESPACE
  67355. class TextLayoutToken
  67356. {
  67357. public:
  67358. String text;
  67359. Font font;
  67360. int x, y, w, h;
  67361. int line, lineHeight;
  67362. bool isWhitespace, isNewLine;
  67363. TextLayoutToken (const String& t,
  67364. const Font& f,
  67365. const bool isWhitespace_) throw()
  67366. : text (t),
  67367. font (f),
  67368. x(0),
  67369. y(0),
  67370. isWhitespace (isWhitespace_)
  67371. {
  67372. w = font.getStringWidth (t);
  67373. h = roundFloatToInt (f.getHeight());
  67374. isNewLine = t.containsAnyOf (T("\r\n"));
  67375. }
  67376. TextLayoutToken (const TextLayoutToken& other) throw()
  67377. : text (other.text),
  67378. font (other.font),
  67379. x (other.x),
  67380. y (other.y),
  67381. w (other.w),
  67382. h (other.h),
  67383. line (other.line),
  67384. lineHeight (other.lineHeight),
  67385. isWhitespace (other.isWhitespace),
  67386. isNewLine (other.isNewLine)
  67387. {
  67388. }
  67389. ~TextLayoutToken() throw()
  67390. {
  67391. }
  67392. void draw (Graphics& g,
  67393. const int xOffset,
  67394. const int yOffset) throw()
  67395. {
  67396. if (! isWhitespace)
  67397. {
  67398. g.setFont (font);
  67399. g.drawSingleLineText (text.trimEnd(),
  67400. xOffset + x,
  67401. yOffset + y + (lineHeight - h)
  67402. + roundFloatToInt (font.getAscent()));
  67403. }
  67404. }
  67405. juce_UseDebuggingNewOperator
  67406. };
  67407. TextLayout::TextLayout() throw()
  67408. : tokens (64),
  67409. totalLines (0)
  67410. {
  67411. }
  67412. TextLayout::TextLayout (const String& text,
  67413. const Font& font) throw()
  67414. : tokens (64),
  67415. totalLines (0)
  67416. {
  67417. appendText (text, font);
  67418. }
  67419. TextLayout::TextLayout (const TextLayout& other) throw()
  67420. : tokens (64),
  67421. totalLines (0)
  67422. {
  67423. *this = other;
  67424. }
  67425. const TextLayout& TextLayout::operator= (const TextLayout& other) throw()
  67426. {
  67427. if (this != &other)
  67428. {
  67429. clear();
  67430. totalLines = other.totalLines;
  67431. for (int i = 0; i < other.tokens.size(); ++i)
  67432. tokens.add (new TextLayoutToken (*(const TextLayoutToken*)(other.tokens.getUnchecked(i))));
  67433. }
  67434. return *this;
  67435. }
  67436. TextLayout::~TextLayout() throw()
  67437. {
  67438. clear();
  67439. }
  67440. void TextLayout::clear() throw()
  67441. {
  67442. for (int i = tokens.size(); --i >= 0;)
  67443. {
  67444. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  67445. delete t;
  67446. }
  67447. tokens.clear();
  67448. totalLines = 0;
  67449. }
  67450. void TextLayout::appendText (const String& text,
  67451. const Font& font) throw()
  67452. {
  67453. const tchar* t = text;
  67454. String currentString;
  67455. int lastCharType = 0;
  67456. for (;;)
  67457. {
  67458. const tchar c = *t++;
  67459. if (c == 0)
  67460. break;
  67461. int charType;
  67462. if (c == T('\r') || c == T('\n'))
  67463. {
  67464. charType = 0;
  67465. }
  67466. else if (CharacterFunctions::isWhitespace (c))
  67467. {
  67468. charType = 2;
  67469. }
  67470. else
  67471. {
  67472. charType = 1;
  67473. }
  67474. if (charType == 0 || charType != lastCharType)
  67475. {
  67476. if (currentString.isNotEmpty())
  67477. {
  67478. tokens.add (new TextLayoutToken (currentString, font,
  67479. lastCharType == 2 || lastCharType == 0));
  67480. }
  67481. currentString = String::charToString (c);
  67482. if (c == T('\r') && *t == T('\n'))
  67483. currentString += *t++;
  67484. }
  67485. else
  67486. {
  67487. currentString += c;
  67488. }
  67489. lastCharType = charType;
  67490. }
  67491. if (currentString.isNotEmpty())
  67492. tokens.add (new TextLayoutToken (currentString,
  67493. font,
  67494. lastCharType == 2));
  67495. }
  67496. void TextLayout::setText (const String& text, const Font& font) throw()
  67497. {
  67498. clear();
  67499. appendText (text, font);
  67500. }
  67501. void TextLayout::layout (int maxWidth,
  67502. const Justification& justification,
  67503. const bool attemptToBalanceLineLengths) throw()
  67504. {
  67505. if (attemptToBalanceLineLengths)
  67506. {
  67507. const int originalW = maxWidth;
  67508. int bestWidth = maxWidth;
  67509. float bestLineProportion = 0.0f;
  67510. while (maxWidth > originalW / 2)
  67511. {
  67512. layout (maxWidth, justification, false);
  67513. if (getNumLines() <= 1)
  67514. return;
  67515. const int lastLineW = getLineWidth (getNumLines() - 1);
  67516. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  67517. const float prop = lastLineW / (float) lastButOneLineW;
  67518. if (prop > 0.9f)
  67519. return;
  67520. if (prop > bestLineProportion)
  67521. {
  67522. bestLineProportion = prop;
  67523. bestWidth = maxWidth;
  67524. }
  67525. maxWidth -= 10;
  67526. }
  67527. layout (bestWidth, justification, false);
  67528. }
  67529. else
  67530. {
  67531. int x = 0;
  67532. int y = 0;
  67533. int h = 0;
  67534. totalLines = 0;
  67535. int i;
  67536. for (i = 0; i < tokens.size(); ++i)
  67537. {
  67538. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  67539. t->x = x;
  67540. t->y = y;
  67541. t->line = totalLines;
  67542. x += t->w;
  67543. h = jmax (h, t->h);
  67544. const TextLayoutToken* nextTok = (TextLayoutToken*) tokens [i + 1];
  67545. if (nextTok == 0)
  67546. break;
  67547. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  67548. {
  67549. // finished a line, so go back and update the heights of the things on it
  67550. for (int j = i; j >= 0; --j)
  67551. {
  67552. TextLayoutToken* const tok = (TextLayoutToken*)tokens.getUnchecked(j);
  67553. if (tok->line == totalLines)
  67554. tok->lineHeight = h;
  67555. else
  67556. break;
  67557. }
  67558. x = 0;
  67559. y += h;
  67560. h = 0;
  67561. ++totalLines;
  67562. }
  67563. }
  67564. // finished a line, so go back and update the heights of the things on it
  67565. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  67566. {
  67567. TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(j);
  67568. if (t->line == totalLines)
  67569. t->lineHeight = h;
  67570. else
  67571. break;
  67572. }
  67573. ++totalLines;
  67574. if (! justification.testFlags (Justification::left))
  67575. {
  67576. int totalW = getWidth();
  67577. for (i = totalLines; --i >= 0;)
  67578. {
  67579. const int lineW = getLineWidth (i);
  67580. int dx = 0;
  67581. if (justification.testFlags (Justification::horizontallyCentred))
  67582. dx = (totalW - lineW) / 2;
  67583. else if (justification.testFlags (Justification::right))
  67584. dx = totalW - lineW;
  67585. for (int j = tokens.size(); --j >= 0;)
  67586. {
  67587. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(j);
  67588. if (t->line == i)
  67589. t->x += dx;
  67590. }
  67591. }
  67592. }
  67593. }
  67594. }
  67595. int TextLayout::getLineWidth (const int lineNumber) const throw()
  67596. {
  67597. int maxW = 0;
  67598. for (int i = tokens.size(); --i >= 0;)
  67599. {
  67600. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  67601. if (t->line == lineNumber && ! t->isWhitespace)
  67602. maxW = jmax (maxW, t->x + t->w);
  67603. }
  67604. return maxW;
  67605. }
  67606. int TextLayout::getWidth() const throw()
  67607. {
  67608. int maxW = 0;
  67609. for (int i = tokens.size(); --i >= 0;)
  67610. {
  67611. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  67612. if (! t->isWhitespace)
  67613. maxW = jmax (maxW, t->x + t->w);
  67614. }
  67615. return maxW;
  67616. }
  67617. int TextLayout::getHeight() const throw()
  67618. {
  67619. int maxH = 0;
  67620. for (int i = tokens.size(); --i >= 0;)
  67621. {
  67622. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  67623. if (! t->isWhitespace)
  67624. maxH = jmax (maxH, t->y + t->h);
  67625. }
  67626. return maxH;
  67627. }
  67628. void TextLayout::draw (Graphics& g,
  67629. const int xOffset,
  67630. const int yOffset) const throw()
  67631. {
  67632. for (int i = tokens.size(); --i >= 0;)
  67633. ((TextLayoutToken*) tokens.getUnchecked(i))->draw (g, xOffset, yOffset);
  67634. }
  67635. void TextLayout::drawWithin (Graphics& g,
  67636. int x, int y, int w, int h,
  67637. const Justification& justification) const throw()
  67638. {
  67639. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  67640. x, y, w, h);
  67641. draw (g, x, y);
  67642. }
  67643. END_JUCE_NAMESPACE
  67644. /********* End of inlined file: juce_TextLayout.cpp *********/
  67645. /********* Start of inlined file: juce_Typeface.cpp *********/
  67646. BEGIN_JUCE_NAMESPACE
  67647. TypefaceGlyphInfo::TypefaceGlyphInfo (const juce_wchar character_,
  67648. const Path& shape,
  67649. const float horizontalSeparation,
  67650. Typeface* const typeface_) throw()
  67651. : character (character_),
  67652. path (shape),
  67653. width (horizontalSeparation),
  67654. typeface (typeface_)
  67655. {
  67656. }
  67657. TypefaceGlyphInfo::~TypefaceGlyphInfo() throw()
  67658. {
  67659. }
  67660. float TypefaceGlyphInfo::getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  67661. {
  67662. if (subsequentCharacter != 0)
  67663. {
  67664. const KerningPair* const pairs = (const KerningPair*) kerningPairs.getData();
  67665. const int numPairs = getNumKerningPairs();
  67666. for (int i = 0; i < numPairs; ++i)
  67667. if (pairs [i].character2 == subsequentCharacter)
  67668. return width + pairs [i].kerningAmount;
  67669. }
  67670. return width;
  67671. }
  67672. void TypefaceGlyphInfo::addKerningPair (const juce_wchar subsequentCharacter,
  67673. const float extraKerningAmount) throw()
  67674. {
  67675. const int numPairs = getNumKerningPairs();
  67676. kerningPairs.setSize ((numPairs + 1) * sizeof (KerningPair));
  67677. KerningPair& p = getKerningPair (numPairs);
  67678. p.character2 = subsequentCharacter;
  67679. p.kerningAmount = extraKerningAmount;
  67680. }
  67681. TypefaceGlyphInfo::KerningPair& TypefaceGlyphInfo::getKerningPair (const int index) const throw()
  67682. {
  67683. return ((KerningPair*) kerningPairs.getData()) [index];
  67684. }
  67685. int TypefaceGlyphInfo::getNumKerningPairs() const throw()
  67686. {
  67687. return kerningPairs.getSize() / sizeof (KerningPair);
  67688. }
  67689. const tchar* Typeface::defaultTypefaceNameSans = T("<Sans-Serif>");
  67690. const tchar* Typeface::defaultTypefaceNameSerif = T("<Serif>");
  67691. const tchar* Typeface::defaultTypefaceNameMono = T("<Monospaced>");
  67692. Typeface::Typeface() throw()
  67693. : hash (0),
  67694. isFullyPopulated (false)
  67695. {
  67696. zeromem (lookupTable, sizeof (lookupTable));
  67697. }
  67698. Typeface::Typeface (const Typeface& other)
  67699. : typefaceName (other.typefaceName),
  67700. ascent (other.ascent),
  67701. bold (other.bold),
  67702. italic (other.italic),
  67703. isFullyPopulated (other.isFullyPopulated),
  67704. defaultCharacter (other.defaultCharacter)
  67705. {
  67706. zeromem (lookupTable, sizeof (lookupTable));
  67707. for (int i = 0; i < other.glyphs.size(); ++i)
  67708. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  67709. updateHashCode();
  67710. }
  67711. Typeface::Typeface (const String& faceName,
  67712. const bool bold,
  67713. const bool italic)
  67714. : isFullyPopulated (false)
  67715. {
  67716. zeromem (lookupTable, sizeof (lookupTable));
  67717. initialiseTypefaceCharacteristics (faceName, bold, italic, false);
  67718. updateHashCode();
  67719. }
  67720. Typeface::~Typeface()
  67721. {
  67722. clear();
  67723. }
  67724. const Typeface& Typeface::operator= (const Typeface& other) throw()
  67725. {
  67726. if (this != &other)
  67727. {
  67728. clear();
  67729. typefaceName = other.typefaceName;
  67730. ascent = other.ascent;
  67731. bold = other.bold;
  67732. italic = other.italic;
  67733. isFullyPopulated = other.isFullyPopulated;
  67734. defaultCharacter = other.defaultCharacter;
  67735. for (int i = 0; i < other.glyphs.size(); ++i)
  67736. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  67737. updateHashCode();
  67738. }
  67739. return *this;
  67740. }
  67741. void Typeface::updateHashCode() throw()
  67742. {
  67743. hash = typefaceName.hashCode();
  67744. if (bold)
  67745. hash ^= 0xffff;
  67746. if (italic)
  67747. hash ^= 0xffff0000;
  67748. }
  67749. void Typeface::clear() throw()
  67750. {
  67751. zeromem (lookupTable, sizeof (lookupTable));
  67752. typefaceName = String::empty;
  67753. bold = false;
  67754. italic = false;
  67755. for (int i = glyphs.size(); --i >= 0;)
  67756. {
  67757. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) (glyphs.getUnchecked(i));
  67758. delete g;
  67759. }
  67760. glyphs.clear();
  67761. updateHashCode();
  67762. }
  67763. Typeface::Typeface (InputStream& serialisedTypefaceStream)
  67764. {
  67765. zeromem (lookupTable, sizeof (lookupTable));
  67766. isFullyPopulated = true;
  67767. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  67768. BufferedInputStream in (&gzin, 32768, false);
  67769. typefaceName = in.readString();
  67770. bold = in.readBool();
  67771. italic = in.readBool();
  67772. ascent = in.readFloat();
  67773. defaultCharacter = (juce_wchar) in.readShort();
  67774. int i, numChars = in.readInt();
  67775. for (i = 0; i < numChars; ++i)
  67776. {
  67777. const juce_wchar c = (juce_wchar) in.readShort();
  67778. const float width = in.readFloat();
  67779. Path p;
  67780. p.loadPathFromStream (in);
  67781. addGlyph (c, p, width);
  67782. }
  67783. const int numKerningPairs = in.readInt();
  67784. for (i = 0; i < numKerningPairs; ++i)
  67785. {
  67786. const juce_wchar char1 = (juce_wchar) in.readShort();
  67787. const juce_wchar char2 = (juce_wchar) in.readShort();
  67788. addKerningPair (char1, char2, in.readFloat());
  67789. }
  67790. updateHashCode();
  67791. }
  67792. void Typeface::serialise (OutputStream& outputStream)
  67793. {
  67794. GZIPCompressorOutputStream out (&outputStream);
  67795. out.writeString (typefaceName);
  67796. out.writeBool (bold);
  67797. out.writeBool (italic);
  67798. out.writeFloat (ascent);
  67799. out.writeShort ((short) (unsigned short) defaultCharacter);
  67800. out.writeInt (glyphs.size());
  67801. int i, numKerningPairs = 0;
  67802. for (i = 0; i < glyphs.size(); ++i)
  67803. {
  67804. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  67805. out.writeShort ((short) (unsigned short) g.character);
  67806. out.writeFloat (g.width);
  67807. g.path.writePathToStream (out);
  67808. numKerningPairs += g.getNumKerningPairs();
  67809. }
  67810. out.writeInt (numKerningPairs);
  67811. for (i = 0; i < glyphs.size(); ++i)
  67812. {
  67813. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  67814. for (int j = 0; j < g.getNumKerningPairs(); ++j)
  67815. {
  67816. const TypefaceGlyphInfo::KerningPair& p = g.getKerningPair (j);
  67817. out.writeShort ((short) (unsigned short) g.character);
  67818. out.writeShort ((short) (unsigned short) p.character2);
  67819. out.writeFloat (p.kerningAmount);
  67820. }
  67821. }
  67822. }
  67823. const Path* Typeface::getOutlineForGlyph (const juce_wchar character) throw()
  67824. {
  67825. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) getGlyph (character);
  67826. if (g != 0)
  67827. return &(g->path);
  67828. else
  67829. return 0;
  67830. }
  67831. const TypefaceGlyphInfo* Typeface::getGlyph (const juce_wchar character) throw()
  67832. {
  67833. if (((unsigned int) character) < 128 && lookupTable [character] > 0)
  67834. return (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  67835. for (int i = 0; i < glyphs.size(); ++i)
  67836. {
  67837. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  67838. if (g->character == character)
  67839. return g;
  67840. }
  67841. if ((! isFullyPopulated)
  67842. && findAndAddSystemGlyph (character))
  67843. {
  67844. for (int i = 0; i < glyphs.size(); ++i)
  67845. {
  67846. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  67847. if (g->character == character)
  67848. return g;
  67849. }
  67850. }
  67851. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  67852. {
  67853. const TypefaceGlyphInfo* spaceGlyph = getGlyph (L' ');
  67854. if (spaceGlyph != 0)
  67855. {
  67856. // Add a copy of the empty glyph, mapped onto this character
  67857. addGlyph (character, spaceGlyph->getPath(), spaceGlyph->getHorizontalSpacing (0));
  67858. spaceGlyph = (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  67859. }
  67860. return spaceGlyph;
  67861. }
  67862. else if (character != defaultCharacter)
  67863. {
  67864. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  67865. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  67866. if (fallbackTypeface != 0 && fallbackTypeface != this)
  67867. return fallbackTypeface->getGlyph (character);
  67868. return getGlyph (defaultCharacter);
  67869. }
  67870. return 0;
  67871. }
  67872. void Typeface::addGlyph (const juce_wchar character,
  67873. const Path& path,
  67874. const float horizontalSpacing) throw()
  67875. {
  67876. #ifdef JUCE_DEBUG
  67877. for (int i = 0; i < glyphs.size(); ++i)
  67878. {
  67879. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  67880. if (g->character == character)
  67881. jassertfalse;
  67882. }
  67883. #endif
  67884. if (((unsigned int) character) < 128)
  67885. lookupTable [character] = (short) glyphs.size();
  67886. glyphs.add (new TypefaceGlyphInfo (character,
  67887. path,
  67888. horizontalSpacing,
  67889. this));
  67890. }
  67891. void Typeface::addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw()
  67892. {
  67893. if (glyphInfoToCopy != 0)
  67894. {
  67895. if (glyphInfoToCopy->character > 0 && glyphInfoToCopy->character < 128)
  67896. lookupTable [glyphInfoToCopy->character] = (short) glyphs.size();
  67897. TypefaceGlyphInfo* const newOne
  67898. = new TypefaceGlyphInfo (glyphInfoToCopy->character,
  67899. glyphInfoToCopy->path,
  67900. glyphInfoToCopy->width,
  67901. this);
  67902. newOne->kerningPairs = glyphInfoToCopy->kerningPairs;
  67903. glyphs.add (newOne);
  67904. }
  67905. }
  67906. void Typeface::addKerningPair (const juce_wchar char1,
  67907. const juce_wchar char2,
  67908. const float extraAmount) throw()
  67909. {
  67910. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) getGlyph (char1);
  67911. if (g != 0)
  67912. g->addKerningPair (char2, extraAmount);
  67913. }
  67914. void Typeface::setName (const String& name) throw()
  67915. {
  67916. typefaceName = name;
  67917. updateHashCode();
  67918. }
  67919. void Typeface::setAscent (const float newAscent) throw()
  67920. {
  67921. ascent = newAscent;
  67922. }
  67923. void Typeface::setDefaultCharacter (const juce_wchar newDefaultCharacter) throw()
  67924. {
  67925. defaultCharacter = newDefaultCharacter;
  67926. }
  67927. void Typeface::setBold (const bool shouldBeBold) throw()
  67928. {
  67929. bold = shouldBeBold;
  67930. updateHashCode();
  67931. }
  67932. void Typeface::setItalic (const bool shouldBeItalic) throw()
  67933. {
  67934. italic = shouldBeItalic;
  67935. updateHashCode();
  67936. }
  67937. class TypefaceCache;
  67938. static TypefaceCache* typefaceCacheInstance = 0;
  67939. void clearUpDefaultFontNames() throw(); // in juce_LookAndFeel.cpp
  67940. class TypefaceCache : private DeletedAtShutdown
  67941. {
  67942. private:
  67943. struct CachedFace
  67944. {
  67945. CachedFace() throw()
  67946. : lastUsageCount (0),
  67947. flags (0)
  67948. {
  67949. }
  67950. String typefaceName;
  67951. int lastUsageCount;
  67952. int flags;
  67953. Typeface::Ptr typeFace;
  67954. };
  67955. int counter;
  67956. OwnedArray <CachedFace> faces;
  67957. TypefaceCache (const TypefaceCache&);
  67958. const TypefaceCache& operator= (const TypefaceCache&);
  67959. public:
  67960. TypefaceCache (int numToCache = 10)
  67961. : counter (1),
  67962. faces (2)
  67963. {
  67964. while (--numToCache >= 0)
  67965. {
  67966. CachedFace* const face = new CachedFace();
  67967. face->typeFace = new Typeface();
  67968. faces.add (face);
  67969. }
  67970. }
  67971. ~TypefaceCache()
  67972. {
  67973. faces.clear();
  67974. jassert (typefaceCacheInstance == this);
  67975. typefaceCacheInstance = 0;
  67976. clearUpDefaultFontNames();
  67977. }
  67978. static TypefaceCache* getInstance() throw()
  67979. {
  67980. if (typefaceCacheInstance == 0)
  67981. typefaceCacheInstance = new TypefaceCache();
  67982. return typefaceCacheInstance;
  67983. }
  67984. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  67985. {
  67986. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  67987. int i;
  67988. for (i = faces.size(); --i >= 0;)
  67989. {
  67990. CachedFace* const face = faces.getUnchecked(i);
  67991. if (face->flags == flags
  67992. && face->typefaceName == font.getTypefaceName())
  67993. {
  67994. face->lastUsageCount = ++counter;
  67995. return face->typeFace;
  67996. }
  67997. }
  67998. int replaceIndex = 0;
  67999. int bestLastUsageCount = INT_MAX;
  68000. for (i = faces.size(); --i >= 0;)
  68001. {
  68002. const int lu = faces.getUnchecked(i)->lastUsageCount;
  68003. if (bestLastUsageCount > lu)
  68004. {
  68005. bestLastUsageCount = lu;
  68006. replaceIndex = i;
  68007. }
  68008. }
  68009. CachedFace* const face = faces.getUnchecked (replaceIndex);
  68010. face->typefaceName = font.getTypefaceName();
  68011. face->flags = flags;
  68012. face->lastUsageCount = ++counter;
  68013. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  68014. return face->typeFace;
  68015. }
  68016. };
  68017. const Typeface::Ptr Typeface::getTypefaceFor (const Font& font) throw()
  68018. {
  68019. return TypefaceCache::getInstance()->findTypefaceFor (font);
  68020. }
  68021. END_JUCE_NAMESPACE
  68022. /********* End of inlined file: juce_Typeface.cpp *********/
  68023. /********* Start of inlined file: juce_AffineTransform.cpp *********/
  68024. BEGIN_JUCE_NAMESPACE
  68025. AffineTransform::AffineTransform() throw()
  68026. : mat00 (1.0f),
  68027. mat01 (0),
  68028. mat02 (0),
  68029. mat10 (0),
  68030. mat11 (1.0f),
  68031. mat12 (0)
  68032. {
  68033. }
  68034. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  68035. : mat00 (other.mat00),
  68036. mat01 (other.mat01),
  68037. mat02 (other.mat02),
  68038. mat10 (other.mat10),
  68039. mat11 (other.mat11),
  68040. mat12 (other.mat12)
  68041. {
  68042. }
  68043. AffineTransform::AffineTransform (const float mat00_,
  68044. const float mat01_,
  68045. const float mat02_,
  68046. const float mat10_,
  68047. const float mat11_,
  68048. const float mat12_) throw()
  68049. : mat00 (mat00_),
  68050. mat01 (mat01_),
  68051. mat02 (mat02_),
  68052. mat10 (mat10_),
  68053. mat11 (mat11_),
  68054. mat12 (mat12_)
  68055. {
  68056. }
  68057. const AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  68058. {
  68059. mat00 = other.mat00;
  68060. mat01 = other.mat01;
  68061. mat02 = other.mat02;
  68062. mat10 = other.mat10;
  68063. mat11 = other.mat11;
  68064. mat12 = other.mat12;
  68065. return *this;
  68066. }
  68067. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  68068. {
  68069. return mat00 == other.mat00
  68070. && mat01 == other.mat01
  68071. && mat02 == other.mat02
  68072. && mat10 == other.mat10
  68073. && mat11 == other.mat11
  68074. && mat12 == other.mat12;
  68075. }
  68076. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  68077. {
  68078. return ! operator== (other);
  68079. }
  68080. bool AffineTransform::isIdentity() const throw()
  68081. {
  68082. return (mat01 == 0)
  68083. && (mat02 == 0)
  68084. && (mat10 == 0)
  68085. && (mat12 == 0)
  68086. && (mat00 == 1.0f)
  68087. && (mat11 == 1.0f);
  68088. }
  68089. const AffineTransform AffineTransform::identity;
  68090. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  68091. {
  68092. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  68093. other.mat00 * mat01 + other.mat01 * mat11,
  68094. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  68095. other.mat10 * mat00 + other.mat11 * mat10,
  68096. other.mat10 * mat01 + other.mat11 * mat11,
  68097. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  68098. }
  68099. const AffineTransform AffineTransform::followedBy (const float omat00,
  68100. const float omat01,
  68101. const float omat02,
  68102. const float omat10,
  68103. const float omat11,
  68104. const float omat12) const throw()
  68105. {
  68106. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  68107. omat00 * mat01 + omat01 * mat11,
  68108. omat00 * mat02 + omat01 * mat12 + omat02,
  68109. omat10 * mat00 + omat11 * mat10,
  68110. omat10 * mat01 + omat11 * mat11,
  68111. omat10 * mat02 + omat11 * mat12 + omat12);
  68112. }
  68113. const AffineTransform AffineTransform::translated (const float dx,
  68114. const float dy) const throw()
  68115. {
  68116. return followedBy (1.0f, 0, dx,
  68117. 0, 1.0f, dy);
  68118. }
  68119. const AffineTransform AffineTransform::translation (const float dx,
  68120. const float dy) throw()
  68121. {
  68122. return AffineTransform (1.0f, 0, dx,
  68123. 0, 1.0f, dy);
  68124. }
  68125. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  68126. {
  68127. const float cosRad = cosf (rad);
  68128. const float sinRad = sinf (rad);
  68129. return followedBy (cosRad, -sinRad, 0,
  68130. sinRad, cosRad, 0);
  68131. }
  68132. const AffineTransform AffineTransform::rotation (const float rad) throw()
  68133. {
  68134. const float cosRad = cosf (rad);
  68135. const float sinRad = sinf (rad);
  68136. return AffineTransform (cosRad, -sinRad, 0,
  68137. sinRad, cosRad, 0);
  68138. }
  68139. const AffineTransform AffineTransform::rotated (const float angle,
  68140. const float pivotX,
  68141. const float pivotY) const throw()
  68142. {
  68143. return translated (-pivotX, -pivotY)
  68144. .rotated (angle)
  68145. .translated (pivotX, pivotY);
  68146. }
  68147. const AffineTransform AffineTransform::rotation (const float angle,
  68148. const float pivotX,
  68149. const float pivotY) throw()
  68150. {
  68151. return translation (-pivotX, -pivotY)
  68152. .rotated (angle)
  68153. .translated (pivotX, pivotY);
  68154. }
  68155. const AffineTransform AffineTransform::scaled (const float factorX,
  68156. const float factorY) const throw()
  68157. {
  68158. return followedBy (factorX, 0, 0,
  68159. 0, factorY, 0);
  68160. }
  68161. const AffineTransform AffineTransform::scale (const float factorX,
  68162. const float factorY) throw()
  68163. {
  68164. return AffineTransform (factorX, 0, 0,
  68165. 0, factorY, 0);
  68166. }
  68167. const AffineTransform AffineTransform::sheared (const float shearX,
  68168. const float shearY) const throw()
  68169. {
  68170. return followedBy (1.0f, shearX, 0,
  68171. shearY, 1.0f, 0);
  68172. }
  68173. const AffineTransform AffineTransform::inverted() const throw()
  68174. {
  68175. double determinant = (mat00 * mat11 - mat10 * mat01);
  68176. if (determinant != 0.0)
  68177. {
  68178. determinant = 1.0 / determinant;
  68179. const float dst00 = (float) (mat11 * determinant);
  68180. const float dst10 = (float) (-mat10 * determinant);
  68181. const float dst01 = (float) (-mat01 * determinant);
  68182. const float dst11 = (float) (mat00 * determinant);
  68183. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  68184. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  68185. }
  68186. else
  68187. {
  68188. // singularity..
  68189. return *this;
  68190. }
  68191. }
  68192. bool AffineTransform::isSingularity() const throw()
  68193. {
  68194. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  68195. }
  68196. void AffineTransform::transformPoint (float& x,
  68197. float& y) const throw()
  68198. {
  68199. const float oldX = x;
  68200. x = mat00 * oldX + mat01 * y + mat02;
  68201. y = mat10 * oldX + mat11 * y + mat12;
  68202. }
  68203. void AffineTransform::transformPoint (double& x,
  68204. double& y) const throw()
  68205. {
  68206. const double oldX = x;
  68207. x = mat00 * oldX + mat01 * y + mat02;
  68208. y = mat10 * oldX + mat11 * y + mat12;
  68209. }
  68210. END_JUCE_NAMESPACE
  68211. /********* End of inlined file: juce_AffineTransform.cpp *********/
  68212. /********* Start of inlined file: juce_BorderSize.cpp *********/
  68213. BEGIN_JUCE_NAMESPACE
  68214. BorderSize::BorderSize() throw()
  68215. : top (0),
  68216. left (0),
  68217. bottom (0),
  68218. right (0)
  68219. {
  68220. }
  68221. BorderSize::BorderSize (const BorderSize& other) throw()
  68222. : top (other.top),
  68223. left (other.left),
  68224. bottom (other.bottom),
  68225. right (other.right)
  68226. {
  68227. }
  68228. BorderSize::BorderSize (const int topGap,
  68229. const int leftGap,
  68230. const int bottomGap,
  68231. const int rightGap) throw()
  68232. : top (topGap),
  68233. left (leftGap),
  68234. bottom (bottomGap),
  68235. right (rightGap)
  68236. {
  68237. }
  68238. BorderSize::BorderSize (const int allGaps) throw()
  68239. : top (allGaps),
  68240. left (allGaps),
  68241. bottom (allGaps),
  68242. right (allGaps)
  68243. {
  68244. }
  68245. BorderSize::~BorderSize() throw()
  68246. {
  68247. }
  68248. void BorderSize::setTop (const int newTopGap) throw()
  68249. {
  68250. top = newTopGap;
  68251. }
  68252. void BorderSize::setLeft (const int newLeftGap) throw()
  68253. {
  68254. left = newLeftGap;
  68255. }
  68256. void BorderSize::setBottom (const int newBottomGap) throw()
  68257. {
  68258. bottom = newBottomGap;
  68259. }
  68260. void BorderSize::setRight (const int newRightGap) throw()
  68261. {
  68262. right = newRightGap;
  68263. }
  68264. const Rectangle BorderSize::subtractedFrom (const Rectangle& r) const throw()
  68265. {
  68266. return Rectangle (r.getX() + left,
  68267. r.getY() + top,
  68268. r.getWidth() - (left + right),
  68269. r.getHeight() - (top + bottom));
  68270. }
  68271. void BorderSize::subtractFrom (Rectangle& r) const throw()
  68272. {
  68273. r.setBounds (r.getX() + left,
  68274. r.getY() + top,
  68275. r.getWidth() - (left + right),
  68276. r.getHeight() - (top + bottom));
  68277. }
  68278. const Rectangle BorderSize::addedTo (const Rectangle& r) const throw()
  68279. {
  68280. return Rectangle (r.getX() - left,
  68281. r.getY() - top,
  68282. r.getWidth() + (left + right),
  68283. r.getHeight() + (top + bottom));
  68284. }
  68285. void BorderSize::addTo (Rectangle& r) const throw()
  68286. {
  68287. r.setBounds (r.getX() - left,
  68288. r.getY() - top,
  68289. r.getWidth() + (left + right),
  68290. r.getHeight() + (top + bottom));
  68291. }
  68292. bool BorderSize::operator== (const BorderSize& other) const throw()
  68293. {
  68294. return top == other.top
  68295. && left == other.left
  68296. && bottom == other.bottom
  68297. && right == other.right;
  68298. }
  68299. bool BorderSize::operator!= (const BorderSize& other) const throw()
  68300. {
  68301. return ! operator== (other);
  68302. }
  68303. END_JUCE_NAMESPACE
  68304. /********* End of inlined file: juce_BorderSize.cpp *********/
  68305. /********* Start of inlined file: juce_Line.cpp *********/
  68306. BEGIN_JUCE_NAMESPACE
  68307. static bool juce_lineIntersection (const float x1, const float y1,
  68308. const float x2, const float y2,
  68309. const float x3, const float y3,
  68310. const float x4, const float y4,
  68311. float& intersectionX,
  68312. float& intersectionY) throw()
  68313. {
  68314. if (x2 != x3 || y2 != y3)
  68315. {
  68316. const float dx1 = x2 - x1;
  68317. const float dy1 = y2 - y1;
  68318. const float dx2 = x4 - x3;
  68319. const float dy2 = y4 - y3;
  68320. const float divisor = dx1 * dy2 - dx2 * dy1;
  68321. if (divisor == 0)
  68322. {
  68323. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  68324. {
  68325. if (dy1 == 0 && dy2 != 0)
  68326. {
  68327. const float along = (y1 - y3) / dy2;
  68328. intersectionX = x3 + along * dx2;
  68329. intersectionY = y1;
  68330. return along >= 0 && along <= 1.0f;
  68331. }
  68332. else if (dy2 == 0 && dy1 != 0)
  68333. {
  68334. const float along = (y3 - y1) / dy1;
  68335. intersectionX = x1 + along * dx1;
  68336. intersectionY = y3;
  68337. return along >= 0 && along <= 1.0f;
  68338. }
  68339. else if (dx1 == 0 && dx2 != 0)
  68340. {
  68341. const float along = (x1 - x3) / dx2;
  68342. intersectionX = x1;
  68343. intersectionY = y3 + along * dy2;
  68344. return along >= 0 && along <= 1.0f;
  68345. }
  68346. else if (dx2 == 0 && dx1 != 0)
  68347. {
  68348. const float along = (x3 - x1) / dx1;
  68349. intersectionX = x3;
  68350. intersectionY = y1 + along * dy1;
  68351. return along >= 0 && along <= 1.0f;
  68352. }
  68353. }
  68354. intersectionX = 0.5f * (x2 + x3);
  68355. intersectionY = 0.5f * (y2 + y3);
  68356. return false;
  68357. }
  68358. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  68359. intersectionX = x1 + along1 * dx1;
  68360. intersectionY = y1 + along1 * dy1;
  68361. if (along1 < 0 || along1 > 1.0f)
  68362. return false;
  68363. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1) / divisor;
  68364. return along2 >= 0 && along2 <= 1.0f;
  68365. }
  68366. intersectionX = x2;
  68367. intersectionY = y2;
  68368. return true;
  68369. }
  68370. Line::Line() throw()
  68371. : startX (0.0f),
  68372. startY (0.0f),
  68373. endX (0.0f),
  68374. endY (0.0f)
  68375. {
  68376. }
  68377. Line::Line (const Line& other) throw()
  68378. : startX (other.startX),
  68379. startY (other.startY),
  68380. endX (other.endX),
  68381. endY (other.endY)
  68382. {
  68383. }
  68384. Line::Line (const float startX_, const float startY_,
  68385. const float endX_, const float endY_) throw()
  68386. : startX (startX_),
  68387. startY (startY_),
  68388. endX (endX_),
  68389. endY (endY_)
  68390. {
  68391. }
  68392. Line::Line (const Point& start,
  68393. const Point& end) throw()
  68394. : startX (start.getX()),
  68395. startY (start.getY()),
  68396. endX (end.getX()),
  68397. endY (end.getY())
  68398. {
  68399. }
  68400. const Line& Line::operator= (const Line& other) throw()
  68401. {
  68402. startX = other.startX;
  68403. startY = other.startY;
  68404. endX = other.endX;
  68405. endY = other.endY;
  68406. return *this;
  68407. }
  68408. Line::~Line() throw()
  68409. {
  68410. }
  68411. const Point Line::getStart() const throw()
  68412. {
  68413. return Point (startX, startY);
  68414. }
  68415. const Point Line::getEnd() const throw()
  68416. {
  68417. return Point (endX, endY);
  68418. }
  68419. void Line::setStart (const float newStartX,
  68420. const float newStartY) throw()
  68421. {
  68422. startX = newStartX;
  68423. startY = newStartY;
  68424. }
  68425. void Line::setStart (const Point& newStart) throw()
  68426. {
  68427. startX = newStart.getX();
  68428. startY = newStart.getY();
  68429. }
  68430. void Line::setEnd (const float newEndX,
  68431. const float newEndY) throw()
  68432. {
  68433. endX = newEndX;
  68434. endY = newEndY;
  68435. }
  68436. void Line::setEnd (const Point& newEnd) throw()
  68437. {
  68438. endX = newEnd.getX();
  68439. endY = newEnd.getY();
  68440. }
  68441. bool Line::operator== (const Line& other) const throw()
  68442. {
  68443. return startX == other.startX
  68444. && startY == other.startY
  68445. && endX == other.endX
  68446. && endY == other.endY;
  68447. }
  68448. bool Line::operator!= (const Line& other) const throw()
  68449. {
  68450. return startX != other.startX
  68451. || startY != other.startY
  68452. || endX != other.endX
  68453. || endY != other.endY;
  68454. }
  68455. void Line::applyTransform (const AffineTransform& transform) throw()
  68456. {
  68457. transform.transformPoint (startX, startY);
  68458. transform.transformPoint (endX, endY);
  68459. }
  68460. float Line::getLength() const throw()
  68461. {
  68462. return (float) juce_hypot (startX - endX,
  68463. startY - endY);
  68464. }
  68465. float Line::getAngle() const throw()
  68466. {
  68467. return atan2f (endX - startX,
  68468. endY - startY);
  68469. }
  68470. const Point Line::getPointAlongLine (const float distanceFromStart) const throw()
  68471. {
  68472. const float alpha = distanceFromStart / getLength();
  68473. return Point (startX + (endX - startX) * alpha,
  68474. startY + (endY - startY) * alpha);
  68475. }
  68476. const Point Line::getPointAlongLine (const float offsetX,
  68477. const float offsetY) const throw()
  68478. {
  68479. const float dx = endX - startX;
  68480. const float dy = endY - startY;
  68481. const double length = juce_hypot (dx, dy);
  68482. if (length == 0)
  68483. return Point (startX, startY);
  68484. else
  68485. return Point (startX + (float) (((dx * offsetX) - (dy * offsetY)) / length),
  68486. startY + (float) (((dy * offsetX) + (dx * offsetY)) / length));
  68487. }
  68488. const Point Line::getPointAlongLineProportionally (const float alpha) const throw()
  68489. {
  68490. return Point (startX + (endX - startX) * alpha,
  68491. startY + (endY - startY) * alpha);
  68492. }
  68493. float Line::getDistanceFromLine (const float x,
  68494. const float y) const throw()
  68495. {
  68496. const double dx = endX - startX;
  68497. const double dy = endY - startY;
  68498. const double length = dx * dx + dy * dy;
  68499. if (length > 0)
  68500. {
  68501. const double prop = ((x - startX) * dx + (y - startY) * dy) / length;
  68502. if (prop >= 0.0f && prop < 1.0f)
  68503. {
  68504. return (float) juce_hypot (x - (startX + prop * dx),
  68505. y - (startY + prop * dy));
  68506. }
  68507. }
  68508. return (float) jmin (juce_hypot (x - startX, y - startY),
  68509. juce_hypot (x - endX, y - endY));
  68510. }
  68511. float Line::findNearestPointTo (const float x,
  68512. const float y) const throw()
  68513. {
  68514. const double dx = endX - startX;
  68515. const double dy = endY - startY;
  68516. const double length = dx * dx + dy * dy;
  68517. if (length <= 0.0)
  68518. return 0.0f;
  68519. return jlimit (0.0f, 1.0f,
  68520. (float) (((x - startX) * dx + (y - startY) * dy) / length));
  68521. }
  68522. const Line Line::withShortenedStart (const float distanceToShortenBy) const throw()
  68523. {
  68524. const float length = getLength();
  68525. return Line (getPointAlongLine (jmin (distanceToShortenBy, length)),
  68526. getEnd());
  68527. }
  68528. const Line Line::withShortenedEnd (const float distanceToShortenBy) const throw()
  68529. {
  68530. const float length = getLength();
  68531. return Line (getStart(),
  68532. getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  68533. }
  68534. bool Line::clipToPath (const Path& path,
  68535. const bool keepSectionOutsidePath) throw()
  68536. {
  68537. const bool startInside = path.contains (startX, startY);
  68538. const bool endInside = path.contains (endX, endY);
  68539. if (startInside == endInside)
  68540. {
  68541. if (keepSectionOutsidePath != startInside)
  68542. {
  68543. // entirely outside the path
  68544. return false;
  68545. }
  68546. else
  68547. {
  68548. // entirely inside the path
  68549. startX = 0.0f;
  68550. startY = 0.0f;
  68551. endX = 0.0f;
  68552. endY = 0.0f;
  68553. return true;
  68554. }
  68555. }
  68556. else
  68557. {
  68558. bool changed = false;
  68559. PathFlatteningIterator iter (path, AffineTransform::identity);
  68560. while (iter.next())
  68561. {
  68562. float ix, iy;
  68563. if (intersects (Line (iter.x1, iter.y1,
  68564. iter.x2, iter.y2),
  68565. ix, iy))
  68566. {
  68567. if ((startInside && keepSectionOutsidePath)
  68568. || (endInside && ! keepSectionOutsidePath))
  68569. {
  68570. setStart (ix, iy);
  68571. }
  68572. else
  68573. {
  68574. setEnd (ix, iy);
  68575. }
  68576. changed = true;
  68577. }
  68578. }
  68579. return changed;
  68580. }
  68581. }
  68582. bool Line::intersects (const Line& line,
  68583. float& intersectionX,
  68584. float& intersectionY) const throw()
  68585. {
  68586. return juce_lineIntersection (startX, startY,
  68587. endX, endY,
  68588. line.startX, line.startY,
  68589. line.endX, line.endY,
  68590. intersectionX,
  68591. intersectionY);
  68592. }
  68593. bool Line::isVertical() const throw()
  68594. {
  68595. return startX == endX;
  68596. }
  68597. bool Line::isHorizontal() const throw()
  68598. {
  68599. return startY == endY;
  68600. }
  68601. bool Line::isPointAbove (const float x, const float y) const throw()
  68602. {
  68603. return startX != endX
  68604. && y < ((endY - startY) * (x - startX)) / (endX - startX) + startY;
  68605. }
  68606. END_JUCE_NAMESPACE
  68607. /********* End of inlined file: juce_Line.cpp *********/
  68608. /********* Start of inlined file: juce_Path.cpp *********/
  68609. BEGIN_JUCE_NAMESPACE
  68610. // tests that some co-ords aren't NaNs
  68611. #define CHECK_COORDS_ARE_VALID(x, y) \
  68612. jassert (x == x && y == y);
  68613. const float Path::lineMarker = 100001.0f;
  68614. const float Path::moveMarker = 100002.0f;
  68615. const float Path::quadMarker = 100003.0f;
  68616. const float Path::cubicMarker = 100004.0f;
  68617. const float Path::closeSubPathMarker = 100005.0f;
  68618. static const int defaultGranularity = 32;
  68619. Path::Path() throw()
  68620. : ArrayAllocationBase <float> (defaultGranularity),
  68621. numElements (0),
  68622. pathXMin (0),
  68623. pathXMax (0),
  68624. pathYMin (0),
  68625. pathYMax (0),
  68626. useNonZeroWinding (true)
  68627. {
  68628. }
  68629. Path::~Path() throw()
  68630. {
  68631. }
  68632. Path::Path (const Path& other) throw()
  68633. : ArrayAllocationBase <float> (defaultGranularity),
  68634. numElements (other.numElements),
  68635. pathXMin (other.pathXMin),
  68636. pathXMax (other.pathXMax),
  68637. pathYMin (other.pathYMin),
  68638. pathYMax (other.pathYMax),
  68639. useNonZeroWinding (other.useNonZeroWinding)
  68640. {
  68641. if (numElements > 0)
  68642. {
  68643. setAllocatedSize (numElements);
  68644. memcpy (elements, other.elements, numElements * sizeof (float));
  68645. }
  68646. }
  68647. const Path& Path::operator= (const Path& other) throw()
  68648. {
  68649. if (this != &other)
  68650. {
  68651. ensureAllocatedSize (other.numElements);
  68652. numElements = other.numElements;
  68653. pathXMin = other.pathXMin;
  68654. pathXMax = other.pathXMax;
  68655. pathYMin = other.pathYMin;
  68656. pathYMax = other.pathYMax;
  68657. useNonZeroWinding = other.useNonZeroWinding;
  68658. if (numElements > 0)
  68659. memcpy (elements, other.elements, numElements * sizeof (float));
  68660. }
  68661. return *this;
  68662. }
  68663. void Path::clear() throw()
  68664. {
  68665. numElements = 0;
  68666. pathXMin = 0;
  68667. pathYMin = 0;
  68668. pathYMax = 0;
  68669. pathXMax = 0;
  68670. }
  68671. void Path::swapWithPath (Path& other)
  68672. {
  68673. swapVariables <int> (this->numAllocated, other.numAllocated);
  68674. swapVariables <float*> (this->elements, other.elements);
  68675. swapVariables <int> (this->numElements, other.numElements);
  68676. swapVariables <float> (this->pathXMin, other.pathXMin);
  68677. swapVariables <float> (this->pathXMax, other.pathXMax);
  68678. swapVariables <float> (this->pathYMin, other.pathYMin);
  68679. swapVariables <float> (this->pathYMax, other.pathYMax);
  68680. swapVariables <bool> (this->useNonZeroWinding, other.useNonZeroWinding);
  68681. }
  68682. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  68683. {
  68684. useNonZeroWinding = isNonZero;
  68685. }
  68686. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  68687. const bool preserveProportions) throw()
  68688. {
  68689. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  68690. }
  68691. bool Path::isEmpty() const throw()
  68692. {
  68693. int i = 0;
  68694. while (i < numElements)
  68695. {
  68696. const float type = elements [i++];
  68697. if (type == moveMarker)
  68698. {
  68699. i += 2;
  68700. }
  68701. else if (type == lineMarker
  68702. || type == quadMarker
  68703. || type == cubicMarker)
  68704. {
  68705. return false;
  68706. }
  68707. }
  68708. return true;
  68709. }
  68710. void Path::getBounds (float& x, float& y,
  68711. float& w, float& h) const throw()
  68712. {
  68713. x = pathXMin;
  68714. y = pathYMin;
  68715. w = pathXMax - pathXMin;
  68716. h = pathYMax - pathYMin;
  68717. }
  68718. void Path::getBoundsTransformed (const AffineTransform& transform,
  68719. float& x, float& y,
  68720. float& w, float& h) const throw()
  68721. {
  68722. float x1 = pathXMin;
  68723. float y1 = pathYMin;
  68724. transform.transformPoint (x1, y1);
  68725. float x2 = pathXMax;
  68726. float y2 = pathYMin;
  68727. transform.transformPoint (x2, y2);
  68728. float x3 = pathXMin;
  68729. float y3 = pathYMax;
  68730. transform.transformPoint (x3, y3);
  68731. float x4 = pathXMax;
  68732. float y4 = pathYMax;
  68733. transform.transformPoint (x4, y4);
  68734. x = jmin (x1, x2, x3, x4);
  68735. y = jmin (y1, y2, y3, y4);
  68736. w = jmax (x1, x2, x3, x4) - x;
  68737. h = jmax (y1, y2, y3, y4) - y;
  68738. }
  68739. void Path::startNewSubPath (const float x,
  68740. const float y) throw()
  68741. {
  68742. CHECK_COORDS_ARE_VALID (x, y);
  68743. if (numElements == 0)
  68744. {
  68745. pathXMin = pathXMax = x;
  68746. pathYMin = pathYMax = y;
  68747. }
  68748. else
  68749. {
  68750. pathXMin = jmin (pathXMin, x);
  68751. pathXMax = jmax (pathXMax, x);
  68752. pathYMin = jmin (pathYMin, y);
  68753. pathYMax = jmax (pathYMax, y);
  68754. }
  68755. ensureAllocatedSize (numElements + 3);
  68756. elements [numElements++] = moveMarker;
  68757. elements [numElements++] = x;
  68758. elements [numElements++] = y;
  68759. }
  68760. void Path::lineTo (const float x, const float y) throw()
  68761. {
  68762. CHECK_COORDS_ARE_VALID (x, y);
  68763. if (numElements == 0)
  68764. startNewSubPath (0, 0);
  68765. ensureAllocatedSize (numElements + 3);
  68766. elements [numElements++] = lineMarker;
  68767. elements [numElements++] = x;
  68768. elements [numElements++] = y;
  68769. pathXMin = jmin (pathXMin, x);
  68770. pathXMax = jmax (pathXMax, x);
  68771. pathYMin = jmin (pathYMin, y);
  68772. pathYMax = jmax (pathYMax, y);
  68773. }
  68774. void Path::quadraticTo (const float x1, const float y1,
  68775. const float x2, const float y2) throw()
  68776. {
  68777. CHECK_COORDS_ARE_VALID (x1, y1);
  68778. CHECK_COORDS_ARE_VALID (x2, y2);
  68779. if (numElements == 0)
  68780. startNewSubPath (0, 0);
  68781. ensureAllocatedSize (numElements + 5);
  68782. elements [numElements++] = quadMarker;
  68783. elements [numElements++] = x1;
  68784. elements [numElements++] = y1;
  68785. elements [numElements++] = x2;
  68786. elements [numElements++] = y2;
  68787. pathXMin = jmin (pathXMin, x1, x2);
  68788. pathXMax = jmax (pathXMax, x1, x2);
  68789. pathYMin = jmin (pathYMin, y1, y2);
  68790. pathYMax = jmax (pathYMax, y1, y2);
  68791. }
  68792. void Path::cubicTo (const float x1, const float y1,
  68793. const float x2, const float y2,
  68794. const float x3, const float y3) throw()
  68795. {
  68796. CHECK_COORDS_ARE_VALID (x1, y1);
  68797. CHECK_COORDS_ARE_VALID (x2, y2);
  68798. CHECK_COORDS_ARE_VALID (x3, y3);
  68799. if (numElements == 0)
  68800. startNewSubPath (0, 0);
  68801. ensureAllocatedSize (numElements + 7);
  68802. elements [numElements++] = cubicMarker;
  68803. elements [numElements++] = x1;
  68804. elements [numElements++] = y1;
  68805. elements [numElements++] = x2;
  68806. elements [numElements++] = y2;
  68807. elements [numElements++] = x3;
  68808. elements [numElements++] = y3;
  68809. pathXMin = jmin (pathXMin, x1, x2, x3);
  68810. pathXMax = jmax (pathXMax, x1, x2, x3);
  68811. pathYMin = jmin (pathYMin, y1, y2, y3);
  68812. pathYMax = jmax (pathYMax, y1, y2, y3);
  68813. }
  68814. void Path::closeSubPath() throw()
  68815. {
  68816. if (numElements > 0
  68817. && elements [numElements - 1] != closeSubPathMarker)
  68818. {
  68819. ensureAllocatedSize (numElements + 1);
  68820. elements [numElements++] = closeSubPathMarker;
  68821. }
  68822. }
  68823. const Point Path::getCurrentPosition() const
  68824. {
  68825. int i = numElements - 1;
  68826. if (i > 0 && elements[i] == closeSubPathMarker)
  68827. {
  68828. while (i >= 0)
  68829. {
  68830. if (elements[i] == moveMarker)
  68831. {
  68832. i += 2;
  68833. break;
  68834. }
  68835. --i;
  68836. }
  68837. }
  68838. if (i > 0)
  68839. return Point (elements [i - 1], elements [i]);
  68840. return Point (0.0f, 0.0f);
  68841. }
  68842. void Path::addRectangle (const float x, const float y,
  68843. const float w, const float h) throw()
  68844. {
  68845. startNewSubPath (x, y + h);
  68846. lineTo (x, y);
  68847. lineTo (x + w, y);
  68848. lineTo (x + w, y + h);
  68849. closeSubPath();
  68850. }
  68851. void Path::addRoundedRectangle (const float x, const float y,
  68852. const float w, const float h,
  68853. float csx,
  68854. float csy) throw()
  68855. {
  68856. csx = jmin (csx, w * 0.5f);
  68857. csy = jmin (csy, h * 0.5f);
  68858. const float cs45x = csx * 0.45f;
  68859. const float cs45y = csy * 0.45f;
  68860. const float x2 = x + w;
  68861. const float y2 = y + h;
  68862. startNewSubPath (x + csx, y);
  68863. lineTo (x2 - csx, y);
  68864. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  68865. lineTo (x2, y2 - csy);
  68866. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  68867. lineTo (x + csx, y2);
  68868. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  68869. lineTo (x, y + csy);
  68870. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  68871. closeSubPath();
  68872. }
  68873. void Path::addRoundedRectangle (const float x, const float y,
  68874. const float w, const float h,
  68875. float cs) throw()
  68876. {
  68877. addRoundedRectangle (x, y, w, h, cs, cs);
  68878. }
  68879. void Path::addTriangle (const float x1, const float y1,
  68880. const float x2, const float y2,
  68881. const float x3, const float y3) throw()
  68882. {
  68883. startNewSubPath (x1, y1);
  68884. lineTo (x2, y2);
  68885. lineTo (x3, y3);
  68886. closeSubPath();
  68887. }
  68888. void Path::addQuadrilateral (const float x1, const float y1,
  68889. const float x2, const float y2,
  68890. const float x3, const float y3,
  68891. const float x4, const float y4) throw()
  68892. {
  68893. startNewSubPath (x1, y1);
  68894. lineTo (x2, y2);
  68895. lineTo (x3, y3);
  68896. lineTo (x4, y4);
  68897. closeSubPath();
  68898. }
  68899. void Path::addEllipse (const float x, const float y,
  68900. const float w, const float h) throw()
  68901. {
  68902. const float hw = w * 0.5f;
  68903. const float hw55 = hw * 0.55f;
  68904. const float hh = h * 0.5f;
  68905. const float hh45 = hh * 0.55f;
  68906. const float cx = x + hw;
  68907. const float cy = y + hh;
  68908. startNewSubPath (cx, cy - hh);
  68909. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  68910. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  68911. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  68912. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  68913. closeSubPath();
  68914. }
  68915. void Path::addArc (const float x, const float y,
  68916. const float w, const float h,
  68917. const float fromRadians,
  68918. const float toRadians,
  68919. const bool startAsNewSubPath) throw()
  68920. {
  68921. const float radiusX = w / 2.0f;
  68922. const float radiusY = h / 2.0f;
  68923. addCentredArc (x + radiusX,
  68924. y + radiusY,
  68925. radiusX, radiusY,
  68926. 0.0f,
  68927. fromRadians, toRadians,
  68928. startAsNewSubPath);
  68929. }
  68930. static const float ellipseAngularIncrement = 0.05f;
  68931. void Path::addCentredArc (const float centreX, const float centreY,
  68932. const float radiusX, const float radiusY,
  68933. const float rotationOfEllipse,
  68934. const float fromRadians,
  68935. const float toRadians,
  68936. const bool startAsNewSubPath) throw()
  68937. {
  68938. if (radiusX > 0.0f && radiusY > 0.0f)
  68939. {
  68940. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  68941. float angle = fromRadians;
  68942. if (startAsNewSubPath)
  68943. {
  68944. float x = centreX + radiusX * sinf (angle);
  68945. float y = centreY - radiusY * cosf (angle);
  68946. if (rotationOfEllipse != 0)
  68947. rotation.transformPoint (x, y);
  68948. startNewSubPath (x, y);
  68949. }
  68950. if (fromRadians < toRadians)
  68951. {
  68952. if (startAsNewSubPath)
  68953. angle += ellipseAngularIncrement;
  68954. while (angle < toRadians)
  68955. {
  68956. float x = centreX + radiusX * sinf (angle);
  68957. float y = centreY - radiusY * cosf (angle);
  68958. if (rotationOfEllipse != 0)
  68959. rotation.transformPoint (x, y);
  68960. lineTo (x, y);
  68961. angle += ellipseAngularIncrement;
  68962. }
  68963. }
  68964. else
  68965. {
  68966. if (startAsNewSubPath)
  68967. angle -= ellipseAngularIncrement;
  68968. while (angle > toRadians)
  68969. {
  68970. float x = centreX + radiusX * sinf (angle);
  68971. float y = centreY - radiusY * cosf (angle);
  68972. if (rotationOfEllipse != 0)
  68973. rotation.transformPoint (x, y);
  68974. lineTo (x, y);
  68975. angle -= ellipseAngularIncrement;
  68976. }
  68977. }
  68978. float x = centreX + radiusX * sinf (toRadians);
  68979. float y = centreY - radiusY * cosf (toRadians);
  68980. if (rotationOfEllipse != 0)
  68981. rotation.transformPoint (x, y);
  68982. lineTo (x, y);
  68983. }
  68984. }
  68985. void Path::addPieSegment (const float x, const float y,
  68986. const float width, const float height,
  68987. const float fromRadians,
  68988. const float toRadians,
  68989. const float innerCircleProportionalSize)
  68990. {
  68991. float hw = width * 0.5f;
  68992. float hh = height * 0.5f;
  68993. const float centreX = x + hw;
  68994. const float centreY = y + hh;
  68995. startNewSubPath (centreX + hw * sinf (fromRadians),
  68996. centreY - hh * cosf (fromRadians));
  68997. addArc (x, y, width, height, fromRadians, toRadians);
  68998. if (fabs (fromRadians - toRadians) > float_Pi * 1.999f)
  68999. {
  69000. closeSubPath();
  69001. if (innerCircleProportionalSize > 0)
  69002. {
  69003. hw *= innerCircleProportionalSize;
  69004. hh *= innerCircleProportionalSize;
  69005. startNewSubPath (centreX + hw * sinf (toRadians),
  69006. centreY - hh * cosf (toRadians));
  69007. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  69008. toRadians, fromRadians);
  69009. }
  69010. }
  69011. else
  69012. {
  69013. if (innerCircleProportionalSize > 0)
  69014. {
  69015. hw *= innerCircleProportionalSize;
  69016. hh *= innerCircleProportionalSize;
  69017. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  69018. toRadians, fromRadians);
  69019. }
  69020. else
  69021. {
  69022. lineTo (centreX, centreY);
  69023. }
  69024. }
  69025. closeSubPath();
  69026. }
  69027. static void perpendicularOffset (const float x1, const float y1,
  69028. const float x2, const float y2,
  69029. const float offsetX, const float offsetY,
  69030. float& resultX, float& resultY) throw()
  69031. {
  69032. const float dx = x2 - x1;
  69033. const float dy = y2 - y1;
  69034. const float len = juce_hypotf (dx, dy);
  69035. if (len == 0)
  69036. {
  69037. resultX = x1;
  69038. resultY = y1;
  69039. }
  69040. else
  69041. {
  69042. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  69043. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  69044. }
  69045. }
  69046. void Path::addLineSegment (const float startX, const float startY,
  69047. const float endX, const float endY,
  69048. float lineThickness) throw()
  69049. {
  69050. lineThickness *= 0.5f;
  69051. float x, y;
  69052. perpendicularOffset (startX, startY, endX, endY,
  69053. 0, lineThickness, x, y);
  69054. startNewSubPath (x, y);
  69055. perpendicularOffset (startX, startY, endX, endY,
  69056. 0, -lineThickness, x, y);
  69057. lineTo (x, y);
  69058. perpendicularOffset (endX, endY, startX, startY,
  69059. 0, lineThickness, x, y);
  69060. lineTo (x, y);
  69061. perpendicularOffset (endX, endY, startX, startY,
  69062. 0, -lineThickness, x, y);
  69063. lineTo (x, y);
  69064. closeSubPath();
  69065. }
  69066. void Path::addArrow (const float startX, const float startY,
  69067. const float endX, const float endY,
  69068. float lineThickness,
  69069. float arrowheadWidth,
  69070. float arrowheadLength) throw()
  69071. {
  69072. lineThickness *= 0.5f;
  69073. arrowheadWidth *= 0.5f;
  69074. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  69075. startY - endY));
  69076. float x, y;
  69077. perpendicularOffset (startX, startY, endX, endY,
  69078. 0, lineThickness, x, y);
  69079. startNewSubPath (x, y);
  69080. perpendicularOffset (startX, startY, endX, endY,
  69081. 0, -lineThickness, x, y);
  69082. lineTo (x, y);
  69083. perpendicularOffset (endX, endY, startX, startY,
  69084. arrowheadLength, lineThickness, x, y);
  69085. lineTo (x, y);
  69086. perpendicularOffset (endX, endY, startX, startY,
  69087. arrowheadLength, arrowheadWidth, x, y);
  69088. lineTo (x, y);
  69089. perpendicularOffset (endX, endY, startX, startY,
  69090. 0, 0, x, y);
  69091. lineTo (x, y);
  69092. perpendicularOffset (endX, endY, startX, startY,
  69093. arrowheadLength, -arrowheadWidth, x, y);
  69094. lineTo (x, y);
  69095. perpendicularOffset (endX, endY, startX, startY,
  69096. arrowheadLength, -lineThickness, x, y);
  69097. lineTo (x, y);
  69098. closeSubPath();
  69099. }
  69100. void Path::addStar (const float centreX,
  69101. const float centreY,
  69102. const int numberOfPoints,
  69103. const float innerRadius,
  69104. const float outerRadius,
  69105. const float startAngle)
  69106. {
  69107. jassert (numberOfPoints > 1); // this would be silly.
  69108. if (numberOfPoints > 1)
  69109. {
  69110. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  69111. for (int i = 0; i < numberOfPoints; ++i)
  69112. {
  69113. float angle = startAngle + i * angleBetweenPoints;
  69114. const float x = centreX + outerRadius * sinf (angle);
  69115. const float y = centreY - outerRadius * cosf (angle);
  69116. if (i == 0)
  69117. startNewSubPath (x, y);
  69118. else
  69119. lineTo (x, y);
  69120. angle += angleBetweenPoints * 0.5f;
  69121. lineTo (centreX + innerRadius * sinf (angle),
  69122. centreY - innerRadius * cosf (angle));
  69123. }
  69124. closeSubPath();
  69125. }
  69126. }
  69127. void Path::addBubble (float x, float y,
  69128. float w, float h,
  69129. float cs,
  69130. float tipX,
  69131. float tipY,
  69132. int whichSide,
  69133. float arrowPos,
  69134. float arrowWidth)
  69135. {
  69136. if (w > 1.0f && h > 1.0f)
  69137. {
  69138. cs = jmin (cs, w * 0.5f, h * 0.5f);
  69139. const float cs2 = 2.0f * cs;
  69140. startNewSubPath (x + cs, y);
  69141. if (whichSide == 0)
  69142. {
  69143. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  69144. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  69145. lineTo (arrowX1, y);
  69146. lineTo (tipX, tipY);
  69147. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  69148. }
  69149. lineTo (x + w - cs, y);
  69150. if (cs > 0.0f)
  69151. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  69152. if (whichSide == 3)
  69153. {
  69154. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  69155. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  69156. lineTo (x + w, arrowY1);
  69157. lineTo (tipX, tipY);
  69158. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  69159. }
  69160. lineTo (x + w, y + h - cs);
  69161. if (cs > 0.0f)
  69162. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  69163. if (whichSide == 2)
  69164. {
  69165. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  69166. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  69167. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  69168. lineTo (tipX, tipY);
  69169. lineTo (arrowX1, y + h);
  69170. }
  69171. lineTo (x + cs, y + h);
  69172. if (cs > 0.0f)
  69173. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  69174. if (whichSide == 1)
  69175. {
  69176. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  69177. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  69178. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  69179. lineTo (tipX, tipY);
  69180. lineTo (x, arrowY1);
  69181. }
  69182. lineTo (x, y + cs);
  69183. if (cs > 0.0f)
  69184. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - ellipseAngularIncrement);
  69185. closeSubPath();
  69186. }
  69187. }
  69188. void Path::addPath (const Path& other) throw()
  69189. {
  69190. int i = 0;
  69191. while (i < other.numElements)
  69192. {
  69193. const float type = other.elements [i++];
  69194. if (type == moveMarker)
  69195. {
  69196. startNewSubPath (other.elements [i],
  69197. other.elements [i + 1]);
  69198. i += 2;
  69199. }
  69200. else if (type == lineMarker)
  69201. {
  69202. lineTo (other.elements [i],
  69203. other.elements [i + 1]);
  69204. i += 2;
  69205. }
  69206. else if (type == quadMarker)
  69207. {
  69208. quadraticTo (other.elements [i],
  69209. other.elements [i + 1],
  69210. other.elements [i + 2],
  69211. other.elements [i + 3]);
  69212. i += 4;
  69213. }
  69214. else if (type == cubicMarker)
  69215. {
  69216. cubicTo (other.elements [i],
  69217. other.elements [i + 1],
  69218. other.elements [i + 2],
  69219. other.elements [i + 3],
  69220. other.elements [i + 4],
  69221. other.elements [i + 5]);
  69222. i += 6;
  69223. }
  69224. else if (type == closeSubPathMarker)
  69225. {
  69226. closeSubPath();
  69227. }
  69228. else
  69229. {
  69230. // something's gone wrong with the element list!
  69231. jassertfalse
  69232. }
  69233. }
  69234. }
  69235. void Path::addPath (const Path& other,
  69236. const AffineTransform& transformToApply) throw()
  69237. {
  69238. int i = 0;
  69239. while (i < other.numElements)
  69240. {
  69241. const float type = other.elements [i++];
  69242. if (type == closeSubPathMarker)
  69243. {
  69244. closeSubPath();
  69245. }
  69246. else
  69247. {
  69248. float x = other.elements [i++];
  69249. float y = other.elements [i++];
  69250. transformToApply.transformPoint (x, y);
  69251. if (type == moveMarker)
  69252. {
  69253. startNewSubPath (x, y);
  69254. }
  69255. else if (type == lineMarker)
  69256. {
  69257. lineTo (x, y);
  69258. }
  69259. else if (type == quadMarker)
  69260. {
  69261. float x2 = other.elements [i++];
  69262. float y2 = other.elements [i++];
  69263. transformToApply.transformPoint (x2, y2);
  69264. quadraticTo (x, y, x2, y2);
  69265. }
  69266. else if (type == cubicMarker)
  69267. {
  69268. float x2 = other.elements [i++];
  69269. float y2 = other.elements [i++];
  69270. float x3 = other.elements [i++];
  69271. float y3 = other.elements [i++];
  69272. transformToApply.transformPoint (x2, y2);
  69273. transformToApply.transformPoint (x3, y3);
  69274. cubicTo (x, y, x2, y2, x3, y3);
  69275. }
  69276. else
  69277. {
  69278. // something's gone wrong with the element list!
  69279. jassertfalse
  69280. }
  69281. }
  69282. }
  69283. }
  69284. void Path::applyTransform (const AffineTransform& transform) throw()
  69285. {
  69286. int i = 0;
  69287. pathYMin = pathXMin = 0;
  69288. pathYMax = pathXMax = 0;
  69289. bool setMaxMin = false;
  69290. while (i < numElements)
  69291. {
  69292. const float type = elements [i++];
  69293. if (type == moveMarker)
  69294. {
  69295. transform.transformPoint (elements [i],
  69296. elements [i + 1]);
  69297. if (setMaxMin)
  69298. {
  69299. pathXMin = jmin (pathXMin, elements [i]);
  69300. pathXMax = jmax (pathXMax, elements [i]);
  69301. pathYMin = jmin (pathYMin, elements [i + 1]);
  69302. pathYMax = jmax (pathYMax, elements [i + 1]);
  69303. }
  69304. else
  69305. {
  69306. pathXMin = pathXMax = elements [i];
  69307. pathYMin = pathYMax = elements [i + 1];
  69308. setMaxMin = true;
  69309. }
  69310. i += 2;
  69311. }
  69312. else if (type == lineMarker)
  69313. {
  69314. transform.transformPoint (elements [i],
  69315. elements [i + 1]);
  69316. pathXMin = jmin (pathXMin, elements [i]);
  69317. pathXMax = jmax (pathXMax, elements [i]);
  69318. pathYMin = jmin (pathYMin, elements [i + 1]);
  69319. pathYMax = jmax (pathYMax, elements [i + 1]);
  69320. i += 2;
  69321. }
  69322. else if (type == quadMarker)
  69323. {
  69324. transform.transformPoint (elements [i],
  69325. elements [i + 1]);
  69326. transform.transformPoint (elements [i + 2],
  69327. elements [i + 3]);
  69328. pathXMin = jmin (pathXMin, elements [i], elements [i + 2]);
  69329. pathXMax = jmax (pathXMax, elements [i], elements [i + 2]);
  69330. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3]);
  69331. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3]);
  69332. i += 4;
  69333. }
  69334. else if (type == cubicMarker)
  69335. {
  69336. transform.transformPoint (elements [i],
  69337. elements [i + 1]);
  69338. transform.transformPoint (elements [i + 2],
  69339. elements [i + 3]);
  69340. transform.transformPoint (elements [i + 4],
  69341. elements [i + 5]);
  69342. pathXMin = jmin (pathXMin, elements [i], elements [i + 2], elements [i + 4]);
  69343. pathXMax = jmax (pathXMax, elements [i], elements [i + 2], elements [i + 4]);
  69344. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3], elements [i + 5]);
  69345. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3], elements [i + 5]);
  69346. i += 6;
  69347. }
  69348. }
  69349. }
  69350. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  69351. const float w, const float h,
  69352. const bool preserveProportions,
  69353. const Justification& justification) const throw()
  69354. {
  69355. float sx, sy, sw, sh;
  69356. getBounds (sx, sy, sw, sh);
  69357. if (preserveProportions)
  69358. {
  69359. if (w <= 0 || h <= 0 || sw <= 0 || sh <= 0)
  69360. return AffineTransform::identity;
  69361. float newW, newH;
  69362. const float srcRatio = sh / sw;
  69363. if (srcRatio > h / w)
  69364. {
  69365. newW = h / srcRatio;
  69366. newH = h;
  69367. }
  69368. else
  69369. {
  69370. newW = w;
  69371. newH = w * srcRatio;
  69372. }
  69373. float newXCentre = x;
  69374. float newYCentre = y;
  69375. if (justification.testFlags (Justification::left))
  69376. newXCentre += newW * 0.5f;
  69377. else if (justification.testFlags (Justification::right))
  69378. newXCentre += w - newW * 0.5f;
  69379. else
  69380. newXCentre += w * 0.5f;
  69381. if (justification.testFlags (Justification::top))
  69382. newYCentre += newH * 0.5f;
  69383. else if (justification.testFlags (Justification::bottom))
  69384. newYCentre += h - newH * 0.5f;
  69385. else
  69386. newYCentre += h * 0.5f;
  69387. return AffineTransform::translation (sw * -0.5f - sx, sh * -0.5f - sy)
  69388. .scaled (newW / sw, newH / sh)
  69389. .translated (newXCentre, newYCentre);
  69390. }
  69391. else
  69392. {
  69393. return AffineTransform::translation (-sx, -sy)
  69394. .scaled (w / sw, h / sh)
  69395. .translated (x, y);
  69396. }
  69397. }
  69398. bool Path::contains (const float x, const float y, const float tolerence) const throw()
  69399. {
  69400. if (x <= pathXMin || x >= pathXMax
  69401. || y <= pathYMin || y >= pathYMax)
  69402. return false;
  69403. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  69404. int positiveCrossings = 0;
  69405. int negativeCrossings = 0;
  69406. while (i.next())
  69407. {
  69408. if ((i.y1 <= y && i.y2 > y)
  69409. || (i.y2 <= y && i.y1 > y))
  69410. {
  69411. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  69412. if (intersectX <= x)
  69413. {
  69414. if (i.y1 < i.y2)
  69415. ++positiveCrossings;
  69416. else
  69417. ++negativeCrossings;
  69418. }
  69419. }
  69420. }
  69421. return (useNonZeroWinding) ? (negativeCrossings != positiveCrossings)
  69422. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  69423. }
  69424. bool Path::intersectsLine (const float x1, const float y1,
  69425. const float x2, const float y2,
  69426. const float tolerence) throw()
  69427. {
  69428. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  69429. const Line line1 (x1, y1, x2, y2);
  69430. while (i.next())
  69431. {
  69432. const Line line2 (i.x1, i.y1, i.x2, i.y2);
  69433. float ix, iy;
  69434. if (line1.intersects (line2, ix, iy))
  69435. return true;
  69436. }
  69437. return false;
  69438. }
  69439. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const throw()
  69440. {
  69441. if (cornerRadius <= 0.01f)
  69442. return *this;
  69443. int indexOfPathStart = 0, indexOfPathStartThis = 0;
  69444. int n = 0;
  69445. bool lastWasLine = false, firstWasLine = false;
  69446. Path p;
  69447. while (n < numElements)
  69448. {
  69449. const float type = elements [n++];
  69450. if (type == moveMarker)
  69451. {
  69452. indexOfPathStart = p.numElements;
  69453. indexOfPathStartThis = n - 1;
  69454. const float x = elements [n++];
  69455. const float y = elements [n++];
  69456. p.startNewSubPath (x, y);
  69457. lastWasLine = false;
  69458. firstWasLine = (elements [n] == lineMarker);
  69459. }
  69460. else if (type == lineMarker || type == closeSubPathMarker)
  69461. {
  69462. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  69463. if (type == lineMarker)
  69464. {
  69465. endX = elements [n++];
  69466. endY = elements [n++];
  69467. if (n > 8)
  69468. {
  69469. startX = elements [n - 8];
  69470. startY = elements [n - 7];
  69471. joinX = elements [n - 5];
  69472. joinY = elements [n - 4];
  69473. }
  69474. }
  69475. else
  69476. {
  69477. endX = elements [indexOfPathStartThis + 1];
  69478. endY = elements [indexOfPathStartThis + 2];
  69479. if (n > 6)
  69480. {
  69481. startX = elements [n - 6];
  69482. startY = elements [n - 5];
  69483. joinX = elements [n - 3];
  69484. joinY = elements [n - 2];
  69485. }
  69486. }
  69487. if (lastWasLine)
  69488. {
  69489. const double len1 = juce_hypot (startX - joinX,
  69490. startY - joinY);
  69491. if (len1 > 0)
  69492. {
  69493. const double propNeeded = jmin (0.5, cornerRadius / len1);
  69494. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  69495. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  69496. }
  69497. const double len2 = juce_hypot (endX - joinX,
  69498. endY - joinY);
  69499. if (len2 > 0)
  69500. {
  69501. const double propNeeded = jmin (0.5, cornerRadius / len2);
  69502. p.quadraticTo (joinX, joinY,
  69503. (float) (joinX + (endX - joinX) * propNeeded),
  69504. (float) (joinY + (endY - joinY) * propNeeded));
  69505. }
  69506. p.lineTo (endX, endY);
  69507. }
  69508. else if (type == lineMarker)
  69509. {
  69510. p.lineTo (endX, endY);
  69511. lastWasLine = true;
  69512. }
  69513. if (type == closeSubPathMarker)
  69514. {
  69515. if (firstWasLine)
  69516. {
  69517. startX = elements [n - 3];
  69518. startY = elements [n - 2];
  69519. joinX = endX;
  69520. joinY = endY;
  69521. endX = elements [indexOfPathStartThis + 4];
  69522. endY = elements [indexOfPathStartThis + 5];
  69523. const double len1 = juce_hypot (startX - joinX,
  69524. startY - joinY);
  69525. if (len1 > 0)
  69526. {
  69527. const double propNeeded = jmin (0.5, cornerRadius / len1);
  69528. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  69529. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  69530. }
  69531. const double len2 = juce_hypot (endX - joinX,
  69532. endY - joinY);
  69533. if (len2 > 0)
  69534. {
  69535. const double propNeeded = jmin (0.5, cornerRadius / len2);
  69536. endX = (float) (joinX + (endX - joinX) * propNeeded);
  69537. endY = (float) (joinY + (endY - joinY) * propNeeded);
  69538. p.quadraticTo (joinX, joinY, endX, endY);
  69539. p.elements [indexOfPathStart + 1] = endX;
  69540. p.elements [indexOfPathStart + 2] = endY;
  69541. }
  69542. }
  69543. p.closeSubPath();
  69544. }
  69545. }
  69546. else if (type == quadMarker)
  69547. {
  69548. lastWasLine = false;
  69549. const float x1 = elements [n++];
  69550. const float y1 = elements [n++];
  69551. const float x2 = elements [n++];
  69552. const float y2 = elements [n++];
  69553. p.quadraticTo (x1, y1, x2, y2);
  69554. }
  69555. else if (type == cubicMarker)
  69556. {
  69557. lastWasLine = false;
  69558. const float x1 = elements [n++];
  69559. const float y1 = elements [n++];
  69560. const float x2 = elements [n++];
  69561. const float y2 = elements [n++];
  69562. const float x3 = elements [n++];
  69563. const float y3 = elements [n++];
  69564. p.cubicTo (x1, y1, x2, y2, x3, y3);
  69565. }
  69566. }
  69567. return p;
  69568. }
  69569. void Path::loadPathFromStream (InputStream& source)
  69570. {
  69571. while (! source.isExhausted())
  69572. {
  69573. switch (source.readByte())
  69574. {
  69575. case 'm':
  69576. {
  69577. const float x = source.readFloat();
  69578. const float y = source.readFloat();
  69579. startNewSubPath (x, y);
  69580. break;
  69581. }
  69582. case 'l':
  69583. {
  69584. const float x = source.readFloat();
  69585. const float y = source.readFloat();
  69586. lineTo (x, y);
  69587. break;
  69588. }
  69589. case 'q':
  69590. {
  69591. const float x1 = source.readFloat();
  69592. const float y1 = source.readFloat();
  69593. const float x2 = source.readFloat();
  69594. const float y2 = source.readFloat();
  69595. quadraticTo (x1, y1, x2, y2);
  69596. break;
  69597. }
  69598. case 'b':
  69599. {
  69600. const float x1 = source.readFloat();
  69601. const float y1 = source.readFloat();
  69602. const float x2 = source.readFloat();
  69603. const float y2 = source.readFloat();
  69604. const float x3 = source.readFloat();
  69605. const float y3 = source.readFloat();
  69606. cubicTo (x1, y1, x2, y2, x3, y3);
  69607. break;
  69608. }
  69609. case 'c':
  69610. closeSubPath();
  69611. break;
  69612. case 'n':
  69613. useNonZeroWinding = true;
  69614. break;
  69615. case 'z':
  69616. useNonZeroWinding = false;
  69617. break;
  69618. case 'e':
  69619. return; // end of path marker
  69620. default:
  69621. jassertfalse // illegal char in the stream
  69622. break;
  69623. }
  69624. }
  69625. }
  69626. void Path::loadPathFromData (const unsigned char* const data,
  69627. const int numberOfBytes) throw()
  69628. {
  69629. MemoryInputStream in ((const char*) data, numberOfBytes, false);
  69630. loadPathFromStream (in);
  69631. }
  69632. void Path::writePathToStream (OutputStream& dest) const
  69633. {
  69634. dest.writeByte ((useNonZeroWinding) ? 'n' : 'z');
  69635. int i = 0;
  69636. while (i < numElements)
  69637. {
  69638. const float type = elements [i++];
  69639. if (type == moveMarker)
  69640. {
  69641. dest.writeByte ('m');
  69642. dest.writeFloat (elements [i++]);
  69643. dest.writeFloat (elements [i++]);
  69644. }
  69645. else if (type == lineMarker)
  69646. {
  69647. dest.writeByte ('l');
  69648. dest.writeFloat (elements [i++]);
  69649. dest.writeFloat (elements [i++]);
  69650. }
  69651. else if (type == quadMarker)
  69652. {
  69653. dest.writeByte ('q');
  69654. dest.writeFloat (elements [i++]);
  69655. dest.writeFloat (elements [i++]);
  69656. dest.writeFloat (elements [i++]);
  69657. dest.writeFloat (elements [i++]);
  69658. }
  69659. else if (type == cubicMarker)
  69660. {
  69661. dest.writeByte ('b');
  69662. dest.writeFloat (elements [i++]);
  69663. dest.writeFloat (elements [i++]);
  69664. dest.writeFloat (elements [i++]);
  69665. dest.writeFloat (elements [i++]);
  69666. dest.writeFloat (elements [i++]);
  69667. dest.writeFloat (elements [i++]);
  69668. }
  69669. else if (type == closeSubPathMarker)
  69670. {
  69671. dest.writeByte ('c');
  69672. }
  69673. }
  69674. dest.writeByte ('e'); // marks the end-of-path
  69675. }
  69676. const String Path::toString() const
  69677. {
  69678. String s;
  69679. s.preallocateStorage (numElements * 4);
  69680. if (! useNonZeroWinding)
  69681. s << T("a ");
  69682. int i = 0;
  69683. float lastMarker = 0.0f;
  69684. while (i < numElements)
  69685. {
  69686. const float marker = elements [i++];
  69687. tchar markerChar = 0;
  69688. int numCoords = 0;
  69689. if (marker == moveMarker)
  69690. {
  69691. markerChar = T('m');
  69692. numCoords = 2;
  69693. }
  69694. else if (marker == lineMarker)
  69695. {
  69696. markerChar = T('l');
  69697. numCoords = 2;
  69698. }
  69699. else if (marker == quadMarker)
  69700. {
  69701. markerChar = T('q');
  69702. numCoords = 4;
  69703. }
  69704. else if (marker == cubicMarker)
  69705. {
  69706. markerChar = T('c');
  69707. numCoords = 6;
  69708. }
  69709. else
  69710. {
  69711. jassert (marker == closeSubPathMarker);
  69712. markerChar = T('z');
  69713. }
  69714. if (marker != lastMarker)
  69715. {
  69716. s << markerChar << T(' ');
  69717. lastMarker = marker;
  69718. }
  69719. while (--numCoords >= 0 && i < numElements)
  69720. {
  69721. String n (elements [i++], 3);
  69722. while (n.endsWithChar (T('0')))
  69723. n = n.dropLastCharacters (1);
  69724. if (n.endsWithChar (T('.')))
  69725. n = n.dropLastCharacters (1);
  69726. s << n << T(' ');
  69727. }
  69728. }
  69729. return s.trimEnd();
  69730. }
  69731. static const String nextToken (const tchar*& t)
  69732. {
  69733. while (*t == T(' '))
  69734. ++t;
  69735. const tchar* const start = t;
  69736. while (*t != 0 && *t != T(' '))
  69737. ++t;
  69738. const int length = (int) (t - start);
  69739. while (*t == T(' '))
  69740. ++t;
  69741. return String (start, length);
  69742. }
  69743. void Path::restoreFromString (const String& stringVersion)
  69744. {
  69745. clear();
  69746. setUsingNonZeroWinding (true);
  69747. const tchar* t = stringVersion;
  69748. tchar marker = T('m');
  69749. int numValues = 2;
  69750. float values [6];
  69751. while (*t != 0)
  69752. {
  69753. const String token (nextToken (t));
  69754. const tchar firstChar = token[0];
  69755. int startNum = 0;
  69756. if (firstChar == T('m') || firstChar == T('l'))
  69757. {
  69758. marker = firstChar;
  69759. numValues = 2;
  69760. }
  69761. else if (firstChar == T('q'))
  69762. {
  69763. marker = firstChar;
  69764. numValues = 4;
  69765. }
  69766. else if (firstChar == T('c'))
  69767. {
  69768. marker = firstChar;
  69769. numValues = 6;
  69770. }
  69771. else if (firstChar == T('z'))
  69772. {
  69773. marker = firstChar;
  69774. numValues = 0;
  69775. }
  69776. else if (firstChar == T('a'))
  69777. {
  69778. setUsingNonZeroWinding (false);
  69779. continue;
  69780. }
  69781. else
  69782. {
  69783. ++startNum;
  69784. values [0] = token.getFloatValue();
  69785. }
  69786. for (int i = startNum; i < numValues; ++i)
  69787. values [i] = nextToken (t).getFloatValue();
  69788. switch (marker)
  69789. {
  69790. case T('m'):
  69791. startNewSubPath (values[0], values[1]);
  69792. break;
  69793. case T('l'):
  69794. lineTo (values[0], values[1]);
  69795. break;
  69796. case T('q'):
  69797. quadraticTo (values[0], values[1],
  69798. values[2], values[3]);
  69799. break;
  69800. case T('c'):
  69801. cubicTo (values[0], values[1],
  69802. values[2], values[3],
  69803. values[4], values[5]);
  69804. break;
  69805. case T('z'):
  69806. closeSubPath();
  69807. break;
  69808. default:
  69809. jassertfalse // illegal string format?
  69810. break;
  69811. }
  69812. }
  69813. }
  69814. Path::Iterator::Iterator (const Path& path_)
  69815. : path (path_),
  69816. index (0)
  69817. {
  69818. }
  69819. Path::Iterator::~Iterator()
  69820. {
  69821. }
  69822. bool Path::Iterator::next()
  69823. {
  69824. const float* const elements = path.elements;
  69825. if (index < path.numElements)
  69826. {
  69827. const float type = elements [index++];
  69828. if (type == moveMarker)
  69829. {
  69830. elementType = startNewSubPath;
  69831. x1 = elements [index++];
  69832. y1 = elements [index++];
  69833. }
  69834. else if (type == lineMarker)
  69835. {
  69836. elementType = lineTo;
  69837. x1 = elements [index++];
  69838. y1 = elements [index++];
  69839. }
  69840. else if (type == quadMarker)
  69841. {
  69842. elementType = quadraticTo;
  69843. x1 = elements [index++];
  69844. y1 = elements [index++];
  69845. x2 = elements [index++];
  69846. y2 = elements [index++];
  69847. }
  69848. else if (type == cubicMarker)
  69849. {
  69850. elementType = cubicTo;
  69851. x1 = elements [index++];
  69852. y1 = elements [index++];
  69853. x2 = elements [index++];
  69854. y2 = elements [index++];
  69855. x3 = elements [index++];
  69856. y3 = elements [index++];
  69857. }
  69858. else if (type == closeSubPathMarker)
  69859. {
  69860. elementType = closePath;
  69861. }
  69862. return true;
  69863. }
  69864. return false;
  69865. }
  69866. END_JUCE_NAMESPACE
  69867. /********* End of inlined file: juce_Path.cpp *********/
  69868. /********* Start of inlined file: juce_PathIterator.cpp *********/
  69869. BEGIN_JUCE_NAMESPACE
  69870. #if JUCE_MSVC
  69871. #pragma optimize ("t", on)
  69872. #endif
  69873. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  69874. const AffineTransform& transform_,
  69875. float tolerence_) throw()
  69876. : x2 (0),
  69877. y2 (0),
  69878. closesSubPath (false),
  69879. subPathIndex (-1),
  69880. path (path_),
  69881. transform (transform_),
  69882. points (path_.elements),
  69883. tolerence (tolerence_ * tolerence_),
  69884. subPathCloseX (0),
  69885. subPathCloseY (0),
  69886. index (0),
  69887. stackSize (32)
  69888. {
  69889. stackBase = (float*) juce_malloc (stackSize * sizeof (float));
  69890. isIdentityTransform = transform.isIdentity();
  69891. stackPos = stackBase;
  69892. }
  69893. PathFlatteningIterator::~PathFlatteningIterator() throw()
  69894. {
  69895. juce_free (stackBase);
  69896. }
  69897. bool PathFlatteningIterator::next() throw()
  69898. {
  69899. x1 = x2;
  69900. y1 = y2;
  69901. float x3 = 0;
  69902. float y3 = 0;
  69903. float x4 = 0;
  69904. float y4 = 0;
  69905. float type;
  69906. for (;;)
  69907. {
  69908. if (stackPos == stackBase)
  69909. {
  69910. if (index >= path.numElements)
  69911. {
  69912. return false;
  69913. }
  69914. else
  69915. {
  69916. type = points [index++];
  69917. if (type != Path::closeSubPathMarker)
  69918. {
  69919. x2 = points [index++];
  69920. y2 = points [index++];
  69921. if (! isIdentityTransform)
  69922. transform.transformPoint (x2, y2);
  69923. if (type == Path::quadMarker)
  69924. {
  69925. x3 = points [index++];
  69926. y3 = points [index++];
  69927. if (! isIdentityTransform)
  69928. transform.transformPoint (x3, y3);
  69929. }
  69930. else if (type == Path::cubicMarker)
  69931. {
  69932. x3 = points [index++];
  69933. y3 = points [index++];
  69934. x4 = points [index++];
  69935. y4 = points [index++];
  69936. if (! isIdentityTransform)
  69937. {
  69938. transform.transformPoint (x3, y3);
  69939. transform.transformPoint (x4, y4);
  69940. }
  69941. }
  69942. }
  69943. }
  69944. }
  69945. else
  69946. {
  69947. type = *--stackPos;
  69948. if (type != Path::closeSubPathMarker)
  69949. {
  69950. x2 = *--stackPos;
  69951. y2 = *--stackPos;
  69952. if (type == Path::quadMarker)
  69953. {
  69954. x3 = *--stackPos;
  69955. y3 = *--stackPos;
  69956. }
  69957. else if (type == Path::cubicMarker)
  69958. {
  69959. x3 = *--stackPos;
  69960. y3 = *--stackPos;
  69961. x4 = *--stackPos;
  69962. y4 = *--stackPos;
  69963. }
  69964. }
  69965. }
  69966. if (type == Path::lineMarker)
  69967. {
  69968. ++subPathIndex;
  69969. closesSubPath = (stackPos == stackBase)
  69970. && (index < path.numElements)
  69971. && (points [index] == Path::closeSubPathMarker)
  69972. && x2 == subPathCloseX
  69973. && y2 == subPathCloseY;
  69974. return true;
  69975. }
  69976. else if (type == Path::quadMarker)
  69977. {
  69978. const int offset = (int) (stackPos - stackBase);
  69979. if (offset >= stackSize - 10)
  69980. {
  69981. stackSize <<= 1;
  69982. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  69983. stackPos = stackBase + offset;
  69984. }
  69985. const float dx1 = x1 - x2;
  69986. const float dy1 = y1 - y2;
  69987. const float dx2 = x2 - x3;
  69988. const float dy2 = y2 - y3;
  69989. const float m1x = (x1 + x2) * 0.5f;
  69990. const float m1y = (y1 + y2) * 0.5f;
  69991. const float m2x = (x2 + x3) * 0.5f;
  69992. const float m2y = (y2 + y3) * 0.5f;
  69993. const float m3x = (m1x + m2x) * 0.5f;
  69994. const float m3y = (m1y + m2y) * 0.5f;
  69995. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  69996. {
  69997. *stackPos++ = y3;
  69998. *stackPos++ = x3;
  69999. *stackPos++ = m2y;
  70000. *stackPos++ = m2x;
  70001. *stackPos++ = Path::quadMarker;
  70002. *stackPos++ = m3y;
  70003. *stackPos++ = m3x;
  70004. *stackPos++ = m1y;
  70005. *stackPos++ = m1x;
  70006. *stackPos++ = Path::quadMarker;
  70007. }
  70008. else
  70009. {
  70010. *stackPos++ = y3;
  70011. *stackPos++ = x3;
  70012. *stackPos++ = Path::lineMarker;
  70013. *stackPos++ = m3y;
  70014. *stackPos++ = m3x;
  70015. *stackPos++ = Path::lineMarker;
  70016. }
  70017. jassert (stackPos < stackBase + stackSize);
  70018. }
  70019. else if (type == Path::cubicMarker)
  70020. {
  70021. const int offset = (int) (stackPos - stackBase);
  70022. if (offset >= stackSize - 16)
  70023. {
  70024. stackSize <<= 1;
  70025. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  70026. stackPos = stackBase + offset;
  70027. }
  70028. const float dx1 = x1 - x2;
  70029. const float dy1 = y1 - y2;
  70030. const float dx2 = x2 - x3;
  70031. const float dy2 = y2 - y3;
  70032. const float dx3 = x3 - x4;
  70033. const float dy3 = y3 - y4;
  70034. const float m1x = (x1 + x2) * 0.5f;
  70035. const float m1y = (y1 + y2) * 0.5f;
  70036. const float m2x = (x3 + x2) * 0.5f;
  70037. const float m2y = (y3 + y2) * 0.5f;
  70038. const float m3x = (x3 + x4) * 0.5f;
  70039. const float m3y = (y3 + y4) * 0.5f;
  70040. const float m4x = (m1x + m2x) * 0.5f;
  70041. const float m4y = (m1y + m2y) * 0.5f;
  70042. const float m5x = (m3x + m2x) * 0.5f;
  70043. const float m5y = (m3y + m2y) * 0.5f;
  70044. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  70045. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  70046. {
  70047. *stackPos++ = y4;
  70048. *stackPos++ = x4;
  70049. *stackPos++ = m3y;
  70050. *stackPos++ = m3x;
  70051. *stackPos++ = m5y;
  70052. *stackPos++ = m5x;
  70053. *stackPos++ = Path::cubicMarker;
  70054. *stackPos++ = (m4y + m5y) * 0.5f;
  70055. *stackPos++ = (m4x + m5x) * 0.5f;
  70056. *stackPos++ = m4y;
  70057. *stackPos++ = m4x;
  70058. *stackPos++ = m1y;
  70059. *stackPos++ = m1x;
  70060. *stackPos++ = Path::cubicMarker;
  70061. }
  70062. else
  70063. {
  70064. *stackPos++ = y4;
  70065. *stackPos++ = x4;
  70066. *stackPos++ = Path::lineMarker;
  70067. *stackPos++ = m5y;
  70068. *stackPos++ = m5x;
  70069. *stackPos++ = Path::lineMarker;
  70070. *stackPos++ = m4y;
  70071. *stackPos++ = m4x;
  70072. *stackPos++ = Path::lineMarker;
  70073. }
  70074. }
  70075. else if (type == Path::closeSubPathMarker)
  70076. {
  70077. if (x2 != subPathCloseX || y2 != subPathCloseY)
  70078. {
  70079. x1 = x2;
  70080. y1 = y2;
  70081. x2 = subPathCloseX;
  70082. y2 = subPathCloseY;
  70083. closesSubPath = true;
  70084. return true;
  70085. }
  70086. }
  70087. else
  70088. {
  70089. jassert (type == Path::moveMarker);
  70090. subPathIndex = -1;
  70091. subPathCloseX = x1 = x2;
  70092. subPathCloseY = y1 = y2;
  70093. }
  70094. }
  70095. }
  70096. END_JUCE_NAMESPACE
  70097. /********* End of inlined file: juce_PathIterator.cpp *********/
  70098. /********* Start of inlined file: juce_PathStrokeType.cpp *********/
  70099. BEGIN_JUCE_NAMESPACE
  70100. PathStrokeType::PathStrokeType (const float strokeThickness,
  70101. const JointStyle jointStyle_,
  70102. const EndCapStyle endStyle_) throw()
  70103. : thickness (strokeThickness),
  70104. jointStyle (jointStyle_),
  70105. endStyle (endStyle_)
  70106. {
  70107. }
  70108. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  70109. : thickness (other.thickness),
  70110. jointStyle (other.jointStyle),
  70111. endStyle (other.endStyle)
  70112. {
  70113. }
  70114. const PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  70115. {
  70116. thickness = other.thickness;
  70117. jointStyle = other.jointStyle;
  70118. endStyle = other.endStyle;
  70119. return *this;
  70120. }
  70121. PathStrokeType::~PathStrokeType() throw()
  70122. {
  70123. }
  70124. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  70125. {
  70126. return thickness == other.thickness
  70127. && jointStyle == other.jointStyle
  70128. && endStyle == other.endStyle;
  70129. }
  70130. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  70131. {
  70132. return ! operator== (other);
  70133. }
  70134. static bool lineIntersection (const float x1, const float y1,
  70135. const float x2, const float y2,
  70136. const float x3, const float y3,
  70137. const float x4, const float y4,
  70138. float& intersectionX,
  70139. float& intersectionY,
  70140. float& distanceBeyondLine1EndSquared) throw()
  70141. {
  70142. if (x2 != x3 || y2 != y3)
  70143. {
  70144. const float dx1 = x2 - x1;
  70145. const float dy1 = y2 - y1;
  70146. const float dx2 = x4 - x3;
  70147. const float dy2 = y4 - y3;
  70148. const float divisor = dx1 * dy2 - dx2 * dy1;
  70149. if (divisor == 0)
  70150. {
  70151. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  70152. {
  70153. if (dy1 == 0 && dy2 != 0)
  70154. {
  70155. const float along = (y1 - y3) / dy2;
  70156. intersectionX = x3 + along * dx2;
  70157. intersectionY = y1;
  70158. distanceBeyondLine1EndSquared = intersectionX - x2;
  70159. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70160. if ((x2 > x1) == (intersectionX < x2))
  70161. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70162. return along >= 0 && along <= 1.0f;
  70163. }
  70164. else if (dy2 == 0 && dy1 != 0)
  70165. {
  70166. const float along = (y3 - y1) / dy1;
  70167. intersectionX = x1 + along * dx1;
  70168. intersectionY = y3;
  70169. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  70170. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70171. if (along < 1.0f)
  70172. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70173. return along >= 0 && along <= 1.0f;
  70174. }
  70175. else if (dx1 == 0 && dx2 != 0)
  70176. {
  70177. const float along = (x1 - x3) / dx2;
  70178. intersectionX = x1;
  70179. intersectionY = y3 + along * dy2;
  70180. distanceBeyondLine1EndSquared = intersectionY - y2;
  70181. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70182. if ((y2 > y1) == (intersectionY < y2))
  70183. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70184. return along >= 0 && along <= 1.0f;
  70185. }
  70186. else if (dx2 == 0 && dx1 != 0)
  70187. {
  70188. const float along = (x3 - x1) / dx1;
  70189. intersectionX = x3;
  70190. intersectionY = y1 + along * dy1;
  70191. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  70192. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70193. if (along < 1.0f)
  70194. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70195. return along >= 0 && along <= 1.0f;
  70196. }
  70197. }
  70198. intersectionX = 0.5f * (x2 + x3);
  70199. intersectionY = 0.5f * (y2 + y3);
  70200. distanceBeyondLine1EndSquared = 0.0f;
  70201. return false;
  70202. }
  70203. else
  70204. {
  70205. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  70206. intersectionX = x1 + along1 * dx1;
  70207. intersectionY = y1 + along1 * dy1;
  70208. if (along1 >= 0 && along1 <= 1.0f)
  70209. {
  70210. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  70211. if (along2 >= 0 && along2 <= divisor)
  70212. {
  70213. distanceBeyondLine1EndSquared = 0.0f;
  70214. return true;
  70215. }
  70216. }
  70217. distanceBeyondLine1EndSquared = along1 - 1.0f;
  70218. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70219. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  70220. if (along1 < 1.0f)
  70221. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70222. return false;
  70223. }
  70224. }
  70225. intersectionX = x2;
  70226. intersectionY = y2;
  70227. distanceBeyondLine1EndSquared = 0.0f;
  70228. return true;
  70229. }
  70230. // part of stroke drawing stuff
  70231. static void addEdgeAndJoint (Path& destPath,
  70232. const PathStrokeType::JointStyle style,
  70233. const float maxMiterExtensionSquared, const float width,
  70234. const float x1, const float y1,
  70235. const float x2, const float y2,
  70236. const float x3, const float y3,
  70237. const float x4, const float y4,
  70238. const float midX, const float midY) throw()
  70239. {
  70240. if (style == PathStrokeType::beveled
  70241. || (x3 == x4 && y3 == y4)
  70242. || (x1 == x2 && y1 == y2))
  70243. {
  70244. destPath.lineTo (x2, y2);
  70245. destPath.lineTo (x3, y3);
  70246. }
  70247. else
  70248. {
  70249. float jx, jy, distanceBeyondLine1EndSquared;
  70250. // if they intersect, use this point..
  70251. if (lineIntersection (x1, y1, x2, y2,
  70252. x3, y3, x4, y4,
  70253. jx, jy, distanceBeyondLine1EndSquared))
  70254. {
  70255. destPath.lineTo (jx, jy);
  70256. }
  70257. else
  70258. {
  70259. if (style == PathStrokeType::mitered)
  70260. {
  70261. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  70262. && distanceBeyondLine1EndSquared > 0.0f)
  70263. {
  70264. destPath.lineTo (jx, jy);
  70265. }
  70266. else
  70267. {
  70268. // the end sticks out too far, so just use a blunt joint
  70269. destPath.lineTo (x2, y2);
  70270. destPath.lineTo (x3, y3);
  70271. }
  70272. }
  70273. else
  70274. {
  70275. // curved joints
  70276. float angle = atan2f (x2 - midX, y2 - midY);
  70277. float angle2 = atan2f (x3 - midX, y3 - midY);
  70278. while (angle < angle2 - 0.01f)
  70279. angle2 -= float_Pi * 2.0f;
  70280. destPath.lineTo (x2, y2);
  70281. while (angle > angle2)
  70282. {
  70283. destPath.lineTo (midX + width * sinf (angle),
  70284. midY + width * cosf (angle));
  70285. angle -= 0.1f;
  70286. }
  70287. destPath.lineTo (x3, y3);
  70288. }
  70289. }
  70290. }
  70291. }
  70292. static inline void addLineEnd (Path& destPath,
  70293. const PathStrokeType::EndCapStyle style,
  70294. const float x1, const float y1,
  70295. const float x2, const float y2,
  70296. const float width) throw()
  70297. {
  70298. if (style == PathStrokeType::butt)
  70299. {
  70300. destPath.lineTo (x2, y2);
  70301. }
  70302. else
  70303. {
  70304. float offx1, offy1, offx2, offy2;
  70305. float dx = x2 - x1;
  70306. float dy = y2 - y1;
  70307. const float len = juce_hypotf (dx, dy);
  70308. if (len == 0)
  70309. {
  70310. offx1 = offx2 = x1;
  70311. offy1 = offy2 = y1;
  70312. }
  70313. else
  70314. {
  70315. const float offset = width / len;
  70316. dx *= offset;
  70317. dy *= offset;
  70318. offx1 = x1 + dy;
  70319. offy1 = y1 - dx;
  70320. offx2 = x2 + dy;
  70321. offy2 = y2 - dx;
  70322. }
  70323. if (style == PathStrokeType::square)
  70324. {
  70325. // sqaure ends
  70326. destPath.lineTo (offx1, offy1);
  70327. destPath.lineTo (offx2, offy2);
  70328. destPath.lineTo (x2, y2);
  70329. }
  70330. else
  70331. {
  70332. // rounded ends
  70333. const float midx = (offx1 + offx2) * 0.5f;
  70334. const float midy = (offy1 + offy2) * 0.5f;
  70335. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  70336. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  70337. midx, midy);
  70338. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  70339. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  70340. x2, y2);
  70341. }
  70342. }
  70343. }
  70344. struct LineSection
  70345. {
  70346. LineSection() throw() {}
  70347. LineSection (int) throw() {}
  70348. float x1, y1, x2, y2; // original line
  70349. float lx1, ly1, lx2, ly2; // the left-hand stroke
  70350. float rx1, ry1, rx2, ry2; // the right-hand stroke
  70351. };
  70352. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  70353. const bool isClosed,
  70354. const float width, const float maxMiterExtensionSquared,
  70355. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle) throw()
  70356. {
  70357. jassert (subPath.size() > 0);
  70358. const LineSection& firstLine = subPath.getReference (0);
  70359. float lastX1 = firstLine.lx1;
  70360. float lastY1 = firstLine.ly1;
  70361. float lastX2 = firstLine.lx2;
  70362. float lastY2 = firstLine.ly2;
  70363. if (isClosed)
  70364. {
  70365. destPath.startNewSubPath (lastX1, lastY1);
  70366. }
  70367. else
  70368. {
  70369. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  70370. addLineEnd (destPath, endStyle,
  70371. firstLine.rx2, firstLine.ry2,
  70372. lastX1, lastY1,
  70373. width);
  70374. }
  70375. int i;
  70376. for (i = 1; i < subPath.size(); ++i)
  70377. {
  70378. const LineSection& l = subPath.getReference (i);
  70379. addEdgeAndJoint (destPath, jointStyle,
  70380. maxMiterExtensionSquared, width,
  70381. lastX1, lastY1, lastX2, lastY2,
  70382. l.lx1, l.ly1, l.lx2, l.ly2,
  70383. l.x1, l.y1);
  70384. lastX1 = l.lx1;
  70385. lastY1 = l.ly1;
  70386. lastX2 = l.lx2;
  70387. lastY2 = l.ly2;
  70388. }
  70389. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  70390. if (isClosed)
  70391. {
  70392. const LineSection& l = subPath.getReference (0);
  70393. addEdgeAndJoint (destPath, jointStyle,
  70394. maxMiterExtensionSquared, width,
  70395. lastX1, lastY1, lastX2, lastY2,
  70396. l.lx1, l.ly1, l.lx2, l.ly2,
  70397. l.x1, l.y1);
  70398. destPath.closeSubPath();
  70399. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  70400. }
  70401. else
  70402. {
  70403. destPath.lineTo (lastX2, lastY2);
  70404. addLineEnd (destPath, endStyle,
  70405. lastX2, lastY2,
  70406. lastLine.rx1, lastLine.ry1,
  70407. width);
  70408. }
  70409. lastX1 = lastLine.rx1;
  70410. lastY1 = lastLine.ry1;
  70411. lastX2 = lastLine.rx2;
  70412. lastY2 = lastLine.ry2;
  70413. for (i = subPath.size() - 1; --i >= 0;)
  70414. {
  70415. const LineSection& l = subPath.getReference (i);
  70416. addEdgeAndJoint (destPath, jointStyle,
  70417. maxMiterExtensionSquared, width,
  70418. lastX1, lastY1, lastX2, lastY2,
  70419. l.rx1, l.ry1, l.rx2, l.ry2,
  70420. l.x2, l.y2);
  70421. lastX1 = l.rx1;
  70422. lastY1 = l.ry1;
  70423. lastX2 = l.rx2;
  70424. lastY2 = l.ry2;
  70425. }
  70426. if (isClosed)
  70427. {
  70428. addEdgeAndJoint (destPath, jointStyle,
  70429. maxMiterExtensionSquared, width,
  70430. lastX1, lastY1, lastX2, lastY2,
  70431. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  70432. lastLine.x2, lastLine.y2);
  70433. }
  70434. else
  70435. {
  70436. // do the last line
  70437. destPath.lineTo (lastX2, lastY2);
  70438. }
  70439. destPath.closeSubPath();
  70440. }
  70441. void PathStrokeType::createStrokedPath (Path& destPath,
  70442. const Path& source,
  70443. const AffineTransform& transform,
  70444. const float extraAccuracy) const throw()
  70445. {
  70446. if (thickness <= 0)
  70447. {
  70448. destPath.clear();
  70449. return;
  70450. }
  70451. const Path* sourcePath = &source;
  70452. Path temp;
  70453. if (sourcePath == &destPath)
  70454. {
  70455. destPath.swapWithPath (temp);
  70456. sourcePath = &temp;
  70457. }
  70458. else
  70459. {
  70460. destPath.clear();
  70461. }
  70462. destPath.setUsingNonZeroWinding (true);
  70463. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  70464. const float width = 0.5f * thickness;
  70465. // Iterate the path, creating a list of the
  70466. // left/right-hand lines along either side of it...
  70467. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  70468. Array <LineSection> subPath;
  70469. LineSection l;
  70470. l.x1 = 0;
  70471. l.y1 = 0;
  70472. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  70473. while (it.next())
  70474. {
  70475. if (it.subPathIndex == 0)
  70476. {
  70477. if (subPath.size() > 0)
  70478. {
  70479. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  70480. subPath.clearQuick();
  70481. }
  70482. l.x1 = it.x1;
  70483. l.y1 = it.y1;
  70484. }
  70485. l.x2 = it.x2;
  70486. l.y2 = it.y2;
  70487. float dx = l.x2 - l.x1;
  70488. float dy = l.y2 - l.y1;
  70489. const float hypotSquared = dx*dx + dy*dy;
  70490. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  70491. {
  70492. const float len = sqrtf (hypotSquared);
  70493. if (len == 0)
  70494. {
  70495. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  70496. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  70497. }
  70498. else
  70499. {
  70500. const float offset = width / len;
  70501. dx *= offset;
  70502. dy *= offset;
  70503. l.rx2 = l.x1 - dy;
  70504. l.ry2 = l.y1 + dx;
  70505. l.lx1 = l.x1 + dy;
  70506. l.ly1 = l.y1 - dx;
  70507. l.lx2 = l.x2 + dy;
  70508. l.ly2 = l.y2 - dx;
  70509. l.rx1 = l.x2 - dy;
  70510. l.ry1 = l.y2 + dx;
  70511. }
  70512. subPath.add (l);
  70513. if (it.closesSubPath)
  70514. {
  70515. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  70516. subPath.clearQuick();
  70517. }
  70518. else
  70519. {
  70520. l.x1 = it.x2;
  70521. l.y1 = it.y2;
  70522. }
  70523. }
  70524. }
  70525. if (subPath.size() > 0)
  70526. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  70527. }
  70528. void PathStrokeType::createDashedStroke (Path& destPath,
  70529. const Path& sourcePath,
  70530. const float* dashLengths,
  70531. int numDashLengths,
  70532. const AffineTransform& transform,
  70533. const float extraAccuracy) const throw()
  70534. {
  70535. if (thickness <= 0)
  70536. return;
  70537. // this should really be an even number..
  70538. jassert ((numDashLengths & 1) == 0);
  70539. Path newDestPath;
  70540. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  70541. bool first = true;
  70542. int dashNum = 0;
  70543. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  70544. float dx = 0.0f, dy = 0.0f;
  70545. for (;;)
  70546. {
  70547. const bool isSolid = ((dashNum & 1) == 0);
  70548. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  70549. jassert (dashLen > 0); // must be a positive increment!
  70550. if (dashLen <= 0)
  70551. break;
  70552. pos += dashLen;
  70553. while (pos > lineEndPos)
  70554. {
  70555. if (! it.next())
  70556. {
  70557. if (isSolid && ! first)
  70558. newDestPath.lineTo (it.x2, it.y2);
  70559. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  70560. return;
  70561. }
  70562. if (isSolid && ! first)
  70563. newDestPath.lineTo (it.x1, it.y1);
  70564. else
  70565. newDestPath.startNewSubPath (it.x1, it.y1);
  70566. dx = it.x2 - it.x1;
  70567. dy = it.y2 - it.y1;
  70568. lineLen = juce_hypotf (dx, dy);
  70569. lineEndPos += lineLen;
  70570. first = it.closesSubPath;
  70571. }
  70572. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  70573. if (isSolid)
  70574. newDestPath.lineTo (it.x1 + dx * alpha,
  70575. it.y1 + dy * alpha);
  70576. else
  70577. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  70578. it.y1 + dy * alpha);
  70579. }
  70580. }
  70581. END_JUCE_NAMESPACE
  70582. /********* End of inlined file: juce_PathStrokeType.cpp *********/
  70583. /********* Start of inlined file: juce_Point.cpp *********/
  70584. BEGIN_JUCE_NAMESPACE
  70585. Point::Point() throw()
  70586. : x (0.0f),
  70587. y (0.0f)
  70588. {
  70589. }
  70590. Point::Point (const Point& other) throw()
  70591. : x (other.x),
  70592. y (other.y)
  70593. {
  70594. }
  70595. const Point& Point::operator= (const Point& other) throw()
  70596. {
  70597. x = other.x;
  70598. y = other.y;
  70599. return *this;
  70600. }
  70601. Point::Point (const float x_,
  70602. const float y_) throw()
  70603. : x (x_),
  70604. y (y_)
  70605. {
  70606. }
  70607. Point::~Point() throw()
  70608. {
  70609. }
  70610. void Point::setXY (const float x_,
  70611. const float y_) throw()
  70612. {
  70613. x = x_;
  70614. y = y_;
  70615. }
  70616. void Point::applyTransform (const AffineTransform& transform) throw()
  70617. {
  70618. transform.transformPoint (x, y);
  70619. }
  70620. END_JUCE_NAMESPACE
  70621. /********* End of inlined file: juce_Point.cpp *********/
  70622. /********* Start of inlined file: juce_PositionedRectangle.cpp *********/
  70623. BEGIN_JUCE_NAMESPACE
  70624. PositionedRectangle::PositionedRectangle() throw()
  70625. : x (0.0),
  70626. y (0.0),
  70627. w (0.0),
  70628. h (0.0),
  70629. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  70630. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  70631. wMode (absoluteSize),
  70632. hMode (absoluteSize)
  70633. {
  70634. }
  70635. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  70636. : x (other.x),
  70637. y (other.y),
  70638. w (other.w),
  70639. h (other.h),
  70640. xMode (other.xMode),
  70641. yMode (other.yMode),
  70642. wMode (other.wMode),
  70643. hMode (other.hMode)
  70644. {
  70645. }
  70646. const PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  70647. {
  70648. if (this != &other)
  70649. {
  70650. x = other.x;
  70651. y = other.y;
  70652. w = other.w;
  70653. h = other.h;
  70654. xMode = other.xMode;
  70655. yMode = other.yMode;
  70656. wMode = other.wMode;
  70657. hMode = other.hMode;
  70658. }
  70659. return *this;
  70660. }
  70661. PositionedRectangle::~PositionedRectangle() throw()
  70662. {
  70663. }
  70664. const bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  70665. {
  70666. return x == other.x
  70667. && y == other.y
  70668. && w == other.w
  70669. && h == other.h
  70670. && xMode == other.xMode
  70671. && yMode == other.yMode
  70672. && wMode == other.wMode
  70673. && hMode == other.hMode;
  70674. }
  70675. const bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  70676. {
  70677. return ! operator== (other);
  70678. }
  70679. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  70680. {
  70681. StringArray tokens;
  70682. tokens.addTokens (stringVersion, false);
  70683. decodePosString (tokens [0], xMode, x);
  70684. decodePosString (tokens [1], yMode, y);
  70685. decodeSizeString (tokens [2], wMode, w);
  70686. decodeSizeString (tokens [3], hMode, h);
  70687. }
  70688. const String PositionedRectangle::toString() const throw()
  70689. {
  70690. String s;
  70691. s.preallocateStorage (12);
  70692. addPosDescription (s, xMode, x);
  70693. s << T(' ');
  70694. addPosDescription (s, yMode, y);
  70695. s << T(' ');
  70696. addSizeDescription (s, wMode, w);
  70697. s << T(' ');
  70698. addSizeDescription (s, hMode, h);
  70699. return s;
  70700. }
  70701. const Rectangle PositionedRectangle::getRectangle (const Rectangle& target) const throw()
  70702. {
  70703. jassert (! target.isEmpty());
  70704. double x_, y_, w_, h_;
  70705. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  70706. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  70707. return Rectangle (roundDoubleToInt (x_), roundDoubleToInt (y_),
  70708. roundDoubleToInt (w_), roundDoubleToInt (h_));
  70709. }
  70710. void PositionedRectangle::getRectangleDouble (const Rectangle& target,
  70711. double& x_, double& y_,
  70712. double& w_, double& h_) const throw()
  70713. {
  70714. jassert (! target.isEmpty());
  70715. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  70716. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  70717. }
  70718. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  70719. {
  70720. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  70721. }
  70722. void PositionedRectangle::updateFrom (const Rectangle& rectangle,
  70723. const Rectangle& target) throw()
  70724. {
  70725. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  70726. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  70727. }
  70728. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  70729. const double newW, const double newH,
  70730. const Rectangle& target) throw()
  70731. {
  70732. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  70733. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  70734. }
  70735. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  70736. {
  70737. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  70738. updateFrom (comp.getBounds(), Rectangle());
  70739. else
  70740. updateFrom (comp.getBounds(), Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  70741. }
  70742. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  70743. {
  70744. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  70745. }
  70746. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  70747. {
  70748. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  70749. | absoluteFromParentBottomRight
  70750. | absoluteFromParentCentre
  70751. | proportionOfParentSize));
  70752. }
  70753. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  70754. {
  70755. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  70756. }
  70757. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  70758. {
  70759. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  70760. | absoluteFromParentBottomRight
  70761. | absoluteFromParentCentre
  70762. | proportionOfParentSize));
  70763. }
  70764. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  70765. {
  70766. return (SizeMode) wMode;
  70767. }
  70768. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  70769. {
  70770. return (SizeMode) hMode;
  70771. }
  70772. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  70773. const PositionMode xMode_,
  70774. const AnchorPoint yAnchor,
  70775. const PositionMode yMode_,
  70776. const SizeMode widthMode,
  70777. const SizeMode heightMode,
  70778. const Rectangle& target) throw()
  70779. {
  70780. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  70781. {
  70782. double tx, tw;
  70783. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  70784. xMode = (uint8) (xAnchor | xMode_);
  70785. wMode = (uint8) widthMode;
  70786. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  70787. }
  70788. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  70789. {
  70790. double ty, th;
  70791. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  70792. yMode = (uint8) (yAnchor | yMode_);
  70793. hMode = (uint8) heightMode;
  70794. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  70795. }
  70796. }
  70797. bool PositionedRectangle::isPositionAbsolute() const throw()
  70798. {
  70799. return xMode == absoluteFromParentTopLeft
  70800. && yMode == absoluteFromParentTopLeft
  70801. && wMode == absoluteSize
  70802. && hMode == absoluteSize;
  70803. }
  70804. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  70805. {
  70806. if ((mode & proportionOfParentSize) != 0)
  70807. {
  70808. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  70809. }
  70810. else
  70811. {
  70812. s << (roundDoubleToInt (value * 100.0) / 100.0);
  70813. if ((mode & absoluteFromParentBottomRight) != 0)
  70814. s << T('R');
  70815. else if ((mode & absoluteFromParentCentre) != 0)
  70816. s << T('C');
  70817. }
  70818. if ((mode & anchorAtRightOrBottom) != 0)
  70819. s << T('r');
  70820. else if ((mode & anchorAtCentre) != 0)
  70821. s << T('c');
  70822. }
  70823. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  70824. {
  70825. if (mode == proportionalSize)
  70826. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  70827. else if (mode == parentSizeMinusAbsolute)
  70828. s << (roundDoubleToInt (value * 100.0) / 100.0) << T('M');
  70829. else
  70830. s << (roundDoubleToInt (value * 100.0) / 100.0);
  70831. }
  70832. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  70833. {
  70834. if (s.containsChar (T('r')))
  70835. mode = anchorAtRightOrBottom;
  70836. else if (s.containsChar (T('c')))
  70837. mode = anchorAtCentre;
  70838. else
  70839. mode = anchorAtLeftOrTop;
  70840. if (s.containsChar (T('%')))
  70841. {
  70842. mode |= proportionOfParentSize;
  70843. value = s.removeCharacters (T("%rcRC")).getDoubleValue() / 100.0;
  70844. }
  70845. else
  70846. {
  70847. if (s.containsChar (T('R')))
  70848. mode |= absoluteFromParentBottomRight;
  70849. else if (s.containsChar (T('C')))
  70850. mode |= absoluteFromParentCentre;
  70851. else
  70852. mode |= absoluteFromParentTopLeft;
  70853. value = s.removeCharacters (T("rcRC")).getDoubleValue();
  70854. }
  70855. }
  70856. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  70857. {
  70858. if (s.containsChar (T('%')))
  70859. {
  70860. mode = proportionalSize;
  70861. value = s.upToFirstOccurrenceOf (T("%"), false, false).getDoubleValue() / 100.0;
  70862. }
  70863. else if (s.containsChar (T('M')))
  70864. {
  70865. mode = parentSizeMinusAbsolute;
  70866. value = s.getDoubleValue();
  70867. }
  70868. else
  70869. {
  70870. mode = absoluteSize;
  70871. value = s.getDoubleValue();
  70872. }
  70873. }
  70874. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  70875. const double x_, const double w_,
  70876. const uint8 xMode_, const uint8 wMode_,
  70877. const int parentPos,
  70878. const int parentSize) const throw()
  70879. {
  70880. if (wMode_ == proportionalSize)
  70881. wOut = roundDoubleToInt (w_ * parentSize);
  70882. else if (wMode_ == parentSizeMinusAbsolute)
  70883. wOut = jmax (0, parentSize - roundDoubleToInt (w_));
  70884. else
  70885. wOut = roundDoubleToInt (w_);
  70886. if ((xMode_ & proportionOfParentSize) != 0)
  70887. xOut = parentPos + x_ * parentSize;
  70888. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  70889. xOut = (parentPos + parentSize) - x_;
  70890. else if ((xMode_ & absoluteFromParentCentre) != 0)
  70891. xOut = x_ + (parentPos + parentSize / 2);
  70892. else
  70893. xOut = x_ + parentPos;
  70894. if ((xMode_ & anchorAtRightOrBottom) != 0)
  70895. xOut -= wOut;
  70896. else if ((xMode_ & anchorAtCentre) != 0)
  70897. xOut -= wOut / 2;
  70898. }
  70899. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  70900. double x_, const double w_,
  70901. const uint8 xMode_, const uint8 wMode_,
  70902. const int parentPos,
  70903. const int parentSize) const throw()
  70904. {
  70905. if (wMode_ == proportionalSize)
  70906. {
  70907. if (parentSize > 0)
  70908. wOut = w_ / parentSize;
  70909. }
  70910. else if (wMode_ == parentSizeMinusAbsolute)
  70911. wOut = parentSize - w_;
  70912. else
  70913. wOut = w_;
  70914. if ((xMode_ & anchorAtRightOrBottom) != 0)
  70915. x_ += w_;
  70916. else if ((xMode_ & anchorAtCentre) != 0)
  70917. x_ += w_ / 2;
  70918. if ((xMode_ & proportionOfParentSize) != 0)
  70919. {
  70920. if (parentSize > 0)
  70921. xOut = (x_ - parentPos) / parentSize;
  70922. }
  70923. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  70924. xOut = (parentPos + parentSize) - x_;
  70925. else if ((xMode_ & absoluteFromParentCentre) != 0)
  70926. xOut = x_ - (parentPos + parentSize / 2);
  70927. else
  70928. xOut = x_ - parentPos;
  70929. }
  70930. END_JUCE_NAMESPACE
  70931. /********* End of inlined file: juce_PositionedRectangle.cpp *********/
  70932. /********* Start of inlined file: juce_Rectangle.cpp *********/
  70933. BEGIN_JUCE_NAMESPACE
  70934. Rectangle::Rectangle() throw()
  70935. : x (0),
  70936. y (0),
  70937. w (0),
  70938. h (0)
  70939. {
  70940. }
  70941. Rectangle::Rectangle (const int x_, const int y_,
  70942. const int w_, const int h_) throw()
  70943. : x (x_),
  70944. y (y_),
  70945. w (w_),
  70946. h (h_)
  70947. {
  70948. }
  70949. Rectangle::Rectangle (const int w_, const int h_) throw()
  70950. : x (0),
  70951. y (0),
  70952. w (w_),
  70953. h (h_)
  70954. {
  70955. }
  70956. Rectangle::Rectangle (const Rectangle& other) throw()
  70957. : x (other.x),
  70958. y (other.y),
  70959. w (other.w),
  70960. h (other.h)
  70961. {
  70962. }
  70963. Rectangle::~Rectangle() throw()
  70964. {
  70965. }
  70966. bool Rectangle::isEmpty() const throw()
  70967. {
  70968. return w <= 0 || h <= 0;
  70969. }
  70970. void Rectangle::setBounds (const int x_,
  70971. const int y_,
  70972. const int w_,
  70973. const int h_) throw()
  70974. {
  70975. x = x_;
  70976. y = y_;
  70977. w = w_;
  70978. h = h_;
  70979. }
  70980. void Rectangle::setPosition (const int x_,
  70981. const int y_) throw()
  70982. {
  70983. x = x_;
  70984. y = y_;
  70985. }
  70986. void Rectangle::setSize (const int w_,
  70987. const int h_) throw()
  70988. {
  70989. w = w_;
  70990. h = h_;
  70991. }
  70992. void Rectangle::setLeft (const int newLeft) throw()
  70993. {
  70994. w = jmax (0, x + w - newLeft);
  70995. x = newLeft;
  70996. }
  70997. void Rectangle::setTop (const int newTop) throw()
  70998. {
  70999. h = jmax (0, y + h - newTop);
  71000. y = newTop;
  71001. }
  71002. void Rectangle::setRight (const int newRight) throw()
  71003. {
  71004. x = jmin (x, newRight);
  71005. w = newRight - x;
  71006. }
  71007. void Rectangle::setBottom (const int newBottom) throw()
  71008. {
  71009. y = jmin (y, newBottom);
  71010. h = newBottom - y;
  71011. }
  71012. void Rectangle::translate (const int dx,
  71013. const int dy) throw()
  71014. {
  71015. x += dx;
  71016. y += dy;
  71017. }
  71018. const Rectangle Rectangle::translated (const int dx,
  71019. const int dy) const throw()
  71020. {
  71021. return Rectangle (x + dx, y + dy, w, h);
  71022. }
  71023. void Rectangle::expand (const int deltaX,
  71024. const int deltaY) throw()
  71025. {
  71026. const int nw = jmax (0, w + deltaX + deltaX);
  71027. const int nh = jmax (0, h + deltaY + deltaY);
  71028. setBounds (x - deltaX,
  71029. y - deltaY,
  71030. nw, nh);
  71031. }
  71032. const Rectangle Rectangle::expanded (const int deltaX,
  71033. const int deltaY) const throw()
  71034. {
  71035. const int nw = jmax (0, w + deltaX + deltaX);
  71036. const int nh = jmax (0, h + deltaY + deltaY);
  71037. return Rectangle (x - deltaX,
  71038. y - deltaY,
  71039. nw, nh);
  71040. }
  71041. void Rectangle::reduce (const int deltaX,
  71042. const int deltaY) throw()
  71043. {
  71044. expand (-deltaX, -deltaY);
  71045. }
  71046. const Rectangle Rectangle::reduced (const int deltaX,
  71047. const int deltaY) const throw()
  71048. {
  71049. return expanded (-deltaX, -deltaY);
  71050. }
  71051. bool Rectangle::operator== (const Rectangle& other) const throw()
  71052. {
  71053. return x == other.x
  71054. && y == other.y
  71055. && w == other.w
  71056. && h == other.h;
  71057. }
  71058. bool Rectangle::operator!= (const Rectangle& other) const throw()
  71059. {
  71060. return x != other.x
  71061. || y != other.y
  71062. || w != other.w
  71063. || h != other.h;
  71064. }
  71065. bool Rectangle::contains (const int px,
  71066. const int py) const throw()
  71067. {
  71068. return px >= x
  71069. && py >= y
  71070. && px < x + w
  71071. && py < y + h;
  71072. }
  71073. bool Rectangle::contains (const Rectangle& other) const throw()
  71074. {
  71075. return x <= other.x
  71076. && y <= other.y
  71077. && x + w >= other.x + other.w
  71078. && y + h >= other.y + other.h;
  71079. }
  71080. bool Rectangle::intersects (const Rectangle& other) const throw()
  71081. {
  71082. return x + w > other.x
  71083. && y + h > other.y
  71084. && x < other.x + other.w
  71085. && y < other.y + other.h
  71086. && w > 0
  71087. && h > 0;
  71088. }
  71089. const Rectangle Rectangle::getIntersection (const Rectangle& other) const throw()
  71090. {
  71091. const int nx = jmax (x, other.x);
  71092. const int ny = jmax (y, other.y);
  71093. const int nw = jmin (x + w, other.x + other.w) - nx;
  71094. const int nh = jmin (y + h, other.y + other.h) - ny;
  71095. if (nw >= 0 && nh >= 0)
  71096. return Rectangle (nx, ny, nw, nh);
  71097. else
  71098. return Rectangle();
  71099. }
  71100. bool Rectangle::intersectRectangle (int& x1, int& y1, int& w1, int& h1) const throw()
  71101. {
  71102. const int maxX = jmax (x1, x);
  71103. w1 = jmin (x1 + w1, x + w) - maxX;
  71104. if (w1 > 0)
  71105. {
  71106. const int maxY = jmax (y1, y);
  71107. h1 = jmin (y1 + h1, y + h) - maxY;
  71108. if (h1 > 0)
  71109. {
  71110. x1 = maxX;
  71111. y1 = maxY;
  71112. return true;
  71113. }
  71114. }
  71115. return false;
  71116. }
  71117. bool Rectangle::intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  71118. int x2, int y2, int w2, int h2) throw()
  71119. {
  71120. const int x = jmax (x1, x2);
  71121. w1 = jmin (x1 + w1, x2 + w2) - x;
  71122. if (w1 > 0)
  71123. {
  71124. const int y = jmax (y1, y2);
  71125. h1 = jmin (y1 + h1, y2 + h2) - y;
  71126. if (h1 > 0)
  71127. {
  71128. x1 = x;
  71129. y1 = y;
  71130. return true;
  71131. }
  71132. }
  71133. return false;
  71134. }
  71135. const Rectangle Rectangle::getUnion (const Rectangle& other) const throw()
  71136. {
  71137. const int newX = jmin (x, other.x);
  71138. const int newY = jmin (y, other.y);
  71139. return Rectangle (newX, newY,
  71140. jmax (x + w, other.x + other.w) - newX,
  71141. jmax (y + h, other.y + other.h) - newY);
  71142. }
  71143. bool Rectangle::enlargeIfAdjacent (const Rectangle& other) throw()
  71144. {
  71145. if (x == other.x && getRight() == other.getRight()
  71146. && (other.getBottom() >= y && other.y <= getBottom()))
  71147. {
  71148. const int newY = jmin (y, other.y);
  71149. h = jmax (getBottom(), other.getBottom()) - newY;
  71150. y = newY;
  71151. return true;
  71152. }
  71153. else if (y == other.y && getBottom() == other.getBottom()
  71154. && (other.getRight() >= x && other.x <= getRight()))
  71155. {
  71156. const int newX = jmin (x, other.x);
  71157. w = jmax (getRight(), other.getRight()) - newX;
  71158. x = newX;
  71159. return true;
  71160. }
  71161. return false;
  71162. }
  71163. bool Rectangle::reduceIfPartlyContainedIn (const Rectangle& other) throw()
  71164. {
  71165. int inside = 0;
  71166. const int otherR = other.getRight();
  71167. if (x >= other.x && x < otherR)
  71168. inside = 1;
  71169. const int otherB = other.getBottom();
  71170. if (y >= other.y && y < otherB)
  71171. inside |= 2;
  71172. const int r = x + w;
  71173. if (r >= other.x && r < otherR)
  71174. inside |= 4;
  71175. const int b = y + h;
  71176. if (b >= other.y && b < otherB)
  71177. inside |= 8;
  71178. switch (inside)
  71179. {
  71180. case 1 + 2 + 8:
  71181. w = r - otherR;
  71182. x = otherR;
  71183. return true;
  71184. case 1 + 2 + 4:
  71185. h = b - otherB;
  71186. y = otherB;
  71187. return true;
  71188. case 2 + 4 + 8:
  71189. w = other.x - x;
  71190. return true;
  71191. case 1 + 4 + 8:
  71192. h = other.y - y;
  71193. return true;
  71194. }
  71195. return false;
  71196. }
  71197. const String Rectangle::toString() const throw()
  71198. {
  71199. String s;
  71200. s.preallocateStorage (16);
  71201. s << x << T(' ')
  71202. << y << T(' ')
  71203. << w << T(' ')
  71204. << h;
  71205. return s;
  71206. }
  71207. const Rectangle Rectangle::fromString (const String& stringVersion)
  71208. {
  71209. StringArray toks;
  71210. toks.addTokens (stringVersion.trim(), T(",; \t\r\n"), 0);
  71211. return Rectangle (toks[0].trim().getIntValue(),
  71212. toks[1].trim().getIntValue(),
  71213. toks[2].trim().getIntValue(),
  71214. toks[3].trim().getIntValue());
  71215. }
  71216. END_JUCE_NAMESPACE
  71217. /********* End of inlined file: juce_Rectangle.cpp *********/
  71218. /********* Start of inlined file: juce_RectangleList.cpp *********/
  71219. BEGIN_JUCE_NAMESPACE
  71220. RectangleList::RectangleList() throw()
  71221. {
  71222. }
  71223. RectangleList::RectangleList (const Rectangle& rect) throw()
  71224. {
  71225. if (! rect.isEmpty())
  71226. rects.add (rect);
  71227. }
  71228. RectangleList::RectangleList (const RectangleList& other) throw()
  71229. : rects (other.rects)
  71230. {
  71231. }
  71232. const RectangleList& RectangleList::operator= (const RectangleList& other) throw()
  71233. {
  71234. if (this != &other)
  71235. rects = other.rects;
  71236. return *this;
  71237. }
  71238. RectangleList::~RectangleList() throw()
  71239. {
  71240. }
  71241. void RectangleList::clear() throw()
  71242. {
  71243. rects.clearQuick();
  71244. }
  71245. const Rectangle RectangleList::getRectangle (const int index) const throw()
  71246. {
  71247. if (((unsigned int) index) < (unsigned int) rects.size())
  71248. return rects.getReference (index);
  71249. return Rectangle();
  71250. }
  71251. bool RectangleList::isEmpty() const throw()
  71252. {
  71253. return rects.size() == 0;
  71254. }
  71255. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  71256. : current (0),
  71257. owner (list),
  71258. index (list.rects.size())
  71259. {
  71260. }
  71261. RectangleList::Iterator::~Iterator() throw()
  71262. {
  71263. }
  71264. bool RectangleList::Iterator::next() throw()
  71265. {
  71266. if (--index >= 0)
  71267. {
  71268. current = & (owner.rects.getReference (index));
  71269. return true;
  71270. }
  71271. return false;
  71272. }
  71273. void RectangleList::add (const Rectangle& rect) throw()
  71274. {
  71275. if (! rect.isEmpty())
  71276. {
  71277. if (rects.size() == 0)
  71278. {
  71279. rects.add (rect);
  71280. }
  71281. else
  71282. {
  71283. bool anyOverlaps = false;
  71284. int i;
  71285. for (i = rects.size(); --i >= 0;)
  71286. {
  71287. Rectangle& ourRect = rects.getReference (i);
  71288. if (rect.intersects (ourRect))
  71289. {
  71290. if (rect.contains (ourRect))
  71291. rects.remove (i);
  71292. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  71293. anyOverlaps = true;
  71294. }
  71295. }
  71296. if (anyOverlaps && rects.size() > 0)
  71297. {
  71298. RectangleList r (rect);
  71299. for (i = rects.size(); --i >= 0;)
  71300. {
  71301. const Rectangle& ourRect = rects.getReference (i);
  71302. if (rect.intersects (ourRect))
  71303. {
  71304. r.subtract (ourRect);
  71305. if (r.rects.size() == 0)
  71306. return;
  71307. }
  71308. }
  71309. for (i = r.getNumRectangles(); --i >= 0;)
  71310. rects.add (r.rects.getReference (i));
  71311. }
  71312. else
  71313. {
  71314. rects.add (rect);
  71315. }
  71316. }
  71317. }
  71318. }
  71319. void RectangleList::addWithoutMerging (const Rectangle& rect) throw()
  71320. {
  71321. rects.add (rect);
  71322. }
  71323. void RectangleList::add (const int x, const int y, const int w, const int h) throw()
  71324. {
  71325. if (rects.size() == 0)
  71326. {
  71327. if (w > 0 && h > 0)
  71328. rects.add (Rectangle (x, y, w, h));
  71329. }
  71330. else
  71331. {
  71332. add (Rectangle (x, y, w, h));
  71333. }
  71334. }
  71335. void RectangleList::add (const RectangleList& other) throw()
  71336. {
  71337. for (int i = 0; i < other.rects.size(); ++i)
  71338. add (other.rects.getReference (i));
  71339. }
  71340. void RectangleList::subtract (const Rectangle& rect) throw()
  71341. {
  71342. const int originalNumRects = rects.size();
  71343. if (originalNumRects > 0)
  71344. {
  71345. const int x1 = rect.x;
  71346. const int y1 = rect.y;
  71347. const int x2 = x1 + rect.w;
  71348. const int y2 = y1 + rect.h;
  71349. for (int i = getNumRectangles(); --i >= 0;)
  71350. {
  71351. Rectangle& r = rects.getReference (i);
  71352. const int rx1 = r.x;
  71353. const int ry1 = r.y;
  71354. const int rx2 = rx1 + r.w;
  71355. const int ry2 = ry1 + r.h;
  71356. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  71357. {
  71358. if (x1 > rx1 && x1 < rx2)
  71359. {
  71360. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  71361. {
  71362. r.w = x1 - rx1;
  71363. }
  71364. else
  71365. {
  71366. r.x = x1;
  71367. r.w = rx2 - x1;
  71368. rects.insert (i + 1, Rectangle (rx1, ry1, x1 - rx1, ry2 - ry1));
  71369. i += 2;
  71370. }
  71371. }
  71372. else if (x2 > rx1 && x2 < rx2)
  71373. {
  71374. r.x = x2;
  71375. r.w = rx2 - x2;
  71376. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  71377. {
  71378. rects.insert (i + 1, Rectangle (rx1, ry1, x2 - rx1, ry2 - ry1));
  71379. i += 2;
  71380. }
  71381. }
  71382. else if (y1 > ry1 && y1 < ry2)
  71383. {
  71384. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  71385. {
  71386. r.h = y1 - ry1;
  71387. }
  71388. else
  71389. {
  71390. r.y = y1;
  71391. r.h = ry2 - y1;
  71392. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y1 - ry1));
  71393. i += 2;
  71394. }
  71395. }
  71396. else if (y2 > ry1 && y2 < ry2)
  71397. {
  71398. r.y = y2;
  71399. r.h = ry2 - y2;
  71400. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  71401. {
  71402. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y2 - ry1));
  71403. i += 2;
  71404. }
  71405. }
  71406. else
  71407. {
  71408. rects.remove (i);
  71409. }
  71410. }
  71411. }
  71412. if (rects.size() > originalNumRects + 10)
  71413. consolidate();
  71414. }
  71415. }
  71416. void RectangleList::subtract (const RectangleList& otherList) throw()
  71417. {
  71418. for (int i = otherList.rects.size(); --i >= 0;)
  71419. subtract (otherList.rects.getReference (i));
  71420. }
  71421. bool RectangleList::clipTo (const Rectangle& rect) throw()
  71422. {
  71423. bool notEmpty = false;
  71424. if (rect.isEmpty())
  71425. {
  71426. clear();
  71427. }
  71428. else
  71429. {
  71430. for (int i = rects.size(); --i >= 0;)
  71431. {
  71432. Rectangle& r = rects.getReference (i);
  71433. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  71434. rects.remove (i);
  71435. else
  71436. notEmpty = true;
  71437. }
  71438. }
  71439. return notEmpty;
  71440. }
  71441. bool RectangleList::clipTo (const RectangleList& other) throw()
  71442. {
  71443. if (rects.size() == 0)
  71444. return false;
  71445. RectangleList result;
  71446. for (int j = 0; j < rects.size(); ++j)
  71447. {
  71448. const Rectangle& rect = rects.getReference (j);
  71449. for (int i = other.rects.size(); --i >= 0;)
  71450. {
  71451. Rectangle r (other.rects.getReference (i));
  71452. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  71453. result.rects.add (r);
  71454. }
  71455. }
  71456. swapWith (result);
  71457. return ! isEmpty();
  71458. }
  71459. bool RectangleList::getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw()
  71460. {
  71461. destRegion.clear();
  71462. if (! rect.isEmpty())
  71463. {
  71464. for (int i = rects.size(); --i >= 0;)
  71465. {
  71466. Rectangle r (rects.getReference (i));
  71467. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  71468. destRegion.rects.add (r);
  71469. }
  71470. }
  71471. return destRegion.rects.size() > 0;
  71472. }
  71473. void RectangleList::swapWith (RectangleList& otherList) throw()
  71474. {
  71475. rects.swapWithArray (otherList.rects);
  71476. }
  71477. void RectangleList::consolidate() throw()
  71478. {
  71479. int i;
  71480. for (i = 0; i < getNumRectangles() - 1; ++i)
  71481. {
  71482. Rectangle& r = rects.getReference (i);
  71483. const int rx1 = r.x;
  71484. const int ry1 = r.y;
  71485. const int rx2 = rx1 + r.w;
  71486. const int ry2 = ry1 + r.h;
  71487. for (int j = rects.size(); --j > i;)
  71488. {
  71489. Rectangle& r2 = rects.getReference (j);
  71490. const int jrx1 = r2.x;
  71491. const int jry1 = r2.y;
  71492. const int jrx2 = jrx1 + r2.w;
  71493. const int jry2 = jry1 + r2.h;
  71494. // if the vertical edges of any blocks are touching and their horizontals don't
  71495. // line up, split them horizontally..
  71496. if (jrx1 == rx2 || jrx2 == rx1)
  71497. {
  71498. if (jry1 > ry1 && jry1 < ry2)
  71499. {
  71500. r.h = jry1 - ry1;
  71501. rects.add (Rectangle (rx1, jry1, rx2 - rx1, ry2 - jry1));
  71502. i = -1;
  71503. break;
  71504. }
  71505. if (jry2 > ry1 && jry2 < ry2)
  71506. {
  71507. r.h = jry2 - ry1;
  71508. rects.add (Rectangle (rx1, jry2, rx2 - rx1, ry2 - jry2));
  71509. i = -1;
  71510. break;
  71511. }
  71512. else if (ry1 > jry1 && ry1 < jry2)
  71513. {
  71514. r2.h = ry1 - jry1;
  71515. rects.add (Rectangle (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  71516. i = -1;
  71517. break;
  71518. }
  71519. else if (ry2 > jry1 && ry2 < jry2)
  71520. {
  71521. r2.h = ry2 - jry1;
  71522. rects.add (Rectangle (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  71523. i = -1;
  71524. break;
  71525. }
  71526. }
  71527. }
  71528. }
  71529. for (i = 0; i < rects.size() - 1; ++i)
  71530. {
  71531. Rectangle& r = rects.getReference (i);
  71532. for (int j = rects.size(); --j > i;)
  71533. {
  71534. if (r.enlargeIfAdjacent (rects.getReference (j)))
  71535. {
  71536. rects.remove (j);
  71537. i = -1;
  71538. break;
  71539. }
  71540. }
  71541. }
  71542. }
  71543. bool RectangleList::containsPoint (const int x, const int y) const throw()
  71544. {
  71545. for (int i = getNumRectangles(); --i >= 0;)
  71546. if (rects.getReference (i).contains (x, y))
  71547. return true;
  71548. return false;
  71549. }
  71550. bool RectangleList::containsRectangle (const Rectangle& rectangleToCheck) const throw()
  71551. {
  71552. if (rects.size() > 1)
  71553. {
  71554. RectangleList r (rectangleToCheck);
  71555. for (int i = rects.size(); --i >= 0;)
  71556. {
  71557. r.subtract (rects.getReference (i));
  71558. if (r.rects.size() == 0)
  71559. return true;
  71560. }
  71561. }
  71562. else if (rects.size() > 0)
  71563. {
  71564. return rects.getReference (0).contains (rectangleToCheck);
  71565. }
  71566. return false;
  71567. }
  71568. bool RectangleList::intersectsRectangle (const Rectangle& rectangleToCheck) const throw()
  71569. {
  71570. for (int i = rects.size(); --i >= 0;)
  71571. if (rects.getReference (i).intersects (rectangleToCheck))
  71572. return true;
  71573. return false;
  71574. }
  71575. bool RectangleList::intersects (const RectangleList& other) const throw()
  71576. {
  71577. for (int i = rects.size(); --i >= 0;)
  71578. if (other.intersectsRectangle (rects.getReference (i)))
  71579. return true;
  71580. return false;
  71581. }
  71582. const Rectangle RectangleList::getBounds() const throw()
  71583. {
  71584. if (rects.size() <= 1)
  71585. {
  71586. if (rects.size() == 0)
  71587. return Rectangle();
  71588. else
  71589. return rects.getReference (0);
  71590. }
  71591. else
  71592. {
  71593. const Rectangle& r = rects.getReference (0);
  71594. int minX = r.x;
  71595. int minY = r.y;
  71596. int maxX = minX + r.w;
  71597. int maxY = minY + r.h;
  71598. for (int i = rects.size(); --i > 0;)
  71599. {
  71600. const Rectangle& r2 = rects.getReference (i);
  71601. minX = jmin (minX, r2.x);
  71602. minY = jmin (minY, r2.y);
  71603. maxX = jmax (maxX, r2.getRight());
  71604. maxY = jmax (maxY, r2.getBottom());
  71605. }
  71606. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  71607. }
  71608. }
  71609. void RectangleList::offsetAll (const int dx, const int dy) throw()
  71610. {
  71611. for (int i = rects.size(); --i >= 0;)
  71612. {
  71613. Rectangle& r = rects.getReference (i);
  71614. r.x += dx;
  71615. r.y += dy;
  71616. }
  71617. }
  71618. const Path RectangleList::toPath() const throw()
  71619. {
  71620. Path p;
  71621. for (int i = rects.size(); --i >= 0;)
  71622. {
  71623. const Rectangle& r = rects.getReference (i);
  71624. p.addRectangle ((float) r.x,
  71625. (float) r.y,
  71626. (float) r.w,
  71627. (float) r.h);
  71628. }
  71629. return p;
  71630. }
  71631. END_JUCE_NAMESPACE
  71632. /********* End of inlined file: juce_RectangleList.cpp *********/
  71633. /********* Start of inlined file: juce_Image.cpp *********/
  71634. BEGIN_JUCE_NAMESPACE
  71635. static const int fullAlphaThreshold = 253;
  71636. Image::Image (const PixelFormat format_,
  71637. const int imageWidth_,
  71638. const int imageHeight_)
  71639. : format (format_),
  71640. imageWidth (imageWidth_),
  71641. imageHeight (imageHeight_),
  71642. imageData (0)
  71643. {
  71644. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  71645. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  71646. // actual image will be at least 1x1.
  71647. }
  71648. Image::Image (const PixelFormat format_,
  71649. const int imageWidth_,
  71650. const int imageHeight_,
  71651. const bool clearImage)
  71652. : format (format_),
  71653. imageWidth (imageWidth_),
  71654. imageHeight (imageHeight_)
  71655. {
  71656. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  71657. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  71658. // actual image will be at least 1x1.
  71659. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  71660. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  71661. const int dataSize = lineStride * jmax (1, imageHeight_);
  71662. imageData = (uint8*) (clearImage ? juce_calloc (dataSize)
  71663. : juce_malloc (dataSize));
  71664. }
  71665. Image::Image (const Image& other)
  71666. : format (other.format),
  71667. imageWidth (other.imageWidth),
  71668. imageHeight (other.imageHeight)
  71669. {
  71670. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  71671. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  71672. const int dataSize = lineStride * jmax (1, imageHeight);
  71673. imageData = (uint8*) juce_malloc (dataSize);
  71674. int ls, ps;
  71675. const uint8* srcData = other.lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  71676. setPixelData (0, 0, imageWidth, imageHeight, srcData, ls);
  71677. other.releasePixelDataReadOnly (srcData);
  71678. }
  71679. Image::~Image()
  71680. {
  71681. juce_free (imageData);
  71682. }
  71683. LowLevelGraphicsContext* Image::createLowLevelContext()
  71684. {
  71685. return new LowLevelGraphicsSoftwareRenderer (*this);
  71686. }
  71687. uint8* Image::lockPixelDataReadWrite (int x, int y, int w, int h, int& ls, int& ps)
  71688. {
  71689. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  71690. w = w;
  71691. h = h;
  71692. ls = lineStride;
  71693. ps = pixelStride;
  71694. return imageData + x * pixelStride + y * lineStride;
  71695. }
  71696. void Image::releasePixelDataReadWrite (void*)
  71697. {
  71698. }
  71699. const uint8* Image::lockPixelDataReadOnly (int x, int y, int w, int h, int& ls, int& ps) const
  71700. {
  71701. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  71702. w = w;
  71703. h = h;
  71704. ls = lineStride;
  71705. ps = pixelStride;
  71706. return imageData + x * pixelStride + y * lineStride;
  71707. }
  71708. void Image::releasePixelDataReadOnly (const void*) const
  71709. {
  71710. }
  71711. void Image::setPixelData (int x, int y, int w, int h,
  71712. const uint8* sourcePixelData, int sourceLineStride)
  71713. {
  71714. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  71715. if (Rectangle::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  71716. {
  71717. int ls, ps;
  71718. uint8* dest = lockPixelDataReadWrite (x, y, w, h, ls, ps);
  71719. for (int i = 0; i < h; ++i)
  71720. {
  71721. memcpy (dest + ls * i,
  71722. sourcePixelData + sourceLineStride * i,
  71723. w * pixelStride);
  71724. }
  71725. releasePixelDataReadWrite (dest);
  71726. }
  71727. }
  71728. void Image::clear (int dx, int dy, int dw, int dh,
  71729. const Colour& colourToClearTo)
  71730. {
  71731. const PixelARGB col (colourToClearTo.getPixelARGB());
  71732. int ls, ps;
  71733. uint8* dstData = lockPixelDataReadWrite (dx, dy, dw, dh, ls, ps);
  71734. uint8* dest = dstData;
  71735. while (--dh >= 0)
  71736. {
  71737. uint8* line = dest;
  71738. dest += ls;
  71739. if (isARGB())
  71740. {
  71741. for (int x = dw; --x >= 0;)
  71742. {
  71743. ((PixelARGB*) line)->set (col);
  71744. line += ps;
  71745. }
  71746. }
  71747. else if (isRGB())
  71748. {
  71749. for (int x = dw; --x >= 0;)
  71750. {
  71751. ((PixelRGB*) line)->set (col);
  71752. line += ps;
  71753. }
  71754. }
  71755. else
  71756. {
  71757. for (int x = dw; --x >= 0;)
  71758. {
  71759. *line = col.getAlpha();
  71760. line += ps;
  71761. }
  71762. }
  71763. }
  71764. releasePixelDataReadWrite (dstData);
  71765. }
  71766. Image* Image::createCopy (int newWidth, int newHeight,
  71767. const Graphics::ResamplingQuality quality) const
  71768. {
  71769. if (newWidth < 0)
  71770. newWidth = imageWidth;
  71771. if (newHeight < 0)
  71772. newHeight = imageHeight;
  71773. Image* const newImage = new Image (format, newWidth, newHeight, true);
  71774. Graphics g (*newImage);
  71775. g.setImageResamplingQuality (quality);
  71776. g.drawImage (this,
  71777. 0, 0, newWidth, newHeight,
  71778. 0, 0, imageWidth, imageHeight,
  71779. false);
  71780. return newImage;
  71781. }
  71782. const Colour Image::getPixelAt (const int x, const int y) const
  71783. {
  71784. Colour c;
  71785. if (((unsigned int) x) < (unsigned int) imageWidth
  71786. && ((unsigned int) y) < (unsigned int) imageHeight)
  71787. {
  71788. int ls, ps;
  71789. const uint8* const pixels = lockPixelDataReadOnly (x, y, 1, 1, ls, ps);
  71790. if (isARGB())
  71791. {
  71792. PixelARGB p (*(const PixelARGB*) pixels);
  71793. p.unpremultiply();
  71794. c = Colour (p.getARGB());
  71795. }
  71796. else if (isRGB())
  71797. c = Colour (((const PixelRGB*) pixels)->getARGB());
  71798. else
  71799. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixels);
  71800. releasePixelDataReadOnly (pixels);
  71801. }
  71802. return c;
  71803. }
  71804. void Image::setPixelAt (const int x, const int y,
  71805. const Colour& colour)
  71806. {
  71807. if (((unsigned int) x) < (unsigned int) imageWidth
  71808. && ((unsigned int) y) < (unsigned int) imageHeight)
  71809. {
  71810. int ls, ps;
  71811. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  71812. const PixelARGB col (colour.getPixelARGB());
  71813. if (isARGB())
  71814. ((PixelARGB*) pixels)->set (col);
  71815. else if (isRGB())
  71816. ((PixelRGB*) pixels)->set (col);
  71817. else
  71818. *pixels = col.getAlpha();
  71819. releasePixelDataReadWrite (pixels);
  71820. }
  71821. }
  71822. void Image::multiplyAlphaAt (const int x, const int y,
  71823. const float multiplier)
  71824. {
  71825. if (((unsigned int) x) < (unsigned int) imageWidth
  71826. && ((unsigned int) y) < (unsigned int) imageHeight
  71827. && hasAlphaChannel())
  71828. {
  71829. int ls, ps;
  71830. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  71831. if (isARGB())
  71832. ((PixelARGB*) pixels)->multiplyAlpha (multiplier);
  71833. else
  71834. *pixels = (uint8) (*pixels * multiplier);
  71835. releasePixelDataReadWrite (pixels);
  71836. }
  71837. }
  71838. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  71839. {
  71840. if (hasAlphaChannel())
  71841. {
  71842. int ls, ps;
  71843. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  71844. if (isARGB())
  71845. {
  71846. for (int y = 0; y < imageHeight; ++y)
  71847. {
  71848. uint8* p = pixels + y * ls;
  71849. for (int x = 0; x < imageWidth; ++x)
  71850. {
  71851. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  71852. p += ps;
  71853. }
  71854. }
  71855. }
  71856. else
  71857. {
  71858. for (int y = 0; y < imageHeight; ++y)
  71859. {
  71860. uint8* p = pixels + y * ls;
  71861. for (int x = 0; x < imageWidth; ++x)
  71862. {
  71863. *p = (uint8) (*p * amountToMultiplyBy);
  71864. p += ps;
  71865. }
  71866. }
  71867. }
  71868. releasePixelDataReadWrite (pixels);
  71869. }
  71870. else
  71871. {
  71872. jassertfalse // can't do this without an alpha-channel!
  71873. }
  71874. }
  71875. void Image::desaturate()
  71876. {
  71877. if (isARGB() || isRGB())
  71878. {
  71879. int ls, ps;
  71880. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  71881. if (isARGB())
  71882. {
  71883. for (int y = 0; y < imageHeight; ++y)
  71884. {
  71885. uint8* p = pixels + y * ls;
  71886. for (int x = 0; x < imageWidth; ++x)
  71887. {
  71888. ((PixelARGB*) p)->desaturate();
  71889. p += ps;
  71890. }
  71891. }
  71892. }
  71893. else
  71894. {
  71895. for (int y = 0; y < imageHeight; ++y)
  71896. {
  71897. uint8* p = pixels + y * ls;
  71898. for (int x = 0; x < imageWidth; ++x)
  71899. {
  71900. ((PixelRGB*) p)->desaturate();
  71901. p += ps;
  71902. }
  71903. }
  71904. }
  71905. releasePixelDataReadWrite (pixels);
  71906. }
  71907. }
  71908. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  71909. {
  71910. if (hasAlphaChannel())
  71911. {
  71912. const uint8 threshold = (uint8) jlimit (0, 255, roundFloatToInt (alphaThreshold * 255.0f));
  71913. SparseSet <int> pixelsOnRow;
  71914. int ls, ps;
  71915. const uint8* const pixels = lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  71916. for (int y = 0; y < imageHeight; ++y)
  71917. {
  71918. pixelsOnRow.clear();
  71919. const uint8* lineData = pixels + ls * y;
  71920. if (isARGB())
  71921. {
  71922. for (int x = 0; x < imageWidth; ++x)
  71923. {
  71924. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  71925. pixelsOnRow.addRange (x, 1);
  71926. lineData += ps;
  71927. }
  71928. }
  71929. else
  71930. {
  71931. for (int x = 0; x < imageWidth; ++x)
  71932. {
  71933. if (*lineData >= threshold)
  71934. pixelsOnRow.addRange (x, 1);
  71935. lineData += ps;
  71936. }
  71937. }
  71938. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  71939. {
  71940. int x, w;
  71941. if (pixelsOnRow.getRange (i, x, w))
  71942. result.add (Rectangle (x, y, w, 1));
  71943. }
  71944. result.consolidate();
  71945. }
  71946. releasePixelDataReadOnly (pixels);
  71947. }
  71948. else
  71949. {
  71950. result.add (0, 0, imageWidth, imageHeight);
  71951. }
  71952. }
  71953. void Image::moveImageSection (int dx, int dy,
  71954. int sx, int sy,
  71955. int w, int h)
  71956. {
  71957. if (dx < 0)
  71958. {
  71959. w += dx;
  71960. sx -= dx;
  71961. dx = 0;
  71962. }
  71963. if (dy < 0)
  71964. {
  71965. h += dy;
  71966. sy -= dy;
  71967. dy = 0;
  71968. }
  71969. if (sx < 0)
  71970. {
  71971. w += sx;
  71972. dx -= sx;
  71973. sx = 0;
  71974. }
  71975. if (sy < 0)
  71976. {
  71977. h += sy;
  71978. dy -= sy;
  71979. sy = 0;
  71980. }
  71981. const int minX = jmin (dx, sx);
  71982. const int minY = jmin (dy, sy);
  71983. w = jmin (w, getWidth() - jmax (sx, dx));
  71984. h = jmin (h, getHeight() - jmax (sy, dy));
  71985. if (w > 0 && h > 0)
  71986. {
  71987. const int maxX = jmax (dx, sx) + w;
  71988. const int maxY = jmax (dy, sy) + h;
  71989. int ls, ps;
  71990. uint8* const pixels = lockPixelDataReadWrite (minX, minY, maxX - minX, maxY - minY, ls, ps);
  71991. uint8* dst = pixels + ls * (dy - minY) + ps * (dx - minX);
  71992. const uint8* src = pixels + ls * (sy - minY) + ps * (sx - minX);
  71993. const int lineSize = ps * w;
  71994. if (dy > sy)
  71995. {
  71996. while (--h >= 0)
  71997. {
  71998. const int offset = h * ls;
  71999. memmove (dst + offset, src + offset, lineSize);
  72000. }
  72001. }
  72002. else if (dst != src)
  72003. {
  72004. while (--h >= 0)
  72005. {
  72006. memmove (dst, src, lineSize);
  72007. dst += ls;
  72008. src += ls;
  72009. }
  72010. }
  72011. releasePixelDataReadWrite (pixels);
  72012. }
  72013. }
  72014. END_JUCE_NAMESPACE
  72015. /********* End of inlined file: juce_Image.cpp *********/
  72016. /********* Start of inlined file: juce_ImageCache.cpp *********/
  72017. BEGIN_JUCE_NAMESPACE
  72018. struct CachedImageInfo
  72019. {
  72020. Image* image;
  72021. int64 hashCode;
  72022. int refCount;
  72023. unsigned int releaseTime;
  72024. juce_UseDebuggingNewOperator
  72025. };
  72026. static ImageCache* instance = 0;
  72027. static int cacheTimeout = 5000;
  72028. ImageCache::ImageCache() throw()
  72029. : images (4)
  72030. {
  72031. }
  72032. ImageCache::~ImageCache()
  72033. {
  72034. const ScopedLock sl (lock);
  72035. for (int i = images.size(); --i >= 0;)
  72036. {
  72037. CachedImageInfo* const ci = (CachedImageInfo*)(images.getUnchecked(i));
  72038. delete ci->image;
  72039. delete ci;
  72040. }
  72041. images.clear();
  72042. jassert (instance == this);
  72043. instance = 0;
  72044. }
  72045. Image* ImageCache::getFromHashCode (const int64 hashCode)
  72046. {
  72047. if (instance != 0)
  72048. {
  72049. const ScopedLock sl (instance->lock);
  72050. for (int i = instance->images.size(); --i >= 0;)
  72051. {
  72052. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72053. if (ci->hashCode == hashCode)
  72054. {
  72055. atomicIncrement (ci->refCount);
  72056. return ci->image;
  72057. }
  72058. }
  72059. }
  72060. return 0;
  72061. }
  72062. void ImageCache::addImageToCache (Image* const image,
  72063. const int64 hashCode)
  72064. {
  72065. if (image != 0)
  72066. {
  72067. if (instance == 0)
  72068. instance = new ImageCache();
  72069. CachedImageInfo* const newC = new CachedImageInfo();
  72070. newC->hashCode = hashCode;
  72071. newC->image = image;
  72072. newC->refCount = 1;
  72073. newC->releaseTime = 0;
  72074. const ScopedLock sl (instance->lock);
  72075. instance->images.add (newC);
  72076. }
  72077. }
  72078. void ImageCache::release (Image* const imageToRelease)
  72079. {
  72080. if (imageToRelease != 0 && instance != 0)
  72081. {
  72082. const ScopedLock sl (instance->lock);
  72083. for (int i = instance->images.size(); --i >= 0;)
  72084. {
  72085. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72086. if (ci->image == imageToRelease)
  72087. {
  72088. if (--(ci->refCount) == 0)
  72089. ci->releaseTime = Time::getApproximateMillisecondCounter();
  72090. if (! instance->isTimerRunning())
  72091. instance->startTimer (999);
  72092. break;
  72093. }
  72094. }
  72095. }
  72096. }
  72097. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  72098. {
  72099. if (instance != 0)
  72100. {
  72101. const ScopedLock sl (instance->lock);
  72102. for (int i = instance->images.size(); --i >= 0;)
  72103. if (((const CachedImageInfo*) instance->images.getUnchecked(i))->image == imageToLookFor)
  72104. return true;
  72105. }
  72106. return false;
  72107. }
  72108. void ImageCache::incReferenceCount (Image* const image)
  72109. {
  72110. if (instance != 0)
  72111. {
  72112. const ScopedLock sl (instance->lock);
  72113. for (int i = instance->images.size(); --i >= 0;)
  72114. {
  72115. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72116. if (ci->image == image)
  72117. {
  72118. ci->refCount++;
  72119. return;
  72120. }
  72121. }
  72122. }
  72123. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  72124. }
  72125. void ImageCache::timerCallback()
  72126. {
  72127. int numberStillNeedingReleasing = 0;
  72128. const unsigned int now = Time::getApproximateMillisecondCounter();
  72129. const ScopedLock sl (lock);
  72130. for (int i = images.size(); --i >= 0;)
  72131. {
  72132. CachedImageInfo* const ci = (CachedImageInfo*) images.getUnchecked(i);
  72133. if (ci->refCount <= 0)
  72134. {
  72135. if (now > ci->releaseTime + cacheTimeout
  72136. || now < ci->releaseTime - 1000)
  72137. {
  72138. images.remove (i);
  72139. delete ci->image;
  72140. delete ci;
  72141. }
  72142. else
  72143. {
  72144. ++numberStillNeedingReleasing;
  72145. }
  72146. }
  72147. }
  72148. if (numberStillNeedingReleasing == 0)
  72149. stopTimer();
  72150. }
  72151. Image* ImageCache::getFromFile (const File& file)
  72152. {
  72153. const int64 hashCode = file.getFullPathName().hashCode64();
  72154. Image* image = getFromHashCode (hashCode);
  72155. if (image == 0)
  72156. {
  72157. image = ImageFileFormat::loadFrom (file);
  72158. addImageToCache (image, hashCode);
  72159. }
  72160. return image;
  72161. }
  72162. Image* ImageCache::getFromMemory (const void* imageData,
  72163. const int dataSize)
  72164. {
  72165. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  72166. Image* image = getFromHashCode (hashCode);
  72167. if (image == 0)
  72168. {
  72169. image = ImageFileFormat::loadFrom (imageData, dataSize);
  72170. addImageToCache (image, hashCode);
  72171. }
  72172. return image;
  72173. }
  72174. void ImageCache::setCacheTimeout (const int millisecs)
  72175. {
  72176. cacheTimeout = millisecs;
  72177. }
  72178. END_JUCE_NAMESPACE
  72179. /********* End of inlined file: juce_ImageCache.cpp *********/
  72180. /********* Start of inlined file: juce_ImageConvolutionKernel.cpp *********/
  72181. BEGIN_JUCE_NAMESPACE
  72182. ImageConvolutionKernel::ImageConvolutionKernel (const int size_) throw()
  72183. : size (size_)
  72184. {
  72185. values = new float* [size];
  72186. for (int i = size; --i >= 0;)
  72187. values[i] = new float [size];
  72188. clear();
  72189. }
  72190. ImageConvolutionKernel::~ImageConvolutionKernel() throw()
  72191. {
  72192. for (int i = size; --i >= 0;)
  72193. delete[] values[i];
  72194. delete[] values;
  72195. }
  72196. void ImageConvolutionKernel::setKernelValue (const int x,
  72197. const int y,
  72198. const float value) throw()
  72199. {
  72200. if (((unsigned int) x) < (unsigned int) size
  72201. && ((unsigned int) y) < (unsigned int) size)
  72202. {
  72203. values[x][y] = value;
  72204. }
  72205. else
  72206. {
  72207. jassertfalse
  72208. }
  72209. }
  72210. void ImageConvolutionKernel::clear() throw()
  72211. {
  72212. for (int y = size; --y >= 0;)
  72213. for (int x = size; --x >= 0;)
  72214. values[x][y] = 0;
  72215. }
  72216. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum) throw()
  72217. {
  72218. double currentTotal = 0.0;
  72219. for (int y = size; --y >= 0;)
  72220. for (int x = size; --x >= 0;)
  72221. currentTotal += values[x][y];
  72222. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  72223. }
  72224. void ImageConvolutionKernel::rescaleAllValues (const float multiplier) throw()
  72225. {
  72226. for (int y = size; --y >= 0;)
  72227. for (int x = size; --x >= 0;)
  72228. values[x][y] *= multiplier;
  72229. }
  72230. void ImageConvolutionKernel::createGaussianBlur (const float radius) throw()
  72231. {
  72232. const double radiusFactor = -1.0 / (radius * radius * 2);
  72233. const int centre = size >> 1;
  72234. for (int y = size; --y >= 0;)
  72235. {
  72236. for (int x = size; --x >= 0;)
  72237. {
  72238. const int cx = x - centre;
  72239. const int cy = y - centre;
  72240. values[x][y] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  72241. }
  72242. }
  72243. setOverallSum (1.0f);
  72244. }
  72245. void ImageConvolutionKernel::applyToImage (Image& destImage,
  72246. const Image* sourceImage,
  72247. int dx,
  72248. int dy,
  72249. int dw,
  72250. int dh) const
  72251. {
  72252. Image* imageCreated = 0;
  72253. if (sourceImage == 0)
  72254. {
  72255. sourceImage = imageCreated = destImage.createCopy();
  72256. }
  72257. else
  72258. {
  72259. jassert (sourceImage->getWidth() == destImage.getWidth()
  72260. && sourceImage->getHeight() == destImage.getHeight()
  72261. && sourceImage->getFormat() == destImage.getFormat());
  72262. if (sourceImage->getWidth() != destImage.getWidth()
  72263. || sourceImage->getHeight() != destImage.getHeight()
  72264. || sourceImage->getFormat() != destImage.getFormat())
  72265. return;
  72266. }
  72267. const int imageWidth = destImage.getWidth();
  72268. const int imageHeight = destImage.getHeight();
  72269. if (dx >= imageWidth || dy >= imageHeight)
  72270. return;
  72271. if (dx + dw > imageWidth)
  72272. dw = imageWidth - dx;
  72273. if (dy + dh > imageHeight)
  72274. dh = imageHeight - dy;
  72275. const int dx2 = dx + dw;
  72276. const int dy2 = dy + dh;
  72277. int lineStride, pixelStride;
  72278. uint8* pixels = destImage.lockPixelDataReadWrite (dx, dy, dw, dh, lineStride, pixelStride);
  72279. uint8* line = pixels;
  72280. int srcLineStride, srcPixelStride;
  72281. const uint8* srcPixels = sourceImage->lockPixelDataReadOnly (0, 0, sourceImage->getWidth(), sourceImage->getHeight(), srcLineStride, srcPixelStride);
  72282. if (pixelStride == 4)
  72283. {
  72284. for (int y = dy; y < dy2; ++y)
  72285. {
  72286. uint8* dest = line;
  72287. line += lineStride;
  72288. for (int x = dx; x < dx2; ++x)
  72289. {
  72290. float c1 = 0;
  72291. float c2 = 0;
  72292. float c3 = 0;
  72293. float c4 = 0;
  72294. for (int yy = 0; yy < size; ++yy)
  72295. {
  72296. const int sy = y + yy - (size >> 1);
  72297. if (sy >= imageHeight)
  72298. break;
  72299. if (sy >= 0)
  72300. {
  72301. int sx = x - (size >> 1);
  72302. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  72303. for (int xx = 0; xx < size; ++xx)
  72304. {
  72305. if (sx >= imageWidth)
  72306. break;
  72307. if (sx >= 0)
  72308. {
  72309. const float kernelMult = values[xx][yy];
  72310. c1 += kernelMult * *src++;
  72311. c2 += kernelMult * *src++;
  72312. c3 += kernelMult * *src++;
  72313. c4 += kernelMult * *src++;
  72314. }
  72315. else
  72316. {
  72317. src += 4;
  72318. }
  72319. ++sx;
  72320. }
  72321. }
  72322. }
  72323. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c1));
  72324. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c2));
  72325. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c3));
  72326. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c4));
  72327. }
  72328. }
  72329. }
  72330. else if (pixelStride == 3)
  72331. {
  72332. for (int y = dy; y < dy2; ++y)
  72333. {
  72334. uint8* dest = line;
  72335. line += lineStride;
  72336. for (int x = dx; x < dx2; ++x)
  72337. {
  72338. float c1 = 0;
  72339. float c2 = 0;
  72340. float c3 = 0;
  72341. for (int yy = 0; yy < size; ++yy)
  72342. {
  72343. const int sy = y + yy - (size >> 1);
  72344. if (sy >= imageHeight)
  72345. break;
  72346. if (sy >= 0)
  72347. {
  72348. int sx = x - (size >> 1);
  72349. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  72350. for (int xx = 0; xx < size; ++xx)
  72351. {
  72352. if (sx >= imageWidth)
  72353. break;
  72354. if (sx >= 0)
  72355. {
  72356. const float kernelMult = values[xx][yy];
  72357. c1 += kernelMult * *src++;
  72358. c2 += kernelMult * *src++;
  72359. c3 += kernelMult * *src++;
  72360. }
  72361. else
  72362. {
  72363. src += 3;
  72364. }
  72365. ++sx;
  72366. }
  72367. }
  72368. }
  72369. *dest++ = (uint8) roundFloatToInt (c1);
  72370. *dest++ = (uint8) roundFloatToInt (c2);
  72371. *dest++ = (uint8) roundFloatToInt (c3);
  72372. }
  72373. }
  72374. }
  72375. sourceImage->releasePixelDataReadOnly (srcPixels);
  72376. destImage.releasePixelDataReadWrite (pixels);
  72377. if (imageCreated != 0)
  72378. delete imageCreated;
  72379. }
  72380. END_JUCE_NAMESPACE
  72381. /********* End of inlined file: juce_ImageConvolutionKernel.cpp *********/
  72382. /********* Start of inlined file: juce_ImageFileFormat.cpp *********/
  72383. BEGIN_JUCE_NAMESPACE
  72384. /********* Start of inlined file: juce_GIFLoader.h *********/
  72385. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  72386. #define __JUCE_GIFLOADER_JUCEHEADER__
  72387. #ifndef DOXYGEN
  72388. static const int maxGifCode = 1 << 12;
  72389. /**
  72390. Used internally by ImageFileFormat - don't use this class directly in your
  72391. application.
  72392. @see ImageFileFormat
  72393. */
  72394. class GIFLoader
  72395. {
  72396. public:
  72397. GIFLoader (InputStream& in);
  72398. ~GIFLoader() throw();
  72399. Image* getImage() const throw() { return image; }
  72400. private:
  72401. Image* image;
  72402. InputStream& input;
  72403. uint8 buffer [300];
  72404. uint8 palette [256][4];
  72405. bool dataBlockIsZero, fresh, finished;
  72406. int currentBit, lastBit, lastByteIndex;
  72407. int codeSize, setCodeSize;
  72408. int maxCode, maxCodeSize;
  72409. int firstcode, oldcode;
  72410. int clearCode, end_code;
  72411. int table [2] [maxGifCode];
  72412. int stack [2 * maxGifCode];
  72413. int *sp;
  72414. bool getSizeFromHeader (int& width, int& height);
  72415. bool readPalette (const int numCols);
  72416. int readDataBlock (unsigned char* dest);
  72417. int processExtension (int type, int& transparent);
  72418. int readLZWByte (bool initialise, int input_code_size);
  72419. int getCode (int code_size, bool initialise);
  72420. bool readImage (int width, int height,
  72421. int interlace, int transparent);
  72422. GIFLoader (const GIFLoader&);
  72423. const GIFLoader& operator= (const GIFLoader&);
  72424. };
  72425. #endif // DOXYGEN
  72426. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  72427. /********* End of inlined file: juce_GIFLoader.h *********/
  72428. Image* juce_loadPNGImageFromStream (InputStream& inputStream) throw();
  72429. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw();
  72430. PNGImageFormat::PNGImageFormat() throw() {}
  72431. PNGImageFormat::~PNGImageFormat() throw() {}
  72432. const String PNGImageFormat::getFormatName()
  72433. {
  72434. return T("PNG");
  72435. }
  72436. bool PNGImageFormat::canUnderstand (InputStream& in)
  72437. {
  72438. const int bytesNeeded = 4;
  72439. char header [bytesNeeded];
  72440. return in.read (header, bytesNeeded) == bytesNeeded
  72441. && header[1] == 'P'
  72442. && header[2] == 'N'
  72443. && header[3] == 'G';
  72444. }
  72445. Image* PNGImageFormat::decodeImage (InputStream& in)
  72446. {
  72447. return juce_loadPNGImageFromStream (in);
  72448. }
  72449. bool PNGImageFormat::writeImageToStream (const Image& sourceImage,
  72450. OutputStream& destStream)
  72451. {
  72452. return juce_writePNGImageToStream (sourceImage, destStream);
  72453. }
  72454. Image* juce_loadJPEGImageFromStream (InputStream& inputStream) throw();
  72455. bool juce_writeJPEGImageToStream (const Image& image, OutputStream& out, float quality) throw();
  72456. JPEGImageFormat::JPEGImageFormat() throw()
  72457. : quality (-1.0f)
  72458. {
  72459. }
  72460. JPEGImageFormat::~JPEGImageFormat() throw() {}
  72461. void JPEGImageFormat::setQuality (const float newQuality)
  72462. {
  72463. quality = newQuality;
  72464. }
  72465. const String JPEGImageFormat::getFormatName()
  72466. {
  72467. return T("JPEG");
  72468. }
  72469. bool JPEGImageFormat::canUnderstand (InputStream& in)
  72470. {
  72471. const int bytesNeeded = 10;
  72472. uint8 header [bytesNeeded];
  72473. if (in.read (header, bytesNeeded) == bytesNeeded)
  72474. {
  72475. return header[0] == 0xff
  72476. && header[1] == 0xd8
  72477. && header[2] == 0xff
  72478. && (header[3] == 0xe0 || header[3] == 0xe1);
  72479. }
  72480. return false;
  72481. }
  72482. Image* JPEGImageFormat::decodeImage (InputStream& in)
  72483. {
  72484. return juce_loadJPEGImageFromStream (in);
  72485. }
  72486. bool JPEGImageFormat::writeImageToStream (const Image& sourceImage,
  72487. OutputStream& destStream)
  72488. {
  72489. return juce_writeJPEGImageToStream (sourceImage, destStream, quality);
  72490. }
  72491. class GIFImageFormat : public ImageFileFormat
  72492. {
  72493. public:
  72494. GIFImageFormat() throw() {}
  72495. ~GIFImageFormat() throw() {}
  72496. const String getFormatName()
  72497. {
  72498. return T("GIF");
  72499. }
  72500. bool canUnderstand (InputStream& in)
  72501. {
  72502. const int bytesNeeded = 4;
  72503. char header [bytesNeeded];
  72504. return (in.read (header, bytesNeeded) == bytesNeeded)
  72505. && header[0] == 'G'
  72506. && header[1] == 'I'
  72507. && header[2] == 'F';
  72508. }
  72509. Image* decodeImage (InputStream& in)
  72510. {
  72511. GIFLoader* const loader = new GIFLoader (in);
  72512. Image* const im = loader->getImage();
  72513. delete loader;
  72514. return im;
  72515. }
  72516. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  72517. {
  72518. return false;
  72519. }
  72520. };
  72521. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  72522. {
  72523. static PNGImageFormat png;
  72524. static JPEGImageFormat jpg;
  72525. static GIFImageFormat gif;
  72526. ImageFileFormat* formats[4];
  72527. int numFormats = 0;
  72528. formats [numFormats++] = &png;
  72529. formats [numFormats++] = &jpg;
  72530. formats [numFormats++] = &gif;
  72531. const int64 streamPos = input.getPosition();
  72532. for (int i = 0; i < numFormats; ++i)
  72533. {
  72534. const bool found = formats[i]->canUnderstand (input);
  72535. input.setPosition (streamPos);
  72536. if (found)
  72537. return formats[i];
  72538. }
  72539. return 0;
  72540. }
  72541. Image* ImageFileFormat::loadFrom (InputStream& input)
  72542. {
  72543. ImageFileFormat* const format = findImageFormatForStream (input);
  72544. if (format != 0)
  72545. return format->decodeImage (input);
  72546. return 0;
  72547. }
  72548. Image* ImageFileFormat::loadFrom (const File& file)
  72549. {
  72550. InputStream* const in = file.createInputStream();
  72551. if (in != 0)
  72552. {
  72553. BufferedInputStream b (in, 8192, true);
  72554. return loadFrom (b);
  72555. }
  72556. return 0;
  72557. }
  72558. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  72559. {
  72560. if (rawData != 0 && numBytes > 4)
  72561. {
  72562. MemoryInputStream stream (rawData, numBytes, false);
  72563. return loadFrom (stream);
  72564. }
  72565. return 0;
  72566. }
  72567. END_JUCE_NAMESPACE
  72568. /********* End of inlined file: juce_ImageFileFormat.cpp *********/
  72569. /********* Start of inlined file: juce_GIFLoader.cpp *********/
  72570. BEGIN_JUCE_NAMESPACE
  72571. static inline int makeWord (const unsigned char a, const unsigned char b) throw()
  72572. {
  72573. return (b << 8) | a;
  72574. }
  72575. GIFLoader::GIFLoader (InputStream& in)
  72576. : image (0),
  72577. input (in),
  72578. dataBlockIsZero (false),
  72579. fresh (false),
  72580. finished (false)
  72581. {
  72582. currentBit = lastBit = lastByteIndex = 0;
  72583. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  72584. firstcode = oldcode = 0;
  72585. clearCode = end_code = 0;
  72586. int imageWidth, imageHeight;
  72587. int transparent = -1;
  72588. if (! getSizeFromHeader (imageWidth, imageHeight))
  72589. return;
  72590. if ((imageWidth <= 0) || (imageHeight <= 0))
  72591. return;
  72592. unsigned char buf [16];
  72593. if (in.read (buf, 3) != 3)
  72594. return;
  72595. int numColours = 2 << (buf[0] & 7);
  72596. if ((buf[0] & 0x80) != 0)
  72597. readPalette (numColours);
  72598. for (;;)
  72599. {
  72600. if (input.read (buf, 1) != 1)
  72601. break;
  72602. if (buf[0] == ';')
  72603. break;
  72604. if (buf[0] == '!')
  72605. {
  72606. if (input.read (buf, 1) != 1)
  72607. break;
  72608. if (processExtension (buf[0], transparent) < 0)
  72609. break;
  72610. continue;
  72611. }
  72612. if (buf[0] != ',')
  72613. continue;
  72614. if (input.read (buf, 9) != 9)
  72615. break;
  72616. imageWidth = makeWord (buf[4], buf[5]);
  72617. imageHeight = makeWord (buf[6], buf[7]);
  72618. numColours = 2 << (buf[8] & 7);
  72619. if ((buf[8] & 0x80) != 0)
  72620. if (! readPalette (numColours))
  72621. break;
  72622. image = new Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  72623. imageWidth, imageHeight, (transparent >= 0));
  72624. readImage (imageWidth, imageHeight,
  72625. (buf[8] & 0x40) != 0,
  72626. transparent);
  72627. break;
  72628. }
  72629. }
  72630. GIFLoader::~GIFLoader() throw()
  72631. {
  72632. }
  72633. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  72634. {
  72635. unsigned char b [8];
  72636. if (input.read (b, 6) == 6)
  72637. {
  72638. if ((strncmp ("GIF87a", (char*) b, 6) == 0)
  72639. || (strncmp ("GIF89a", (char*) b, 6) == 0))
  72640. {
  72641. if (input.read (b, 4) == 4)
  72642. {
  72643. w = makeWord (b[0], b[1]);
  72644. h = makeWord (b[2], b[3]);
  72645. return true;
  72646. }
  72647. }
  72648. }
  72649. return false;
  72650. }
  72651. bool GIFLoader::readPalette (const int numCols)
  72652. {
  72653. unsigned char rgb[4];
  72654. for (int i = 0; i < numCols; ++i)
  72655. {
  72656. input.read (rgb, 3);
  72657. palette [i][0] = rgb[0];
  72658. palette [i][1] = rgb[1];
  72659. palette [i][2] = rgb[2];
  72660. palette [i][3] = 0xff;
  72661. }
  72662. return true;
  72663. }
  72664. int GIFLoader::readDataBlock (unsigned char* const dest)
  72665. {
  72666. unsigned char n;
  72667. if (input.read (&n, 1) == 1)
  72668. {
  72669. dataBlockIsZero = (n == 0);
  72670. if (dataBlockIsZero || (input.read (dest, n) == n))
  72671. return n;
  72672. }
  72673. return -1;
  72674. }
  72675. int GIFLoader::processExtension (const int type, int& transparent)
  72676. {
  72677. unsigned char b [300];
  72678. int n = 0;
  72679. if (type == 0xf9)
  72680. {
  72681. n = readDataBlock (b);
  72682. if (n < 0)
  72683. return 1;
  72684. if ((b[0] & 0x1) != 0)
  72685. transparent = b[3];
  72686. }
  72687. do
  72688. {
  72689. n = readDataBlock (b);
  72690. }
  72691. while (n > 0);
  72692. return n;
  72693. }
  72694. int GIFLoader::getCode (const int codeSize, const bool initialise)
  72695. {
  72696. if (initialise)
  72697. {
  72698. currentBit = 0;
  72699. lastBit = 0;
  72700. finished = false;
  72701. return 0;
  72702. }
  72703. if ((currentBit + codeSize) >= lastBit)
  72704. {
  72705. if (finished)
  72706. return -1;
  72707. buffer[0] = buffer [lastByteIndex - 2];
  72708. buffer[1] = buffer [lastByteIndex - 1];
  72709. const int n = readDataBlock (&buffer[2]);
  72710. if (n == 0)
  72711. finished = true;
  72712. lastByteIndex = 2 + n;
  72713. currentBit = (currentBit - lastBit) + 16;
  72714. lastBit = (2 + n) * 8 ;
  72715. }
  72716. int result = 0;
  72717. int i = currentBit;
  72718. for (int j = 0; j < codeSize; ++j)
  72719. {
  72720. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  72721. ++i;
  72722. }
  72723. currentBit += codeSize;
  72724. return result;
  72725. }
  72726. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  72727. {
  72728. int code, incode, i;
  72729. if (initialise)
  72730. {
  72731. setCodeSize = inputCodeSize;
  72732. codeSize = setCodeSize + 1;
  72733. clearCode = 1 << setCodeSize;
  72734. end_code = clearCode + 1;
  72735. maxCodeSize = 2 * clearCode;
  72736. maxCode = clearCode + 2;
  72737. getCode (0, true);
  72738. fresh = true;
  72739. for (i = 0; i < clearCode; ++i)
  72740. {
  72741. table[0][i] = 0;
  72742. table[1][i] = i;
  72743. }
  72744. for (; i < maxGifCode; ++i)
  72745. {
  72746. table[0][i] = 0;
  72747. table[1][i] = 0;
  72748. }
  72749. sp = stack;
  72750. return 0;
  72751. }
  72752. else if (fresh)
  72753. {
  72754. fresh = false;
  72755. do
  72756. {
  72757. firstcode = oldcode
  72758. = getCode (codeSize, false);
  72759. }
  72760. while (firstcode == clearCode);
  72761. return firstcode;
  72762. }
  72763. if (sp > stack)
  72764. return *--sp;
  72765. while ((code = getCode (codeSize, false)) >= 0)
  72766. {
  72767. if (code == clearCode)
  72768. {
  72769. for (i = 0; i < clearCode; ++i)
  72770. {
  72771. table[0][i] = 0;
  72772. table[1][i] = i;
  72773. }
  72774. for (; i < maxGifCode; ++i)
  72775. {
  72776. table[0][i] = 0;
  72777. table[1][i] = 0;
  72778. }
  72779. codeSize = setCodeSize + 1;
  72780. maxCodeSize = 2 * clearCode;
  72781. maxCode = clearCode + 2;
  72782. sp = stack;
  72783. firstcode = oldcode = getCode (codeSize, false);
  72784. return firstcode;
  72785. }
  72786. else if (code == end_code)
  72787. {
  72788. if (dataBlockIsZero)
  72789. return -2;
  72790. unsigned char buf [260];
  72791. int n;
  72792. while ((n = readDataBlock (buf)) > 0)
  72793. {}
  72794. if (n != 0)
  72795. return -2;
  72796. }
  72797. incode = code;
  72798. if (code >= maxCode)
  72799. {
  72800. *sp++ = firstcode;
  72801. code = oldcode;
  72802. }
  72803. while (code >= clearCode)
  72804. {
  72805. *sp++ = table[1][code];
  72806. if (code == table[0][code])
  72807. return -2;
  72808. code = table[0][code];
  72809. }
  72810. *sp++ = firstcode = table[1][code];
  72811. if ((code = maxCode) < maxGifCode)
  72812. {
  72813. table[0][code] = oldcode;
  72814. table[1][code] = firstcode;
  72815. ++maxCode;
  72816. if ((maxCode >= maxCodeSize)
  72817. && (maxCodeSize < maxGifCode))
  72818. {
  72819. maxCodeSize <<= 1;
  72820. ++codeSize;
  72821. }
  72822. }
  72823. oldcode = incode;
  72824. if (sp > stack)
  72825. return *--sp;
  72826. }
  72827. return code;
  72828. }
  72829. bool GIFLoader::readImage (const int width, const int height,
  72830. const int interlace, const int transparent)
  72831. {
  72832. unsigned char c;
  72833. if (input.read (&c, 1) != 1
  72834. || readLZWByte (true, c) < 0)
  72835. return false;
  72836. if (transparent >= 0)
  72837. {
  72838. palette [transparent][0] = 0;
  72839. palette [transparent][1] = 0;
  72840. palette [transparent][2] = 0;
  72841. palette [transparent][3] = 0;
  72842. }
  72843. int index;
  72844. int xpos = 0, ypos = 0, pass = 0;
  72845. int stride, pixelStride;
  72846. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  72847. uint8* p = pixels;
  72848. const bool hasAlpha = image->hasAlphaChannel();
  72849. while ((index = readLZWByte (false, c)) >= 0)
  72850. {
  72851. const uint8* const paletteEntry = palette [index];
  72852. if (hasAlpha)
  72853. {
  72854. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  72855. paletteEntry[0],
  72856. paletteEntry[1],
  72857. paletteEntry[2]);
  72858. ((PixelARGB*) p)->premultiply();
  72859. p += pixelStride;
  72860. }
  72861. else
  72862. {
  72863. ((PixelRGB*) p)->setARGB (0,
  72864. paletteEntry[0],
  72865. paletteEntry[1],
  72866. paletteEntry[2]);
  72867. p += pixelStride;
  72868. }
  72869. ++xpos;
  72870. if (xpos == width)
  72871. {
  72872. xpos = 0;
  72873. if (interlace)
  72874. {
  72875. switch (pass)
  72876. {
  72877. case 0:
  72878. case 1:
  72879. ypos += 8;
  72880. break;
  72881. case 2:
  72882. ypos += 4;
  72883. break;
  72884. case 3:
  72885. ypos += 2;
  72886. break;
  72887. }
  72888. while (ypos >= height)
  72889. {
  72890. ++pass;
  72891. switch (pass)
  72892. {
  72893. case 1:
  72894. ypos = 4;
  72895. break;
  72896. case 2:
  72897. ypos = 2;
  72898. break;
  72899. case 3:
  72900. ypos = 1;
  72901. break;
  72902. default:
  72903. return true;
  72904. }
  72905. }
  72906. }
  72907. else
  72908. {
  72909. ++ypos;
  72910. }
  72911. p = pixels + xpos * pixelStride + ypos * stride;
  72912. }
  72913. if (ypos >= height)
  72914. break;
  72915. }
  72916. image->releasePixelDataReadWrite (pixels);
  72917. return true;
  72918. }
  72919. END_JUCE_NAMESPACE
  72920. /********* End of inlined file: juce_GIFLoader.cpp *********/
  72921. #endif
  72922. //==============================================================================
  72923. // some files include lots of library code, so leave them to the end to avoid cluttering
  72924. // up the build for the clean files.
  72925. /********* Start of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  72926. namespace zlibNamespace
  72927. {
  72928. #if JUCE_INCLUDE_ZLIB_CODE
  72929. #undef OS_CODE
  72930. #undef fdopen
  72931. /********* Start of inlined file: zlib.h *********/
  72932. #ifndef ZLIB_H
  72933. #define ZLIB_H
  72934. /********* Start of inlined file: zconf.h *********/
  72935. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  72936. #ifndef ZCONF_H
  72937. #define ZCONF_H
  72938. // *** Just a few hacks here to make it compile nicely with Juce..
  72939. #define Z_PREFIX 1
  72940. #undef __MACTYPES__
  72941. #ifdef _MSC_VER
  72942. #pragma warning (disable : 4131 4127 4244 4267)
  72943. #endif
  72944. /*
  72945. * If you *really* need a unique prefix for all types and library functions,
  72946. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  72947. */
  72948. #ifdef Z_PREFIX
  72949. # define deflateInit_ z_deflateInit_
  72950. # define deflate z_deflate
  72951. # define deflateEnd z_deflateEnd
  72952. # define inflateInit_ z_inflateInit_
  72953. # define inflate z_inflate
  72954. # define inflateEnd z_inflateEnd
  72955. # define deflateInit2_ z_deflateInit2_
  72956. # define deflateSetDictionary z_deflateSetDictionary
  72957. # define deflateCopy z_deflateCopy
  72958. # define deflateReset z_deflateReset
  72959. # define deflateParams z_deflateParams
  72960. # define deflateBound z_deflateBound
  72961. # define deflatePrime z_deflatePrime
  72962. # define inflateInit2_ z_inflateInit2_
  72963. # define inflateSetDictionary z_inflateSetDictionary
  72964. # define inflateSync z_inflateSync
  72965. # define inflateSyncPoint z_inflateSyncPoint
  72966. # define inflateCopy z_inflateCopy
  72967. # define inflateReset z_inflateReset
  72968. # define inflateBack z_inflateBack
  72969. # define inflateBackEnd z_inflateBackEnd
  72970. # define compress z_compress
  72971. # define compress2 z_compress2
  72972. # define compressBound z_compressBound
  72973. # define uncompress z_uncompress
  72974. # define adler32 z_adler32
  72975. # define crc32 z_crc32
  72976. # define get_crc_table z_get_crc_table
  72977. # define zError z_zError
  72978. # define alloc_func z_alloc_func
  72979. # define free_func z_free_func
  72980. # define in_func z_in_func
  72981. # define out_func z_out_func
  72982. # define Byte z_Byte
  72983. # define uInt z_uInt
  72984. # define uLong z_uLong
  72985. # define Bytef z_Bytef
  72986. # define charf z_charf
  72987. # define intf z_intf
  72988. # define uIntf z_uIntf
  72989. # define uLongf z_uLongf
  72990. # define voidpf z_voidpf
  72991. # define voidp z_voidp
  72992. #endif
  72993. #if defined(__MSDOS__) && !defined(MSDOS)
  72994. # define MSDOS
  72995. #endif
  72996. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  72997. # define OS2
  72998. #endif
  72999. #if defined(_WINDOWS) && !defined(WINDOWS)
  73000. # define WINDOWS
  73001. #endif
  73002. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  73003. # ifndef WIN32
  73004. # define WIN32
  73005. # endif
  73006. #endif
  73007. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  73008. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  73009. # ifndef SYS16BIT
  73010. # define SYS16BIT
  73011. # endif
  73012. # endif
  73013. #endif
  73014. /*
  73015. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  73016. * than 64k bytes at a time (needed on systems with 16-bit int).
  73017. */
  73018. #ifdef SYS16BIT
  73019. # define MAXSEG_64K
  73020. #endif
  73021. #ifdef MSDOS
  73022. # define UNALIGNED_OK
  73023. #endif
  73024. #ifdef __STDC_VERSION__
  73025. # ifndef STDC
  73026. # define STDC
  73027. # endif
  73028. # if __STDC_VERSION__ >= 199901L
  73029. # ifndef STDC99
  73030. # define STDC99
  73031. # endif
  73032. # endif
  73033. #endif
  73034. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  73035. # define STDC
  73036. #endif
  73037. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  73038. # define STDC
  73039. #endif
  73040. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  73041. # define STDC
  73042. #endif
  73043. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  73044. # define STDC
  73045. #endif
  73046. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  73047. # define STDC
  73048. #endif
  73049. #ifndef STDC
  73050. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  73051. # define const /* note: need a more gentle solution here */
  73052. # endif
  73053. #endif
  73054. /* Some Mac compilers merge all .h files incorrectly: */
  73055. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  73056. # define NO_DUMMY_DECL
  73057. #endif
  73058. /* Maximum value for memLevel in deflateInit2 */
  73059. #ifndef MAX_MEM_LEVEL
  73060. # ifdef MAXSEG_64K
  73061. # define MAX_MEM_LEVEL 8
  73062. # else
  73063. # define MAX_MEM_LEVEL 9
  73064. # endif
  73065. #endif
  73066. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  73067. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  73068. * created by gzip. (Files created by minigzip can still be extracted by
  73069. * gzip.)
  73070. */
  73071. #ifndef MAX_WBITS
  73072. # define MAX_WBITS 15 /* 32K LZ77 window */
  73073. #endif
  73074. /* The memory requirements for deflate are (in bytes):
  73075. (1 << (windowBits+2)) + (1 << (memLevel+9))
  73076. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  73077. plus a few kilobytes for small objects. For example, if you want to reduce
  73078. the default memory requirements from 256K to 128K, compile with
  73079. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  73080. Of course this will generally degrade compression (there's no free lunch).
  73081. The memory requirements for inflate are (in bytes) 1 << windowBits
  73082. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  73083. for small objects.
  73084. */
  73085. /* Type declarations */
  73086. #ifndef OF /* function prototypes */
  73087. # ifdef STDC
  73088. # define OF(args) args
  73089. # else
  73090. # define OF(args) ()
  73091. # endif
  73092. #endif
  73093. /* The following definitions for FAR are needed only for MSDOS mixed
  73094. * model programming (small or medium model with some far allocations).
  73095. * This was tested only with MSC; for other MSDOS compilers you may have
  73096. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  73097. * just define FAR to be empty.
  73098. */
  73099. #ifdef SYS16BIT
  73100. # if defined(M_I86SM) || defined(M_I86MM)
  73101. /* MSC small or medium model */
  73102. # define SMALL_MEDIUM
  73103. # ifdef _MSC_VER
  73104. # define FAR _far
  73105. # else
  73106. # define FAR far
  73107. # endif
  73108. # endif
  73109. # if (defined(__SMALL__) || defined(__MEDIUM__))
  73110. /* Turbo C small or medium model */
  73111. # define SMALL_MEDIUM
  73112. # ifdef __BORLANDC__
  73113. # define FAR _far
  73114. # else
  73115. # define FAR far
  73116. # endif
  73117. # endif
  73118. #endif
  73119. #if defined(WINDOWS) || defined(WIN32)
  73120. /* If building or using zlib as a DLL, define ZLIB_DLL.
  73121. * This is not mandatory, but it offers a little performance increase.
  73122. */
  73123. # ifdef ZLIB_DLL
  73124. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  73125. # ifdef ZLIB_INTERNAL
  73126. # define ZEXTERN extern __declspec(dllexport)
  73127. # else
  73128. # define ZEXTERN extern __declspec(dllimport)
  73129. # endif
  73130. # endif
  73131. # endif /* ZLIB_DLL */
  73132. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  73133. * define ZLIB_WINAPI.
  73134. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  73135. */
  73136. # ifdef ZLIB_WINAPI
  73137. # ifdef FAR
  73138. # undef FAR
  73139. # endif
  73140. # include <windows.h>
  73141. /* No need for _export, use ZLIB.DEF instead. */
  73142. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  73143. # define ZEXPORT WINAPI
  73144. # ifdef WIN32
  73145. # define ZEXPORTVA WINAPIV
  73146. # else
  73147. # define ZEXPORTVA FAR CDECL
  73148. # endif
  73149. # endif
  73150. #endif
  73151. #if defined (__BEOS__)
  73152. # ifdef ZLIB_DLL
  73153. # ifdef ZLIB_INTERNAL
  73154. # define ZEXPORT __declspec(dllexport)
  73155. # define ZEXPORTVA __declspec(dllexport)
  73156. # else
  73157. # define ZEXPORT __declspec(dllimport)
  73158. # define ZEXPORTVA __declspec(dllimport)
  73159. # endif
  73160. # endif
  73161. #endif
  73162. #ifndef ZEXTERN
  73163. # define ZEXTERN extern
  73164. #endif
  73165. #ifndef ZEXPORT
  73166. # define ZEXPORT
  73167. #endif
  73168. #ifndef ZEXPORTVA
  73169. # define ZEXPORTVA
  73170. #endif
  73171. #ifndef FAR
  73172. # define FAR
  73173. #endif
  73174. #if !defined(__MACTYPES__)
  73175. typedef unsigned char Byte; /* 8 bits */
  73176. #endif
  73177. typedef unsigned int uInt; /* 16 bits or more */
  73178. typedef unsigned long uLong; /* 32 bits or more */
  73179. #ifdef SMALL_MEDIUM
  73180. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  73181. # define Bytef Byte FAR
  73182. #else
  73183. typedef Byte FAR Bytef;
  73184. #endif
  73185. typedef char FAR charf;
  73186. typedef int FAR intf;
  73187. typedef uInt FAR uIntf;
  73188. typedef uLong FAR uLongf;
  73189. #ifdef STDC
  73190. typedef void const *voidpc;
  73191. typedef void FAR *voidpf;
  73192. typedef void *voidp;
  73193. #else
  73194. typedef Byte const *voidpc;
  73195. typedef Byte FAR *voidpf;
  73196. typedef Byte *voidp;
  73197. #endif
  73198. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  73199. # include <sys/types.h> /* for off_t */
  73200. # include <unistd.h> /* for SEEK_* and off_t */
  73201. # ifdef VMS
  73202. # include <unixio.h> /* for off_t */
  73203. # endif
  73204. # define z_off_t off_t
  73205. #endif
  73206. #ifndef SEEK_SET
  73207. # define SEEK_SET 0 /* Seek from beginning of file. */
  73208. # define SEEK_CUR 1 /* Seek from current position. */
  73209. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  73210. #endif
  73211. #ifndef z_off_t
  73212. # define z_off_t long
  73213. #endif
  73214. #if defined(__OS400__)
  73215. # define NO_vsnprintf
  73216. #endif
  73217. #if defined(__MVS__)
  73218. # define NO_vsnprintf
  73219. # ifdef FAR
  73220. # undef FAR
  73221. # endif
  73222. #endif
  73223. /* MVS linker does not support external names larger than 8 bytes */
  73224. #if defined(__MVS__)
  73225. # pragma map(deflateInit_,"DEIN")
  73226. # pragma map(deflateInit2_,"DEIN2")
  73227. # pragma map(deflateEnd,"DEEND")
  73228. # pragma map(deflateBound,"DEBND")
  73229. # pragma map(inflateInit_,"ININ")
  73230. # pragma map(inflateInit2_,"ININ2")
  73231. # pragma map(inflateEnd,"INEND")
  73232. # pragma map(inflateSync,"INSY")
  73233. # pragma map(inflateSetDictionary,"INSEDI")
  73234. # pragma map(compressBound,"CMBND")
  73235. # pragma map(inflate_table,"INTABL")
  73236. # pragma map(inflate_fast,"INFA")
  73237. # pragma map(inflate_copyright,"INCOPY")
  73238. #endif
  73239. #endif /* ZCONF_H */
  73240. /********* End of inlined file: zconf.h *********/
  73241. #ifdef __cplusplus
  73242. extern "C" {
  73243. #endif
  73244. #define ZLIB_VERSION "1.2.3"
  73245. #define ZLIB_VERNUM 0x1230
  73246. /*
  73247. The 'zlib' compression library provides in-memory compression and
  73248. decompression functions, including integrity checks of the uncompressed
  73249. data. This version of the library supports only one compression method
  73250. (deflation) but other algorithms will be added later and will have the same
  73251. stream interface.
  73252. Compression can be done in a single step if the buffers are large
  73253. enough (for example if an input file is mmap'ed), or can be done by
  73254. repeated calls of the compression function. In the latter case, the
  73255. application must provide more input and/or consume the output
  73256. (providing more output space) before each call.
  73257. The compressed data format used by default by the in-memory functions is
  73258. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  73259. around a deflate stream, which is itself documented in RFC 1951.
  73260. The library also supports reading and writing files in gzip (.gz) format
  73261. with an interface similar to that of stdio using the functions that start
  73262. with "gz". The gzip format is different from the zlib format. gzip is a
  73263. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  73264. This library can optionally read and write gzip streams in memory as well.
  73265. The zlib format was designed to be compact and fast for use in memory
  73266. and on communications channels. The gzip format was designed for single-
  73267. file compression on file systems, has a larger header than zlib to maintain
  73268. directory information, and uses a different, slower check method than zlib.
  73269. The library does not install any signal handler. The decoder checks
  73270. the consistency of the compressed data, so the library should never
  73271. crash even in case of corrupted input.
  73272. */
  73273. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  73274. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  73275. struct internal_state;
  73276. typedef struct z_stream_s {
  73277. Bytef *next_in; /* next input byte */
  73278. uInt avail_in; /* number of bytes available at next_in */
  73279. uLong total_in; /* total nb of input bytes read so far */
  73280. Bytef *next_out; /* next output byte should be put there */
  73281. uInt avail_out; /* remaining free space at next_out */
  73282. uLong total_out; /* total nb of bytes output so far */
  73283. char *msg; /* last error message, NULL if no error */
  73284. struct internal_state FAR *state; /* not visible by applications */
  73285. alloc_func zalloc; /* used to allocate the internal state */
  73286. free_func zfree; /* used to free the internal state */
  73287. voidpf opaque; /* private data object passed to zalloc and zfree */
  73288. int data_type; /* best guess about the data type: binary or text */
  73289. uLong adler; /* adler32 value of the uncompressed data */
  73290. uLong reserved; /* reserved for future use */
  73291. } z_stream;
  73292. typedef z_stream FAR *z_streamp;
  73293. /*
  73294. gzip header information passed to and from zlib routines. See RFC 1952
  73295. for more details on the meanings of these fields.
  73296. */
  73297. typedef struct gz_header_s {
  73298. int text; /* true if compressed data believed to be text */
  73299. uLong time; /* modification time */
  73300. int xflags; /* extra flags (not used when writing a gzip file) */
  73301. int os; /* operating system */
  73302. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  73303. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  73304. uInt extra_max; /* space at extra (only when reading header) */
  73305. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  73306. uInt name_max; /* space at name (only when reading header) */
  73307. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  73308. uInt comm_max; /* space at comment (only when reading header) */
  73309. int hcrc; /* true if there was or will be a header crc */
  73310. int done; /* true when done reading gzip header (not used
  73311. when writing a gzip file) */
  73312. } gz_header;
  73313. typedef gz_header FAR *gz_headerp;
  73314. /*
  73315. The application must update next_in and avail_in when avail_in has
  73316. dropped to zero. It must update next_out and avail_out when avail_out
  73317. has dropped to zero. The application must initialize zalloc, zfree and
  73318. opaque before calling the init function. All other fields are set by the
  73319. compression library and must not be updated by the application.
  73320. The opaque value provided by the application will be passed as the first
  73321. parameter for calls of zalloc and zfree. This can be useful for custom
  73322. memory management. The compression library attaches no meaning to the
  73323. opaque value.
  73324. zalloc must return Z_NULL if there is not enough memory for the object.
  73325. If zlib is used in a multi-threaded application, zalloc and zfree must be
  73326. thread safe.
  73327. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  73328. exactly 65536 bytes, but will not be required to allocate more than this
  73329. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  73330. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  73331. have their offset normalized to zero. The default allocation function
  73332. provided by this library ensures this (see zutil.c). To reduce memory
  73333. requirements and avoid any allocation of 64K objects, at the expense of
  73334. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  73335. The fields total_in and total_out can be used for statistics or
  73336. progress reports. After compression, total_in holds the total size of
  73337. the uncompressed data and may be saved for use in the decompressor
  73338. (particularly if the decompressor wants to decompress everything in
  73339. a single step).
  73340. */
  73341. /* constants */
  73342. #define Z_NO_FLUSH 0
  73343. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  73344. #define Z_SYNC_FLUSH 2
  73345. #define Z_FULL_FLUSH 3
  73346. #define Z_FINISH 4
  73347. #define Z_BLOCK 5
  73348. /* Allowed flush values; see deflate() and inflate() below for details */
  73349. #define Z_OK 0
  73350. #define Z_STREAM_END 1
  73351. #define Z_NEED_DICT 2
  73352. #define Z_ERRNO (-1)
  73353. #define Z_STREAM_ERROR (-2)
  73354. #define Z_DATA_ERROR (-3)
  73355. #define Z_MEM_ERROR (-4)
  73356. #define Z_BUF_ERROR (-5)
  73357. #define Z_VERSION_ERROR (-6)
  73358. /* Return codes for the compression/decompression functions. Negative
  73359. * values are errors, positive values are used for special but normal events.
  73360. */
  73361. #define Z_NO_COMPRESSION 0
  73362. #define Z_BEST_SPEED 1
  73363. #define Z_BEST_COMPRESSION 9
  73364. #define Z_DEFAULT_COMPRESSION (-1)
  73365. /* compression levels */
  73366. #define Z_FILTERED 1
  73367. #define Z_HUFFMAN_ONLY 2
  73368. #define Z_RLE 3
  73369. #define Z_FIXED 4
  73370. #define Z_DEFAULT_STRATEGY 0
  73371. /* compression strategy; see deflateInit2() below for details */
  73372. #define Z_BINARY 0
  73373. #define Z_TEXT 1
  73374. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  73375. #define Z_UNKNOWN 2
  73376. /* Possible values of the data_type field (though see inflate()) */
  73377. #define Z_DEFLATED 8
  73378. /* The deflate compression method (the only one supported in this version) */
  73379. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  73380. #define zlib_version zlibVersion()
  73381. /* for compatibility with versions < 1.0.2 */
  73382. /* basic functions */
  73383. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  73384. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  73385. If the first character differs, the library code actually used is
  73386. not compatible with the zlib.h header file used by the application.
  73387. This check is automatically made by deflateInit and inflateInit.
  73388. */
  73389. /*
  73390. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  73391. Initializes the internal stream state for compression. The fields
  73392. zalloc, zfree and opaque must be initialized before by the caller.
  73393. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  73394. use default allocation functions.
  73395. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  73396. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  73397. all (the input data is simply copied a block at a time).
  73398. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  73399. compression (currently equivalent to level 6).
  73400. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  73401. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  73402. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  73403. with the version assumed by the caller (ZLIB_VERSION).
  73404. msg is set to null if there is no error message. deflateInit does not
  73405. perform any compression: this will be done by deflate().
  73406. */
  73407. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  73408. /*
  73409. deflate compresses as much data as possible, and stops when the input
  73410. buffer becomes empty or the output buffer becomes full. It may introduce some
  73411. output latency (reading input without producing any output) except when
  73412. forced to flush.
  73413. The detailed semantics are as follows. deflate performs one or both of the
  73414. following actions:
  73415. - Compress more input starting at next_in and update next_in and avail_in
  73416. accordingly. If not all input can be processed (because there is not
  73417. enough room in the output buffer), next_in and avail_in are updated and
  73418. processing will resume at this point for the next call of deflate().
  73419. - Provide more output starting at next_out and update next_out and avail_out
  73420. accordingly. This action is forced if the parameter flush is non zero.
  73421. Forcing flush frequently degrades the compression ratio, so this parameter
  73422. should be set only when necessary (in interactive applications).
  73423. Some output may be provided even if flush is not set.
  73424. Before the call of deflate(), the application should ensure that at least
  73425. one of the actions is possible, by providing more input and/or consuming
  73426. more output, and updating avail_in or avail_out accordingly; avail_out
  73427. should never be zero before the call. The application can consume the
  73428. compressed output when it wants, for example when the output buffer is full
  73429. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  73430. and with zero avail_out, it must be called again after making room in the
  73431. output buffer because there might be more output pending.
  73432. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  73433. decide how much data to accumualte before producing output, in order to
  73434. maximize compression.
  73435. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  73436. flushed to the output buffer and the output is aligned on a byte boundary, so
  73437. that the decompressor can get all input data available so far. (In particular
  73438. avail_in is zero after the call if enough output space has been provided
  73439. before the call.) Flushing may degrade compression for some compression
  73440. algorithms and so it should be used only when necessary.
  73441. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  73442. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  73443. restart from this point if previous compressed data has been damaged or if
  73444. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  73445. compression.
  73446. If deflate returns with avail_out == 0, this function must be called again
  73447. with the same value of the flush parameter and more output space (updated
  73448. avail_out), until the flush is complete (deflate returns with non-zero
  73449. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  73450. avail_out is greater than six to avoid repeated flush markers due to
  73451. avail_out == 0 on return.
  73452. If the parameter flush is set to Z_FINISH, pending input is processed,
  73453. pending output is flushed and deflate returns with Z_STREAM_END if there
  73454. was enough output space; if deflate returns with Z_OK, this function must be
  73455. called again with Z_FINISH and more output space (updated avail_out) but no
  73456. more input data, until it returns with Z_STREAM_END or an error. After
  73457. deflate has returned Z_STREAM_END, the only possible operations on the
  73458. stream are deflateReset or deflateEnd.
  73459. Z_FINISH can be used immediately after deflateInit if all the compression
  73460. is to be done in a single step. In this case, avail_out must be at least
  73461. the value returned by deflateBound (see below). If deflate does not return
  73462. Z_STREAM_END, then it must be called again as described above.
  73463. deflate() sets strm->adler to the adler32 checksum of all input read
  73464. so far (that is, total_in bytes).
  73465. deflate() may update strm->data_type if it can make a good guess about
  73466. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  73467. binary. This field is only for information purposes and does not affect
  73468. the compression algorithm in any manner.
  73469. deflate() returns Z_OK if some progress has been made (more input
  73470. processed or more output produced), Z_STREAM_END if all input has been
  73471. consumed and all output has been produced (only when flush is set to
  73472. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  73473. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  73474. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  73475. fatal, and deflate() can be called again with more input and more output
  73476. space to continue compressing.
  73477. */
  73478. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  73479. /*
  73480. All dynamically allocated data structures for this stream are freed.
  73481. This function discards any unprocessed input and does not flush any
  73482. pending output.
  73483. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  73484. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  73485. prematurely (some input or output was discarded). In the error case,
  73486. msg may be set but then points to a static string (which must not be
  73487. deallocated).
  73488. */
  73489. /*
  73490. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  73491. Initializes the internal stream state for decompression. The fields
  73492. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  73493. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  73494. value depends on the compression method), inflateInit determines the
  73495. compression method from the zlib header and allocates all data structures
  73496. accordingly; otherwise the allocation will be deferred to the first call of
  73497. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  73498. use default allocation functions.
  73499. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  73500. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  73501. version assumed by the caller. msg is set to null if there is no error
  73502. message. inflateInit does not perform any decompression apart from reading
  73503. the zlib header if present: this will be done by inflate(). (So next_in and
  73504. avail_in may be modified, but next_out and avail_out are unchanged.)
  73505. */
  73506. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  73507. /*
  73508. inflate decompresses as much data as possible, and stops when the input
  73509. buffer becomes empty or the output buffer becomes full. It may introduce
  73510. some output latency (reading input without producing any output) except when
  73511. forced to flush.
  73512. The detailed semantics are as follows. inflate performs one or both of the
  73513. following actions:
  73514. - Decompress more input starting at next_in and update next_in and avail_in
  73515. accordingly. If not all input can be processed (because there is not
  73516. enough room in the output buffer), next_in is updated and processing
  73517. will resume at this point for the next call of inflate().
  73518. - Provide more output starting at next_out and update next_out and avail_out
  73519. accordingly. inflate() provides as much output as possible, until there
  73520. is no more input data or no more space in the output buffer (see below
  73521. about the flush parameter).
  73522. Before the call of inflate(), the application should ensure that at least
  73523. one of the actions is possible, by providing more input and/or consuming
  73524. more output, and updating the next_* and avail_* values accordingly.
  73525. The application can consume the uncompressed output when it wants, for
  73526. example when the output buffer is full (avail_out == 0), or after each
  73527. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  73528. must be called again after making room in the output buffer because there
  73529. might be more output pending.
  73530. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  73531. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  73532. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  73533. if and when it gets to the next deflate block boundary. When decoding the
  73534. zlib or gzip format, this will cause inflate() to return immediately after
  73535. the header and before the first block. When doing a raw inflate, inflate()
  73536. will go ahead and process the first block, and will return when it gets to
  73537. the end of that block, or when it runs out of data.
  73538. The Z_BLOCK option assists in appending to or combining deflate streams.
  73539. Also to assist in this, on return inflate() will set strm->data_type to the
  73540. number of unused bits in the last byte taken from strm->next_in, plus 64
  73541. if inflate() is currently decoding the last block in the deflate stream,
  73542. plus 128 if inflate() returned immediately after decoding an end-of-block
  73543. code or decoding the complete header up to just before the first byte of the
  73544. deflate stream. The end-of-block will not be indicated until all of the
  73545. uncompressed data from that block has been written to strm->next_out. The
  73546. number of unused bits may in general be greater than seven, except when
  73547. bit 7 of data_type is set, in which case the number of unused bits will be
  73548. less than eight.
  73549. inflate() should normally be called until it returns Z_STREAM_END or an
  73550. error. However if all decompression is to be performed in a single step
  73551. (a single call of inflate), the parameter flush should be set to
  73552. Z_FINISH. In this case all pending input is processed and all pending
  73553. output is flushed; avail_out must be large enough to hold all the
  73554. uncompressed data. (The size of the uncompressed data may have been saved
  73555. by the compressor for this purpose.) The next operation on this stream must
  73556. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  73557. is never required, but can be used to inform inflate that a faster approach
  73558. may be used for the single inflate() call.
  73559. In this implementation, inflate() always flushes as much output as
  73560. possible to the output buffer, and always uses the faster approach on the
  73561. first call. So the only effect of the flush parameter in this implementation
  73562. is on the return value of inflate(), as noted below, or when it returns early
  73563. because Z_BLOCK is used.
  73564. If a preset dictionary is needed after this call (see inflateSetDictionary
  73565. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  73566. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  73567. strm->adler to the adler32 checksum of all output produced so far (that is,
  73568. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  73569. below. At the end of the stream, inflate() checks that its computed adler32
  73570. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  73571. only if the checksum is correct.
  73572. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  73573. deflate data. The header type is detected automatically. Any information
  73574. contained in the gzip header is not retained, so applications that need that
  73575. information should instead use raw inflate, see inflateInit2() below, or
  73576. inflateBack() and perform their own processing of the gzip header and
  73577. trailer.
  73578. inflate() returns Z_OK if some progress has been made (more input processed
  73579. or more output produced), Z_STREAM_END if the end of the compressed data has
  73580. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  73581. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  73582. corrupted (input stream not conforming to the zlib format or incorrect check
  73583. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  73584. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  73585. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  73586. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  73587. inflate() can be called again with more input and more output space to
  73588. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  73589. call inflateSync() to look for a good compression block if a partial recovery
  73590. of the data is desired.
  73591. */
  73592. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  73593. /*
  73594. All dynamically allocated data structures for this stream are freed.
  73595. This function discards any unprocessed input and does not flush any
  73596. pending output.
  73597. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  73598. was inconsistent. In the error case, msg may be set but then points to a
  73599. static string (which must not be deallocated).
  73600. */
  73601. /* Advanced functions */
  73602. /*
  73603. The following functions are needed only in some special applications.
  73604. */
  73605. /*
  73606. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  73607. int level,
  73608. int method,
  73609. int windowBits,
  73610. int memLevel,
  73611. int strategy));
  73612. This is another version of deflateInit with more compression options. The
  73613. fields next_in, zalloc, zfree and opaque must be initialized before by
  73614. the caller.
  73615. The method parameter is the compression method. It must be Z_DEFLATED in
  73616. this version of the library.
  73617. The windowBits parameter is the base two logarithm of the window size
  73618. (the size of the history buffer). It should be in the range 8..15 for this
  73619. version of the library. Larger values of this parameter result in better
  73620. compression at the expense of memory usage. The default value is 15 if
  73621. deflateInit is used instead.
  73622. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  73623. determines the window size. deflate() will then generate raw deflate data
  73624. with no zlib header or trailer, and will not compute an adler32 check value.
  73625. windowBits can also be greater than 15 for optional gzip encoding. Add
  73626. 16 to windowBits to write a simple gzip header and trailer around the
  73627. compressed data instead of a zlib wrapper. The gzip header will have no
  73628. file name, no extra data, no comment, no modification time (set to zero),
  73629. no header crc, and the operating system will be set to 255 (unknown). If a
  73630. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  73631. The memLevel parameter specifies how much memory should be allocated
  73632. for the internal compression state. memLevel=1 uses minimum memory but
  73633. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  73634. for optimal speed. The default value is 8. See zconf.h for total memory
  73635. usage as a function of windowBits and memLevel.
  73636. The strategy parameter is used to tune the compression algorithm. Use the
  73637. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  73638. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  73639. string match), or Z_RLE to limit match distances to one (run-length
  73640. encoding). Filtered data consists mostly of small values with a somewhat
  73641. random distribution. In this case, the compression algorithm is tuned to
  73642. compress them better. The effect of Z_FILTERED is to force more Huffman
  73643. coding and less string matching; it is somewhat intermediate between
  73644. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  73645. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  73646. parameter only affects the compression ratio but not the correctness of the
  73647. compressed output even if it is not set appropriately. Z_FIXED prevents the
  73648. use of dynamic Huffman codes, allowing for a simpler decoder for special
  73649. applications.
  73650. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  73651. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  73652. method). msg is set to null if there is no error message. deflateInit2 does
  73653. not perform any compression: this will be done by deflate().
  73654. */
  73655. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  73656. const Bytef *dictionary,
  73657. uInt dictLength));
  73658. /*
  73659. Initializes the compression dictionary from the given byte sequence
  73660. without producing any compressed output. This function must be called
  73661. immediately after deflateInit, deflateInit2 or deflateReset, before any
  73662. call of deflate. The compressor and decompressor must use exactly the same
  73663. dictionary (see inflateSetDictionary).
  73664. The dictionary should consist of strings (byte sequences) that are likely
  73665. to be encountered later in the data to be compressed, with the most commonly
  73666. used strings preferably put towards the end of the dictionary. Using a
  73667. dictionary is most useful when the data to be compressed is short and can be
  73668. predicted with good accuracy; the data can then be compressed better than
  73669. with the default empty dictionary.
  73670. Depending on the size of the compression data structures selected by
  73671. deflateInit or deflateInit2, a part of the dictionary may in effect be
  73672. discarded, for example if the dictionary is larger than the window size in
  73673. deflate or deflate2. Thus the strings most likely to be useful should be
  73674. put at the end of the dictionary, not at the front. In addition, the
  73675. current implementation of deflate will use at most the window size minus
  73676. 262 bytes of the provided dictionary.
  73677. Upon return of this function, strm->adler is set to the adler32 value
  73678. of the dictionary; the decompressor may later use this value to determine
  73679. which dictionary has been used by the compressor. (The adler32 value
  73680. applies to the whole dictionary even if only a subset of the dictionary is
  73681. actually used by the compressor.) If a raw deflate was requested, then the
  73682. adler32 value is not computed and strm->adler is not set.
  73683. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  73684. parameter is invalid (such as NULL dictionary) or the stream state is
  73685. inconsistent (for example if deflate has already been called for this stream
  73686. or if the compression method is bsort). deflateSetDictionary does not
  73687. perform any compression: this will be done by deflate().
  73688. */
  73689. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  73690. z_streamp source));
  73691. /*
  73692. Sets the destination stream as a complete copy of the source stream.
  73693. This function can be useful when several compression strategies will be
  73694. tried, for example when there are several ways of pre-processing the input
  73695. data with a filter. The streams that will be discarded should then be freed
  73696. by calling deflateEnd. Note that deflateCopy duplicates the internal
  73697. compression state which can be quite large, so this strategy is slow and
  73698. can consume lots of memory.
  73699. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  73700. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  73701. (such as zalloc being NULL). msg is left unchanged in both source and
  73702. destination.
  73703. */
  73704. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  73705. /*
  73706. This function is equivalent to deflateEnd followed by deflateInit,
  73707. but does not free and reallocate all the internal compression state.
  73708. The stream will keep the same compression level and any other attributes
  73709. that may have been set by deflateInit2.
  73710. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  73711. stream state was inconsistent (such as zalloc or state being NULL).
  73712. */
  73713. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  73714. int level,
  73715. int strategy));
  73716. /*
  73717. Dynamically update the compression level and compression strategy. The
  73718. interpretation of level and strategy is as in deflateInit2. This can be
  73719. used to switch between compression and straight copy of the input data, or
  73720. to switch to a different kind of input data requiring a different
  73721. strategy. If the compression level is changed, the input available so far
  73722. is compressed with the old level (and may be flushed); the new level will
  73723. take effect only at the next call of deflate().
  73724. Before the call of deflateParams, the stream state must be set as for
  73725. a call of deflate(), since the currently available input may have to
  73726. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  73727. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  73728. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  73729. if strm->avail_out was zero.
  73730. */
  73731. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  73732. int good_length,
  73733. int max_lazy,
  73734. int nice_length,
  73735. int max_chain));
  73736. /*
  73737. Fine tune deflate's internal compression parameters. This should only be
  73738. used by someone who understands the algorithm used by zlib's deflate for
  73739. searching for the best matching string, and even then only by the most
  73740. fanatic optimizer trying to squeeze out the last compressed bit for their
  73741. specific input data. Read the deflate.c source code for the meaning of the
  73742. max_lazy, good_length, nice_length, and max_chain parameters.
  73743. deflateTune() can be called after deflateInit() or deflateInit2(), and
  73744. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  73745. */
  73746. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  73747. uLong sourceLen));
  73748. /*
  73749. deflateBound() returns an upper bound on the compressed size after
  73750. deflation of sourceLen bytes. It must be called after deflateInit()
  73751. or deflateInit2(). This would be used to allocate an output buffer
  73752. for deflation in a single pass, and so would be called before deflate().
  73753. */
  73754. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  73755. int bits,
  73756. int value));
  73757. /*
  73758. deflatePrime() inserts bits in the deflate output stream. The intent
  73759. is that this function is used to start off the deflate output with the
  73760. bits leftover from a previous deflate stream when appending to it. As such,
  73761. this function can only be used for raw deflate, and must be used before the
  73762. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  73763. less than or equal to 16, and that many of the least significant bits of
  73764. value will be inserted in the output.
  73765. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  73766. stream state was inconsistent.
  73767. */
  73768. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  73769. gz_headerp head));
  73770. /*
  73771. deflateSetHeader() provides gzip header information for when a gzip
  73772. stream is requested by deflateInit2(). deflateSetHeader() may be called
  73773. after deflateInit2() or deflateReset() and before the first call of
  73774. deflate(). The text, time, os, extra field, name, and comment information
  73775. in the provided gz_header structure are written to the gzip header (xflag is
  73776. ignored -- the extra flags are set according to the compression level). The
  73777. caller must assure that, if not Z_NULL, name and comment are terminated with
  73778. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  73779. available there. If hcrc is true, a gzip header crc is included. Note that
  73780. the current versions of the command-line version of gzip (up through version
  73781. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  73782. gzip file" and give up.
  73783. If deflateSetHeader is not used, the default gzip header has text false,
  73784. the time set to zero, and os set to 255, with no extra, name, or comment
  73785. fields. The gzip header is returned to the default state by deflateReset().
  73786. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  73787. stream state was inconsistent.
  73788. */
  73789. /*
  73790. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  73791. int windowBits));
  73792. This is another version of inflateInit with an extra parameter. The
  73793. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  73794. before by the caller.
  73795. The windowBits parameter is the base two logarithm of the maximum window
  73796. size (the size of the history buffer). It should be in the range 8..15 for
  73797. this version of the library. The default value is 15 if inflateInit is used
  73798. instead. windowBits must be greater than or equal to the windowBits value
  73799. provided to deflateInit2() while compressing, or it must be equal to 15 if
  73800. deflateInit2() was not used. If a compressed stream with a larger window
  73801. size is given as input, inflate() will return with the error code
  73802. Z_DATA_ERROR instead of trying to allocate a larger window.
  73803. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  73804. determines the window size. inflate() will then process raw deflate data,
  73805. not looking for a zlib or gzip header, not generating a check value, and not
  73806. looking for any check values for comparison at the end of the stream. This
  73807. is for use with other formats that use the deflate compressed data format
  73808. such as zip. Those formats provide their own check values. If a custom
  73809. format is developed using the raw deflate format for compressed data, it is
  73810. recommended that a check value such as an adler32 or a crc32 be applied to
  73811. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  73812. most applications, the zlib format should be used as is. Note that comments
  73813. above on the use in deflateInit2() applies to the magnitude of windowBits.
  73814. windowBits can also be greater than 15 for optional gzip decoding. Add
  73815. 32 to windowBits to enable zlib and gzip decoding with automatic header
  73816. detection, or add 16 to decode only the gzip format (the zlib format will
  73817. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  73818. a crc32 instead of an adler32.
  73819. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  73820. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  73821. is set to null if there is no error message. inflateInit2 does not perform
  73822. any decompression apart from reading the zlib header if present: this will
  73823. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  73824. and avail_out are unchanged.)
  73825. */
  73826. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  73827. const Bytef *dictionary,
  73828. uInt dictLength));
  73829. /*
  73830. Initializes the decompression dictionary from the given uncompressed byte
  73831. sequence. This function must be called immediately after a call of inflate,
  73832. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  73833. can be determined from the adler32 value returned by that call of inflate.
  73834. The compressor and decompressor must use exactly the same dictionary (see
  73835. deflateSetDictionary). For raw inflate, this function can be called
  73836. immediately after inflateInit2() or inflateReset() and before any call of
  73837. inflate() to set the dictionary. The application must insure that the
  73838. dictionary that was used for compression is provided.
  73839. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  73840. parameter is invalid (such as NULL dictionary) or the stream state is
  73841. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  73842. expected one (incorrect adler32 value). inflateSetDictionary does not
  73843. perform any decompression: this will be done by subsequent calls of
  73844. inflate().
  73845. */
  73846. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  73847. /*
  73848. Skips invalid compressed data until a full flush point (see above the
  73849. description of deflate with Z_FULL_FLUSH) can be found, or until all
  73850. available input is skipped. No output is provided.
  73851. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  73852. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  73853. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  73854. case, the application may save the current current value of total_in which
  73855. indicates where valid compressed data was found. In the error case, the
  73856. application may repeatedly call inflateSync, providing more input each time,
  73857. until success or end of the input data.
  73858. */
  73859. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  73860. z_streamp source));
  73861. /*
  73862. Sets the destination stream as a complete copy of the source stream.
  73863. This function can be useful when randomly accessing a large stream. The
  73864. first pass through the stream can periodically record the inflate state,
  73865. allowing restarting inflate at those points when randomly accessing the
  73866. stream.
  73867. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  73868. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  73869. (such as zalloc being NULL). msg is left unchanged in both source and
  73870. destination.
  73871. */
  73872. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  73873. /*
  73874. This function is equivalent to inflateEnd followed by inflateInit,
  73875. but does not free and reallocate all the internal decompression state.
  73876. The stream will keep attributes that may have been set by inflateInit2.
  73877. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  73878. stream state was inconsistent (such as zalloc or state being NULL).
  73879. */
  73880. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  73881. int bits,
  73882. int value));
  73883. /*
  73884. This function inserts bits in the inflate input stream. The intent is
  73885. that this function is used to start inflating at a bit position in the
  73886. middle of a byte. The provided bits will be used before any bytes are used
  73887. from next_in. This function should only be used with raw inflate, and
  73888. should be used before the first inflate() call after inflateInit2() or
  73889. inflateReset(). bits must be less than or equal to 16, and that many of the
  73890. least significant bits of value will be inserted in the input.
  73891. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  73892. stream state was inconsistent.
  73893. */
  73894. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  73895. gz_headerp head));
  73896. /*
  73897. inflateGetHeader() requests that gzip header information be stored in the
  73898. provided gz_header structure. inflateGetHeader() may be called after
  73899. inflateInit2() or inflateReset(), and before the first call of inflate().
  73900. As inflate() processes the gzip stream, head->done is zero until the header
  73901. is completed, at which time head->done is set to one. If a zlib stream is
  73902. being decoded, then head->done is set to -1 to indicate that there will be
  73903. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  73904. force inflate() to return immediately after header processing is complete
  73905. and before any actual data is decompressed.
  73906. The text, time, xflags, and os fields are filled in with the gzip header
  73907. contents. hcrc is set to true if there is a header CRC. (The header CRC
  73908. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  73909. contains the maximum number of bytes to write to extra. Once done is true,
  73910. extra_len contains the actual extra field length, and extra contains the
  73911. extra field, or that field truncated if extra_max is less than extra_len.
  73912. If name is not Z_NULL, then up to name_max characters are written there,
  73913. terminated with a zero unless the length is greater than name_max. If
  73914. comment is not Z_NULL, then up to comm_max characters are written there,
  73915. terminated with a zero unless the length is greater than comm_max. When
  73916. any of extra, name, or comment are not Z_NULL and the respective field is
  73917. not present in the header, then that field is set to Z_NULL to signal its
  73918. absence. This allows the use of deflateSetHeader() with the returned
  73919. structure to duplicate the header. However if those fields are set to
  73920. allocated memory, then the application will need to save those pointers
  73921. elsewhere so that they can be eventually freed.
  73922. If inflateGetHeader is not used, then the header information is simply
  73923. discarded. The header is always checked for validity, including the header
  73924. CRC if present. inflateReset() will reset the process to discard the header
  73925. information. The application would need to call inflateGetHeader() again to
  73926. retrieve the header from the next gzip stream.
  73927. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  73928. stream state was inconsistent.
  73929. */
  73930. /*
  73931. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  73932. unsigned char FAR *window));
  73933. Initialize the internal stream state for decompression using inflateBack()
  73934. calls. The fields zalloc, zfree and opaque in strm must be initialized
  73935. before the call. If zalloc and zfree are Z_NULL, then the default library-
  73936. derived memory allocation routines are used. windowBits is the base two
  73937. logarithm of the window size, in the range 8..15. window is a caller
  73938. supplied buffer of that size. Except for special applications where it is
  73939. assured that deflate was used with small window sizes, windowBits must be 15
  73940. and a 32K byte window must be supplied to be able to decompress general
  73941. deflate streams.
  73942. See inflateBack() for the usage of these routines.
  73943. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  73944. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  73945. be allocated, or Z_VERSION_ERROR if the version of the library does not
  73946. match the version of the header file.
  73947. */
  73948. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  73949. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  73950. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  73951. in_func in, void FAR *in_desc,
  73952. out_func out, void FAR *out_desc));
  73953. /*
  73954. inflateBack() does a raw inflate with a single call using a call-back
  73955. interface for input and output. This is more efficient than inflate() for
  73956. file i/o applications in that it avoids copying between the output and the
  73957. sliding window by simply making the window itself the output buffer. This
  73958. function trusts the application to not change the output buffer passed by
  73959. the output function, at least until inflateBack() returns.
  73960. inflateBackInit() must be called first to allocate the internal state
  73961. and to initialize the state with the user-provided window buffer.
  73962. inflateBack() may then be used multiple times to inflate a complete, raw
  73963. deflate stream with each call. inflateBackEnd() is then called to free
  73964. the allocated state.
  73965. A raw deflate stream is one with no zlib or gzip header or trailer.
  73966. This routine would normally be used in a utility that reads zip or gzip
  73967. files and writes out uncompressed files. The utility would decode the
  73968. header and process the trailer on its own, hence this routine expects
  73969. only the raw deflate stream to decompress. This is different from the
  73970. normal behavior of inflate(), which expects either a zlib or gzip header and
  73971. trailer around the deflate stream.
  73972. inflateBack() uses two subroutines supplied by the caller that are then
  73973. called by inflateBack() for input and output. inflateBack() calls those
  73974. routines until it reads a complete deflate stream and writes out all of the
  73975. uncompressed data, or until it encounters an error. The function's
  73976. parameters and return types are defined above in the in_func and out_func
  73977. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  73978. number of bytes of provided input, and a pointer to that input in buf. If
  73979. there is no input available, in() must return zero--buf is ignored in that
  73980. case--and inflateBack() will return a buffer error. inflateBack() will call
  73981. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  73982. should return zero on success, or non-zero on failure. If out() returns
  73983. non-zero, inflateBack() will return with an error. Neither in() nor out()
  73984. are permitted to change the contents of the window provided to
  73985. inflateBackInit(), which is also the buffer that out() uses to write from.
  73986. The length written by out() will be at most the window size. Any non-zero
  73987. amount of input may be provided by in().
  73988. For convenience, inflateBack() can be provided input on the first call by
  73989. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  73990. in() will be called. Therefore strm->next_in must be initialized before
  73991. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  73992. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  73993. must also be initialized, and then if strm->avail_in is not zero, input will
  73994. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  73995. The in_desc and out_desc parameters of inflateBack() is passed as the
  73996. first parameter of in() and out() respectively when they are called. These
  73997. descriptors can be optionally used to pass any information that the caller-
  73998. supplied in() and out() functions need to do their job.
  73999. On return, inflateBack() will set strm->next_in and strm->avail_in to
  74000. pass back any unused input that was provided by the last in() call. The
  74001. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  74002. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  74003. error in the deflate stream (in which case strm->msg is set to indicate the
  74004. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  74005. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  74006. distinguished using strm->next_in which will be Z_NULL only if in() returned
  74007. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  74008. out() returning non-zero. (in() will always be called before out(), so
  74009. strm->next_in is assured to be defined if out() returns non-zero.) Note
  74010. that inflateBack() cannot return Z_OK.
  74011. */
  74012. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  74013. /*
  74014. All memory allocated by inflateBackInit() is freed.
  74015. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  74016. state was inconsistent.
  74017. */
  74018. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  74019. /* Return flags indicating compile-time options.
  74020. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  74021. 1.0: size of uInt
  74022. 3.2: size of uLong
  74023. 5.4: size of voidpf (pointer)
  74024. 7.6: size of z_off_t
  74025. Compiler, assembler, and debug options:
  74026. 8: DEBUG
  74027. 9: ASMV or ASMINF -- use ASM code
  74028. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  74029. 11: 0 (reserved)
  74030. One-time table building (smaller code, but not thread-safe if true):
  74031. 12: BUILDFIXED -- build static block decoding tables when needed
  74032. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  74033. 14,15: 0 (reserved)
  74034. Library content (indicates missing functionality):
  74035. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  74036. deflate code when not needed)
  74037. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  74038. and decode gzip streams (to avoid linking crc code)
  74039. 18-19: 0 (reserved)
  74040. Operation variations (changes in library functionality):
  74041. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  74042. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  74043. 22,23: 0 (reserved)
  74044. The sprintf variant used by gzprintf (zero is best):
  74045. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  74046. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  74047. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  74048. Remainder:
  74049. 27-31: 0 (reserved)
  74050. */
  74051. /* utility functions */
  74052. /*
  74053. The following utility functions are implemented on top of the
  74054. basic stream-oriented functions. To simplify the interface, some
  74055. default options are assumed (compression level and memory usage,
  74056. standard memory allocation functions). The source code of these
  74057. utility functions can easily be modified if you need special options.
  74058. */
  74059. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  74060. const Bytef *source, uLong sourceLen));
  74061. /*
  74062. Compresses the source buffer into the destination buffer. sourceLen is
  74063. the byte length of the source buffer. Upon entry, destLen is the total
  74064. size of the destination buffer, which must be at least the value returned
  74065. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  74066. compressed buffer.
  74067. This function can be used to compress a whole file at once if the
  74068. input file is mmap'ed.
  74069. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  74070. enough memory, Z_BUF_ERROR if there was not enough room in the output
  74071. buffer.
  74072. */
  74073. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  74074. const Bytef *source, uLong sourceLen,
  74075. int level));
  74076. /*
  74077. Compresses the source buffer into the destination buffer. The level
  74078. parameter has the same meaning as in deflateInit. sourceLen is the byte
  74079. length of the source buffer. Upon entry, destLen is the total size of the
  74080. destination buffer, which must be at least the value returned by
  74081. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  74082. compressed buffer.
  74083. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74084. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  74085. Z_STREAM_ERROR if the level parameter is invalid.
  74086. */
  74087. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  74088. /*
  74089. compressBound() returns an upper bound on the compressed size after
  74090. compress() or compress2() on sourceLen bytes. It would be used before
  74091. a compress() or compress2() call to allocate the destination buffer.
  74092. */
  74093. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  74094. const Bytef *source, uLong sourceLen));
  74095. /*
  74096. Decompresses the source buffer into the destination buffer. sourceLen is
  74097. the byte length of the source buffer. Upon entry, destLen is the total
  74098. size of the destination buffer, which must be large enough to hold the
  74099. entire uncompressed data. (The size of the uncompressed data must have
  74100. been saved previously by the compressor and transmitted to the decompressor
  74101. by some mechanism outside the scope of this compression library.)
  74102. Upon exit, destLen is the actual size of the compressed buffer.
  74103. This function can be used to decompress a whole file at once if the
  74104. input file is mmap'ed.
  74105. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  74106. enough memory, Z_BUF_ERROR if there was not enough room in the output
  74107. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  74108. */
  74109. typedef voidp gzFile;
  74110. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  74111. /*
  74112. Opens a gzip (.gz) file for reading or writing. The mode parameter
  74113. is as in fopen ("rb" or "wb") but can also include a compression level
  74114. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  74115. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  74116. as in "wb1R". (See the description of deflateInit2 for more information
  74117. about the strategy parameter.)
  74118. gzopen can be used to read a file which is not in gzip format; in this
  74119. case gzread will directly read from the file without decompression.
  74120. gzopen returns NULL if the file could not be opened or if there was
  74121. insufficient memory to allocate the (de)compression state; errno
  74122. can be checked to distinguish the two cases (if errno is zero, the
  74123. zlib error is Z_MEM_ERROR). */
  74124. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  74125. /*
  74126. gzdopen() associates a gzFile with the file descriptor fd. File
  74127. descriptors are obtained from calls like open, dup, creat, pipe or
  74128. fileno (in the file has been previously opened with fopen).
  74129. The mode parameter is as in gzopen.
  74130. The next call of gzclose on the returned gzFile will also close the
  74131. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  74132. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  74133. gzdopen returns NULL if there was insufficient memory to allocate
  74134. the (de)compression state.
  74135. */
  74136. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  74137. /*
  74138. Dynamically update the compression level or strategy. See the description
  74139. of deflateInit2 for the meaning of these parameters.
  74140. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  74141. opened for writing.
  74142. */
  74143. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  74144. /*
  74145. Reads the given number of uncompressed bytes from the compressed file.
  74146. If the input file was not in gzip format, gzread copies the given number
  74147. of bytes into the buffer.
  74148. gzread returns the number of uncompressed bytes actually read (0 for
  74149. end of file, -1 for error). */
  74150. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  74151. voidpc buf, unsigned len));
  74152. /*
  74153. Writes the given number of uncompressed bytes into the compressed file.
  74154. gzwrite returns the number of uncompressed bytes actually written
  74155. (0 in case of error).
  74156. */
  74157. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  74158. /*
  74159. Converts, formats, and writes the args to the compressed file under
  74160. control of the format string, as in fprintf. gzprintf returns the number of
  74161. uncompressed bytes actually written (0 in case of error). The number of
  74162. uncompressed bytes written is limited to 4095. The caller should assure that
  74163. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  74164. return an error (0) with nothing written. In this case, there may also be a
  74165. buffer overflow with unpredictable consequences, which is possible only if
  74166. zlib was compiled with the insecure functions sprintf() or vsprintf()
  74167. because the secure snprintf() or vsnprintf() functions were not available.
  74168. */
  74169. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  74170. /*
  74171. Writes the given null-terminated string to the compressed file, excluding
  74172. the terminating null character.
  74173. gzputs returns the number of characters written, or -1 in case of error.
  74174. */
  74175. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  74176. /*
  74177. Reads bytes from the compressed file until len-1 characters are read, or
  74178. a newline character is read and transferred to buf, or an end-of-file
  74179. condition is encountered. The string is then terminated with a null
  74180. character.
  74181. gzgets returns buf, or Z_NULL in case of error.
  74182. */
  74183. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  74184. /*
  74185. Writes c, converted to an unsigned char, into the compressed file.
  74186. gzputc returns the value that was written, or -1 in case of error.
  74187. */
  74188. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  74189. /*
  74190. Reads one byte from the compressed file. gzgetc returns this byte
  74191. or -1 in case of end of file or error.
  74192. */
  74193. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  74194. /*
  74195. Push one character back onto the stream to be read again later.
  74196. Only one character of push-back is allowed. gzungetc() returns the
  74197. character pushed, or -1 on failure. gzungetc() will fail if a
  74198. character has been pushed but not read yet, or if c is -1. The pushed
  74199. character will be discarded if the stream is repositioned with gzseek()
  74200. or gzrewind().
  74201. */
  74202. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  74203. /*
  74204. Flushes all pending output into the compressed file. The parameter
  74205. flush is as in the deflate() function. The return value is the zlib
  74206. error number (see function gzerror below). gzflush returns Z_OK if
  74207. the flush parameter is Z_FINISH and all output could be flushed.
  74208. gzflush should be called only when strictly necessary because it can
  74209. degrade compression.
  74210. */
  74211. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  74212. z_off_t offset, int whence));
  74213. /*
  74214. Sets the starting position for the next gzread or gzwrite on the
  74215. given compressed file. The offset represents a number of bytes in the
  74216. uncompressed data stream. The whence parameter is defined as in lseek(2);
  74217. the value SEEK_END is not supported.
  74218. If the file is opened for reading, this function is emulated but can be
  74219. extremely slow. If the file is opened for writing, only forward seeks are
  74220. supported; gzseek then compresses a sequence of zeroes up to the new
  74221. starting position.
  74222. gzseek returns the resulting offset location as measured in bytes from
  74223. the beginning of the uncompressed stream, or -1 in case of error, in
  74224. particular if the file is opened for writing and the new starting position
  74225. would be before the current position.
  74226. */
  74227. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  74228. /*
  74229. Rewinds the given file. This function is supported only for reading.
  74230. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  74231. */
  74232. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  74233. /*
  74234. Returns the starting position for the next gzread or gzwrite on the
  74235. given compressed file. This position represents a number of bytes in the
  74236. uncompressed data stream.
  74237. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  74238. */
  74239. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  74240. /*
  74241. Returns 1 when EOF has previously been detected reading the given
  74242. input stream, otherwise zero.
  74243. */
  74244. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  74245. /*
  74246. Returns 1 if file is being read directly without decompression, otherwise
  74247. zero.
  74248. */
  74249. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  74250. /*
  74251. Flushes all pending output if necessary, closes the compressed file
  74252. and deallocates all the (de)compression state. The return value is the zlib
  74253. error number (see function gzerror below).
  74254. */
  74255. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  74256. /*
  74257. Returns the error message for the last error which occurred on the
  74258. given compressed file. errnum is set to zlib error number. If an
  74259. error occurred in the file system and not in the compression library,
  74260. errnum is set to Z_ERRNO and the application may consult errno
  74261. to get the exact error code.
  74262. */
  74263. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  74264. /*
  74265. Clears the error and end-of-file flags for file. This is analogous to the
  74266. clearerr() function in stdio. This is useful for continuing to read a gzip
  74267. file that is being written concurrently.
  74268. */
  74269. /* checksum functions */
  74270. /*
  74271. These functions are not related to compression but are exported
  74272. anyway because they might be useful in applications using the
  74273. compression library.
  74274. */
  74275. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  74276. /*
  74277. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  74278. return the updated checksum. If buf is NULL, this function returns
  74279. the required initial value for the checksum.
  74280. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  74281. much faster. Usage example:
  74282. uLong adler = adler32(0L, Z_NULL, 0);
  74283. while (read_buffer(buffer, length) != EOF) {
  74284. adler = adler32(adler, buffer, length);
  74285. }
  74286. if (adler != original_adler) error();
  74287. */
  74288. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  74289. z_off_t len2));
  74290. /*
  74291. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  74292. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  74293. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  74294. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  74295. */
  74296. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  74297. /*
  74298. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  74299. updated CRC-32. If buf is NULL, this function returns the required initial
  74300. value for the for the crc. Pre- and post-conditioning (one's complement) is
  74301. performed within this function so it shouldn't be done by the application.
  74302. Usage example:
  74303. uLong crc = crc32(0L, Z_NULL, 0);
  74304. while (read_buffer(buffer, length) != EOF) {
  74305. crc = crc32(crc, buffer, length);
  74306. }
  74307. if (crc != original_crc) error();
  74308. */
  74309. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  74310. /*
  74311. Combine two CRC-32 check values into one. For two sequences of bytes,
  74312. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  74313. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  74314. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  74315. len2.
  74316. */
  74317. /* various hacks, don't look :) */
  74318. /* deflateInit and inflateInit are macros to allow checking the zlib version
  74319. * and the compiler's view of z_stream:
  74320. */
  74321. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  74322. const char *version, int stream_size));
  74323. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  74324. const char *version, int stream_size));
  74325. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  74326. int windowBits, int memLevel,
  74327. int strategy, const char *version,
  74328. int stream_size));
  74329. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  74330. const char *version, int stream_size));
  74331. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  74332. unsigned char FAR *window,
  74333. const char *version,
  74334. int stream_size));
  74335. #define deflateInit(strm, level) \
  74336. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  74337. #define inflateInit(strm) \
  74338. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  74339. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  74340. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  74341. (strategy), ZLIB_VERSION, sizeof(z_stream))
  74342. #define inflateInit2(strm, windowBits) \
  74343. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  74344. #define inflateBackInit(strm, windowBits, window) \
  74345. inflateBackInit_((strm), (windowBits), (window), \
  74346. ZLIB_VERSION, sizeof(z_stream))
  74347. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  74348. struct internal_state {int dummy;}; /* hack for buggy compilers */
  74349. #endif
  74350. ZEXTERN const char * ZEXPORT zError OF((int));
  74351. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  74352. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  74353. #ifdef __cplusplus
  74354. }
  74355. #endif
  74356. #endif /* ZLIB_H */
  74357. /********* End of inlined file: zlib.h *********/
  74358. #undef OS_CODE
  74359. #else
  74360. #include <zlib.h>
  74361. #endif
  74362. }
  74363. BEGIN_JUCE_NAMESPACE
  74364. using namespace zlibNamespace;
  74365. // internal helper object that holds the zlib structures so they don't have to be
  74366. // included publicly.
  74367. class GZIPCompressorHelper
  74368. {
  74369. private:
  74370. z_stream* stream;
  74371. uint8* data;
  74372. int dataSize, compLevel, strategy;
  74373. bool setParams;
  74374. public:
  74375. bool finished, shouldFinish;
  74376. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  74377. : data (0),
  74378. dataSize (0),
  74379. compLevel (compressionLevel),
  74380. strategy (0),
  74381. setParams (true),
  74382. finished (false),
  74383. shouldFinish (false)
  74384. {
  74385. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  74386. if (deflateInit2 (stream,
  74387. compLevel,
  74388. Z_DEFLATED,
  74389. nowrap ? -MAX_WBITS : MAX_WBITS,
  74390. 8,
  74391. strategy) != Z_OK)
  74392. {
  74393. juce_free (stream);
  74394. stream = 0;
  74395. }
  74396. }
  74397. ~GZIPCompressorHelper()
  74398. {
  74399. if (stream != 0)
  74400. {
  74401. deflateEnd (stream);
  74402. juce_free (stream);
  74403. }
  74404. }
  74405. bool needsInput() const throw()
  74406. {
  74407. return dataSize <= 0;
  74408. }
  74409. void setInput (uint8* const newData, const int size) throw()
  74410. {
  74411. data = newData;
  74412. dataSize = size;
  74413. }
  74414. int doNextBlock (uint8* const dest, const int destSize) throw()
  74415. {
  74416. if (stream != 0)
  74417. {
  74418. stream->next_in = data;
  74419. stream->next_out = dest;
  74420. stream->avail_in = dataSize;
  74421. stream->avail_out = destSize;
  74422. const int result = setParams ? deflateParams (stream, compLevel, strategy)
  74423. : deflate (stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  74424. setParams = false;
  74425. switch (result)
  74426. {
  74427. case Z_STREAM_END:
  74428. finished = true;
  74429. case Z_OK:
  74430. data += dataSize - stream->avail_in;
  74431. dataSize = stream->avail_in;
  74432. return destSize - stream->avail_out;
  74433. default:
  74434. break;
  74435. }
  74436. }
  74437. return 0;
  74438. }
  74439. };
  74440. const int gzipCompBufferSize = 32768;
  74441. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  74442. int compressionLevel,
  74443. const bool deleteDestStream_,
  74444. const bool noWrap)
  74445. : destStream (destStream_),
  74446. deleteDestStream (deleteDestStream_)
  74447. {
  74448. if (compressionLevel < 1 || compressionLevel > 9)
  74449. compressionLevel = -1;
  74450. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  74451. buffer = (uint8*) juce_malloc (gzipCompBufferSize);
  74452. }
  74453. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  74454. {
  74455. flush();
  74456. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  74457. delete h;
  74458. juce_free (buffer);
  74459. if (deleteDestStream)
  74460. delete destStream;
  74461. }
  74462. void GZIPCompressorOutputStream::flush()
  74463. {
  74464. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  74465. if (! h->finished)
  74466. {
  74467. h->shouldFinish = true;
  74468. while (! h->finished)
  74469. doNextBlock();
  74470. }
  74471. destStream->flush();
  74472. }
  74473. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  74474. {
  74475. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  74476. if (! h->finished)
  74477. {
  74478. h->setInput ((uint8*) destBuffer, howMany);
  74479. while (! h->needsInput())
  74480. {
  74481. if (! doNextBlock())
  74482. return false;
  74483. }
  74484. }
  74485. return true;
  74486. }
  74487. bool GZIPCompressorOutputStream::doNextBlock()
  74488. {
  74489. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  74490. const int len = h->doNextBlock (buffer, gzipCompBufferSize);
  74491. if (len > 0)
  74492. return destStream->write (buffer, len);
  74493. else
  74494. return true;
  74495. }
  74496. int64 GZIPCompressorOutputStream::getPosition()
  74497. {
  74498. return destStream->getPosition();
  74499. }
  74500. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  74501. {
  74502. jassertfalse // can't do it!
  74503. return false;
  74504. }
  74505. END_JUCE_NAMESPACE
  74506. /********* End of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  74507. /********* Start of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  74508. #if JUCE_MSVC
  74509. #pragma warning (push)
  74510. #pragma warning (disable: 4309 4305)
  74511. #endif
  74512. namespace zlibNamespace
  74513. {
  74514. #if JUCE_INCLUDE_ZLIB_CODE
  74515. extern "C"
  74516. {
  74517. #undef OS_CODE
  74518. #undef fdopen
  74519. #define ZLIB_INTERNAL
  74520. #define NO_DUMMY_DECL
  74521. /********* Start of inlined file: adler32.c *********/
  74522. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74523. #define ZLIB_INTERNAL
  74524. #define BASE 65521UL /* largest prime smaller than 65536 */
  74525. #define NMAX 5552
  74526. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  74527. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  74528. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  74529. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  74530. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  74531. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  74532. /* use NO_DIVIDE if your processor does not do division in hardware */
  74533. #ifdef NO_DIVIDE
  74534. # define MOD(a) \
  74535. do { \
  74536. if (a >= (BASE << 16)) a -= (BASE << 16); \
  74537. if (a >= (BASE << 15)) a -= (BASE << 15); \
  74538. if (a >= (BASE << 14)) a -= (BASE << 14); \
  74539. if (a >= (BASE << 13)) a -= (BASE << 13); \
  74540. if (a >= (BASE << 12)) a -= (BASE << 12); \
  74541. if (a >= (BASE << 11)) a -= (BASE << 11); \
  74542. if (a >= (BASE << 10)) a -= (BASE << 10); \
  74543. if (a >= (BASE << 9)) a -= (BASE << 9); \
  74544. if (a >= (BASE << 8)) a -= (BASE << 8); \
  74545. if (a >= (BASE << 7)) a -= (BASE << 7); \
  74546. if (a >= (BASE << 6)) a -= (BASE << 6); \
  74547. if (a >= (BASE << 5)) a -= (BASE << 5); \
  74548. if (a >= (BASE << 4)) a -= (BASE << 4); \
  74549. if (a >= (BASE << 3)) a -= (BASE << 3); \
  74550. if (a >= (BASE << 2)) a -= (BASE << 2); \
  74551. if (a >= (BASE << 1)) a -= (BASE << 1); \
  74552. if (a >= BASE) a -= BASE; \
  74553. } while (0)
  74554. # define MOD4(a) \
  74555. do { \
  74556. if (a >= (BASE << 4)) a -= (BASE << 4); \
  74557. if (a >= (BASE << 3)) a -= (BASE << 3); \
  74558. if (a >= (BASE << 2)) a -= (BASE << 2); \
  74559. if (a >= (BASE << 1)) a -= (BASE << 1); \
  74560. if (a >= BASE) a -= BASE; \
  74561. } while (0)
  74562. #else
  74563. # define MOD(a) a %= BASE
  74564. # define MOD4(a) a %= BASE
  74565. #endif
  74566. /* ========================================================================= */
  74567. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  74568. {
  74569. unsigned long sum2;
  74570. unsigned n;
  74571. /* split Adler-32 into component sums */
  74572. sum2 = (adler >> 16) & 0xffff;
  74573. adler &= 0xffff;
  74574. /* in case user likes doing a byte at a time, keep it fast */
  74575. if (len == 1) {
  74576. adler += buf[0];
  74577. if (adler >= BASE)
  74578. adler -= BASE;
  74579. sum2 += adler;
  74580. if (sum2 >= BASE)
  74581. sum2 -= BASE;
  74582. return adler | (sum2 << 16);
  74583. }
  74584. /* initial Adler-32 value (deferred check for len == 1 speed) */
  74585. if (buf == Z_NULL)
  74586. return 1L;
  74587. /* in case short lengths are provided, keep it somewhat fast */
  74588. if (len < 16) {
  74589. while (len--) {
  74590. adler += *buf++;
  74591. sum2 += adler;
  74592. }
  74593. if (adler >= BASE)
  74594. adler -= BASE;
  74595. MOD4(sum2); /* only added so many BASE's */
  74596. return adler | (sum2 << 16);
  74597. }
  74598. /* do length NMAX blocks -- requires just one modulo operation */
  74599. while (len >= NMAX) {
  74600. len -= NMAX;
  74601. n = NMAX / 16; /* NMAX is divisible by 16 */
  74602. do {
  74603. DO16(buf); /* 16 sums unrolled */
  74604. buf += 16;
  74605. } while (--n);
  74606. MOD(adler);
  74607. MOD(sum2);
  74608. }
  74609. /* do remaining bytes (less than NMAX, still just one modulo) */
  74610. if (len) { /* avoid modulos if none remaining */
  74611. while (len >= 16) {
  74612. len -= 16;
  74613. DO16(buf);
  74614. buf += 16;
  74615. }
  74616. while (len--) {
  74617. adler += *buf++;
  74618. sum2 += adler;
  74619. }
  74620. MOD(adler);
  74621. MOD(sum2);
  74622. }
  74623. /* return recombined sums */
  74624. return adler | (sum2 << 16);
  74625. }
  74626. /* ========================================================================= */
  74627. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  74628. {
  74629. unsigned long sum1;
  74630. unsigned long sum2;
  74631. unsigned rem;
  74632. /* the derivation of this formula is left as an exercise for the reader */
  74633. rem = (unsigned)(len2 % BASE);
  74634. sum1 = adler1 & 0xffff;
  74635. sum2 = rem * sum1;
  74636. MOD(sum2);
  74637. sum1 += (adler2 & 0xffff) + BASE - 1;
  74638. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  74639. if (sum1 > BASE) sum1 -= BASE;
  74640. if (sum1 > BASE) sum1 -= BASE;
  74641. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  74642. if (sum2 > BASE) sum2 -= BASE;
  74643. return sum1 | (sum2 << 16);
  74644. }
  74645. /********* End of inlined file: adler32.c *********/
  74646. /********* Start of inlined file: compress.c *********/
  74647. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74648. #define ZLIB_INTERNAL
  74649. /* ===========================================================================
  74650. Compresses the source buffer into the destination buffer. The level
  74651. parameter has the same meaning as in deflateInit. sourceLen is the byte
  74652. length of the source buffer. Upon entry, destLen is the total size of the
  74653. destination buffer, which must be at least 0.1% larger than sourceLen plus
  74654. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  74655. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74656. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  74657. Z_STREAM_ERROR if the level parameter is invalid.
  74658. */
  74659. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  74660. uLong sourceLen, int level)
  74661. {
  74662. z_stream stream;
  74663. int err;
  74664. stream.next_in = (Bytef*)source;
  74665. stream.avail_in = (uInt)sourceLen;
  74666. #ifdef MAXSEG_64K
  74667. /* Check for source > 64K on 16-bit machine: */
  74668. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  74669. #endif
  74670. stream.next_out = dest;
  74671. stream.avail_out = (uInt)*destLen;
  74672. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  74673. stream.zalloc = (alloc_func)0;
  74674. stream.zfree = (free_func)0;
  74675. stream.opaque = (voidpf)0;
  74676. err = deflateInit(&stream, level);
  74677. if (err != Z_OK) return err;
  74678. err = deflate(&stream, Z_FINISH);
  74679. if (err != Z_STREAM_END) {
  74680. deflateEnd(&stream);
  74681. return err == Z_OK ? Z_BUF_ERROR : err;
  74682. }
  74683. *destLen = stream.total_out;
  74684. err = deflateEnd(&stream);
  74685. return err;
  74686. }
  74687. /* ===========================================================================
  74688. */
  74689. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  74690. {
  74691. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  74692. }
  74693. /* ===========================================================================
  74694. If the default memLevel or windowBits for deflateInit() is changed, then
  74695. this function needs to be updated.
  74696. */
  74697. uLong ZEXPORT compressBound (uLong sourceLen)
  74698. {
  74699. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  74700. }
  74701. /********* End of inlined file: compress.c *********/
  74702. #undef DO1
  74703. #undef DO8
  74704. /********* Start of inlined file: crc32.c *********/
  74705. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74706. /*
  74707. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  74708. protection on the static variables used to control the first-use generation
  74709. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  74710. first call get_crc_table() to initialize the tables before allowing more than
  74711. one thread to use crc32().
  74712. */
  74713. #ifdef MAKECRCH
  74714. # include <stdio.h>
  74715. # ifndef DYNAMIC_CRC_TABLE
  74716. # define DYNAMIC_CRC_TABLE
  74717. # endif /* !DYNAMIC_CRC_TABLE */
  74718. #endif /* MAKECRCH */
  74719. /********* Start of inlined file: zutil.h *********/
  74720. /* WARNING: this file should *not* be used by applications. It is
  74721. part of the implementation of the compression library and is
  74722. subject to change. Applications should only use zlib.h.
  74723. */
  74724. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74725. #ifndef ZUTIL_H
  74726. #define ZUTIL_H
  74727. #define ZLIB_INTERNAL
  74728. #ifdef STDC
  74729. # ifndef _WIN32_WCE
  74730. # include <stddef.h>
  74731. # endif
  74732. # include <string.h>
  74733. # include <stdlib.h>
  74734. #endif
  74735. #ifdef NO_ERRNO_H
  74736. # ifdef _WIN32_WCE
  74737. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  74738. * errno. We define it as a global variable to simplify porting.
  74739. * Its value is always 0 and should not be used. We rename it to
  74740. * avoid conflict with other libraries that use the same workaround.
  74741. */
  74742. # define errno z_errno
  74743. # endif
  74744. extern int errno;
  74745. #else
  74746. # ifndef _WIN32_WCE
  74747. # include <errno.h>
  74748. # endif
  74749. #endif
  74750. #ifndef local
  74751. # define local static
  74752. #endif
  74753. /* compile with -Dlocal if your debugger can't find static symbols */
  74754. typedef unsigned char uch;
  74755. typedef uch FAR uchf;
  74756. typedef unsigned short ush;
  74757. typedef ush FAR ushf;
  74758. typedef unsigned long ulg;
  74759. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  74760. /* (size given to avoid silly warnings with Visual C++) */
  74761. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  74762. #define ERR_RETURN(strm,err) \
  74763. return (strm->msg = (char*)ERR_MSG(err), (err))
  74764. /* To be used only when the state is known to be valid */
  74765. /* common constants */
  74766. #ifndef DEF_WBITS
  74767. # define DEF_WBITS MAX_WBITS
  74768. #endif
  74769. /* default windowBits for decompression. MAX_WBITS is for compression only */
  74770. #if MAX_MEM_LEVEL >= 8
  74771. # define DEF_MEM_LEVEL 8
  74772. #else
  74773. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  74774. #endif
  74775. /* default memLevel */
  74776. #define STORED_BLOCK 0
  74777. #define STATIC_TREES 1
  74778. #define DYN_TREES 2
  74779. /* The three kinds of block type */
  74780. #define MIN_MATCH 3
  74781. #define MAX_MATCH 258
  74782. /* The minimum and maximum match lengths */
  74783. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  74784. /* target dependencies */
  74785. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  74786. # define OS_CODE 0x00
  74787. # if defined(__TURBOC__) || defined(__BORLANDC__)
  74788. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  74789. /* Allow compilation with ANSI keywords only enabled */
  74790. void _Cdecl farfree( void *block );
  74791. void *_Cdecl farmalloc( unsigned long nbytes );
  74792. # else
  74793. # include <alloc.h>
  74794. # endif
  74795. # else /* MSC or DJGPP */
  74796. # include <malloc.h>
  74797. # endif
  74798. #endif
  74799. #ifdef AMIGA
  74800. # define OS_CODE 0x01
  74801. #endif
  74802. #if defined(VAXC) || defined(VMS)
  74803. # define OS_CODE 0x02
  74804. # define F_OPEN(name, mode) \
  74805. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  74806. #endif
  74807. #if defined(ATARI) || defined(atarist)
  74808. # define OS_CODE 0x05
  74809. #endif
  74810. #ifdef OS2
  74811. # define OS_CODE 0x06
  74812. # ifdef M_I86
  74813. #include <malloc.h>
  74814. # endif
  74815. #endif
  74816. #if defined(MACOS) || TARGET_OS_MAC
  74817. # define OS_CODE 0x07
  74818. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  74819. # include <unix.h> /* for fdopen */
  74820. # else
  74821. # ifndef fdopen
  74822. # define fdopen(fd,mode) NULL /* No fdopen() */
  74823. # endif
  74824. # endif
  74825. #endif
  74826. #ifdef TOPS20
  74827. # define OS_CODE 0x0a
  74828. #endif
  74829. #ifdef WIN32
  74830. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  74831. # define OS_CODE 0x0b
  74832. # endif
  74833. #endif
  74834. #ifdef __50SERIES /* Prime/PRIMOS */
  74835. # define OS_CODE 0x0f
  74836. #endif
  74837. #if defined(_BEOS_) || defined(RISCOS)
  74838. # define fdopen(fd,mode) NULL /* No fdopen() */
  74839. #endif
  74840. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  74841. # if defined(_WIN32_WCE)
  74842. # define fdopen(fd,mode) NULL /* No fdopen() */
  74843. # ifndef _PTRDIFF_T_DEFINED
  74844. typedef int ptrdiff_t;
  74845. # define _PTRDIFF_T_DEFINED
  74846. # endif
  74847. # else
  74848. # define fdopen(fd,type) _fdopen(fd,type)
  74849. # endif
  74850. #endif
  74851. /* common defaults */
  74852. #ifndef OS_CODE
  74853. # define OS_CODE 0x03 /* assume Unix */
  74854. #endif
  74855. #ifndef F_OPEN
  74856. # define F_OPEN(name, mode) fopen((name), (mode))
  74857. #endif
  74858. /* functions */
  74859. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  74860. # ifndef HAVE_VSNPRINTF
  74861. # define HAVE_VSNPRINTF
  74862. # endif
  74863. #endif
  74864. #if defined(__CYGWIN__)
  74865. # ifndef HAVE_VSNPRINTF
  74866. # define HAVE_VSNPRINTF
  74867. # endif
  74868. #endif
  74869. #ifndef HAVE_VSNPRINTF
  74870. # ifdef MSDOS
  74871. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  74872. but for now we just assume it doesn't. */
  74873. # define NO_vsnprintf
  74874. # endif
  74875. # ifdef __TURBOC__
  74876. # define NO_vsnprintf
  74877. # endif
  74878. # ifdef WIN32
  74879. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  74880. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  74881. # define vsnprintf _vsnprintf
  74882. # endif
  74883. # endif
  74884. # ifdef __SASC
  74885. # define NO_vsnprintf
  74886. # endif
  74887. #endif
  74888. #ifdef VMS
  74889. # define NO_vsnprintf
  74890. #endif
  74891. #if defined(pyr)
  74892. # define NO_MEMCPY
  74893. #endif
  74894. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  74895. /* Use our own functions for small and medium model with MSC <= 5.0.
  74896. * You may have to use the same strategy for Borland C (untested).
  74897. * The __SC__ check is for Symantec.
  74898. */
  74899. # define NO_MEMCPY
  74900. #endif
  74901. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  74902. # define HAVE_MEMCPY
  74903. #endif
  74904. #ifdef HAVE_MEMCPY
  74905. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  74906. # define zmemcpy _fmemcpy
  74907. # define zmemcmp _fmemcmp
  74908. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  74909. # else
  74910. # define zmemcpy memcpy
  74911. # define zmemcmp memcmp
  74912. # define zmemzero(dest, len) memset(dest, 0, len)
  74913. # endif
  74914. #else
  74915. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  74916. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  74917. extern void zmemzero OF((Bytef* dest, uInt len));
  74918. #endif
  74919. /* Diagnostic functions */
  74920. #ifdef DEBUG
  74921. # include <stdio.h>
  74922. extern int z_verbose;
  74923. extern void z_error OF((const char *m));
  74924. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  74925. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  74926. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  74927. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  74928. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  74929. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  74930. #else
  74931. # define Assert(cond,msg)
  74932. # define Trace(x)
  74933. # define Tracev(x)
  74934. # define Tracevv(x)
  74935. # define Tracec(c,x)
  74936. # define Tracecv(c,x)
  74937. #endif
  74938. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  74939. void zcfree OF((voidpf opaque, voidpf ptr));
  74940. #define ZALLOC(strm, items, size) \
  74941. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  74942. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  74943. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  74944. #endif /* ZUTIL_H */
  74945. /********* End of inlined file: zutil.h *********/
  74946. /* for STDC and FAR definitions */
  74947. #define local static
  74948. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  74949. #ifndef NOBYFOUR
  74950. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  74951. # include <limits.h>
  74952. # define BYFOUR
  74953. # if (UINT_MAX == 0xffffffffUL)
  74954. typedef unsigned int u4;
  74955. # else
  74956. # if (ULONG_MAX == 0xffffffffUL)
  74957. typedef unsigned long u4;
  74958. # else
  74959. # if (USHRT_MAX == 0xffffffffUL)
  74960. typedef unsigned short u4;
  74961. # else
  74962. # undef BYFOUR /* can't find a four-byte integer type! */
  74963. # endif
  74964. # endif
  74965. # endif
  74966. # endif /* STDC */
  74967. #endif /* !NOBYFOUR */
  74968. /* Definitions for doing the crc four data bytes at a time. */
  74969. #ifdef BYFOUR
  74970. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  74971. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  74972. local unsigned long crc32_little OF((unsigned long,
  74973. const unsigned char FAR *, unsigned));
  74974. local unsigned long crc32_big OF((unsigned long,
  74975. const unsigned char FAR *, unsigned));
  74976. # define TBLS 8
  74977. #else
  74978. # define TBLS 1
  74979. #endif /* BYFOUR */
  74980. /* Local functions for crc concatenation */
  74981. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  74982. unsigned long vec));
  74983. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  74984. #ifdef DYNAMIC_CRC_TABLE
  74985. local volatile int crc_table_empty = 1;
  74986. local unsigned long FAR crc_table[TBLS][256];
  74987. local void make_crc_table OF((void));
  74988. #ifdef MAKECRCH
  74989. local void write_table OF((FILE *, const unsigned long FAR *));
  74990. #endif /* MAKECRCH */
  74991. /*
  74992. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  74993. 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.
  74994. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  74995. with the lowest powers in the most significant bit. Then adding polynomials
  74996. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  74997. one. If we call the above polynomial p, and represent a byte as the
  74998. polynomial q, also with the lowest power in the most significant bit (so the
  74999. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  75000. where a mod b means the remainder after dividing a by b.
  75001. This calculation is done using the shift-register method of multiplying and
  75002. taking the remainder. The register is initialized to zero, and for each
  75003. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  75004. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  75005. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  75006. out is a one). We start with the highest power (least significant bit) of
  75007. q and repeat for all eight bits of q.
  75008. The first table is simply the CRC of all possible eight bit values. This is
  75009. all the information needed to generate CRCs on data a byte at a time for all
  75010. combinations of CRC register values and incoming bytes. The remaining tables
  75011. allow for word-at-a-time CRC calculation for both big-endian and little-
  75012. endian machines, where a word is four bytes.
  75013. */
  75014. local void make_crc_table()
  75015. {
  75016. unsigned long c;
  75017. int n, k;
  75018. unsigned long poly; /* polynomial exclusive-or pattern */
  75019. /* terms of polynomial defining this crc (except x^32): */
  75020. static volatile int first = 1; /* flag to limit concurrent making */
  75021. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  75022. /* See if another task is already doing this (not thread-safe, but better
  75023. than nothing -- significantly reduces duration of vulnerability in
  75024. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  75025. if (first) {
  75026. first = 0;
  75027. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  75028. poly = 0UL;
  75029. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  75030. poly |= 1UL << (31 - p[n]);
  75031. /* generate a crc for every 8-bit value */
  75032. for (n = 0; n < 256; n++) {
  75033. c = (unsigned long)n;
  75034. for (k = 0; k < 8; k++)
  75035. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  75036. crc_table[0][n] = c;
  75037. }
  75038. #ifdef BYFOUR
  75039. /* generate crc for each value followed by one, two, and three zeros,
  75040. and then the byte reversal of those as well as the first table */
  75041. for (n = 0; n < 256; n++) {
  75042. c = crc_table[0][n];
  75043. crc_table[4][n] = REV(c);
  75044. for (k = 1; k < 4; k++) {
  75045. c = crc_table[0][c & 0xff] ^ (c >> 8);
  75046. crc_table[k][n] = c;
  75047. crc_table[k + 4][n] = REV(c);
  75048. }
  75049. }
  75050. #endif /* BYFOUR */
  75051. crc_table_empty = 0;
  75052. }
  75053. else { /* not first */
  75054. /* wait for the other guy to finish (not efficient, but rare) */
  75055. while (crc_table_empty)
  75056. ;
  75057. }
  75058. #ifdef MAKECRCH
  75059. /* write out CRC tables to crc32.h */
  75060. {
  75061. FILE *out;
  75062. out = fopen("crc32.h", "w");
  75063. if (out == NULL) return;
  75064. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  75065. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  75066. fprintf(out, "local const unsigned long FAR ");
  75067. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  75068. write_table(out, crc_table[0]);
  75069. # ifdef BYFOUR
  75070. fprintf(out, "#ifdef BYFOUR\n");
  75071. for (k = 1; k < 8; k++) {
  75072. fprintf(out, " },\n {\n");
  75073. write_table(out, crc_table[k]);
  75074. }
  75075. fprintf(out, "#endif\n");
  75076. # endif /* BYFOUR */
  75077. fprintf(out, " }\n};\n");
  75078. fclose(out);
  75079. }
  75080. #endif /* MAKECRCH */
  75081. }
  75082. #ifdef MAKECRCH
  75083. local void write_table(out, table)
  75084. FILE *out;
  75085. const unsigned long FAR *table;
  75086. {
  75087. int n;
  75088. for (n = 0; n < 256; n++)
  75089. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  75090. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  75091. }
  75092. #endif /* MAKECRCH */
  75093. #else /* !DYNAMIC_CRC_TABLE */
  75094. /* ========================================================================
  75095. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  75096. */
  75097. /********* Start of inlined file: crc32.h *********/
  75098. local const unsigned long FAR crc_table[TBLS][256] =
  75099. {
  75100. {
  75101. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  75102. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  75103. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  75104. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  75105. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  75106. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  75107. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  75108. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  75109. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  75110. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  75111. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  75112. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  75113. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  75114. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  75115. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  75116. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  75117. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  75118. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  75119. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  75120. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  75121. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  75122. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  75123. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  75124. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  75125. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  75126. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  75127. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  75128. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  75129. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  75130. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  75131. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  75132. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  75133. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  75134. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  75135. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  75136. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  75137. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  75138. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  75139. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  75140. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  75141. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  75142. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  75143. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  75144. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  75145. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  75146. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  75147. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  75148. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  75149. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  75150. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  75151. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  75152. 0x2d02ef8dUL
  75153. #ifdef BYFOUR
  75154. },
  75155. {
  75156. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  75157. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  75158. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  75159. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  75160. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  75161. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  75162. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  75163. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  75164. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  75165. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  75166. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  75167. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  75168. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  75169. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  75170. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  75171. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  75172. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  75173. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  75174. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  75175. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  75176. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  75177. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  75178. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  75179. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  75180. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  75181. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  75182. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  75183. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  75184. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  75185. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  75186. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  75187. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  75188. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  75189. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  75190. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  75191. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  75192. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  75193. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  75194. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  75195. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  75196. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  75197. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  75198. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  75199. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  75200. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  75201. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  75202. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  75203. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  75204. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  75205. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  75206. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  75207. 0x9324fd72UL
  75208. },
  75209. {
  75210. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  75211. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  75212. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  75213. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  75214. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  75215. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  75216. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  75217. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  75218. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  75219. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  75220. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  75221. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  75222. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  75223. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  75224. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  75225. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  75226. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  75227. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  75228. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  75229. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  75230. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  75231. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  75232. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  75233. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  75234. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  75235. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  75236. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  75237. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  75238. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  75239. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  75240. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  75241. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  75242. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  75243. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  75244. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  75245. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  75246. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  75247. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  75248. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  75249. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  75250. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  75251. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  75252. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  75253. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  75254. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  75255. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  75256. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  75257. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  75258. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  75259. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  75260. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  75261. 0xbe9834edUL
  75262. },
  75263. {
  75264. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  75265. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  75266. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  75267. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  75268. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  75269. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  75270. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  75271. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  75272. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  75273. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  75274. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  75275. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  75276. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  75277. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  75278. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  75279. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  75280. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  75281. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  75282. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  75283. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  75284. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  75285. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  75286. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  75287. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  75288. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  75289. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  75290. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  75291. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  75292. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  75293. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  75294. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  75295. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  75296. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  75297. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  75298. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  75299. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  75300. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  75301. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  75302. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  75303. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  75304. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  75305. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  75306. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  75307. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  75308. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  75309. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  75310. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  75311. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  75312. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  75313. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  75314. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  75315. 0xde0506f1UL
  75316. },
  75317. {
  75318. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  75319. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  75320. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  75321. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  75322. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  75323. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  75324. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  75325. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  75326. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  75327. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  75328. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  75329. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  75330. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  75331. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  75332. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  75333. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  75334. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  75335. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  75336. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  75337. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  75338. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  75339. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  75340. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  75341. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  75342. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  75343. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  75344. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  75345. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  75346. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  75347. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  75348. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  75349. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  75350. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  75351. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  75352. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  75353. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  75354. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  75355. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  75356. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  75357. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  75358. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  75359. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  75360. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  75361. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  75362. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  75363. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  75364. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  75365. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  75366. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  75367. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  75368. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  75369. 0x8def022dUL
  75370. },
  75371. {
  75372. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  75373. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  75374. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  75375. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  75376. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  75377. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  75378. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  75379. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  75380. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  75381. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  75382. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  75383. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  75384. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  75385. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  75386. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  75387. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  75388. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  75389. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  75390. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  75391. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  75392. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  75393. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  75394. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  75395. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  75396. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  75397. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  75398. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  75399. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  75400. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  75401. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  75402. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  75403. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  75404. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  75405. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  75406. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  75407. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  75408. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  75409. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  75410. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  75411. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  75412. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  75413. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  75414. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  75415. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  75416. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  75417. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  75418. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  75419. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  75420. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  75421. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  75422. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  75423. 0x72fd2493UL
  75424. },
  75425. {
  75426. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  75427. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  75428. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  75429. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  75430. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  75431. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  75432. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  75433. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  75434. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  75435. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  75436. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  75437. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  75438. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  75439. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  75440. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  75441. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  75442. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  75443. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  75444. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  75445. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  75446. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  75447. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  75448. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  75449. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  75450. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  75451. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  75452. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  75453. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  75454. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  75455. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  75456. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  75457. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  75458. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  75459. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  75460. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  75461. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  75462. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  75463. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  75464. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  75465. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  75466. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  75467. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  75468. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  75469. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  75470. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  75471. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  75472. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  75473. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  75474. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  75475. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  75476. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  75477. 0xed3498beUL
  75478. },
  75479. {
  75480. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  75481. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  75482. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  75483. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  75484. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  75485. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  75486. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  75487. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  75488. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  75489. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  75490. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  75491. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  75492. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  75493. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  75494. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  75495. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  75496. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  75497. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  75498. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  75499. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  75500. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  75501. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  75502. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  75503. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  75504. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  75505. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  75506. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  75507. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  75508. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  75509. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  75510. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  75511. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  75512. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  75513. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  75514. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  75515. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  75516. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  75517. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  75518. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  75519. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  75520. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  75521. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  75522. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  75523. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  75524. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  75525. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  75526. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  75527. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  75528. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  75529. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  75530. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  75531. 0xf10605deUL
  75532. #endif
  75533. }
  75534. };
  75535. /********* End of inlined file: crc32.h *********/
  75536. #endif /* DYNAMIC_CRC_TABLE */
  75537. /* =========================================================================
  75538. * This function can be used by asm versions of crc32()
  75539. */
  75540. const unsigned long FAR * ZEXPORT get_crc_table()
  75541. {
  75542. #ifdef DYNAMIC_CRC_TABLE
  75543. if (crc_table_empty)
  75544. make_crc_table();
  75545. #endif /* DYNAMIC_CRC_TABLE */
  75546. return (const unsigned long FAR *)crc_table;
  75547. }
  75548. /* ========================================================================= */
  75549. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  75550. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  75551. /* ========================================================================= */
  75552. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  75553. {
  75554. if (buf == Z_NULL) return 0UL;
  75555. #ifdef DYNAMIC_CRC_TABLE
  75556. if (crc_table_empty)
  75557. make_crc_table();
  75558. #endif /* DYNAMIC_CRC_TABLE */
  75559. #ifdef BYFOUR
  75560. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  75561. u4 endian;
  75562. endian = 1;
  75563. if (*((unsigned char *)(&endian)))
  75564. return crc32_little(crc, buf, len);
  75565. else
  75566. return crc32_big(crc, buf, len);
  75567. }
  75568. #endif /* BYFOUR */
  75569. crc = crc ^ 0xffffffffUL;
  75570. while (len >= 8) {
  75571. DO8;
  75572. len -= 8;
  75573. }
  75574. if (len) do {
  75575. DO1;
  75576. } while (--len);
  75577. return crc ^ 0xffffffffUL;
  75578. }
  75579. #ifdef BYFOUR
  75580. /* ========================================================================= */
  75581. #define DOLIT4 c ^= *buf4++; \
  75582. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  75583. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  75584. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  75585. /* ========================================================================= */
  75586. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  75587. {
  75588. register u4 c;
  75589. register const u4 FAR *buf4;
  75590. c = (u4)crc;
  75591. c = ~c;
  75592. while (len && ((ptrdiff_t)buf & 3)) {
  75593. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  75594. len--;
  75595. }
  75596. buf4 = (const u4 FAR *)(const void FAR *)buf;
  75597. while (len >= 32) {
  75598. DOLIT32;
  75599. len -= 32;
  75600. }
  75601. while (len >= 4) {
  75602. DOLIT4;
  75603. len -= 4;
  75604. }
  75605. buf = (const unsigned char FAR *)buf4;
  75606. if (len) do {
  75607. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  75608. } while (--len);
  75609. c = ~c;
  75610. return (unsigned long)c;
  75611. }
  75612. /* ========================================================================= */
  75613. #define DOBIG4 c ^= *++buf4; \
  75614. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  75615. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  75616. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  75617. /* ========================================================================= */
  75618. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  75619. {
  75620. register u4 c;
  75621. register const u4 FAR *buf4;
  75622. c = REV((u4)crc);
  75623. c = ~c;
  75624. while (len && ((ptrdiff_t)buf & 3)) {
  75625. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  75626. len--;
  75627. }
  75628. buf4 = (const u4 FAR *)(const void FAR *)buf;
  75629. buf4--;
  75630. while (len >= 32) {
  75631. DOBIG32;
  75632. len -= 32;
  75633. }
  75634. while (len >= 4) {
  75635. DOBIG4;
  75636. len -= 4;
  75637. }
  75638. buf4++;
  75639. buf = (const unsigned char FAR *)buf4;
  75640. if (len) do {
  75641. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  75642. } while (--len);
  75643. c = ~c;
  75644. return (unsigned long)(REV(c));
  75645. }
  75646. #endif /* BYFOUR */
  75647. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  75648. /* ========================================================================= */
  75649. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  75650. {
  75651. unsigned long sum;
  75652. sum = 0;
  75653. while (vec) {
  75654. if (vec & 1)
  75655. sum ^= *mat;
  75656. vec >>= 1;
  75657. mat++;
  75658. }
  75659. return sum;
  75660. }
  75661. /* ========================================================================= */
  75662. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  75663. {
  75664. int n;
  75665. for (n = 0; n < GF2_DIM; n++)
  75666. square[n] = gf2_matrix_times(mat, mat[n]);
  75667. }
  75668. /* ========================================================================= */
  75669. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  75670. {
  75671. int n;
  75672. unsigned long row;
  75673. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  75674. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  75675. /* degenerate case */
  75676. if (len2 == 0)
  75677. return crc1;
  75678. /* put operator for one zero bit in odd */
  75679. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  75680. row = 1;
  75681. for (n = 1; n < GF2_DIM; n++) {
  75682. odd[n] = row;
  75683. row <<= 1;
  75684. }
  75685. /* put operator for two zero bits in even */
  75686. gf2_matrix_square(even, odd);
  75687. /* put operator for four zero bits in odd */
  75688. gf2_matrix_square(odd, even);
  75689. /* apply len2 zeros to crc1 (first square will put the operator for one
  75690. zero byte, eight zero bits, in even) */
  75691. do {
  75692. /* apply zeros operator for this bit of len2 */
  75693. gf2_matrix_square(even, odd);
  75694. if (len2 & 1)
  75695. crc1 = gf2_matrix_times(even, crc1);
  75696. len2 >>= 1;
  75697. /* if no more bits set, then done */
  75698. if (len2 == 0)
  75699. break;
  75700. /* another iteration of the loop with odd and even swapped */
  75701. gf2_matrix_square(odd, even);
  75702. if (len2 & 1)
  75703. crc1 = gf2_matrix_times(odd, crc1);
  75704. len2 >>= 1;
  75705. /* if no more bits set, then done */
  75706. } while (len2 != 0);
  75707. /* return combined crc */
  75708. crc1 ^= crc2;
  75709. return crc1;
  75710. }
  75711. /********* End of inlined file: crc32.c *********/
  75712. /********* Start of inlined file: deflate.c *********/
  75713. /*
  75714. * ALGORITHM
  75715. *
  75716. * The "deflation" process depends on being able to identify portions
  75717. * of the input text which are identical to earlier input (within a
  75718. * sliding window trailing behind the input currently being processed).
  75719. *
  75720. * The most straightforward technique turns out to be the fastest for
  75721. * most input files: try all possible matches and select the longest.
  75722. * The key feature of this algorithm is that insertions into the string
  75723. * dictionary are very simple and thus fast, and deletions are avoided
  75724. * completely. Insertions are performed at each input character, whereas
  75725. * string matches are performed only when the previous match ends. So it
  75726. * is preferable to spend more time in matches to allow very fast string
  75727. * insertions and avoid deletions. The matching algorithm for small
  75728. * strings is inspired from that of Rabin & Karp. A brute force approach
  75729. * is used to find longer strings when a small match has been found.
  75730. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  75731. * (by Leonid Broukhis).
  75732. * A previous version of this file used a more sophisticated algorithm
  75733. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  75734. * time, but has a larger average cost, uses more memory and is patented.
  75735. * However the F&G algorithm may be faster for some highly redundant
  75736. * files if the parameter max_chain_length (described below) is too large.
  75737. *
  75738. * ACKNOWLEDGEMENTS
  75739. *
  75740. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  75741. * I found it in 'freeze' written by Leonid Broukhis.
  75742. * Thanks to many people for bug reports and testing.
  75743. *
  75744. * REFERENCES
  75745. *
  75746. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  75747. * Available in http://www.ietf.org/rfc/rfc1951.txt
  75748. *
  75749. * A description of the Rabin and Karp algorithm is given in the book
  75750. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  75751. *
  75752. * Fiala,E.R., and Greene,D.H.
  75753. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  75754. *
  75755. */
  75756. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75757. /********* Start of inlined file: deflate.h *********/
  75758. /* WARNING: this file should *not* be used by applications. It is
  75759. part of the implementation of the compression library and is
  75760. subject to change. Applications should only use zlib.h.
  75761. */
  75762. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75763. #ifndef DEFLATE_H
  75764. #define DEFLATE_H
  75765. /* define NO_GZIP when compiling if you want to disable gzip header and
  75766. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  75767. the crc code when it is not needed. For shared libraries, gzip encoding
  75768. should be left enabled. */
  75769. #ifndef NO_GZIP
  75770. # define GZIP
  75771. #endif
  75772. #define NO_DUMMY_DECL
  75773. /* ===========================================================================
  75774. * Internal compression state.
  75775. */
  75776. #define LENGTH_CODES 29
  75777. /* number of length codes, not counting the special END_BLOCK code */
  75778. #define LITERALS 256
  75779. /* number of literal bytes 0..255 */
  75780. #define L_CODES (LITERALS+1+LENGTH_CODES)
  75781. /* number of Literal or Length codes, including the END_BLOCK code */
  75782. #define D_CODES 30
  75783. /* number of distance codes */
  75784. #define BL_CODES 19
  75785. /* number of codes used to transfer the bit lengths */
  75786. #define HEAP_SIZE (2*L_CODES+1)
  75787. /* maximum heap size */
  75788. #define MAX_BITS 15
  75789. /* All codes must not exceed MAX_BITS bits */
  75790. #define INIT_STATE 42
  75791. #define EXTRA_STATE 69
  75792. #define NAME_STATE 73
  75793. #define COMMENT_STATE 91
  75794. #define HCRC_STATE 103
  75795. #define BUSY_STATE 113
  75796. #define FINISH_STATE 666
  75797. /* Stream status */
  75798. /* Data structure describing a single value and its code string. */
  75799. typedef struct ct_data_s {
  75800. union {
  75801. ush freq; /* frequency count */
  75802. ush code; /* bit string */
  75803. } fc;
  75804. union {
  75805. ush dad; /* father node in Huffman tree */
  75806. ush len; /* length of bit string */
  75807. } dl;
  75808. } FAR ct_data;
  75809. #define Freq fc.freq
  75810. #define Code fc.code
  75811. #define Dad dl.dad
  75812. #define Len dl.len
  75813. typedef struct static_tree_desc_s static_tree_desc;
  75814. typedef struct tree_desc_s {
  75815. ct_data *dyn_tree; /* the dynamic tree */
  75816. int max_code; /* largest code with non zero frequency */
  75817. static_tree_desc *stat_desc; /* the corresponding static tree */
  75818. } FAR tree_desc;
  75819. typedef ush Pos;
  75820. typedef Pos FAR Posf;
  75821. typedef unsigned IPos;
  75822. /* A Pos is an index in the character window. We use short instead of int to
  75823. * save space in the various tables. IPos is used only for parameter passing.
  75824. */
  75825. typedef struct internal_state {
  75826. z_streamp strm; /* pointer back to this zlib stream */
  75827. int status; /* as the name implies */
  75828. Bytef *pending_buf; /* output still pending */
  75829. ulg pending_buf_size; /* size of pending_buf */
  75830. Bytef *pending_out; /* next pending byte to output to the stream */
  75831. uInt pending; /* nb of bytes in the pending buffer */
  75832. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  75833. gz_headerp gzhead; /* gzip header information to write */
  75834. uInt gzindex; /* where in extra, name, or comment */
  75835. Byte method; /* STORED (for zip only) or DEFLATED */
  75836. int last_flush; /* value of flush param for previous deflate call */
  75837. /* used by deflate.c: */
  75838. uInt w_size; /* LZ77 window size (32K by default) */
  75839. uInt w_bits; /* log2(w_size) (8..16) */
  75840. uInt w_mask; /* w_size - 1 */
  75841. Bytef *window;
  75842. /* Sliding window. Input bytes are read into the second half of the window,
  75843. * and move to the first half later to keep a dictionary of at least wSize
  75844. * bytes. With this organization, matches are limited to a distance of
  75845. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  75846. * performed with a length multiple of the block size. Also, it limits
  75847. * the window size to 64K, which is quite useful on MSDOS.
  75848. * To do: use the user input buffer as sliding window.
  75849. */
  75850. ulg window_size;
  75851. /* Actual size of window: 2*wSize, except when the user input buffer
  75852. * is directly used as sliding window.
  75853. */
  75854. Posf *prev;
  75855. /* Link to older string with same hash index. To limit the size of this
  75856. * array to 64K, this link is maintained only for the last 32K strings.
  75857. * An index in this array is thus a window index modulo 32K.
  75858. */
  75859. Posf *head; /* Heads of the hash chains or NIL. */
  75860. uInt ins_h; /* hash index of string to be inserted */
  75861. uInt hash_size; /* number of elements in hash table */
  75862. uInt hash_bits; /* log2(hash_size) */
  75863. uInt hash_mask; /* hash_size-1 */
  75864. uInt hash_shift;
  75865. /* Number of bits by which ins_h must be shifted at each input
  75866. * step. It must be such that after MIN_MATCH steps, the oldest
  75867. * byte no longer takes part in the hash key, that is:
  75868. * hash_shift * MIN_MATCH >= hash_bits
  75869. */
  75870. long block_start;
  75871. /* Window position at the beginning of the current output block. Gets
  75872. * negative when the window is moved backwards.
  75873. */
  75874. uInt match_length; /* length of best match */
  75875. IPos prev_match; /* previous match */
  75876. int match_available; /* set if previous match exists */
  75877. uInt strstart; /* start of string to insert */
  75878. uInt match_start; /* start of matching string */
  75879. uInt lookahead; /* number of valid bytes ahead in window */
  75880. uInt prev_length;
  75881. /* Length of the best match at previous step. Matches not greater than this
  75882. * are discarded. This is used in the lazy match evaluation.
  75883. */
  75884. uInt max_chain_length;
  75885. /* To speed up deflation, hash chains are never searched beyond this
  75886. * length. A higher limit improves compression ratio but degrades the
  75887. * speed.
  75888. */
  75889. uInt max_lazy_match;
  75890. /* Attempt to find a better match only when the current match is strictly
  75891. * smaller than this value. This mechanism is used only for compression
  75892. * levels >= 4.
  75893. */
  75894. # define max_insert_length max_lazy_match
  75895. /* Insert new strings in the hash table only if the match length is not
  75896. * greater than this length. This saves time but degrades compression.
  75897. * max_insert_length is used only for compression levels <= 3.
  75898. */
  75899. int level; /* compression level (1..9) */
  75900. int strategy; /* favor or force Huffman coding*/
  75901. uInt good_match;
  75902. /* Use a faster search when the previous match is longer than this */
  75903. int nice_match; /* Stop searching when current match exceeds this */
  75904. /* used by trees.c: */
  75905. /* Didn't use ct_data typedef below to supress compiler warning */
  75906. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  75907. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  75908. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  75909. struct tree_desc_s l_desc; /* desc. for literal tree */
  75910. struct tree_desc_s d_desc; /* desc. for distance tree */
  75911. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  75912. ush bl_count[MAX_BITS+1];
  75913. /* number of codes at each bit length for an optimal tree */
  75914. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  75915. int heap_len; /* number of elements in the heap */
  75916. int heap_max; /* element of largest frequency */
  75917. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  75918. * The same heap array is used to build all trees.
  75919. */
  75920. uch depth[2*L_CODES+1];
  75921. /* Depth of each subtree used as tie breaker for trees of equal frequency
  75922. */
  75923. uchf *l_buf; /* buffer for literals or lengths */
  75924. uInt lit_bufsize;
  75925. /* Size of match buffer for literals/lengths. There are 4 reasons for
  75926. * limiting lit_bufsize to 64K:
  75927. * - frequencies can be kept in 16 bit counters
  75928. * - if compression is not successful for the first block, all input
  75929. * data is still in the window so we can still emit a stored block even
  75930. * when input comes from standard input. (This can also be done for
  75931. * all blocks if lit_bufsize is not greater than 32K.)
  75932. * - if compression is not successful for a file smaller than 64K, we can
  75933. * even emit a stored file instead of a stored block (saving 5 bytes).
  75934. * This is applicable only for zip (not gzip or zlib).
  75935. * - creating new Huffman trees less frequently may not provide fast
  75936. * adaptation to changes in the input data statistics. (Take for
  75937. * example a binary file with poorly compressible code followed by
  75938. * a highly compressible string table.) Smaller buffer sizes give
  75939. * fast adaptation but have of course the overhead of transmitting
  75940. * trees more frequently.
  75941. * - I can't count above 4
  75942. */
  75943. uInt last_lit; /* running index in l_buf */
  75944. ushf *d_buf;
  75945. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  75946. * the same number of elements. To use different lengths, an extra flag
  75947. * array would be necessary.
  75948. */
  75949. ulg opt_len; /* bit length of current block with optimal trees */
  75950. ulg static_len; /* bit length of current block with static trees */
  75951. uInt matches; /* number of string matches in current block */
  75952. int last_eob_len; /* bit length of EOB code for last block */
  75953. #ifdef DEBUG
  75954. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  75955. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  75956. #endif
  75957. ush bi_buf;
  75958. /* Output buffer. bits are inserted starting at the bottom (least
  75959. * significant bits).
  75960. */
  75961. int bi_valid;
  75962. /* Number of valid bits in bi_buf. All bits above the last valid bit
  75963. * are always zero.
  75964. */
  75965. } FAR deflate_state;
  75966. /* Output a byte on the stream.
  75967. * IN assertion: there is enough room in pending_buf.
  75968. */
  75969. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  75970. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  75971. /* Minimum amount of lookahead, except at the end of the input file.
  75972. * See deflate.c for comments about the MIN_MATCH+1.
  75973. */
  75974. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  75975. /* In order to simplify the code, particularly on 16 bit machines, match
  75976. * distances are limited to MAX_DIST instead of WSIZE.
  75977. */
  75978. /* in trees.c */
  75979. void _tr_init OF((deflate_state *s));
  75980. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  75981. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  75982. int eof));
  75983. void _tr_align OF((deflate_state *s));
  75984. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  75985. int eof));
  75986. #define d_code(dist) \
  75987. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  75988. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  75989. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  75990. * used.
  75991. */
  75992. #ifndef DEBUG
  75993. /* Inline versions of _tr_tally for speed: */
  75994. #if defined(GEN_TREES_H) || !defined(STDC)
  75995. extern uch _length_code[];
  75996. extern uch _dist_code[];
  75997. #else
  75998. extern const uch _length_code[];
  75999. extern const uch _dist_code[];
  76000. #endif
  76001. # define _tr_tally_lit(s, c, flush) \
  76002. { uch cc = (c); \
  76003. s->d_buf[s->last_lit] = 0; \
  76004. s->l_buf[s->last_lit++] = cc; \
  76005. s->dyn_ltree[cc].Freq++; \
  76006. flush = (s->last_lit == s->lit_bufsize-1); \
  76007. }
  76008. # define _tr_tally_dist(s, distance, length, flush) \
  76009. { uch len = (length); \
  76010. ush dist = (distance); \
  76011. s->d_buf[s->last_lit] = dist; \
  76012. s->l_buf[s->last_lit++] = len; \
  76013. dist--; \
  76014. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  76015. s->dyn_dtree[d_code(dist)].Freq++; \
  76016. flush = (s->last_lit == s->lit_bufsize-1); \
  76017. }
  76018. #else
  76019. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  76020. # define _tr_tally_dist(s, distance, length, flush) \
  76021. flush = _tr_tally(s, distance, length)
  76022. #endif
  76023. #endif /* DEFLATE_H */
  76024. /********* End of inlined file: deflate.h *********/
  76025. const char deflate_copyright[] =
  76026. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  76027. /*
  76028. If you use the zlib library in a product, an acknowledgment is welcome
  76029. in the documentation of your product. If for some reason you cannot
  76030. include such an acknowledgment, I would appreciate that you keep this
  76031. copyright string in the executable of your product.
  76032. */
  76033. /* ===========================================================================
  76034. * Function prototypes.
  76035. */
  76036. typedef enum {
  76037. need_more, /* block not completed, need more input or more output */
  76038. block_done, /* block flush performed */
  76039. finish_started, /* finish started, need only more output at next deflate */
  76040. finish_done /* finish done, accept no more input or output */
  76041. } block_state;
  76042. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  76043. /* Compression function. Returns the block state after the call. */
  76044. local void fill_window OF((deflate_state *s));
  76045. local block_state deflate_stored OF((deflate_state *s, int flush));
  76046. local block_state deflate_fast OF((deflate_state *s, int flush));
  76047. #ifndef FASTEST
  76048. local block_state deflate_slow OF((deflate_state *s, int flush));
  76049. #endif
  76050. local void lm_init OF((deflate_state *s));
  76051. local void putShortMSB OF((deflate_state *s, uInt b));
  76052. local void flush_pending OF((z_streamp strm));
  76053. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  76054. #ifndef FASTEST
  76055. #ifdef ASMV
  76056. void match_init OF((void)); /* asm code initialization */
  76057. uInt longest_match OF((deflate_state *s, IPos cur_match));
  76058. #else
  76059. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  76060. #endif
  76061. #endif
  76062. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  76063. #ifdef DEBUG
  76064. local void check_match OF((deflate_state *s, IPos start, IPos match,
  76065. int length));
  76066. #endif
  76067. /* ===========================================================================
  76068. * Local data
  76069. */
  76070. #define NIL 0
  76071. /* Tail of hash chains */
  76072. #ifndef TOO_FAR
  76073. # define TOO_FAR 4096
  76074. #endif
  76075. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  76076. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  76077. /* Minimum amount of lookahead, except at the end of the input file.
  76078. * See deflate.c for comments about the MIN_MATCH+1.
  76079. */
  76080. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  76081. * the desired pack level (0..9). The values given below have been tuned to
  76082. * exclude worst case performance for pathological files. Better values may be
  76083. * found for specific files.
  76084. */
  76085. typedef struct config_s {
  76086. ush good_length; /* reduce lazy search above this match length */
  76087. ush max_lazy; /* do not perform lazy search above this match length */
  76088. ush nice_length; /* quit search above this match length */
  76089. ush max_chain;
  76090. compress_func func;
  76091. } config;
  76092. #ifdef FASTEST
  76093. local const config configuration_table[2] = {
  76094. /* good lazy nice chain */
  76095. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  76096. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  76097. #else
  76098. local const config configuration_table[10] = {
  76099. /* good lazy nice chain */
  76100. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  76101. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  76102. /* 2 */ {4, 5, 16, 8, deflate_fast},
  76103. /* 3 */ {4, 6, 32, 32, deflate_fast},
  76104. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  76105. /* 5 */ {8, 16, 32, 32, deflate_slow},
  76106. /* 6 */ {8, 16, 128, 128, deflate_slow},
  76107. /* 7 */ {8, 32, 128, 256, deflate_slow},
  76108. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  76109. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  76110. #endif
  76111. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  76112. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  76113. * meaning.
  76114. */
  76115. #define EQUAL 0
  76116. /* result of memcmp for equal strings */
  76117. #ifndef NO_DUMMY_DECL
  76118. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  76119. #endif
  76120. /* ===========================================================================
  76121. * Update a hash value with the given input byte
  76122. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  76123. * input characters, so that a running hash key can be computed from the
  76124. * previous key instead of complete recalculation each time.
  76125. */
  76126. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  76127. /* ===========================================================================
  76128. * Insert string str in the dictionary and set match_head to the previous head
  76129. * of the hash chain (the most recent string with same hash key). Return
  76130. * the previous length of the hash chain.
  76131. * If this file is compiled with -DFASTEST, the compression level is forced
  76132. * to 1, and no hash chains are maintained.
  76133. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  76134. * input characters and the first MIN_MATCH bytes of str are valid
  76135. * (except for the last MIN_MATCH-1 bytes of the input file).
  76136. */
  76137. #ifdef FASTEST
  76138. #define INSERT_STRING(s, str, match_head) \
  76139. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  76140. match_head = s->head[s->ins_h], \
  76141. s->head[s->ins_h] = (Pos)(str))
  76142. #else
  76143. #define INSERT_STRING(s, str, match_head) \
  76144. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  76145. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  76146. s->head[s->ins_h] = (Pos)(str))
  76147. #endif
  76148. /* ===========================================================================
  76149. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  76150. * prev[] will be initialized on the fly.
  76151. */
  76152. #define CLEAR_HASH(s) \
  76153. s->head[s->hash_size-1] = NIL; \
  76154. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  76155. /* ========================================================================= */
  76156. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  76157. {
  76158. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  76159. Z_DEFAULT_STRATEGY, version, stream_size);
  76160. /* To do: ignore strm->next_in if we use it as window */
  76161. }
  76162. /* ========================================================================= */
  76163. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  76164. {
  76165. deflate_state *s;
  76166. int wrap = 1;
  76167. static const char my_version[] = ZLIB_VERSION;
  76168. ushf *overlay;
  76169. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  76170. * output size for (length,distance) codes is <= 24 bits.
  76171. */
  76172. if (version == Z_NULL || version[0] != my_version[0] ||
  76173. stream_size != sizeof(z_stream)) {
  76174. return Z_VERSION_ERROR;
  76175. }
  76176. if (strm == Z_NULL) return Z_STREAM_ERROR;
  76177. strm->msg = Z_NULL;
  76178. if (strm->zalloc == (alloc_func)0) {
  76179. strm->zalloc = zcalloc;
  76180. strm->opaque = (voidpf)0;
  76181. }
  76182. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  76183. #ifdef FASTEST
  76184. if (level != 0) level = 1;
  76185. #else
  76186. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  76187. #endif
  76188. if (windowBits < 0) { /* suppress zlib wrapper */
  76189. wrap = 0;
  76190. windowBits = -windowBits;
  76191. }
  76192. #ifdef GZIP
  76193. else if (windowBits > 15) {
  76194. wrap = 2; /* write gzip wrapper instead */
  76195. windowBits -= 16;
  76196. }
  76197. #endif
  76198. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  76199. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  76200. strategy < 0 || strategy > Z_FIXED) {
  76201. return Z_STREAM_ERROR;
  76202. }
  76203. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  76204. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  76205. if (s == Z_NULL) return Z_MEM_ERROR;
  76206. strm->state = (struct internal_state FAR *)s;
  76207. s->strm = strm;
  76208. s->wrap = wrap;
  76209. s->gzhead = Z_NULL;
  76210. s->w_bits = windowBits;
  76211. s->w_size = 1 << s->w_bits;
  76212. s->w_mask = s->w_size - 1;
  76213. s->hash_bits = memLevel + 7;
  76214. s->hash_size = 1 << s->hash_bits;
  76215. s->hash_mask = s->hash_size - 1;
  76216. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  76217. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  76218. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  76219. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  76220. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  76221. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  76222. s->pending_buf = (uchf *) overlay;
  76223. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  76224. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  76225. s->pending_buf == Z_NULL) {
  76226. s->status = FINISH_STATE;
  76227. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  76228. deflateEnd (strm);
  76229. return Z_MEM_ERROR;
  76230. }
  76231. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  76232. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  76233. s->level = level;
  76234. s->strategy = strategy;
  76235. s->method = (Byte)method;
  76236. return deflateReset(strm);
  76237. }
  76238. /* ========================================================================= */
  76239. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  76240. {
  76241. deflate_state *s;
  76242. uInt length = dictLength;
  76243. uInt n;
  76244. IPos hash_head = 0;
  76245. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  76246. strm->state->wrap == 2 ||
  76247. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  76248. return Z_STREAM_ERROR;
  76249. s = strm->state;
  76250. if (s->wrap)
  76251. strm->adler = adler32(strm->adler, dictionary, dictLength);
  76252. if (length < MIN_MATCH) return Z_OK;
  76253. if (length > MAX_DIST(s)) {
  76254. length = MAX_DIST(s);
  76255. dictionary += dictLength - length; /* use the tail of the dictionary */
  76256. }
  76257. zmemcpy(s->window, dictionary, length);
  76258. s->strstart = length;
  76259. s->block_start = (long)length;
  76260. /* Insert all strings in the hash table (except for the last two bytes).
  76261. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  76262. * call of fill_window.
  76263. */
  76264. s->ins_h = s->window[0];
  76265. UPDATE_HASH(s, s->ins_h, s->window[1]);
  76266. for (n = 0; n <= length - MIN_MATCH; n++) {
  76267. INSERT_STRING(s, n, hash_head);
  76268. }
  76269. if (hash_head) hash_head = 0; /* to make compiler happy */
  76270. return Z_OK;
  76271. }
  76272. /* ========================================================================= */
  76273. int ZEXPORT deflateReset (z_streamp strm)
  76274. {
  76275. deflate_state *s;
  76276. if (strm == Z_NULL || strm->state == Z_NULL ||
  76277. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  76278. return Z_STREAM_ERROR;
  76279. }
  76280. strm->total_in = strm->total_out = 0;
  76281. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  76282. strm->data_type = Z_UNKNOWN;
  76283. s = (deflate_state *)strm->state;
  76284. s->pending = 0;
  76285. s->pending_out = s->pending_buf;
  76286. if (s->wrap < 0) {
  76287. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  76288. }
  76289. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  76290. strm->adler =
  76291. #ifdef GZIP
  76292. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  76293. #endif
  76294. adler32(0L, Z_NULL, 0);
  76295. s->last_flush = Z_NO_FLUSH;
  76296. _tr_init(s);
  76297. lm_init(s);
  76298. return Z_OK;
  76299. }
  76300. /* ========================================================================= */
  76301. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  76302. {
  76303. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76304. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  76305. strm->state->gzhead = head;
  76306. return Z_OK;
  76307. }
  76308. /* ========================================================================= */
  76309. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  76310. {
  76311. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76312. strm->state->bi_valid = bits;
  76313. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  76314. return Z_OK;
  76315. }
  76316. /* ========================================================================= */
  76317. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  76318. {
  76319. deflate_state *s;
  76320. compress_func func;
  76321. int err = Z_OK;
  76322. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76323. s = strm->state;
  76324. #ifdef FASTEST
  76325. if (level != 0) level = 1;
  76326. #else
  76327. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  76328. #endif
  76329. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  76330. return Z_STREAM_ERROR;
  76331. }
  76332. func = configuration_table[s->level].func;
  76333. if (func != configuration_table[level].func && strm->total_in != 0) {
  76334. /* Flush the last buffer: */
  76335. err = deflate(strm, Z_PARTIAL_FLUSH);
  76336. }
  76337. if (s->level != level) {
  76338. s->level = level;
  76339. s->max_lazy_match = configuration_table[level].max_lazy;
  76340. s->good_match = configuration_table[level].good_length;
  76341. s->nice_match = configuration_table[level].nice_length;
  76342. s->max_chain_length = configuration_table[level].max_chain;
  76343. }
  76344. s->strategy = strategy;
  76345. return err;
  76346. }
  76347. /* ========================================================================= */
  76348. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  76349. {
  76350. deflate_state *s;
  76351. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76352. s = strm->state;
  76353. s->good_match = good_length;
  76354. s->max_lazy_match = max_lazy;
  76355. s->nice_match = nice_length;
  76356. s->max_chain_length = max_chain;
  76357. return Z_OK;
  76358. }
  76359. /* =========================================================================
  76360. * For the default windowBits of 15 and memLevel of 8, this function returns
  76361. * a close to exact, as well as small, upper bound on the compressed size.
  76362. * They are coded as constants here for a reason--if the #define's are
  76363. * changed, then this function needs to be changed as well. The return
  76364. * value for 15 and 8 only works for those exact settings.
  76365. *
  76366. * For any setting other than those defaults for windowBits and memLevel,
  76367. * the value returned is a conservative worst case for the maximum expansion
  76368. * resulting from using fixed blocks instead of stored blocks, which deflate
  76369. * can emit on compressed data for some combinations of the parameters.
  76370. *
  76371. * This function could be more sophisticated to provide closer upper bounds
  76372. * for every combination of windowBits and memLevel, as well as wrap.
  76373. * But even the conservative upper bound of about 14% expansion does not
  76374. * seem onerous for output buffer allocation.
  76375. */
  76376. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  76377. {
  76378. deflate_state *s;
  76379. uLong destLen;
  76380. /* conservative upper bound */
  76381. destLen = sourceLen +
  76382. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  76383. /* if can't get parameters, return conservative bound */
  76384. if (strm == Z_NULL || strm->state == Z_NULL)
  76385. return destLen;
  76386. /* if not default parameters, return conservative bound */
  76387. s = strm->state;
  76388. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  76389. return destLen;
  76390. /* default settings: return tight bound for that case */
  76391. return compressBound(sourceLen);
  76392. }
  76393. /* =========================================================================
  76394. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  76395. * IN assertion: the stream state is correct and there is enough room in
  76396. * pending_buf.
  76397. */
  76398. local void putShortMSB (deflate_state *s, uInt b)
  76399. {
  76400. put_byte(s, (Byte)(b >> 8));
  76401. put_byte(s, (Byte)(b & 0xff));
  76402. }
  76403. /* =========================================================================
  76404. * Flush as much pending output as possible. All deflate() output goes
  76405. * through this function so some applications may wish to modify it
  76406. * to avoid allocating a large strm->next_out buffer and copying into it.
  76407. * (See also read_buf()).
  76408. */
  76409. local void flush_pending (z_streamp strm)
  76410. {
  76411. unsigned len = strm->state->pending;
  76412. if (len > strm->avail_out) len = strm->avail_out;
  76413. if (len == 0) return;
  76414. zmemcpy(strm->next_out, strm->state->pending_out, len);
  76415. strm->next_out += len;
  76416. strm->state->pending_out += len;
  76417. strm->total_out += len;
  76418. strm->avail_out -= len;
  76419. strm->state->pending -= len;
  76420. if (strm->state->pending == 0) {
  76421. strm->state->pending_out = strm->state->pending_buf;
  76422. }
  76423. }
  76424. /* ========================================================================= */
  76425. int ZEXPORT deflate (z_streamp strm, int flush)
  76426. {
  76427. int old_flush; /* value of flush param for previous deflate call */
  76428. deflate_state *s;
  76429. if (strm == Z_NULL || strm->state == Z_NULL ||
  76430. flush > Z_FINISH || flush < 0) {
  76431. return Z_STREAM_ERROR;
  76432. }
  76433. s = strm->state;
  76434. if (strm->next_out == Z_NULL ||
  76435. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  76436. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  76437. ERR_RETURN(strm, Z_STREAM_ERROR);
  76438. }
  76439. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  76440. s->strm = strm; /* just in case */
  76441. old_flush = s->last_flush;
  76442. s->last_flush = flush;
  76443. /* Write the header */
  76444. if (s->status == INIT_STATE) {
  76445. #ifdef GZIP
  76446. if (s->wrap == 2) {
  76447. strm->adler = crc32(0L, Z_NULL, 0);
  76448. put_byte(s, 31);
  76449. put_byte(s, 139);
  76450. put_byte(s, 8);
  76451. if (s->gzhead == NULL) {
  76452. put_byte(s, 0);
  76453. put_byte(s, 0);
  76454. put_byte(s, 0);
  76455. put_byte(s, 0);
  76456. put_byte(s, 0);
  76457. put_byte(s, s->level == 9 ? 2 :
  76458. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  76459. 4 : 0));
  76460. put_byte(s, OS_CODE);
  76461. s->status = BUSY_STATE;
  76462. }
  76463. else {
  76464. put_byte(s, (s->gzhead->text ? 1 : 0) +
  76465. (s->gzhead->hcrc ? 2 : 0) +
  76466. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  76467. (s->gzhead->name == Z_NULL ? 0 : 8) +
  76468. (s->gzhead->comment == Z_NULL ? 0 : 16)
  76469. );
  76470. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  76471. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  76472. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  76473. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  76474. put_byte(s, s->level == 9 ? 2 :
  76475. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  76476. 4 : 0));
  76477. put_byte(s, s->gzhead->os & 0xff);
  76478. if (s->gzhead->extra != NULL) {
  76479. put_byte(s, s->gzhead->extra_len & 0xff);
  76480. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  76481. }
  76482. if (s->gzhead->hcrc)
  76483. strm->adler = crc32(strm->adler, s->pending_buf,
  76484. s->pending);
  76485. s->gzindex = 0;
  76486. s->status = EXTRA_STATE;
  76487. }
  76488. }
  76489. else
  76490. #endif
  76491. {
  76492. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  76493. uInt level_flags;
  76494. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  76495. level_flags = 0;
  76496. else if (s->level < 6)
  76497. level_flags = 1;
  76498. else if (s->level == 6)
  76499. level_flags = 2;
  76500. else
  76501. level_flags = 3;
  76502. header |= (level_flags << 6);
  76503. if (s->strstart != 0) header |= PRESET_DICT;
  76504. header += 31 - (header % 31);
  76505. s->status = BUSY_STATE;
  76506. putShortMSB(s, header);
  76507. /* Save the adler32 of the preset dictionary: */
  76508. if (s->strstart != 0) {
  76509. putShortMSB(s, (uInt)(strm->adler >> 16));
  76510. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  76511. }
  76512. strm->adler = adler32(0L, Z_NULL, 0);
  76513. }
  76514. }
  76515. #ifdef GZIP
  76516. if (s->status == EXTRA_STATE) {
  76517. if (s->gzhead->extra != NULL) {
  76518. uInt beg = s->pending; /* start of bytes to update crc */
  76519. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  76520. if (s->pending == s->pending_buf_size) {
  76521. if (s->gzhead->hcrc && s->pending > beg)
  76522. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  76523. s->pending - beg);
  76524. flush_pending(strm);
  76525. beg = s->pending;
  76526. if (s->pending == s->pending_buf_size)
  76527. break;
  76528. }
  76529. put_byte(s, s->gzhead->extra[s->gzindex]);
  76530. s->gzindex++;
  76531. }
  76532. if (s->gzhead->hcrc && s->pending > beg)
  76533. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  76534. s->pending - beg);
  76535. if (s->gzindex == s->gzhead->extra_len) {
  76536. s->gzindex = 0;
  76537. s->status = NAME_STATE;
  76538. }
  76539. }
  76540. else
  76541. s->status = NAME_STATE;
  76542. }
  76543. if (s->status == NAME_STATE) {
  76544. if (s->gzhead->name != NULL) {
  76545. uInt beg = s->pending; /* start of bytes to update crc */
  76546. int val;
  76547. do {
  76548. if (s->pending == s->pending_buf_size) {
  76549. if (s->gzhead->hcrc && s->pending > beg)
  76550. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  76551. s->pending - beg);
  76552. flush_pending(strm);
  76553. beg = s->pending;
  76554. if (s->pending == s->pending_buf_size) {
  76555. val = 1;
  76556. break;
  76557. }
  76558. }
  76559. val = s->gzhead->name[s->gzindex++];
  76560. put_byte(s, val);
  76561. } while (val != 0);
  76562. if (s->gzhead->hcrc && s->pending > beg)
  76563. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  76564. s->pending - beg);
  76565. if (val == 0) {
  76566. s->gzindex = 0;
  76567. s->status = COMMENT_STATE;
  76568. }
  76569. }
  76570. else
  76571. s->status = COMMENT_STATE;
  76572. }
  76573. if (s->status == COMMENT_STATE) {
  76574. if (s->gzhead->comment != NULL) {
  76575. uInt beg = s->pending; /* start of bytes to update crc */
  76576. int val;
  76577. do {
  76578. if (s->pending == s->pending_buf_size) {
  76579. if (s->gzhead->hcrc && s->pending > beg)
  76580. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  76581. s->pending - beg);
  76582. flush_pending(strm);
  76583. beg = s->pending;
  76584. if (s->pending == s->pending_buf_size) {
  76585. val = 1;
  76586. break;
  76587. }
  76588. }
  76589. val = s->gzhead->comment[s->gzindex++];
  76590. put_byte(s, val);
  76591. } while (val != 0);
  76592. if (s->gzhead->hcrc && s->pending > beg)
  76593. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  76594. s->pending - beg);
  76595. if (val == 0)
  76596. s->status = HCRC_STATE;
  76597. }
  76598. else
  76599. s->status = HCRC_STATE;
  76600. }
  76601. if (s->status == HCRC_STATE) {
  76602. if (s->gzhead->hcrc) {
  76603. if (s->pending + 2 > s->pending_buf_size)
  76604. flush_pending(strm);
  76605. if (s->pending + 2 <= s->pending_buf_size) {
  76606. put_byte(s, (Byte)(strm->adler & 0xff));
  76607. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  76608. strm->adler = crc32(0L, Z_NULL, 0);
  76609. s->status = BUSY_STATE;
  76610. }
  76611. }
  76612. else
  76613. s->status = BUSY_STATE;
  76614. }
  76615. #endif
  76616. /* Flush as much pending output as possible */
  76617. if (s->pending != 0) {
  76618. flush_pending(strm);
  76619. if (strm->avail_out == 0) {
  76620. /* Since avail_out is 0, deflate will be called again with
  76621. * more output space, but possibly with both pending and
  76622. * avail_in equal to zero. There won't be anything to do,
  76623. * but this is not an error situation so make sure we
  76624. * return OK instead of BUF_ERROR at next call of deflate:
  76625. */
  76626. s->last_flush = -1;
  76627. return Z_OK;
  76628. }
  76629. /* Make sure there is something to do and avoid duplicate consecutive
  76630. * flushes. For repeated and useless calls with Z_FINISH, we keep
  76631. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  76632. */
  76633. } else if (strm->avail_in == 0 && flush <= old_flush &&
  76634. flush != Z_FINISH) {
  76635. ERR_RETURN(strm, Z_BUF_ERROR);
  76636. }
  76637. /* User must not provide more input after the first FINISH: */
  76638. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  76639. ERR_RETURN(strm, Z_BUF_ERROR);
  76640. }
  76641. /* Start a new block or continue the current one.
  76642. */
  76643. if (strm->avail_in != 0 || s->lookahead != 0 ||
  76644. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  76645. block_state bstate;
  76646. bstate = (*(configuration_table[s->level].func))(s, flush);
  76647. if (bstate == finish_started || bstate == finish_done) {
  76648. s->status = FINISH_STATE;
  76649. }
  76650. if (bstate == need_more || bstate == finish_started) {
  76651. if (strm->avail_out == 0) {
  76652. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  76653. }
  76654. return Z_OK;
  76655. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  76656. * of deflate should use the same flush parameter to make sure
  76657. * that the flush is complete. So we don't have to output an
  76658. * empty block here, this will be done at next call. This also
  76659. * ensures that for a very small output buffer, we emit at most
  76660. * one empty block.
  76661. */
  76662. }
  76663. if (bstate == block_done) {
  76664. if (flush == Z_PARTIAL_FLUSH) {
  76665. _tr_align(s);
  76666. } else { /* FULL_FLUSH or SYNC_FLUSH */
  76667. _tr_stored_block(s, (char*)0, 0L, 0);
  76668. /* For a full flush, this empty block will be recognized
  76669. * as a special marker by inflate_sync().
  76670. */
  76671. if (flush == Z_FULL_FLUSH) {
  76672. CLEAR_HASH(s); /* forget history */
  76673. }
  76674. }
  76675. flush_pending(strm);
  76676. if (strm->avail_out == 0) {
  76677. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  76678. return Z_OK;
  76679. }
  76680. }
  76681. }
  76682. Assert(strm->avail_out > 0, "bug2");
  76683. if (flush != Z_FINISH) return Z_OK;
  76684. if (s->wrap <= 0) return Z_STREAM_END;
  76685. /* Write the trailer */
  76686. #ifdef GZIP
  76687. if (s->wrap == 2) {
  76688. put_byte(s, (Byte)(strm->adler & 0xff));
  76689. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  76690. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  76691. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  76692. put_byte(s, (Byte)(strm->total_in & 0xff));
  76693. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  76694. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  76695. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  76696. }
  76697. else
  76698. #endif
  76699. {
  76700. putShortMSB(s, (uInt)(strm->adler >> 16));
  76701. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  76702. }
  76703. flush_pending(strm);
  76704. /* If avail_out is zero, the application will call deflate again
  76705. * to flush the rest.
  76706. */
  76707. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  76708. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  76709. }
  76710. /* ========================================================================= */
  76711. int ZEXPORT deflateEnd (z_streamp strm)
  76712. {
  76713. int status;
  76714. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76715. status = strm->state->status;
  76716. if (status != INIT_STATE &&
  76717. status != EXTRA_STATE &&
  76718. status != NAME_STATE &&
  76719. status != COMMENT_STATE &&
  76720. status != HCRC_STATE &&
  76721. status != BUSY_STATE &&
  76722. status != FINISH_STATE) {
  76723. return Z_STREAM_ERROR;
  76724. }
  76725. /* Deallocate in reverse order of allocations: */
  76726. TRY_FREE(strm, strm->state->pending_buf);
  76727. TRY_FREE(strm, strm->state->head);
  76728. TRY_FREE(strm, strm->state->prev);
  76729. TRY_FREE(strm, strm->state->window);
  76730. ZFREE(strm, strm->state);
  76731. strm->state = Z_NULL;
  76732. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  76733. }
  76734. /* =========================================================================
  76735. * Copy the source state to the destination state.
  76736. * To simplify the source, this is not supported for 16-bit MSDOS (which
  76737. * doesn't have enough memory anyway to duplicate compression states).
  76738. */
  76739. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  76740. {
  76741. #ifdef MAXSEG_64K
  76742. return Z_STREAM_ERROR;
  76743. #else
  76744. deflate_state *ds;
  76745. deflate_state *ss;
  76746. ushf *overlay;
  76747. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  76748. return Z_STREAM_ERROR;
  76749. }
  76750. ss = source->state;
  76751. zmemcpy(dest, source, sizeof(z_stream));
  76752. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  76753. if (ds == Z_NULL) return Z_MEM_ERROR;
  76754. dest->state = (struct internal_state FAR *) ds;
  76755. zmemcpy(ds, ss, sizeof(deflate_state));
  76756. ds->strm = dest;
  76757. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  76758. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  76759. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  76760. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  76761. ds->pending_buf = (uchf *) overlay;
  76762. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  76763. ds->pending_buf == Z_NULL) {
  76764. deflateEnd (dest);
  76765. return Z_MEM_ERROR;
  76766. }
  76767. /* following zmemcpy do not work for 16-bit MSDOS */
  76768. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  76769. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  76770. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  76771. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  76772. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  76773. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  76774. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  76775. ds->l_desc.dyn_tree = ds->dyn_ltree;
  76776. ds->d_desc.dyn_tree = ds->dyn_dtree;
  76777. ds->bl_desc.dyn_tree = ds->bl_tree;
  76778. return Z_OK;
  76779. #endif /* MAXSEG_64K */
  76780. }
  76781. /* ===========================================================================
  76782. * Read a new buffer from the current input stream, update the adler32
  76783. * and total number of bytes read. All deflate() input goes through
  76784. * this function so some applications may wish to modify it to avoid
  76785. * allocating a large strm->next_in buffer and copying from it.
  76786. * (See also flush_pending()).
  76787. */
  76788. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  76789. {
  76790. unsigned len = strm->avail_in;
  76791. if (len > size) len = size;
  76792. if (len == 0) return 0;
  76793. strm->avail_in -= len;
  76794. if (strm->state->wrap == 1) {
  76795. strm->adler = adler32(strm->adler, strm->next_in, len);
  76796. }
  76797. #ifdef GZIP
  76798. else if (strm->state->wrap == 2) {
  76799. strm->adler = crc32(strm->adler, strm->next_in, len);
  76800. }
  76801. #endif
  76802. zmemcpy(buf, strm->next_in, len);
  76803. strm->next_in += len;
  76804. strm->total_in += len;
  76805. return (int)len;
  76806. }
  76807. /* ===========================================================================
  76808. * Initialize the "longest match" routines for a new zlib stream
  76809. */
  76810. local void lm_init (deflate_state *s)
  76811. {
  76812. s->window_size = (ulg)2L*s->w_size;
  76813. CLEAR_HASH(s);
  76814. /* Set the default configuration parameters:
  76815. */
  76816. s->max_lazy_match = configuration_table[s->level].max_lazy;
  76817. s->good_match = configuration_table[s->level].good_length;
  76818. s->nice_match = configuration_table[s->level].nice_length;
  76819. s->max_chain_length = configuration_table[s->level].max_chain;
  76820. s->strstart = 0;
  76821. s->block_start = 0L;
  76822. s->lookahead = 0;
  76823. s->match_length = s->prev_length = MIN_MATCH-1;
  76824. s->match_available = 0;
  76825. s->ins_h = 0;
  76826. #ifndef FASTEST
  76827. #ifdef ASMV
  76828. match_init(); /* initialize the asm code */
  76829. #endif
  76830. #endif
  76831. }
  76832. #ifndef FASTEST
  76833. /* ===========================================================================
  76834. * Set match_start to the longest match starting at the given string and
  76835. * return its length. Matches shorter or equal to prev_length are discarded,
  76836. * in which case the result is equal to prev_length and match_start is
  76837. * garbage.
  76838. * IN assertions: cur_match is the head of the hash chain for the current
  76839. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  76840. * OUT assertion: the match length is not greater than s->lookahead.
  76841. */
  76842. #ifndef ASMV
  76843. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  76844. * match.S. The code will be functionally equivalent.
  76845. */
  76846. local uInt longest_match(deflate_state *s, IPos cur_match)
  76847. {
  76848. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  76849. register Bytef *scan = s->window + s->strstart; /* current string */
  76850. register Bytef *match; /* matched string */
  76851. register int len; /* length of current match */
  76852. int best_len = s->prev_length; /* best match length so far */
  76853. int nice_match = s->nice_match; /* stop if match long enough */
  76854. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  76855. s->strstart - (IPos)MAX_DIST(s) : NIL;
  76856. /* Stop when cur_match becomes <= limit. To simplify the code,
  76857. * we prevent matches with the string of window index 0.
  76858. */
  76859. Posf *prev = s->prev;
  76860. uInt wmask = s->w_mask;
  76861. #ifdef UNALIGNED_OK
  76862. /* Compare two bytes at a time. Note: this is not always beneficial.
  76863. * Try with and without -DUNALIGNED_OK to check.
  76864. */
  76865. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  76866. register ush scan_start = *(ushf*)scan;
  76867. register ush scan_end = *(ushf*)(scan+best_len-1);
  76868. #else
  76869. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  76870. register Byte scan_end1 = scan[best_len-1];
  76871. register Byte scan_end = scan[best_len];
  76872. #endif
  76873. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  76874. * It is easy to get rid of this optimization if necessary.
  76875. */
  76876. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  76877. /* Do not waste too much time if we already have a good match: */
  76878. if (s->prev_length >= s->good_match) {
  76879. chain_length >>= 2;
  76880. }
  76881. /* Do not look for matches beyond the end of the input. This is necessary
  76882. * to make deflate deterministic.
  76883. */
  76884. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  76885. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  76886. do {
  76887. Assert(cur_match < s->strstart, "no future");
  76888. match = s->window + cur_match;
  76889. /* Skip to next match if the match length cannot increase
  76890. * or if the match length is less than 2. Note that the checks below
  76891. * for insufficient lookahead only occur occasionally for performance
  76892. * reasons. Therefore uninitialized memory will be accessed, and
  76893. * conditional jumps will be made that depend on those values.
  76894. * However the length of the match is limited to the lookahead, so
  76895. * the output of deflate is not affected by the uninitialized values.
  76896. */
  76897. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  76898. /* This code assumes sizeof(unsigned short) == 2. Do not use
  76899. * UNALIGNED_OK if your compiler uses a different size.
  76900. */
  76901. if (*(ushf*)(match+best_len-1) != scan_end ||
  76902. *(ushf*)match != scan_start) continue;
  76903. /* It is not necessary to compare scan[2] and match[2] since they are
  76904. * always equal when the other bytes match, given that the hash keys
  76905. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  76906. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  76907. * lookahead only every 4th comparison; the 128th check will be made
  76908. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  76909. * necessary to put more guard bytes at the end of the window, or
  76910. * to check more often for insufficient lookahead.
  76911. */
  76912. Assert(scan[2] == match[2], "scan[2]?");
  76913. scan++, match++;
  76914. do {
  76915. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  76916. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  76917. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  76918. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  76919. scan < strend);
  76920. /* The funny "do {}" generates better code on most compilers */
  76921. /* Here, scan <= window+strstart+257 */
  76922. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  76923. if (*scan == *match) scan++;
  76924. len = (MAX_MATCH - 1) - (int)(strend-scan);
  76925. scan = strend - (MAX_MATCH-1);
  76926. #else /* UNALIGNED_OK */
  76927. if (match[best_len] != scan_end ||
  76928. match[best_len-1] != scan_end1 ||
  76929. *match != *scan ||
  76930. *++match != scan[1]) continue;
  76931. /* The check at best_len-1 can be removed because it will be made
  76932. * again later. (This heuristic is not always a win.)
  76933. * It is not necessary to compare scan[2] and match[2] since they
  76934. * are always equal when the other bytes match, given that
  76935. * the hash keys are equal and that HASH_BITS >= 8.
  76936. */
  76937. scan += 2, match++;
  76938. Assert(*scan == *match, "match[2]?");
  76939. /* We check for insufficient lookahead only every 8th comparison;
  76940. * the 256th check will be made at strstart+258.
  76941. */
  76942. do {
  76943. } while (*++scan == *++match && *++scan == *++match &&
  76944. *++scan == *++match && *++scan == *++match &&
  76945. *++scan == *++match && *++scan == *++match &&
  76946. *++scan == *++match && *++scan == *++match &&
  76947. scan < strend);
  76948. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  76949. len = MAX_MATCH - (int)(strend - scan);
  76950. scan = strend - MAX_MATCH;
  76951. #endif /* UNALIGNED_OK */
  76952. if (len > best_len) {
  76953. s->match_start = cur_match;
  76954. best_len = len;
  76955. if (len >= nice_match) break;
  76956. #ifdef UNALIGNED_OK
  76957. scan_end = *(ushf*)(scan+best_len-1);
  76958. #else
  76959. scan_end1 = scan[best_len-1];
  76960. scan_end = scan[best_len];
  76961. #endif
  76962. }
  76963. } while ((cur_match = prev[cur_match & wmask]) > limit
  76964. && --chain_length != 0);
  76965. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  76966. return s->lookahead;
  76967. }
  76968. #endif /* ASMV */
  76969. #endif /* FASTEST */
  76970. /* ---------------------------------------------------------------------------
  76971. * Optimized version for level == 1 or strategy == Z_RLE only
  76972. */
  76973. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  76974. {
  76975. register Bytef *scan = s->window + s->strstart; /* current string */
  76976. register Bytef *match; /* matched string */
  76977. register int len; /* length of current match */
  76978. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  76979. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  76980. * It is easy to get rid of this optimization if necessary.
  76981. */
  76982. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  76983. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  76984. Assert(cur_match < s->strstart, "no future");
  76985. match = s->window + cur_match;
  76986. /* Return failure if the match length is less than 2:
  76987. */
  76988. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  76989. /* The check at best_len-1 can be removed because it will be made
  76990. * again later. (This heuristic is not always a win.)
  76991. * It is not necessary to compare scan[2] and match[2] since they
  76992. * are always equal when the other bytes match, given that
  76993. * the hash keys are equal and that HASH_BITS >= 8.
  76994. */
  76995. scan += 2, match += 2;
  76996. Assert(*scan == *match, "match[2]?");
  76997. /* We check for insufficient lookahead only every 8th comparison;
  76998. * the 256th check will be made at strstart+258.
  76999. */
  77000. do {
  77001. } while (*++scan == *++match && *++scan == *++match &&
  77002. *++scan == *++match && *++scan == *++match &&
  77003. *++scan == *++match && *++scan == *++match &&
  77004. *++scan == *++match && *++scan == *++match &&
  77005. scan < strend);
  77006. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77007. len = MAX_MATCH - (int)(strend - scan);
  77008. if (len < MIN_MATCH) return MIN_MATCH - 1;
  77009. s->match_start = cur_match;
  77010. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  77011. }
  77012. #ifdef DEBUG
  77013. /* ===========================================================================
  77014. * Check that the match at match_start is indeed a match.
  77015. */
  77016. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  77017. {
  77018. /* check that the match is indeed a match */
  77019. if (zmemcmp(s->window + match,
  77020. s->window + start, length) != EQUAL) {
  77021. fprintf(stderr, " start %u, match %u, length %d\n",
  77022. start, match, length);
  77023. do {
  77024. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  77025. } while (--length != 0);
  77026. z_error("invalid match");
  77027. }
  77028. if (z_verbose > 1) {
  77029. fprintf(stderr,"\\[%d,%d]", start-match, length);
  77030. do { putc(s->window[start++], stderr); } while (--length != 0);
  77031. }
  77032. }
  77033. #else
  77034. # define check_match(s, start, match, length)
  77035. #endif /* DEBUG */
  77036. /* ===========================================================================
  77037. * Fill the window when the lookahead becomes insufficient.
  77038. * Updates strstart and lookahead.
  77039. *
  77040. * IN assertion: lookahead < MIN_LOOKAHEAD
  77041. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  77042. * At least one byte has been read, or avail_in == 0; reads are
  77043. * performed for at least two bytes (required for the zip translate_eol
  77044. * option -- not supported here).
  77045. */
  77046. local void fill_window (deflate_state *s)
  77047. {
  77048. register unsigned n, m;
  77049. register Posf *p;
  77050. unsigned more; /* Amount of free space at the end of the window. */
  77051. uInt wsize = s->w_size;
  77052. do {
  77053. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  77054. /* Deal with !@#$% 64K limit: */
  77055. if (sizeof(int) <= 2) {
  77056. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  77057. more = wsize;
  77058. } else if (more == (unsigned)(-1)) {
  77059. /* Very unlikely, but possible on 16 bit machine if
  77060. * strstart == 0 && lookahead == 1 (input done a byte at time)
  77061. */
  77062. more--;
  77063. }
  77064. }
  77065. /* If the window is almost full and there is insufficient lookahead,
  77066. * move the upper half to the lower one to make room in the upper half.
  77067. */
  77068. if (s->strstart >= wsize+MAX_DIST(s)) {
  77069. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  77070. s->match_start -= wsize;
  77071. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  77072. s->block_start -= (long) wsize;
  77073. /* Slide the hash table (could be avoided with 32 bit values
  77074. at the expense of memory usage). We slide even when level == 0
  77075. to keep the hash table consistent if we switch back to level > 0
  77076. later. (Using level 0 permanently is not an optimal usage of
  77077. zlib, so we don't care about this pathological case.)
  77078. */
  77079. /* %%% avoid this when Z_RLE */
  77080. n = s->hash_size;
  77081. p = &s->head[n];
  77082. do {
  77083. m = *--p;
  77084. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  77085. } while (--n);
  77086. n = wsize;
  77087. #ifndef FASTEST
  77088. p = &s->prev[n];
  77089. do {
  77090. m = *--p;
  77091. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  77092. /* If n is not on any hash chain, prev[n] is garbage but
  77093. * its value will never be used.
  77094. */
  77095. } while (--n);
  77096. #endif
  77097. more += wsize;
  77098. }
  77099. if (s->strm->avail_in == 0) return;
  77100. /* If there was no sliding:
  77101. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  77102. * more == window_size - lookahead - strstart
  77103. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  77104. * => more >= window_size - 2*WSIZE + 2
  77105. * In the BIG_MEM or MMAP case (not yet supported),
  77106. * window_size == input_size + MIN_LOOKAHEAD &&
  77107. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  77108. * Otherwise, window_size == 2*WSIZE so more >= 2.
  77109. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  77110. */
  77111. Assert(more >= 2, "more < 2");
  77112. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  77113. s->lookahead += n;
  77114. /* Initialize the hash value now that we have some input: */
  77115. if (s->lookahead >= MIN_MATCH) {
  77116. s->ins_h = s->window[s->strstart];
  77117. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  77118. #if MIN_MATCH != 3
  77119. Call UPDATE_HASH() MIN_MATCH-3 more times
  77120. #endif
  77121. }
  77122. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  77123. * but this is not important since only literal bytes will be emitted.
  77124. */
  77125. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  77126. }
  77127. /* ===========================================================================
  77128. * Flush the current block, with given end-of-file flag.
  77129. * IN assertion: strstart is set to the end of the current match.
  77130. */
  77131. #define FLUSH_BLOCK_ONLY(s, eof) { \
  77132. _tr_flush_block(s, (s->block_start >= 0L ? \
  77133. (charf *)&s->window[(unsigned)s->block_start] : \
  77134. (charf *)Z_NULL), \
  77135. (ulg)((long)s->strstart - s->block_start), \
  77136. (eof)); \
  77137. s->block_start = s->strstart; \
  77138. flush_pending(s->strm); \
  77139. Tracev((stderr,"[FLUSH]")); \
  77140. }
  77141. /* Same but force premature exit if necessary. */
  77142. #define FLUSH_BLOCK(s, eof) { \
  77143. FLUSH_BLOCK_ONLY(s, eof); \
  77144. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  77145. }
  77146. /* ===========================================================================
  77147. * Copy without compression as much as possible from the input stream, return
  77148. * the current block state.
  77149. * This function does not insert new strings in the dictionary since
  77150. * uncompressible data is probably not useful. This function is used
  77151. * only for the level=0 compression option.
  77152. * NOTE: this function should be optimized to avoid extra copying from
  77153. * window to pending_buf.
  77154. */
  77155. local block_state deflate_stored(deflate_state *s, int flush)
  77156. {
  77157. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  77158. * to pending_buf_size, and each stored block has a 5 byte header:
  77159. */
  77160. ulg max_block_size = 0xffff;
  77161. ulg max_start;
  77162. if (max_block_size > s->pending_buf_size - 5) {
  77163. max_block_size = s->pending_buf_size - 5;
  77164. }
  77165. /* Copy as much as possible from input to output: */
  77166. for (;;) {
  77167. /* Fill the window as much as possible: */
  77168. if (s->lookahead <= 1) {
  77169. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  77170. s->block_start >= (long)s->w_size, "slide too late");
  77171. fill_window(s);
  77172. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  77173. if (s->lookahead == 0) break; /* flush the current block */
  77174. }
  77175. Assert(s->block_start >= 0L, "block gone");
  77176. s->strstart += s->lookahead;
  77177. s->lookahead = 0;
  77178. /* Emit a stored block if pending_buf will be full: */
  77179. max_start = s->block_start + max_block_size;
  77180. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  77181. /* strstart == 0 is possible when wraparound on 16-bit machine */
  77182. s->lookahead = (uInt)(s->strstart - max_start);
  77183. s->strstart = (uInt)max_start;
  77184. FLUSH_BLOCK(s, 0);
  77185. }
  77186. /* Flush if we may have to slide, otherwise block_start may become
  77187. * negative and the data will be gone:
  77188. */
  77189. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  77190. FLUSH_BLOCK(s, 0);
  77191. }
  77192. }
  77193. FLUSH_BLOCK(s, flush == Z_FINISH);
  77194. return flush == Z_FINISH ? finish_done : block_done;
  77195. }
  77196. /* ===========================================================================
  77197. * Compress as much as possible from the input stream, return the current
  77198. * block state.
  77199. * This function does not perform lazy evaluation of matches and inserts
  77200. * new strings in the dictionary only for unmatched strings or for short
  77201. * matches. It is used only for the fast compression options.
  77202. */
  77203. local block_state deflate_fast(deflate_state *s, int flush)
  77204. {
  77205. IPos hash_head = NIL; /* head of the hash chain */
  77206. int bflush; /* set if current block must be flushed */
  77207. for (;;) {
  77208. /* Make sure that we always have enough lookahead, except
  77209. * at the end of the input file. We need MAX_MATCH bytes
  77210. * for the next match, plus MIN_MATCH bytes to insert the
  77211. * string following the next match.
  77212. */
  77213. if (s->lookahead < MIN_LOOKAHEAD) {
  77214. fill_window(s);
  77215. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  77216. return need_more;
  77217. }
  77218. if (s->lookahead == 0) break; /* flush the current block */
  77219. }
  77220. /* Insert the string window[strstart .. strstart+2] in the
  77221. * dictionary, and set hash_head to the head of the hash chain:
  77222. */
  77223. if (s->lookahead >= MIN_MATCH) {
  77224. INSERT_STRING(s, s->strstart, hash_head);
  77225. }
  77226. /* Find the longest match, discarding those <= prev_length.
  77227. * At this point we have always match_length < MIN_MATCH
  77228. */
  77229. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  77230. /* To simplify the code, we prevent matches with the string
  77231. * of window index 0 (in particular we have to avoid a match
  77232. * of the string with itself at the start of the input file).
  77233. */
  77234. #ifdef FASTEST
  77235. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  77236. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  77237. s->match_length = longest_match_fast (s, hash_head);
  77238. }
  77239. #else
  77240. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  77241. s->match_length = longest_match (s, hash_head);
  77242. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  77243. s->match_length = longest_match_fast (s, hash_head);
  77244. }
  77245. #endif
  77246. /* longest_match() or longest_match_fast() sets match_start */
  77247. }
  77248. if (s->match_length >= MIN_MATCH) {
  77249. check_match(s, s->strstart, s->match_start, s->match_length);
  77250. _tr_tally_dist(s, s->strstart - s->match_start,
  77251. s->match_length - MIN_MATCH, bflush);
  77252. s->lookahead -= s->match_length;
  77253. /* Insert new strings in the hash table only if the match length
  77254. * is not too large. This saves time but degrades compression.
  77255. */
  77256. #ifndef FASTEST
  77257. if (s->match_length <= s->max_insert_length &&
  77258. s->lookahead >= MIN_MATCH) {
  77259. s->match_length--; /* string at strstart already in table */
  77260. do {
  77261. s->strstart++;
  77262. INSERT_STRING(s, s->strstart, hash_head);
  77263. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  77264. * always MIN_MATCH bytes ahead.
  77265. */
  77266. } while (--s->match_length != 0);
  77267. s->strstart++;
  77268. } else
  77269. #endif
  77270. {
  77271. s->strstart += s->match_length;
  77272. s->match_length = 0;
  77273. s->ins_h = s->window[s->strstart];
  77274. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  77275. #if MIN_MATCH != 3
  77276. Call UPDATE_HASH() MIN_MATCH-3 more times
  77277. #endif
  77278. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  77279. * matter since it will be recomputed at next deflate call.
  77280. */
  77281. }
  77282. } else {
  77283. /* No match, output a literal byte */
  77284. Tracevv((stderr,"%c", s->window[s->strstart]));
  77285. _tr_tally_lit (s, s->window[s->strstart], bflush);
  77286. s->lookahead--;
  77287. s->strstart++;
  77288. }
  77289. if (bflush) FLUSH_BLOCK(s, 0);
  77290. }
  77291. FLUSH_BLOCK(s, flush == Z_FINISH);
  77292. return flush == Z_FINISH ? finish_done : block_done;
  77293. }
  77294. #ifndef FASTEST
  77295. /* ===========================================================================
  77296. * Same as above, but achieves better compression. We use a lazy
  77297. * evaluation for matches: a match is finally adopted only if there is
  77298. * no better match at the next window position.
  77299. */
  77300. local block_state deflate_slow(deflate_state *s, int flush)
  77301. {
  77302. IPos hash_head = NIL; /* head of hash chain */
  77303. int bflush; /* set if current block must be flushed */
  77304. /* Process the input block. */
  77305. for (;;) {
  77306. /* Make sure that we always have enough lookahead, except
  77307. * at the end of the input file. We need MAX_MATCH bytes
  77308. * for the next match, plus MIN_MATCH bytes to insert the
  77309. * string following the next match.
  77310. */
  77311. if (s->lookahead < MIN_LOOKAHEAD) {
  77312. fill_window(s);
  77313. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  77314. return need_more;
  77315. }
  77316. if (s->lookahead == 0) break; /* flush the current block */
  77317. }
  77318. /* Insert the string window[strstart .. strstart+2] in the
  77319. * dictionary, and set hash_head to the head of the hash chain:
  77320. */
  77321. if (s->lookahead >= MIN_MATCH) {
  77322. INSERT_STRING(s, s->strstart, hash_head);
  77323. }
  77324. /* Find the longest match, discarding those <= prev_length.
  77325. */
  77326. s->prev_length = s->match_length, s->prev_match = s->match_start;
  77327. s->match_length = MIN_MATCH-1;
  77328. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  77329. s->strstart - hash_head <= MAX_DIST(s)) {
  77330. /* To simplify the code, we prevent matches with the string
  77331. * of window index 0 (in particular we have to avoid a match
  77332. * of the string with itself at the start of the input file).
  77333. */
  77334. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  77335. s->match_length = longest_match (s, hash_head);
  77336. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  77337. s->match_length = longest_match_fast (s, hash_head);
  77338. }
  77339. /* longest_match() or longest_match_fast() sets match_start */
  77340. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  77341. #if TOO_FAR <= 32767
  77342. || (s->match_length == MIN_MATCH &&
  77343. s->strstart - s->match_start > TOO_FAR)
  77344. #endif
  77345. )) {
  77346. /* If prev_match is also MIN_MATCH, match_start is garbage
  77347. * but we will ignore the current match anyway.
  77348. */
  77349. s->match_length = MIN_MATCH-1;
  77350. }
  77351. }
  77352. /* If there was a match at the previous step and the current
  77353. * match is not better, output the previous match:
  77354. */
  77355. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  77356. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  77357. /* Do not insert strings in hash table beyond this. */
  77358. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  77359. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  77360. s->prev_length - MIN_MATCH, bflush);
  77361. /* Insert in hash table all strings up to the end of the match.
  77362. * strstart-1 and strstart are already inserted. If there is not
  77363. * enough lookahead, the last two strings are not inserted in
  77364. * the hash table.
  77365. */
  77366. s->lookahead -= s->prev_length-1;
  77367. s->prev_length -= 2;
  77368. do {
  77369. if (++s->strstart <= max_insert) {
  77370. INSERT_STRING(s, s->strstart, hash_head);
  77371. }
  77372. } while (--s->prev_length != 0);
  77373. s->match_available = 0;
  77374. s->match_length = MIN_MATCH-1;
  77375. s->strstart++;
  77376. if (bflush) FLUSH_BLOCK(s, 0);
  77377. } else if (s->match_available) {
  77378. /* If there was no match at the previous position, output a
  77379. * single literal. If there was a match but the current match
  77380. * is longer, truncate the previous match to a single literal.
  77381. */
  77382. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  77383. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  77384. if (bflush) {
  77385. FLUSH_BLOCK_ONLY(s, 0);
  77386. }
  77387. s->strstart++;
  77388. s->lookahead--;
  77389. if (s->strm->avail_out == 0) return need_more;
  77390. } else {
  77391. /* There is no previous match to compare with, wait for
  77392. * the next step to decide.
  77393. */
  77394. s->match_available = 1;
  77395. s->strstart++;
  77396. s->lookahead--;
  77397. }
  77398. }
  77399. Assert (flush != Z_NO_FLUSH, "no flush?");
  77400. if (s->match_available) {
  77401. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  77402. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  77403. s->match_available = 0;
  77404. }
  77405. FLUSH_BLOCK(s, flush == Z_FINISH);
  77406. return flush == Z_FINISH ? finish_done : block_done;
  77407. }
  77408. #endif /* FASTEST */
  77409. #if 0
  77410. /* ===========================================================================
  77411. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  77412. * one. Do not maintain a hash table. (It will be regenerated if this run of
  77413. * deflate switches away from Z_RLE.)
  77414. */
  77415. local block_state deflate_rle(s, flush)
  77416. deflate_state *s;
  77417. int flush;
  77418. {
  77419. int bflush; /* set if current block must be flushed */
  77420. uInt run; /* length of run */
  77421. uInt max; /* maximum length of run */
  77422. uInt prev; /* byte at distance one to match */
  77423. Bytef *scan; /* scan for end of run */
  77424. for (;;) {
  77425. /* Make sure that we always have enough lookahead, except
  77426. * at the end of the input file. We need MAX_MATCH bytes
  77427. * for the longest encodable run.
  77428. */
  77429. if (s->lookahead < MAX_MATCH) {
  77430. fill_window(s);
  77431. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  77432. return need_more;
  77433. }
  77434. if (s->lookahead == 0) break; /* flush the current block */
  77435. }
  77436. /* See how many times the previous byte repeats */
  77437. run = 0;
  77438. if (s->strstart > 0) { /* if there is a previous byte, that is */
  77439. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  77440. scan = s->window + s->strstart - 1;
  77441. prev = *scan++;
  77442. do {
  77443. if (*scan++ != prev)
  77444. break;
  77445. } while (++run < max);
  77446. }
  77447. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  77448. if (run >= MIN_MATCH) {
  77449. check_match(s, s->strstart, s->strstart - 1, run);
  77450. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  77451. s->lookahead -= run;
  77452. s->strstart += run;
  77453. } else {
  77454. /* No match, output a literal byte */
  77455. Tracevv((stderr,"%c", s->window[s->strstart]));
  77456. _tr_tally_lit (s, s->window[s->strstart], bflush);
  77457. s->lookahead--;
  77458. s->strstart++;
  77459. }
  77460. if (bflush) FLUSH_BLOCK(s, 0);
  77461. }
  77462. FLUSH_BLOCK(s, flush == Z_FINISH);
  77463. return flush == Z_FINISH ? finish_done : block_done;
  77464. }
  77465. #endif
  77466. /********* End of inlined file: deflate.c *********/
  77467. /********* Start of inlined file: inffast.c *********/
  77468. /********* Start of inlined file: inftrees.h *********/
  77469. /* WARNING: this file should *not* be used by applications. It is
  77470. part of the implementation of the compression library and is
  77471. subject to change. Applications should only use zlib.h.
  77472. */
  77473. #ifndef _INFTREES_H_
  77474. #define _INFTREES_H_
  77475. /* Structure for decoding tables. Each entry provides either the
  77476. information needed to do the operation requested by the code that
  77477. indexed that table entry, or it provides a pointer to another
  77478. table that indexes more bits of the code. op indicates whether
  77479. the entry is a pointer to another table, a literal, a length or
  77480. distance, an end-of-block, or an invalid code. For a table
  77481. pointer, the low four bits of op is the number of index bits of
  77482. that table. For a length or distance, the low four bits of op
  77483. is the number of extra bits to get after the code. bits is
  77484. the number of bits in this code or part of the code to drop off
  77485. of the bit buffer. val is the actual byte to output in the case
  77486. of a literal, the base length or distance, or the offset from
  77487. the current table to the next table. Each entry is four bytes. */
  77488. typedef struct {
  77489. unsigned char op; /* operation, extra bits, table bits */
  77490. unsigned char bits; /* bits in this part of the code */
  77491. unsigned short val; /* offset in table or code value */
  77492. } code;
  77493. /* op values as set by inflate_table():
  77494. 00000000 - literal
  77495. 0000tttt - table link, tttt != 0 is the number of table index bits
  77496. 0001eeee - length or distance, eeee is the number of extra bits
  77497. 01100000 - end of block
  77498. 01000000 - invalid code
  77499. */
  77500. /* Maximum size of dynamic tree. The maximum found in a long but non-
  77501. exhaustive search was 1444 code structures (852 for length/literals
  77502. and 592 for distances, the latter actually the result of an
  77503. exhaustive search). The true maximum is not known, but the value
  77504. below is more than safe. */
  77505. #define ENOUGH 2048
  77506. #define MAXD 592
  77507. /* Type of code to build for inftable() */
  77508. typedef enum {
  77509. CODES,
  77510. LENS,
  77511. DISTS
  77512. } codetype;
  77513. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  77514. unsigned codes, code FAR * FAR *table,
  77515. unsigned FAR *bits, unsigned short FAR *work));
  77516. #endif
  77517. /********* End of inlined file: inftrees.h *********/
  77518. /********* Start of inlined file: inflate.h *********/
  77519. /* WARNING: this file should *not* be used by applications. It is
  77520. part of the implementation of the compression library and is
  77521. subject to change. Applications should only use zlib.h.
  77522. */
  77523. #ifndef _INFLATE_H_
  77524. #define _INFLATE_H_
  77525. /* define NO_GZIP when compiling if you want to disable gzip header and
  77526. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  77527. the crc code when it is not needed. For shared libraries, gzip decoding
  77528. should be left enabled. */
  77529. #ifndef NO_GZIP
  77530. # define GUNZIP
  77531. #endif
  77532. /* Possible inflate modes between inflate() calls */
  77533. typedef enum {
  77534. HEAD, /* i: waiting for magic header */
  77535. FLAGS, /* i: waiting for method and flags (gzip) */
  77536. TIME, /* i: waiting for modification time (gzip) */
  77537. OS, /* i: waiting for extra flags and operating system (gzip) */
  77538. EXLEN, /* i: waiting for extra length (gzip) */
  77539. EXTRA, /* i: waiting for extra bytes (gzip) */
  77540. NAME, /* i: waiting for end of file name (gzip) */
  77541. COMMENT, /* i: waiting for end of comment (gzip) */
  77542. HCRC, /* i: waiting for header crc (gzip) */
  77543. DICTID, /* i: waiting for dictionary check value */
  77544. DICT, /* waiting for inflateSetDictionary() call */
  77545. TYPE, /* i: waiting for type bits, including last-flag bit */
  77546. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  77547. STORED, /* i: waiting for stored size (length and complement) */
  77548. COPY, /* i/o: waiting for input or output to copy stored block */
  77549. TABLE, /* i: waiting for dynamic block table lengths */
  77550. LENLENS, /* i: waiting for code length code lengths */
  77551. CODELENS, /* i: waiting for length/lit and distance code lengths */
  77552. LEN, /* i: waiting for length/lit code */
  77553. LENEXT, /* i: waiting for length extra bits */
  77554. DIST, /* i: waiting for distance code */
  77555. DISTEXT, /* i: waiting for distance extra bits */
  77556. MATCH, /* o: waiting for output space to copy string */
  77557. LIT, /* o: waiting for output space to write literal */
  77558. CHECK, /* i: waiting for 32-bit check value */
  77559. LENGTH, /* i: waiting for 32-bit length (gzip) */
  77560. DONE, /* finished check, done -- remain here until reset */
  77561. BAD, /* got a data error -- remain here until reset */
  77562. MEM, /* got an inflate() memory error -- remain here until reset */
  77563. SYNC /* looking for synchronization bytes to restart inflate() */
  77564. } inflate_mode;
  77565. /*
  77566. State transitions between above modes -
  77567. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  77568. Process header:
  77569. HEAD -> (gzip) or (zlib)
  77570. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  77571. NAME -> COMMENT -> HCRC -> TYPE
  77572. (zlib) -> DICTID or TYPE
  77573. DICTID -> DICT -> TYPE
  77574. Read deflate blocks:
  77575. TYPE -> STORED or TABLE or LEN or CHECK
  77576. STORED -> COPY -> TYPE
  77577. TABLE -> LENLENS -> CODELENS -> LEN
  77578. Read deflate codes:
  77579. LEN -> LENEXT or LIT or TYPE
  77580. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  77581. LIT -> LEN
  77582. Process trailer:
  77583. CHECK -> LENGTH -> DONE
  77584. */
  77585. /* state maintained between inflate() calls. Approximately 7K bytes. */
  77586. struct inflate_state {
  77587. inflate_mode mode; /* current inflate mode */
  77588. int last; /* true if processing last block */
  77589. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  77590. int havedict; /* true if dictionary provided */
  77591. int flags; /* gzip header method and flags (0 if zlib) */
  77592. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  77593. unsigned long check; /* protected copy of check value */
  77594. unsigned long total; /* protected copy of output count */
  77595. gz_headerp head; /* where to save gzip header information */
  77596. /* sliding window */
  77597. unsigned wbits; /* log base 2 of requested window size */
  77598. unsigned wsize; /* window size or zero if not using window */
  77599. unsigned whave; /* valid bytes in the window */
  77600. unsigned write; /* window write index */
  77601. unsigned char FAR *window; /* allocated sliding window, if needed */
  77602. /* bit accumulator */
  77603. unsigned long hold; /* input bit accumulator */
  77604. unsigned bits; /* number of bits in "in" */
  77605. /* for string and stored block copying */
  77606. unsigned length; /* literal or length of data to copy */
  77607. unsigned offset; /* distance back to copy string from */
  77608. /* for table and code decoding */
  77609. unsigned extra; /* extra bits needed */
  77610. /* fixed and dynamic code tables */
  77611. code const FAR *lencode; /* starting table for length/literal codes */
  77612. code const FAR *distcode; /* starting table for distance codes */
  77613. unsigned lenbits; /* index bits for lencode */
  77614. unsigned distbits; /* index bits for distcode */
  77615. /* dynamic table building */
  77616. unsigned ncode; /* number of code length code lengths */
  77617. unsigned nlen; /* number of length code lengths */
  77618. unsigned ndist; /* number of distance code lengths */
  77619. unsigned have; /* number of code lengths in lens[] */
  77620. code FAR *next; /* next available space in codes[] */
  77621. unsigned short lens[320]; /* temporary storage for code lengths */
  77622. unsigned short work[288]; /* work area for code table building */
  77623. code codes[ENOUGH]; /* space for code tables */
  77624. };
  77625. #endif
  77626. /********* End of inlined file: inflate.h *********/
  77627. /********* Start of inlined file: inffast.h *********/
  77628. /* WARNING: this file should *not* be used by applications. It is
  77629. part of the implementation of the compression library and is
  77630. subject to change. Applications should only use zlib.h.
  77631. */
  77632. void inflate_fast OF((z_streamp strm, unsigned start));
  77633. /********* End of inlined file: inffast.h *********/
  77634. #ifndef ASMINF
  77635. /* Allow machine dependent optimization for post-increment or pre-increment.
  77636. Based on testing to date,
  77637. Pre-increment preferred for:
  77638. - PowerPC G3 (Adler)
  77639. - MIPS R5000 (Randers-Pehrson)
  77640. Post-increment preferred for:
  77641. - none
  77642. No measurable difference:
  77643. - Pentium III (Anderson)
  77644. - M68060 (Nikl)
  77645. */
  77646. #ifdef POSTINC
  77647. # define OFF 0
  77648. # define PUP(a) *(a)++
  77649. #else
  77650. # define OFF 1
  77651. # define PUP(a) *++(a)
  77652. #endif
  77653. /*
  77654. Decode literal, length, and distance codes and write out the resulting
  77655. literal and match bytes until either not enough input or output is
  77656. available, an end-of-block is encountered, or a data error is encountered.
  77657. When large enough input and output buffers are supplied to inflate(), for
  77658. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  77659. inflate execution time is spent in this routine.
  77660. Entry assumptions:
  77661. state->mode == LEN
  77662. strm->avail_in >= 6
  77663. strm->avail_out >= 258
  77664. start >= strm->avail_out
  77665. state->bits < 8
  77666. On return, state->mode is one of:
  77667. LEN -- ran out of enough output space or enough available input
  77668. TYPE -- reached end of block code, inflate() to interpret next block
  77669. BAD -- error in block data
  77670. Notes:
  77671. - The maximum input bits used by a length/distance pair is 15 bits for the
  77672. length code, 5 bits for the length extra, 15 bits for the distance code,
  77673. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  77674. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  77675. checking for available input while decoding.
  77676. - The maximum bytes that a single length/distance pair can output is 258
  77677. bytes, which is the maximum length that can be coded. inflate_fast()
  77678. requires strm->avail_out >= 258 for each loop to avoid checking for
  77679. output space.
  77680. */
  77681. void inflate_fast (z_streamp strm, unsigned start)
  77682. {
  77683. struct inflate_state FAR *state;
  77684. unsigned char FAR *in; /* local strm->next_in */
  77685. unsigned char FAR *last; /* while in < last, enough input available */
  77686. unsigned char FAR *out; /* local strm->next_out */
  77687. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  77688. unsigned char FAR *end; /* while out < end, enough space available */
  77689. #ifdef INFLATE_STRICT
  77690. unsigned dmax; /* maximum distance from zlib header */
  77691. #endif
  77692. unsigned wsize; /* window size or zero if not using window */
  77693. unsigned whave; /* valid bytes in the window */
  77694. unsigned write; /* window write index */
  77695. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  77696. unsigned long hold; /* local strm->hold */
  77697. unsigned bits; /* local strm->bits */
  77698. code const FAR *lcode; /* local strm->lencode */
  77699. code const FAR *dcode; /* local strm->distcode */
  77700. unsigned lmask; /* mask for first level of length codes */
  77701. unsigned dmask; /* mask for first level of distance codes */
  77702. code thisx; /* retrieved table entry */
  77703. unsigned op; /* code bits, operation, extra bits, or */
  77704. /* window position, window bytes to copy */
  77705. unsigned len; /* match length, unused bytes */
  77706. unsigned dist; /* match distance */
  77707. unsigned char FAR *from; /* where to copy match from */
  77708. /* copy state to local variables */
  77709. state = (struct inflate_state FAR *)strm->state;
  77710. in = strm->next_in - OFF;
  77711. last = in + (strm->avail_in - 5);
  77712. out = strm->next_out - OFF;
  77713. beg = out - (start - strm->avail_out);
  77714. end = out + (strm->avail_out - 257);
  77715. #ifdef INFLATE_STRICT
  77716. dmax = state->dmax;
  77717. #endif
  77718. wsize = state->wsize;
  77719. whave = state->whave;
  77720. write = state->write;
  77721. window = state->window;
  77722. hold = state->hold;
  77723. bits = state->bits;
  77724. lcode = state->lencode;
  77725. dcode = state->distcode;
  77726. lmask = (1U << state->lenbits) - 1;
  77727. dmask = (1U << state->distbits) - 1;
  77728. /* decode literals and length/distances until end-of-block or not enough
  77729. input data or output space */
  77730. do {
  77731. if (bits < 15) {
  77732. hold += (unsigned long)(PUP(in)) << bits;
  77733. bits += 8;
  77734. hold += (unsigned long)(PUP(in)) << bits;
  77735. bits += 8;
  77736. }
  77737. thisx = lcode[hold & lmask];
  77738. dolen:
  77739. op = (unsigned)(thisx.bits);
  77740. hold >>= op;
  77741. bits -= op;
  77742. op = (unsigned)(thisx.op);
  77743. if (op == 0) { /* literal */
  77744. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  77745. "inflate: literal '%c'\n" :
  77746. "inflate: literal 0x%02x\n", thisx.val));
  77747. PUP(out) = (unsigned char)(thisx.val);
  77748. }
  77749. else if (op & 16) { /* length base */
  77750. len = (unsigned)(thisx.val);
  77751. op &= 15; /* number of extra bits */
  77752. if (op) {
  77753. if (bits < op) {
  77754. hold += (unsigned long)(PUP(in)) << bits;
  77755. bits += 8;
  77756. }
  77757. len += (unsigned)hold & ((1U << op) - 1);
  77758. hold >>= op;
  77759. bits -= op;
  77760. }
  77761. Tracevv((stderr, "inflate: length %u\n", len));
  77762. if (bits < 15) {
  77763. hold += (unsigned long)(PUP(in)) << bits;
  77764. bits += 8;
  77765. hold += (unsigned long)(PUP(in)) << bits;
  77766. bits += 8;
  77767. }
  77768. thisx = dcode[hold & dmask];
  77769. dodist:
  77770. op = (unsigned)(thisx.bits);
  77771. hold >>= op;
  77772. bits -= op;
  77773. op = (unsigned)(thisx.op);
  77774. if (op & 16) { /* distance base */
  77775. dist = (unsigned)(thisx.val);
  77776. op &= 15; /* number of extra bits */
  77777. if (bits < op) {
  77778. hold += (unsigned long)(PUP(in)) << bits;
  77779. bits += 8;
  77780. if (bits < op) {
  77781. hold += (unsigned long)(PUP(in)) << bits;
  77782. bits += 8;
  77783. }
  77784. }
  77785. dist += (unsigned)hold & ((1U << op) - 1);
  77786. #ifdef INFLATE_STRICT
  77787. if (dist > dmax) {
  77788. strm->msg = (char *)"invalid distance too far back";
  77789. state->mode = BAD;
  77790. break;
  77791. }
  77792. #endif
  77793. hold >>= op;
  77794. bits -= op;
  77795. Tracevv((stderr, "inflate: distance %u\n", dist));
  77796. op = (unsigned)(out - beg); /* max distance in output */
  77797. if (dist > op) { /* see if copy from window */
  77798. op = dist - op; /* distance back in window */
  77799. if (op > whave) {
  77800. strm->msg = (char *)"invalid distance too far back";
  77801. state->mode = BAD;
  77802. break;
  77803. }
  77804. from = window - OFF;
  77805. if (write == 0) { /* very common case */
  77806. from += wsize - op;
  77807. if (op < len) { /* some from window */
  77808. len -= op;
  77809. do {
  77810. PUP(out) = PUP(from);
  77811. } while (--op);
  77812. from = out - dist; /* rest from output */
  77813. }
  77814. }
  77815. else if (write < op) { /* wrap around window */
  77816. from += wsize + write - op;
  77817. op -= write;
  77818. if (op < len) { /* some from end of window */
  77819. len -= op;
  77820. do {
  77821. PUP(out) = PUP(from);
  77822. } while (--op);
  77823. from = window - OFF;
  77824. if (write < len) { /* some from start of window */
  77825. op = write;
  77826. len -= op;
  77827. do {
  77828. PUP(out) = PUP(from);
  77829. } while (--op);
  77830. from = out - dist; /* rest from output */
  77831. }
  77832. }
  77833. }
  77834. else { /* contiguous in window */
  77835. from += write - op;
  77836. if (op < len) { /* some from window */
  77837. len -= op;
  77838. do {
  77839. PUP(out) = PUP(from);
  77840. } while (--op);
  77841. from = out - dist; /* rest from output */
  77842. }
  77843. }
  77844. while (len > 2) {
  77845. PUP(out) = PUP(from);
  77846. PUP(out) = PUP(from);
  77847. PUP(out) = PUP(from);
  77848. len -= 3;
  77849. }
  77850. if (len) {
  77851. PUP(out) = PUP(from);
  77852. if (len > 1)
  77853. PUP(out) = PUP(from);
  77854. }
  77855. }
  77856. else {
  77857. from = out - dist; /* copy direct from output */
  77858. do { /* minimum length is three */
  77859. PUP(out) = PUP(from);
  77860. PUP(out) = PUP(from);
  77861. PUP(out) = PUP(from);
  77862. len -= 3;
  77863. } while (len > 2);
  77864. if (len) {
  77865. PUP(out) = PUP(from);
  77866. if (len > 1)
  77867. PUP(out) = PUP(from);
  77868. }
  77869. }
  77870. }
  77871. else if ((op & 64) == 0) { /* 2nd level distance code */
  77872. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  77873. goto dodist;
  77874. }
  77875. else {
  77876. strm->msg = (char *)"invalid distance code";
  77877. state->mode = BAD;
  77878. break;
  77879. }
  77880. }
  77881. else if ((op & 64) == 0) { /* 2nd level length code */
  77882. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  77883. goto dolen;
  77884. }
  77885. else if (op & 32) { /* end-of-block */
  77886. Tracevv((stderr, "inflate: end of block\n"));
  77887. state->mode = TYPE;
  77888. break;
  77889. }
  77890. else {
  77891. strm->msg = (char *)"invalid literal/length code";
  77892. state->mode = BAD;
  77893. break;
  77894. }
  77895. } while (in < last && out < end);
  77896. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  77897. len = bits >> 3;
  77898. in -= len;
  77899. bits -= len << 3;
  77900. hold &= (1U << bits) - 1;
  77901. /* update state and return */
  77902. strm->next_in = in + OFF;
  77903. strm->next_out = out + OFF;
  77904. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  77905. strm->avail_out = (unsigned)(out < end ?
  77906. 257 + (end - out) : 257 - (out - end));
  77907. state->hold = hold;
  77908. state->bits = bits;
  77909. return;
  77910. }
  77911. /*
  77912. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  77913. - Using bit fields for code structure
  77914. - Different op definition to avoid & for extra bits (do & for table bits)
  77915. - Three separate decoding do-loops for direct, window, and write == 0
  77916. - Special case for distance > 1 copies to do overlapped load and store copy
  77917. - Explicit branch predictions (based on measured branch probabilities)
  77918. - Deferring match copy and interspersed it with decoding subsequent codes
  77919. - Swapping literal/length else
  77920. - Swapping window/direct else
  77921. - Larger unrolled copy loops (three is about right)
  77922. - Moving len -= 3 statement into middle of loop
  77923. */
  77924. #endif /* !ASMINF */
  77925. /********* End of inlined file: inffast.c *********/
  77926. #undef PULLBYTE
  77927. #undef LOAD
  77928. #undef RESTORE
  77929. #undef INITBITS
  77930. #undef NEEDBITS
  77931. #undef DROPBITS
  77932. #undef BYTEBITS
  77933. /********* Start of inlined file: inflate.c *********/
  77934. /*
  77935. * Change history:
  77936. *
  77937. * 1.2.beta0 24 Nov 2002
  77938. * - First version -- complete rewrite of inflate to simplify code, avoid
  77939. * creation of window when not needed, minimize use of window when it is
  77940. * needed, make inffast.c even faster, implement gzip decoding, and to
  77941. * improve code readability and style over the previous zlib inflate code
  77942. *
  77943. * 1.2.beta1 25 Nov 2002
  77944. * - Use pointers for available input and output checking in inffast.c
  77945. * - Remove input and output counters in inffast.c
  77946. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  77947. * - Remove unnecessary second byte pull from length extra in inffast.c
  77948. * - Unroll direct copy to three copies per loop in inffast.c
  77949. *
  77950. * 1.2.beta2 4 Dec 2002
  77951. * - Change external routine names to reduce potential conflicts
  77952. * - Correct filename to inffixed.h for fixed tables in inflate.c
  77953. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  77954. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  77955. * to avoid negation problem on Alphas (64 bit) in inflate.c
  77956. *
  77957. * 1.2.beta3 22 Dec 2002
  77958. * - Add comments on state->bits assertion in inffast.c
  77959. * - Add comments on op field in inftrees.h
  77960. * - Fix bug in reuse of allocated window after inflateReset()
  77961. * - Remove bit fields--back to byte structure for speed
  77962. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  77963. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  77964. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  77965. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  77966. * - Use local copies of stream next and avail values, as well as local bit
  77967. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  77968. *
  77969. * 1.2.beta4 1 Jan 2003
  77970. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  77971. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  77972. * - Add comments in inffast.c to introduce the inflate_fast() routine
  77973. * - Rearrange window copies in inflate_fast() for speed and simplification
  77974. * - Unroll last copy for window match in inflate_fast()
  77975. * - Use local copies of window variables in inflate_fast() for speed
  77976. * - Pull out common write == 0 case for speed in inflate_fast()
  77977. * - Make op and len in inflate_fast() unsigned for consistency
  77978. * - Add FAR to lcode and dcode declarations in inflate_fast()
  77979. * - Simplified bad distance check in inflate_fast()
  77980. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  77981. * source file infback.c to provide a call-back interface to inflate for
  77982. * programs like gzip and unzip -- uses window as output buffer to avoid
  77983. * window copying
  77984. *
  77985. * 1.2.beta5 1 Jan 2003
  77986. * - Improved inflateBack() interface to allow the caller to provide initial
  77987. * input in strm.
  77988. * - Fixed stored blocks bug in inflateBack()
  77989. *
  77990. * 1.2.beta6 4 Jan 2003
  77991. * - Added comments in inffast.c on effectiveness of POSTINC
  77992. * - Typecasting all around to reduce compiler warnings
  77993. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  77994. * make compilers happy
  77995. * - Changed type of window in inflateBackInit() to unsigned char *
  77996. *
  77997. * 1.2.beta7 27 Jan 2003
  77998. * - Changed many types to unsigned or unsigned short to avoid warnings
  77999. * - Added inflateCopy() function
  78000. *
  78001. * 1.2.0 9 Mar 2003
  78002. * - Changed inflateBack() interface to provide separate opaque descriptors
  78003. * for the in() and out() functions
  78004. * - Changed inflateBack() argument and in_func typedef to swap the length
  78005. * and buffer address return values for the input function
  78006. * - Check next_in and next_out for Z_NULL on entry to inflate()
  78007. *
  78008. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  78009. */
  78010. /********* Start of inlined file: inffast.h *********/
  78011. /* WARNING: this file should *not* be used by applications. It is
  78012. part of the implementation of the compression library and is
  78013. subject to change. Applications should only use zlib.h.
  78014. */
  78015. void inflate_fast OF((z_streamp strm, unsigned start));
  78016. /********* End of inlined file: inffast.h *********/
  78017. #ifdef MAKEFIXED
  78018. # ifndef BUILDFIXED
  78019. # define BUILDFIXED
  78020. # endif
  78021. #endif
  78022. /* function prototypes */
  78023. local void fixedtables OF((struct inflate_state FAR *state));
  78024. local int updatewindow OF((z_streamp strm, unsigned out));
  78025. #ifdef BUILDFIXED
  78026. void makefixed OF((void));
  78027. #endif
  78028. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  78029. unsigned len));
  78030. int ZEXPORT inflateReset (z_streamp strm)
  78031. {
  78032. struct inflate_state FAR *state;
  78033. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78034. state = (struct inflate_state FAR *)strm->state;
  78035. strm->total_in = strm->total_out = state->total = 0;
  78036. strm->msg = Z_NULL;
  78037. strm->adler = 1; /* to support ill-conceived Java test suite */
  78038. state->mode = HEAD;
  78039. state->last = 0;
  78040. state->havedict = 0;
  78041. state->dmax = 32768U;
  78042. state->head = Z_NULL;
  78043. state->wsize = 0;
  78044. state->whave = 0;
  78045. state->write = 0;
  78046. state->hold = 0;
  78047. state->bits = 0;
  78048. state->lencode = state->distcode = state->next = state->codes;
  78049. Tracev((stderr, "inflate: reset\n"));
  78050. return Z_OK;
  78051. }
  78052. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  78053. {
  78054. struct inflate_state FAR *state;
  78055. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78056. state = (struct inflate_state FAR *)strm->state;
  78057. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  78058. value &= (1L << bits) - 1;
  78059. state->hold += value << state->bits;
  78060. state->bits += bits;
  78061. return Z_OK;
  78062. }
  78063. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  78064. {
  78065. struct inflate_state FAR *state;
  78066. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  78067. stream_size != (int)(sizeof(z_stream)))
  78068. return Z_VERSION_ERROR;
  78069. if (strm == Z_NULL) return Z_STREAM_ERROR;
  78070. strm->msg = Z_NULL; /* in case we return an error */
  78071. if (strm->zalloc == (alloc_func)0) {
  78072. strm->zalloc = zcalloc;
  78073. strm->opaque = (voidpf)0;
  78074. }
  78075. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  78076. state = (struct inflate_state FAR *)
  78077. ZALLOC(strm, 1, sizeof(struct inflate_state));
  78078. if (state == Z_NULL) return Z_MEM_ERROR;
  78079. Tracev((stderr, "inflate: allocated\n"));
  78080. strm->state = (struct internal_state FAR *)state;
  78081. if (windowBits < 0) {
  78082. state->wrap = 0;
  78083. windowBits = -windowBits;
  78084. }
  78085. else {
  78086. state->wrap = (windowBits >> 4) + 1;
  78087. #ifdef GUNZIP
  78088. if (windowBits < 48) windowBits &= 15;
  78089. #endif
  78090. }
  78091. if (windowBits < 8 || windowBits > 15) {
  78092. ZFREE(strm, state);
  78093. strm->state = Z_NULL;
  78094. return Z_STREAM_ERROR;
  78095. }
  78096. state->wbits = (unsigned)windowBits;
  78097. state->window = Z_NULL;
  78098. return inflateReset(strm);
  78099. }
  78100. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  78101. {
  78102. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  78103. }
  78104. /*
  78105. Return state with length and distance decoding tables and index sizes set to
  78106. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  78107. If BUILDFIXED is defined, then instead this routine builds the tables the
  78108. first time it's called, and returns those tables the first time and
  78109. thereafter. This reduces the size of the code by about 2K bytes, in
  78110. exchange for a little execution time. However, BUILDFIXED should not be
  78111. used for threaded applications, since the rewriting of the tables and virgin
  78112. may not be thread-safe.
  78113. */
  78114. local void fixedtables (struct inflate_state FAR *state)
  78115. {
  78116. #ifdef BUILDFIXED
  78117. static int virgin = 1;
  78118. static code *lenfix, *distfix;
  78119. static code fixed[544];
  78120. /* build fixed huffman tables if first call (may not be thread safe) */
  78121. if (virgin) {
  78122. unsigned sym, bits;
  78123. static code *next;
  78124. /* literal/length table */
  78125. sym = 0;
  78126. while (sym < 144) state->lens[sym++] = 8;
  78127. while (sym < 256) state->lens[sym++] = 9;
  78128. while (sym < 280) state->lens[sym++] = 7;
  78129. while (sym < 288) state->lens[sym++] = 8;
  78130. next = fixed;
  78131. lenfix = next;
  78132. bits = 9;
  78133. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  78134. /* distance table */
  78135. sym = 0;
  78136. while (sym < 32) state->lens[sym++] = 5;
  78137. distfix = next;
  78138. bits = 5;
  78139. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  78140. /* do this just once */
  78141. virgin = 0;
  78142. }
  78143. #else /* !BUILDFIXED */
  78144. /********* Start of inlined file: inffixed.h *********/
  78145. /* inffixed.h -- table for decoding fixed codes
  78146. * Generated automatically by makefixed().
  78147. */
  78148. /* WARNING: this file should *not* be used by applications. It
  78149. is part of the implementation of the compression library and
  78150. is subject to change. Applications should only use zlib.h.
  78151. */
  78152. static const code lenfix[512] = {
  78153. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  78154. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  78155. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  78156. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  78157. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  78158. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  78159. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  78160. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  78161. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  78162. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  78163. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  78164. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  78165. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  78166. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  78167. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  78168. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  78169. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  78170. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  78171. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  78172. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  78173. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  78174. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  78175. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  78176. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  78177. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  78178. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  78179. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  78180. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  78181. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  78182. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  78183. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  78184. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  78185. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  78186. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  78187. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  78188. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  78189. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  78190. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  78191. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  78192. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  78193. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  78194. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  78195. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  78196. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  78197. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  78198. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  78199. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  78200. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  78201. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  78202. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  78203. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  78204. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  78205. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  78206. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  78207. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  78208. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  78209. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  78210. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  78211. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  78212. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  78213. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  78214. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  78215. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  78216. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  78217. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  78218. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  78219. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  78220. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  78221. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  78222. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  78223. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  78224. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  78225. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  78226. {0,9,255}
  78227. };
  78228. static const code distfix[32] = {
  78229. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  78230. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  78231. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  78232. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  78233. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  78234. {22,5,193},{64,5,0}
  78235. };
  78236. /********* End of inlined file: inffixed.h *********/
  78237. #endif /* BUILDFIXED */
  78238. state->lencode = lenfix;
  78239. state->lenbits = 9;
  78240. state->distcode = distfix;
  78241. state->distbits = 5;
  78242. }
  78243. #ifdef MAKEFIXED
  78244. #include <stdio.h>
  78245. /*
  78246. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  78247. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  78248. those tables to stdout, which would be piped to inffixed.h. A small program
  78249. can simply call makefixed to do this:
  78250. void makefixed(void);
  78251. int main(void)
  78252. {
  78253. makefixed();
  78254. return 0;
  78255. }
  78256. Then that can be linked with zlib built with MAKEFIXED defined and run:
  78257. a.out > inffixed.h
  78258. */
  78259. void makefixed()
  78260. {
  78261. unsigned low, size;
  78262. struct inflate_state state;
  78263. fixedtables(&state);
  78264. puts(" /* inffixed.h -- table for decoding fixed codes");
  78265. puts(" * Generated automatically by makefixed().");
  78266. puts(" */");
  78267. puts("");
  78268. puts(" /* WARNING: this file should *not* be used by applications.");
  78269. puts(" It is part of the implementation of this library and is");
  78270. puts(" subject to change. Applications should only use zlib.h.");
  78271. puts(" */");
  78272. puts("");
  78273. size = 1U << 9;
  78274. printf(" static const code lenfix[%u] = {", size);
  78275. low = 0;
  78276. for (;;) {
  78277. if ((low % 7) == 0) printf("\n ");
  78278. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  78279. state.lencode[low].val);
  78280. if (++low == size) break;
  78281. putchar(',');
  78282. }
  78283. puts("\n };");
  78284. size = 1U << 5;
  78285. printf("\n static const code distfix[%u] = {", size);
  78286. low = 0;
  78287. for (;;) {
  78288. if ((low % 6) == 0) printf("\n ");
  78289. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  78290. state.distcode[low].val);
  78291. if (++low == size) break;
  78292. putchar(',');
  78293. }
  78294. puts("\n };");
  78295. }
  78296. #endif /* MAKEFIXED */
  78297. /*
  78298. Update the window with the last wsize (normally 32K) bytes written before
  78299. returning. If window does not exist yet, create it. This is only called
  78300. when a window is already in use, or when output has been written during this
  78301. inflate call, but the end of the deflate stream has not been reached yet.
  78302. It is also called to create a window for dictionary data when a dictionary
  78303. is loaded.
  78304. Providing output buffers larger than 32K to inflate() should provide a speed
  78305. advantage, since only the last 32K of output is copied to the sliding window
  78306. upon return from inflate(), and since all distances after the first 32K of
  78307. output will fall in the output data, making match copies simpler and faster.
  78308. The advantage may be dependent on the size of the processor's data caches.
  78309. */
  78310. local int updatewindow (z_streamp strm, unsigned out)
  78311. {
  78312. struct inflate_state FAR *state;
  78313. unsigned copy, dist;
  78314. state = (struct inflate_state FAR *)strm->state;
  78315. /* if it hasn't been done already, allocate space for the window */
  78316. if (state->window == Z_NULL) {
  78317. state->window = (unsigned char FAR *)
  78318. ZALLOC(strm, 1U << state->wbits,
  78319. sizeof(unsigned char));
  78320. if (state->window == Z_NULL) return 1;
  78321. }
  78322. /* if window not in use yet, initialize */
  78323. if (state->wsize == 0) {
  78324. state->wsize = 1U << state->wbits;
  78325. state->write = 0;
  78326. state->whave = 0;
  78327. }
  78328. /* copy state->wsize or less output bytes into the circular window */
  78329. copy = out - strm->avail_out;
  78330. if (copy >= state->wsize) {
  78331. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  78332. state->write = 0;
  78333. state->whave = state->wsize;
  78334. }
  78335. else {
  78336. dist = state->wsize - state->write;
  78337. if (dist > copy) dist = copy;
  78338. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  78339. copy -= dist;
  78340. if (copy) {
  78341. zmemcpy(state->window, strm->next_out - copy, copy);
  78342. state->write = copy;
  78343. state->whave = state->wsize;
  78344. }
  78345. else {
  78346. state->write += dist;
  78347. if (state->write == state->wsize) state->write = 0;
  78348. if (state->whave < state->wsize) state->whave += dist;
  78349. }
  78350. }
  78351. return 0;
  78352. }
  78353. /* Macros for inflate(): */
  78354. /* check function to use adler32() for zlib or crc32() for gzip */
  78355. #ifdef GUNZIP
  78356. # define UPDATE(check, buf, len) \
  78357. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  78358. #else
  78359. # define UPDATE(check, buf, len) adler32(check, buf, len)
  78360. #endif
  78361. /* check macros for header crc */
  78362. #ifdef GUNZIP
  78363. # define CRC2(check, word) \
  78364. do { \
  78365. hbuf[0] = (unsigned char)(word); \
  78366. hbuf[1] = (unsigned char)((word) >> 8); \
  78367. check = crc32(check, hbuf, 2); \
  78368. } while (0)
  78369. # define CRC4(check, word) \
  78370. do { \
  78371. hbuf[0] = (unsigned char)(word); \
  78372. hbuf[1] = (unsigned char)((word) >> 8); \
  78373. hbuf[2] = (unsigned char)((word) >> 16); \
  78374. hbuf[3] = (unsigned char)((word) >> 24); \
  78375. check = crc32(check, hbuf, 4); \
  78376. } while (0)
  78377. #endif
  78378. /* Load registers with state in inflate() for speed */
  78379. #define LOAD() \
  78380. do { \
  78381. put = strm->next_out; \
  78382. left = strm->avail_out; \
  78383. next = strm->next_in; \
  78384. have = strm->avail_in; \
  78385. hold = state->hold; \
  78386. bits = state->bits; \
  78387. } while (0)
  78388. /* Restore state from registers in inflate() */
  78389. #define RESTORE() \
  78390. do { \
  78391. strm->next_out = put; \
  78392. strm->avail_out = left; \
  78393. strm->next_in = next; \
  78394. strm->avail_in = have; \
  78395. state->hold = hold; \
  78396. state->bits = bits; \
  78397. } while (0)
  78398. /* Clear the input bit accumulator */
  78399. #define INITBITS() \
  78400. do { \
  78401. hold = 0; \
  78402. bits = 0; \
  78403. } while (0)
  78404. /* Get a byte of input into the bit accumulator, or return from inflate()
  78405. if there is no input available. */
  78406. #define PULLBYTE() \
  78407. do { \
  78408. if (have == 0) goto inf_leave; \
  78409. have--; \
  78410. hold += (unsigned long)(*next++) << bits; \
  78411. bits += 8; \
  78412. } while (0)
  78413. /* Assure that there are at least n bits in the bit accumulator. If there is
  78414. not enough available input to do that, then return from inflate(). */
  78415. #define NEEDBITS(n) \
  78416. do { \
  78417. while (bits < (unsigned)(n)) \
  78418. PULLBYTE(); \
  78419. } while (0)
  78420. /* Return the low n bits of the bit accumulator (n < 16) */
  78421. #define BITS(n) \
  78422. ((unsigned)hold & ((1U << (n)) - 1))
  78423. /* Remove n bits from the bit accumulator */
  78424. #define DROPBITS(n) \
  78425. do { \
  78426. hold >>= (n); \
  78427. bits -= (unsigned)(n); \
  78428. } while (0)
  78429. /* Remove zero to seven bits as needed to go to a byte boundary */
  78430. #define BYTEBITS() \
  78431. do { \
  78432. hold >>= bits & 7; \
  78433. bits -= bits & 7; \
  78434. } while (0)
  78435. /* Reverse the bytes in a 32-bit value */
  78436. #define REVERSE(q) \
  78437. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  78438. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  78439. /*
  78440. inflate() uses a state machine to process as much input data and generate as
  78441. much output data as possible before returning. The state machine is
  78442. structured roughly as follows:
  78443. for (;;) switch (state) {
  78444. ...
  78445. case STATEn:
  78446. if (not enough input data or output space to make progress)
  78447. return;
  78448. ... make progress ...
  78449. state = STATEm;
  78450. break;
  78451. ...
  78452. }
  78453. so when inflate() is called again, the same case is attempted again, and
  78454. if the appropriate resources are provided, the machine proceeds to the
  78455. next state. The NEEDBITS() macro is usually the way the state evaluates
  78456. whether it can proceed or should return. NEEDBITS() does the return if
  78457. the requested bits are not available. The typical use of the BITS macros
  78458. is:
  78459. NEEDBITS(n);
  78460. ... do something with BITS(n) ...
  78461. DROPBITS(n);
  78462. where NEEDBITS(n) either returns from inflate() if there isn't enough
  78463. input left to load n bits into the accumulator, or it continues. BITS(n)
  78464. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  78465. the low n bits off the accumulator. INITBITS() clears the accumulator
  78466. and sets the number of available bits to zero. BYTEBITS() discards just
  78467. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  78468. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  78469. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  78470. if there is no input available. The decoding of variable length codes uses
  78471. PULLBYTE() directly in order to pull just enough bytes to decode the next
  78472. code, and no more.
  78473. Some states loop until they get enough input, making sure that enough
  78474. state information is maintained to continue the loop where it left off
  78475. if NEEDBITS() returns in the loop. For example, want, need, and keep
  78476. would all have to actually be part of the saved state in case NEEDBITS()
  78477. returns:
  78478. case STATEw:
  78479. while (want < need) {
  78480. NEEDBITS(n);
  78481. keep[want++] = BITS(n);
  78482. DROPBITS(n);
  78483. }
  78484. state = STATEx;
  78485. case STATEx:
  78486. As shown above, if the next state is also the next case, then the break
  78487. is omitted.
  78488. A state may also return if there is not enough output space available to
  78489. complete that state. Those states are copying stored data, writing a
  78490. literal byte, and copying a matching string.
  78491. When returning, a "goto inf_leave" is used to update the total counters,
  78492. update the check value, and determine whether any progress has been made
  78493. during that inflate() call in order to return the proper return code.
  78494. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  78495. When there is a window, goto inf_leave will update the window with the last
  78496. output written. If a goto inf_leave occurs in the middle of decompression
  78497. and there is no window currently, goto inf_leave will create one and copy
  78498. output to the window for the next call of inflate().
  78499. In this implementation, the flush parameter of inflate() only affects the
  78500. return code (per zlib.h). inflate() always writes as much as possible to
  78501. strm->next_out, given the space available and the provided input--the effect
  78502. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  78503. the allocation of and copying into a sliding window until necessary, which
  78504. provides the effect documented in zlib.h for Z_FINISH when the entire input
  78505. stream available. So the only thing the flush parameter actually does is:
  78506. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  78507. will return Z_BUF_ERROR if it has not reached the end of the stream.
  78508. */
  78509. int ZEXPORT inflate (z_streamp strm, int flush)
  78510. {
  78511. struct inflate_state FAR *state;
  78512. unsigned char FAR *next; /* next input */
  78513. unsigned char FAR *put; /* next output */
  78514. unsigned have, left; /* available input and output */
  78515. unsigned long hold; /* bit buffer */
  78516. unsigned bits; /* bits in bit buffer */
  78517. unsigned in, out; /* save starting available input and output */
  78518. unsigned copy; /* number of stored or match bytes to copy */
  78519. unsigned char FAR *from; /* where to copy match bytes from */
  78520. code thisx; /* current decoding table entry */
  78521. code last; /* parent table entry */
  78522. unsigned len; /* length to copy for repeats, bits to drop */
  78523. int ret; /* return code */
  78524. #ifdef GUNZIP
  78525. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  78526. #endif
  78527. static const unsigned short order[19] = /* permutation of code lengths */
  78528. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  78529. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  78530. (strm->next_in == Z_NULL && strm->avail_in != 0))
  78531. return Z_STREAM_ERROR;
  78532. state = (struct inflate_state FAR *)strm->state;
  78533. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  78534. LOAD();
  78535. in = have;
  78536. out = left;
  78537. ret = Z_OK;
  78538. for (;;)
  78539. switch (state->mode) {
  78540. case HEAD:
  78541. if (state->wrap == 0) {
  78542. state->mode = TYPEDO;
  78543. break;
  78544. }
  78545. NEEDBITS(16);
  78546. #ifdef GUNZIP
  78547. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  78548. state->check = crc32(0L, Z_NULL, 0);
  78549. CRC2(state->check, hold);
  78550. INITBITS();
  78551. state->mode = FLAGS;
  78552. break;
  78553. }
  78554. state->flags = 0; /* expect zlib header */
  78555. if (state->head != Z_NULL)
  78556. state->head->done = -1;
  78557. if (!(state->wrap & 1) || /* check if zlib header allowed */
  78558. #else
  78559. if (
  78560. #endif
  78561. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  78562. strm->msg = (char *)"incorrect header check";
  78563. state->mode = BAD;
  78564. break;
  78565. }
  78566. if (BITS(4) != Z_DEFLATED) {
  78567. strm->msg = (char *)"unknown compression method";
  78568. state->mode = BAD;
  78569. break;
  78570. }
  78571. DROPBITS(4);
  78572. len = BITS(4) + 8;
  78573. if (len > state->wbits) {
  78574. strm->msg = (char *)"invalid window size";
  78575. state->mode = BAD;
  78576. break;
  78577. }
  78578. state->dmax = 1U << len;
  78579. Tracev((stderr, "inflate: zlib header ok\n"));
  78580. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  78581. state->mode = hold & 0x200 ? DICTID : TYPE;
  78582. INITBITS();
  78583. break;
  78584. #ifdef GUNZIP
  78585. case FLAGS:
  78586. NEEDBITS(16);
  78587. state->flags = (int)(hold);
  78588. if ((state->flags & 0xff) != Z_DEFLATED) {
  78589. strm->msg = (char *)"unknown compression method";
  78590. state->mode = BAD;
  78591. break;
  78592. }
  78593. if (state->flags & 0xe000) {
  78594. strm->msg = (char *)"unknown header flags set";
  78595. state->mode = BAD;
  78596. break;
  78597. }
  78598. if (state->head != Z_NULL)
  78599. state->head->text = (int)((hold >> 8) & 1);
  78600. if (state->flags & 0x0200) CRC2(state->check, hold);
  78601. INITBITS();
  78602. state->mode = TIME;
  78603. case TIME:
  78604. NEEDBITS(32);
  78605. if (state->head != Z_NULL)
  78606. state->head->time = hold;
  78607. if (state->flags & 0x0200) CRC4(state->check, hold);
  78608. INITBITS();
  78609. state->mode = OS;
  78610. case OS:
  78611. NEEDBITS(16);
  78612. if (state->head != Z_NULL) {
  78613. state->head->xflags = (int)(hold & 0xff);
  78614. state->head->os = (int)(hold >> 8);
  78615. }
  78616. if (state->flags & 0x0200) CRC2(state->check, hold);
  78617. INITBITS();
  78618. state->mode = EXLEN;
  78619. case EXLEN:
  78620. if (state->flags & 0x0400) {
  78621. NEEDBITS(16);
  78622. state->length = (unsigned)(hold);
  78623. if (state->head != Z_NULL)
  78624. state->head->extra_len = (unsigned)hold;
  78625. if (state->flags & 0x0200) CRC2(state->check, hold);
  78626. INITBITS();
  78627. }
  78628. else if (state->head != Z_NULL)
  78629. state->head->extra = Z_NULL;
  78630. state->mode = EXTRA;
  78631. case EXTRA:
  78632. if (state->flags & 0x0400) {
  78633. copy = state->length;
  78634. if (copy > have) copy = have;
  78635. if (copy) {
  78636. if (state->head != Z_NULL &&
  78637. state->head->extra != Z_NULL) {
  78638. len = state->head->extra_len - state->length;
  78639. zmemcpy(state->head->extra + len, next,
  78640. len + copy > state->head->extra_max ?
  78641. state->head->extra_max - len : copy);
  78642. }
  78643. if (state->flags & 0x0200)
  78644. state->check = crc32(state->check, next, copy);
  78645. have -= copy;
  78646. next += copy;
  78647. state->length -= copy;
  78648. }
  78649. if (state->length) goto inf_leave;
  78650. }
  78651. state->length = 0;
  78652. state->mode = NAME;
  78653. case NAME:
  78654. if (state->flags & 0x0800) {
  78655. if (have == 0) goto inf_leave;
  78656. copy = 0;
  78657. do {
  78658. len = (unsigned)(next[copy++]);
  78659. if (state->head != Z_NULL &&
  78660. state->head->name != Z_NULL &&
  78661. state->length < state->head->name_max)
  78662. state->head->name[state->length++] = len;
  78663. } while (len && copy < have);
  78664. if (state->flags & 0x0200)
  78665. state->check = crc32(state->check, next, copy);
  78666. have -= copy;
  78667. next += copy;
  78668. if (len) goto inf_leave;
  78669. }
  78670. else if (state->head != Z_NULL)
  78671. state->head->name = Z_NULL;
  78672. state->length = 0;
  78673. state->mode = COMMENT;
  78674. case COMMENT:
  78675. if (state->flags & 0x1000) {
  78676. if (have == 0) goto inf_leave;
  78677. copy = 0;
  78678. do {
  78679. len = (unsigned)(next[copy++]);
  78680. if (state->head != Z_NULL &&
  78681. state->head->comment != Z_NULL &&
  78682. state->length < state->head->comm_max)
  78683. state->head->comment[state->length++] = len;
  78684. } while (len && copy < have);
  78685. if (state->flags & 0x0200)
  78686. state->check = crc32(state->check, next, copy);
  78687. have -= copy;
  78688. next += copy;
  78689. if (len) goto inf_leave;
  78690. }
  78691. else if (state->head != Z_NULL)
  78692. state->head->comment = Z_NULL;
  78693. state->mode = HCRC;
  78694. case HCRC:
  78695. if (state->flags & 0x0200) {
  78696. NEEDBITS(16);
  78697. if (hold != (state->check & 0xffff)) {
  78698. strm->msg = (char *)"header crc mismatch";
  78699. state->mode = BAD;
  78700. break;
  78701. }
  78702. INITBITS();
  78703. }
  78704. if (state->head != Z_NULL) {
  78705. state->head->hcrc = (int)((state->flags >> 9) & 1);
  78706. state->head->done = 1;
  78707. }
  78708. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  78709. state->mode = TYPE;
  78710. break;
  78711. #endif
  78712. case DICTID:
  78713. NEEDBITS(32);
  78714. strm->adler = state->check = REVERSE(hold);
  78715. INITBITS();
  78716. state->mode = DICT;
  78717. case DICT:
  78718. if (state->havedict == 0) {
  78719. RESTORE();
  78720. return Z_NEED_DICT;
  78721. }
  78722. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  78723. state->mode = TYPE;
  78724. case TYPE:
  78725. if (flush == Z_BLOCK) goto inf_leave;
  78726. case TYPEDO:
  78727. if (state->last) {
  78728. BYTEBITS();
  78729. state->mode = CHECK;
  78730. break;
  78731. }
  78732. NEEDBITS(3);
  78733. state->last = BITS(1);
  78734. DROPBITS(1);
  78735. switch (BITS(2)) {
  78736. case 0: /* stored block */
  78737. Tracev((stderr, "inflate: stored block%s\n",
  78738. state->last ? " (last)" : ""));
  78739. state->mode = STORED;
  78740. break;
  78741. case 1: /* fixed block */
  78742. fixedtables(state);
  78743. Tracev((stderr, "inflate: fixed codes block%s\n",
  78744. state->last ? " (last)" : ""));
  78745. state->mode = LEN; /* decode codes */
  78746. break;
  78747. case 2: /* dynamic block */
  78748. Tracev((stderr, "inflate: dynamic codes block%s\n",
  78749. state->last ? " (last)" : ""));
  78750. state->mode = TABLE;
  78751. break;
  78752. case 3:
  78753. strm->msg = (char *)"invalid block type";
  78754. state->mode = BAD;
  78755. }
  78756. DROPBITS(2);
  78757. break;
  78758. case STORED:
  78759. BYTEBITS(); /* go to byte boundary */
  78760. NEEDBITS(32);
  78761. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  78762. strm->msg = (char *)"invalid stored block lengths";
  78763. state->mode = BAD;
  78764. break;
  78765. }
  78766. state->length = (unsigned)hold & 0xffff;
  78767. Tracev((stderr, "inflate: stored length %u\n",
  78768. state->length));
  78769. INITBITS();
  78770. state->mode = COPY;
  78771. case COPY:
  78772. copy = state->length;
  78773. if (copy) {
  78774. if (copy > have) copy = have;
  78775. if (copy > left) copy = left;
  78776. if (copy == 0) goto inf_leave;
  78777. zmemcpy(put, next, copy);
  78778. have -= copy;
  78779. next += copy;
  78780. left -= copy;
  78781. put += copy;
  78782. state->length -= copy;
  78783. break;
  78784. }
  78785. Tracev((stderr, "inflate: stored end\n"));
  78786. state->mode = TYPE;
  78787. break;
  78788. case TABLE:
  78789. NEEDBITS(14);
  78790. state->nlen = BITS(5) + 257;
  78791. DROPBITS(5);
  78792. state->ndist = BITS(5) + 1;
  78793. DROPBITS(5);
  78794. state->ncode = BITS(4) + 4;
  78795. DROPBITS(4);
  78796. #ifndef PKZIP_BUG_WORKAROUND
  78797. if (state->nlen > 286 || state->ndist > 30) {
  78798. strm->msg = (char *)"too many length or distance symbols";
  78799. state->mode = BAD;
  78800. break;
  78801. }
  78802. #endif
  78803. Tracev((stderr, "inflate: table sizes ok\n"));
  78804. state->have = 0;
  78805. state->mode = LENLENS;
  78806. case LENLENS:
  78807. while (state->have < state->ncode) {
  78808. NEEDBITS(3);
  78809. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  78810. DROPBITS(3);
  78811. }
  78812. while (state->have < 19)
  78813. state->lens[order[state->have++]] = 0;
  78814. state->next = state->codes;
  78815. state->lencode = (code const FAR *)(state->next);
  78816. state->lenbits = 7;
  78817. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  78818. &(state->lenbits), state->work);
  78819. if (ret) {
  78820. strm->msg = (char *)"invalid code lengths set";
  78821. state->mode = BAD;
  78822. break;
  78823. }
  78824. Tracev((stderr, "inflate: code lengths ok\n"));
  78825. state->have = 0;
  78826. state->mode = CODELENS;
  78827. case CODELENS:
  78828. while (state->have < state->nlen + state->ndist) {
  78829. for (;;) {
  78830. thisx = state->lencode[BITS(state->lenbits)];
  78831. if ((unsigned)(thisx.bits) <= bits) break;
  78832. PULLBYTE();
  78833. }
  78834. if (thisx.val < 16) {
  78835. NEEDBITS(thisx.bits);
  78836. DROPBITS(thisx.bits);
  78837. state->lens[state->have++] = thisx.val;
  78838. }
  78839. else {
  78840. if (thisx.val == 16) {
  78841. NEEDBITS(thisx.bits + 2);
  78842. DROPBITS(thisx.bits);
  78843. if (state->have == 0) {
  78844. strm->msg = (char *)"invalid bit length repeat";
  78845. state->mode = BAD;
  78846. break;
  78847. }
  78848. len = state->lens[state->have - 1];
  78849. copy = 3 + BITS(2);
  78850. DROPBITS(2);
  78851. }
  78852. else if (thisx.val == 17) {
  78853. NEEDBITS(thisx.bits + 3);
  78854. DROPBITS(thisx.bits);
  78855. len = 0;
  78856. copy = 3 + BITS(3);
  78857. DROPBITS(3);
  78858. }
  78859. else {
  78860. NEEDBITS(thisx.bits + 7);
  78861. DROPBITS(thisx.bits);
  78862. len = 0;
  78863. copy = 11 + BITS(7);
  78864. DROPBITS(7);
  78865. }
  78866. if (state->have + copy > state->nlen + state->ndist) {
  78867. strm->msg = (char *)"invalid bit length repeat";
  78868. state->mode = BAD;
  78869. break;
  78870. }
  78871. while (copy--)
  78872. state->lens[state->have++] = (unsigned short)len;
  78873. }
  78874. }
  78875. /* handle error breaks in while */
  78876. if (state->mode == BAD) break;
  78877. /* build code tables */
  78878. state->next = state->codes;
  78879. state->lencode = (code const FAR *)(state->next);
  78880. state->lenbits = 9;
  78881. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  78882. &(state->lenbits), state->work);
  78883. if (ret) {
  78884. strm->msg = (char *)"invalid literal/lengths set";
  78885. state->mode = BAD;
  78886. break;
  78887. }
  78888. state->distcode = (code const FAR *)(state->next);
  78889. state->distbits = 6;
  78890. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  78891. &(state->next), &(state->distbits), state->work);
  78892. if (ret) {
  78893. strm->msg = (char *)"invalid distances set";
  78894. state->mode = BAD;
  78895. break;
  78896. }
  78897. Tracev((stderr, "inflate: codes ok\n"));
  78898. state->mode = LEN;
  78899. case LEN:
  78900. if (have >= 6 && left >= 258) {
  78901. RESTORE();
  78902. inflate_fast(strm, out);
  78903. LOAD();
  78904. break;
  78905. }
  78906. for (;;) {
  78907. thisx = state->lencode[BITS(state->lenbits)];
  78908. if ((unsigned)(thisx.bits) <= bits) break;
  78909. PULLBYTE();
  78910. }
  78911. if (thisx.op && (thisx.op & 0xf0) == 0) {
  78912. last = thisx;
  78913. for (;;) {
  78914. thisx = state->lencode[last.val +
  78915. (BITS(last.bits + last.op) >> last.bits)];
  78916. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  78917. PULLBYTE();
  78918. }
  78919. DROPBITS(last.bits);
  78920. }
  78921. DROPBITS(thisx.bits);
  78922. state->length = (unsigned)thisx.val;
  78923. if ((int)(thisx.op) == 0) {
  78924. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  78925. "inflate: literal '%c'\n" :
  78926. "inflate: literal 0x%02x\n", thisx.val));
  78927. state->mode = LIT;
  78928. break;
  78929. }
  78930. if (thisx.op & 32) {
  78931. Tracevv((stderr, "inflate: end of block\n"));
  78932. state->mode = TYPE;
  78933. break;
  78934. }
  78935. if (thisx.op & 64) {
  78936. strm->msg = (char *)"invalid literal/length code";
  78937. state->mode = BAD;
  78938. break;
  78939. }
  78940. state->extra = (unsigned)(thisx.op) & 15;
  78941. state->mode = LENEXT;
  78942. case LENEXT:
  78943. if (state->extra) {
  78944. NEEDBITS(state->extra);
  78945. state->length += BITS(state->extra);
  78946. DROPBITS(state->extra);
  78947. }
  78948. Tracevv((stderr, "inflate: length %u\n", state->length));
  78949. state->mode = DIST;
  78950. case DIST:
  78951. for (;;) {
  78952. thisx = state->distcode[BITS(state->distbits)];
  78953. if ((unsigned)(thisx.bits) <= bits) break;
  78954. PULLBYTE();
  78955. }
  78956. if ((thisx.op & 0xf0) == 0) {
  78957. last = thisx;
  78958. for (;;) {
  78959. thisx = state->distcode[last.val +
  78960. (BITS(last.bits + last.op) >> last.bits)];
  78961. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  78962. PULLBYTE();
  78963. }
  78964. DROPBITS(last.bits);
  78965. }
  78966. DROPBITS(thisx.bits);
  78967. if (thisx.op & 64) {
  78968. strm->msg = (char *)"invalid distance code";
  78969. state->mode = BAD;
  78970. break;
  78971. }
  78972. state->offset = (unsigned)thisx.val;
  78973. state->extra = (unsigned)(thisx.op) & 15;
  78974. state->mode = DISTEXT;
  78975. case DISTEXT:
  78976. if (state->extra) {
  78977. NEEDBITS(state->extra);
  78978. state->offset += BITS(state->extra);
  78979. DROPBITS(state->extra);
  78980. }
  78981. #ifdef INFLATE_STRICT
  78982. if (state->offset > state->dmax) {
  78983. strm->msg = (char *)"invalid distance too far back";
  78984. state->mode = BAD;
  78985. break;
  78986. }
  78987. #endif
  78988. if (state->offset > state->whave + out - left) {
  78989. strm->msg = (char *)"invalid distance too far back";
  78990. state->mode = BAD;
  78991. break;
  78992. }
  78993. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  78994. state->mode = MATCH;
  78995. case MATCH:
  78996. if (left == 0) goto inf_leave;
  78997. copy = out - left;
  78998. if (state->offset > copy) { /* copy from window */
  78999. copy = state->offset - copy;
  79000. if (copy > state->write) {
  79001. copy -= state->write;
  79002. from = state->window + (state->wsize - copy);
  79003. }
  79004. else
  79005. from = state->window + (state->write - copy);
  79006. if (copy > state->length) copy = state->length;
  79007. }
  79008. else { /* copy from output */
  79009. from = put - state->offset;
  79010. copy = state->length;
  79011. }
  79012. if (copy > left) copy = left;
  79013. left -= copy;
  79014. state->length -= copy;
  79015. do {
  79016. *put++ = *from++;
  79017. } while (--copy);
  79018. if (state->length == 0) state->mode = LEN;
  79019. break;
  79020. case LIT:
  79021. if (left == 0) goto inf_leave;
  79022. *put++ = (unsigned char)(state->length);
  79023. left--;
  79024. state->mode = LEN;
  79025. break;
  79026. case CHECK:
  79027. if (state->wrap) {
  79028. NEEDBITS(32);
  79029. out -= left;
  79030. strm->total_out += out;
  79031. state->total += out;
  79032. if (out)
  79033. strm->adler = state->check =
  79034. UPDATE(state->check, put - out, out);
  79035. out = left;
  79036. if ((
  79037. #ifdef GUNZIP
  79038. state->flags ? hold :
  79039. #endif
  79040. REVERSE(hold)) != state->check) {
  79041. strm->msg = (char *)"incorrect data check";
  79042. state->mode = BAD;
  79043. break;
  79044. }
  79045. INITBITS();
  79046. Tracev((stderr, "inflate: check matches trailer\n"));
  79047. }
  79048. #ifdef GUNZIP
  79049. state->mode = LENGTH;
  79050. case LENGTH:
  79051. if (state->wrap && state->flags) {
  79052. NEEDBITS(32);
  79053. if (hold != (state->total & 0xffffffffUL)) {
  79054. strm->msg = (char *)"incorrect length check";
  79055. state->mode = BAD;
  79056. break;
  79057. }
  79058. INITBITS();
  79059. Tracev((stderr, "inflate: length matches trailer\n"));
  79060. }
  79061. #endif
  79062. state->mode = DONE;
  79063. case DONE:
  79064. ret = Z_STREAM_END;
  79065. goto inf_leave;
  79066. case BAD:
  79067. ret = Z_DATA_ERROR;
  79068. goto inf_leave;
  79069. case MEM:
  79070. return Z_MEM_ERROR;
  79071. case SYNC:
  79072. default:
  79073. return Z_STREAM_ERROR;
  79074. }
  79075. /*
  79076. Return from inflate(), updating the total counts and the check value.
  79077. If there was no progress during the inflate() call, return a buffer
  79078. error. Call updatewindow() to create and/or update the window state.
  79079. Note: a memory error from inflate() is non-recoverable.
  79080. */
  79081. inf_leave:
  79082. RESTORE();
  79083. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  79084. if (updatewindow(strm, out)) {
  79085. state->mode = MEM;
  79086. return Z_MEM_ERROR;
  79087. }
  79088. in -= strm->avail_in;
  79089. out -= strm->avail_out;
  79090. strm->total_in += in;
  79091. strm->total_out += out;
  79092. state->total += out;
  79093. if (state->wrap && out)
  79094. strm->adler = state->check =
  79095. UPDATE(state->check, strm->next_out - out, out);
  79096. strm->data_type = state->bits + (state->last ? 64 : 0) +
  79097. (state->mode == TYPE ? 128 : 0);
  79098. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  79099. ret = Z_BUF_ERROR;
  79100. return ret;
  79101. }
  79102. int ZEXPORT inflateEnd (z_streamp strm)
  79103. {
  79104. struct inflate_state FAR *state;
  79105. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  79106. return Z_STREAM_ERROR;
  79107. state = (struct inflate_state FAR *)strm->state;
  79108. if (state->window != Z_NULL) ZFREE(strm, state->window);
  79109. ZFREE(strm, strm->state);
  79110. strm->state = Z_NULL;
  79111. Tracev((stderr, "inflate: end\n"));
  79112. return Z_OK;
  79113. }
  79114. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  79115. {
  79116. struct inflate_state FAR *state;
  79117. unsigned long id_;
  79118. /* check state */
  79119. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79120. state = (struct inflate_state FAR *)strm->state;
  79121. if (state->wrap != 0 && state->mode != DICT)
  79122. return Z_STREAM_ERROR;
  79123. /* check for correct dictionary id */
  79124. if (state->mode == DICT) {
  79125. id_ = adler32(0L, Z_NULL, 0);
  79126. id_ = adler32(id_, dictionary, dictLength);
  79127. if (id_ != state->check)
  79128. return Z_DATA_ERROR;
  79129. }
  79130. /* copy dictionary to window */
  79131. if (updatewindow(strm, strm->avail_out)) {
  79132. state->mode = MEM;
  79133. return Z_MEM_ERROR;
  79134. }
  79135. if (dictLength > state->wsize) {
  79136. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  79137. state->wsize);
  79138. state->whave = state->wsize;
  79139. }
  79140. else {
  79141. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  79142. dictLength);
  79143. state->whave = dictLength;
  79144. }
  79145. state->havedict = 1;
  79146. Tracev((stderr, "inflate: dictionary set\n"));
  79147. return Z_OK;
  79148. }
  79149. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  79150. {
  79151. struct inflate_state FAR *state;
  79152. /* check state */
  79153. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79154. state = (struct inflate_state FAR *)strm->state;
  79155. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  79156. /* save header structure */
  79157. state->head = head;
  79158. head->done = 0;
  79159. return Z_OK;
  79160. }
  79161. /*
  79162. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  79163. or when out of input. When called, *have is the number of pattern bytes
  79164. found in order so far, in 0..3. On return *have is updated to the new
  79165. state. If on return *have equals four, then the pattern was found and the
  79166. return value is how many bytes were read including the last byte of the
  79167. pattern. If *have is less than four, then the pattern has not been found
  79168. yet and the return value is len. In the latter case, syncsearch() can be
  79169. called again with more data and the *have state. *have is initialized to
  79170. zero for the first call.
  79171. */
  79172. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  79173. {
  79174. unsigned got;
  79175. unsigned next;
  79176. got = *have;
  79177. next = 0;
  79178. while (next < len && got < 4) {
  79179. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  79180. got++;
  79181. else if (buf[next])
  79182. got = 0;
  79183. else
  79184. got = 4 - got;
  79185. next++;
  79186. }
  79187. *have = got;
  79188. return next;
  79189. }
  79190. int ZEXPORT inflateSync (z_streamp strm)
  79191. {
  79192. unsigned len; /* number of bytes to look at or looked at */
  79193. unsigned long in, out; /* temporary to save total_in and total_out */
  79194. unsigned char buf[4]; /* to restore bit buffer to byte string */
  79195. struct inflate_state FAR *state;
  79196. /* check parameters */
  79197. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79198. state = (struct inflate_state FAR *)strm->state;
  79199. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  79200. /* if first time, start search in bit buffer */
  79201. if (state->mode != SYNC) {
  79202. state->mode = SYNC;
  79203. state->hold <<= state->bits & 7;
  79204. state->bits -= state->bits & 7;
  79205. len = 0;
  79206. while (state->bits >= 8) {
  79207. buf[len++] = (unsigned char)(state->hold);
  79208. state->hold >>= 8;
  79209. state->bits -= 8;
  79210. }
  79211. state->have = 0;
  79212. syncsearch(&(state->have), buf, len);
  79213. }
  79214. /* search available input */
  79215. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  79216. strm->avail_in -= len;
  79217. strm->next_in += len;
  79218. strm->total_in += len;
  79219. /* return no joy or set up to restart inflate() on a new block */
  79220. if (state->have != 4) return Z_DATA_ERROR;
  79221. in = strm->total_in; out = strm->total_out;
  79222. inflateReset(strm);
  79223. strm->total_in = in; strm->total_out = out;
  79224. state->mode = TYPE;
  79225. return Z_OK;
  79226. }
  79227. /*
  79228. Returns true if inflate is currently at the end of a block generated by
  79229. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  79230. implementation to provide an additional safety check. PPP uses
  79231. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  79232. block. When decompressing, PPP checks that at the end of input packet,
  79233. inflate is waiting for these length bytes.
  79234. */
  79235. int ZEXPORT inflateSyncPoint (z_streamp strm)
  79236. {
  79237. struct inflate_state FAR *state;
  79238. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79239. state = (struct inflate_state FAR *)strm->state;
  79240. return state->mode == STORED && state->bits == 0;
  79241. }
  79242. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  79243. {
  79244. struct inflate_state FAR *state;
  79245. struct inflate_state FAR *copy;
  79246. unsigned char FAR *window;
  79247. unsigned wsize;
  79248. /* check input */
  79249. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  79250. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  79251. return Z_STREAM_ERROR;
  79252. state = (struct inflate_state FAR *)source->state;
  79253. /* allocate space */
  79254. copy = (struct inflate_state FAR *)
  79255. ZALLOC(source, 1, sizeof(struct inflate_state));
  79256. if (copy == Z_NULL) return Z_MEM_ERROR;
  79257. window = Z_NULL;
  79258. if (state->window != Z_NULL) {
  79259. window = (unsigned char FAR *)
  79260. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  79261. if (window == Z_NULL) {
  79262. ZFREE(source, copy);
  79263. return Z_MEM_ERROR;
  79264. }
  79265. }
  79266. /* copy state */
  79267. zmemcpy(dest, source, sizeof(z_stream));
  79268. zmemcpy(copy, state, sizeof(struct inflate_state));
  79269. if (state->lencode >= state->codes &&
  79270. state->lencode <= state->codes + ENOUGH - 1) {
  79271. copy->lencode = copy->codes + (state->lencode - state->codes);
  79272. copy->distcode = copy->codes + (state->distcode - state->codes);
  79273. }
  79274. copy->next = copy->codes + (state->next - state->codes);
  79275. if (window != Z_NULL) {
  79276. wsize = 1U << state->wbits;
  79277. zmemcpy(window, state->window, wsize);
  79278. }
  79279. copy->window = window;
  79280. dest->state = (struct internal_state FAR *)copy;
  79281. return Z_OK;
  79282. }
  79283. /********* End of inlined file: inflate.c *********/
  79284. /********* Start of inlined file: inftrees.c *********/
  79285. #define MAXBITS 15
  79286. const char inflate_copyright[] =
  79287. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  79288. /*
  79289. If you use the zlib library in a product, an acknowledgment is welcome
  79290. in the documentation of your product. If for some reason you cannot
  79291. include such an acknowledgment, I would appreciate that you keep this
  79292. copyright string in the executable of your product.
  79293. */
  79294. /*
  79295. Build a set of tables to decode the provided canonical Huffman code.
  79296. The code lengths are lens[0..codes-1]. The result starts at *table,
  79297. whose indices are 0..2^bits-1. work is a writable array of at least
  79298. lens shorts, which is used as a work area. type is the type of code
  79299. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  79300. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  79301. on return points to the next available entry's address. bits is the
  79302. requested root table index bits, and on return it is the actual root
  79303. table index bits. It will differ if the request is greater than the
  79304. longest code or if it is less than the shortest code.
  79305. */
  79306. int inflate_table (codetype type,
  79307. unsigned short FAR *lens,
  79308. unsigned codes,
  79309. code FAR * FAR *table,
  79310. unsigned FAR *bits,
  79311. unsigned short FAR *work)
  79312. {
  79313. unsigned len; /* a code's length in bits */
  79314. unsigned sym; /* index of code symbols */
  79315. unsigned min, max; /* minimum and maximum code lengths */
  79316. unsigned root; /* number of index bits for root table */
  79317. unsigned curr; /* number of index bits for current table */
  79318. unsigned drop; /* code bits to drop for sub-table */
  79319. int left; /* number of prefix codes available */
  79320. unsigned used; /* code entries in table used */
  79321. unsigned huff; /* Huffman code */
  79322. unsigned incr; /* for incrementing code, index */
  79323. unsigned fill; /* index for replicating entries */
  79324. unsigned low; /* low bits for current root entry */
  79325. unsigned mask; /* mask for low root bits */
  79326. code thisx; /* table entry for duplication */
  79327. code FAR *next; /* next available space in table */
  79328. const unsigned short FAR *base; /* base value table to use */
  79329. const unsigned short FAR *extra; /* extra bits table to use */
  79330. int end; /* use base and extra for symbol > end */
  79331. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  79332. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  79333. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  79334. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  79335. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  79336. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  79337. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  79338. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  79339. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  79340. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  79341. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  79342. 8193, 12289, 16385, 24577, 0, 0};
  79343. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  79344. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  79345. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  79346. 28, 28, 29, 29, 64, 64};
  79347. /*
  79348. Process a set of code lengths to create a canonical Huffman code. The
  79349. code lengths are lens[0..codes-1]. Each length corresponds to the
  79350. symbols 0..codes-1. The Huffman code is generated by first sorting the
  79351. symbols by length from short to long, and retaining the symbol order
  79352. for codes with equal lengths. Then the code starts with all zero bits
  79353. for the first code of the shortest length, and the codes are integer
  79354. increments for the same length, and zeros are appended as the length
  79355. increases. For the deflate format, these bits are stored backwards
  79356. from their more natural integer increment ordering, and so when the
  79357. decoding tables are built in the large loop below, the integer codes
  79358. are incremented backwards.
  79359. This routine assumes, but does not check, that all of the entries in
  79360. lens[] are in the range 0..MAXBITS. The caller must assure this.
  79361. 1..MAXBITS is interpreted as that code length. zero means that that
  79362. symbol does not occur in this code.
  79363. The codes are sorted by computing a count of codes for each length,
  79364. creating from that a table of starting indices for each length in the
  79365. sorted table, and then entering the symbols in order in the sorted
  79366. table. The sorted table is work[], with that space being provided by
  79367. the caller.
  79368. The length counts are used for other purposes as well, i.e. finding
  79369. the minimum and maximum length codes, determining if there are any
  79370. codes at all, checking for a valid set of lengths, and looking ahead
  79371. at length counts to determine sub-table sizes when building the
  79372. decoding tables.
  79373. */
  79374. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  79375. for (len = 0; len <= MAXBITS; len++)
  79376. count[len] = 0;
  79377. for (sym = 0; sym < codes; sym++)
  79378. count[lens[sym]]++;
  79379. /* bound code lengths, force root to be within code lengths */
  79380. root = *bits;
  79381. for (max = MAXBITS; max >= 1; max--)
  79382. if (count[max] != 0) break;
  79383. if (root > max) root = max;
  79384. if (max == 0) { /* no symbols to code at all */
  79385. thisx.op = (unsigned char)64; /* invalid code marker */
  79386. thisx.bits = (unsigned char)1;
  79387. thisx.val = (unsigned short)0;
  79388. *(*table)++ = thisx; /* make a table to force an error */
  79389. *(*table)++ = thisx;
  79390. *bits = 1;
  79391. return 0; /* no symbols, but wait for decoding to report error */
  79392. }
  79393. for (min = 1; min <= MAXBITS; min++)
  79394. if (count[min] != 0) break;
  79395. if (root < min) root = min;
  79396. /* check for an over-subscribed or incomplete set of lengths */
  79397. left = 1;
  79398. for (len = 1; len <= MAXBITS; len++) {
  79399. left <<= 1;
  79400. left -= count[len];
  79401. if (left < 0) return -1; /* over-subscribed */
  79402. }
  79403. if (left > 0 && (type == CODES || max != 1))
  79404. return -1; /* incomplete set */
  79405. /* generate offsets into symbol table for each length for sorting */
  79406. offs[1] = 0;
  79407. for (len = 1; len < MAXBITS; len++)
  79408. offs[len + 1] = offs[len] + count[len];
  79409. /* sort symbols by length, by symbol order within each length */
  79410. for (sym = 0; sym < codes; sym++)
  79411. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  79412. /*
  79413. Create and fill in decoding tables. In this loop, the table being
  79414. filled is at next and has curr index bits. The code being used is huff
  79415. with length len. That code is converted to an index by dropping drop
  79416. bits off of the bottom. For codes where len is less than drop + curr,
  79417. those top drop + curr - len bits are incremented through all values to
  79418. fill the table with replicated entries.
  79419. root is the number of index bits for the root table. When len exceeds
  79420. root, sub-tables are created pointed to by the root entry with an index
  79421. of the low root bits of huff. This is saved in low to check for when a
  79422. new sub-table should be started. drop is zero when the root table is
  79423. being filled, and drop is root when sub-tables are being filled.
  79424. When a new sub-table is needed, it is necessary to look ahead in the
  79425. code lengths to determine what size sub-table is needed. The length
  79426. counts are used for this, and so count[] is decremented as codes are
  79427. entered in the tables.
  79428. used keeps track of how many table entries have been allocated from the
  79429. provided *table space. It is checked when a LENS table is being made
  79430. against the space in *table, ENOUGH, minus the maximum space needed by
  79431. the worst case distance code, MAXD. This should never happen, but the
  79432. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  79433. This assumes that when type == LENS, bits == 9.
  79434. sym increments through all symbols, and the loop terminates when
  79435. all codes of length max, i.e. all codes, have been processed. This
  79436. routine permits incomplete codes, so another loop after this one fills
  79437. in the rest of the decoding tables with invalid code markers.
  79438. */
  79439. /* set up for code type */
  79440. switch (type) {
  79441. case CODES:
  79442. base = extra = work; /* dummy value--not used */
  79443. end = 19;
  79444. break;
  79445. case LENS:
  79446. base = lbase;
  79447. base -= 257;
  79448. extra = lext;
  79449. extra -= 257;
  79450. end = 256;
  79451. break;
  79452. default: /* DISTS */
  79453. base = dbase;
  79454. extra = dext;
  79455. end = -1;
  79456. }
  79457. /* initialize state for loop */
  79458. huff = 0; /* starting code */
  79459. sym = 0; /* starting code symbol */
  79460. len = min; /* starting code length */
  79461. next = *table; /* current table to fill in */
  79462. curr = root; /* current table index bits */
  79463. drop = 0; /* current bits to drop from code for index */
  79464. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  79465. used = 1U << root; /* use root table entries */
  79466. mask = used - 1; /* mask for comparing low */
  79467. /* check available table space */
  79468. if (type == LENS && used >= ENOUGH - MAXD)
  79469. return 1;
  79470. /* process all codes and make table entries */
  79471. for (;;) {
  79472. /* create table entry */
  79473. thisx.bits = (unsigned char)(len - drop);
  79474. if ((int)(work[sym]) < end) {
  79475. thisx.op = (unsigned char)0;
  79476. thisx.val = work[sym];
  79477. }
  79478. else if ((int)(work[sym]) > end) {
  79479. thisx.op = (unsigned char)(extra[work[sym]]);
  79480. thisx.val = base[work[sym]];
  79481. }
  79482. else {
  79483. thisx.op = (unsigned char)(32 + 64); /* end of block */
  79484. thisx.val = 0;
  79485. }
  79486. /* replicate for those indices with low len bits equal to huff */
  79487. incr = 1U << (len - drop);
  79488. fill = 1U << curr;
  79489. min = fill; /* save offset to next table */
  79490. do {
  79491. fill -= incr;
  79492. next[(huff >> drop) + fill] = thisx;
  79493. } while (fill != 0);
  79494. /* backwards increment the len-bit code huff */
  79495. incr = 1U << (len - 1);
  79496. while (huff & incr)
  79497. incr >>= 1;
  79498. if (incr != 0) {
  79499. huff &= incr - 1;
  79500. huff += incr;
  79501. }
  79502. else
  79503. huff = 0;
  79504. /* go to next symbol, update count, len */
  79505. sym++;
  79506. if (--(count[len]) == 0) {
  79507. if (len == max) break;
  79508. len = lens[work[sym]];
  79509. }
  79510. /* create new sub-table if needed */
  79511. if (len > root && (huff & mask) != low) {
  79512. /* if first time, transition to sub-tables */
  79513. if (drop == 0)
  79514. drop = root;
  79515. /* increment past last table */
  79516. next += min; /* here min is 1 << curr */
  79517. /* determine length of next table */
  79518. curr = len - drop;
  79519. left = (int)(1 << curr);
  79520. while (curr + drop < max) {
  79521. left -= count[curr + drop];
  79522. if (left <= 0) break;
  79523. curr++;
  79524. left <<= 1;
  79525. }
  79526. /* check for enough space */
  79527. used += 1U << curr;
  79528. if (type == LENS && used >= ENOUGH - MAXD)
  79529. return 1;
  79530. /* point entry in root table to sub-table */
  79531. low = huff & mask;
  79532. (*table)[low].op = (unsigned char)curr;
  79533. (*table)[low].bits = (unsigned char)root;
  79534. (*table)[low].val = (unsigned short)(next - *table);
  79535. }
  79536. }
  79537. /*
  79538. Fill in rest of table for incomplete codes. This loop is similar to the
  79539. loop above in incrementing huff for table indices. It is assumed that
  79540. len is equal to curr + drop, so there is no loop needed to increment
  79541. through high index bits. When the current sub-table is filled, the loop
  79542. drops back to the root table to fill in any remaining entries there.
  79543. */
  79544. thisx.op = (unsigned char)64; /* invalid code marker */
  79545. thisx.bits = (unsigned char)(len - drop);
  79546. thisx.val = (unsigned short)0;
  79547. while (huff != 0) {
  79548. /* when done with sub-table, drop back to root table */
  79549. if (drop != 0 && (huff & mask) != low) {
  79550. drop = 0;
  79551. len = root;
  79552. next = *table;
  79553. thisx.bits = (unsigned char)len;
  79554. }
  79555. /* put invalid code marker in table */
  79556. next[huff >> drop] = thisx;
  79557. /* backwards increment the len-bit code huff */
  79558. incr = 1U << (len - 1);
  79559. while (huff & incr)
  79560. incr >>= 1;
  79561. if (incr != 0) {
  79562. huff &= incr - 1;
  79563. huff += incr;
  79564. }
  79565. else
  79566. huff = 0;
  79567. }
  79568. /* set return parameters */
  79569. *table += used;
  79570. *bits = root;
  79571. return 0;
  79572. }
  79573. /********* End of inlined file: inftrees.c *********/
  79574. /********* Start of inlined file: trees.c *********/
  79575. /*
  79576. * ALGORITHM
  79577. *
  79578. * The "deflation" process uses several Huffman trees. The more
  79579. * common source values are represented by shorter bit sequences.
  79580. *
  79581. * Each code tree is stored in a compressed form which is itself
  79582. * a Huffman encoding of the lengths of all the code strings (in
  79583. * ascending order by source values). The actual code strings are
  79584. * reconstructed from the lengths in the inflate process, as described
  79585. * in the deflate specification.
  79586. *
  79587. * REFERENCES
  79588. *
  79589. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  79590. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  79591. *
  79592. * Storer, James A.
  79593. * Data Compression: Methods and Theory, pp. 49-50.
  79594. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  79595. *
  79596. * Sedgewick, R.
  79597. * Algorithms, p290.
  79598. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  79599. */
  79600. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79601. /* #define GEN_TREES_H */
  79602. #ifdef DEBUG
  79603. # include <ctype.h>
  79604. #endif
  79605. /* ===========================================================================
  79606. * Constants
  79607. */
  79608. #define MAX_BL_BITS 7
  79609. /* Bit length codes must not exceed MAX_BL_BITS bits */
  79610. #define END_BLOCK 256
  79611. /* end of block literal code */
  79612. #define REP_3_6 16
  79613. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  79614. #define REPZ_3_10 17
  79615. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  79616. #define REPZ_11_138 18
  79617. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  79618. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  79619. = {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};
  79620. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  79621. = {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};
  79622. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  79623. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  79624. local const uch bl_order[BL_CODES]
  79625. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  79626. /* The lengths of the bit length codes are sent in order of decreasing
  79627. * probability, to avoid transmitting the lengths for unused bit length codes.
  79628. */
  79629. #define Buf_size (8 * 2*sizeof(char))
  79630. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  79631. * more than 16 bits on some systems.)
  79632. */
  79633. /* ===========================================================================
  79634. * Local data. These are initialized only once.
  79635. */
  79636. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  79637. #if defined(GEN_TREES_H) || !defined(STDC)
  79638. /* non ANSI compilers may not accept trees.h */
  79639. local ct_data static_ltree[L_CODES+2];
  79640. /* The static literal tree. Since the bit lengths are imposed, there is no
  79641. * need for the L_CODES extra codes used during heap construction. However
  79642. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  79643. * below).
  79644. */
  79645. local ct_data static_dtree[D_CODES];
  79646. /* The static distance tree. (Actually a trivial tree since all codes use
  79647. * 5 bits.)
  79648. */
  79649. uch _dist_code[DIST_CODE_LEN];
  79650. /* Distance codes. The first 256 values correspond to the distances
  79651. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  79652. * the 15 bit distances.
  79653. */
  79654. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  79655. /* length code for each normalized match length (0 == MIN_MATCH) */
  79656. local int base_length[LENGTH_CODES];
  79657. /* First normalized length for each code (0 = MIN_MATCH) */
  79658. local int base_dist[D_CODES];
  79659. /* First normalized distance for each code (0 = distance of 1) */
  79660. #else
  79661. /********* Start of inlined file: trees.h *********/
  79662. local const ct_data static_ltree[L_CODES+2] = {
  79663. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  79664. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  79665. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  79666. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  79667. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  79668. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  79669. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  79670. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  79671. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  79672. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  79673. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  79674. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  79675. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  79676. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  79677. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  79678. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  79679. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  79680. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  79681. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  79682. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  79683. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  79684. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  79685. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  79686. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  79687. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  79688. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  79689. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  79690. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  79691. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  79692. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  79693. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  79694. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  79695. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  79696. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  79697. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  79698. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  79699. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  79700. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  79701. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  79702. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  79703. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  79704. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  79705. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  79706. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  79707. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  79708. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  79709. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  79710. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  79711. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  79712. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  79713. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  79714. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  79715. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  79716. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  79717. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  79718. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  79719. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  79720. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  79721. };
  79722. local const ct_data static_dtree[D_CODES] = {
  79723. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  79724. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  79725. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  79726. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  79727. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  79728. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  79729. };
  79730. const uch _dist_code[DIST_CODE_LEN] = {
  79731. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  79732. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  79733. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  79734. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  79735. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  79736. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  79737. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  79738. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  79739. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  79740. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  79741. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  79742. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  79743. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  79744. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  79745. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  79746. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  79747. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  79748. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  79749. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  79750. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  79751. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  79752. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  79753. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  79754. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  79755. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  79756. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  79757. };
  79758. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  79759. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  79760. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  79761. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  79762. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  79763. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  79764. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  79765. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  79766. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  79767. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  79768. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  79769. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  79770. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  79771. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  79772. };
  79773. local const int base_length[LENGTH_CODES] = {
  79774. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  79775. 64, 80, 96, 112, 128, 160, 192, 224, 0
  79776. };
  79777. local const int base_dist[D_CODES] = {
  79778. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  79779. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  79780. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  79781. };
  79782. /********* End of inlined file: trees.h *********/
  79783. #endif /* GEN_TREES_H */
  79784. struct static_tree_desc_s {
  79785. const ct_data *static_tree; /* static tree or NULL */
  79786. const intf *extra_bits; /* extra bits for each code or NULL */
  79787. int extra_base; /* base index for extra_bits */
  79788. int elems; /* max number of elements in the tree */
  79789. int max_length; /* max bit length for the codes */
  79790. };
  79791. local static_tree_desc static_l_desc =
  79792. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  79793. local static_tree_desc static_d_desc =
  79794. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  79795. local static_tree_desc static_bl_desc =
  79796. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  79797. /* ===========================================================================
  79798. * Local (static) routines in this file.
  79799. */
  79800. local void tr_static_init OF((void));
  79801. local void init_block OF((deflate_state *s));
  79802. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  79803. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  79804. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  79805. local void build_tree OF((deflate_state *s, tree_desc *desc));
  79806. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  79807. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  79808. local int build_bl_tree OF((deflate_state *s));
  79809. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  79810. int blcodes));
  79811. local void compress_block OF((deflate_state *s, ct_data *ltree,
  79812. ct_data *dtree));
  79813. local void set_data_type OF((deflate_state *s));
  79814. local unsigned bi_reverse OF((unsigned value, int length));
  79815. local void bi_windup OF((deflate_state *s));
  79816. local void bi_flush OF((deflate_state *s));
  79817. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  79818. int header));
  79819. #ifdef GEN_TREES_H
  79820. local void gen_trees_header OF((void));
  79821. #endif
  79822. #ifndef DEBUG
  79823. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  79824. /* Send a code of the given tree. c and tree must not have side effects */
  79825. #else /* DEBUG */
  79826. # define send_code(s, c, tree) \
  79827. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  79828. send_bits(s, tree[c].Code, tree[c].Len); }
  79829. #endif
  79830. /* ===========================================================================
  79831. * Output a short LSB first on the stream.
  79832. * IN assertion: there is enough room in pendingBuf.
  79833. */
  79834. #define put_short(s, w) { \
  79835. put_byte(s, (uch)((w) & 0xff)); \
  79836. put_byte(s, (uch)((ush)(w) >> 8)); \
  79837. }
  79838. /* ===========================================================================
  79839. * Send a value on a given number of bits.
  79840. * IN assertion: length <= 16 and value fits in length bits.
  79841. */
  79842. #ifdef DEBUG
  79843. local void send_bits OF((deflate_state *s, int value, int length));
  79844. local void send_bits (deflate_state *s, int value, int length)
  79845. {
  79846. Tracevv((stderr," l %2d v %4x ", length, value));
  79847. Assert(length > 0 && length <= 15, "invalid length");
  79848. s->bits_sent += (ulg)length;
  79849. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  79850. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  79851. * unused bits in value.
  79852. */
  79853. if (s->bi_valid > (int)Buf_size - length) {
  79854. s->bi_buf |= (value << s->bi_valid);
  79855. put_short(s, s->bi_buf);
  79856. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  79857. s->bi_valid += length - Buf_size;
  79858. } else {
  79859. s->bi_buf |= value << s->bi_valid;
  79860. s->bi_valid += length;
  79861. }
  79862. }
  79863. #else /* !DEBUG */
  79864. #define send_bits(s, value, length) \
  79865. { int len = length;\
  79866. if (s->bi_valid > (int)Buf_size - len) {\
  79867. int val = value;\
  79868. s->bi_buf |= (val << s->bi_valid);\
  79869. put_short(s, s->bi_buf);\
  79870. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  79871. s->bi_valid += len - Buf_size;\
  79872. } else {\
  79873. s->bi_buf |= (value) << s->bi_valid;\
  79874. s->bi_valid += len;\
  79875. }\
  79876. }
  79877. #endif /* DEBUG */
  79878. /* the arguments must not have side effects */
  79879. /* ===========================================================================
  79880. * Initialize the various 'constant' tables.
  79881. */
  79882. local void tr_static_init()
  79883. {
  79884. #if defined(GEN_TREES_H) || !defined(STDC)
  79885. static int static_init_done = 0;
  79886. int n; /* iterates over tree elements */
  79887. int bits; /* bit counter */
  79888. int length; /* length value */
  79889. int code; /* code value */
  79890. int dist; /* distance index */
  79891. ush bl_count[MAX_BITS+1];
  79892. /* number of codes at each bit length for an optimal tree */
  79893. if (static_init_done) return;
  79894. /* For some embedded targets, global variables are not initialized: */
  79895. static_l_desc.static_tree = static_ltree;
  79896. static_l_desc.extra_bits = extra_lbits;
  79897. static_d_desc.static_tree = static_dtree;
  79898. static_d_desc.extra_bits = extra_dbits;
  79899. static_bl_desc.extra_bits = extra_blbits;
  79900. /* Initialize the mapping length (0..255) -> length code (0..28) */
  79901. length = 0;
  79902. for (code = 0; code < LENGTH_CODES-1; code++) {
  79903. base_length[code] = length;
  79904. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  79905. _length_code[length++] = (uch)code;
  79906. }
  79907. }
  79908. Assert (length == 256, "tr_static_init: length != 256");
  79909. /* Note that the length 255 (match length 258) can be represented
  79910. * in two different ways: code 284 + 5 bits or code 285, so we
  79911. * overwrite length_code[255] to use the best encoding:
  79912. */
  79913. _length_code[length-1] = (uch)code;
  79914. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  79915. dist = 0;
  79916. for (code = 0 ; code < 16; code++) {
  79917. base_dist[code] = dist;
  79918. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  79919. _dist_code[dist++] = (uch)code;
  79920. }
  79921. }
  79922. Assert (dist == 256, "tr_static_init: dist != 256");
  79923. dist >>= 7; /* from now on, all distances are divided by 128 */
  79924. for ( ; code < D_CODES; code++) {
  79925. base_dist[code] = dist << 7;
  79926. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  79927. _dist_code[256 + dist++] = (uch)code;
  79928. }
  79929. }
  79930. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  79931. /* Construct the codes of the static literal tree */
  79932. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  79933. n = 0;
  79934. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  79935. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  79936. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  79937. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  79938. /* Codes 286 and 287 do not exist, but we must include them in the
  79939. * tree construction to get a canonical Huffman tree (longest code
  79940. * all ones)
  79941. */
  79942. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  79943. /* The static distance tree is trivial: */
  79944. for (n = 0; n < D_CODES; n++) {
  79945. static_dtree[n].Len = 5;
  79946. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  79947. }
  79948. static_init_done = 1;
  79949. # ifdef GEN_TREES_H
  79950. gen_trees_header();
  79951. # endif
  79952. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  79953. }
  79954. /* ===========================================================================
  79955. * Genererate the file trees.h describing the static trees.
  79956. */
  79957. #ifdef GEN_TREES_H
  79958. # ifndef DEBUG
  79959. # include <stdio.h>
  79960. # endif
  79961. # define SEPARATOR(i, last, width) \
  79962. ((i) == (last)? "\n};\n\n" : \
  79963. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  79964. void gen_trees_header()
  79965. {
  79966. FILE *header = fopen("trees.h", "w");
  79967. int i;
  79968. Assert (header != NULL, "Can't open trees.h");
  79969. fprintf(header,
  79970. "/* header created automatically with -DGEN_TREES_H */\n\n");
  79971. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  79972. for (i = 0; i < L_CODES+2; i++) {
  79973. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  79974. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  79975. }
  79976. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  79977. for (i = 0; i < D_CODES; i++) {
  79978. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  79979. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  79980. }
  79981. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  79982. for (i = 0; i < DIST_CODE_LEN; i++) {
  79983. fprintf(header, "%2u%s", _dist_code[i],
  79984. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  79985. }
  79986. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  79987. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  79988. fprintf(header, "%2u%s", _length_code[i],
  79989. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  79990. }
  79991. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  79992. for (i = 0; i < LENGTH_CODES; i++) {
  79993. fprintf(header, "%1u%s", base_length[i],
  79994. SEPARATOR(i, LENGTH_CODES-1, 20));
  79995. }
  79996. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  79997. for (i = 0; i < D_CODES; i++) {
  79998. fprintf(header, "%5u%s", base_dist[i],
  79999. SEPARATOR(i, D_CODES-1, 10));
  80000. }
  80001. fclose(header);
  80002. }
  80003. #endif /* GEN_TREES_H */
  80004. /* ===========================================================================
  80005. * Initialize the tree data structures for a new zlib stream.
  80006. */
  80007. void _tr_init(deflate_state *s)
  80008. {
  80009. tr_static_init();
  80010. s->l_desc.dyn_tree = s->dyn_ltree;
  80011. s->l_desc.stat_desc = &static_l_desc;
  80012. s->d_desc.dyn_tree = s->dyn_dtree;
  80013. s->d_desc.stat_desc = &static_d_desc;
  80014. s->bl_desc.dyn_tree = s->bl_tree;
  80015. s->bl_desc.stat_desc = &static_bl_desc;
  80016. s->bi_buf = 0;
  80017. s->bi_valid = 0;
  80018. s->last_eob_len = 8; /* enough lookahead for inflate */
  80019. #ifdef DEBUG
  80020. s->compressed_len = 0L;
  80021. s->bits_sent = 0L;
  80022. #endif
  80023. /* Initialize the first block of the first file: */
  80024. init_block(s);
  80025. }
  80026. /* ===========================================================================
  80027. * Initialize a new block.
  80028. */
  80029. local void init_block (deflate_state *s)
  80030. {
  80031. int n; /* iterates over tree elements */
  80032. /* Initialize the trees. */
  80033. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  80034. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  80035. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  80036. s->dyn_ltree[END_BLOCK].Freq = 1;
  80037. s->opt_len = s->static_len = 0L;
  80038. s->last_lit = s->matches = 0;
  80039. }
  80040. #define SMALLEST 1
  80041. /* Index within the heap array of least frequent node in the Huffman tree */
  80042. /* ===========================================================================
  80043. * Remove the smallest element from the heap and recreate the heap with
  80044. * one less element. Updates heap and heap_len.
  80045. */
  80046. #define pqremove(s, tree, top) \
  80047. {\
  80048. top = s->heap[SMALLEST]; \
  80049. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  80050. pqdownheap(s, tree, SMALLEST); \
  80051. }
  80052. /* ===========================================================================
  80053. * Compares to subtrees, using the tree depth as tie breaker when
  80054. * the subtrees have equal frequency. This minimizes the worst case length.
  80055. */
  80056. #define smaller(tree, n, m, depth) \
  80057. (tree[n].Freq < tree[m].Freq || \
  80058. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  80059. /* ===========================================================================
  80060. * Restore the heap property by moving down the tree starting at node k,
  80061. * exchanging a node with the smallest of its two sons if necessary, stopping
  80062. * when the heap property is re-established (each father smaller than its
  80063. * two sons).
  80064. */
  80065. local void pqdownheap (deflate_state *s,
  80066. ct_data *tree, /* the tree to restore */
  80067. int k) /* node to move down */
  80068. {
  80069. int v = s->heap[k];
  80070. int j = k << 1; /* left son of k */
  80071. while (j <= s->heap_len) {
  80072. /* Set j to the smallest of the two sons: */
  80073. if (j < s->heap_len &&
  80074. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  80075. j++;
  80076. }
  80077. /* Exit if v is smaller than both sons */
  80078. if (smaller(tree, v, s->heap[j], s->depth)) break;
  80079. /* Exchange v with the smallest son */
  80080. s->heap[k] = s->heap[j]; k = j;
  80081. /* And continue down the tree, setting j to the left son of k */
  80082. j <<= 1;
  80083. }
  80084. s->heap[k] = v;
  80085. }
  80086. /* ===========================================================================
  80087. * Compute the optimal bit lengths for a tree and update the total bit length
  80088. * for the current block.
  80089. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  80090. * above are the tree nodes sorted by increasing frequency.
  80091. * OUT assertions: the field len is set to the optimal bit length, the
  80092. * array bl_count contains the frequencies for each bit length.
  80093. * The length opt_len is updated; static_len is also updated if stree is
  80094. * not null.
  80095. */
  80096. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  80097. {
  80098. ct_data *tree = desc->dyn_tree;
  80099. int max_code = desc->max_code;
  80100. const ct_data *stree = desc->stat_desc->static_tree;
  80101. const intf *extra = desc->stat_desc->extra_bits;
  80102. int base = desc->stat_desc->extra_base;
  80103. int max_length = desc->stat_desc->max_length;
  80104. int h; /* heap index */
  80105. int n, m; /* iterate over the tree elements */
  80106. int bits; /* bit length */
  80107. int xbits; /* extra bits */
  80108. ush f; /* frequency */
  80109. int overflow = 0; /* number of elements with bit length too large */
  80110. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  80111. /* In a first pass, compute the optimal bit lengths (which may
  80112. * overflow in the case of the bit length tree).
  80113. */
  80114. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  80115. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  80116. n = s->heap[h];
  80117. bits = tree[tree[n].Dad].Len + 1;
  80118. if (bits > max_length) bits = max_length, overflow++;
  80119. tree[n].Len = (ush)bits;
  80120. /* We overwrite tree[n].Dad which is no longer needed */
  80121. if (n > max_code) continue; /* not a leaf node */
  80122. s->bl_count[bits]++;
  80123. xbits = 0;
  80124. if (n >= base) xbits = extra[n-base];
  80125. f = tree[n].Freq;
  80126. s->opt_len += (ulg)f * (bits + xbits);
  80127. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  80128. }
  80129. if (overflow == 0) return;
  80130. Trace((stderr,"\nbit length overflow\n"));
  80131. /* This happens for example on obj2 and pic of the Calgary corpus */
  80132. /* Find the first bit length which could increase: */
  80133. do {
  80134. bits = max_length-1;
  80135. while (s->bl_count[bits] == 0) bits--;
  80136. s->bl_count[bits]--; /* move one leaf down the tree */
  80137. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  80138. s->bl_count[max_length]--;
  80139. /* The brother of the overflow item also moves one step up,
  80140. * but this does not affect bl_count[max_length]
  80141. */
  80142. overflow -= 2;
  80143. } while (overflow > 0);
  80144. /* Now recompute all bit lengths, scanning in increasing frequency.
  80145. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  80146. * lengths instead of fixing only the wrong ones. This idea is taken
  80147. * from 'ar' written by Haruhiko Okumura.)
  80148. */
  80149. for (bits = max_length; bits != 0; bits--) {
  80150. n = s->bl_count[bits];
  80151. while (n != 0) {
  80152. m = s->heap[--h];
  80153. if (m > max_code) continue;
  80154. if ((unsigned) tree[m].Len != (unsigned) bits) {
  80155. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  80156. s->opt_len += ((long)bits - (long)tree[m].Len)
  80157. *(long)tree[m].Freq;
  80158. tree[m].Len = (ush)bits;
  80159. }
  80160. n--;
  80161. }
  80162. }
  80163. }
  80164. /* ===========================================================================
  80165. * Generate the codes for a given tree and bit counts (which need not be
  80166. * optimal).
  80167. * IN assertion: the array bl_count contains the bit length statistics for
  80168. * the given tree and the field len is set for all tree elements.
  80169. * OUT assertion: the field code is set for all tree elements of non
  80170. * zero code length.
  80171. */
  80172. local void gen_codes (ct_data *tree, /* the tree to decorate */
  80173. int max_code, /* largest code with non zero frequency */
  80174. ushf *bl_count) /* number of codes at each bit length */
  80175. {
  80176. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  80177. ush code = 0; /* running code value */
  80178. int bits; /* bit index */
  80179. int n; /* code index */
  80180. /* The distribution counts are first used to generate the code values
  80181. * without bit reversal.
  80182. */
  80183. for (bits = 1; bits <= MAX_BITS; bits++) {
  80184. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  80185. }
  80186. /* Check that the bit counts in bl_count are consistent. The last code
  80187. * must be all ones.
  80188. */
  80189. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  80190. "inconsistent bit counts");
  80191. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  80192. for (n = 0; n <= max_code; n++) {
  80193. int len = tree[n].Len;
  80194. if (len == 0) continue;
  80195. /* Now reverse the bits */
  80196. tree[n].Code = bi_reverse(next_code[len]++, len);
  80197. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  80198. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  80199. }
  80200. }
  80201. /* ===========================================================================
  80202. * Construct one Huffman tree and assigns the code bit strings and lengths.
  80203. * Update the total bit length for the current block.
  80204. * IN assertion: the field freq is set for all tree elements.
  80205. * OUT assertions: the fields len and code are set to the optimal bit length
  80206. * and corresponding code. The length opt_len is updated; static_len is
  80207. * also updated if stree is not null. The field max_code is set.
  80208. */
  80209. local void build_tree (deflate_state *s,
  80210. tree_desc *desc) /* the tree descriptor */
  80211. {
  80212. ct_data *tree = desc->dyn_tree;
  80213. const ct_data *stree = desc->stat_desc->static_tree;
  80214. int elems = desc->stat_desc->elems;
  80215. int n, m; /* iterate over heap elements */
  80216. int max_code = -1; /* largest code with non zero frequency */
  80217. int node; /* new node being created */
  80218. /* Construct the initial heap, with least frequent element in
  80219. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  80220. * heap[0] is not used.
  80221. */
  80222. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  80223. for (n = 0; n < elems; n++) {
  80224. if (tree[n].Freq != 0) {
  80225. s->heap[++(s->heap_len)] = max_code = n;
  80226. s->depth[n] = 0;
  80227. } else {
  80228. tree[n].Len = 0;
  80229. }
  80230. }
  80231. /* The pkzip format requires that at least one distance code exists,
  80232. * and that at least one bit should be sent even if there is only one
  80233. * possible code. So to avoid special checks later on we force at least
  80234. * two codes of non zero frequency.
  80235. */
  80236. while (s->heap_len < 2) {
  80237. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  80238. tree[node].Freq = 1;
  80239. s->depth[node] = 0;
  80240. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  80241. /* node is 0 or 1 so it does not have extra bits */
  80242. }
  80243. desc->max_code = max_code;
  80244. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  80245. * establish sub-heaps of increasing lengths:
  80246. */
  80247. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  80248. /* Construct the Huffman tree by repeatedly combining the least two
  80249. * frequent nodes.
  80250. */
  80251. node = elems; /* next internal node of the tree */
  80252. do {
  80253. pqremove(s, tree, n); /* n = node of least frequency */
  80254. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  80255. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  80256. s->heap[--(s->heap_max)] = m;
  80257. /* Create a new node father of n and m */
  80258. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  80259. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  80260. s->depth[n] : s->depth[m]) + 1);
  80261. tree[n].Dad = tree[m].Dad = (ush)node;
  80262. #ifdef DUMP_BL_TREE
  80263. if (tree == s->bl_tree) {
  80264. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  80265. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  80266. }
  80267. #endif
  80268. /* and insert the new node in the heap */
  80269. s->heap[SMALLEST] = node++;
  80270. pqdownheap(s, tree, SMALLEST);
  80271. } while (s->heap_len >= 2);
  80272. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  80273. /* At this point, the fields freq and dad are set. We can now
  80274. * generate the bit lengths.
  80275. */
  80276. gen_bitlen(s, (tree_desc *)desc);
  80277. /* The field len is now set, we can generate the bit codes */
  80278. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  80279. }
  80280. /* ===========================================================================
  80281. * Scan a literal or distance tree to determine the frequencies of the codes
  80282. * in the bit length tree.
  80283. */
  80284. local void scan_tree (deflate_state *s,
  80285. ct_data *tree, /* the tree to be scanned */
  80286. int max_code) /* and its largest code of non zero frequency */
  80287. {
  80288. int n; /* iterates over all tree elements */
  80289. int prevlen = -1; /* last emitted length */
  80290. int curlen; /* length of current code */
  80291. int nextlen = tree[0].Len; /* length of next code */
  80292. int count = 0; /* repeat count of the current code */
  80293. int max_count = 7; /* max repeat count */
  80294. int min_count = 4; /* min repeat count */
  80295. if (nextlen == 0) max_count = 138, min_count = 3;
  80296. tree[max_code+1].Len = (ush)0xffff; /* guard */
  80297. for (n = 0; n <= max_code; n++) {
  80298. curlen = nextlen; nextlen = tree[n+1].Len;
  80299. if (++count < max_count && curlen == nextlen) {
  80300. continue;
  80301. } else if (count < min_count) {
  80302. s->bl_tree[curlen].Freq += count;
  80303. } else if (curlen != 0) {
  80304. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  80305. s->bl_tree[REP_3_6].Freq++;
  80306. } else if (count <= 10) {
  80307. s->bl_tree[REPZ_3_10].Freq++;
  80308. } else {
  80309. s->bl_tree[REPZ_11_138].Freq++;
  80310. }
  80311. count = 0; prevlen = curlen;
  80312. if (nextlen == 0) {
  80313. max_count = 138, min_count = 3;
  80314. } else if (curlen == nextlen) {
  80315. max_count = 6, min_count = 3;
  80316. } else {
  80317. max_count = 7, min_count = 4;
  80318. }
  80319. }
  80320. }
  80321. /* ===========================================================================
  80322. * Send a literal or distance tree in compressed form, using the codes in
  80323. * bl_tree.
  80324. */
  80325. local void send_tree (deflate_state *s,
  80326. ct_data *tree, /* the tree to be scanned */
  80327. int max_code) /* and its largest code of non zero frequency */
  80328. {
  80329. int n; /* iterates over all tree elements */
  80330. int prevlen = -1; /* last emitted length */
  80331. int curlen; /* length of current code */
  80332. int nextlen = tree[0].Len; /* length of next code */
  80333. int count = 0; /* repeat count of the current code */
  80334. int max_count = 7; /* max repeat count */
  80335. int min_count = 4; /* min repeat count */
  80336. /* tree[max_code+1].Len = -1; */ /* guard already set */
  80337. if (nextlen == 0) max_count = 138, min_count = 3;
  80338. for (n = 0; n <= max_code; n++) {
  80339. curlen = nextlen; nextlen = tree[n+1].Len;
  80340. if (++count < max_count && curlen == nextlen) {
  80341. continue;
  80342. } else if (count < min_count) {
  80343. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  80344. } else if (curlen != 0) {
  80345. if (curlen != prevlen) {
  80346. send_code(s, curlen, s->bl_tree); count--;
  80347. }
  80348. Assert(count >= 3 && count <= 6, " 3_6?");
  80349. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  80350. } else if (count <= 10) {
  80351. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  80352. } else {
  80353. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  80354. }
  80355. count = 0; prevlen = curlen;
  80356. if (nextlen == 0) {
  80357. max_count = 138, min_count = 3;
  80358. } else if (curlen == nextlen) {
  80359. max_count = 6, min_count = 3;
  80360. } else {
  80361. max_count = 7, min_count = 4;
  80362. }
  80363. }
  80364. }
  80365. /* ===========================================================================
  80366. * Construct the Huffman tree for the bit lengths and return the index in
  80367. * bl_order of the last bit length code to send.
  80368. */
  80369. local int build_bl_tree (deflate_state *s)
  80370. {
  80371. int max_blindex; /* index of last bit length code of non zero freq */
  80372. /* Determine the bit length frequencies for literal and distance trees */
  80373. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  80374. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  80375. /* Build the bit length tree: */
  80376. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  80377. /* opt_len now includes the length of the tree representations, except
  80378. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  80379. */
  80380. /* Determine the number of bit length codes to send. The pkzip format
  80381. * requires that at least 4 bit length codes be sent. (appnote.txt says
  80382. * 3 but the actual value used is 4.)
  80383. */
  80384. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  80385. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  80386. }
  80387. /* Update opt_len to include the bit length tree and counts */
  80388. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  80389. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  80390. s->opt_len, s->static_len));
  80391. return max_blindex;
  80392. }
  80393. /* ===========================================================================
  80394. * Send the header for a block using dynamic Huffman trees: the counts, the
  80395. * lengths of the bit length codes, the literal tree and the distance tree.
  80396. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  80397. */
  80398. local void send_all_trees (deflate_state *s,
  80399. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  80400. {
  80401. int rank; /* index in bl_order */
  80402. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  80403. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  80404. "too many codes");
  80405. Tracev((stderr, "\nbl counts: "));
  80406. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  80407. send_bits(s, dcodes-1, 5);
  80408. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  80409. for (rank = 0; rank < blcodes; rank++) {
  80410. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  80411. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  80412. }
  80413. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  80414. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  80415. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  80416. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  80417. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  80418. }
  80419. /* ===========================================================================
  80420. * Send a stored block
  80421. */
  80422. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  80423. {
  80424. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  80425. #ifdef DEBUG
  80426. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  80427. s->compressed_len += (stored_len + 4) << 3;
  80428. #endif
  80429. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  80430. }
  80431. /* ===========================================================================
  80432. * Send one empty static block to give enough lookahead for inflate.
  80433. * This takes 10 bits, of which 7 may remain in the bit buffer.
  80434. * The current inflate code requires 9 bits of lookahead. If the
  80435. * last two codes for the previous block (real code plus EOB) were coded
  80436. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  80437. * the last real code. In this case we send two empty static blocks instead
  80438. * of one. (There are no problems if the previous block is stored or fixed.)
  80439. * To simplify the code, we assume the worst case of last real code encoded
  80440. * on one bit only.
  80441. */
  80442. void _tr_align (deflate_state *s)
  80443. {
  80444. send_bits(s, STATIC_TREES<<1, 3);
  80445. send_code(s, END_BLOCK, static_ltree);
  80446. #ifdef DEBUG
  80447. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  80448. #endif
  80449. bi_flush(s);
  80450. /* Of the 10 bits for the empty block, we have already sent
  80451. * (10 - bi_valid) bits. The lookahead for the last real code (before
  80452. * the EOB of the previous block) was thus at least one plus the length
  80453. * of the EOB plus what we have just sent of the empty static block.
  80454. */
  80455. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  80456. send_bits(s, STATIC_TREES<<1, 3);
  80457. send_code(s, END_BLOCK, static_ltree);
  80458. #ifdef DEBUG
  80459. s->compressed_len += 10L;
  80460. #endif
  80461. bi_flush(s);
  80462. }
  80463. s->last_eob_len = 7;
  80464. }
  80465. /* ===========================================================================
  80466. * Determine the best encoding for the current block: dynamic trees, static
  80467. * trees or store, and output the encoded block to the zip file.
  80468. */
  80469. void _tr_flush_block (deflate_state *s,
  80470. charf *buf, /* input block, or NULL if too old */
  80471. ulg stored_len, /* length of input block */
  80472. int eof) /* true if this is the last block for a file */
  80473. {
  80474. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  80475. int max_blindex = 0; /* index of last bit length code of non zero freq */
  80476. /* Build the Huffman trees unless a stored block is forced */
  80477. if (s->level > 0) {
  80478. /* Check if the file is binary or text */
  80479. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  80480. set_data_type(s);
  80481. /* Construct the literal and distance trees */
  80482. build_tree(s, (tree_desc *)(&(s->l_desc)));
  80483. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  80484. s->static_len));
  80485. build_tree(s, (tree_desc *)(&(s->d_desc)));
  80486. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  80487. s->static_len));
  80488. /* At this point, opt_len and static_len are the total bit lengths of
  80489. * the compressed block data, excluding the tree representations.
  80490. */
  80491. /* Build the bit length tree for the above two trees, and get the index
  80492. * in bl_order of the last bit length code to send.
  80493. */
  80494. max_blindex = build_bl_tree(s);
  80495. /* Determine the best encoding. Compute the block lengths in bytes. */
  80496. opt_lenb = (s->opt_len+3+7)>>3;
  80497. static_lenb = (s->static_len+3+7)>>3;
  80498. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  80499. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  80500. s->last_lit));
  80501. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  80502. } else {
  80503. Assert(buf != (char*)0, "lost buf");
  80504. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  80505. }
  80506. #ifdef FORCE_STORED
  80507. if (buf != (char*)0) { /* force stored block */
  80508. #else
  80509. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  80510. /* 4: two words for the lengths */
  80511. #endif
  80512. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  80513. * Otherwise we can't have processed more than WSIZE input bytes since
  80514. * the last block flush, because compression would have been
  80515. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  80516. * transform a block into a stored block.
  80517. */
  80518. _tr_stored_block(s, buf, stored_len, eof);
  80519. #ifdef FORCE_STATIC
  80520. } else if (static_lenb >= 0) { /* force static trees */
  80521. #else
  80522. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  80523. #endif
  80524. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  80525. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  80526. #ifdef DEBUG
  80527. s->compressed_len += 3 + s->static_len;
  80528. #endif
  80529. } else {
  80530. send_bits(s, (DYN_TREES<<1)+eof, 3);
  80531. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  80532. max_blindex+1);
  80533. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  80534. #ifdef DEBUG
  80535. s->compressed_len += 3 + s->opt_len;
  80536. #endif
  80537. }
  80538. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  80539. /* The above check is made mod 2^32, for files larger than 512 MB
  80540. * and uLong implemented on 32 bits.
  80541. */
  80542. init_block(s);
  80543. if (eof) {
  80544. bi_windup(s);
  80545. #ifdef DEBUG
  80546. s->compressed_len += 7; /* align on byte boundary */
  80547. #endif
  80548. }
  80549. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  80550. s->compressed_len-7*eof));
  80551. }
  80552. /* ===========================================================================
  80553. * Save the match info and tally the frequency counts. Return true if
  80554. * the current block must be flushed.
  80555. */
  80556. int _tr_tally (deflate_state *s,
  80557. unsigned dist, /* distance of matched string */
  80558. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  80559. {
  80560. s->d_buf[s->last_lit] = (ush)dist;
  80561. s->l_buf[s->last_lit++] = (uch)lc;
  80562. if (dist == 0) {
  80563. /* lc is the unmatched char */
  80564. s->dyn_ltree[lc].Freq++;
  80565. } else {
  80566. s->matches++;
  80567. /* Here, lc is the match length - MIN_MATCH */
  80568. dist--; /* dist = match distance - 1 */
  80569. Assert((ush)dist < (ush)MAX_DIST(s) &&
  80570. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  80571. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  80572. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  80573. s->dyn_dtree[d_code(dist)].Freq++;
  80574. }
  80575. #ifdef TRUNCATE_BLOCK
  80576. /* Try to guess if it is profitable to stop the current block here */
  80577. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  80578. /* Compute an upper bound for the compressed length */
  80579. ulg out_length = (ulg)s->last_lit*8L;
  80580. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  80581. int dcode;
  80582. for (dcode = 0; dcode < D_CODES; dcode++) {
  80583. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  80584. (5L+extra_dbits[dcode]);
  80585. }
  80586. out_length >>= 3;
  80587. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  80588. s->last_lit, in_length, out_length,
  80589. 100L - out_length*100L/in_length));
  80590. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  80591. }
  80592. #endif
  80593. return (s->last_lit == s->lit_bufsize-1);
  80594. /* We avoid equality with lit_bufsize because of wraparound at 64K
  80595. * on 16 bit machines and because stored blocks are restricted to
  80596. * 64K-1 bytes.
  80597. */
  80598. }
  80599. /* ===========================================================================
  80600. * Send the block data compressed using the given Huffman trees
  80601. */
  80602. local void compress_block (deflate_state *s,
  80603. ct_data *ltree, /* literal tree */
  80604. ct_data *dtree) /* distance tree */
  80605. {
  80606. unsigned dist; /* distance of matched string */
  80607. int lc; /* match length or unmatched char (if dist == 0) */
  80608. unsigned lx = 0; /* running index in l_buf */
  80609. unsigned code; /* the code to send */
  80610. int extra; /* number of extra bits to send */
  80611. if (s->last_lit != 0) do {
  80612. dist = s->d_buf[lx];
  80613. lc = s->l_buf[lx++];
  80614. if (dist == 0) {
  80615. send_code(s, lc, ltree); /* send a literal byte */
  80616. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  80617. } else {
  80618. /* Here, lc is the match length - MIN_MATCH */
  80619. code = _length_code[lc];
  80620. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  80621. extra = extra_lbits[code];
  80622. if (extra != 0) {
  80623. lc -= base_length[code];
  80624. send_bits(s, lc, extra); /* send the extra length bits */
  80625. }
  80626. dist--; /* dist is now the match distance - 1 */
  80627. code = d_code(dist);
  80628. Assert (code < D_CODES, "bad d_code");
  80629. send_code(s, code, dtree); /* send the distance code */
  80630. extra = extra_dbits[code];
  80631. if (extra != 0) {
  80632. dist -= base_dist[code];
  80633. send_bits(s, dist, extra); /* send the extra distance bits */
  80634. }
  80635. } /* literal or match pair ? */
  80636. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  80637. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  80638. "pendingBuf overflow");
  80639. } while (lx < s->last_lit);
  80640. send_code(s, END_BLOCK, ltree);
  80641. s->last_eob_len = ltree[END_BLOCK].Len;
  80642. }
  80643. /* ===========================================================================
  80644. * Set the data type to BINARY or TEXT, using a crude approximation:
  80645. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  80646. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  80647. * IN assertion: the fields Freq of dyn_ltree are set.
  80648. */
  80649. local void set_data_type (deflate_state *s)
  80650. {
  80651. int n;
  80652. for (n = 0; n < 9; n++)
  80653. if (s->dyn_ltree[n].Freq != 0)
  80654. break;
  80655. if (n == 9)
  80656. for (n = 14; n < 32; n++)
  80657. if (s->dyn_ltree[n].Freq != 0)
  80658. break;
  80659. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  80660. }
  80661. /* ===========================================================================
  80662. * Reverse the first len bits of a code, using straightforward code (a faster
  80663. * method would use a table)
  80664. * IN assertion: 1 <= len <= 15
  80665. */
  80666. local unsigned bi_reverse (unsigned code, int len)
  80667. {
  80668. register unsigned res = 0;
  80669. do {
  80670. res |= code & 1;
  80671. code >>= 1, res <<= 1;
  80672. } while (--len > 0);
  80673. return res >> 1;
  80674. }
  80675. /* ===========================================================================
  80676. * Flush the bit buffer, keeping at most 7 bits in it.
  80677. */
  80678. local void bi_flush (deflate_state *s)
  80679. {
  80680. if (s->bi_valid == 16) {
  80681. put_short(s, s->bi_buf);
  80682. s->bi_buf = 0;
  80683. s->bi_valid = 0;
  80684. } else if (s->bi_valid >= 8) {
  80685. put_byte(s, (Byte)s->bi_buf);
  80686. s->bi_buf >>= 8;
  80687. s->bi_valid -= 8;
  80688. }
  80689. }
  80690. /* ===========================================================================
  80691. * Flush the bit buffer and align the output on a byte boundary
  80692. */
  80693. local void bi_windup (deflate_state *s)
  80694. {
  80695. if (s->bi_valid > 8) {
  80696. put_short(s, s->bi_buf);
  80697. } else if (s->bi_valid > 0) {
  80698. put_byte(s, (Byte)s->bi_buf);
  80699. }
  80700. s->bi_buf = 0;
  80701. s->bi_valid = 0;
  80702. #ifdef DEBUG
  80703. s->bits_sent = (s->bits_sent+7) & ~7;
  80704. #endif
  80705. }
  80706. /* ===========================================================================
  80707. * Copy a stored block, storing first the length and its
  80708. * one's complement if requested.
  80709. */
  80710. local void copy_block(deflate_state *s,
  80711. charf *buf, /* the input data */
  80712. unsigned len, /* its length */
  80713. int header) /* true if block header must be written */
  80714. {
  80715. bi_windup(s); /* align on byte boundary */
  80716. s->last_eob_len = 8; /* enough lookahead for inflate */
  80717. if (header) {
  80718. put_short(s, (ush)len);
  80719. put_short(s, (ush)~len);
  80720. #ifdef DEBUG
  80721. s->bits_sent += 2*16;
  80722. #endif
  80723. }
  80724. #ifdef DEBUG
  80725. s->bits_sent += (ulg)len<<3;
  80726. #endif
  80727. while (len--) {
  80728. put_byte(s, *buf++);
  80729. }
  80730. }
  80731. /********* End of inlined file: trees.c *********/
  80732. /********* Start of inlined file: zutil.c *********/
  80733. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80734. #ifndef NO_DUMMY_DECL
  80735. struct internal_state {int dummy;}; /* for buggy compilers */
  80736. #endif
  80737. const char * const z_errmsg[10] = {
  80738. "need dictionary", /* Z_NEED_DICT 2 */
  80739. "stream end", /* Z_STREAM_END 1 */
  80740. "", /* Z_OK 0 */
  80741. "file error", /* Z_ERRNO (-1) */
  80742. "stream error", /* Z_STREAM_ERROR (-2) */
  80743. "data error", /* Z_DATA_ERROR (-3) */
  80744. "insufficient memory", /* Z_MEM_ERROR (-4) */
  80745. "buffer error", /* Z_BUF_ERROR (-5) */
  80746. "incompatible version",/* Z_VERSION_ERROR (-6) */
  80747. ""};
  80748. /*const char * ZEXPORT zlibVersion()
  80749. {
  80750. return ZLIB_VERSION;
  80751. }
  80752. uLong ZEXPORT zlibCompileFlags()
  80753. {
  80754. uLong flags;
  80755. flags = 0;
  80756. switch (sizeof(uInt)) {
  80757. case 2: break;
  80758. case 4: flags += 1; break;
  80759. case 8: flags += 2; break;
  80760. default: flags += 3;
  80761. }
  80762. switch (sizeof(uLong)) {
  80763. case 2: break;
  80764. case 4: flags += 1 << 2; break;
  80765. case 8: flags += 2 << 2; break;
  80766. default: flags += 3 << 2;
  80767. }
  80768. switch (sizeof(voidpf)) {
  80769. case 2: break;
  80770. case 4: flags += 1 << 4; break;
  80771. case 8: flags += 2 << 4; break;
  80772. default: flags += 3 << 4;
  80773. }
  80774. switch (sizeof(z_off_t)) {
  80775. case 2: break;
  80776. case 4: flags += 1 << 6; break;
  80777. case 8: flags += 2 << 6; break;
  80778. default: flags += 3 << 6;
  80779. }
  80780. #ifdef DEBUG
  80781. flags += 1 << 8;
  80782. #endif
  80783. #if defined(ASMV) || defined(ASMINF)
  80784. flags += 1 << 9;
  80785. #endif
  80786. #ifdef ZLIB_WINAPI
  80787. flags += 1 << 10;
  80788. #endif
  80789. #ifdef BUILDFIXED
  80790. flags += 1 << 12;
  80791. #endif
  80792. #ifdef DYNAMIC_CRC_TABLE
  80793. flags += 1 << 13;
  80794. #endif
  80795. #ifdef NO_GZCOMPRESS
  80796. flags += 1L << 16;
  80797. #endif
  80798. #ifdef NO_GZIP
  80799. flags += 1L << 17;
  80800. #endif
  80801. #ifdef PKZIP_BUG_WORKAROUND
  80802. flags += 1L << 20;
  80803. #endif
  80804. #ifdef FASTEST
  80805. flags += 1L << 21;
  80806. #endif
  80807. #ifdef STDC
  80808. # ifdef NO_vsnprintf
  80809. flags += 1L << 25;
  80810. # ifdef HAS_vsprintf_void
  80811. flags += 1L << 26;
  80812. # endif
  80813. # else
  80814. # ifdef HAS_vsnprintf_void
  80815. flags += 1L << 26;
  80816. # endif
  80817. # endif
  80818. #else
  80819. flags += 1L << 24;
  80820. # ifdef NO_snprintf
  80821. flags += 1L << 25;
  80822. # ifdef HAS_sprintf_void
  80823. flags += 1L << 26;
  80824. # endif
  80825. # else
  80826. # ifdef HAS_snprintf_void
  80827. flags += 1L << 26;
  80828. # endif
  80829. # endif
  80830. #endif
  80831. return flags;
  80832. }*/
  80833. #ifdef DEBUG
  80834. # ifndef verbose
  80835. # define verbose 0
  80836. # endif
  80837. int z_verbose = verbose;
  80838. void z_error (const char *m)
  80839. {
  80840. fprintf(stderr, "%s\n", m);
  80841. exit(1);
  80842. }
  80843. #endif
  80844. /* exported to allow conversion of error code to string for compress() and
  80845. * uncompress()
  80846. */
  80847. const char * ZEXPORT zError(int err)
  80848. {
  80849. return ERR_MSG(err);
  80850. }
  80851. #if defined(_WIN32_WCE)
  80852. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  80853. * errno. We define it as a global variable to simplify porting.
  80854. * Its value is always 0 and should not be used.
  80855. */
  80856. int errno = 0;
  80857. #endif
  80858. #ifndef HAVE_MEMCPY
  80859. void zmemcpy(dest, source, len)
  80860. Bytef* dest;
  80861. const Bytef* source;
  80862. uInt len;
  80863. {
  80864. if (len == 0) return;
  80865. do {
  80866. *dest++ = *source++; /* ??? to be unrolled */
  80867. } while (--len != 0);
  80868. }
  80869. int zmemcmp(s1, s2, len)
  80870. const Bytef* s1;
  80871. const Bytef* s2;
  80872. uInt len;
  80873. {
  80874. uInt j;
  80875. for (j = 0; j < len; j++) {
  80876. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  80877. }
  80878. return 0;
  80879. }
  80880. void zmemzero(dest, len)
  80881. Bytef* dest;
  80882. uInt len;
  80883. {
  80884. if (len == 0) return;
  80885. do {
  80886. *dest++ = 0; /* ??? to be unrolled */
  80887. } while (--len != 0);
  80888. }
  80889. #endif
  80890. #ifdef SYS16BIT
  80891. #ifdef __TURBOC__
  80892. /* Turbo C in 16-bit mode */
  80893. # define MY_ZCALLOC
  80894. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  80895. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  80896. * must fix the pointer. Warning: the pointer must be put back to its
  80897. * original form in order to free it, use zcfree().
  80898. */
  80899. #define MAX_PTR 10
  80900. /* 10*64K = 640K */
  80901. local int next_ptr = 0;
  80902. typedef struct ptr_table_s {
  80903. voidpf org_ptr;
  80904. voidpf new_ptr;
  80905. } ptr_table;
  80906. local ptr_table table[MAX_PTR];
  80907. /* This table is used to remember the original form of pointers
  80908. * to large buffers (64K). Such pointers are normalized with a zero offset.
  80909. * Since MSDOS is not a preemptive multitasking OS, this table is not
  80910. * protected from concurrent access. This hack doesn't work anyway on
  80911. * a protected system like OS/2. Use Microsoft C instead.
  80912. */
  80913. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80914. {
  80915. voidpf buf = opaque; /* just to make some compilers happy */
  80916. ulg bsize = (ulg)items*size;
  80917. /* If we allocate less than 65520 bytes, we assume that farmalloc
  80918. * will return a usable pointer which doesn't have to be normalized.
  80919. */
  80920. if (bsize < 65520L) {
  80921. buf = farmalloc(bsize);
  80922. if (*(ush*)&buf != 0) return buf;
  80923. } else {
  80924. buf = farmalloc(bsize + 16L);
  80925. }
  80926. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  80927. table[next_ptr].org_ptr = buf;
  80928. /* Normalize the pointer to seg:0 */
  80929. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  80930. *(ush*)&buf = 0;
  80931. table[next_ptr++].new_ptr = buf;
  80932. return buf;
  80933. }
  80934. void zcfree (voidpf opaque, voidpf ptr)
  80935. {
  80936. int n;
  80937. if (*(ush*)&ptr != 0) { /* object < 64K */
  80938. farfree(ptr);
  80939. return;
  80940. }
  80941. /* Find the original pointer */
  80942. for (n = 0; n < next_ptr; n++) {
  80943. if (ptr != table[n].new_ptr) continue;
  80944. farfree(table[n].org_ptr);
  80945. while (++n < next_ptr) {
  80946. table[n-1] = table[n];
  80947. }
  80948. next_ptr--;
  80949. return;
  80950. }
  80951. ptr = opaque; /* just to make some compilers happy */
  80952. Assert(0, "zcfree: ptr not found");
  80953. }
  80954. #endif /* __TURBOC__ */
  80955. #ifdef M_I86
  80956. /* Microsoft C in 16-bit mode */
  80957. # define MY_ZCALLOC
  80958. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  80959. # define _halloc halloc
  80960. # define _hfree hfree
  80961. #endif
  80962. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80963. {
  80964. if (opaque) opaque = 0; /* to make compiler happy */
  80965. return _halloc((long)items, size);
  80966. }
  80967. void zcfree (voidpf opaque, voidpf ptr)
  80968. {
  80969. if (opaque) opaque = 0; /* to make compiler happy */
  80970. _hfree(ptr);
  80971. }
  80972. #endif /* M_I86 */
  80973. #endif /* SYS16BIT */
  80974. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  80975. #ifndef STDC
  80976. extern voidp malloc OF((uInt size));
  80977. extern voidp calloc OF((uInt items, uInt size));
  80978. extern void free OF((voidpf ptr));
  80979. #endif
  80980. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80981. {
  80982. if (opaque) items += size - size; /* make compiler happy */
  80983. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  80984. (voidpf)calloc(items, size);
  80985. }
  80986. void zcfree (voidpf opaque, voidpf ptr)
  80987. {
  80988. free(ptr);
  80989. if (opaque) return; /* make compiler happy */
  80990. }
  80991. #endif /* MY_ZCALLOC */
  80992. /********* End of inlined file: zutil.c *********/
  80993. #undef Byte
  80994. }
  80995. #else
  80996. #include <zlib.h>
  80997. #endif
  80998. }
  80999. #if JUCE_MSVC
  81000. #pragma warning (pop)
  81001. #endif
  81002. BEGIN_JUCE_NAMESPACE
  81003. using namespace zlibNamespace;
  81004. // internal helper object that holds the zlib structures so they don't have to be
  81005. // included publicly.
  81006. class GZIPDecompressHelper
  81007. {
  81008. private:
  81009. z_stream* stream;
  81010. uint8* data;
  81011. int dataSize;
  81012. public:
  81013. bool finished, needsDictionary, error;
  81014. GZIPDecompressHelper (const bool noWrap) throw()
  81015. : data (0),
  81016. dataSize (0),
  81017. finished (false),
  81018. needsDictionary (false),
  81019. error (false)
  81020. {
  81021. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  81022. if (inflateInit2 (stream, (noWrap) ? -MAX_WBITS
  81023. : MAX_WBITS) != Z_OK)
  81024. {
  81025. juce_free (stream);
  81026. stream = 0;
  81027. error = true;
  81028. finished = true;
  81029. }
  81030. }
  81031. ~GZIPDecompressHelper() throw()
  81032. {
  81033. if (stream != 0)
  81034. {
  81035. inflateEnd (stream);
  81036. juce_free (stream);
  81037. }
  81038. }
  81039. bool needsInput() const throw() { return dataSize <= 0; }
  81040. void setInput (uint8* const data_, const int size) throw()
  81041. {
  81042. data = data_;
  81043. dataSize = size;
  81044. }
  81045. int doNextBlock (uint8* const dest, const int destSize) throw()
  81046. {
  81047. if (stream != 0 && data != 0 && ! finished)
  81048. {
  81049. stream->next_in = data;
  81050. stream->next_out = dest;
  81051. stream->avail_in = dataSize;
  81052. stream->avail_out = destSize;
  81053. switch (inflate (stream, Z_PARTIAL_FLUSH))
  81054. {
  81055. case Z_STREAM_END:
  81056. finished = true;
  81057. // deliberate fall-through
  81058. case Z_OK:
  81059. data += dataSize - stream->avail_in;
  81060. dataSize = stream->avail_in;
  81061. return destSize - stream->avail_out;
  81062. case Z_NEED_DICT:
  81063. needsDictionary = true;
  81064. data += dataSize - stream->avail_in;
  81065. dataSize = stream->avail_in;
  81066. break;
  81067. case Z_DATA_ERROR:
  81068. case Z_MEM_ERROR:
  81069. error = true;
  81070. default:
  81071. break;
  81072. }
  81073. }
  81074. return 0;
  81075. }
  81076. };
  81077. const int gzipDecompBufferSize = 32768;
  81078. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  81079. const bool deleteSourceWhenDestroyed_,
  81080. const bool noWrap_,
  81081. const int64 uncompressedStreamLength_)
  81082. : sourceStream (sourceStream_),
  81083. uncompressedStreamLength (uncompressedStreamLength_),
  81084. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  81085. noWrap (noWrap_),
  81086. isEof (false),
  81087. activeBufferSize (0),
  81088. originalSourcePos (sourceStream_->getPosition()),
  81089. currentPos (0)
  81090. {
  81091. buffer = (uint8*) juce_malloc (gzipDecompBufferSize);
  81092. helper = new GZIPDecompressHelper (noWrap_);
  81093. }
  81094. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  81095. {
  81096. juce_free (buffer);
  81097. if (deleteSourceWhenDestroyed)
  81098. delete sourceStream;
  81099. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81100. delete h;
  81101. }
  81102. int64 GZIPDecompressorInputStream::getTotalLength()
  81103. {
  81104. return uncompressedStreamLength;
  81105. }
  81106. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  81107. {
  81108. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81109. if ((howMany > 0) && ! isEof)
  81110. {
  81111. jassert (destBuffer != 0);
  81112. if (destBuffer != 0)
  81113. {
  81114. int numRead = 0;
  81115. uint8* d = (uint8*) destBuffer;
  81116. while (! h->error)
  81117. {
  81118. const int n = h->doNextBlock (d, howMany);
  81119. currentPos += n;
  81120. if (n == 0)
  81121. {
  81122. if (h->finished || h->needsDictionary)
  81123. {
  81124. isEof = true;
  81125. return numRead;
  81126. }
  81127. if (h->needsInput())
  81128. {
  81129. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  81130. if (activeBufferSize > 0)
  81131. {
  81132. h->setInput ((uint8*) buffer, activeBufferSize);
  81133. }
  81134. else
  81135. {
  81136. isEof = true;
  81137. return numRead;
  81138. }
  81139. }
  81140. }
  81141. else
  81142. {
  81143. numRead += n;
  81144. howMany -= n;
  81145. d += n;
  81146. if (howMany <= 0)
  81147. return numRead;
  81148. }
  81149. }
  81150. }
  81151. }
  81152. return 0;
  81153. }
  81154. bool GZIPDecompressorInputStream::isExhausted()
  81155. {
  81156. const GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81157. return h->error || isEof;
  81158. }
  81159. int64 GZIPDecompressorInputStream::getPosition()
  81160. {
  81161. return currentPos;
  81162. }
  81163. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  81164. {
  81165. if (newPos != currentPos)
  81166. {
  81167. if (newPos > currentPos)
  81168. {
  81169. skipNextBytes (newPos - currentPos);
  81170. }
  81171. else
  81172. {
  81173. // reset the stream and start again..
  81174. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81175. delete h;
  81176. isEof = false;
  81177. activeBufferSize = 0;
  81178. currentPos = 0;
  81179. helper = new GZIPDecompressHelper (noWrap);
  81180. sourceStream->setPosition (originalSourcePos);
  81181. skipNextBytes (newPos);
  81182. }
  81183. }
  81184. return true;
  81185. }
  81186. END_JUCE_NAMESPACE
  81187. /********* End of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  81188. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  81189. /********* Start of inlined file: juce_FlacAudioFormat.cpp *********/
  81190. #ifdef _MSC_VER
  81191. #include <windows.h>
  81192. #endif
  81193. #if JUCE_USE_FLAC
  81194. #ifdef _MSC_VER
  81195. #pragma warning (disable : 4505)
  81196. #pragma warning (push)
  81197. #endif
  81198. namespace FlacNamespace
  81199. {
  81200. #if JUCE_INCLUDE_FLAC_CODE
  81201. #define FLAC__NO_DLL 1
  81202. #if ! defined (SIZE_MAX)
  81203. #define SIZE_MAX 0xffffffff
  81204. #endif
  81205. #define __STDC_LIMIT_MACROS 1
  81206. /********* Start of inlined file: all.h *********/
  81207. #ifndef FLAC__ALL_H
  81208. #define FLAC__ALL_H
  81209. /********* Start of inlined file: export.h *********/
  81210. #ifndef FLAC__EXPORT_H
  81211. #define FLAC__EXPORT_H
  81212. /** \file include/FLAC/export.h
  81213. *
  81214. * \brief
  81215. * This module contains #defines and symbols for exporting function
  81216. * calls, and providing version information and compiled-in features.
  81217. *
  81218. * See the \link flac_export export \endlink module.
  81219. */
  81220. /** \defgroup flac_export FLAC/export.h: export symbols
  81221. * \ingroup flac
  81222. *
  81223. * \brief
  81224. * This module contains #defines and symbols for exporting function
  81225. * calls, and providing version information and compiled-in features.
  81226. *
  81227. * If you are compiling with MSVC and will link to the static library
  81228. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  81229. * make sure the symbols are exported properly.
  81230. *
  81231. * \{
  81232. */
  81233. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  81234. #define FLAC_API
  81235. #else
  81236. #ifdef FLAC_API_EXPORTS
  81237. #define FLAC_API _declspec(dllexport)
  81238. #else
  81239. #define FLAC_API _declspec(dllimport)
  81240. #endif
  81241. #endif
  81242. /** These #defines will mirror the libtool-based library version number, see
  81243. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  81244. */
  81245. #define FLAC_API_VERSION_CURRENT 10
  81246. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  81247. #define FLAC_API_VERSION_AGE 2 /**< see above */
  81248. #ifdef __cplusplus
  81249. extern "C" {
  81250. #endif
  81251. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  81252. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  81253. #ifdef __cplusplus
  81254. }
  81255. #endif
  81256. /* \} */
  81257. #endif
  81258. /********* End of inlined file: export.h *********/
  81259. /********* Start of inlined file: assert.h *********/
  81260. #ifndef FLAC__ASSERT_H
  81261. #define FLAC__ASSERT_H
  81262. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  81263. #ifdef DEBUG
  81264. #include <assert.h>
  81265. #define FLAC__ASSERT(x) assert(x)
  81266. #define FLAC__ASSERT_DECLARATION(x) x
  81267. #else
  81268. #define FLAC__ASSERT(x)
  81269. #define FLAC__ASSERT_DECLARATION(x)
  81270. #endif
  81271. #endif
  81272. /********* End of inlined file: assert.h *********/
  81273. /********* Start of inlined file: callback.h *********/
  81274. #ifndef FLAC__CALLBACK_H
  81275. #define FLAC__CALLBACK_H
  81276. /********* Start of inlined file: ordinals.h *********/
  81277. #ifndef FLAC__ORDINALS_H
  81278. #define FLAC__ORDINALS_H
  81279. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  81280. #include <inttypes.h>
  81281. #endif
  81282. typedef signed char FLAC__int8;
  81283. typedef unsigned char FLAC__uint8;
  81284. #if defined(_MSC_VER) || defined(__BORLANDC__)
  81285. typedef __int16 FLAC__int16;
  81286. typedef __int32 FLAC__int32;
  81287. typedef __int64 FLAC__int64;
  81288. typedef unsigned __int16 FLAC__uint16;
  81289. typedef unsigned __int32 FLAC__uint32;
  81290. typedef unsigned __int64 FLAC__uint64;
  81291. #elif defined(__EMX__)
  81292. typedef short FLAC__int16;
  81293. typedef long FLAC__int32;
  81294. typedef long long FLAC__int64;
  81295. typedef unsigned short FLAC__uint16;
  81296. typedef unsigned long FLAC__uint32;
  81297. typedef unsigned long long FLAC__uint64;
  81298. #else
  81299. typedef int16_t FLAC__int16;
  81300. typedef int32_t FLAC__int32;
  81301. typedef int64_t FLAC__int64;
  81302. typedef uint16_t FLAC__uint16;
  81303. typedef uint32_t FLAC__uint32;
  81304. typedef uint64_t FLAC__uint64;
  81305. #endif
  81306. typedef int FLAC__bool;
  81307. typedef FLAC__uint8 FLAC__byte;
  81308. #ifdef true
  81309. #undef true
  81310. #endif
  81311. #ifdef false
  81312. #undef false
  81313. #endif
  81314. #ifndef __cplusplus
  81315. #define true 1
  81316. #define false 0
  81317. #endif
  81318. #endif
  81319. /********* End of inlined file: ordinals.h *********/
  81320. #include <stdlib.h> /* for size_t */
  81321. /** \file include/FLAC/callback.h
  81322. *
  81323. * \brief
  81324. * This module defines the structures for describing I/O callbacks
  81325. * to the other FLAC interfaces.
  81326. *
  81327. * See the detailed documentation for callbacks in the
  81328. * \link flac_callbacks callbacks \endlink module.
  81329. */
  81330. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  81331. * \ingroup flac
  81332. *
  81333. * \brief
  81334. * This module defines the structures for describing I/O callbacks
  81335. * to the other FLAC interfaces.
  81336. *
  81337. * The purpose of the I/O callback functions is to create a common way
  81338. * for the metadata interfaces to handle I/O.
  81339. *
  81340. * Originally the metadata interfaces required filenames as the way of
  81341. * specifying FLAC files to operate on. This is problematic in some
  81342. * environments so there is an additional option to specify a set of
  81343. * callbacks for doing I/O on the FLAC file, instead of the filename.
  81344. *
  81345. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  81346. * opaque structure for a data source.
  81347. *
  81348. * The callback function prototypes are similar (but not identical) to the
  81349. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  81350. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  81351. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  81352. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  81353. * is required. \warning You generally CANNOT directly use fseek or ftell
  81354. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  81355. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  81356. * large files. You will have to find an equivalent function (e.g. ftello),
  81357. * or write a wrapper. The same is true for feof() since this is usually
  81358. * implemented as a macro, not as a function whose address can be taken.
  81359. *
  81360. * \{
  81361. */
  81362. #ifdef __cplusplus
  81363. extern "C" {
  81364. #endif
  81365. /** This is the opaque handle type used by the callbacks. Typically
  81366. * this is a \c FILE* or address of a file descriptor.
  81367. */
  81368. typedef void* FLAC__IOHandle;
  81369. /** Signature for the read callback.
  81370. * The signature and semantics match POSIX fread() implementations
  81371. * and can generally be used interchangeably.
  81372. *
  81373. * \param ptr The address of the read buffer.
  81374. * \param size The size of the records to be read.
  81375. * \param nmemb The number of records to be read.
  81376. * \param handle The handle to the data source.
  81377. * \retval size_t
  81378. * The number of records read.
  81379. */
  81380. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  81381. /** Signature for the write callback.
  81382. * The signature and semantics match POSIX fwrite() implementations
  81383. * and can generally be used interchangeably.
  81384. *
  81385. * \param ptr The address of the write buffer.
  81386. * \param size The size of the records to be written.
  81387. * \param nmemb The number of records to be written.
  81388. * \param handle The handle to the data source.
  81389. * \retval size_t
  81390. * The number of records written.
  81391. */
  81392. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  81393. /** Signature for the seek callback.
  81394. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  81395. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  81396. * and 32-bits wide.
  81397. *
  81398. * \param handle The handle to the data source.
  81399. * \param offset The new position, relative to \a whence
  81400. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  81401. * \retval int
  81402. * \c 0 on success, \c -1 on error.
  81403. */
  81404. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  81405. /** Signature for the tell callback.
  81406. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  81407. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  81408. * and 32-bits wide.
  81409. *
  81410. * \param handle The handle to the data source.
  81411. * \retval FLAC__int64
  81412. * The current position on success, \c -1 on error.
  81413. */
  81414. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  81415. /** Signature for the EOF callback.
  81416. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  81417. * on many systems, feof() is a macro, so in this case a wrapper function
  81418. * must be provided instead.
  81419. *
  81420. * \param handle The handle to the data source.
  81421. * \retval int
  81422. * \c 0 if not at end of file, nonzero if at end of file.
  81423. */
  81424. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  81425. /** Signature for the close callback.
  81426. * The signature and semantics match POSIX fclose() implementations
  81427. * and can generally be used interchangeably.
  81428. *
  81429. * \param handle The handle to the data source.
  81430. * \retval int
  81431. * \c 0 on success, \c EOF on error.
  81432. */
  81433. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  81434. /** A structure for holding a set of callbacks.
  81435. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  81436. * describe which of the callbacks are required. The ones that are not
  81437. * required may be set to NULL.
  81438. *
  81439. * If the seek requirement for an interface is optional, you can signify that
  81440. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  81441. */
  81442. typedef struct {
  81443. FLAC__IOCallback_Read read;
  81444. FLAC__IOCallback_Write write;
  81445. FLAC__IOCallback_Seek seek;
  81446. FLAC__IOCallback_Tell tell;
  81447. FLAC__IOCallback_Eof eof;
  81448. FLAC__IOCallback_Close close;
  81449. } FLAC__IOCallbacks;
  81450. /* \} */
  81451. #ifdef __cplusplus
  81452. }
  81453. #endif
  81454. #endif
  81455. /********* End of inlined file: callback.h *********/
  81456. /********* Start of inlined file: format.h *********/
  81457. #ifndef FLAC__FORMAT_H
  81458. #define FLAC__FORMAT_H
  81459. #ifdef __cplusplus
  81460. extern "C" {
  81461. #endif
  81462. /** \file include/FLAC/format.h
  81463. *
  81464. * \brief
  81465. * This module contains structure definitions for the representation
  81466. * of FLAC format components in memory. These are the basic
  81467. * structures used by the rest of the interfaces.
  81468. *
  81469. * See the detailed documentation in the
  81470. * \link flac_format format \endlink module.
  81471. */
  81472. /** \defgroup flac_format FLAC/format.h: format components
  81473. * \ingroup flac
  81474. *
  81475. * \brief
  81476. * This module contains structure definitions for the representation
  81477. * of FLAC format components in memory. These are the basic
  81478. * structures used by the rest of the interfaces.
  81479. *
  81480. * First, you should be familiar with the
  81481. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  81482. * follow directly from the specification. As a user of libFLAC, the
  81483. * interesting parts really are the structures that describe the frame
  81484. * header and metadata blocks.
  81485. *
  81486. * The format structures here are very primitive, designed to store
  81487. * information in an efficient way. Reading information from the
  81488. * structures is easy but creating or modifying them directly is
  81489. * more complex. For the most part, as a user of a library, editing
  81490. * is not necessary; however, for metadata blocks it is, so there are
  81491. * convenience functions provided in the \link flac_metadata metadata
  81492. * module \endlink to simplify the manipulation of metadata blocks.
  81493. *
  81494. * \note
  81495. * It's not the best convention, but symbols ending in _LEN are in bits
  81496. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  81497. * global variables because they are usually used when declaring byte
  81498. * arrays and some compilers require compile-time knowledge of array
  81499. * sizes when declared on the stack.
  81500. *
  81501. * \{
  81502. */
  81503. /*
  81504. Most of the values described in this file are defined by the FLAC
  81505. format specification. There is nothing to tune here.
  81506. */
  81507. /** The largest legal metadata type code. */
  81508. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  81509. /** The minimum block size, in samples, permitted by the format. */
  81510. #define FLAC__MIN_BLOCK_SIZE (16u)
  81511. /** The maximum block size, in samples, permitted by the format. */
  81512. #define FLAC__MAX_BLOCK_SIZE (65535u)
  81513. /** The maximum block size, in samples, permitted by the FLAC subset for
  81514. * sample rates up to 48kHz. */
  81515. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  81516. /** The maximum number of channels permitted by the format. */
  81517. #define FLAC__MAX_CHANNELS (8u)
  81518. /** The minimum sample resolution permitted by the format. */
  81519. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  81520. /** The maximum sample resolution permitted by the format. */
  81521. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  81522. /** The maximum sample resolution permitted by libFLAC.
  81523. *
  81524. * \warning
  81525. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  81526. * the reference encoder/decoder is currently limited to 24 bits because
  81527. * of prevalent 32-bit math, so make sure and use this value when
  81528. * appropriate.
  81529. */
  81530. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  81531. /** The maximum sample rate permitted by the format. The value is
  81532. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  81533. * as to why.
  81534. */
  81535. #define FLAC__MAX_SAMPLE_RATE (655350u)
  81536. /** The maximum LPC order permitted by the format. */
  81537. #define FLAC__MAX_LPC_ORDER (32u)
  81538. /** The maximum LPC order permitted by the FLAC subset for sample rates
  81539. * up to 48kHz. */
  81540. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  81541. /** The minimum quantized linear predictor coefficient precision
  81542. * permitted by the format.
  81543. */
  81544. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  81545. /** The maximum quantized linear predictor coefficient precision
  81546. * permitted by the format.
  81547. */
  81548. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  81549. /** The maximum order of the fixed predictors permitted by the format. */
  81550. #define FLAC__MAX_FIXED_ORDER (4u)
  81551. /** The maximum Rice partition order permitted by the format. */
  81552. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  81553. /** The maximum Rice partition order permitted by the FLAC Subset. */
  81554. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  81555. /** The version string of the release, stamped onto the libraries and binaries.
  81556. *
  81557. * \note
  81558. * This does not correspond to the shared library version number, which
  81559. * is used to determine binary compatibility.
  81560. */
  81561. extern FLAC_API const char *FLAC__VERSION_STRING;
  81562. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  81563. * This is a NUL-terminated ASCII string; when inserted into the
  81564. * VORBIS_COMMENT the trailing null is stripped.
  81565. */
  81566. extern FLAC_API const char *FLAC__VENDOR_STRING;
  81567. /** The byte string representation of the beginning of a FLAC stream. */
  81568. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  81569. /** The 32-bit integer big-endian representation of the beginning of
  81570. * a FLAC stream.
  81571. */
  81572. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  81573. /** The length of the FLAC signature in bits. */
  81574. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  81575. /** The length of the FLAC signature in bytes. */
  81576. #define FLAC__STREAM_SYNC_LENGTH (4u)
  81577. /*****************************************************************************
  81578. *
  81579. * Subframe structures
  81580. *
  81581. *****************************************************************************/
  81582. /*****************************************************************************/
  81583. /** An enumeration of the available entropy coding methods. */
  81584. typedef enum {
  81585. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  81586. /**< Residual is coded by partitioning into contexts, each with it's own
  81587. * 4-bit Rice parameter. */
  81588. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  81589. /**< Residual is coded by partitioning into contexts, each with it's own
  81590. * 5-bit Rice parameter. */
  81591. } FLAC__EntropyCodingMethodType;
  81592. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  81593. *
  81594. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  81595. * give the string equivalent. The contents should not be modified.
  81596. */
  81597. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  81598. /** Contents of a Rice partitioned residual
  81599. */
  81600. typedef struct {
  81601. unsigned *parameters;
  81602. /**< The Rice parameters for each context. */
  81603. unsigned *raw_bits;
  81604. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  81605. * partitions and zero for unescaped partitions.
  81606. */
  81607. unsigned capacity_by_order;
  81608. /**< The capacity of the \a parameters and \a raw_bits arrays
  81609. * specified as an order, i.e. the number of array elements
  81610. * allocated is 2 ^ \a capacity_by_order.
  81611. */
  81612. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  81613. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  81614. */
  81615. typedef struct {
  81616. unsigned order;
  81617. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  81618. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  81619. /**< The context's Rice parameters and/or raw bits. */
  81620. } FLAC__EntropyCodingMethod_PartitionedRice;
  81621. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  81622. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  81623. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  81624. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  81625. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  81626. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  81627. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  81628. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  81629. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  81630. */
  81631. typedef struct {
  81632. FLAC__EntropyCodingMethodType type;
  81633. union {
  81634. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  81635. } data;
  81636. } FLAC__EntropyCodingMethod;
  81637. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  81638. /*****************************************************************************/
  81639. /** An enumeration of the available subframe types. */
  81640. typedef enum {
  81641. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  81642. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  81643. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  81644. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  81645. } FLAC__SubframeType;
  81646. /** Maps a FLAC__SubframeType to a C string.
  81647. *
  81648. * Using a FLAC__SubframeType as the index to this array will
  81649. * give the string equivalent. The contents should not be modified.
  81650. */
  81651. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  81652. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  81653. */
  81654. typedef struct {
  81655. FLAC__int32 value; /**< The constant signal value. */
  81656. } FLAC__Subframe_Constant;
  81657. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  81658. */
  81659. typedef struct {
  81660. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  81661. } FLAC__Subframe_Verbatim;
  81662. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  81663. */
  81664. typedef struct {
  81665. FLAC__EntropyCodingMethod entropy_coding_method;
  81666. /**< The residual coding method. */
  81667. unsigned order;
  81668. /**< The polynomial order. */
  81669. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  81670. /**< Warmup samples to prime the predictor, length == order. */
  81671. const FLAC__int32 *residual;
  81672. /**< The residual signal, length == (blocksize minus order) samples. */
  81673. } FLAC__Subframe_Fixed;
  81674. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  81675. */
  81676. typedef struct {
  81677. FLAC__EntropyCodingMethod entropy_coding_method;
  81678. /**< The residual coding method. */
  81679. unsigned order;
  81680. /**< The FIR order. */
  81681. unsigned qlp_coeff_precision;
  81682. /**< Quantized FIR filter coefficient precision in bits. */
  81683. int quantization_level;
  81684. /**< The qlp coeff shift needed. */
  81685. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  81686. /**< FIR filter coefficients. */
  81687. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  81688. /**< Warmup samples to prime the predictor, length == order. */
  81689. const FLAC__int32 *residual;
  81690. /**< The residual signal, length == (blocksize minus order) samples. */
  81691. } FLAC__Subframe_LPC;
  81692. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  81693. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  81694. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  81695. */
  81696. typedef struct {
  81697. FLAC__SubframeType type;
  81698. union {
  81699. FLAC__Subframe_Constant constant;
  81700. FLAC__Subframe_Fixed fixed;
  81701. FLAC__Subframe_LPC lpc;
  81702. FLAC__Subframe_Verbatim verbatim;
  81703. } data;
  81704. unsigned wasted_bits;
  81705. } FLAC__Subframe;
  81706. /** == 1 (bit)
  81707. *
  81708. * This used to be a zero-padding bit (hence the name
  81709. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  81710. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  81711. * to mean something else.
  81712. */
  81713. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  81714. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  81715. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  81716. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  81717. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  81718. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  81719. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  81720. /*****************************************************************************/
  81721. /*****************************************************************************
  81722. *
  81723. * Frame structures
  81724. *
  81725. *****************************************************************************/
  81726. /** An enumeration of the available channel assignments. */
  81727. typedef enum {
  81728. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  81729. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  81730. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  81731. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  81732. } FLAC__ChannelAssignment;
  81733. /** Maps a FLAC__ChannelAssignment to a C string.
  81734. *
  81735. * Using a FLAC__ChannelAssignment as the index to this array will
  81736. * give the string equivalent. The contents should not be modified.
  81737. */
  81738. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  81739. /** An enumeration of the possible frame numbering methods. */
  81740. typedef enum {
  81741. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  81742. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  81743. } FLAC__FrameNumberType;
  81744. /** Maps a FLAC__FrameNumberType to a C string.
  81745. *
  81746. * Using a FLAC__FrameNumberType as the index to this array will
  81747. * give the string equivalent. The contents should not be modified.
  81748. */
  81749. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  81750. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  81751. */
  81752. typedef struct {
  81753. unsigned blocksize;
  81754. /**< The number of samples per subframe. */
  81755. unsigned sample_rate;
  81756. /**< The sample rate in Hz. */
  81757. unsigned channels;
  81758. /**< The number of channels (== number of subframes). */
  81759. FLAC__ChannelAssignment channel_assignment;
  81760. /**< The channel assignment for the frame. */
  81761. unsigned bits_per_sample;
  81762. /**< The sample resolution. */
  81763. FLAC__FrameNumberType number_type;
  81764. /**< The numbering scheme used for the frame. As a convenience, the
  81765. * decoder will always convert a frame number to a sample number because
  81766. * the rules are complex. */
  81767. union {
  81768. FLAC__uint32 frame_number;
  81769. FLAC__uint64 sample_number;
  81770. } number;
  81771. /**< The frame number or sample number of first sample in frame;
  81772. * use the \a number_type value to determine which to use. */
  81773. FLAC__uint8 crc;
  81774. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  81775. * of the raw frame header bytes, meaning everything before the CRC byte
  81776. * including the sync code.
  81777. */
  81778. } FLAC__FrameHeader;
  81779. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  81780. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  81781. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  81782. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  81783. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  81784. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  81785. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  81786. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  81787. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  81788. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  81789. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  81790. */
  81791. typedef struct {
  81792. FLAC__uint16 crc;
  81793. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  81794. * 0) of the bytes before the crc, back to and including the frame header
  81795. * sync code.
  81796. */
  81797. } FLAC__FrameFooter;
  81798. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  81799. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  81800. */
  81801. typedef struct {
  81802. FLAC__FrameHeader header;
  81803. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  81804. FLAC__FrameFooter footer;
  81805. } FLAC__Frame;
  81806. /*****************************************************************************/
  81807. /*****************************************************************************
  81808. *
  81809. * Meta-data structures
  81810. *
  81811. *****************************************************************************/
  81812. /** An enumeration of the available metadata block types. */
  81813. typedef enum {
  81814. FLAC__METADATA_TYPE_STREAMINFO = 0,
  81815. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  81816. FLAC__METADATA_TYPE_PADDING = 1,
  81817. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  81818. FLAC__METADATA_TYPE_APPLICATION = 2,
  81819. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  81820. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  81821. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  81822. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  81823. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  81824. FLAC__METADATA_TYPE_CUESHEET = 5,
  81825. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  81826. FLAC__METADATA_TYPE_PICTURE = 6,
  81827. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  81828. FLAC__METADATA_TYPE_UNDEFINED = 7
  81829. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  81830. } FLAC__MetadataType;
  81831. /** Maps a FLAC__MetadataType to a C string.
  81832. *
  81833. * Using a FLAC__MetadataType as the index to this array will
  81834. * give the string equivalent. The contents should not be modified.
  81835. */
  81836. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  81837. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  81838. */
  81839. typedef struct {
  81840. unsigned min_blocksize, max_blocksize;
  81841. unsigned min_framesize, max_framesize;
  81842. unsigned sample_rate;
  81843. unsigned channels;
  81844. unsigned bits_per_sample;
  81845. FLAC__uint64 total_samples;
  81846. FLAC__byte md5sum[16];
  81847. } FLAC__StreamMetadata_StreamInfo;
  81848. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  81849. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  81850. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  81851. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  81852. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  81853. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  81854. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  81855. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  81856. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  81857. /** The total stream length of the STREAMINFO block in bytes. */
  81858. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  81859. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  81860. */
  81861. typedef struct {
  81862. int dummy;
  81863. /**< Conceptually this is an empty struct since we don't store the
  81864. * padding bytes. Empty structs are not allowed by some C compilers,
  81865. * hence the dummy.
  81866. */
  81867. } FLAC__StreamMetadata_Padding;
  81868. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  81869. */
  81870. typedef struct {
  81871. FLAC__byte id[4];
  81872. FLAC__byte *data;
  81873. } FLAC__StreamMetadata_Application;
  81874. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  81875. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  81876. */
  81877. typedef struct {
  81878. FLAC__uint64 sample_number;
  81879. /**< The sample number of the target frame. */
  81880. FLAC__uint64 stream_offset;
  81881. /**< The offset, in bytes, of the target frame with respect to
  81882. * beginning of the first frame. */
  81883. unsigned frame_samples;
  81884. /**< The number of samples in the target frame. */
  81885. } FLAC__StreamMetadata_SeekPoint;
  81886. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  81887. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  81888. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  81889. /** The total stream length of a seek point in bytes. */
  81890. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  81891. /** The value used in the \a sample_number field of
  81892. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  81893. * point (== 0xffffffffffffffff).
  81894. */
  81895. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  81896. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  81897. *
  81898. * \note From the format specification:
  81899. * - The seek points must be sorted by ascending sample number.
  81900. * - Each seek point's sample number must be the first sample of the
  81901. * target frame.
  81902. * - Each seek point's sample number must be unique within the table.
  81903. * - Existence of a SEEKTABLE block implies a correct setting of
  81904. * total_samples in the stream_info block.
  81905. * - Behavior is undefined when more than one SEEKTABLE block is
  81906. * present in a stream.
  81907. */
  81908. typedef struct {
  81909. unsigned num_points;
  81910. FLAC__StreamMetadata_SeekPoint *points;
  81911. } FLAC__StreamMetadata_SeekTable;
  81912. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  81913. *
  81914. * For convenience, the APIs maintain a trailing NUL character at the end of
  81915. * \a entry which is not counted toward \a length, i.e.
  81916. * \code strlen(entry) == length \endcode
  81917. */
  81918. typedef struct {
  81919. FLAC__uint32 length;
  81920. FLAC__byte *entry;
  81921. } FLAC__StreamMetadata_VorbisComment_Entry;
  81922. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  81923. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  81924. */
  81925. typedef struct {
  81926. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  81927. FLAC__uint32 num_comments;
  81928. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  81929. } FLAC__StreamMetadata_VorbisComment;
  81930. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  81931. /** FLAC CUESHEET track index structure. (See the
  81932. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  81933. * the full description of each field.)
  81934. */
  81935. typedef struct {
  81936. FLAC__uint64 offset;
  81937. /**< Offset in samples, relative to the track offset, of the index
  81938. * point.
  81939. */
  81940. FLAC__byte number;
  81941. /**< The index point number. */
  81942. } FLAC__StreamMetadata_CueSheet_Index;
  81943. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  81944. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  81945. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  81946. /** FLAC CUESHEET track structure. (See the
  81947. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  81948. * the full description of each field.)
  81949. */
  81950. typedef struct {
  81951. FLAC__uint64 offset;
  81952. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  81953. FLAC__byte number;
  81954. /**< The track number. */
  81955. char isrc[13];
  81956. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  81957. unsigned type:1;
  81958. /**< The track type: 0 for audio, 1 for non-audio. */
  81959. unsigned pre_emphasis:1;
  81960. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  81961. FLAC__byte num_indices;
  81962. /**< The number of track index points. */
  81963. FLAC__StreamMetadata_CueSheet_Index *indices;
  81964. /**< NULL if num_indices == 0, else pointer to array of index points. */
  81965. } FLAC__StreamMetadata_CueSheet_Track;
  81966. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  81967. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  81968. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  81969. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  81970. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  81971. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  81972. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  81973. /** FLAC CUESHEET structure. (See the
  81974. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  81975. * for the full description of each field.)
  81976. */
  81977. typedef struct {
  81978. char media_catalog_number[129];
  81979. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  81980. * general, the media catalog number may be 0 to 128 bytes long; any
  81981. * unused characters should be right-padded with NUL characters.
  81982. */
  81983. FLAC__uint64 lead_in;
  81984. /**< The number of lead-in samples. */
  81985. FLAC__bool is_cd;
  81986. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  81987. unsigned num_tracks;
  81988. /**< The number of tracks. */
  81989. FLAC__StreamMetadata_CueSheet_Track *tracks;
  81990. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  81991. } FLAC__StreamMetadata_CueSheet;
  81992. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  81993. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  81994. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  81995. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  81996. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  81997. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  81998. typedef enum {
  81999. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  82000. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  82001. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  82002. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  82003. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  82004. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  82005. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  82006. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  82007. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  82008. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  82009. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  82010. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  82011. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  82012. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  82013. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  82014. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  82015. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  82016. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  82017. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  82018. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  82019. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  82020. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  82021. } FLAC__StreamMetadata_Picture_Type;
  82022. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  82023. *
  82024. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  82025. * will give the string equivalent. The contents should not be
  82026. * modified.
  82027. */
  82028. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  82029. /** FLAC PICTURE structure. (See the
  82030. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  82031. * for the full description of each field.)
  82032. */
  82033. typedef struct {
  82034. FLAC__StreamMetadata_Picture_Type type;
  82035. /**< The kind of picture stored. */
  82036. char *mime_type;
  82037. /**< Picture data's MIME type, in ASCII printable characters
  82038. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  82039. * use picture data of MIME type \c image/jpeg or \c image/png. A
  82040. * MIME type of '-->' is also allowed, in which case the picture
  82041. * data should be a complete URL. In file storage, the MIME type is
  82042. * stored as a 32-bit length followed by the ASCII string with no NUL
  82043. * terminator, but is converted to a plain C string in this structure
  82044. * for convenience.
  82045. */
  82046. FLAC__byte *description;
  82047. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  82048. * the description is stored as a 32-bit length followed by the UTF-8
  82049. * string with no NUL terminator, but is converted to a plain C string
  82050. * in this structure for convenience.
  82051. */
  82052. FLAC__uint32 width;
  82053. /**< Picture's width in pixels. */
  82054. FLAC__uint32 height;
  82055. /**< Picture's height in pixels. */
  82056. FLAC__uint32 depth;
  82057. /**< Picture's color depth in bits-per-pixel. */
  82058. FLAC__uint32 colors;
  82059. /**< For indexed palettes (like GIF), picture's number of colors (the
  82060. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  82061. */
  82062. FLAC__uint32 data_length;
  82063. /**< Length of binary picture data in bytes. */
  82064. FLAC__byte *data;
  82065. /**< Binary picture data. */
  82066. } FLAC__StreamMetadata_Picture;
  82067. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  82068. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  82069. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  82070. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  82071. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  82072. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  82073. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  82074. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  82075. /** Structure that is used when a metadata block of unknown type is loaded.
  82076. * The contents are opaque. The structure is used only internally to
  82077. * correctly handle unknown metadata.
  82078. */
  82079. typedef struct {
  82080. FLAC__byte *data;
  82081. } FLAC__StreamMetadata_Unknown;
  82082. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  82083. */
  82084. typedef struct {
  82085. FLAC__MetadataType type;
  82086. /**< The type of the metadata block; used determine which member of the
  82087. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  82088. * then \a data.unknown must be used. */
  82089. FLAC__bool is_last;
  82090. /**< \c true if this metadata block is the last, else \a false */
  82091. unsigned length;
  82092. /**< Length, in bytes, of the block data as it appears in the stream. */
  82093. union {
  82094. FLAC__StreamMetadata_StreamInfo stream_info;
  82095. FLAC__StreamMetadata_Padding padding;
  82096. FLAC__StreamMetadata_Application application;
  82097. FLAC__StreamMetadata_SeekTable seek_table;
  82098. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  82099. FLAC__StreamMetadata_CueSheet cue_sheet;
  82100. FLAC__StreamMetadata_Picture picture;
  82101. FLAC__StreamMetadata_Unknown unknown;
  82102. } data;
  82103. /**< Polymorphic block data; use the \a type value to determine which
  82104. * to use. */
  82105. } FLAC__StreamMetadata;
  82106. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  82107. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  82108. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  82109. /** The total stream length of a metadata block header in bytes. */
  82110. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  82111. /*****************************************************************************/
  82112. /*****************************************************************************
  82113. *
  82114. * Utility functions
  82115. *
  82116. *****************************************************************************/
  82117. /** Tests that a sample rate is valid for FLAC.
  82118. *
  82119. * \param sample_rate The sample rate to test for compliance.
  82120. * \retval FLAC__bool
  82121. * \c true if the given sample rate conforms to the specification, else
  82122. * \c false.
  82123. */
  82124. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  82125. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  82126. * for valid sample rates are slightly more complex since the rate has to
  82127. * be expressible completely in the frame header.
  82128. *
  82129. * \param sample_rate The sample rate to test for compliance.
  82130. * \retval FLAC__bool
  82131. * \c true if the given sample rate conforms to the specification for the
  82132. * subset, else \c false.
  82133. */
  82134. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  82135. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  82136. * comment specification.
  82137. *
  82138. * Vorbis comment names must be composed only of characters from
  82139. * [0x20-0x3C,0x3E-0x7D].
  82140. *
  82141. * \param name A NUL-terminated string to be checked.
  82142. * \assert
  82143. * \code name != NULL \endcode
  82144. * \retval FLAC__bool
  82145. * \c false if entry name is illegal, else \c true.
  82146. */
  82147. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  82148. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  82149. * comment specification.
  82150. *
  82151. * Vorbis comment values must be valid UTF-8 sequences.
  82152. *
  82153. * \param value A string to be checked.
  82154. * \param length A the length of \a value in bytes. May be
  82155. * \c (unsigned)(-1) to indicate that \a value is a plain
  82156. * UTF-8 NUL-terminated string.
  82157. * \assert
  82158. * \code value != NULL \endcode
  82159. * \retval FLAC__bool
  82160. * \c false if entry name is illegal, else \c true.
  82161. */
  82162. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  82163. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  82164. * comment specification.
  82165. *
  82166. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  82167. * 'value' must be legal according to
  82168. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  82169. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  82170. *
  82171. * \param entry An entry to be checked.
  82172. * \param length The length of \a entry in bytes.
  82173. * \assert
  82174. * \code value != NULL \endcode
  82175. * \retval FLAC__bool
  82176. * \c false if entry name is illegal, else \c true.
  82177. */
  82178. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  82179. /** Check a seek table to see if it conforms to the FLAC specification.
  82180. * See the format specification for limits on the contents of the
  82181. * seek table.
  82182. *
  82183. * \param seek_table A pointer to a seek table to be checked.
  82184. * \assert
  82185. * \code seek_table != NULL \endcode
  82186. * \retval FLAC__bool
  82187. * \c false if seek table is illegal, else \c true.
  82188. */
  82189. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  82190. /** Sort a seek table's seek points according to the format specification.
  82191. * This includes a "unique-ification" step to remove duplicates, i.e.
  82192. * seek points with identical \a sample_number values. Duplicate seek
  82193. * points are converted into placeholder points and sorted to the end of
  82194. * the table.
  82195. *
  82196. * \param seek_table A pointer to a seek table to be sorted.
  82197. * \assert
  82198. * \code seek_table != NULL \endcode
  82199. * \retval unsigned
  82200. * The number of duplicate seek points converted into placeholders.
  82201. */
  82202. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  82203. /** Check a cue sheet to see if it conforms to the FLAC specification.
  82204. * See the format specification for limits on the contents of the
  82205. * cue sheet.
  82206. *
  82207. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  82208. * \param check_cd_da_subset If \c true, check CUESHEET against more
  82209. * stringent requirements for a CD-DA (audio) disc.
  82210. * \param violation Address of a pointer to a string. If there is a
  82211. * violation, a pointer to a string explanation of the
  82212. * violation will be returned here. \a violation may be
  82213. * \c NULL if you don't need the returned string. Do not
  82214. * free the returned string; it will always point to static
  82215. * data.
  82216. * \assert
  82217. * \code cue_sheet != NULL \endcode
  82218. * \retval FLAC__bool
  82219. * \c false if cue sheet is illegal, else \c true.
  82220. */
  82221. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  82222. /** Check picture data to see if it conforms to the FLAC specification.
  82223. * See the format specification for limits on the contents of the
  82224. * PICTURE block.
  82225. *
  82226. * \param picture A pointer to existing picture data to be checked.
  82227. * \param violation Address of a pointer to a string. If there is a
  82228. * violation, a pointer to a string explanation of the
  82229. * violation will be returned here. \a violation may be
  82230. * \c NULL if you don't need the returned string. Do not
  82231. * free the returned string; it will always point to static
  82232. * data.
  82233. * \assert
  82234. * \code picture != NULL \endcode
  82235. * \retval FLAC__bool
  82236. * \c false if picture data is illegal, else \c true.
  82237. */
  82238. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  82239. /* \} */
  82240. #ifdef __cplusplus
  82241. }
  82242. #endif
  82243. #endif
  82244. /********* End of inlined file: format.h *********/
  82245. /********* Start of inlined file: metadata.h *********/
  82246. #ifndef FLAC__METADATA_H
  82247. #define FLAC__METADATA_H
  82248. #include <sys/types.h> /* for off_t */
  82249. /* --------------------------------------------------------------------
  82250. (For an example of how all these routines are used, see the source
  82251. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  82252. metaflac in src/metaflac/)
  82253. ------------------------------------------------------------------*/
  82254. /** \file include/FLAC/metadata.h
  82255. *
  82256. * \brief
  82257. * This module provides functions for creating and manipulating FLAC
  82258. * metadata blocks in memory, and three progressively more powerful
  82259. * interfaces for traversing and editing metadata in FLAC files.
  82260. *
  82261. * See the detailed documentation for each interface in the
  82262. * \link flac_metadata metadata \endlink module.
  82263. */
  82264. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  82265. * \ingroup flac
  82266. *
  82267. * \brief
  82268. * This module provides functions for creating and manipulating FLAC
  82269. * metadata blocks in memory, and three progressively more powerful
  82270. * interfaces for traversing and editing metadata in native FLAC files.
  82271. * Note that currently only the Chain interface (level 2) supports Ogg
  82272. * FLAC files, and it is read-only i.e. no writing back changed
  82273. * metadata to file.
  82274. *
  82275. * There are three metadata interfaces of increasing complexity:
  82276. *
  82277. * Level 0:
  82278. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  82279. * PICTURE blocks.
  82280. *
  82281. * Level 1:
  82282. * Read-write access to all metadata blocks. This level is write-
  82283. * efficient in most cases (more on this below), and uses less memory
  82284. * than level 2.
  82285. *
  82286. * Level 2:
  82287. * Read-write access to all metadata blocks. This level is write-
  82288. * efficient in all cases, but uses more memory since all metadata for
  82289. * the whole file is read into memory and manipulated before writing
  82290. * out again.
  82291. *
  82292. * What do we mean by efficient? Since FLAC metadata appears at the
  82293. * beginning of the file, when writing metadata back to a FLAC file
  82294. * it is possible to grow or shrink the metadata such that the entire
  82295. * file must be rewritten. However, if the size remains the same during
  82296. * changes or PADDING blocks are utilized, only the metadata needs to be
  82297. * overwritten, which is much faster.
  82298. *
  82299. * Efficient means the whole file is rewritten at most one time, and only
  82300. * when necessary. Level 1 is not efficient only in the case that you
  82301. * cause more than one metadata block to grow or shrink beyond what can
  82302. * be accomodated by padding. In this case you should probably use level
  82303. * 2, which allows you to edit all the metadata for a file in memory and
  82304. * write it out all at once.
  82305. *
  82306. * All levels know how to skip over and not disturb an ID3v2 tag at the
  82307. * front of the file.
  82308. *
  82309. * All levels access files via their filenames. In addition, level 2
  82310. * has additional alternative read and write functions that take an I/O
  82311. * handle and callbacks, for situations where access by filename is not
  82312. * possible.
  82313. *
  82314. * In addition to the three interfaces, this module defines functions for
  82315. * creating and manipulating various metadata objects in memory. As we see
  82316. * from the Format module, FLAC metadata blocks in memory are very primitive
  82317. * structures for storing information in an efficient way. Reading
  82318. * information from the structures is easy but creating or modifying them
  82319. * directly is more complex. The metadata object routines here facilitate
  82320. * this by taking care of the consistency and memory management drudgery.
  82321. *
  82322. * Unless you will be using the level 1 or 2 interfaces to modify existing
  82323. * metadata however, you will not probably not need these.
  82324. *
  82325. * From a dependency standpoint, none of the encoders or decoders require
  82326. * the metadata module. This is so that embedded users can strip out the
  82327. * metadata module from libFLAC to reduce the size and complexity.
  82328. */
  82329. #ifdef __cplusplus
  82330. extern "C" {
  82331. #endif
  82332. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  82333. * \ingroup flac_metadata
  82334. *
  82335. * \brief
  82336. * The level 0 interface consists of individual routines to read the
  82337. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  82338. * only a filename.
  82339. *
  82340. * They try to skip any ID3v2 tag at the head of the file.
  82341. *
  82342. * \{
  82343. */
  82344. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  82345. * will try to skip any ID3v2 tag at the head of the file.
  82346. *
  82347. * \param filename The path to the FLAC file to read.
  82348. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  82349. * FLAC__StreamMetadata is a simple structure with no
  82350. * memory allocation involved, you pass the address of
  82351. * an existing structure. It need not be initialized.
  82352. * \assert
  82353. * \code filename != NULL \endcode
  82354. * \code streaminfo != NULL \endcode
  82355. * \retval FLAC__bool
  82356. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  82357. * \c false if there was a memory allocation error, a file decoder error,
  82358. * or the file contained no STREAMINFO block. (A memory allocation error
  82359. * is possible because this function must set up a file decoder.)
  82360. */
  82361. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  82362. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  82363. * function will try to skip any ID3v2 tag at the head of the file.
  82364. *
  82365. * \param filename The path to the FLAC file to read.
  82366. * \param tags The address where the returned pointer will be
  82367. * stored. The \a tags object must be deleted by
  82368. * the caller using FLAC__metadata_object_delete().
  82369. * \assert
  82370. * \code filename != NULL \endcode
  82371. * \code tags != NULL \endcode
  82372. * \retval FLAC__bool
  82373. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  82374. * and \a *tags will be set to the address of the metadata structure.
  82375. * Returns \c false if there was a memory allocation error, a file
  82376. * decoder error, or the file contained no VORBIS_COMMENT block, and
  82377. * \a *tags will be set to \c NULL.
  82378. */
  82379. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  82380. /** Read the CUESHEET metadata block of the given FLAC file. This
  82381. * function will try to skip any ID3v2 tag at the head of the file.
  82382. *
  82383. * \param filename The path to the FLAC file to read.
  82384. * \param cuesheet The address where the returned pointer will be
  82385. * stored. The \a cuesheet object must be deleted by
  82386. * the caller using FLAC__metadata_object_delete().
  82387. * \assert
  82388. * \code filename != NULL \endcode
  82389. * \code cuesheet != NULL \endcode
  82390. * \retval FLAC__bool
  82391. * \c true if a valid CUESHEET block was read from \a filename,
  82392. * and \a *cuesheet will be set to the address of the metadata
  82393. * structure. Returns \c false if there was a memory allocation
  82394. * error, a file decoder error, or the file contained no CUESHEET
  82395. * block, and \a *cuesheet will be set to \c NULL.
  82396. */
  82397. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  82398. /** Read a PICTURE metadata block of the given FLAC file. This
  82399. * function will try to skip any ID3v2 tag at the head of the file.
  82400. * Since there can be more than one PICTURE block in a file, this
  82401. * function takes a number of parameters that act as constraints to
  82402. * the search. The PICTURE block with the largest area matching all
  82403. * the constraints will be returned, or \a *picture will be set to
  82404. * \c NULL if there was no such block.
  82405. *
  82406. * \param filename The path to the FLAC file to read.
  82407. * \param picture The address where the returned pointer will be
  82408. * stored. The \a picture object must be deleted by
  82409. * the caller using FLAC__metadata_object_delete().
  82410. * \param type The desired picture type. Use \c -1 to mean
  82411. * "any type".
  82412. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  82413. * string will be matched exactly. Use \c NULL to
  82414. * mean "any MIME type".
  82415. * \param description The desired description. The string will be
  82416. * matched exactly. Use \c NULL to mean "any
  82417. * description".
  82418. * \param max_width The maximum width in pixels desired. Use
  82419. * \c (unsigned)(-1) to mean "any width".
  82420. * \param max_height The maximum height in pixels desired. Use
  82421. * \c (unsigned)(-1) to mean "any height".
  82422. * \param max_depth The maximum color depth in bits-per-pixel desired.
  82423. * Use \c (unsigned)(-1) to mean "any depth".
  82424. * \param max_colors The maximum number of colors desired. Use
  82425. * \c (unsigned)(-1) to mean "any number of colors".
  82426. * \assert
  82427. * \code filename != NULL \endcode
  82428. * \code picture != NULL \endcode
  82429. * \retval FLAC__bool
  82430. * \c true if a valid PICTURE block was read from \a filename,
  82431. * and \a *picture will be set to the address of the metadata
  82432. * structure. Returns \c false if there was a memory allocation
  82433. * error, a file decoder error, or the file contained no PICTURE
  82434. * block, and \a *picture will be set to \c NULL.
  82435. */
  82436. 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);
  82437. /* \} */
  82438. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  82439. * \ingroup flac_metadata
  82440. *
  82441. * \brief
  82442. * The level 1 interface provides read-write access to FLAC file metadata and
  82443. * operates directly on the FLAC file.
  82444. *
  82445. * The general usage of this interface is:
  82446. *
  82447. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  82448. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  82449. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  82450. * see if the file is writable, or only read access is allowed.
  82451. * - Use FLAC__metadata_simple_iterator_next() and
  82452. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  82453. * This is does not read the actual blocks themselves.
  82454. * FLAC__metadata_simple_iterator_next() is relatively fast.
  82455. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  82456. * forward from the front of the file.
  82457. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  82458. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  82459. * the current iterator position. The returned object is yours to modify
  82460. * and free.
  82461. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  82462. * back. You must have write permission to the original file. Make sure to
  82463. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  82464. * below.
  82465. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  82466. * Use the object creation functions from
  82467. * \link flac_metadata_object here \endlink to generate new objects.
  82468. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  82469. * currently referred to by the iterator, or replace it with padding.
  82470. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  82471. * finished.
  82472. *
  82473. * \note
  82474. * The FLAC file remains open the whole time between
  82475. * FLAC__metadata_simple_iterator_init() and
  82476. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  82477. * the file during this time.
  82478. *
  82479. * \note
  82480. * Do not modify the \a is_last, \a length, or \a type fields of returned
  82481. * FLAC__StreamMetadata objects. These are managed automatically.
  82482. *
  82483. * \note
  82484. * If any of the modification functions
  82485. * (FLAC__metadata_simple_iterator_set_block(),
  82486. * FLAC__metadata_simple_iterator_delete_block(),
  82487. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  82488. * you should delete the iterator as it may no longer be valid.
  82489. *
  82490. * \{
  82491. */
  82492. struct FLAC__Metadata_SimpleIterator;
  82493. /** The opaque structure definition for the level 1 iterator type.
  82494. * See the
  82495. * \link flac_metadata_level1 metadata level 1 module \endlink
  82496. * for a detailed description.
  82497. */
  82498. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  82499. /** Status type for FLAC__Metadata_SimpleIterator.
  82500. *
  82501. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  82502. */
  82503. typedef enum {
  82504. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  82505. /**< The iterator is in the normal OK state */
  82506. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  82507. /**< The data passed into a function violated the function's usage criteria */
  82508. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  82509. /**< The iterator could not open the target file */
  82510. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  82511. /**< The iterator could not find the FLAC signature at the start of the file */
  82512. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  82513. /**< The iterator tried to write to a file that was not writable */
  82514. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  82515. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  82516. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  82517. /**< The iterator encountered an error while reading the FLAC file */
  82518. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  82519. /**< The iterator encountered an error while seeking in the FLAC file */
  82520. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  82521. /**< The iterator encountered an error while writing the FLAC file */
  82522. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  82523. /**< The iterator encountered an error renaming the FLAC file */
  82524. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  82525. /**< The iterator encountered an error removing the temporary file */
  82526. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  82527. /**< Memory allocation failed */
  82528. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  82529. /**< The caller violated an assertion or an unexpected error occurred */
  82530. } FLAC__Metadata_SimpleIteratorStatus;
  82531. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  82532. *
  82533. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  82534. * will give the string equivalent. The contents should not be modified.
  82535. */
  82536. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  82537. /** Create a new iterator instance.
  82538. *
  82539. * \retval FLAC__Metadata_SimpleIterator*
  82540. * \c NULL if there was an error allocating memory, else the new instance.
  82541. */
  82542. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  82543. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  82544. *
  82545. * \param iterator A pointer to an existing iterator.
  82546. * \assert
  82547. * \code iterator != NULL \endcode
  82548. */
  82549. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  82550. /** Get the current status of the iterator. Call this after a function
  82551. * returns \c false to get the reason for the error. Also resets the status
  82552. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  82553. *
  82554. * \param iterator A pointer to an existing iterator.
  82555. * \assert
  82556. * \code iterator != NULL \endcode
  82557. * \retval FLAC__Metadata_SimpleIteratorStatus
  82558. * The current status of the iterator.
  82559. */
  82560. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  82561. /** Initialize the iterator to point to the first metadata block in the
  82562. * given FLAC file.
  82563. *
  82564. * \param iterator A pointer to an existing iterator.
  82565. * \param filename The path to the FLAC file.
  82566. * \param read_only If \c true, the FLAC file will be opened
  82567. * in read-only mode; if \c false, the FLAC
  82568. * file will be opened for edit even if no
  82569. * edits are performed.
  82570. * \param preserve_file_stats If \c true, the owner and modification
  82571. * time will be preserved even if the FLAC
  82572. * file is written to.
  82573. * \assert
  82574. * \code iterator != NULL \endcode
  82575. * \code filename != NULL \endcode
  82576. * \retval FLAC__bool
  82577. * \c false if a memory allocation error occurs, the file can't be
  82578. * opened, or another error occurs, else \c true.
  82579. */
  82580. 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);
  82581. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  82582. * FLAC__metadata_simple_iterator_set_block() and
  82583. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  82584. *
  82585. * \param iterator A pointer to an existing iterator.
  82586. * \assert
  82587. * \code iterator != NULL \endcode
  82588. * \retval FLAC__bool
  82589. * See above.
  82590. */
  82591. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  82592. /** Moves the iterator forward one metadata block, returning \c false if
  82593. * already at the end.
  82594. *
  82595. * \param iterator A pointer to an existing initialized iterator.
  82596. * \assert
  82597. * \code iterator != NULL \endcode
  82598. * \a iterator has been successfully initialized with
  82599. * FLAC__metadata_simple_iterator_init()
  82600. * \retval FLAC__bool
  82601. * \c false if already at the last metadata block of the chain, else
  82602. * \c true.
  82603. */
  82604. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  82605. /** Moves the iterator backward one metadata block, returning \c false if
  82606. * already at the beginning.
  82607. *
  82608. * \param iterator A pointer to an existing initialized iterator.
  82609. * \assert
  82610. * \code iterator != NULL \endcode
  82611. * \a iterator has been successfully initialized with
  82612. * FLAC__metadata_simple_iterator_init()
  82613. * \retval FLAC__bool
  82614. * \c false if already at the first metadata block of the chain, else
  82615. * \c true.
  82616. */
  82617. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  82618. /** Returns a flag telling if the current metadata block is the last.
  82619. *
  82620. * \param iterator A pointer to an existing initialized iterator.
  82621. * \assert
  82622. * \code iterator != NULL \endcode
  82623. * \a iterator has been successfully initialized with
  82624. * FLAC__metadata_simple_iterator_init()
  82625. * \retval FLAC__bool
  82626. * \c true if the current metadata block is the last in the file,
  82627. * else \c false.
  82628. */
  82629. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  82630. /** Get the offset of the metadata block at the current position. This
  82631. * avoids reading the actual block data which can save time for large
  82632. * blocks.
  82633. *
  82634. * \param iterator A pointer to an existing initialized iterator.
  82635. * \assert
  82636. * \code iterator != NULL \endcode
  82637. * \a iterator has been successfully initialized with
  82638. * FLAC__metadata_simple_iterator_init()
  82639. * \retval off_t
  82640. * The offset of the metadata block at the current iterator position.
  82641. * This is the byte offset relative to the beginning of the file of
  82642. * the current metadata block's header.
  82643. */
  82644. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  82645. /** Get the type of the metadata block at the current position. This
  82646. * avoids reading the actual block data which can save time for large
  82647. * blocks.
  82648. *
  82649. * \param iterator A pointer to an existing initialized iterator.
  82650. * \assert
  82651. * \code iterator != NULL \endcode
  82652. * \a iterator has been successfully initialized with
  82653. * FLAC__metadata_simple_iterator_init()
  82654. * \retval FLAC__MetadataType
  82655. * The type of the metadata block at the current iterator position.
  82656. */
  82657. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  82658. /** Get the length of the metadata block at the current position. This
  82659. * avoids reading the actual block data which can save time for large
  82660. * blocks.
  82661. *
  82662. * \param iterator A pointer to an existing initialized iterator.
  82663. * \assert
  82664. * \code iterator != NULL \endcode
  82665. * \a iterator has been successfully initialized with
  82666. * FLAC__metadata_simple_iterator_init()
  82667. * \retval unsigned
  82668. * The length of the metadata block at the current iterator position.
  82669. * The is same length as that in the
  82670. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  82671. * i.e. the length of the metadata body that follows the header.
  82672. */
  82673. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  82674. /** Get the application ID of the \c APPLICATION block at the current
  82675. * position. This avoids reading the actual block data which can save
  82676. * time for large blocks.
  82677. *
  82678. * \param iterator A pointer to an existing initialized iterator.
  82679. * \param id A pointer to a buffer of at least \c 4 bytes where
  82680. * the ID will be stored.
  82681. * \assert
  82682. * \code iterator != NULL \endcode
  82683. * \code id != NULL \endcode
  82684. * \a iterator has been successfully initialized with
  82685. * FLAC__metadata_simple_iterator_init()
  82686. * \retval FLAC__bool
  82687. * \c true if the ID was successfully read, else \c false, in which
  82688. * case you should check FLAC__metadata_simple_iterator_status() to
  82689. * find out why. If the status is
  82690. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  82691. * current metadata block is not an \c APPLICATION block. Otherwise
  82692. * if the status is
  82693. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  82694. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  82695. * occurred and the iterator can no longer be used.
  82696. */
  82697. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  82698. /** Get the metadata block at the current position. You can modify the
  82699. * block but must use FLAC__metadata_simple_iterator_set_block() to
  82700. * write it back to the FLAC file.
  82701. *
  82702. * You must call FLAC__metadata_object_delete() on the returned object
  82703. * when you are finished with it.
  82704. *
  82705. * \param iterator A pointer to an existing initialized iterator.
  82706. * \assert
  82707. * \code iterator != NULL \endcode
  82708. * \a iterator has been successfully initialized with
  82709. * FLAC__metadata_simple_iterator_init()
  82710. * \retval FLAC__StreamMetadata*
  82711. * The current metadata block, or \c NULL if there was a memory
  82712. * allocation error.
  82713. */
  82714. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  82715. /** Write a block back to the FLAC file. This function tries to be
  82716. * as efficient as possible; how the block is actually written is
  82717. * shown by the following:
  82718. *
  82719. * Existing block is a STREAMINFO block and the new block is a
  82720. * STREAMINFO block: the new block is written in place. Make sure
  82721. * you know what you're doing when changing the values of a
  82722. * STREAMINFO block.
  82723. *
  82724. * Existing block is a STREAMINFO block and the new block is a
  82725. * not a STREAMINFO block: this is an error since the first block
  82726. * must be a STREAMINFO block. Returns \c false without altering the
  82727. * file.
  82728. *
  82729. * Existing block is not a STREAMINFO block and the new block is a
  82730. * STREAMINFO block: this is an error since there may be only one
  82731. * STREAMINFO block. Returns \c false without altering the file.
  82732. *
  82733. * Existing block and new block are the same length: the existing
  82734. * block will be replaced by the new block, written in place.
  82735. *
  82736. * Existing block is longer than new block: if use_padding is \c true,
  82737. * the existing block will be overwritten in place with the new
  82738. * block followed by a PADDING block, if possible, to make the total
  82739. * size the same as the existing block. Remember that a padding
  82740. * block requires at least four bytes so if the difference in size
  82741. * between the new block and existing block is less than that, the
  82742. * entire file will have to be rewritten, using the new block's
  82743. * exact size. If use_padding is \c false, the entire file will be
  82744. * rewritten, replacing the existing block by the new block.
  82745. *
  82746. * Existing block is shorter than new block: if use_padding is \c true,
  82747. * the function will try and expand the new block into the following
  82748. * PADDING block, if it exists and doing so won't shrink the PADDING
  82749. * block to less than 4 bytes. If there is no following PADDING
  82750. * block, or it will shrink to less than 4 bytes, or use_padding is
  82751. * \c false, the entire file is rewritten, replacing the existing block
  82752. * with the new block. Note that in this case any following PADDING
  82753. * block is preserved as is.
  82754. *
  82755. * After writing the block, the iterator will remain in the same
  82756. * place, i.e. pointing to the new block.
  82757. *
  82758. * \param iterator A pointer to an existing initialized iterator.
  82759. * \param block The block to set.
  82760. * \param use_padding See above.
  82761. * \assert
  82762. * \code iterator != NULL \endcode
  82763. * \a iterator has been successfully initialized with
  82764. * FLAC__metadata_simple_iterator_init()
  82765. * \code block != NULL \endcode
  82766. * \retval FLAC__bool
  82767. * \c true if successful, else \c false.
  82768. */
  82769. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  82770. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  82771. * except that instead of writing over an existing block, it appends
  82772. * a block after the existing block. \a use_padding is again used to
  82773. * tell the function to try an expand into following padding in an
  82774. * attempt to avoid rewriting the entire file.
  82775. *
  82776. * This function will fail and return \c false if given a STREAMINFO
  82777. * block.
  82778. *
  82779. * After writing the block, the iterator will be pointing to the
  82780. * new block.
  82781. *
  82782. * \param iterator A pointer to an existing initialized iterator.
  82783. * \param block The block to set.
  82784. * \param use_padding See above.
  82785. * \assert
  82786. * \code iterator != NULL \endcode
  82787. * \a iterator has been successfully initialized with
  82788. * FLAC__metadata_simple_iterator_init()
  82789. * \code block != NULL \endcode
  82790. * \retval FLAC__bool
  82791. * \c true if successful, else \c false.
  82792. */
  82793. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  82794. /** Deletes the block at the current position. This will cause the
  82795. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  82796. * in which case the block will be replaced by an equal-sized PADDING
  82797. * block. The iterator will be left pointing to the block before the
  82798. * one just deleted.
  82799. *
  82800. * You may not delete the STREAMINFO block.
  82801. *
  82802. * \param iterator A pointer to an existing initialized iterator.
  82803. * \param use_padding See above.
  82804. * \assert
  82805. * \code iterator != NULL \endcode
  82806. * \a iterator has been successfully initialized with
  82807. * FLAC__metadata_simple_iterator_init()
  82808. * \retval FLAC__bool
  82809. * \c true if successful, else \c false.
  82810. */
  82811. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  82812. /* \} */
  82813. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  82814. * \ingroup flac_metadata
  82815. *
  82816. * \brief
  82817. * The level 2 interface provides read-write access to FLAC file metadata;
  82818. * all metadata is read into memory, operated on in memory, and then written
  82819. * to file, which is more efficient than level 1 when editing multiple blocks.
  82820. *
  82821. * Currently Ogg FLAC is supported for read only, via
  82822. * FLAC__metadata_chain_read_ogg() but a subsequent
  82823. * FLAC__metadata_chain_write() will fail.
  82824. *
  82825. * The general usage of this interface is:
  82826. *
  82827. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  82828. * linked list of FLAC metadata blocks.
  82829. * - Read all metadata into the the chain from a FLAC file using
  82830. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  82831. * check the status.
  82832. * - Optionally, consolidate the padding using
  82833. * FLAC__metadata_chain_merge_padding() or
  82834. * FLAC__metadata_chain_sort_padding().
  82835. * - Create a new iterator using FLAC__metadata_iterator_new()
  82836. * - Initialize the iterator to point to the first element in the chain
  82837. * using FLAC__metadata_iterator_init()
  82838. * - Traverse the chain using FLAC__metadata_iterator_next and
  82839. * FLAC__metadata_iterator_prev().
  82840. * - Get a block for reading or modification using
  82841. * FLAC__metadata_iterator_get_block(). The pointer to the object
  82842. * inside the chain is returned, so the block is yours to modify.
  82843. * Changes will be reflected in the FLAC file when you write the
  82844. * chain. You can also add and delete blocks (see functions below).
  82845. * - When done, write out the chain using FLAC__metadata_chain_write().
  82846. * Make sure to read the whole comment to the function below.
  82847. * - Delete the chain using FLAC__metadata_chain_delete().
  82848. *
  82849. * \note
  82850. * Even though the FLAC file is not open while the chain is being
  82851. * manipulated, you must not alter the file externally during
  82852. * this time. The chain assumes the FLAC file will not change
  82853. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  82854. * and FLAC__metadata_chain_write().
  82855. *
  82856. * \note
  82857. * Do not modify the is_last, length, or type fields of returned
  82858. * FLAC__StreamMetadata objects. These are managed automatically.
  82859. *
  82860. * \note
  82861. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  82862. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  82863. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  82864. * become owned by the chain and they will be deleted when the chain is
  82865. * deleted.
  82866. *
  82867. * \{
  82868. */
  82869. struct FLAC__Metadata_Chain;
  82870. /** The opaque structure definition for the level 2 chain type.
  82871. */
  82872. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  82873. struct FLAC__Metadata_Iterator;
  82874. /** The opaque structure definition for the level 2 iterator type.
  82875. */
  82876. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  82877. typedef enum {
  82878. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  82879. /**< The chain is in the normal OK state */
  82880. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  82881. /**< The data passed into a function violated the function's usage criteria */
  82882. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  82883. /**< The chain could not open the target file */
  82884. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  82885. /**< The chain could not find the FLAC signature at the start of the file */
  82886. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  82887. /**< The chain tried to write to a file that was not writable */
  82888. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  82889. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  82890. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  82891. /**< The chain encountered an error while reading the FLAC file */
  82892. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  82893. /**< The chain encountered an error while seeking in the FLAC file */
  82894. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  82895. /**< The chain encountered an error while writing the FLAC file */
  82896. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  82897. /**< The chain encountered an error renaming the FLAC file */
  82898. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  82899. /**< The chain encountered an error removing the temporary file */
  82900. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  82901. /**< Memory allocation failed */
  82902. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  82903. /**< The caller violated an assertion or an unexpected error occurred */
  82904. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  82905. /**< One or more of the required callbacks was NULL */
  82906. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  82907. /**< FLAC__metadata_chain_write() was called on a chain read by
  82908. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  82909. * or
  82910. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  82911. * was called on a chain read by
  82912. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  82913. * Matching read/write methods must always be used. */
  82914. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  82915. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  82916. * chain write requires a tempfile; use
  82917. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  82918. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  82919. * called when the chain write does not require a tempfile; use
  82920. * FLAC__metadata_chain_write_with_callbacks() instead.
  82921. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  82922. * before writing via callbacks. */
  82923. } FLAC__Metadata_ChainStatus;
  82924. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  82925. *
  82926. * Using a FLAC__Metadata_ChainStatus as the index to this array
  82927. * will give the string equivalent. The contents should not be modified.
  82928. */
  82929. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  82930. /*********** FLAC__Metadata_Chain ***********/
  82931. /** Create a new chain instance.
  82932. *
  82933. * \retval FLAC__Metadata_Chain*
  82934. * \c NULL if there was an error allocating memory, else the new instance.
  82935. */
  82936. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  82937. /** Free a chain instance. Deletes the object pointed to by \a chain.
  82938. *
  82939. * \param chain A pointer to an existing chain.
  82940. * \assert
  82941. * \code chain != NULL \endcode
  82942. */
  82943. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  82944. /** Get the current status of the chain. Call this after a function
  82945. * returns \c false to get the reason for the error. Also resets the
  82946. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  82947. *
  82948. * \param chain A pointer to an existing chain.
  82949. * \assert
  82950. * \code chain != NULL \endcode
  82951. * \retval FLAC__Metadata_ChainStatus
  82952. * The current status of the chain.
  82953. */
  82954. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  82955. /** Read all metadata from a FLAC file into the chain.
  82956. *
  82957. * \param chain A pointer to an existing chain.
  82958. * \param filename The path to the FLAC file to read.
  82959. * \assert
  82960. * \code chain != NULL \endcode
  82961. * \code filename != NULL \endcode
  82962. * \retval FLAC__bool
  82963. * \c true if a valid list of metadata blocks was read from
  82964. * \a filename, else \c false. On failure, check the status with
  82965. * FLAC__metadata_chain_status().
  82966. */
  82967. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  82968. /** Read all metadata from an Ogg FLAC file into the chain.
  82969. *
  82970. * \note Ogg FLAC metadata data writing is not supported yet and
  82971. * FLAC__metadata_chain_write() will fail.
  82972. *
  82973. * \param chain A pointer to an existing chain.
  82974. * \param filename The path to the Ogg FLAC file to read.
  82975. * \assert
  82976. * \code chain != NULL \endcode
  82977. * \code filename != NULL \endcode
  82978. * \retval FLAC__bool
  82979. * \c true if a valid list of metadata blocks was read from
  82980. * \a filename, else \c false. On failure, check the status with
  82981. * FLAC__metadata_chain_status().
  82982. */
  82983. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  82984. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  82985. *
  82986. * The \a handle need only be open for reading, but must be seekable.
  82987. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  82988. * for Windows).
  82989. *
  82990. * \param chain A pointer to an existing chain.
  82991. * \param handle The I/O handle of the FLAC stream to read. The
  82992. * handle will NOT be closed after the metadata is read;
  82993. * that is the duty of the caller.
  82994. * \param callbacks
  82995. * A set of callbacks to use for I/O. The mandatory
  82996. * callbacks are \a read, \a seek, and \a tell.
  82997. * \assert
  82998. * \code chain != NULL \endcode
  82999. * \retval FLAC__bool
  83000. * \c true if a valid list of metadata blocks was read from
  83001. * \a handle, else \c false. On failure, check the status with
  83002. * FLAC__metadata_chain_status().
  83003. */
  83004. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83005. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  83006. *
  83007. * The \a handle need only be open for reading, but must be seekable.
  83008. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83009. * for Windows).
  83010. *
  83011. * \note Ogg FLAC metadata data writing is not supported yet and
  83012. * FLAC__metadata_chain_write() will fail.
  83013. *
  83014. * \param chain A pointer to an existing chain.
  83015. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  83016. * handle will NOT be closed after the metadata is read;
  83017. * that is the duty of the caller.
  83018. * \param callbacks
  83019. * A set of callbacks to use for I/O. The mandatory
  83020. * callbacks are \a read, \a seek, and \a tell.
  83021. * \assert
  83022. * \code chain != NULL \endcode
  83023. * \retval FLAC__bool
  83024. * \c true if a valid list of metadata blocks was read from
  83025. * \a handle, else \c false. On failure, check the status with
  83026. * FLAC__metadata_chain_status().
  83027. */
  83028. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83029. /** Checks if writing the given chain would require the use of a
  83030. * temporary file, or if it could be written in place.
  83031. *
  83032. * Under certain conditions, padding can be utilized so that writing
  83033. * edited metadata back to the FLAC file does not require rewriting the
  83034. * entire file. If rewriting is required, then a temporary workfile is
  83035. * required. When writing metadata using callbacks, you must check
  83036. * this function to know whether to call
  83037. * FLAC__metadata_chain_write_with_callbacks() or
  83038. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  83039. * writing with FLAC__metadata_chain_write(), the temporary file is
  83040. * handled internally.
  83041. *
  83042. * \param chain A pointer to an existing chain.
  83043. * \param use_padding
  83044. * Whether or not padding will be allowed to be used
  83045. * during the write. The value of \a use_padding given
  83046. * here must match the value later passed to
  83047. * FLAC__metadata_chain_write_with_callbacks() or
  83048. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  83049. * \assert
  83050. * \code chain != NULL \endcode
  83051. * \retval FLAC__bool
  83052. * \c true if writing the current chain would require a tempfile, or
  83053. * \c false if metadata can be written in place.
  83054. */
  83055. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  83056. /** Write all metadata out to the FLAC file. This function tries to be as
  83057. * efficient as possible; how the metadata is actually written is shown by
  83058. * the following:
  83059. *
  83060. * If the current chain is the same size as the existing metadata, the new
  83061. * data is written in place.
  83062. *
  83063. * If the current chain is longer than the existing metadata, and
  83064. * \a use_padding is \c true, and the last block is a PADDING block of
  83065. * sufficient length, the function will truncate the final padding block
  83066. * so that the overall size of the metadata is the same as the existing
  83067. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  83068. * the above conditions are met, the entire FLAC file must be rewritten.
  83069. * If you want to use padding this way it is a good idea to call
  83070. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  83071. * amount of padding to work with, unless you need to preserve ordering
  83072. * of the PADDING blocks for some reason.
  83073. *
  83074. * If the current chain is shorter than the existing metadata, and
  83075. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  83076. * is extended to make the overall size the same as the existing data. If
  83077. * \a use_padding is \c true and the last block is not a PADDING block, a new
  83078. * PADDING block is added to the end of the new data to make it the same
  83079. * size as the existing data (if possible, see the note to
  83080. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  83081. * and the new data is written in place. If none of the above apply or
  83082. * \a use_padding is \c false, the entire FLAC file is rewritten.
  83083. *
  83084. * If \a preserve_file_stats is \c true, the owner and modification time will
  83085. * be preserved even if the FLAC file is written.
  83086. *
  83087. * For this write function to be used, the chain must have been read with
  83088. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  83089. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  83090. *
  83091. * \param chain A pointer to an existing chain.
  83092. * \param use_padding See above.
  83093. * \param preserve_file_stats See above.
  83094. * \assert
  83095. * \code chain != NULL \endcode
  83096. * \retval FLAC__bool
  83097. * \c true if the write succeeded, else \c false. On failure,
  83098. * check the status with FLAC__metadata_chain_status().
  83099. */
  83100. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  83101. /** Write all metadata out to a FLAC stream via callbacks.
  83102. *
  83103. * (See FLAC__metadata_chain_write() for the details on how padding is
  83104. * used to write metadata in place if possible.)
  83105. *
  83106. * The \a handle must be open for updating and be seekable. The
  83107. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  83108. * for Windows).
  83109. *
  83110. * For this write function to be used, the chain must have been read with
  83111. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83112. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83113. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  83114. * \c false.
  83115. *
  83116. * \param chain A pointer to an existing chain.
  83117. * \param use_padding See FLAC__metadata_chain_write()
  83118. * \param handle The I/O handle of the FLAC stream to write. The
  83119. * handle will NOT be closed after the metadata is
  83120. * written; that is the duty of the caller.
  83121. * \param callbacks A set of callbacks to use for I/O. The mandatory
  83122. * callbacks are \a write and \a seek.
  83123. * \assert
  83124. * \code chain != NULL \endcode
  83125. * \retval FLAC__bool
  83126. * \c true if the write succeeded, else \c false. On failure,
  83127. * check the status with FLAC__metadata_chain_status().
  83128. */
  83129. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83130. /** Write all metadata out to a FLAC stream via callbacks.
  83131. *
  83132. * (See FLAC__metadata_chain_write() for the details on how padding is
  83133. * used to write metadata in place if possible.)
  83134. *
  83135. * This version of the write-with-callbacks function must be used when
  83136. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  83137. * this function, you must supply an I/O handle corresponding to the
  83138. * FLAC file to edit, and a temporary handle to which the new FLAC
  83139. * file will be written. It is the caller's job to move this temporary
  83140. * FLAC file on top of the original FLAC file to complete the metadata
  83141. * edit.
  83142. *
  83143. * The \a handle must be open for reading and be seekable. The
  83144. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83145. * for Windows).
  83146. *
  83147. * The \a temp_handle must be open for writing. The
  83148. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  83149. * for Windows). It should be an empty stream, or at least positioned
  83150. * at the start-of-file (in which case it is the caller's duty to
  83151. * truncate it on return).
  83152. *
  83153. * For this write function to be used, the chain must have been read with
  83154. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83155. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83156. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  83157. * \c true.
  83158. *
  83159. * \param chain A pointer to an existing chain.
  83160. * \param use_padding See FLAC__metadata_chain_write()
  83161. * \param handle The I/O handle of the original FLAC stream to read.
  83162. * The handle will NOT be closed after the metadata is
  83163. * written; that is the duty of the caller.
  83164. * \param callbacks A set of callbacks to use for I/O on \a handle.
  83165. * The mandatory callbacks are \a read, \a seek, and
  83166. * \a eof.
  83167. * \param temp_handle The I/O handle of the FLAC stream to write. The
  83168. * handle will NOT be closed after the metadata is
  83169. * written; that is the duty of the caller.
  83170. * \param temp_callbacks
  83171. * A set of callbacks to use for I/O on temp_handle.
  83172. * The only mandatory callback is \a write.
  83173. * \assert
  83174. * \code chain != NULL \endcode
  83175. * \retval FLAC__bool
  83176. * \c true if the write succeeded, else \c false. On failure,
  83177. * check the status with FLAC__metadata_chain_status().
  83178. */
  83179. 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);
  83180. /** Merge adjacent PADDING blocks into a single block.
  83181. *
  83182. * \note This function does not write to the FLAC file, it only
  83183. * modifies the chain.
  83184. *
  83185. * \warning Any iterator on the current chain will become invalid after this
  83186. * call. You should delete the iterator and get a new one.
  83187. *
  83188. * \param chain A pointer to an existing chain.
  83189. * \assert
  83190. * \code chain != NULL \endcode
  83191. */
  83192. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  83193. /** This function will move all PADDING blocks to the end on the metadata,
  83194. * then merge them into a single block.
  83195. *
  83196. * \note This function does not write to the FLAC file, it only
  83197. * modifies the chain.
  83198. *
  83199. * \warning Any iterator on the current chain will become invalid after this
  83200. * call. You should delete the iterator and get a new one.
  83201. *
  83202. * \param chain A pointer to an existing chain.
  83203. * \assert
  83204. * \code chain != NULL \endcode
  83205. */
  83206. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  83207. /*********** FLAC__Metadata_Iterator ***********/
  83208. /** Create a new iterator instance.
  83209. *
  83210. * \retval FLAC__Metadata_Iterator*
  83211. * \c NULL if there was an error allocating memory, else the new instance.
  83212. */
  83213. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  83214. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  83215. *
  83216. * \param iterator A pointer to an existing iterator.
  83217. * \assert
  83218. * \code iterator != NULL \endcode
  83219. */
  83220. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  83221. /** Initialize the iterator to point to the first metadata block in the
  83222. * given chain.
  83223. *
  83224. * \param iterator A pointer to an existing iterator.
  83225. * \param chain A pointer to an existing and initialized (read) chain.
  83226. * \assert
  83227. * \code iterator != NULL \endcode
  83228. * \code chain != NULL \endcode
  83229. */
  83230. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  83231. /** Moves the iterator forward one metadata block, returning \c false if
  83232. * already at the end.
  83233. *
  83234. * \param iterator A pointer to an existing initialized iterator.
  83235. * \assert
  83236. * \code iterator != NULL \endcode
  83237. * \a iterator has been successfully initialized with
  83238. * FLAC__metadata_iterator_init()
  83239. * \retval FLAC__bool
  83240. * \c false if already at the last metadata block of the chain, else
  83241. * \c true.
  83242. */
  83243. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  83244. /** Moves the iterator backward one metadata block, returning \c false if
  83245. * already at the beginning.
  83246. *
  83247. * \param iterator A pointer to an existing initialized iterator.
  83248. * \assert
  83249. * \code iterator != NULL \endcode
  83250. * \a iterator has been successfully initialized with
  83251. * FLAC__metadata_iterator_init()
  83252. * \retval FLAC__bool
  83253. * \c false if already at the first metadata block of the chain, else
  83254. * \c true.
  83255. */
  83256. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  83257. /** Get the type of the metadata block at the current position.
  83258. *
  83259. * \param iterator A pointer to an existing initialized iterator.
  83260. * \assert
  83261. * \code iterator != NULL \endcode
  83262. * \a iterator has been successfully initialized with
  83263. * FLAC__metadata_iterator_init()
  83264. * \retval FLAC__MetadataType
  83265. * The type of the metadata block at the current iterator position.
  83266. */
  83267. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  83268. /** Get the metadata block at the current position. You can modify
  83269. * the block in place but must write the chain before the changes
  83270. * are reflected to the FLAC file. You do not need to call
  83271. * FLAC__metadata_iterator_set_block() to reflect the changes;
  83272. * the pointer returned by FLAC__metadata_iterator_get_block()
  83273. * points directly into the chain.
  83274. *
  83275. * \warning
  83276. * Do not call FLAC__metadata_object_delete() on the returned object;
  83277. * to delete a block use FLAC__metadata_iterator_delete_block().
  83278. *
  83279. * \param iterator A pointer to an existing initialized iterator.
  83280. * \assert
  83281. * \code iterator != NULL \endcode
  83282. * \a iterator has been successfully initialized with
  83283. * FLAC__metadata_iterator_init()
  83284. * \retval FLAC__StreamMetadata*
  83285. * The current metadata block.
  83286. */
  83287. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  83288. /** Set the metadata block at the current position, replacing the existing
  83289. * block. The new block passed in becomes owned by the chain and it will be
  83290. * deleted when the chain is deleted.
  83291. *
  83292. * \param iterator A pointer to an existing initialized iterator.
  83293. * \param block A pointer to a metadata block.
  83294. * \assert
  83295. * \code iterator != NULL \endcode
  83296. * \a iterator has been successfully initialized with
  83297. * FLAC__metadata_iterator_init()
  83298. * \code block != NULL \endcode
  83299. * \retval FLAC__bool
  83300. * \c false if the conditions in the above description are not met, or
  83301. * a memory allocation error occurs, otherwise \c true.
  83302. */
  83303. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  83304. /** Removes the current block from the chain. If \a replace_with_padding is
  83305. * \c true, the block will instead be replaced with a padding block of equal
  83306. * size. You can not delete the STREAMINFO block. The iterator will be
  83307. * left pointing to the block before the one just "deleted", even if
  83308. * \a replace_with_padding is \c true.
  83309. *
  83310. * \param iterator A pointer to an existing initialized iterator.
  83311. * \param replace_with_padding See above.
  83312. * \assert
  83313. * \code iterator != NULL \endcode
  83314. * \a iterator has been successfully initialized with
  83315. * FLAC__metadata_iterator_init()
  83316. * \retval FLAC__bool
  83317. * \c false if the conditions in the above description are not met,
  83318. * otherwise \c true.
  83319. */
  83320. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  83321. /** Insert a new block before the current block. You cannot insert a block
  83322. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  83323. * as there can be only one, the one that already exists at the head when you
  83324. * read in a chain. The chain takes ownership of the new block and it will be
  83325. * deleted when the chain is deleted. The iterator will be left pointing to
  83326. * the new block.
  83327. *
  83328. * \param iterator A pointer to an existing initialized iterator.
  83329. * \param block A pointer to a metadata block to insert.
  83330. * \assert
  83331. * \code iterator != NULL \endcode
  83332. * \a iterator has been successfully initialized with
  83333. * FLAC__metadata_iterator_init()
  83334. * \retval FLAC__bool
  83335. * \c false if the conditions in the above description are not met, or
  83336. * a memory allocation error occurs, otherwise \c true.
  83337. */
  83338. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  83339. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  83340. * block as there can be only one, the one that already exists at the head when
  83341. * you read in a chain. The chain takes ownership of the new block and it will
  83342. * be deleted when the chain is deleted. The iterator will be left pointing to
  83343. * the new block.
  83344. *
  83345. * \param iterator A pointer to an existing initialized iterator.
  83346. * \param block A pointer to a metadata block to insert.
  83347. * \assert
  83348. * \code iterator != NULL \endcode
  83349. * \a iterator has been successfully initialized with
  83350. * FLAC__metadata_iterator_init()
  83351. * \retval FLAC__bool
  83352. * \c false if the conditions in the above description are not met, or
  83353. * a memory allocation error occurs, otherwise \c true.
  83354. */
  83355. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  83356. /* \} */
  83357. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  83358. * \ingroup flac_metadata
  83359. *
  83360. * \brief
  83361. * This module contains methods for manipulating FLAC metadata objects.
  83362. *
  83363. * Since many are variable length we have to be careful about the memory
  83364. * management. We decree that all pointers to data in the object are
  83365. * owned by the object and memory-managed by the object.
  83366. *
  83367. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  83368. * functions to create all instances. When using the
  83369. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  83370. * \a copy to \c true to have the function make it's own copy of the data, or
  83371. * to \c false to give the object ownership of your data. In the latter case
  83372. * your pointer must be freeable by free() and will be free()d when the object
  83373. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  83374. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  83375. * the length argument is 0 and the \a copy argument is \c false.
  83376. *
  83377. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  83378. * will return \c NULL in the case of a memory allocation error, otherwise a new
  83379. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  83380. * case of a memory allocation error.
  83381. *
  83382. * We don't have the convenience of C++ here, so note that the library relies
  83383. * on you to keep the types straight. In other words, if you pass, for
  83384. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  83385. * FLAC__metadata_object_application_set_data(), you will get an assertion
  83386. * failure.
  83387. *
  83388. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  83389. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  83390. * toward the length or stored in the stream, but it can make working with plain
  83391. * comments (those that don't contain embedded-NULs in the value) easier.
  83392. * Entries passed into these functions have trailing NULs added if missing, and
  83393. * returned entries are guaranteed to have a trailing NUL.
  83394. *
  83395. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  83396. * comment entry/name/value will first validate that it complies with the Vorbis
  83397. * comment specification and return false if it does not.
  83398. *
  83399. * There is no need to recalculate the length field on metadata blocks you
  83400. * have modified. They will be calculated automatically before they are
  83401. * written back to a file.
  83402. *
  83403. * \{
  83404. */
  83405. /** Create a new metadata object instance of the given type.
  83406. *
  83407. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  83408. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  83409. * the vendor string set (but zero comments).
  83410. *
  83411. * Do not pass in a value greater than or equal to
  83412. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  83413. * doing.
  83414. *
  83415. * \param type Type of object to create
  83416. * \retval FLAC__StreamMetadata*
  83417. * \c NULL if there was an error allocating memory or the type code is
  83418. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  83419. */
  83420. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  83421. /** Create a copy of an existing metadata object.
  83422. *
  83423. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  83424. * object is also copied. The caller takes ownership of the new block and
  83425. * is responsible for freeing it with FLAC__metadata_object_delete().
  83426. *
  83427. * \param object Pointer to object to copy.
  83428. * \assert
  83429. * \code object != NULL \endcode
  83430. * \retval FLAC__StreamMetadata*
  83431. * \c NULL if there was an error allocating memory, else the new instance.
  83432. */
  83433. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  83434. /** Free a metadata object. Deletes the object pointed to by \a object.
  83435. *
  83436. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  83437. * object is also deleted.
  83438. *
  83439. * \param object A pointer to an existing object.
  83440. * \assert
  83441. * \code object != NULL \endcode
  83442. */
  83443. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  83444. /** Compares two metadata objects.
  83445. *
  83446. * The compare is "deep", i.e. dynamically allocated data within the
  83447. * object is also compared.
  83448. *
  83449. * \param block1 A pointer to an existing object.
  83450. * \param block2 A pointer to an existing object.
  83451. * \assert
  83452. * \code block1 != NULL \endcode
  83453. * \code block2 != NULL \endcode
  83454. * \retval FLAC__bool
  83455. * \c true if objects are identical, else \c false.
  83456. */
  83457. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  83458. /** Sets the application data of an APPLICATION block.
  83459. *
  83460. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  83461. * takes ownership of the pointer. The existing data will be freed if this
  83462. * function is successful, otherwise the original data will remain if \a copy
  83463. * is \c true and malloc() fails.
  83464. *
  83465. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  83466. *
  83467. * \param object A pointer to an existing APPLICATION object.
  83468. * \param data A pointer to the data to set.
  83469. * \param length The length of \a data in bytes.
  83470. * \param copy See above.
  83471. * \assert
  83472. * \code object != NULL \endcode
  83473. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  83474. * \code (data != NULL && length > 0) ||
  83475. * (data == NULL && length == 0 && copy == false) \endcode
  83476. * \retval FLAC__bool
  83477. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83478. */
  83479. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  83480. /** Resize the seekpoint array.
  83481. *
  83482. * If the size shrinks, elements will truncated; if it grows, new placeholder
  83483. * points will be added to the end.
  83484. *
  83485. * \param object A pointer to an existing SEEKTABLE object.
  83486. * \param new_num_points The desired length of the array; may be \c 0.
  83487. * \assert
  83488. * \code object != NULL \endcode
  83489. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83490. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  83491. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  83492. * \retval FLAC__bool
  83493. * \c false if memory allocation error, else \c true.
  83494. */
  83495. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  83496. /** Set a seekpoint in a seektable.
  83497. *
  83498. * \param object A pointer to an existing SEEKTABLE object.
  83499. * \param point_num Index into seekpoint array to set.
  83500. * \param point The point to set.
  83501. * \assert
  83502. * \code object != NULL \endcode
  83503. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83504. * \code object->data.seek_table.num_points > point_num \endcode
  83505. */
  83506. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  83507. /** Insert a seekpoint into a seektable.
  83508. *
  83509. * \param object A pointer to an existing SEEKTABLE object.
  83510. * \param point_num Index into seekpoint array to set.
  83511. * \param point The point to set.
  83512. * \assert
  83513. * \code object != NULL \endcode
  83514. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83515. * \code object->data.seek_table.num_points >= point_num \endcode
  83516. * \retval FLAC__bool
  83517. * \c false if memory allocation error, else \c true.
  83518. */
  83519. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  83520. /** Delete a seekpoint from a seektable.
  83521. *
  83522. * \param object A pointer to an existing SEEKTABLE object.
  83523. * \param point_num Index into seekpoint array to set.
  83524. * \assert
  83525. * \code object != NULL \endcode
  83526. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83527. * \code object->data.seek_table.num_points > point_num \endcode
  83528. * \retval FLAC__bool
  83529. * \c false if memory allocation error, else \c true.
  83530. */
  83531. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  83532. /** Check a seektable to see if it conforms to the FLAC specification.
  83533. * See the format specification for limits on the contents of the
  83534. * seektable.
  83535. *
  83536. * \param object A pointer to an existing SEEKTABLE object.
  83537. * \assert
  83538. * \code object != NULL \endcode
  83539. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83540. * \retval FLAC__bool
  83541. * \c false if seek table is illegal, else \c true.
  83542. */
  83543. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  83544. /** Append a number of placeholder points to the end of a seek table.
  83545. *
  83546. * \note
  83547. * As with the other ..._seektable_template_... functions, you should
  83548. * call FLAC__metadata_object_seektable_template_sort() when finished
  83549. * to make the seek table legal.
  83550. *
  83551. * \param object A pointer to an existing SEEKTABLE object.
  83552. * \param num The number of placeholder points to append.
  83553. * \assert
  83554. * \code object != NULL \endcode
  83555. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83556. * \retval FLAC__bool
  83557. * \c false if memory allocation fails, else \c true.
  83558. */
  83559. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  83560. /** Append a specific seek point template to the end of a seek table.
  83561. *
  83562. * \note
  83563. * As with the other ..._seektable_template_... functions, you should
  83564. * call FLAC__metadata_object_seektable_template_sort() when finished
  83565. * to make the seek table legal.
  83566. *
  83567. * \param object A pointer to an existing SEEKTABLE object.
  83568. * \param sample_number The sample number of the seek point template.
  83569. * \assert
  83570. * \code object != NULL \endcode
  83571. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83572. * \retval FLAC__bool
  83573. * \c false if memory allocation fails, else \c true.
  83574. */
  83575. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  83576. /** Append specific seek point templates to the end of a seek table.
  83577. *
  83578. * \note
  83579. * As with the other ..._seektable_template_... functions, you should
  83580. * call FLAC__metadata_object_seektable_template_sort() when finished
  83581. * to make the seek table legal.
  83582. *
  83583. * \param object A pointer to an existing SEEKTABLE object.
  83584. * \param sample_numbers An array of sample numbers for the seek points.
  83585. * \param num The number of seek point templates to append.
  83586. * \assert
  83587. * \code object != NULL \endcode
  83588. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83589. * \retval FLAC__bool
  83590. * \c false if memory allocation fails, else \c true.
  83591. */
  83592. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  83593. /** Append a set of evenly-spaced seek point templates to the end of a
  83594. * seek table.
  83595. *
  83596. * \note
  83597. * As with the other ..._seektable_template_... functions, you should
  83598. * call FLAC__metadata_object_seektable_template_sort() when finished
  83599. * to make the seek table legal.
  83600. *
  83601. * \param object A pointer to an existing SEEKTABLE object.
  83602. * \param num The number of placeholder points to append.
  83603. * \param total_samples The total number of samples to be encoded;
  83604. * the seekpoints will be spaced approximately
  83605. * \a total_samples / \a num samples apart.
  83606. * \assert
  83607. * \code object != NULL \endcode
  83608. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83609. * \code total_samples > 0 \endcode
  83610. * \retval FLAC__bool
  83611. * \c false if memory allocation fails, else \c true.
  83612. */
  83613. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  83614. /** Append a set of evenly-spaced seek point templates to the end of a
  83615. * seek table.
  83616. *
  83617. * \note
  83618. * As with the other ..._seektable_template_... functions, you should
  83619. * call FLAC__metadata_object_seektable_template_sort() when finished
  83620. * to make the seek table legal.
  83621. *
  83622. * \param object A pointer to an existing SEEKTABLE object.
  83623. * \param samples The number of samples apart to space the placeholder
  83624. * points. The first point will be at sample \c 0, the
  83625. * second at sample \a samples, then 2*\a samples, and
  83626. * so on. As long as \a samples and \a total_samples
  83627. * are greater than \c 0, there will always be at least
  83628. * one seekpoint at sample \c 0.
  83629. * \param total_samples The total number of samples to be encoded;
  83630. * the seekpoints will be spaced
  83631. * \a samples samples apart.
  83632. * \assert
  83633. * \code object != NULL \endcode
  83634. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83635. * \code samples > 0 \endcode
  83636. * \code total_samples > 0 \endcode
  83637. * \retval FLAC__bool
  83638. * \c false if memory allocation fails, else \c true.
  83639. */
  83640. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  83641. /** Sort a seek table's seek points according to the format specification,
  83642. * removing duplicates.
  83643. *
  83644. * \param object A pointer to a seek table to be sorted.
  83645. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  83646. * If \c true, duplicates are deleted and the seek table is
  83647. * shrunk appropriately; the number of placeholder points
  83648. * present in the seek table will be the same after the call
  83649. * as before.
  83650. * \assert
  83651. * \code object != NULL \endcode
  83652. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83653. * \retval FLAC__bool
  83654. * \c false if realloc() fails, else \c true.
  83655. */
  83656. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  83657. /** Sets the vendor string in a VORBIS_COMMENT block.
  83658. *
  83659. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83660. * one already.
  83661. *
  83662. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83663. * takes ownership of the \c entry.entry pointer.
  83664. *
  83665. * \note If this function returns \c false, the caller still owns the
  83666. * pointer.
  83667. *
  83668. * \param object A pointer to an existing VORBIS_COMMENT object.
  83669. * \param entry The entry to set the vendor string to.
  83670. * \param copy See above.
  83671. * \assert
  83672. * \code object != NULL \endcode
  83673. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83674. * \code (entry.entry != NULL && entry.length > 0) ||
  83675. * (entry.entry == NULL && entry.length == 0) \endcode
  83676. * \retval FLAC__bool
  83677. * \c false if memory allocation fails or \a entry does not comply with the
  83678. * Vorbis comment specification, else \c true.
  83679. */
  83680. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  83681. /** Resize the comment array.
  83682. *
  83683. * If the size shrinks, elements will truncated; if it grows, new empty
  83684. * fields will be added to the end.
  83685. *
  83686. * \param object A pointer to an existing VORBIS_COMMENT object.
  83687. * \param new_num_comments The desired length of the array; may be \c 0.
  83688. * \assert
  83689. * \code object != NULL \endcode
  83690. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83691. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  83692. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  83693. * \retval FLAC__bool
  83694. * \c false if memory allocation fails, else \c true.
  83695. */
  83696. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  83697. /** Sets a comment in a VORBIS_COMMENT block.
  83698. *
  83699. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83700. * one already.
  83701. *
  83702. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83703. * takes ownership of the \c entry.entry pointer.
  83704. *
  83705. * \note If this function returns \c false, the caller still owns the
  83706. * pointer.
  83707. *
  83708. * \param object A pointer to an existing VORBIS_COMMENT object.
  83709. * \param comment_num Index into comment array to set.
  83710. * \param entry The entry to set the comment to.
  83711. * \param copy See above.
  83712. * \assert
  83713. * \code object != NULL \endcode
  83714. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83715. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  83716. * \code (entry.entry != NULL && entry.length > 0) ||
  83717. * (entry.entry == NULL && entry.length == 0) \endcode
  83718. * \retval FLAC__bool
  83719. * \c false if memory allocation fails or \a entry does not comply with the
  83720. * Vorbis comment specification, else \c true.
  83721. */
  83722. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  83723. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  83724. *
  83725. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83726. * one already.
  83727. *
  83728. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83729. * takes ownership of the \c entry.entry pointer.
  83730. *
  83731. * \note If this function returns \c false, the caller still owns the
  83732. * pointer.
  83733. *
  83734. * \param object A pointer to an existing VORBIS_COMMENT object.
  83735. * \param comment_num The index at which to insert the comment. The comments
  83736. * at and after \a comment_num move right one position.
  83737. * To append a comment to the end, set \a comment_num to
  83738. * \c object->data.vorbis_comment.num_comments .
  83739. * \param entry The comment to insert.
  83740. * \param copy See above.
  83741. * \assert
  83742. * \code object != NULL \endcode
  83743. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83744. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  83745. * \code (entry.entry != NULL && entry.length > 0) ||
  83746. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  83747. * \retval FLAC__bool
  83748. * \c false if memory allocation fails or \a entry does not comply with the
  83749. * Vorbis comment specification, else \c true.
  83750. */
  83751. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  83752. /** Appends a comment to a VORBIS_COMMENT block.
  83753. *
  83754. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83755. * one already.
  83756. *
  83757. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83758. * takes ownership of the \c entry.entry pointer.
  83759. *
  83760. * \note If this function returns \c false, the caller still owns the
  83761. * pointer.
  83762. *
  83763. * \param object A pointer to an existing VORBIS_COMMENT object.
  83764. * \param entry The comment to insert.
  83765. * \param copy See above.
  83766. * \assert
  83767. * \code object != NULL \endcode
  83768. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83769. * \code (entry.entry != NULL && entry.length > 0) ||
  83770. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  83771. * \retval FLAC__bool
  83772. * \c false if memory allocation fails or \a entry does not comply with the
  83773. * Vorbis comment specification, else \c true.
  83774. */
  83775. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  83776. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  83777. *
  83778. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83779. * one already.
  83780. *
  83781. * Depending on the the value of \a all, either all or just the first comment
  83782. * whose field name(s) match the given entry's name will be replaced by the
  83783. * given entry. If no comments match, \a entry will simply be appended.
  83784. *
  83785. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83786. * takes ownership of the \c entry.entry pointer.
  83787. *
  83788. * \note If this function returns \c false, the caller still owns the
  83789. * pointer.
  83790. *
  83791. * \param object A pointer to an existing VORBIS_COMMENT object.
  83792. * \param entry The comment to insert.
  83793. * \param all If \c true, all comments whose field name matches
  83794. * \a entry's field name will be removed, and \a entry will
  83795. * be inserted at the position of the first matching
  83796. * comment. If \c false, only the first comment whose
  83797. * field name matches \a entry's field name will be
  83798. * replaced with \a entry.
  83799. * \param copy See above.
  83800. * \assert
  83801. * \code object != NULL \endcode
  83802. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83803. * \code (entry.entry != NULL && entry.length > 0) ||
  83804. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  83805. * \retval FLAC__bool
  83806. * \c false if memory allocation fails or \a entry does not comply with the
  83807. * Vorbis comment specification, else \c true.
  83808. */
  83809. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  83810. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  83811. *
  83812. * \param object A pointer to an existing VORBIS_COMMENT object.
  83813. * \param comment_num The index of the comment to delete.
  83814. * \assert
  83815. * \code object != NULL \endcode
  83816. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83817. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  83818. * \retval FLAC__bool
  83819. * \c false if realloc() fails, else \c true.
  83820. */
  83821. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  83822. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  83823. *
  83824. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  83825. * memory and shall be owned by the caller. For convenience the entry will
  83826. * have a terminating NUL.
  83827. *
  83828. * \param entry A pointer to a Vorbis comment entry. The entry's
  83829. * \c entry pointer should not point to allocated
  83830. * memory as it will be overwritten.
  83831. * \param field_name The field name in ASCII, \c NUL terminated.
  83832. * \param field_value The field value in UTF-8, \c NUL terminated.
  83833. * \assert
  83834. * \code entry != NULL \endcode
  83835. * \code field_name != NULL \endcode
  83836. * \code field_value != NULL \endcode
  83837. * \retval FLAC__bool
  83838. * \c false if malloc() fails, or if \a field_name or \a field_value does
  83839. * not comply with the Vorbis comment specification, else \c true.
  83840. */
  83841. 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);
  83842. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  83843. *
  83844. * The returned pointers to name and value will be allocated by malloc()
  83845. * and shall be owned by the caller.
  83846. *
  83847. * \param entry An existing Vorbis comment entry.
  83848. * \param field_name The address of where the returned pointer to the
  83849. * field name will be stored.
  83850. * \param field_value The address of where the returned pointer to the
  83851. * field value will be stored.
  83852. * \assert
  83853. * \code (entry.entry != NULL && entry.length > 0) \endcode
  83854. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  83855. * \code field_name != NULL \endcode
  83856. * \code field_value != NULL \endcode
  83857. * \retval FLAC__bool
  83858. * \c false if memory allocation fails or \a entry does not comply with the
  83859. * Vorbis comment specification, else \c true.
  83860. */
  83861. 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);
  83862. /** Check if the given Vorbis comment entry's field name matches the given
  83863. * field name.
  83864. *
  83865. * \param entry An existing Vorbis comment entry.
  83866. * \param field_name The field name to check.
  83867. * \param field_name_length The length of \a field_name, not including the
  83868. * terminating \c NUL.
  83869. * \assert
  83870. * \code (entry.entry != NULL && entry.length > 0) \endcode
  83871. * \retval FLAC__bool
  83872. * \c true if the field names match, else \c false
  83873. */
  83874. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  83875. /** Find a Vorbis comment with the given field name.
  83876. *
  83877. * The search begins at entry number \a offset; use an offset of 0 to
  83878. * search from the beginning of the comment array.
  83879. *
  83880. * \param object A pointer to an existing VORBIS_COMMENT object.
  83881. * \param offset The offset into the comment array from where to start
  83882. * the search.
  83883. * \param field_name The field name of the comment to find.
  83884. * \assert
  83885. * \code object != NULL \endcode
  83886. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83887. * \code field_name != NULL \endcode
  83888. * \retval int
  83889. * The offset in the comment array of the first comment whose field
  83890. * name matches \a field_name, or \c -1 if no match was found.
  83891. */
  83892. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  83893. /** Remove first Vorbis comment matching the given field name.
  83894. *
  83895. * \param object A pointer to an existing VORBIS_COMMENT object.
  83896. * \param field_name The field name of comment to delete.
  83897. * \assert
  83898. * \code object != NULL \endcode
  83899. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83900. * \retval int
  83901. * \c -1 for memory allocation error, \c 0 for no matching entries,
  83902. * \c 1 for one matching entry deleted.
  83903. */
  83904. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  83905. /** Remove all Vorbis comments matching the given field name.
  83906. *
  83907. * \param object A pointer to an existing VORBIS_COMMENT object.
  83908. * \param field_name The field name of comments to delete.
  83909. * \assert
  83910. * \code object != NULL \endcode
  83911. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83912. * \retval int
  83913. * \c -1 for memory allocation error, \c 0 for no matching entries,
  83914. * else the number of matching entries deleted.
  83915. */
  83916. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  83917. /** Create a new CUESHEET track instance.
  83918. *
  83919. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  83920. *
  83921. * \retval FLAC__StreamMetadata_CueSheet_Track*
  83922. * \c NULL if there was an error allocating memory, else the new instance.
  83923. */
  83924. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  83925. /** Create a copy of an existing CUESHEET track object.
  83926. *
  83927. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  83928. * object is also copied. The caller takes ownership of the new object and
  83929. * is responsible for freeing it with
  83930. * FLAC__metadata_object_cuesheet_track_delete().
  83931. *
  83932. * \param object Pointer to object to copy.
  83933. * \assert
  83934. * \code object != NULL \endcode
  83935. * \retval FLAC__StreamMetadata_CueSheet_Track*
  83936. * \c NULL if there was an error allocating memory, else the new instance.
  83937. */
  83938. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  83939. /** Delete a CUESHEET track object
  83940. *
  83941. * \param object A pointer to an existing CUESHEET track object.
  83942. * \assert
  83943. * \code object != NULL \endcode
  83944. */
  83945. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  83946. /** Resize a track's index point array.
  83947. *
  83948. * If the size shrinks, elements will truncated; if it grows, new blank
  83949. * indices will be added to the end.
  83950. *
  83951. * \param object A pointer to an existing CUESHEET object.
  83952. * \param track_num The index of the track to modify. NOTE: this is not
  83953. * necessarily the same as the track's \a number field.
  83954. * \param new_num_indices The desired length of the array; may be \c 0.
  83955. * \assert
  83956. * \code object != NULL \endcode
  83957. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83958. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83959. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  83960. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  83961. * \retval FLAC__bool
  83962. * \c false if memory allocation error, else \c true.
  83963. */
  83964. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  83965. /** Insert an index point in a CUESHEET track at the given index.
  83966. *
  83967. * \param object A pointer to an existing CUESHEET object.
  83968. * \param track_num The index of the track to modify. NOTE: this is not
  83969. * necessarily the same as the track's \a number field.
  83970. * \param index_num The index into the track's index array at which to
  83971. * insert the index point. NOTE: this is not necessarily
  83972. * the same as the index point's \a number field. The
  83973. * indices at and after \a index_num move right one
  83974. * position. To append an index point to the end, set
  83975. * \a index_num to
  83976. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  83977. * \param index The index point to insert.
  83978. * \assert
  83979. * \code object != NULL \endcode
  83980. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83981. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83982. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  83983. * \retval FLAC__bool
  83984. * \c false if realloc() fails, else \c true.
  83985. */
  83986. 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);
  83987. /** Insert a blank index point in a CUESHEET track at the given index.
  83988. *
  83989. * A blank index point is one in which all field values are zero.
  83990. *
  83991. * \param object A pointer to an existing CUESHEET object.
  83992. * \param track_num The index of the track to modify. NOTE: this is not
  83993. * necessarily the same as the track's \a number field.
  83994. * \param index_num The index into the track's index array at which to
  83995. * insert the index point. NOTE: this is not necessarily
  83996. * the same as the index point's \a number field. The
  83997. * indices at and after \a index_num move right one
  83998. * position. To append an index point to the end, set
  83999. * \a index_num to
  84000. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  84001. * \assert
  84002. * \code object != NULL \endcode
  84003. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84004. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84005. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  84006. * \retval FLAC__bool
  84007. * \c false if realloc() fails, else \c true.
  84008. */
  84009. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  84010. /** Delete an index point in a CUESHEET track at the given index.
  84011. *
  84012. * \param object A pointer to an existing CUESHEET object.
  84013. * \param track_num The index into the track array of the track to
  84014. * modify. NOTE: this is not necessarily the same
  84015. * as the track's \a number field.
  84016. * \param index_num The index into the track's index array of the index
  84017. * to delete. NOTE: this is not necessarily the same
  84018. * as the index's \a number field.
  84019. * \assert
  84020. * \code object != NULL \endcode
  84021. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84022. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84023. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  84024. * \retval FLAC__bool
  84025. * \c false if realloc() fails, else \c true.
  84026. */
  84027. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  84028. /** Resize the track array.
  84029. *
  84030. * If the size shrinks, elements will truncated; if it grows, new blank
  84031. * tracks will be added to the end.
  84032. *
  84033. * \param object A pointer to an existing CUESHEET object.
  84034. * \param new_num_tracks The desired length of the array; may be \c 0.
  84035. * \assert
  84036. * \code object != NULL \endcode
  84037. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84038. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  84039. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  84040. * \retval FLAC__bool
  84041. * \c false if memory allocation error, else \c true.
  84042. */
  84043. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  84044. /** Sets a track in a CUESHEET block.
  84045. *
  84046. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  84047. * takes ownership of the \a track pointer.
  84048. *
  84049. * \param object A pointer to an existing CUESHEET object.
  84050. * \param track_num Index into track array to set. NOTE: this is not
  84051. * necessarily the same as the track's \a number field.
  84052. * \param track The track to set the track to. You may safely pass in
  84053. * a const pointer if \a copy is \c true.
  84054. * \param copy See above.
  84055. * \assert
  84056. * \code object != NULL \endcode
  84057. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84058. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  84059. * \code (track->indices != NULL && track->num_indices > 0) ||
  84060. * (track->indices == NULL && track->num_indices == 0)
  84061. * \retval FLAC__bool
  84062. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84063. */
  84064. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  84065. /** Insert a track in a CUESHEET block at the given index.
  84066. *
  84067. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  84068. * takes ownership of the \a track pointer.
  84069. *
  84070. * \param object A pointer to an existing CUESHEET object.
  84071. * \param track_num The index at which to insert the track. NOTE: this
  84072. * is not necessarily the same as the track's \a number
  84073. * field. The tracks at and after \a track_num move right
  84074. * one position. To append a track to the end, set
  84075. * \a track_num to \c object->data.cue_sheet.num_tracks .
  84076. * \param track The track to insert. You may safely pass in a const
  84077. * pointer if \a copy is \c true.
  84078. * \param copy See above.
  84079. * \assert
  84080. * \code object != NULL \endcode
  84081. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84082. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  84083. * \retval FLAC__bool
  84084. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84085. */
  84086. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  84087. /** Insert a blank track in a CUESHEET block at the given index.
  84088. *
  84089. * A blank track is one in which all field values are zero.
  84090. *
  84091. * \param object A pointer to an existing CUESHEET object.
  84092. * \param track_num The index at which to insert the track. NOTE: this
  84093. * is not necessarily the same as the track's \a number
  84094. * field. The tracks at and after \a track_num move right
  84095. * one position. To append a track to the end, set
  84096. * \a track_num to \c object->data.cue_sheet.num_tracks .
  84097. * \assert
  84098. * \code object != NULL \endcode
  84099. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84100. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  84101. * \retval FLAC__bool
  84102. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84103. */
  84104. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  84105. /** Delete a track in a CUESHEET block at the given index.
  84106. *
  84107. * \param object A pointer to an existing CUESHEET object.
  84108. * \param track_num The index into the track array of the track to
  84109. * delete. NOTE: this is not necessarily the same
  84110. * as the track's \a number field.
  84111. * \assert
  84112. * \code object != NULL \endcode
  84113. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84114. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84115. * \retval FLAC__bool
  84116. * \c false if realloc() fails, else \c true.
  84117. */
  84118. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  84119. /** Check a cue sheet to see if it conforms to the FLAC specification.
  84120. * See the format specification for limits on the contents of the
  84121. * cue sheet.
  84122. *
  84123. * \param object A pointer to an existing CUESHEET object.
  84124. * \param check_cd_da_subset If \c true, check CUESHEET against more
  84125. * stringent requirements for a CD-DA (audio) disc.
  84126. * \param violation Address of a pointer to a string. If there is a
  84127. * violation, a pointer to a string explanation of the
  84128. * violation will be returned here. \a violation may be
  84129. * \c NULL if you don't need the returned string. Do not
  84130. * free the returned string; it will always point to static
  84131. * data.
  84132. * \assert
  84133. * \code object != NULL \endcode
  84134. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84135. * \retval FLAC__bool
  84136. * \c false if cue sheet is illegal, else \c true.
  84137. */
  84138. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  84139. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  84140. * assumes the cue sheet corresponds to a CD; the result is undefined
  84141. * if the cuesheet's is_cd bit is not set.
  84142. *
  84143. * \param object A pointer to an existing CUESHEET object.
  84144. * \assert
  84145. * \code object != NULL \endcode
  84146. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84147. * \retval FLAC__uint32
  84148. * The unsigned integer representation of the CDDB/freedb ID
  84149. */
  84150. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  84151. /** Sets the MIME type of a PICTURE block.
  84152. *
  84153. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  84154. * takes ownership of the pointer. The existing string will be freed if this
  84155. * function is successful, otherwise the original string will remain if \a copy
  84156. * is \c true and malloc() fails.
  84157. *
  84158. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  84159. *
  84160. * \param object A pointer to an existing PICTURE object.
  84161. * \param mime_type A pointer to the MIME type string. The string must be
  84162. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  84163. * is done.
  84164. * \param copy See above.
  84165. * \assert
  84166. * \code object != NULL \endcode
  84167. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84168. * \code (mime_type != NULL) \endcode
  84169. * \retval FLAC__bool
  84170. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84171. */
  84172. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  84173. /** Sets the description of a PICTURE block.
  84174. *
  84175. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  84176. * takes ownership of the pointer. The existing string will be freed if this
  84177. * function is successful, otherwise the original string will remain if \a copy
  84178. * is \c true and malloc() fails.
  84179. *
  84180. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  84181. *
  84182. * \param object A pointer to an existing PICTURE object.
  84183. * \param description A pointer to the description string. The string must be
  84184. * valid UTF-8, NUL-terminated. No validation is done.
  84185. * \param copy See above.
  84186. * \assert
  84187. * \code object != NULL \endcode
  84188. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84189. * \code (description != NULL) \endcode
  84190. * \retval FLAC__bool
  84191. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84192. */
  84193. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  84194. /** Sets the picture data of a PICTURE block.
  84195. *
  84196. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  84197. * takes ownership of the pointer. Also sets the \a data_length field of the
  84198. * metadata object to what is passed in as the \a length parameter. The
  84199. * existing data will be freed if this function is successful, otherwise the
  84200. * original data and data_length will remain if \a copy is \c true and
  84201. * malloc() fails.
  84202. *
  84203. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  84204. *
  84205. * \param object A pointer to an existing PICTURE object.
  84206. * \param data A pointer to the data to set.
  84207. * \param length The length of \a data in bytes.
  84208. * \param copy See above.
  84209. * \assert
  84210. * \code object != NULL \endcode
  84211. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84212. * \code (data != NULL && length > 0) ||
  84213. * (data == NULL && length == 0 && copy == false) \endcode
  84214. * \retval FLAC__bool
  84215. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84216. */
  84217. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  84218. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  84219. * See the format specification for limits on the contents of the
  84220. * PICTURE block.
  84221. *
  84222. * \param object A pointer to existing PICTURE block to be checked.
  84223. * \param violation Address of a pointer to a string. If there is a
  84224. * violation, a pointer to a string explanation of the
  84225. * violation will be returned here. \a violation may be
  84226. * \c NULL if you don't need the returned string. Do not
  84227. * free the returned string; it will always point to static
  84228. * data.
  84229. * \assert
  84230. * \code object != NULL \endcode
  84231. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84232. * \retval FLAC__bool
  84233. * \c false if PICTURE block is illegal, else \c true.
  84234. */
  84235. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  84236. /* \} */
  84237. #ifdef __cplusplus
  84238. }
  84239. #endif
  84240. #endif
  84241. /********* End of inlined file: metadata.h *********/
  84242. /********* Start of inlined file: stream_decoder.h *********/
  84243. #ifndef FLAC__STREAM_DECODER_H
  84244. #define FLAC__STREAM_DECODER_H
  84245. #include <stdio.h> /* for FILE */
  84246. #ifdef __cplusplus
  84247. extern "C" {
  84248. #endif
  84249. /** \file include/FLAC/stream_decoder.h
  84250. *
  84251. * \brief
  84252. * This module contains the functions which implement the stream
  84253. * decoder.
  84254. *
  84255. * See the detailed documentation in the
  84256. * \link flac_stream_decoder stream decoder \endlink module.
  84257. */
  84258. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  84259. * \ingroup flac
  84260. *
  84261. * \brief
  84262. * This module describes the decoder layers provided by libFLAC.
  84263. *
  84264. * The stream decoder can be used to decode complete streams either from
  84265. * the client via callbacks, or directly from a file, depending on how
  84266. * it is initialized. When decoding via callbacks, the client provides
  84267. * callbacks for reading FLAC data and writing decoded samples, and
  84268. * handling metadata and errors. If the client also supplies seek-related
  84269. * callback, the decoder function for sample-accurate seeking within the
  84270. * FLAC input is also available. When decoding from a file, the client
  84271. * needs only supply a filename or open \c FILE* and write/metadata/error
  84272. * callbacks; the rest of the callbacks are supplied internally. For more
  84273. * info see the \link flac_stream_decoder stream decoder \endlink module.
  84274. */
  84275. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  84276. * \ingroup flac_decoder
  84277. *
  84278. * \brief
  84279. * This module contains the functions which implement the stream
  84280. * decoder.
  84281. *
  84282. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  84283. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  84284. *
  84285. * The basic usage of this decoder is as follows:
  84286. * - The program creates an instance of a decoder using
  84287. * FLAC__stream_decoder_new().
  84288. * - The program overrides the default settings using
  84289. * FLAC__stream_decoder_set_*() functions.
  84290. * - The program initializes the instance to validate the settings and
  84291. * prepare for decoding using
  84292. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  84293. * or FLAC__stream_decoder_init_file() for native FLAC,
  84294. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  84295. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  84296. * - The program calls the FLAC__stream_decoder_process_*() functions
  84297. * to decode data, which subsequently calls the callbacks.
  84298. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  84299. * which flushes the input and output and resets the decoder to the
  84300. * uninitialized state.
  84301. * - The instance may be used again or deleted with
  84302. * FLAC__stream_decoder_delete().
  84303. *
  84304. * In more detail, the program will create a new instance by calling
  84305. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  84306. * functions to override the default decoder options, and call
  84307. * one of the FLAC__stream_decoder_init_*() functions.
  84308. *
  84309. * There are three initialization functions for native FLAC, one for
  84310. * setting up the decoder to decode FLAC data from the client via
  84311. * callbacks, and two for decoding directly from a FLAC file.
  84312. *
  84313. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  84314. * You must also supply several callbacks for handling I/O. Some (like
  84315. * seeking) are optional, depending on the capabilities of the input.
  84316. *
  84317. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  84318. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  84319. * \c FILE* or filename and fewer callbacks; the decoder will handle
  84320. * the other callbacks internally.
  84321. *
  84322. * There are three similarly-named init functions for decoding from Ogg
  84323. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  84324. * library has been built with Ogg support.
  84325. *
  84326. * Once the decoder is initialized, your program will call one of several
  84327. * functions to start the decoding process:
  84328. *
  84329. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  84330. * most one metadata block or audio frame and return, calling either the
  84331. * metadata callback or write callback, respectively, once. If the decoder
  84332. * loses sync it will return with only the error callback being called.
  84333. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  84334. * to process the stream from the current location and stop upon reaching
  84335. * the first audio frame. The client will get one metadata, write, or error
  84336. * callback per metadata block, audio frame, or sync error, respectively.
  84337. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  84338. * to process the stream from the current location until the read callback
  84339. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  84340. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  84341. * write, or error callback per metadata block, audio frame, or sync error,
  84342. * respectively.
  84343. *
  84344. * When the decoder has finished decoding (normally or through an abort),
  84345. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  84346. * ensures the decoder is in the correct state and frees memory. Then the
  84347. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  84348. * again to decode another stream.
  84349. *
  84350. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  84351. * At any point after the stream decoder has been initialized, the client can
  84352. * call this function to seek to an exact sample within the stream.
  84353. * Subsequently, the first time the write callback is called it will be
  84354. * passed a (possibly partial) block starting at that sample.
  84355. *
  84356. * If the client cannot seek via the callback interface provided, but still
  84357. * has another way of seeking, it can flush the decoder using
  84358. * FLAC__stream_decoder_flush() and start feeding data from the new position
  84359. * through the read callback.
  84360. *
  84361. * The stream decoder also provides MD5 signature checking. If this is
  84362. * turned on before initialization, FLAC__stream_decoder_finish() will
  84363. * report when the decoded MD5 signature does not match the one stored
  84364. * in the STREAMINFO block. MD5 checking is automatically turned off
  84365. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  84366. * in the STREAMINFO block or when a seek is attempted.
  84367. *
  84368. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  84369. * attention. By default, the decoder only calls the metadata_callback for
  84370. * the STREAMINFO block. These functions allow you to tell the decoder
  84371. * explicitly which blocks to parse and return via the metadata_callback
  84372. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  84373. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  84374. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  84375. * which blocks to return. Remember that metadata blocks can potentially
  84376. * be big (for example, cover art) so filtering out the ones you don't
  84377. * use can reduce the memory requirements of the decoder. Also note the
  84378. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  84379. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  84380. * filtering APPLICATION blocks based on the application ID.
  84381. *
  84382. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  84383. * they still can legally be filtered from the metadata_callback.
  84384. *
  84385. * \note
  84386. * The "set" functions may only be called when the decoder is in the
  84387. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  84388. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  84389. * before FLAC__stream_decoder_init_*(). If this is the case they will
  84390. * return \c true, otherwise \c false.
  84391. *
  84392. * \note
  84393. * FLAC__stream_decoder_finish() resets all settings to the constructor
  84394. * defaults, including the callbacks.
  84395. *
  84396. * \{
  84397. */
  84398. /** State values for a FLAC__StreamDecoder
  84399. *
  84400. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  84401. */
  84402. typedef enum {
  84403. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  84404. /**< The decoder is ready to search for metadata. */
  84405. FLAC__STREAM_DECODER_READ_METADATA,
  84406. /**< The decoder is ready to or is in the process of reading metadata. */
  84407. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  84408. /**< The decoder is ready to or is in the process of searching for the
  84409. * frame sync code.
  84410. */
  84411. FLAC__STREAM_DECODER_READ_FRAME,
  84412. /**< The decoder is ready to or is in the process of reading a frame. */
  84413. FLAC__STREAM_DECODER_END_OF_STREAM,
  84414. /**< The decoder has reached the end of the stream. */
  84415. FLAC__STREAM_DECODER_OGG_ERROR,
  84416. /**< An error occurred in the underlying Ogg layer. */
  84417. FLAC__STREAM_DECODER_SEEK_ERROR,
  84418. /**< An error occurred while seeking. The decoder must be flushed
  84419. * with FLAC__stream_decoder_flush() or reset with
  84420. * FLAC__stream_decoder_reset() before decoding can continue.
  84421. */
  84422. FLAC__STREAM_DECODER_ABORTED,
  84423. /**< The decoder was aborted by the read callback. */
  84424. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  84425. /**< An error occurred allocating memory. The decoder is in an invalid
  84426. * state and can no longer be used.
  84427. */
  84428. FLAC__STREAM_DECODER_UNINITIALIZED
  84429. /**< The decoder is in the uninitialized state; one of the
  84430. * FLAC__stream_decoder_init_*() functions must be called before samples
  84431. * can be processed.
  84432. */
  84433. } FLAC__StreamDecoderState;
  84434. /** Maps a FLAC__StreamDecoderState to a C string.
  84435. *
  84436. * Using a FLAC__StreamDecoderState as the index to this array
  84437. * will give the string equivalent. The contents should not be modified.
  84438. */
  84439. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  84440. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  84441. */
  84442. typedef enum {
  84443. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  84444. /**< Initialization was successful. */
  84445. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  84446. /**< The library was not compiled with support for the given container
  84447. * format.
  84448. */
  84449. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  84450. /**< A required callback was not supplied. */
  84451. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  84452. /**< An error occurred allocating memory. */
  84453. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  84454. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  84455. * FLAC__stream_decoder_init_ogg_file(). */
  84456. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  84457. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  84458. * already initialized, usually because
  84459. * FLAC__stream_decoder_finish() was not called.
  84460. */
  84461. } FLAC__StreamDecoderInitStatus;
  84462. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  84463. *
  84464. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  84465. * will give the string equivalent. The contents should not be modified.
  84466. */
  84467. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  84468. /** Return values for the FLAC__StreamDecoder read callback.
  84469. */
  84470. typedef enum {
  84471. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  84472. /**< The read was OK and decoding can continue. */
  84473. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  84474. /**< The read was attempted while at the end of the stream. Note that
  84475. * the client must only return this value when the read callback was
  84476. * called when already at the end of the stream. Otherwise, if the read
  84477. * itself moves to the end of the stream, the client should still return
  84478. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  84479. * the next read callback it should return
  84480. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  84481. * of \c 0.
  84482. */
  84483. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  84484. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84485. } FLAC__StreamDecoderReadStatus;
  84486. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  84487. *
  84488. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  84489. * will give the string equivalent. The contents should not be modified.
  84490. */
  84491. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  84492. /** Return values for the FLAC__StreamDecoder seek callback.
  84493. */
  84494. typedef enum {
  84495. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  84496. /**< The seek was OK and decoding can continue. */
  84497. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  84498. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84499. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  84500. /**< Client does not support seeking. */
  84501. } FLAC__StreamDecoderSeekStatus;
  84502. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  84503. *
  84504. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  84505. * will give the string equivalent. The contents should not be modified.
  84506. */
  84507. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  84508. /** Return values for the FLAC__StreamDecoder tell callback.
  84509. */
  84510. typedef enum {
  84511. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  84512. /**< The tell was OK and decoding can continue. */
  84513. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  84514. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84515. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  84516. /**< Client does not support telling the position. */
  84517. } FLAC__StreamDecoderTellStatus;
  84518. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  84519. *
  84520. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  84521. * will give the string equivalent. The contents should not be modified.
  84522. */
  84523. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  84524. /** Return values for the FLAC__StreamDecoder length callback.
  84525. */
  84526. typedef enum {
  84527. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  84528. /**< The length call was OK and decoding can continue. */
  84529. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  84530. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84531. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  84532. /**< Client does not support reporting the length. */
  84533. } FLAC__StreamDecoderLengthStatus;
  84534. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  84535. *
  84536. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  84537. * will give the string equivalent. The contents should not be modified.
  84538. */
  84539. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  84540. /** Return values for the FLAC__StreamDecoder write callback.
  84541. */
  84542. typedef enum {
  84543. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  84544. /**< The write was OK and decoding can continue. */
  84545. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  84546. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84547. } FLAC__StreamDecoderWriteStatus;
  84548. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  84549. *
  84550. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  84551. * will give the string equivalent. The contents should not be modified.
  84552. */
  84553. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  84554. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  84555. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  84556. * all. The rest could be caused by bad sync (false synchronization on
  84557. * data that is not the start of a frame) or corrupted data. The error
  84558. * itself is the decoder's best guess at what happened assuming a correct
  84559. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  84560. * could be caused by a correct sync on the start of a frame, but some
  84561. * data in the frame header was corrupted. Or it could be the result of
  84562. * syncing on a point the stream that looked like the starting of a frame
  84563. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  84564. * could be because the decoder encountered a valid frame made by a future
  84565. * version of the encoder which it cannot parse, or because of a false
  84566. * sync making it appear as though an encountered frame was generated by
  84567. * a future encoder.
  84568. */
  84569. typedef enum {
  84570. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  84571. /**< An error in the stream caused the decoder to lose synchronization. */
  84572. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  84573. /**< The decoder encountered a corrupted frame header. */
  84574. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  84575. /**< The frame's data did not match the CRC in the footer. */
  84576. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  84577. /**< The decoder encountered reserved fields in use in the stream. */
  84578. } FLAC__StreamDecoderErrorStatus;
  84579. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  84580. *
  84581. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  84582. * will give the string equivalent. The contents should not be modified.
  84583. */
  84584. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  84585. /***********************************************************************
  84586. *
  84587. * class FLAC__StreamDecoder
  84588. *
  84589. ***********************************************************************/
  84590. struct FLAC__StreamDecoderProtected;
  84591. struct FLAC__StreamDecoderPrivate;
  84592. /** The opaque structure definition for the stream decoder type.
  84593. * See the \link flac_stream_decoder stream decoder module \endlink
  84594. * for a detailed description.
  84595. */
  84596. typedef struct {
  84597. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  84598. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  84599. } FLAC__StreamDecoder;
  84600. /** Signature for the read callback.
  84601. *
  84602. * A function pointer matching this signature must be passed to
  84603. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84604. * called when the decoder needs more input data. The address of the
  84605. * buffer to be filled is supplied, along with the number of bytes the
  84606. * buffer can hold. The callback may choose to supply less data and
  84607. * modify the byte count but must be careful not to overflow the buffer.
  84608. * The callback then returns a status code chosen from
  84609. * FLAC__StreamDecoderReadStatus.
  84610. *
  84611. * Here is an example of a read callback for stdio streams:
  84612. * \code
  84613. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  84614. * {
  84615. * FILE *file = ((MyClientData*)client_data)->file;
  84616. * if(*bytes > 0) {
  84617. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  84618. * if(ferror(file))
  84619. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  84620. * else if(*bytes == 0)
  84621. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  84622. * else
  84623. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  84624. * }
  84625. * else
  84626. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  84627. * }
  84628. * \endcode
  84629. *
  84630. * \note In general, FLAC__StreamDecoder functions which change the
  84631. * state should not be called on the \a decoder while in the callback.
  84632. *
  84633. * \param decoder The decoder instance calling the callback.
  84634. * \param buffer A pointer to a location for the callee to store
  84635. * data to be decoded.
  84636. * \param bytes A pointer to the size of the buffer. On entry
  84637. * to the callback, it contains the maximum number
  84638. * of bytes that may be stored in \a buffer. The
  84639. * callee must set it to the actual number of bytes
  84640. * stored (0 in case of error or end-of-stream) before
  84641. * returning.
  84642. * \param client_data The callee's client data set through
  84643. * FLAC__stream_decoder_init_*().
  84644. * \retval FLAC__StreamDecoderReadStatus
  84645. * The callee's return status. Note that the callback should return
  84646. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  84647. * zero bytes were read and there is no more data to be read.
  84648. */
  84649. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  84650. /** Signature for the seek callback.
  84651. *
  84652. * A function pointer matching this signature may be passed to
  84653. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84654. * called when the decoder needs to seek the input stream. The decoder
  84655. * will pass the absolute byte offset to seek to, 0 meaning the
  84656. * beginning of the stream.
  84657. *
  84658. * Here is an example of a seek callback for stdio streams:
  84659. * \code
  84660. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  84661. * {
  84662. * FILE *file = ((MyClientData*)client_data)->file;
  84663. * if(file == stdin)
  84664. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  84665. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  84666. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  84667. * else
  84668. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  84669. * }
  84670. * \endcode
  84671. *
  84672. * \note In general, FLAC__StreamDecoder functions which change the
  84673. * state should not be called on the \a decoder while in the callback.
  84674. *
  84675. * \param decoder The decoder instance calling the callback.
  84676. * \param absolute_byte_offset The offset from the beginning of the stream
  84677. * to seek to.
  84678. * \param client_data The callee's client data set through
  84679. * FLAC__stream_decoder_init_*().
  84680. * \retval FLAC__StreamDecoderSeekStatus
  84681. * The callee's return status.
  84682. */
  84683. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  84684. /** Signature for the tell callback.
  84685. *
  84686. * A function pointer matching this signature may be passed to
  84687. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84688. * called when the decoder wants to know the current position of the
  84689. * stream. The callback should return the byte offset from the
  84690. * beginning of the stream.
  84691. *
  84692. * Here is an example of a tell callback for stdio streams:
  84693. * \code
  84694. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  84695. * {
  84696. * FILE *file = ((MyClientData*)client_data)->file;
  84697. * off_t pos;
  84698. * if(file == stdin)
  84699. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  84700. * else if((pos = ftello(file)) < 0)
  84701. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  84702. * else {
  84703. * *absolute_byte_offset = (FLAC__uint64)pos;
  84704. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  84705. * }
  84706. * }
  84707. * \endcode
  84708. *
  84709. * \note In general, FLAC__StreamDecoder functions which change the
  84710. * state should not be called on the \a decoder while in the callback.
  84711. *
  84712. * \param decoder The decoder instance calling the callback.
  84713. * \param absolute_byte_offset A pointer to storage for the current offset
  84714. * from the beginning of the stream.
  84715. * \param client_data The callee's client data set through
  84716. * FLAC__stream_decoder_init_*().
  84717. * \retval FLAC__StreamDecoderTellStatus
  84718. * The callee's return status.
  84719. */
  84720. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  84721. /** Signature for the length callback.
  84722. *
  84723. * A function pointer matching this signature may be passed to
  84724. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84725. * called when the decoder wants to know the total length of the stream
  84726. * in bytes.
  84727. *
  84728. * Here is an example of a length callback for stdio streams:
  84729. * \code
  84730. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  84731. * {
  84732. * FILE *file = ((MyClientData*)client_data)->file;
  84733. * struct stat filestats;
  84734. *
  84735. * if(file == stdin)
  84736. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  84737. * else if(fstat(fileno(file), &filestats) != 0)
  84738. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  84739. * else {
  84740. * *stream_length = (FLAC__uint64)filestats.st_size;
  84741. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  84742. * }
  84743. * }
  84744. * \endcode
  84745. *
  84746. * \note In general, FLAC__StreamDecoder functions which change the
  84747. * state should not be called on the \a decoder while in the callback.
  84748. *
  84749. * \param decoder The decoder instance calling the callback.
  84750. * \param stream_length A pointer to storage for the length of the stream
  84751. * in bytes.
  84752. * \param client_data The callee's client data set through
  84753. * FLAC__stream_decoder_init_*().
  84754. * \retval FLAC__StreamDecoderLengthStatus
  84755. * The callee's return status.
  84756. */
  84757. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  84758. /** Signature for the EOF callback.
  84759. *
  84760. * A function pointer matching this signature may be passed to
  84761. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84762. * called when the decoder needs to know if the end of the stream has
  84763. * been reached.
  84764. *
  84765. * Here is an example of a EOF callback for stdio streams:
  84766. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  84767. * \code
  84768. * {
  84769. * FILE *file = ((MyClientData*)client_data)->file;
  84770. * return feof(file)? true : false;
  84771. * }
  84772. * \endcode
  84773. *
  84774. * \note In general, FLAC__StreamDecoder functions which change the
  84775. * state should not be called on the \a decoder while in the callback.
  84776. *
  84777. * \param decoder The decoder instance calling the callback.
  84778. * \param client_data The callee's client data set through
  84779. * FLAC__stream_decoder_init_*().
  84780. * \retval FLAC__bool
  84781. * \c true if the currently at the end of the stream, else \c false.
  84782. */
  84783. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  84784. /** Signature for the write callback.
  84785. *
  84786. * A function pointer matching this signature must be passed to one of
  84787. * the FLAC__stream_decoder_init_*() functions.
  84788. * The supplied function will be called when the decoder has decoded a
  84789. * single audio frame. The decoder will pass the frame metadata as well
  84790. * as an array of pointers (one for each channel) pointing to the
  84791. * decoded audio.
  84792. *
  84793. * \note In general, FLAC__StreamDecoder functions which change the
  84794. * state should not be called on the \a decoder while in the callback.
  84795. *
  84796. * \param decoder The decoder instance calling the callback.
  84797. * \param frame The description of the decoded frame. See
  84798. * FLAC__Frame.
  84799. * \param buffer An array of pointers to decoded channels of data.
  84800. * Each pointer will point to an array of signed
  84801. * samples of length \a frame->header.blocksize.
  84802. * Channels will be ordered according to the FLAC
  84803. * specification; see the documentation for the
  84804. * <A HREF="../format.html#frame_header">frame header</A>.
  84805. * \param client_data The callee's client data set through
  84806. * FLAC__stream_decoder_init_*().
  84807. * \retval FLAC__StreamDecoderWriteStatus
  84808. * The callee's return status.
  84809. */
  84810. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  84811. /** Signature for the metadata callback.
  84812. *
  84813. * A function pointer matching this signature must be passed to one of
  84814. * the FLAC__stream_decoder_init_*() functions.
  84815. * The supplied function will be called when the decoder has decoded a
  84816. * metadata block. In a valid FLAC file there will always be one
  84817. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  84818. * These will be supplied by the decoder in the same order as they
  84819. * appear in the stream and always before the first audio frame (i.e.
  84820. * write callback). The metadata block that is passed in must not be
  84821. * modified, and it doesn't live beyond the callback, so you should make
  84822. * a copy of it with FLAC__metadata_object_clone() if you will need it
  84823. * elsewhere. Since metadata blocks can potentially be large, by
  84824. * default the decoder only calls the metadata callback for the
  84825. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  84826. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  84827. *
  84828. * \note In general, FLAC__StreamDecoder functions which change the
  84829. * state should not be called on the \a decoder while in the callback.
  84830. *
  84831. * \param decoder The decoder instance calling the callback.
  84832. * \param metadata The decoded metadata block.
  84833. * \param client_data The callee's client data set through
  84834. * FLAC__stream_decoder_init_*().
  84835. */
  84836. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  84837. /** Signature for the error callback.
  84838. *
  84839. * A function pointer matching this signature must be passed to one of
  84840. * the FLAC__stream_decoder_init_*() functions.
  84841. * The supplied function will be called whenever an error occurs during
  84842. * decoding.
  84843. *
  84844. * \note In general, FLAC__StreamDecoder functions which change the
  84845. * state should not be called on the \a decoder while in the callback.
  84846. *
  84847. * \param decoder The decoder instance calling the callback.
  84848. * \param status The error encountered by the decoder.
  84849. * \param client_data The callee's client data set through
  84850. * FLAC__stream_decoder_init_*().
  84851. */
  84852. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  84853. /***********************************************************************
  84854. *
  84855. * Class constructor/destructor
  84856. *
  84857. ***********************************************************************/
  84858. /** Create a new stream decoder instance. The instance is created with
  84859. * default settings; see the individual FLAC__stream_decoder_set_*()
  84860. * functions for each setting's default.
  84861. *
  84862. * \retval FLAC__StreamDecoder*
  84863. * \c NULL if there was an error allocating memory, else the new instance.
  84864. */
  84865. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  84866. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  84867. *
  84868. * \param decoder A pointer to an existing decoder.
  84869. * \assert
  84870. * \code decoder != NULL \endcode
  84871. */
  84872. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  84873. /***********************************************************************
  84874. *
  84875. * Public class method prototypes
  84876. *
  84877. ***********************************************************************/
  84878. /** Set the serial number for the FLAC stream within the Ogg container.
  84879. * The default behavior is to use the serial number of the first Ogg
  84880. * page. Setting a serial number here will explicitly specify which
  84881. * stream is to be decoded.
  84882. *
  84883. * \note
  84884. * This does not need to be set for native FLAC decoding.
  84885. *
  84886. * \default \c use serial number of first page
  84887. * \param decoder A decoder instance to set.
  84888. * \param serial_number See above.
  84889. * \assert
  84890. * \code decoder != NULL \endcode
  84891. * \retval FLAC__bool
  84892. * \c false if the decoder is already initialized, else \c true.
  84893. */
  84894. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  84895. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  84896. * compute the MD5 signature of the unencoded audio data while decoding
  84897. * and compare it to the signature from the STREAMINFO block, if it
  84898. * exists, during FLAC__stream_decoder_finish().
  84899. *
  84900. * MD5 signature checking will be turned off (until the next
  84901. * FLAC__stream_decoder_reset()) if there is no signature in the
  84902. * STREAMINFO block or when a seek is attempted.
  84903. *
  84904. * Clients that do not use the MD5 check should leave this off to speed
  84905. * up decoding.
  84906. *
  84907. * \default \c false
  84908. * \param decoder A decoder instance to set.
  84909. * \param value Flag value (see above).
  84910. * \assert
  84911. * \code decoder != NULL \endcode
  84912. * \retval FLAC__bool
  84913. * \c false if the decoder is already initialized, else \c true.
  84914. */
  84915. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  84916. /** Direct the decoder to pass on all metadata blocks of type \a type.
  84917. *
  84918. * \default By default, only the \c STREAMINFO block is returned via the
  84919. * metadata callback.
  84920. * \param decoder A decoder instance to set.
  84921. * \param type See above.
  84922. * \assert
  84923. * \code decoder != NULL \endcode
  84924. * \a type is valid
  84925. * \retval FLAC__bool
  84926. * \c false if the decoder is already initialized, else \c true.
  84927. */
  84928. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  84929. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  84930. * given \a id.
  84931. *
  84932. * \default By default, only the \c STREAMINFO block is returned via the
  84933. * metadata callback.
  84934. * \param decoder A decoder instance to set.
  84935. * \param id See above.
  84936. * \assert
  84937. * \code decoder != NULL \endcode
  84938. * \code id != NULL \endcode
  84939. * \retval FLAC__bool
  84940. * \c false if the decoder is already initialized, else \c true.
  84941. */
  84942. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  84943. /** Direct the decoder to pass on all metadata blocks of any type.
  84944. *
  84945. * \default By default, only the \c STREAMINFO block is returned via the
  84946. * metadata callback.
  84947. * \param decoder A decoder instance to set.
  84948. * \assert
  84949. * \code decoder != NULL \endcode
  84950. * \retval FLAC__bool
  84951. * \c false if the decoder is already initialized, else \c true.
  84952. */
  84953. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  84954. /** Direct the decoder to filter out all metadata blocks of type \a type.
  84955. *
  84956. * \default By default, only the \c STREAMINFO block is returned via the
  84957. * metadata callback.
  84958. * \param decoder A decoder instance to set.
  84959. * \param type See above.
  84960. * \assert
  84961. * \code decoder != NULL \endcode
  84962. * \a type is valid
  84963. * \retval FLAC__bool
  84964. * \c false if the decoder is already initialized, else \c true.
  84965. */
  84966. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  84967. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  84968. * the given \a id.
  84969. *
  84970. * \default By default, only the \c STREAMINFO block is returned via the
  84971. * metadata callback.
  84972. * \param decoder A decoder instance to set.
  84973. * \param id See above.
  84974. * \assert
  84975. * \code decoder != NULL \endcode
  84976. * \code id != NULL \endcode
  84977. * \retval FLAC__bool
  84978. * \c false if the decoder is already initialized, else \c true.
  84979. */
  84980. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  84981. /** Direct the decoder to filter out all metadata blocks of any type.
  84982. *
  84983. * \default By default, only the \c STREAMINFO block is returned via the
  84984. * metadata callback.
  84985. * \param decoder A decoder instance to set.
  84986. * \assert
  84987. * \code decoder != NULL \endcode
  84988. * \retval FLAC__bool
  84989. * \c false if the decoder is already initialized, else \c true.
  84990. */
  84991. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  84992. /** Get the current decoder state.
  84993. *
  84994. * \param decoder A decoder instance to query.
  84995. * \assert
  84996. * \code decoder != NULL \endcode
  84997. * \retval FLAC__StreamDecoderState
  84998. * The current decoder state.
  84999. */
  85000. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  85001. /** Get the current decoder state as a C string.
  85002. *
  85003. * \param decoder A decoder instance to query.
  85004. * \assert
  85005. * \code decoder != NULL \endcode
  85006. * \retval const char *
  85007. * The decoder state as a C string. Do not modify the contents.
  85008. */
  85009. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  85010. /** Get the "MD5 signature checking" flag.
  85011. * This is the value of the setting, not whether or not the decoder is
  85012. * currently checking the MD5 (remember, it can be turned off automatically
  85013. * by a seek). When the decoder is reset the flag will be restored to the
  85014. * value returned by this function.
  85015. *
  85016. * \param decoder A decoder instance to query.
  85017. * \assert
  85018. * \code decoder != NULL \endcode
  85019. * \retval FLAC__bool
  85020. * See above.
  85021. */
  85022. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  85023. /** Get the total number of samples in the stream being decoded.
  85024. * Will only be valid after decoding has started and will contain the
  85025. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  85026. *
  85027. * \param decoder A decoder instance to query.
  85028. * \assert
  85029. * \code decoder != NULL \endcode
  85030. * \retval unsigned
  85031. * See above.
  85032. */
  85033. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  85034. /** Get the current number of channels in the stream being decoded.
  85035. * Will only be valid after decoding has started and will contain the
  85036. * value from the most recently decoded frame header.
  85037. *
  85038. * \param decoder A decoder instance to query.
  85039. * \assert
  85040. * \code decoder != NULL \endcode
  85041. * \retval unsigned
  85042. * See above.
  85043. */
  85044. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  85045. /** Get the current channel assignment in the stream being decoded.
  85046. * Will only be valid after decoding has started and will contain the
  85047. * value from the most recently decoded frame header.
  85048. *
  85049. * \param decoder A decoder instance to query.
  85050. * \assert
  85051. * \code decoder != NULL \endcode
  85052. * \retval FLAC__ChannelAssignment
  85053. * See above.
  85054. */
  85055. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  85056. /** Get the current sample resolution in the stream being decoded.
  85057. * Will only be valid after decoding has started and will contain the
  85058. * value from the most recently decoded frame header.
  85059. *
  85060. * \param decoder A decoder instance to query.
  85061. * \assert
  85062. * \code decoder != NULL \endcode
  85063. * \retval unsigned
  85064. * See above.
  85065. */
  85066. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  85067. /** Get the current sample rate in Hz of the stream being decoded.
  85068. * Will only be valid after decoding has started and will contain the
  85069. * value from the most recently decoded frame header.
  85070. *
  85071. * \param decoder A decoder instance to query.
  85072. * \assert
  85073. * \code decoder != NULL \endcode
  85074. * \retval unsigned
  85075. * See above.
  85076. */
  85077. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  85078. /** Get the current blocksize of the stream being decoded.
  85079. * Will only be valid after decoding has started and will contain the
  85080. * value from the most recently decoded frame header.
  85081. *
  85082. * \param decoder A decoder instance to query.
  85083. * \assert
  85084. * \code decoder != NULL \endcode
  85085. * \retval unsigned
  85086. * See above.
  85087. */
  85088. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  85089. /** Returns the decoder's current read position within the stream.
  85090. * The position is the byte offset from the start of the stream.
  85091. * Bytes before this position have been fully decoded. Note that
  85092. * there may still be undecoded bytes in the decoder's read FIFO.
  85093. * The returned position is correct even after a seek.
  85094. *
  85095. * \warning This function currently only works for native FLAC,
  85096. * not Ogg FLAC streams.
  85097. *
  85098. * \param decoder A decoder instance to query.
  85099. * \param position Address at which to return the desired position.
  85100. * \assert
  85101. * \code decoder != NULL \endcode
  85102. * \code position != NULL \endcode
  85103. * \retval FLAC__bool
  85104. * \c true if successful, \c false if the stream is not native FLAC,
  85105. * or there was an error from the 'tell' callback or it returned
  85106. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  85107. */
  85108. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  85109. /** Initialize the decoder instance to decode native FLAC streams.
  85110. *
  85111. * This flavor of initialization sets up the decoder to decode from a
  85112. * native FLAC stream. I/O is performed via callbacks to the client.
  85113. * For decoding from a plain file via filename or open FILE*,
  85114. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  85115. * provide a simpler interface.
  85116. *
  85117. * This function should be called after FLAC__stream_decoder_new() and
  85118. * FLAC__stream_decoder_set_*() but before any of the
  85119. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85120. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85121. * if initialization succeeded.
  85122. *
  85123. * \param decoder An uninitialized decoder instance.
  85124. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  85125. * pointer must not be \c NULL.
  85126. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  85127. * pointer may be \c NULL if seeking is not
  85128. * supported. If \a seek_callback is not \c NULL then a
  85129. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  85130. * Alternatively, a dummy seek callback that just
  85131. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  85132. * may also be supplied, all though this is slightly
  85133. * less efficient for the decoder.
  85134. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  85135. * pointer may be \c NULL if not supported by the client. If
  85136. * \a seek_callback is not \c NULL then a
  85137. * \a tell_callback must also be supplied.
  85138. * Alternatively, a dummy tell callback that just
  85139. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  85140. * may also be supplied, all though this is slightly
  85141. * less efficient for the decoder.
  85142. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  85143. * pointer may be \c NULL if not supported by the client. If
  85144. * \a seek_callback is not \c NULL then a
  85145. * \a length_callback must also be supplied.
  85146. * Alternatively, a dummy length callback that just
  85147. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  85148. * may also be supplied, all though this is slightly
  85149. * less efficient for the decoder.
  85150. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  85151. * pointer may be \c NULL if not supported by the client. If
  85152. * \a seek_callback is not \c NULL then a
  85153. * \a eof_callback must also be supplied.
  85154. * Alternatively, a dummy length callback that just
  85155. * returns \c false
  85156. * may also be supplied, all though this is slightly
  85157. * less efficient for the decoder.
  85158. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85159. * pointer must not be \c NULL.
  85160. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85161. * pointer may be \c NULL if the callback is not
  85162. * desired.
  85163. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85164. * pointer must not be \c NULL.
  85165. * \param client_data This value will be supplied to callbacks in their
  85166. * \a client_data argument.
  85167. * \assert
  85168. * \code decoder != NULL \endcode
  85169. * \retval FLAC__StreamDecoderInitStatus
  85170. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85171. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85172. */
  85173. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  85174. FLAC__StreamDecoder *decoder,
  85175. FLAC__StreamDecoderReadCallback read_callback,
  85176. FLAC__StreamDecoderSeekCallback seek_callback,
  85177. FLAC__StreamDecoderTellCallback tell_callback,
  85178. FLAC__StreamDecoderLengthCallback length_callback,
  85179. FLAC__StreamDecoderEofCallback eof_callback,
  85180. FLAC__StreamDecoderWriteCallback write_callback,
  85181. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85182. FLAC__StreamDecoderErrorCallback error_callback,
  85183. void *client_data
  85184. );
  85185. /** Initialize the decoder instance to decode Ogg FLAC streams.
  85186. *
  85187. * This flavor of initialization sets up the decoder to decode from a
  85188. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  85189. * client. For decoding from a plain file via filename or open FILE*,
  85190. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  85191. * provide a simpler interface.
  85192. *
  85193. * This function should be called after FLAC__stream_decoder_new() and
  85194. * FLAC__stream_decoder_set_*() but before any of the
  85195. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85196. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85197. * if initialization succeeded.
  85198. *
  85199. * \note Support for Ogg FLAC in the library is optional. If this
  85200. * library has been built without support for Ogg FLAC, this function
  85201. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  85202. *
  85203. * \param decoder An uninitialized decoder instance.
  85204. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  85205. * pointer must not be \c NULL.
  85206. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  85207. * pointer may be \c NULL if seeking is not
  85208. * supported. If \a seek_callback is not \c NULL then a
  85209. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  85210. * Alternatively, a dummy seek callback that just
  85211. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  85212. * may also be supplied, all though this is slightly
  85213. * less efficient for the decoder.
  85214. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  85215. * pointer may be \c NULL if not supported by the client. If
  85216. * \a seek_callback is not \c NULL then a
  85217. * \a tell_callback must also be supplied.
  85218. * Alternatively, a dummy tell callback that just
  85219. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  85220. * may also be supplied, all though this is slightly
  85221. * less efficient for the decoder.
  85222. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  85223. * pointer may be \c NULL if not supported by the client. If
  85224. * \a seek_callback is not \c NULL then a
  85225. * \a length_callback must also be supplied.
  85226. * Alternatively, a dummy length callback that just
  85227. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  85228. * may also be supplied, all though this is slightly
  85229. * less efficient for the decoder.
  85230. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  85231. * pointer may be \c NULL if not supported by the client. If
  85232. * \a seek_callback is not \c NULL then a
  85233. * \a eof_callback must also be supplied.
  85234. * Alternatively, a dummy length callback that just
  85235. * returns \c false
  85236. * may also be supplied, all though this is slightly
  85237. * less efficient for the decoder.
  85238. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85239. * pointer must not be \c NULL.
  85240. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85241. * pointer may be \c NULL if the callback is not
  85242. * desired.
  85243. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85244. * pointer must not be \c NULL.
  85245. * \param client_data This value will be supplied to callbacks in their
  85246. * \a client_data argument.
  85247. * \assert
  85248. * \code decoder != NULL \endcode
  85249. * \retval FLAC__StreamDecoderInitStatus
  85250. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85251. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85252. */
  85253. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  85254. FLAC__StreamDecoder *decoder,
  85255. FLAC__StreamDecoderReadCallback read_callback,
  85256. FLAC__StreamDecoderSeekCallback seek_callback,
  85257. FLAC__StreamDecoderTellCallback tell_callback,
  85258. FLAC__StreamDecoderLengthCallback length_callback,
  85259. FLAC__StreamDecoderEofCallback eof_callback,
  85260. FLAC__StreamDecoderWriteCallback write_callback,
  85261. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85262. FLAC__StreamDecoderErrorCallback error_callback,
  85263. void *client_data
  85264. );
  85265. /** Initialize the decoder instance to decode native FLAC files.
  85266. *
  85267. * This flavor of initialization sets up the decoder to decode from a
  85268. * plain native FLAC file. For non-stdio streams, you must use
  85269. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  85270. *
  85271. * This function should be called after FLAC__stream_decoder_new() and
  85272. * FLAC__stream_decoder_set_*() but before any of the
  85273. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85274. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85275. * if initialization succeeded.
  85276. *
  85277. * \param decoder An uninitialized decoder instance.
  85278. * \param file An open FLAC file. The file should have been
  85279. * opened with mode \c "rb" and rewound. The file
  85280. * becomes owned by the decoder and should not be
  85281. * manipulated by the client while decoding.
  85282. * Unless \a file is \c stdin, it will be closed
  85283. * when FLAC__stream_decoder_finish() is called.
  85284. * Note however that seeking will not work when
  85285. * decoding from \c stdout since it is not seekable.
  85286. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85287. * pointer must not be \c NULL.
  85288. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85289. * pointer may be \c NULL if the callback is not
  85290. * desired.
  85291. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85292. * pointer must not be \c NULL.
  85293. * \param client_data This value will be supplied to callbacks in their
  85294. * \a client_data argument.
  85295. * \assert
  85296. * \code decoder != NULL \endcode
  85297. * \code file != NULL \endcode
  85298. * \retval FLAC__StreamDecoderInitStatus
  85299. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85300. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85301. */
  85302. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  85303. FLAC__StreamDecoder *decoder,
  85304. FILE *file,
  85305. FLAC__StreamDecoderWriteCallback write_callback,
  85306. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85307. FLAC__StreamDecoderErrorCallback error_callback,
  85308. void *client_data
  85309. );
  85310. /** Initialize the decoder instance to decode Ogg FLAC files.
  85311. *
  85312. * This flavor of initialization sets up the decoder to decode from a
  85313. * plain Ogg FLAC file. For non-stdio streams, you must use
  85314. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  85315. *
  85316. * This function should be called after FLAC__stream_decoder_new() and
  85317. * FLAC__stream_decoder_set_*() but before any of the
  85318. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85319. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85320. * if initialization succeeded.
  85321. *
  85322. * \note Support for Ogg FLAC in the library is optional. If this
  85323. * library has been built without support for Ogg FLAC, this function
  85324. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  85325. *
  85326. * \param decoder An uninitialized decoder instance.
  85327. * \param file An open FLAC file. The file should have been
  85328. * opened with mode \c "rb" and rewound. The file
  85329. * becomes owned by the decoder and should not be
  85330. * manipulated by the client while decoding.
  85331. * Unless \a file is \c stdin, it will be closed
  85332. * when FLAC__stream_decoder_finish() is called.
  85333. * Note however that seeking will not work when
  85334. * decoding from \c stdout since it is not seekable.
  85335. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85336. * pointer must not be \c NULL.
  85337. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85338. * pointer may be \c NULL if the callback is not
  85339. * desired.
  85340. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85341. * pointer must not be \c NULL.
  85342. * \param client_data This value will be supplied to callbacks in their
  85343. * \a client_data argument.
  85344. * \assert
  85345. * \code decoder != NULL \endcode
  85346. * \code file != NULL \endcode
  85347. * \retval FLAC__StreamDecoderInitStatus
  85348. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85349. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85350. */
  85351. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  85352. FLAC__StreamDecoder *decoder,
  85353. FILE *file,
  85354. FLAC__StreamDecoderWriteCallback write_callback,
  85355. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85356. FLAC__StreamDecoderErrorCallback error_callback,
  85357. void *client_data
  85358. );
  85359. /** Initialize the decoder instance to decode native FLAC files.
  85360. *
  85361. * This flavor of initialization sets up the decoder to decode from a plain
  85362. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  85363. * example, with Unicode filenames on Windows), you must use
  85364. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  85365. * and provide callbacks for the I/O.
  85366. *
  85367. * This function should be called after FLAC__stream_decoder_new() and
  85368. * FLAC__stream_decoder_set_*() but before any of the
  85369. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85370. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85371. * if initialization succeeded.
  85372. *
  85373. * \param decoder An uninitialized decoder instance.
  85374. * \param filename The name of the file to decode from. The file will
  85375. * be opened with fopen(). Use \c NULL to decode from
  85376. * \c stdin. Note that \c stdin is not seekable.
  85377. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85378. * pointer must not be \c NULL.
  85379. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85380. * pointer may be \c NULL if the callback is not
  85381. * desired.
  85382. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85383. * pointer must not be \c NULL.
  85384. * \param client_data This value will be supplied to callbacks in their
  85385. * \a client_data argument.
  85386. * \assert
  85387. * \code decoder != NULL \endcode
  85388. * \retval FLAC__StreamDecoderInitStatus
  85389. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85390. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85391. */
  85392. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  85393. FLAC__StreamDecoder *decoder,
  85394. const char *filename,
  85395. FLAC__StreamDecoderWriteCallback write_callback,
  85396. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85397. FLAC__StreamDecoderErrorCallback error_callback,
  85398. void *client_data
  85399. );
  85400. /** Initialize the decoder instance to decode Ogg FLAC files.
  85401. *
  85402. * This flavor of initialization sets up the decoder to decode from a plain
  85403. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  85404. * example, with Unicode filenames on Windows), you must use
  85405. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  85406. * and provide callbacks for the I/O.
  85407. *
  85408. * This function should be called after FLAC__stream_decoder_new() and
  85409. * FLAC__stream_decoder_set_*() but before any of the
  85410. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85411. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85412. * if initialization succeeded.
  85413. *
  85414. * \note Support for Ogg FLAC in the library is optional. If this
  85415. * library has been built without support for Ogg FLAC, this function
  85416. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  85417. *
  85418. * \param decoder An uninitialized decoder instance.
  85419. * \param filename The name of the file to decode from. The file will
  85420. * be opened with fopen(). Use \c NULL to decode from
  85421. * \c stdin. Note that \c stdin is not seekable.
  85422. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85423. * pointer must not be \c NULL.
  85424. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85425. * pointer may be \c NULL if the callback is not
  85426. * desired.
  85427. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85428. * pointer must not be \c NULL.
  85429. * \param client_data This value will be supplied to callbacks in their
  85430. * \a client_data argument.
  85431. * \assert
  85432. * \code decoder != NULL \endcode
  85433. * \retval FLAC__StreamDecoderInitStatus
  85434. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85435. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85436. */
  85437. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  85438. FLAC__StreamDecoder *decoder,
  85439. const char *filename,
  85440. FLAC__StreamDecoderWriteCallback write_callback,
  85441. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85442. FLAC__StreamDecoderErrorCallback error_callback,
  85443. void *client_data
  85444. );
  85445. /** Finish the decoding process.
  85446. * Flushes the decoding buffer, releases resources, resets the decoder
  85447. * settings to their defaults, and returns the decoder state to
  85448. * FLAC__STREAM_DECODER_UNINITIALIZED.
  85449. *
  85450. * In the event of a prematurely-terminated decode, it is not strictly
  85451. * necessary to call this immediately before FLAC__stream_decoder_delete()
  85452. * but it is good practice to match every FLAC__stream_decoder_init_*()
  85453. * with a FLAC__stream_decoder_finish().
  85454. *
  85455. * \param decoder An uninitialized decoder instance.
  85456. * \assert
  85457. * \code decoder != NULL \endcode
  85458. * \retval FLAC__bool
  85459. * \c false if MD5 checking is on AND a STREAMINFO block was available
  85460. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  85461. * signature does not match the one computed by the decoder; else
  85462. * \c true.
  85463. */
  85464. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  85465. /** Flush the stream input.
  85466. * The decoder's input buffer will be cleared and the state set to
  85467. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  85468. * off MD5 checking.
  85469. *
  85470. * \param decoder A decoder instance.
  85471. * \assert
  85472. * \code decoder != NULL \endcode
  85473. * \retval FLAC__bool
  85474. * \c true if successful, else \c false if a memory allocation
  85475. * error occurs (in which case the state will be set to
  85476. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  85477. */
  85478. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  85479. /** Reset the decoding process.
  85480. * The decoder's input buffer will be cleared and the state set to
  85481. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  85482. * FLAC__stream_decoder_finish() except that the settings are
  85483. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  85484. * before decoding again. MD5 checking will be restored to its original
  85485. * setting.
  85486. *
  85487. * If the decoder is seekable, or was initialized with
  85488. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  85489. * the decoder will also attempt to seek to the beginning of the file.
  85490. * If this rewind fails, this function will return \c false. It follows
  85491. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  85492. * \c stdin.
  85493. *
  85494. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  85495. * and is not seekable (i.e. no seek callback was provided or the seek
  85496. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  85497. * is the duty of the client to start feeding data from the beginning of
  85498. * the stream on the next FLAC__stream_decoder_process() or
  85499. * FLAC__stream_decoder_process_interleaved() call.
  85500. *
  85501. * \param decoder A decoder instance.
  85502. * \assert
  85503. * \code decoder != NULL \endcode
  85504. * \retval FLAC__bool
  85505. * \c true if successful, else \c false if a memory allocation occurs
  85506. * (in which case the state will be set to
  85507. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  85508. * occurs (the state will be unchanged).
  85509. */
  85510. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  85511. /** Decode one metadata block or audio frame.
  85512. * This version instructs the decoder to decode a either a single metadata
  85513. * block or a single frame and stop, unless the callbacks return a fatal
  85514. * error or the read callback returns
  85515. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  85516. *
  85517. * As the decoder needs more input it will call the read callback.
  85518. * Depending on what was decoded, the metadata or write callback will be
  85519. * called with the decoded metadata block or audio frame.
  85520. *
  85521. * Unless there is a fatal read error or end of stream, this function
  85522. * will return once one whole frame is decoded. In other words, if the
  85523. * stream is not synchronized or points to a corrupt frame header, the
  85524. * decoder will continue to try and resync until it gets to a valid
  85525. * frame, then decode one frame, then return. If the decoder points to
  85526. * a frame whose frame CRC in the frame footer does not match the
  85527. * computed frame CRC, this function will issue a
  85528. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  85529. * error callback, and return, having decoded one complete, although
  85530. * corrupt, frame. (Such corrupted frames are sent as silence of the
  85531. * correct length to the write callback.)
  85532. *
  85533. * \param decoder An initialized decoder instance.
  85534. * \assert
  85535. * \code decoder != NULL \endcode
  85536. * \retval FLAC__bool
  85537. * \c false if any fatal read, write, or memory allocation error
  85538. * occurred (meaning decoding must stop), else \c true; for more
  85539. * information about the decoder, check the decoder state with
  85540. * FLAC__stream_decoder_get_state().
  85541. */
  85542. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  85543. /** Decode until the end of the metadata.
  85544. * This version instructs the decoder to decode from the current position
  85545. * and continue until all the metadata has been read, or until the
  85546. * callbacks return a fatal error or the read callback returns
  85547. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  85548. *
  85549. * As the decoder needs more input it will call the read callback.
  85550. * As each metadata block is decoded, the metadata callback will be called
  85551. * with the decoded metadata.
  85552. *
  85553. * \param decoder An initialized decoder instance.
  85554. * \assert
  85555. * \code decoder != NULL \endcode
  85556. * \retval FLAC__bool
  85557. * \c false if any fatal read, write, or memory allocation error
  85558. * occurred (meaning decoding must stop), else \c true; for more
  85559. * information about the decoder, check the decoder state with
  85560. * FLAC__stream_decoder_get_state().
  85561. */
  85562. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  85563. /** Decode until the end of the stream.
  85564. * This version instructs the decoder to decode from the current position
  85565. * and continue until the end of stream (the read callback returns
  85566. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  85567. * callbacks return a fatal error.
  85568. *
  85569. * As the decoder needs more input it will call the read callback.
  85570. * As each metadata block and frame is decoded, the metadata or write
  85571. * callback will be called with the decoded metadata or frame.
  85572. *
  85573. * \param decoder An initialized decoder instance.
  85574. * \assert
  85575. * \code decoder != NULL \endcode
  85576. * \retval FLAC__bool
  85577. * \c false if any fatal read, write, or memory allocation error
  85578. * occurred (meaning decoding must stop), else \c true; for more
  85579. * information about the decoder, check the decoder state with
  85580. * FLAC__stream_decoder_get_state().
  85581. */
  85582. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  85583. /** Skip one audio frame.
  85584. * This version instructs the decoder to 'skip' a single frame and stop,
  85585. * unless the callbacks return a fatal error or the read callback returns
  85586. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  85587. *
  85588. * The decoding flow is the same as what occurs when
  85589. * FLAC__stream_decoder_process_single() is called to process an audio
  85590. * frame, except that this function does not decode the parsed data into
  85591. * PCM or call the write callback. The integrity of the frame is still
  85592. * checked the same way as in the other process functions.
  85593. *
  85594. * This function will return once one whole frame is skipped, in the
  85595. * same way that FLAC__stream_decoder_process_single() will return once
  85596. * one whole frame is decoded.
  85597. *
  85598. * This function can be used in more quickly determining FLAC frame
  85599. * boundaries when decoding of the actual data is not needed, for
  85600. * example when an application is separating a FLAC stream into frames
  85601. * for editing or storing in a container. To do this, the application
  85602. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  85603. * to the next frame, then use
  85604. * FLAC__stream_decoder_get_decode_position() to find the new frame
  85605. * boundary.
  85606. *
  85607. * This function should only be called when the stream has advanced
  85608. * past all the metadata, otherwise it will return \c false.
  85609. *
  85610. * \param decoder An initialized decoder instance not in a metadata
  85611. * state.
  85612. * \assert
  85613. * \code decoder != NULL \endcode
  85614. * \retval FLAC__bool
  85615. * \c false if any fatal read, write, or memory allocation error
  85616. * occurred (meaning decoding must stop), or if the decoder
  85617. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  85618. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  85619. * information about the decoder, check the decoder state with
  85620. * FLAC__stream_decoder_get_state().
  85621. */
  85622. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  85623. /** Flush the input and seek to an absolute sample.
  85624. * Decoding will resume at the given sample. Note that because of
  85625. * this, the next write callback may contain a partial block. The
  85626. * client must support seeking the input or this function will fail
  85627. * and return \c false. Furthermore, if the decoder state is
  85628. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  85629. * with FLAC__stream_decoder_flush() or reset with
  85630. * FLAC__stream_decoder_reset() before decoding can continue.
  85631. *
  85632. * \param decoder A decoder instance.
  85633. * \param sample The target sample number to seek to.
  85634. * \assert
  85635. * \code decoder != NULL \endcode
  85636. * \retval FLAC__bool
  85637. * \c true if successful, else \c false.
  85638. */
  85639. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  85640. /* \} */
  85641. #ifdef __cplusplus
  85642. }
  85643. #endif
  85644. #endif
  85645. /********* End of inlined file: stream_decoder.h *********/
  85646. /********* Start of inlined file: stream_encoder.h *********/
  85647. #ifndef FLAC__STREAM_ENCODER_H
  85648. #define FLAC__STREAM_ENCODER_H
  85649. #include <stdio.h> /* for FILE */
  85650. #ifdef __cplusplus
  85651. extern "C" {
  85652. #endif
  85653. /** \file include/FLAC/stream_encoder.h
  85654. *
  85655. * \brief
  85656. * This module contains the functions which implement the stream
  85657. * encoder.
  85658. *
  85659. * See the detailed documentation in the
  85660. * \link flac_stream_encoder stream encoder \endlink module.
  85661. */
  85662. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  85663. * \ingroup flac
  85664. *
  85665. * \brief
  85666. * This module describes the encoder layers provided by libFLAC.
  85667. *
  85668. * The stream encoder can be used to encode complete streams either to the
  85669. * client via callbacks, or directly to a file, depending on how it is
  85670. * initialized. When encoding via callbacks, the client provides a write
  85671. * callback which will be called whenever FLAC data is ready to be written.
  85672. * If the client also supplies a seek callback, the encoder will also
  85673. * automatically handle the writing back of metadata discovered while
  85674. * encoding, like stream info, seek points offsets, etc. When encoding to
  85675. * a file, the client needs only supply a filename or open \c FILE* and an
  85676. * optional progress callback for periodic notification of progress; the
  85677. * write and seek callbacks are supplied internally. For more info see the
  85678. * \link flac_stream_encoder stream encoder \endlink module.
  85679. */
  85680. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  85681. * \ingroup flac_encoder
  85682. *
  85683. * \brief
  85684. * This module contains the functions which implement the stream
  85685. * encoder.
  85686. *
  85687. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  85688. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  85689. *
  85690. * The basic usage of this encoder is as follows:
  85691. * - The program creates an instance of an encoder using
  85692. * FLAC__stream_encoder_new().
  85693. * - The program overrides the default settings using
  85694. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  85695. * functions should be called:
  85696. * - FLAC__stream_encoder_set_channels()
  85697. * - FLAC__stream_encoder_set_bits_per_sample()
  85698. * - FLAC__stream_encoder_set_sample_rate()
  85699. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  85700. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  85701. * - If the application wants to control the compression level or set its own
  85702. * metadata, then the following should also be called:
  85703. * - FLAC__stream_encoder_set_compression_level()
  85704. * - FLAC__stream_encoder_set_verify()
  85705. * - FLAC__stream_encoder_set_metadata()
  85706. * - The rest of the set functions should only be called if the client needs
  85707. * exact control over how the audio is compressed; thorough understanding
  85708. * of the FLAC format is necessary to achieve good results.
  85709. * - The program initializes the instance to validate the settings and
  85710. * prepare for encoding using
  85711. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  85712. * or FLAC__stream_encoder_init_file() for native FLAC
  85713. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  85714. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  85715. * - The program calls FLAC__stream_encoder_process() or
  85716. * FLAC__stream_encoder_process_interleaved() to encode data, which
  85717. * subsequently calls the callbacks when there is encoder data ready
  85718. * to be written.
  85719. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  85720. * which causes the encoder to encode any data still in its input pipe,
  85721. * update the metadata with the final encoding statistics if output
  85722. * seeking is possible, and finally reset the encoder to the
  85723. * uninitialized state.
  85724. * - The instance may be used again or deleted with
  85725. * FLAC__stream_encoder_delete().
  85726. *
  85727. * In more detail, the stream encoder functions similarly to the
  85728. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  85729. * callbacks and more options. Typically the client will create a new
  85730. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  85731. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  85732. * calling one of the FLAC__stream_encoder_init_*() functions.
  85733. *
  85734. * Unlike the decoders, the stream encoder has many options that can
  85735. * affect the speed and compression ratio. When setting these parameters
  85736. * you should have some basic knowledge of the format (see the
  85737. * <A HREF="../documentation.html#format">user-level documentation</A>
  85738. * or the <A HREF="../format.html">formal description</A>). The
  85739. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  85740. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  85741. * functions will do this, so make sure to pay attention to the state
  85742. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  85743. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  85744. * before FLAC__stream_encoder_init_*() will take on the defaults from
  85745. * the constructor.
  85746. *
  85747. * There are three initialization functions for native FLAC, one for
  85748. * setting up the encoder to encode FLAC data to the client via
  85749. * callbacks, and two for encoding directly to a file.
  85750. *
  85751. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  85752. * You must also supply a write callback which will be called anytime
  85753. * there is raw encoded data to write. If the client can seek the output
  85754. * it is best to also supply seek and tell callbacks, as this allows the
  85755. * encoder to go back after encoding is finished to write back
  85756. * information that was collected while encoding, like seek point offsets,
  85757. * frame sizes, etc.
  85758. *
  85759. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  85760. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  85761. * filename or open \c FILE*; the encoder will handle all the callbacks
  85762. * internally. You may also supply a progress callback for periodic
  85763. * notification of the encoding progress.
  85764. *
  85765. * There are three similarly-named init functions for encoding to Ogg
  85766. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  85767. * library has been built with Ogg support.
  85768. *
  85769. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  85770. * call the write callback several times, once with the \c fLaC signature,
  85771. * and once for each encoded metadata block. Note that for Ogg FLAC
  85772. * encoding you will usually get at least twice the number of callbacks than
  85773. * with native FLAC, one for the Ogg page header and one for the page body.
  85774. *
  85775. * After initializing the instance, the client may feed audio data to the
  85776. * encoder in one of two ways:
  85777. *
  85778. * - Channel separate, through FLAC__stream_encoder_process() - The client
  85779. * will pass an array of pointers to buffers, one for each channel, to
  85780. * the encoder, each of the same length. The samples need not be
  85781. * block-aligned, but each channel should have the same number of samples.
  85782. * - Channel interleaved, through
  85783. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  85784. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  85785. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  85786. * Again, the samples need not be block-aligned but they must be
  85787. * sample-aligned, i.e. the first value should be channel0_sample0 and
  85788. * the last value channelN_sampleM.
  85789. *
  85790. * Note that for either process call, each sample in the buffers should be a
  85791. * signed integer, right-justified to the resolution set by
  85792. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  85793. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  85794. *
  85795. * When the client is finished encoding data, it calls
  85796. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  85797. * data still in its input pipe, and call the metadata callback with the
  85798. * final encoding statistics. Then the instance may be deleted with
  85799. * FLAC__stream_encoder_delete() or initialized again to encode another
  85800. * stream.
  85801. *
  85802. * For programs that write their own metadata, but that do not know the
  85803. * actual metadata until after encoding, it is advantageous to instruct
  85804. * the encoder to write a PADDING block of the correct size, so that
  85805. * instead of rewriting the whole stream after encoding, the program can
  85806. * just overwrite the PADDING block. If only the maximum size of the
  85807. * metadata is known, the program can write a slightly larger padding
  85808. * block, then split it after encoding.
  85809. *
  85810. * Make sure you understand how lengths are calculated. All FLAC metadata
  85811. * blocks have a 4 byte header which contains the type and length. This
  85812. * length does not include the 4 bytes of the header. See the format page
  85813. * for the specification of metadata blocks and their lengths.
  85814. *
  85815. * \note
  85816. * If you are writing the FLAC data to a file via callbacks, make sure it
  85817. * is open for update (e.g. mode "w+" for stdio streams). This is because
  85818. * after the first encoding pass, the encoder will try to seek back to the
  85819. * beginning of the stream, to the STREAMINFO block, to write some data
  85820. * there. (If using FLAC__stream_encoder_init*_file() or
  85821. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  85822. *
  85823. * \note
  85824. * The "set" functions may only be called when the encoder is in the
  85825. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  85826. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  85827. * before FLAC__stream_encoder_init_*(). If this is the case they will
  85828. * return \c true, otherwise \c false.
  85829. *
  85830. * \note
  85831. * FLAC__stream_encoder_finish() resets all settings to the constructor
  85832. * defaults.
  85833. *
  85834. * \{
  85835. */
  85836. /** State values for a FLAC__StreamEncoder.
  85837. *
  85838. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  85839. *
  85840. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  85841. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  85842. * must be deleted with FLAC__stream_encoder_delete().
  85843. */
  85844. typedef enum {
  85845. FLAC__STREAM_ENCODER_OK = 0,
  85846. /**< The encoder is in the normal OK state and samples can be processed. */
  85847. FLAC__STREAM_ENCODER_UNINITIALIZED,
  85848. /**< The encoder is in the uninitialized state; one of the
  85849. * FLAC__stream_encoder_init_*() functions must be called before samples
  85850. * can be processed.
  85851. */
  85852. FLAC__STREAM_ENCODER_OGG_ERROR,
  85853. /**< An error occurred in the underlying Ogg layer. */
  85854. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  85855. /**< An error occurred in the underlying verify stream decoder;
  85856. * check FLAC__stream_encoder_get_verify_decoder_state().
  85857. */
  85858. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  85859. /**< The verify decoder detected a mismatch between the original
  85860. * audio signal and the decoded audio signal.
  85861. */
  85862. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  85863. /**< One of the callbacks returned a fatal error. */
  85864. FLAC__STREAM_ENCODER_IO_ERROR,
  85865. /**< An I/O error occurred while opening/reading/writing a file.
  85866. * Check \c errno.
  85867. */
  85868. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  85869. /**< An error occurred while writing the stream; usually, the
  85870. * write_callback returned an error.
  85871. */
  85872. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  85873. /**< Memory allocation failed. */
  85874. } FLAC__StreamEncoderState;
  85875. /** Maps a FLAC__StreamEncoderState to a C string.
  85876. *
  85877. * Using a FLAC__StreamEncoderState as the index to this array
  85878. * will give the string equivalent. The contents should not be modified.
  85879. */
  85880. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  85881. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  85882. */
  85883. typedef enum {
  85884. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  85885. /**< Initialization was successful. */
  85886. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  85887. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  85888. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  85889. /**< The library was not compiled with support for the given container
  85890. * format.
  85891. */
  85892. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  85893. /**< A required callback was not supplied. */
  85894. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  85895. /**< The encoder has an invalid setting for number of channels. */
  85896. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  85897. /**< The encoder has an invalid setting for bits-per-sample.
  85898. * FLAC supports 4-32 bps but the reference encoder currently supports
  85899. * only up to 24 bps.
  85900. */
  85901. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  85902. /**< The encoder has an invalid setting for the input sample rate. */
  85903. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  85904. /**< The encoder has an invalid setting for the block size. */
  85905. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  85906. /**< The encoder has an invalid setting for the maximum LPC order. */
  85907. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  85908. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  85909. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  85910. /**< The specified block size is less than the maximum LPC order. */
  85911. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  85912. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  85913. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  85914. /**< The metadata input to the encoder is invalid, in one of the following ways:
  85915. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  85916. * - One of the metadata blocks contains an undefined type
  85917. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  85918. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  85919. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  85920. */
  85921. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  85922. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  85923. * already initialized, usually because
  85924. * FLAC__stream_encoder_finish() was not called.
  85925. */
  85926. } FLAC__StreamEncoderInitStatus;
  85927. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  85928. *
  85929. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  85930. * will give the string equivalent. The contents should not be modified.
  85931. */
  85932. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  85933. /** Return values for the FLAC__StreamEncoder read callback.
  85934. */
  85935. typedef enum {
  85936. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  85937. /**< The read was OK and decoding can continue. */
  85938. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  85939. /**< The read was attempted at the end of the stream. */
  85940. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  85941. /**< An unrecoverable error occurred. */
  85942. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  85943. /**< Client does not support reading back from the output. */
  85944. } FLAC__StreamEncoderReadStatus;
  85945. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  85946. *
  85947. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  85948. * will give the string equivalent. The contents should not be modified.
  85949. */
  85950. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  85951. /** Return values for the FLAC__StreamEncoder write callback.
  85952. */
  85953. typedef enum {
  85954. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  85955. /**< The write was OK and encoding can continue. */
  85956. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  85957. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  85958. } FLAC__StreamEncoderWriteStatus;
  85959. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  85960. *
  85961. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  85962. * will give the string equivalent. The contents should not be modified.
  85963. */
  85964. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  85965. /** Return values for the FLAC__StreamEncoder seek callback.
  85966. */
  85967. typedef enum {
  85968. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  85969. /**< The seek was OK and encoding can continue. */
  85970. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  85971. /**< An unrecoverable error occurred. */
  85972. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  85973. /**< Client does not support seeking. */
  85974. } FLAC__StreamEncoderSeekStatus;
  85975. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  85976. *
  85977. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  85978. * will give the string equivalent. The contents should not be modified.
  85979. */
  85980. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  85981. /** Return values for the FLAC__StreamEncoder tell callback.
  85982. */
  85983. typedef enum {
  85984. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  85985. /**< The tell was OK and encoding can continue. */
  85986. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  85987. /**< An unrecoverable error occurred. */
  85988. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  85989. /**< Client does not support seeking. */
  85990. } FLAC__StreamEncoderTellStatus;
  85991. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  85992. *
  85993. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  85994. * will give the string equivalent. The contents should not be modified.
  85995. */
  85996. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  85997. /***********************************************************************
  85998. *
  85999. * class FLAC__StreamEncoder
  86000. *
  86001. ***********************************************************************/
  86002. struct FLAC__StreamEncoderProtected;
  86003. struct FLAC__StreamEncoderPrivate;
  86004. /** The opaque structure definition for the stream encoder type.
  86005. * See the \link flac_stream_encoder stream encoder module \endlink
  86006. * for a detailed description.
  86007. */
  86008. typedef struct {
  86009. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  86010. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  86011. } FLAC__StreamEncoder;
  86012. /** Signature for the read callback.
  86013. *
  86014. * A function pointer matching this signature must be passed to
  86015. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  86016. * The supplied function will be called when the encoder needs to read back
  86017. * encoded data. This happens during the metadata callback, when the encoder
  86018. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  86019. * while encoding. The address of the buffer to be filled is supplied, along
  86020. * with the number of bytes the buffer can hold. The callback may choose to
  86021. * supply less data and modify the byte count but must be careful not to
  86022. * overflow the buffer. The callback then returns a status code chosen from
  86023. * FLAC__StreamEncoderReadStatus.
  86024. *
  86025. * Here is an example of a read callback for stdio streams:
  86026. * \code
  86027. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  86028. * {
  86029. * FILE *file = ((MyClientData*)client_data)->file;
  86030. * if(*bytes > 0) {
  86031. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  86032. * if(ferror(file))
  86033. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  86034. * else if(*bytes == 0)
  86035. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  86036. * else
  86037. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  86038. * }
  86039. * else
  86040. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  86041. * }
  86042. * \endcode
  86043. *
  86044. * \note In general, FLAC__StreamEncoder functions which change the
  86045. * state should not be called on the \a encoder while in the callback.
  86046. *
  86047. * \param encoder The encoder instance calling the callback.
  86048. * \param buffer A pointer to a location for the callee to store
  86049. * data to be encoded.
  86050. * \param bytes A pointer to the size of the buffer. On entry
  86051. * to the callback, it contains the maximum number
  86052. * of bytes that may be stored in \a buffer. The
  86053. * callee must set it to the actual number of bytes
  86054. * stored (0 in case of error or end-of-stream) before
  86055. * returning.
  86056. * \param client_data The callee's client data set through
  86057. * FLAC__stream_encoder_set_client_data().
  86058. * \retval FLAC__StreamEncoderReadStatus
  86059. * The callee's return status.
  86060. */
  86061. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  86062. /** Signature for the write callback.
  86063. *
  86064. * A function pointer matching this signature must be passed to
  86065. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86066. * by the encoder anytime there is raw encoded data ready to write. It may
  86067. * include metadata mixed with encoded audio frames and the data is not
  86068. * guaranteed to be aligned on frame or metadata block boundaries.
  86069. *
  86070. * The only duty of the callback is to write out the \a bytes worth of data
  86071. * in \a buffer to the current position in the output stream. The arguments
  86072. * \a samples and \a current_frame are purely informational. If \a samples
  86073. * is greater than \c 0, then \a current_frame will hold the current frame
  86074. * number that is being written; otherwise it indicates that the write
  86075. * callback is being called to write metadata.
  86076. *
  86077. * \note
  86078. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  86079. * write callback will be called twice when writing each audio
  86080. * frame; once for the page header, and once for the page body.
  86081. * When writing the page header, the \a samples argument to the
  86082. * write callback will be \c 0.
  86083. *
  86084. * \note In general, FLAC__StreamEncoder functions which change the
  86085. * state should not be called on the \a encoder while in the callback.
  86086. *
  86087. * \param encoder The encoder instance calling the callback.
  86088. * \param buffer An array of encoded data of length \a bytes.
  86089. * \param bytes The byte length of \a buffer.
  86090. * \param samples The number of samples encoded by \a buffer.
  86091. * \c 0 has a special meaning; see above.
  86092. * \param current_frame The number of the current frame being encoded.
  86093. * \param client_data The callee's client data set through
  86094. * FLAC__stream_encoder_init_*().
  86095. * \retval FLAC__StreamEncoderWriteStatus
  86096. * The callee's return status.
  86097. */
  86098. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  86099. /** Signature for the seek callback.
  86100. *
  86101. * A function pointer matching this signature may be passed to
  86102. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86103. * when the encoder needs to seek the output stream. The encoder will pass
  86104. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  86105. *
  86106. * Here is an example of a seek callback for stdio streams:
  86107. * \code
  86108. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  86109. * {
  86110. * FILE *file = ((MyClientData*)client_data)->file;
  86111. * if(file == stdin)
  86112. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  86113. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  86114. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  86115. * else
  86116. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  86117. * }
  86118. * \endcode
  86119. *
  86120. * \note In general, FLAC__StreamEncoder functions which change the
  86121. * state should not be called on the \a encoder while in the callback.
  86122. *
  86123. * \param encoder The encoder instance calling the callback.
  86124. * \param absolute_byte_offset The offset from the beginning of the stream
  86125. * to seek to.
  86126. * \param client_data The callee's client data set through
  86127. * FLAC__stream_encoder_init_*().
  86128. * \retval FLAC__StreamEncoderSeekStatus
  86129. * The callee's return status.
  86130. */
  86131. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  86132. /** Signature for the tell callback.
  86133. *
  86134. * A function pointer matching this signature may be passed to
  86135. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86136. * when the encoder needs to know the current position of the output stream.
  86137. *
  86138. * \warning
  86139. * The callback must return the true current byte offset of the output to
  86140. * which the encoder is writing. If you are buffering the output, make
  86141. * sure and take this into account. If you are writing directly to a
  86142. * FILE* from your write callback, ftell() is sufficient. If you are
  86143. * writing directly to a file descriptor from your write callback, you
  86144. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  86145. * these points to rewrite metadata after encoding.
  86146. *
  86147. * Here is an example of a tell callback for stdio streams:
  86148. * \code
  86149. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  86150. * {
  86151. * FILE *file = ((MyClientData*)client_data)->file;
  86152. * off_t pos;
  86153. * if(file == stdin)
  86154. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  86155. * else if((pos = ftello(file)) < 0)
  86156. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  86157. * else {
  86158. * *absolute_byte_offset = (FLAC__uint64)pos;
  86159. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  86160. * }
  86161. * }
  86162. * \endcode
  86163. *
  86164. * \note In general, FLAC__StreamEncoder functions which change the
  86165. * state should not be called on the \a encoder while in the callback.
  86166. *
  86167. * \param encoder The encoder instance calling the callback.
  86168. * \param absolute_byte_offset The address at which to store the current
  86169. * position of the output.
  86170. * \param client_data The callee's client data set through
  86171. * FLAC__stream_encoder_init_*().
  86172. * \retval FLAC__StreamEncoderTellStatus
  86173. * The callee's return status.
  86174. */
  86175. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  86176. /** Signature for the metadata callback.
  86177. *
  86178. * A function pointer matching this signature may be passed to
  86179. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86180. * once at the end of encoding with the populated STREAMINFO structure. This
  86181. * is so the client can seek back to the beginning of the file and write the
  86182. * STREAMINFO block with the correct statistics after encoding (like
  86183. * minimum/maximum frame size and total samples).
  86184. *
  86185. * \note In general, FLAC__StreamEncoder functions which change the
  86186. * state should not be called on the \a encoder while in the callback.
  86187. *
  86188. * \param encoder The encoder instance calling the callback.
  86189. * \param metadata The final populated STREAMINFO block.
  86190. * \param client_data The callee's client data set through
  86191. * FLAC__stream_encoder_init_*().
  86192. */
  86193. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  86194. /** Signature for the progress callback.
  86195. *
  86196. * A function pointer matching this signature may be passed to
  86197. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  86198. * The supplied function will be called when the encoder has finished
  86199. * writing a frame. The \c total_frames_estimate argument to the
  86200. * callback will be based on the value from
  86201. * FLAC__stream_encoder_set_total_samples_estimate().
  86202. *
  86203. * \note In general, FLAC__StreamEncoder functions which change the
  86204. * state should not be called on the \a encoder while in the callback.
  86205. *
  86206. * \param encoder The encoder instance calling the callback.
  86207. * \param bytes_written Bytes written so far.
  86208. * \param samples_written Samples written so far.
  86209. * \param frames_written Frames written so far.
  86210. * \param total_frames_estimate The estimate of the total number of
  86211. * frames to be written.
  86212. * \param client_data The callee's client data set through
  86213. * FLAC__stream_encoder_init_*().
  86214. */
  86215. 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);
  86216. /***********************************************************************
  86217. *
  86218. * Class constructor/destructor
  86219. *
  86220. ***********************************************************************/
  86221. /** Create a new stream encoder instance. The instance is created with
  86222. * default settings; see the individual FLAC__stream_encoder_set_*()
  86223. * functions for each setting's default.
  86224. *
  86225. * \retval FLAC__StreamEncoder*
  86226. * \c NULL if there was an error allocating memory, else the new instance.
  86227. */
  86228. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  86229. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  86230. *
  86231. * \param encoder A pointer to an existing encoder.
  86232. * \assert
  86233. * \code encoder != NULL \endcode
  86234. */
  86235. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  86236. /***********************************************************************
  86237. *
  86238. * Public class method prototypes
  86239. *
  86240. ***********************************************************************/
  86241. /** Set the serial number for the FLAC stream to use in the Ogg container.
  86242. *
  86243. * \note
  86244. * This does not need to be set for native FLAC encoding.
  86245. *
  86246. * \note
  86247. * It is recommended to set a serial number explicitly as the default of '0'
  86248. * may collide with other streams.
  86249. *
  86250. * \default \c 0
  86251. * \param encoder An encoder instance to set.
  86252. * \param serial_number See above.
  86253. * \assert
  86254. * \code encoder != NULL \endcode
  86255. * \retval FLAC__bool
  86256. * \c false if the encoder is already initialized, else \c true.
  86257. */
  86258. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  86259. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  86260. * encoded output by feeding it through an internal decoder and comparing
  86261. * the original signal against the decoded signal. If a mismatch occurs,
  86262. * the process call will return \c false. Note that this will slow the
  86263. * encoding process by the extra time required for decoding and comparison.
  86264. *
  86265. * \default \c false
  86266. * \param encoder An encoder instance to set.
  86267. * \param value Flag value (see above).
  86268. * \assert
  86269. * \code encoder != NULL \endcode
  86270. * \retval FLAC__bool
  86271. * \c false if the encoder is already initialized, else \c true.
  86272. */
  86273. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86274. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  86275. * the encoder will comply with the Subset and will check the
  86276. * settings during FLAC__stream_encoder_init_*() to see if all settings
  86277. * comply. If \c false, the settings may take advantage of the full
  86278. * range that the format allows.
  86279. *
  86280. * Make sure you know what it entails before setting this to \c false.
  86281. *
  86282. * \default \c true
  86283. * \param encoder An encoder instance to set.
  86284. * \param value Flag value (see above).
  86285. * \assert
  86286. * \code encoder != NULL \endcode
  86287. * \retval FLAC__bool
  86288. * \c false if the encoder is already initialized, else \c true.
  86289. */
  86290. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86291. /** Set the number of channels to be encoded.
  86292. *
  86293. * \default \c 2
  86294. * \param encoder An encoder instance to set.
  86295. * \param value See above.
  86296. * \assert
  86297. * \code encoder != NULL \endcode
  86298. * \retval FLAC__bool
  86299. * \c false if the encoder is already initialized, else \c true.
  86300. */
  86301. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  86302. /** Set the sample resolution of the input to be encoded.
  86303. *
  86304. * \warning
  86305. * Do not feed the encoder data that is wider than the value you
  86306. * set here or you will generate an invalid stream.
  86307. *
  86308. * \default \c 16
  86309. * \param encoder An encoder instance to set.
  86310. * \param value See above.
  86311. * \assert
  86312. * \code encoder != NULL \endcode
  86313. * \retval FLAC__bool
  86314. * \c false if the encoder is already initialized, else \c true.
  86315. */
  86316. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  86317. /** Set the sample rate (in Hz) of the input to be encoded.
  86318. *
  86319. * \default \c 44100
  86320. * \param encoder An encoder instance to set.
  86321. * \param value See above.
  86322. * \assert
  86323. * \code encoder != NULL \endcode
  86324. * \retval FLAC__bool
  86325. * \c false if the encoder is already initialized, else \c true.
  86326. */
  86327. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  86328. /** Set the compression level
  86329. *
  86330. * The compression level is roughly proportional to the amount of effort
  86331. * the encoder expends to compress the file. A higher level usually
  86332. * means more computation but higher compression. The default level is
  86333. * suitable for most applications.
  86334. *
  86335. * Currently the levels range from \c 0 (fastest, least compression) to
  86336. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  86337. * treated as \c 8.
  86338. *
  86339. * This function automatically calls the following other \c _set_
  86340. * functions with appropriate values, so the client does not need to
  86341. * unless it specifically wants to override them:
  86342. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  86343. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  86344. * - FLAC__stream_encoder_set_apodization()
  86345. * - FLAC__stream_encoder_set_max_lpc_order()
  86346. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  86347. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  86348. * - FLAC__stream_encoder_set_do_escape_coding()
  86349. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  86350. * - FLAC__stream_encoder_set_min_residual_partition_order()
  86351. * - FLAC__stream_encoder_set_max_residual_partition_order()
  86352. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  86353. *
  86354. * The actual values set for each level are:
  86355. * <table>
  86356. * <tr>
  86357. * <td><b>level</b><td>
  86358. * <td>do mid-side stereo<td>
  86359. * <td>loose mid-side stereo<td>
  86360. * <td>apodization<td>
  86361. * <td>max lpc order<td>
  86362. * <td>qlp coeff precision<td>
  86363. * <td>qlp coeff prec search<td>
  86364. * <td>escape coding<td>
  86365. * <td>exhaustive model search<td>
  86366. * <td>min residual partition order<td>
  86367. * <td>max residual partition order<td>
  86368. * <td>rice parameter search dist<td>
  86369. * </tr>
  86370. * <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>
  86371. * <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>
  86372. * <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>
  86373. * <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>
  86374. * <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>
  86375. * <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>
  86376. * <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>
  86377. * <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>
  86378. * <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>
  86379. * </table>
  86380. *
  86381. * \default \c 5
  86382. * \param encoder An encoder instance to set.
  86383. * \param value See above.
  86384. * \assert
  86385. * \code encoder != NULL \endcode
  86386. * \retval FLAC__bool
  86387. * \c false if the encoder is already initialized, else \c true.
  86388. */
  86389. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  86390. /** Set the blocksize to use while encoding.
  86391. *
  86392. * The number of samples to use per frame. Use \c 0 to let the encoder
  86393. * estimate a blocksize; this is usually best.
  86394. *
  86395. * \default \c 0
  86396. * \param encoder An encoder instance to set.
  86397. * \param value See above.
  86398. * \assert
  86399. * \code encoder != NULL \endcode
  86400. * \retval FLAC__bool
  86401. * \c false if the encoder is already initialized, else \c true.
  86402. */
  86403. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  86404. /** Set to \c true to enable mid-side encoding on stereo input. The
  86405. * number of channels must be 2 for this to have any effect. Set to
  86406. * \c false to use only independent channel coding.
  86407. *
  86408. * \default \c false
  86409. * \param encoder An encoder instance to set.
  86410. * \param value Flag value (see above).
  86411. * \assert
  86412. * \code encoder != NULL \endcode
  86413. * \retval FLAC__bool
  86414. * \c false if the encoder is already initialized, else \c true.
  86415. */
  86416. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86417. /** Set to \c true to enable adaptive switching between mid-side and
  86418. * left-right encoding on stereo input. Set to \c false to use
  86419. * exhaustive searching. Setting this to \c true requires
  86420. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  86421. * \c true in order to have any effect.
  86422. *
  86423. * \default \c false
  86424. * \param encoder An encoder instance to set.
  86425. * \param value Flag value (see above).
  86426. * \assert
  86427. * \code encoder != NULL \endcode
  86428. * \retval FLAC__bool
  86429. * \c false if the encoder is already initialized, else \c true.
  86430. */
  86431. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86432. /** Sets the apodization function(s) the encoder will use when windowing
  86433. * audio data for LPC analysis.
  86434. *
  86435. * The \a specification is a plain ASCII string which specifies exactly
  86436. * which functions to use. There may be more than one (up to 32),
  86437. * separated by \c ';' characters. Some functions take one or more
  86438. * comma-separated arguments in parentheses.
  86439. *
  86440. * The available functions are \c bartlett, \c bartlett_hann,
  86441. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  86442. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  86443. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  86444. *
  86445. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  86446. * (0<STDDEV<=0.5).
  86447. *
  86448. * For \c tukey(P), P specifies the fraction of the window that is
  86449. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  86450. * corresponds to \c hann.
  86451. *
  86452. * Example specifications are \c "blackman" or
  86453. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  86454. *
  86455. * Any function that is specified erroneously is silently dropped. Up
  86456. * to 32 functions are kept, the rest are dropped. If the specification
  86457. * is empty the encoder defaults to \c "tukey(0.5)".
  86458. *
  86459. * When more than one function is specified, then for every subframe the
  86460. * encoder will try each of them separately and choose the window that
  86461. * results in the smallest compressed subframe.
  86462. *
  86463. * Note that each function specified causes the encoder to occupy a
  86464. * floating point array in which to store the window.
  86465. *
  86466. * \default \c "tukey(0.5)"
  86467. * \param encoder An encoder instance to set.
  86468. * \param specification See above.
  86469. * \assert
  86470. * \code encoder != NULL \endcode
  86471. * \code specification != NULL \endcode
  86472. * \retval FLAC__bool
  86473. * \c false if the encoder is already initialized, else \c true.
  86474. */
  86475. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  86476. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  86477. *
  86478. * \default \c 0
  86479. * \param encoder An encoder instance to set.
  86480. * \param value See above.
  86481. * \assert
  86482. * \code encoder != NULL \endcode
  86483. * \retval FLAC__bool
  86484. * \c false if the encoder is already initialized, else \c true.
  86485. */
  86486. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  86487. /** Set the precision, in bits, of the quantized linear predictor
  86488. * coefficients, or \c 0 to let the encoder select it based on the
  86489. * blocksize.
  86490. *
  86491. * \note
  86492. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  86493. * be less than 32.
  86494. *
  86495. * \default \c 0
  86496. * \param encoder An encoder instance to set.
  86497. * \param value See above.
  86498. * \assert
  86499. * \code encoder != NULL \endcode
  86500. * \retval FLAC__bool
  86501. * \c false if the encoder is already initialized, else \c true.
  86502. */
  86503. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  86504. /** Set to \c false to use only the specified quantized linear predictor
  86505. * coefficient precision, or \c true to search neighboring precision
  86506. * values and use the best one.
  86507. *
  86508. * \default \c false
  86509. * \param encoder An encoder instance to set.
  86510. * \param value See above.
  86511. * \assert
  86512. * \code encoder != NULL \endcode
  86513. * \retval FLAC__bool
  86514. * \c false if the encoder is already initialized, else \c true.
  86515. */
  86516. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86517. /** Deprecated. Setting this value has no effect.
  86518. *
  86519. * \default \c false
  86520. * \param encoder An encoder instance to set.
  86521. * \param value See above.
  86522. * \assert
  86523. * \code encoder != NULL \endcode
  86524. * \retval FLAC__bool
  86525. * \c false if the encoder is already initialized, else \c true.
  86526. */
  86527. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86528. /** Set to \c false to let the encoder estimate the best model order
  86529. * based on the residual signal energy, or \c true to force the
  86530. * encoder to evaluate all order models and select the best.
  86531. *
  86532. * \default \c false
  86533. * \param encoder An encoder instance to set.
  86534. * \param value See above.
  86535. * \assert
  86536. * \code encoder != NULL \endcode
  86537. * \retval FLAC__bool
  86538. * \c false if the encoder is already initialized, else \c true.
  86539. */
  86540. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86541. /** Set the minimum partition order to search when coding the residual.
  86542. * This is used in tandem with
  86543. * FLAC__stream_encoder_set_max_residual_partition_order().
  86544. *
  86545. * The partition order determines the context size in the residual.
  86546. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  86547. *
  86548. * Set both min and max values to \c 0 to force a single context,
  86549. * whose Rice parameter is based on the residual signal variance.
  86550. * Otherwise, set a min and max order, and the encoder will search
  86551. * all orders, using the mean of each context for its Rice parameter,
  86552. * and use the best.
  86553. *
  86554. * \default \c 0
  86555. * \param encoder An encoder instance to set.
  86556. * \param value See above.
  86557. * \assert
  86558. * \code encoder != NULL \endcode
  86559. * \retval FLAC__bool
  86560. * \c false if the encoder is already initialized, else \c true.
  86561. */
  86562. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  86563. /** Set the maximum partition order to search when coding the residual.
  86564. * This is used in tandem with
  86565. * FLAC__stream_encoder_set_min_residual_partition_order().
  86566. *
  86567. * The partition order determines the context size in the residual.
  86568. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  86569. *
  86570. * Set both min and max values to \c 0 to force a single context,
  86571. * whose Rice parameter is based on the residual signal variance.
  86572. * Otherwise, set a min and max order, and the encoder will search
  86573. * all orders, using the mean of each context for its Rice parameter,
  86574. * and use the best.
  86575. *
  86576. * \default \c 0
  86577. * \param encoder An encoder instance to set.
  86578. * \param value See above.
  86579. * \assert
  86580. * \code encoder != NULL \endcode
  86581. * \retval FLAC__bool
  86582. * \c false if the encoder is already initialized, else \c true.
  86583. */
  86584. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  86585. /** Deprecated. Setting this value has no effect.
  86586. *
  86587. * \default \c 0
  86588. * \param encoder An encoder instance to set.
  86589. * \param value See above.
  86590. * \assert
  86591. * \code encoder != NULL \endcode
  86592. * \retval FLAC__bool
  86593. * \c false if the encoder is already initialized, else \c true.
  86594. */
  86595. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  86596. /** Set an estimate of the total samples that will be encoded.
  86597. * This is merely an estimate and may be set to \c 0 if unknown.
  86598. * This value will be written to the STREAMINFO block before encoding,
  86599. * and can remove the need for the caller to rewrite the value later
  86600. * if the value is known before encoding.
  86601. *
  86602. * \default \c 0
  86603. * \param encoder An encoder instance to set.
  86604. * \param value See above.
  86605. * \assert
  86606. * \code encoder != NULL \endcode
  86607. * \retval FLAC__bool
  86608. * \c false if the encoder is already initialized, else \c true.
  86609. */
  86610. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  86611. /** Set the metadata blocks to be emitted to the stream before encoding.
  86612. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  86613. * array of pointers to metadata blocks. The array is non-const since
  86614. * the encoder may need to change the \a is_last flag inside them, and
  86615. * in some cases update seek point offsets. Otherwise, the encoder will
  86616. * not modify or free the blocks. It is up to the caller to free the
  86617. * metadata blocks after encoding finishes.
  86618. *
  86619. * \note
  86620. * The encoder stores only copies of the pointers in the \a metadata array;
  86621. * the metadata blocks themselves must survive at least until after
  86622. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  86623. *
  86624. * \note
  86625. * The STREAMINFO block is always written and no STREAMINFO block may
  86626. * occur in the supplied array.
  86627. *
  86628. * \note
  86629. * By default the encoder does not create a SEEKTABLE. If one is supplied
  86630. * in the \a metadata array, but the client has specified that it does not
  86631. * support seeking, then the SEEKTABLE will be written verbatim. However
  86632. * by itself this is not very useful as the client will not know the stream
  86633. * offsets for the seekpoints ahead of time. In order to get a proper
  86634. * seektable the client must support seeking. See next note.
  86635. *
  86636. * \note
  86637. * SEEKTABLE blocks are handled specially. Since you will not know
  86638. * the values for the seek point stream offsets, you should pass in
  86639. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  86640. * required sample numbers (or placeholder points), with \c 0 for the
  86641. * \a frame_samples and \a stream_offset fields for each point. If the
  86642. * client has specified that it supports seeking by providing a seek
  86643. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  86644. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  86645. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  86646. * then while it is encoding the encoder will fill the stream offsets in
  86647. * for you and when encoding is finished, it will seek back and write the
  86648. * real values into the SEEKTABLE block in the stream. There are helper
  86649. * routines for manipulating seektable template blocks; see metadata.h:
  86650. * FLAC__metadata_object_seektable_template_*(). If the client does
  86651. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  86652. * will slow down or remove the ability to seek in the FLAC stream.
  86653. *
  86654. * \note
  86655. * The encoder instance \b will modify the first \c SEEKTABLE block
  86656. * as it transforms the template to a valid seektable while encoding,
  86657. * but it is still up to the caller to free all metadata blocks after
  86658. * encoding.
  86659. *
  86660. * \note
  86661. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  86662. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  86663. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  86664. * will simply write it's own into the stream. If no VORBIS_COMMENT
  86665. * block is present in the \a metadata array, libFLAC will write an
  86666. * empty one, containing only the vendor string.
  86667. *
  86668. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  86669. * the second metadata block of the stream. The encoder already supplies
  86670. * the STREAMINFO block automatically. If \a metadata does not contain a
  86671. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  86672. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  86673. * first, the init function will reorder \a metadata by moving the
  86674. * VORBIS_COMMENT block to the front; the relative ordering of the other
  86675. * blocks will remain as they were.
  86676. *
  86677. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  86678. * stream to \c 65535. If \a num_blocks exceeds this the function will
  86679. * return \c false.
  86680. *
  86681. * \default \c NULL, 0
  86682. * \param encoder An encoder instance to set.
  86683. * \param metadata See above.
  86684. * \param num_blocks See above.
  86685. * \assert
  86686. * \code encoder != NULL \endcode
  86687. * \retval FLAC__bool
  86688. * \c false if the encoder is already initialized, else \c true.
  86689. * \c false if the encoder is already initialized, or if
  86690. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  86691. */
  86692. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  86693. /** Get the current encoder state.
  86694. *
  86695. * \param encoder An encoder instance to query.
  86696. * \assert
  86697. * \code encoder != NULL \endcode
  86698. * \retval FLAC__StreamEncoderState
  86699. * The current encoder state.
  86700. */
  86701. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  86702. /** Get the state of the verify stream decoder.
  86703. * Useful when the stream encoder state is
  86704. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  86705. *
  86706. * \param encoder An encoder instance to query.
  86707. * \assert
  86708. * \code encoder != NULL \endcode
  86709. * \retval FLAC__StreamDecoderState
  86710. * The verify stream decoder state.
  86711. */
  86712. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  86713. /** Get the current encoder state as a C string.
  86714. * This version automatically resolves
  86715. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  86716. * verify decoder's state.
  86717. *
  86718. * \param encoder A encoder instance to query.
  86719. * \assert
  86720. * \code encoder != NULL \endcode
  86721. * \retval const char *
  86722. * The encoder state as a C string. Do not modify the contents.
  86723. */
  86724. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  86725. /** Get relevant values about the nature of a verify decoder error.
  86726. * Useful when the stream encoder state is
  86727. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  86728. * be addresses in which the stats will be returned, or NULL if value
  86729. * is not desired.
  86730. *
  86731. * \param encoder An encoder instance to query.
  86732. * \param absolute_sample The absolute sample number of the mismatch.
  86733. * \param frame_number The number of the frame in which the mismatch occurred.
  86734. * \param channel The channel in which the mismatch occurred.
  86735. * \param sample The number of the sample (relative to the frame) in
  86736. * which the mismatch occurred.
  86737. * \param expected The expected value for the sample in question.
  86738. * \param got The actual value returned by the decoder.
  86739. * \assert
  86740. * \code encoder != NULL \endcode
  86741. */
  86742. 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);
  86743. /** Get the "verify" flag.
  86744. *
  86745. * \param encoder An encoder instance to query.
  86746. * \assert
  86747. * \code encoder != NULL \endcode
  86748. * \retval FLAC__bool
  86749. * See FLAC__stream_encoder_set_verify().
  86750. */
  86751. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  86752. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  86753. *
  86754. * \param encoder An encoder instance to query.
  86755. * \assert
  86756. * \code encoder != NULL \endcode
  86757. * \retval FLAC__bool
  86758. * See FLAC__stream_encoder_set_streamable_subset().
  86759. */
  86760. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  86761. /** Get the number of input channels being processed.
  86762. *
  86763. * \param encoder An encoder instance to query.
  86764. * \assert
  86765. * \code encoder != NULL \endcode
  86766. * \retval unsigned
  86767. * See FLAC__stream_encoder_set_channels().
  86768. */
  86769. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  86770. /** Get the input sample resolution setting.
  86771. *
  86772. * \param encoder An encoder instance to query.
  86773. * \assert
  86774. * \code encoder != NULL \endcode
  86775. * \retval unsigned
  86776. * See FLAC__stream_encoder_set_bits_per_sample().
  86777. */
  86778. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  86779. /** Get the input sample rate setting.
  86780. *
  86781. * \param encoder An encoder instance to query.
  86782. * \assert
  86783. * \code encoder != NULL \endcode
  86784. * \retval unsigned
  86785. * See FLAC__stream_encoder_set_sample_rate().
  86786. */
  86787. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  86788. /** Get the blocksize setting.
  86789. *
  86790. * \param encoder An encoder instance to query.
  86791. * \assert
  86792. * \code encoder != NULL \endcode
  86793. * \retval unsigned
  86794. * See FLAC__stream_encoder_set_blocksize().
  86795. */
  86796. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  86797. /** Get the "mid/side stereo coding" flag.
  86798. *
  86799. * \param encoder An encoder instance to query.
  86800. * \assert
  86801. * \code encoder != NULL \endcode
  86802. * \retval FLAC__bool
  86803. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  86804. */
  86805. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  86806. /** Get the "adaptive mid/side switching" flag.
  86807. *
  86808. * \param encoder An encoder instance to query.
  86809. * \assert
  86810. * \code encoder != NULL \endcode
  86811. * \retval FLAC__bool
  86812. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  86813. */
  86814. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  86815. /** Get the maximum LPC order setting.
  86816. *
  86817. * \param encoder An encoder instance to query.
  86818. * \assert
  86819. * \code encoder != NULL \endcode
  86820. * \retval unsigned
  86821. * See FLAC__stream_encoder_set_max_lpc_order().
  86822. */
  86823. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  86824. /** Get the quantized linear predictor coefficient precision setting.
  86825. *
  86826. * \param encoder An encoder instance to query.
  86827. * \assert
  86828. * \code encoder != NULL \endcode
  86829. * \retval unsigned
  86830. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  86831. */
  86832. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  86833. /** Get the qlp coefficient precision search flag.
  86834. *
  86835. * \param encoder An encoder instance to query.
  86836. * \assert
  86837. * \code encoder != NULL \endcode
  86838. * \retval FLAC__bool
  86839. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  86840. */
  86841. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  86842. /** Get the "escape coding" flag.
  86843. *
  86844. * \param encoder An encoder instance to query.
  86845. * \assert
  86846. * \code encoder != NULL \endcode
  86847. * \retval FLAC__bool
  86848. * See FLAC__stream_encoder_set_do_escape_coding().
  86849. */
  86850. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  86851. /** Get the exhaustive model search flag.
  86852. *
  86853. * \param encoder An encoder instance to query.
  86854. * \assert
  86855. * \code encoder != NULL \endcode
  86856. * \retval FLAC__bool
  86857. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  86858. */
  86859. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  86860. /** Get the minimum residual partition order setting.
  86861. *
  86862. * \param encoder An encoder instance to query.
  86863. * \assert
  86864. * \code encoder != NULL \endcode
  86865. * \retval unsigned
  86866. * See FLAC__stream_encoder_set_min_residual_partition_order().
  86867. */
  86868. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  86869. /** Get maximum residual partition order setting.
  86870. *
  86871. * \param encoder An encoder instance to query.
  86872. * \assert
  86873. * \code encoder != NULL \endcode
  86874. * \retval unsigned
  86875. * See FLAC__stream_encoder_set_max_residual_partition_order().
  86876. */
  86877. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  86878. /** Get the Rice parameter search distance setting.
  86879. *
  86880. * \param encoder An encoder instance to query.
  86881. * \assert
  86882. * \code encoder != NULL \endcode
  86883. * \retval unsigned
  86884. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  86885. */
  86886. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  86887. /** Get the previously set estimate of the total samples to be encoded.
  86888. * The encoder merely mimics back the value given to
  86889. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  86890. * other way of knowing how many samples the client will encode.
  86891. *
  86892. * \param encoder An encoder instance to set.
  86893. * \assert
  86894. * \code encoder != NULL \endcode
  86895. * \retval FLAC__uint64
  86896. * See FLAC__stream_encoder_get_total_samples_estimate().
  86897. */
  86898. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  86899. /** Initialize the encoder instance to encode native FLAC streams.
  86900. *
  86901. * This flavor of initialization sets up the encoder to encode to a
  86902. * native FLAC stream. I/O is performed via callbacks to the client.
  86903. * For encoding to a plain file via filename or open \c FILE*,
  86904. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  86905. * provide a simpler interface.
  86906. *
  86907. * This function should be called after FLAC__stream_encoder_new() and
  86908. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86909. * or FLAC__stream_encoder_process_interleaved().
  86910. * initialization succeeded.
  86911. *
  86912. * The call to FLAC__stream_encoder_init_stream() currently will also
  86913. * immediately call the write callback several times, once with the \c fLaC
  86914. * signature, and once for each encoded metadata block.
  86915. *
  86916. * \param encoder An uninitialized encoder instance.
  86917. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  86918. * pointer must not be \c NULL.
  86919. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  86920. * pointer may be \c NULL if seeking is not
  86921. * supported. The encoder uses seeking to go back
  86922. * and write some some stream statistics to the
  86923. * STREAMINFO block; this is recommended but not
  86924. * necessary to create a valid FLAC stream. If
  86925. * \a seek_callback is not \c NULL then a
  86926. * \a tell_callback must also be supplied.
  86927. * Alternatively, a dummy seek callback that just
  86928. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86929. * may also be supplied, all though this is slightly
  86930. * less efficient for the encoder.
  86931. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  86932. * pointer may be \c NULL if seeking is not
  86933. * supported. If \a seek_callback is \c NULL then
  86934. * this argument will be ignored. If
  86935. * \a seek_callback is not \c NULL then a
  86936. * \a tell_callback must also be supplied.
  86937. * Alternatively, a dummy tell callback that just
  86938. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  86939. * may also be supplied, all though this is slightly
  86940. * less efficient for the encoder.
  86941. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  86942. * pointer may be \c NULL if the callback is not
  86943. * desired. If the client provides a seek callback,
  86944. * this function is not necessary as the encoder
  86945. * will automatically seek back and update the
  86946. * STREAMINFO block. It may also be \c NULL if the
  86947. * client does not support seeking, since it will
  86948. * have no way of going back to update the
  86949. * STREAMINFO. However the client can still supply
  86950. * a callback if it would like to know the details
  86951. * from the STREAMINFO.
  86952. * \param client_data This value will be supplied to callbacks in their
  86953. * \a client_data argument.
  86954. * \assert
  86955. * \code encoder != NULL \endcode
  86956. * \retval FLAC__StreamEncoderInitStatus
  86957. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86958. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86959. */
  86960. 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);
  86961. /** Initialize the encoder instance to encode Ogg FLAC streams.
  86962. *
  86963. * This flavor of initialization sets up the encoder to encode to a FLAC
  86964. * stream in an Ogg container. I/O is performed via callbacks to the
  86965. * client. For encoding to a plain file via filename or open \c FILE*,
  86966. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  86967. * provide a simpler interface.
  86968. *
  86969. * This function should be called after FLAC__stream_encoder_new() and
  86970. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86971. * or FLAC__stream_encoder_process_interleaved().
  86972. * initialization succeeded.
  86973. *
  86974. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  86975. * immediately call the write callback several times to write the metadata
  86976. * packets.
  86977. *
  86978. * \param encoder An uninitialized encoder instance.
  86979. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  86980. * pointer must not be \c NULL if \a seek_callback
  86981. * is non-NULL since they are both needed to be
  86982. * able to write data back to the Ogg FLAC stream
  86983. * in the post-encode phase.
  86984. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  86985. * pointer must not be \c NULL.
  86986. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  86987. * pointer may be \c NULL if seeking is not
  86988. * supported. The encoder uses seeking to go back
  86989. * and write some some stream statistics to the
  86990. * STREAMINFO block; this is recommended but not
  86991. * necessary to create a valid FLAC stream. If
  86992. * \a seek_callback is not \c NULL then a
  86993. * \a tell_callback must also be supplied.
  86994. * Alternatively, a dummy seek callback that just
  86995. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86996. * may also be supplied, all though this is slightly
  86997. * less efficient for the encoder.
  86998. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  86999. * pointer may be \c NULL if seeking is not
  87000. * supported. If \a seek_callback is \c NULL then
  87001. * this argument will be ignored. If
  87002. * \a seek_callback is not \c NULL then a
  87003. * \a tell_callback must also be supplied.
  87004. * Alternatively, a dummy tell callback that just
  87005. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  87006. * may also be supplied, all though this is slightly
  87007. * less efficient for the encoder.
  87008. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  87009. * pointer may be \c NULL if the callback is not
  87010. * desired. If the client provides a seek callback,
  87011. * this function is not necessary as the encoder
  87012. * will automatically seek back and update the
  87013. * STREAMINFO block. It may also be \c NULL if the
  87014. * client does not support seeking, since it will
  87015. * have no way of going back to update the
  87016. * STREAMINFO. However the client can still supply
  87017. * a callback if it would like to know the details
  87018. * from the STREAMINFO.
  87019. * \param client_data This value will be supplied to callbacks in their
  87020. * \a client_data argument.
  87021. * \assert
  87022. * \code encoder != NULL \endcode
  87023. * \retval FLAC__StreamEncoderInitStatus
  87024. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87025. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87026. */
  87027. 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);
  87028. /** Initialize the encoder instance to encode native FLAC files.
  87029. *
  87030. * This flavor of initialization sets up the encoder to encode to a
  87031. * plain native FLAC file. For non-stdio streams, you must use
  87032. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  87033. *
  87034. * This function should be called after FLAC__stream_encoder_new() and
  87035. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87036. * or FLAC__stream_encoder_process_interleaved().
  87037. * initialization succeeded.
  87038. *
  87039. * \param encoder An uninitialized encoder instance.
  87040. * \param file An open file. The file should have been opened
  87041. * with mode \c "w+b" and rewound. The file
  87042. * becomes owned by the encoder and should not be
  87043. * manipulated by the client while encoding.
  87044. * Unless \a file is \c stdout, it will be closed
  87045. * when FLAC__stream_encoder_finish() is called.
  87046. * Note however that a proper SEEKTABLE cannot be
  87047. * created when encoding to \c stdout since it is
  87048. * not seekable.
  87049. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87050. * pointer may be \c NULL if the callback is not
  87051. * desired.
  87052. * \param client_data This value will be supplied to callbacks in their
  87053. * \a client_data argument.
  87054. * \assert
  87055. * \code encoder != NULL \endcode
  87056. * \code file != NULL \endcode
  87057. * \retval FLAC__StreamEncoderInitStatus
  87058. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87059. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87060. */
  87061. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87062. /** Initialize the encoder instance to encode Ogg FLAC files.
  87063. *
  87064. * This flavor of initialization sets up the encoder to encode to a
  87065. * plain Ogg FLAC file. For non-stdio streams, you must use
  87066. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  87067. *
  87068. * This function should be called after FLAC__stream_encoder_new() and
  87069. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87070. * or FLAC__stream_encoder_process_interleaved().
  87071. * initialization succeeded.
  87072. *
  87073. * \param encoder An uninitialized encoder instance.
  87074. * \param file An open file. The file should have been opened
  87075. * with mode \c "w+b" and rewound. The file
  87076. * becomes owned by the encoder and should not be
  87077. * manipulated by the client while encoding.
  87078. * Unless \a file is \c stdout, it will be closed
  87079. * when FLAC__stream_encoder_finish() is called.
  87080. * Note however that a proper SEEKTABLE cannot be
  87081. * created when encoding to \c stdout since it is
  87082. * not seekable.
  87083. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87084. * pointer may be \c NULL if the callback is not
  87085. * desired.
  87086. * \param client_data This value will be supplied to callbacks in their
  87087. * \a client_data argument.
  87088. * \assert
  87089. * \code encoder != NULL \endcode
  87090. * \code file != NULL \endcode
  87091. * \retval FLAC__StreamEncoderInitStatus
  87092. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87093. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87094. */
  87095. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87096. /** Initialize the encoder instance to encode native FLAC files.
  87097. *
  87098. * This flavor of initialization sets up the encoder to encode to a plain
  87099. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  87100. * with Unicode filenames on Windows), you must use
  87101. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  87102. * and provide callbacks for the I/O.
  87103. *
  87104. * This function should be called after FLAC__stream_encoder_new() and
  87105. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87106. * or FLAC__stream_encoder_process_interleaved().
  87107. * initialization succeeded.
  87108. *
  87109. * \param encoder An uninitialized encoder instance.
  87110. * \param filename The name of the file to encode to. The file will
  87111. * be opened with fopen(). Use \c NULL to encode to
  87112. * \c stdout. Note however that a proper SEEKTABLE
  87113. * cannot be created when encoding to \c stdout since
  87114. * it is not seekable.
  87115. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87116. * pointer may be \c NULL if the callback is not
  87117. * desired.
  87118. * \param client_data This value will be supplied to callbacks in their
  87119. * \a client_data argument.
  87120. * \assert
  87121. * \code encoder != NULL \endcode
  87122. * \retval FLAC__StreamEncoderInitStatus
  87123. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87124. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87125. */
  87126. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87127. /** Initialize the encoder instance to encode Ogg FLAC files.
  87128. *
  87129. * This flavor of initialization sets up the encoder to encode to a plain
  87130. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  87131. * with Unicode filenames on Windows), you must use
  87132. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  87133. * and provide callbacks for the I/O.
  87134. *
  87135. * This function should be called after FLAC__stream_encoder_new() and
  87136. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87137. * or FLAC__stream_encoder_process_interleaved().
  87138. * initialization succeeded.
  87139. *
  87140. * \param encoder An uninitialized encoder instance.
  87141. * \param filename The name of the file to encode to. The file will
  87142. * be opened with fopen(). Use \c NULL to encode to
  87143. * \c stdout. Note however that a proper SEEKTABLE
  87144. * cannot be created when encoding to \c stdout since
  87145. * it is not seekable.
  87146. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87147. * pointer may be \c NULL if the callback is not
  87148. * desired.
  87149. * \param client_data This value will be supplied to callbacks in their
  87150. * \a client_data argument.
  87151. * \assert
  87152. * \code encoder != NULL \endcode
  87153. * \retval FLAC__StreamEncoderInitStatus
  87154. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87155. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87156. */
  87157. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87158. /** Finish the encoding process.
  87159. * Flushes the encoding buffer, releases resources, resets the encoder
  87160. * settings to their defaults, and returns the encoder state to
  87161. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  87162. * one or more write callbacks before returning, and will generate
  87163. * a metadata callback.
  87164. *
  87165. * Note that in the course of processing the last frame, errors can
  87166. * occur, so the caller should be sure to check the return value to
  87167. * ensure the file was encoded properly.
  87168. *
  87169. * In the event of a prematurely-terminated encode, it is not strictly
  87170. * necessary to call this immediately before FLAC__stream_encoder_delete()
  87171. * but it is good practice to match every FLAC__stream_encoder_init_*()
  87172. * with a FLAC__stream_encoder_finish().
  87173. *
  87174. * \param encoder An uninitialized encoder instance.
  87175. * \assert
  87176. * \code encoder != NULL \endcode
  87177. * \retval FLAC__bool
  87178. * \c false if an error occurred processing the last frame; or if verify
  87179. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  87180. * verify mismatch; else \c true. If \c false, caller should check the
  87181. * state with FLAC__stream_encoder_get_state() for more information
  87182. * about the error.
  87183. */
  87184. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  87185. /** Submit data for encoding.
  87186. * This version allows you to supply the input data via an array of
  87187. * pointers, each pointer pointing to an array of \a samples samples
  87188. * representing one channel. The samples need not be block-aligned,
  87189. * but each channel should have the same number of samples. Each sample
  87190. * should be a signed integer, right-justified to the resolution set by
  87191. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  87192. * resolution is 16 bits per sample, the samples should all be in the
  87193. * range [-32768,32767].
  87194. *
  87195. * For applications where channel order is important, channels must
  87196. * follow the order as described in the
  87197. * <A HREF="../format.html#frame_header">frame header</A>.
  87198. *
  87199. * \param encoder An initialized encoder instance in the OK state.
  87200. * \param buffer An array of pointers to each channel's signal.
  87201. * \param samples The number of samples in one channel.
  87202. * \assert
  87203. * \code encoder != NULL \endcode
  87204. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  87205. * \retval FLAC__bool
  87206. * \c true if successful, else \c false; in this case, check the
  87207. * encoder state with FLAC__stream_encoder_get_state() to see what
  87208. * went wrong.
  87209. */
  87210. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  87211. /** Submit data for encoding.
  87212. * This version allows you to supply the input data where the channels
  87213. * are interleaved into a single array (i.e. channel0_sample0,
  87214. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  87215. * The samples need not be block-aligned but they must be
  87216. * sample-aligned, i.e. the first value should be channel0_sample0
  87217. * and the last value channelN_sampleM. Each sample should be a signed
  87218. * integer, right-justified to the resolution set by
  87219. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  87220. * resolution is 16 bits per sample, the samples should all be in the
  87221. * range [-32768,32767].
  87222. *
  87223. * For applications where channel order is important, channels must
  87224. * follow the order as described in the
  87225. * <A HREF="../format.html#frame_header">frame header</A>.
  87226. *
  87227. * \param encoder An initialized encoder instance in the OK state.
  87228. * \param buffer An array of channel-interleaved data (see above).
  87229. * \param samples The number of samples in one channel, the same as for
  87230. * FLAC__stream_encoder_process(). For example, if
  87231. * encoding two channels, \c 1000 \a samples corresponds
  87232. * to a \a buffer of 2000 values.
  87233. * \assert
  87234. * \code encoder != NULL \endcode
  87235. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  87236. * \retval FLAC__bool
  87237. * \c true if successful, else \c false; in this case, check the
  87238. * encoder state with FLAC__stream_encoder_get_state() to see what
  87239. * went wrong.
  87240. */
  87241. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  87242. /* \} */
  87243. #ifdef __cplusplus
  87244. }
  87245. #endif
  87246. #endif
  87247. /********* End of inlined file: stream_encoder.h *********/
  87248. #ifdef _MSC_VER
  87249. /* OPT: an MSVC built-in would be better */
  87250. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  87251. {
  87252. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  87253. return (x>>16) | (x<<16);
  87254. }
  87255. #endif
  87256. #if defined(_MSC_VER) && defined(_X86_)
  87257. /* OPT: an MSVC built-in would be better */
  87258. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  87259. {
  87260. __asm {
  87261. mov edx, start
  87262. mov ecx, len
  87263. test ecx, ecx
  87264. loop1:
  87265. jz done1
  87266. mov eax, [edx]
  87267. bswap eax
  87268. mov [edx], eax
  87269. add edx, 4
  87270. dec ecx
  87271. jmp short loop1
  87272. done1:
  87273. }
  87274. }
  87275. #endif
  87276. /** \mainpage
  87277. *
  87278. * \section intro Introduction
  87279. *
  87280. * This is the documentation for the FLAC C and C++ APIs. It is
  87281. * highly interconnected; this introduction should give you a top
  87282. * level idea of the structure and how to find the information you
  87283. * need. As a prerequisite you should have at least a basic
  87284. * knowledge of the FLAC format, documented
  87285. * <A HREF="../format.html">here</A>.
  87286. *
  87287. * \section c_api FLAC C API
  87288. *
  87289. * The FLAC C API is the interface to libFLAC, a set of structures
  87290. * describing the components of FLAC streams, and functions for
  87291. * encoding and decoding streams, as well as manipulating FLAC
  87292. * metadata in files. The public include files will be installed
  87293. * in your include area (for example /usr/include/FLAC/...).
  87294. *
  87295. * By writing a little code and linking against libFLAC, it is
  87296. * relatively easy to add FLAC support to another program. The
  87297. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  87298. * Complete source code of libFLAC as well as the command-line
  87299. * encoder and plugins is available and is a useful source of
  87300. * examples.
  87301. *
  87302. * Aside from encoders and decoders, libFLAC provides a powerful
  87303. * metadata interface for manipulating metadata in FLAC files. It
  87304. * allows the user to add, delete, and modify FLAC metadata blocks
  87305. * and it can automatically take advantage of PADDING blocks to avoid
  87306. * rewriting the entire FLAC file when changing the size of the
  87307. * metadata.
  87308. *
  87309. * libFLAC usually only requires the standard C library and C math
  87310. * library. In particular, threading is not used so there is no
  87311. * dependency on a thread library. However, libFLAC does not use
  87312. * global variables and should be thread-safe.
  87313. *
  87314. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  87315. * However the metadata editing interfaces currently have limited
  87316. * read-only support for Ogg FLAC files.
  87317. *
  87318. * \section cpp_api FLAC C++ API
  87319. *
  87320. * The FLAC C++ API is a set of classes that encapsulate the
  87321. * structures and functions in libFLAC. They provide slightly more
  87322. * functionality with respect to metadata but are otherwise
  87323. * equivalent. For the most part, they share the same usage as
  87324. * their counterparts in libFLAC, and the FLAC C API documentation
  87325. * can be used as a supplement. The public include files
  87326. * for the C++ API will be installed in your include area (for
  87327. * example /usr/include/FLAC++/...).
  87328. *
  87329. * libFLAC++ is also licensed under
  87330. * <A HREF="../license.html">Xiph's BSD license</A>.
  87331. *
  87332. * \section getting_started Getting Started
  87333. *
  87334. * A good starting point for learning the API is to browse through
  87335. * the <A HREF="modules.html">modules</A>. Modules are logical
  87336. * groupings of related functions or classes, which correspond roughly
  87337. * to header files or sections of header files. Each module includes a
  87338. * detailed description of the general usage of its functions or
  87339. * classes.
  87340. *
  87341. * From there you can go on to look at the documentation of
  87342. * individual functions. You can see different views of the individual
  87343. * functions through the links in top bar across this page.
  87344. *
  87345. * If you prefer a more hands-on approach, you can jump right to some
  87346. * <A HREF="../documentation_example_code.html">example code</A>.
  87347. *
  87348. * \section porting_guide Porting Guide
  87349. *
  87350. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  87351. * has been introduced which gives detailed instructions on how to
  87352. * port your code to newer versions of FLAC.
  87353. *
  87354. * \section embedded_developers Embedded Developers
  87355. *
  87356. * libFLAC has grown larger over time as more functionality has been
  87357. * included, but much of it may be unnecessary for a particular embedded
  87358. * implementation. Unused parts may be pruned by some simple editing of
  87359. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  87360. * metadata interface are all independent from each other.
  87361. *
  87362. * It is easiest to just describe the dependencies:
  87363. *
  87364. * - All modules depend on the \link flac_format Format \endlink module.
  87365. * - The decoders and encoders depend on the bitbuffer.
  87366. * - The decoder is independent of the encoder. The encoder uses the
  87367. * decoder because of the verify feature, but this can be removed if
  87368. * not needed.
  87369. * - Parts of the metadata interface require the stream decoder (but not
  87370. * the encoder).
  87371. * - Ogg support is selectable through the compile time macro
  87372. * \c FLAC__HAS_OGG.
  87373. *
  87374. * For example, if your application only requires the stream decoder, no
  87375. * encoder, and no metadata interface, you can remove the stream encoder
  87376. * and the metadata interface, which will greatly reduce the size of the
  87377. * library.
  87378. *
  87379. * Also, there are several places in the libFLAC code with comments marked
  87380. * with "OPT:" where a #define can be changed to enable code that might be
  87381. * faster on a specific platform. Experimenting with these can yield faster
  87382. * binaries.
  87383. */
  87384. /** \defgroup porting Porting Guide for New Versions
  87385. *
  87386. * This module describes differences in the library interfaces from
  87387. * version to version. It assists in the porting of code that uses
  87388. * the libraries to newer versions of FLAC.
  87389. *
  87390. * One simple facility for making porting easier that has been added
  87391. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  87392. * library's includes (e.g. \c include/FLAC/export.h). The
  87393. * \c #defines mirror the libraries'
  87394. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  87395. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  87396. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  87397. * These can be used to support multiple versions of an API during the
  87398. * transition phase, e.g.
  87399. *
  87400. * \code
  87401. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  87402. * legacy code
  87403. * #else
  87404. * new code
  87405. * #endif
  87406. * \endcode
  87407. *
  87408. * The the source will work for multiple versions and the legacy code can
  87409. * easily be removed when the transition is complete.
  87410. *
  87411. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  87412. * include/FLAC/export.h), which can be used to determine whether or not
  87413. * the library has been compiled with support for Ogg FLAC. This is
  87414. * simpler than trying to call an Ogg init function and catching the
  87415. * error.
  87416. */
  87417. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  87418. * \ingroup porting
  87419. *
  87420. * \brief
  87421. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  87422. *
  87423. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  87424. * been simplified. First, libOggFLAC has been merged into libFLAC and
  87425. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  87426. * decoding layers and three encoding layers have been merged into a
  87427. * single stream decoder and stream encoder. That is, the functionality
  87428. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  87429. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  87430. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  87431. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  87432. * is there is now a single API that can be used to encode or decode
  87433. * streams to/from native FLAC or Ogg FLAC and the single API can work
  87434. * on both seekable and non-seekable streams.
  87435. *
  87436. * Instead of creating an encoder or decoder of a certain layer, now the
  87437. * client will always create a FLAC__StreamEncoder or
  87438. * FLAC__StreamDecoder. The old layers are now differentiated by the
  87439. * initialization function. For example, for the decoder,
  87440. * FLAC__stream_decoder_init() has been replaced by
  87441. * FLAC__stream_decoder_init_stream(). This init function takes
  87442. * callbacks for the I/O, and the seeking callbacks are optional. This
  87443. * allows the client to use the same object for seekable and
  87444. * non-seekable streams. For decoding a FLAC file directly, the client
  87445. * can use FLAC__stream_decoder_init_file() and pass just a filename
  87446. * and fewer callbacks; most of the other callbacks are supplied
  87447. * internally. For situations where fopen()ing by filename is not
  87448. * possible (e.g. Unicode filenames on Windows) the client can instead
  87449. * open the file itself and supply the FILE* to
  87450. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  87451. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  87452. * Since the callbacks and client data are now passed to the init
  87453. * function, the FLAC__stream_decoder_set_*_callback() functions and
  87454. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  87455. * rest of the calls to the decoder are the same as before.
  87456. *
  87457. * There are counterpart init functions for Ogg FLAC, e.g.
  87458. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  87459. * and callbacks are the same as for native FLAC.
  87460. *
  87461. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  87462. * been set up like so:
  87463. *
  87464. * \code
  87465. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  87466. * if(decoder == NULL) do_something;
  87467. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  87468. * [... other settings ...]
  87469. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  87470. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  87471. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  87472. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  87473. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  87474. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  87475. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  87476. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  87477. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  87478. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  87479. * \endcode
  87480. *
  87481. * In FLAC 1.1.3 it is like this:
  87482. *
  87483. * \code
  87484. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  87485. * if(decoder == NULL) do_something;
  87486. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  87487. * [... other settings ...]
  87488. * if(FLAC__stream_decoder_init_stream(
  87489. * decoder,
  87490. * my_read_callback,
  87491. * my_seek_callback, // or NULL
  87492. * my_tell_callback, // or NULL
  87493. * my_length_callback, // or NULL
  87494. * my_eof_callback, // or NULL
  87495. * my_write_callback,
  87496. * my_metadata_callback, // or NULL
  87497. * my_error_callback,
  87498. * my_client_data
  87499. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  87500. * \endcode
  87501. *
  87502. * or you could do;
  87503. *
  87504. * \code
  87505. * [...]
  87506. * FILE *file = fopen("somefile.flac","rb");
  87507. * if(file == NULL) do_somthing;
  87508. * if(FLAC__stream_decoder_init_FILE(
  87509. * decoder,
  87510. * file,
  87511. * my_write_callback,
  87512. * my_metadata_callback, // or NULL
  87513. * my_error_callback,
  87514. * my_client_data
  87515. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  87516. * \endcode
  87517. *
  87518. * or just:
  87519. *
  87520. * \code
  87521. * [...]
  87522. * if(FLAC__stream_decoder_init_file(
  87523. * decoder,
  87524. * "somefile.flac",
  87525. * my_write_callback,
  87526. * my_metadata_callback, // or NULL
  87527. * my_error_callback,
  87528. * my_client_data
  87529. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  87530. * \endcode
  87531. *
  87532. * Another small change to the decoder is in how it handles unparseable
  87533. * streams. Before, when the decoder found an unparseable stream
  87534. * (reserved for when the decoder encounters a stream from a future
  87535. * encoder that it can't parse), it changed the state to
  87536. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  87537. * drops sync and calls the error callback with a new error code
  87538. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  87539. * more robust. If your error callback does not discriminate on the the
  87540. * error state, your code does not need to be changed.
  87541. *
  87542. * The encoder now has a new setting:
  87543. * FLAC__stream_encoder_set_apodization(). This is for setting the
  87544. * method used to window the data before LPC analysis. You only need to
  87545. * add a call to this function if the default is not suitable. There
  87546. * are also two new convenience functions that may be useful:
  87547. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  87548. * FLAC__metadata_get_cuesheet().
  87549. *
  87550. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  87551. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  87552. * is now \c size_t instead of \c unsigned.
  87553. */
  87554. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  87555. * \ingroup porting
  87556. *
  87557. * \brief
  87558. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  87559. *
  87560. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  87561. * There was a slight change in the implementation of
  87562. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  87563. * of the \a metadata array of pointers so the client no longer needs
  87564. * to maintain it after the call. The objects themselves that are
  87565. * pointed to by the array are still not copied though and must be
  87566. * maintained until the call to FLAC__stream_encoder_finish().
  87567. */
  87568. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  87569. * \ingroup porting
  87570. *
  87571. * \brief
  87572. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  87573. *
  87574. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  87575. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  87576. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  87577. *
  87578. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  87579. * has changed to reflect the conversion of one of the reserved bits
  87580. * into active use. It used to be \c 2 and now is \c 1. However the
  87581. * FLAC frame header length has not changed, so to skip the proper
  87582. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  87583. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  87584. */
  87585. /** \defgroup flac FLAC C API
  87586. *
  87587. * The FLAC C API is the interface to libFLAC, a set of structures
  87588. * describing the components of FLAC streams, and functions for
  87589. * encoding and decoding streams, as well as manipulating FLAC
  87590. * metadata in files.
  87591. *
  87592. * You should start with the format components as all other modules
  87593. * are dependent on it.
  87594. */
  87595. #endif
  87596. /********* End of inlined file: all.h *********/
  87597. /********* Start of inlined file: bitmath.c *********/
  87598. /********* Start of inlined file: juce_FlacHeader.h *********/
  87599. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  87600. // tasks..
  87601. #define VERSION "1.2.1"
  87602. #define FLAC__NO_DLL 1
  87603. #ifdef _MSC_VER
  87604. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  87605. #endif
  87606. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  87607. #define FLAC__SYS_DARWIN 1
  87608. #endif
  87609. /********* End of inlined file: juce_FlacHeader.h *********/
  87610. #if JUCE_USE_FLAC
  87611. #if HAVE_CONFIG_H
  87612. # include <config.h>
  87613. #endif
  87614. /********* Start of inlined file: bitmath.h *********/
  87615. #ifndef FLAC__PRIVATE__BITMATH_H
  87616. #define FLAC__PRIVATE__BITMATH_H
  87617. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  87618. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  87619. unsigned FLAC__bitmath_silog2(int v);
  87620. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  87621. #endif
  87622. /********* End of inlined file: bitmath.h *********/
  87623. /* An example of what FLAC__bitmath_ilog2() computes:
  87624. *
  87625. * ilog2( 0) = assertion failure
  87626. * ilog2( 1) = 0
  87627. * ilog2( 2) = 1
  87628. * ilog2( 3) = 1
  87629. * ilog2( 4) = 2
  87630. * ilog2( 5) = 2
  87631. * ilog2( 6) = 2
  87632. * ilog2( 7) = 2
  87633. * ilog2( 8) = 3
  87634. * ilog2( 9) = 3
  87635. * ilog2(10) = 3
  87636. * ilog2(11) = 3
  87637. * ilog2(12) = 3
  87638. * ilog2(13) = 3
  87639. * ilog2(14) = 3
  87640. * ilog2(15) = 3
  87641. * ilog2(16) = 4
  87642. * ilog2(17) = 4
  87643. * ilog2(18) = 4
  87644. */
  87645. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  87646. {
  87647. unsigned l = 0;
  87648. FLAC__ASSERT(v > 0);
  87649. while(v >>= 1)
  87650. l++;
  87651. return l;
  87652. }
  87653. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  87654. {
  87655. unsigned l = 0;
  87656. FLAC__ASSERT(v > 0);
  87657. while(v >>= 1)
  87658. l++;
  87659. return l;
  87660. }
  87661. /* An example of what FLAC__bitmath_silog2() computes:
  87662. *
  87663. * silog2(-10) = 5
  87664. * silog2(- 9) = 5
  87665. * silog2(- 8) = 4
  87666. * silog2(- 7) = 4
  87667. * silog2(- 6) = 4
  87668. * silog2(- 5) = 4
  87669. * silog2(- 4) = 3
  87670. * silog2(- 3) = 3
  87671. * silog2(- 2) = 2
  87672. * silog2(- 1) = 2
  87673. * silog2( 0) = 0
  87674. * silog2( 1) = 2
  87675. * silog2( 2) = 3
  87676. * silog2( 3) = 3
  87677. * silog2( 4) = 4
  87678. * silog2( 5) = 4
  87679. * silog2( 6) = 4
  87680. * silog2( 7) = 4
  87681. * silog2( 8) = 5
  87682. * silog2( 9) = 5
  87683. * silog2( 10) = 5
  87684. */
  87685. unsigned FLAC__bitmath_silog2(int v)
  87686. {
  87687. while(1) {
  87688. if(v == 0) {
  87689. return 0;
  87690. }
  87691. else if(v > 0) {
  87692. unsigned l = 0;
  87693. while(v) {
  87694. l++;
  87695. v >>= 1;
  87696. }
  87697. return l+1;
  87698. }
  87699. else if(v == -1) {
  87700. return 2;
  87701. }
  87702. else {
  87703. v++;
  87704. v = -v;
  87705. }
  87706. }
  87707. }
  87708. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  87709. {
  87710. while(1) {
  87711. if(v == 0) {
  87712. return 0;
  87713. }
  87714. else if(v > 0) {
  87715. unsigned l = 0;
  87716. while(v) {
  87717. l++;
  87718. v >>= 1;
  87719. }
  87720. return l+1;
  87721. }
  87722. else if(v == -1) {
  87723. return 2;
  87724. }
  87725. else {
  87726. v++;
  87727. v = -v;
  87728. }
  87729. }
  87730. }
  87731. #endif
  87732. /********* End of inlined file: bitmath.c *********/
  87733. /********* Start of inlined file: bitreader.c *********/
  87734. /********* Start of inlined file: juce_FlacHeader.h *********/
  87735. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  87736. // tasks..
  87737. #define VERSION "1.2.1"
  87738. #define FLAC__NO_DLL 1
  87739. #ifdef _MSC_VER
  87740. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  87741. #endif
  87742. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  87743. #define FLAC__SYS_DARWIN 1
  87744. #endif
  87745. /********* End of inlined file: juce_FlacHeader.h *********/
  87746. #if JUCE_USE_FLAC
  87747. #if HAVE_CONFIG_H
  87748. # include <config.h>
  87749. #endif
  87750. #include <stdlib.h> /* for malloc() */
  87751. #include <string.h> /* for memcpy(), memset() */
  87752. #ifdef _MSC_VER
  87753. #include <winsock.h> /* for ntohl() */
  87754. #elif defined FLAC__SYS_DARWIN
  87755. #include <machine/endian.h> /* for ntohl() */
  87756. #elif defined __MINGW32__
  87757. #include <winsock.h> /* for ntohl() */
  87758. #else
  87759. #include <netinet/in.h> /* for ntohl() */
  87760. #endif
  87761. /********* Start of inlined file: bitreader.h *********/
  87762. #ifndef FLAC__PRIVATE__BITREADER_H
  87763. #define FLAC__PRIVATE__BITREADER_H
  87764. #include <stdio.h> /* for FILE */
  87765. /********* Start of inlined file: cpu.h *********/
  87766. #ifndef FLAC__PRIVATE__CPU_H
  87767. #define FLAC__PRIVATE__CPU_H
  87768. #ifdef HAVE_CONFIG_H
  87769. #include <config.h>
  87770. #endif
  87771. typedef enum {
  87772. FLAC__CPUINFO_TYPE_IA32,
  87773. FLAC__CPUINFO_TYPE_PPC,
  87774. FLAC__CPUINFO_TYPE_UNKNOWN
  87775. } FLAC__CPUInfo_Type;
  87776. typedef struct {
  87777. FLAC__bool cpuid;
  87778. FLAC__bool bswap;
  87779. FLAC__bool cmov;
  87780. FLAC__bool mmx;
  87781. FLAC__bool fxsr;
  87782. FLAC__bool sse;
  87783. FLAC__bool sse2;
  87784. FLAC__bool sse3;
  87785. FLAC__bool ssse3;
  87786. FLAC__bool _3dnow;
  87787. FLAC__bool ext3dnow;
  87788. FLAC__bool extmmx;
  87789. } FLAC__CPUInfo_IA32;
  87790. typedef struct {
  87791. FLAC__bool altivec;
  87792. FLAC__bool ppc64;
  87793. } FLAC__CPUInfo_PPC;
  87794. typedef struct {
  87795. FLAC__bool use_asm;
  87796. FLAC__CPUInfo_Type type;
  87797. union {
  87798. FLAC__CPUInfo_IA32 ia32;
  87799. FLAC__CPUInfo_PPC ppc;
  87800. } data;
  87801. } FLAC__CPUInfo;
  87802. void FLAC__cpu_info(FLAC__CPUInfo *info);
  87803. #ifndef FLAC__NO_ASM
  87804. #ifdef FLAC__CPU_IA32
  87805. #ifdef FLAC__HAS_NASM
  87806. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  87807. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  87808. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  87809. #endif
  87810. #endif
  87811. #endif
  87812. #endif
  87813. /********* End of inlined file: cpu.h *********/
  87814. /*
  87815. * opaque structure definition
  87816. */
  87817. struct FLAC__BitReader;
  87818. typedef struct FLAC__BitReader FLAC__BitReader;
  87819. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  87820. /*
  87821. * construction, deletion, initialization, etc functions
  87822. */
  87823. FLAC__BitReader *FLAC__bitreader_new(void);
  87824. void FLAC__bitreader_delete(FLAC__BitReader *br);
  87825. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  87826. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  87827. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  87828. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  87829. /*
  87830. * CRC functions
  87831. */
  87832. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  87833. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  87834. /*
  87835. * info functions
  87836. */
  87837. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  87838. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  87839. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  87840. /*
  87841. * read functions
  87842. */
  87843. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  87844. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  87845. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  87846. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  87847. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  87848. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  87849. 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! */
  87850. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  87851. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  87852. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  87853. #ifndef FLAC__NO_ASM
  87854. # ifdef FLAC__CPU_IA32
  87855. # ifdef FLAC__HAS_NASM
  87856. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  87857. # endif
  87858. # endif
  87859. #endif
  87860. #if 0 /* UNUSED */
  87861. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  87862. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  87863. #endif
  87864. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  87865. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  87866. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  87867. #endif
  87868. /********* End of inlined file: bitreader.h *********/
  87869. /********* Start of inlined file: crc.h *********/
  87870. #ifndef FLAC__PRIVATE__CRC_H
  87871. #define FLAC__PRIVATE__CRC_H
  87872. /* 8 bit CRC generator, MSB shifted first
  87873. ** polynomial = x^8 + x^2 + x^1 + x^0
  87874. ** init = 0
  87875. */
  87876. extern FLAC__byte const FLAC__crc8_table[256];
  87877. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  87878. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  87879. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  87880. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  87881. /* 16 bit CRC generator, MSB shifted first
  87882. ** polynomial = x^16 + x^15 + x^2 + x^0
  87883. ** init = 0
  87884. */
  87885. extern unsigned FLAC__crc16_table[256];
  87886. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  87887. /* this alternate may be faster on some systems/compilers */
  87888. #if 0
  87889. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  87890. #endif
  87891. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  87892. #endif
  87893. /********* End of inlined file: crc.h *********/
  87894. /* Things should be fastest when this matches the machine word size */
  87895. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  87896. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  87897. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  87898. typedef FLAC__uint32 brword;
  87899. #define FLAC__BYTES_PER_WORD 4
  87900. #define FLAC__BITS_PER_WORD 32
  87901. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  87902. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  87903. #if WORDS_BIGENDIAN
  87904. #define SWAP_BE_WORD_TO_HOST(x) (x)
  87905. #else
  87906. #if defined (_MSC_VER) && defined (_X86_)
  87907. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  87908. #else
  87909. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  87910. #endif
  87911. #endif
  87912. /* counts the # of zero MSBs in a word */
  87913. #define COUNT_ZERO_MSBS(word) ( \
  87914. (word) <= 0xffff ? \
  87915. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  87916. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  87917. )
  87918. /* this alternate might be slightly faster on some systems/compilers: */
  87919. #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])) )
  87920. /*
  87921. * This should be at least twice as large as the largest number of words
  87922. * required to represent any 'number' (in any encoding) you are going to
  87923. * read. With FLAC this is on the order of maybe a few hundred bits.
  87924. * If the buffer is smaller than that, the decoder won't be able to read
  87925. * in a whole number that is in a variable length encoding (e.g. Rice).
  87926. * But to be practical it should be at least 1K bytes.
  87927. *
  87928. * Increase this number to decrease the number of read callbacks, at the
  87929. * expense of using more memory. Or decrease for the reverse effect,
  87930. * keeping in mind the limit from the first paragraph. The optimal size
  87931. * also depends on the CPU cache size and other factors; some twiddling
  87932. * may be necessary to squeeze out the best performance.
  87933. */
  87934. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  87935. static const unsigned char byte_to_unary_table[] = {
  87936. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  87937. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  87938. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  87939. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  87940. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87941. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87942. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87943. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  87952. };
  87953. #ifdef min
  87954. #undef min
  87955. #endif
  87956. #define min(x,y) ((x)<(y)?(x):(y))
  87957. #ifdef max
  87958. #undef max
  87959. #endif
  87960. #define max(x,y) ((x)>(y)?(x):(y))
  87961. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  87962. #ifdef _MSC_VER
  87963. #define FLAC__U64L(x) x
  87964. #else
  87965. #define FLAC__U64L(x) x##LLU
  87966. #endif
  87967. #ifndef FLaC__INLINE
  87968. #define FLaC__INLINE
  87969. #endif
  87970. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  87971. struct FLAC__BitReader {
  87972. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  87973. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  87974. brword *buffer;
  87975. unsigned capacity; /* in words */
  87976. unsigned words; /* # of completed words in buffer */
  87977. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  87978. unsigned consumed_words; /* #words ... */
  87979. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  87980. unsigned read_crc16; /* the running frame CRC */
  87981. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  87982. FLAC__BitReaderReadCallback read_callback;
  87983. void *client_data;
  87984. FLAC__CPUInfo cpu_info;
  87985. };
  87986. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  87987. {
  87988. register unsigned crc = br->read_crc16;
  87989. #if FLAC__BYTES_PER_WORD == 4
  87990. switch(br->crc16_align) {
  87991. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  87992. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  87993. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  87994. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  87995. }
  87996. #elif FLAC__BYTES_PER_WORD == 8
  87997. switch(br->crc16_align) {
  87998. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  87999. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  88000. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  88001. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  88002. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  88003. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  88004. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  88005. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  88006. }
  88007. #else
  88008. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  88009. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  88010. br->read_crc16 = crc;
  88011. #endif
  88012. br->crc16_align = 0;
  88013. }
  88014. /* would be static except it needs to be called by asm routines */
  88015. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  88016. {
  88017. unsigned start, end;
  88018. size_t bytes;
  88019. FLAC__byte *target;
  88020. /* first shift the unconsumed buffer data toward the front as much as possible */
  88021. if(br->consumed_words > 0) {
  88022. start = br->consumed_words;
  88023. end = br->words + (br->bytes? 1:0);
  88024. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  88025. br->words -= start;
  88026. br->consumed_words = 0;
  88027. }
  88028. /*
  88029. * set the target for reading, taking into account word alignment and endianness
  88030. */
  88031. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  88032. if(bytes == 0)
  88033. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  88034. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  88035. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  88036. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  88037. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  88038. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  88039. * ^^-------target, bytes=3
  88040. * on LE machines, have to byteswap the odd tail word so nothing is
  88041. * overwritten:
  88042. */
  88043. #if WORDS_BIGENDIAN
  88044. #else
  88045. if(br->bytes)
  88046. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  88047. #endif
  88048. /* now it looks like:
  88049. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  88050. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  88051. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  88052. * ^^-------target, bytes=3
  88053. */
  88054. /* read in the data; note that the callback may return a smaller number of bytes */
  88055. if(!br->read_callback(target, &bytes, br->client_data))
  88056. return false;
  88057. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  88058. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  88059. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  88060. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  88061. * now have to byteswap on LE machines:
  88062. */
  88063. #if WORDS_BIGENDIAN
  88064. #else
  88065. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  88066. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  88067. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  88068. start = br->words;
  88069. local_swap32_block_(br->buffer + start, end - start);
  88070. }
  88071. else
  88072. # endif
  88073. for(start = br->words; start < end; start++)
  88074. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  88075. #endif
  88076. /* now it looks like:
  88077. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  88078. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  88079. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  88080. * finally we'll update the reader values:
  88081. */
  88082. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  88083. br->words = end / FLAC__BYTES_PER_WORD;
  88084. br->bytes = end % FLAC__BYTES_PER_WORD;
  88085. return true;
  88086. }
  88087. /***********************************************************************
  88088. *
  88089. * Class constructor/destructor
  88090. *
  88091. ***********************************************************************/
  88092. FLAC__BitReader *FLAC__bitreader_new(void)
  88093. {
  88094. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  88095. /* calloc() implies:
  88096. memset(br, 0, sizeof(FLAC__BitReader));
  88097. br->buffer = 0;
  88098. br->capacity = 0;
  88099. br->words = br->bytes = 0;
  88100. br->consumed_words = br->consumed_bits = 0;
  88101. br->read_callback = 0;
  88102. br->client_data = 0;
  88103. */
  88104. return br;
  88105. }
  88106. void FLAC__bitreader_delete(FLAC__BitReader *br)
  88107. {
  88108. FLAC__ASSERT(0 != br);
  88109. FLAC__bitreader_free(br);
  88110. free(br);
  88111. }
  88112. /***********************************************************************
  88113. *
  88114. * Public class methods
  88115. *
  88116. ***********************************************************************/
  88117. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  88118. {
  88119. FLAC__ASSERT(0 != br);
  88120. br->words = br->bytes = 0;
  88121. br->consumed_words = br->consumed_bits = 0;
  88122. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  88123. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  88124. if(br->buffer == 0)
  88125. return false;
  88126. br->read_callback = rcb;
  88127. br->client_data = cd;
  88128. br->cpu_info = cpu;
  88129. return true;
  88130. }
  88131. void FLAC__bitreader_free(FLAC__BitReader *br)
  88132. {
  88133. FLAC__ASSERT(0 != br);
  88134. if(0 != br->buffer)
  88135. free(br->buffer);
  88136. br->buffer = 0;
  88137. br->capacity = 0;
  88138. br->words = br->bytes = 0;
  88139. br->consumed_words = br->consumed_bits = 0;
  88140. br->read_callback = 0;
  88141. br->client_data = 0;
  88142. }
  88143. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  88144. {
  88145. br->words = br->bytes = 0;
  88146. br->consumed_words = br->consumed_bits = 0;
  88147. return true;
  88148. }
  88149. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  88150. {
  88151. unsigned i, j;
  88152. if(br == 0) {
  88153. fprintf(out, "bitreader is NULL\n");
  88154. }
  88155. else {
  88156. 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);
  88157. for(i = 0; i < br->words; i++) {
  88158. fprintf(out, "%08X: ", i);
  88159. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  88160. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  88161. fprintf(out, ".");
  88162. else
  88163. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  88164. fprintf(out, "\n");
  88165. }
  88166. if(br->bytes > 0) {
  88167. fprintf(out, "%08X: ", i);
  88168. for(j = 0; j < br->bytes*8; j++)
  88169. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  88170. fprintf(out, ".");
  88171. else
  88172. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  88173. fprintf(out, "\n");
  88174. }
  88175. }
  88176. }
  88177. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  88178. {
  88179. FLAC__ASSERT(0 != br);
  88180. FLAC__ASSERT(0 != br->buffer);
  88181. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  88182. br->read_crc16 = (unsigned)seed;
  88183. br->crc16_align = br->consumed_bits;
  88184. }
  88185. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  88186. {
  88187. FLAC__ASSERT(0 != br);
  88188. FLAC__ASSERT(0 != br->buffer);
  88189. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  88190. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  88191. /* CRC any tail bytes in a partially-consumed word */
  88192. if(br->consumed_bits) {
  88193. const brword tail = br->buffer[br->consumed_words];
  88194. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  88195. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  88196. }
  88197. return br->read_crc16;
  88198. }
  88199. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  88200. {
  88201. return ((br->consumed_bits & 7) == 0);
  88202. }
  88203. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  88204. {
  88205. return 8 - (br->consumed_bits & 7);
  88206. }
  88207. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  88208. {
  88209. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  88210. }
  88211. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  88212. {
  88213. FLAC__ASSERT(0 != br);
  88214. FLAC__ASSERT(0 != br->buffer);
  88215. FLAC__ASSERT(bits <= 32);
  88216. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  88217. FLAC__ASSERT(br->consumed_words <= br->words);
  88218. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88219. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88220. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  88221. *val = 0;
  88222. return true;
  88223. }
  88224. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  88225. if(!bitreader_read_from_client_(br))
  88226. return false;
  88227. }
  88228. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  88229. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  88230. if(br->consumed_bits) {
  88231. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88232. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  88233. const brword word = br->buffer[br->consumed_words];
  88234. if(bits < n) {
  88235. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  88236. br->consumed_bits += bits;
  88237. return true;
  88238. }
  88239. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  88240. bits -= n;
  88241. crc16_update_word_(br, word);
  88242. br->consumed_words++;
  88243. br->consumed_bits = 0;
  88244. 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 */
  88245. *val <<= bits;
  88246. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  88247. br->consumed_bits = bits;
  88248. }
  88249. return true;
  88250. }
  88251. else {
  88252. const brword word = br->buffer[br->consumed_words];
  88253. if(bits < FLAC__BITS_PER_WORD) {
  88254. *val = word >> (FLAC__BITS_PER_WORD-bits);
  88255. br->consumed_bits = bits;
  88256. return true;
  88257. }
  88258. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  88259. *val = word;
  88260. crc16_update_word_(br, word);
  88261. br->consumed_words++;
  88262. return true;
  88263. }
  88264. }
  88265. else {
  88266. /* in this case we're starting our read at a partial tail word;
  88267. * the reader has guaranteed that we have at least 'bits' bits
  88268. * available to read, which makes this case simpler.
  88269. */
  88270. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  88271. if(br->consumed_bits) {
  88272. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88273. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  88274. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  88275. br->consumed_bits += bits;
  88276. return true;
  88277. }
  88278. else {
  88279. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  88280. br->consumed_bits += bits;
  88281. return true;
  88282. }
  88283. }
  88284. }
  88285. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  88286. {
  88287. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  88288. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  88289. return false;
  88290. /* sign-extend: */
  88291. *val <<= (32-bits);
  88292. *val >>= (32-bits);
  88293. return true;
  88294. }
  88295. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  88296. {
  88297. FLAC__uint32 hi, lo;
  88298. if(bits > 32) {
  88299. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  88300. return false;
  88301. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  88302. return false;
  88303. *val = hi;
  88304. *val <<= 32;
  88305. *val |= lo;
  88306. }
  88307. else {
  88308. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  88309. return false;
  88310. *val = lo;
  88311. }
  88312. return true;
  88313. }
  88314. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  88315. {
  88316. FLAC__uint32 x8, x32 = 0;
  88317. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  88318. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  88319. return false;
  88320. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  88321. return false;
  88322. x32 |= (x8 << 8);
  88323. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  88324. return false;
  88325. x32 |= (x8 << 16);
  88326. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  88327. return false;
  88328. x32 |= (x8 << 24);
  88329. *val = x32;
  88330. return true;
  88331. }
  88332. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  88333. {
  88334. /*
  88335. * OPT: a faster implementation is possible but probably not that useful
  88336. * since this is only called a couple of times in the metadata readers.
  88337. */
  88338. FLAC__ASSERT(0 != br);
  88339. FLAC__ASSERT(0 != br->buffer);
  88340. if(bits > 0) {
  88341. const unsigned n = br->consumed_bits & 7;
  88342. unsigned m;
  88343. FLAC__uint32 x;
  88344. if(n != 0) {
  88345. m = min(8-n, bits);
  88346. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  88347. return false;
  88348. bits -= m;
  88349. }
  88350. m = bits / 8;
  88351. if(m > 0) {
  88352. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  88353. return false;
  88354. bits %= 8;
  88355. }
  88356. if(bits > 0) {
  88357. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  88358. return false;
  88359. }
  88360. }
  88361. return true;
  88362. }
  88363. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  88364. {
  88365. FLAC__uint32 x;
  88366. FLAC__ASSERT(0 != br);
  88367. FLAC__ASSERT(0 != br->buffer);
  88368. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  88369. /* step 1: skip over partial head word to get word aligned */
  88370. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  88371. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88372. return false;
  88373. nvals--;
  88374. }
  88375. if(0 == nvals)
  88376. return true;
  88377. /* step 2: skip whole words in chunks */
  88378. while(nvals >= FLAC__BYTES_PER_WORD) {
  88379. if(br->consumed_words < br->words) {
  88380. br->consumed_words++;
  88381. nvals -= FLAC__BYTES_PER_WORD;
  88382. }
  88383. else if(!bitreader_read_from_client_(br))
  88384. return false;
  88385. }
  88386. /* step 3: skip any remainder from partial tail bytes */
  88387. while(nvals) {
  88388. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88389. return false;
  88390. nvals--;
  88391. }
  88392. return true;
  88393. }
  88394. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  88395. {
  88396. FLAC__uint32 x;
  88397. FLAC__ASSERT(0 != br);
  88398. FLAC__ASSERT(0 != br->buffer);
  88399. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  88400. /* step 1: read from partial head word to get word aligned */
  88401. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  88402. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88403. return false;
  88404. *val++ = (FLAC__byte)x;
  88405. nvals--;
  88406. }
  88407. if(0 == nvals)
  88408. return true;
  88409. /* step 2: read whole words in chunks */
  88410. while(nvals >= FLAC__BYTES_PER_WORD) {
  88411. if(br->consumed_words < br->words) {
  88412. const brword word = br->buffer[br->consumed_words++];
  88413. #if FLAC__BYTES_PER_WORD == 4
  88414. val[0] = (FLAC__byte)(word >> 24);
  88415. val[1] = (FLAC__byte)(word >> 16);
  88416. val[2] = (FLAC__byte)(word >> 8);
  88417. val[3] = (FLAC__byte)word;
  88418. #elif FLAC__BYTES_PER_WORD == 8
  88419. val[0] = (FLAC__byte)(word >> 56);
  88420. val[1] = (FLAC__byte)(word >> 48);
  88421. val[2] = (FLAC__byte)(word >> 40);
  88422. val[3] = (FLAC__byte)(word >> 32);
  88423. val[4] = (FLAC__byte)(word >> 24);
  88424. val[5] = (FLAC__byte)(word >> 16);
  88425. val[6] = (FLAC__byte)(word >> 8);
  88426. val[7] = (FLAC__byte)word;
  88427. #else
  88428. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  88429. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  88430. #endif
  88431. val += FLAC__BYTES_PER_WORD;
  88432. nvals -= FLAC__BYTES_PER_WORD;
  88433. }
  88434. else if(!bitreader_read_from_client_(br))
  88435. return false;
  88436. }
  88437. /* step 3: read any remainder from partial tail bytes */
  88438. while(nvals) {
  88439. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88440. return false;
  88441. *val++ = (FLAC__byte)x;
  88442. nvals--;
  88443. }
  88444. return true;
  88445. }
  88446. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  88447. #if 0 /* slow but readable version */
  88448. {
  88449. unsigned bit;
  88450. FLAC__ASSERT(0 != br);
  88451. FLAC__ASSERT(0 != br->buffer);
  88452. *val = 0;
  88453. while(1) {
  88454. if(!FLAC__bitreader_read_bit(br, &bit))
  88455. return false;
  88456. if(bit)
  88457. break;
  88458. else
  88459. *val++;
  88460. }
  88461. return true;
  88462. }
  88463. #else
  88464. {
  88465. unsigned i;
  88466. FLAC__ASSERT(0 != br);
  88467. FLAC__ASSERT(0 != br->buffer);
  88468. *val = 0;
  88469. while(1) {
  88470. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  88471. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  88472. if(b) {
  88473. i = COUNT_ZERO_MSBS(b);
  88474. *val += i;
  88475. i++;
  88476. br->consumed_bits += i;
  88477. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  88478. crc16_update_word_(br, br->buffer[br->consumed_words]);
  88479. br->consumed_words++;
  88480. br->consumed_bits = 0;
  88481. }
  88482. return true;
  88483. }
  88484. else {
  88485. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  88486. crc16_update_word_(br, br->buffer[br->consumed_words]);
  88487. br->consumed_words++;
  88488. br->consumed_bits = 0;
  88489. /* didn't find stop bit yet, have to keep going... */
  88490. }
  88491. }
  88492. /* at this point we've eaten up all the whole words; have to try
  88493. * reading through any tail bytes before calling the read callback.
  88494. * this is a repeat of the above logic adjusted for the fact we
  88495. * don't have a whole word. note though if the client is feeding
  88496. * us data a byte at a time (unlikely), br->consumed_bits may not
  88497. * be zero.
  88498. */
  88499. if(br->bytes) {
  88500. const unsigned end = br->bytes * 8;
  88501. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  88502. if(b) {
  88503. i = COUNT_ZERO_MSBS(b);
  88504. *val += i;
  88505. i++;
  88506. br->consumed_bits += i;
  88507. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  88508. return true;
  88509. }
  88510. else {
  88511. *val += end - br->consumed_bits;
  88512. br->consumed_bits += end;
  88513. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  88514. /* didn't find stop bit yet, have to keep going... */
  88515. }
  88516. }
  88517. if(!bitreader_read_from_client_(br))
  88518. return false;
  88519. }
  88520. }
  88521. #endif
  88522. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  88523. {
  88524. FLAC__uint32 lsbs = 0, msbs = 0;
  88525. unsigned uval;
  88526. FLAC__ASSERT(0 != br);
  88527. FLAC__ASSERT(0 != br->buffer);
  88528. FLAC__ASSERT(parameter <= 31);
  88529. /* read the unary MSBs and end bit */
  88530. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  88531. return false;
  88532. /* read the binary LSBs */
  88533. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  88534. return false;
  88535. /* compose the value */
  88536. uval = (msbs << parameter) | lsbs;
  88537. if(uval & 1)
  88538. *val = -((int)(uval >> 1)) - 1;
  88539. else
  88540. *val = (int)(uval >> 1);
  88541. return true;
  88542. }
  88543. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  88544. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  88545. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  88546. /* OPT: possibly faster version for use with MSVC */
  88547. #ifdef _MSC_VER
  88548. {
  88549. unsigned i;
  88550. unsigned uval = 0;
  88551. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  88552. /* try and get br->consumed_words and br->consumed_bits into register;
  88553. * must remember to flush them back to *br before calling other
  88554. * bitwriter functions that use them, and before returning */
  88555. register unsigned cwords;
  88556. register unsigned cbits;
  88557. FLAC__ASSERT(0 != br);
  88558. FLAC__ASSERT(0 != br->buffer);
  88559. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88560. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88561. FLAC__ASSERT(parameter < 32);
  88562. /* 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 */
  88563. if(nvals == 0)
  88564. return true;
  88565. cbits = br->consumed_bits;
  88566. cwords = br->consumed_words;
  88567. while(1) {
  88568. /* read unary part */
  88569. while(1) {
  88570. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  88571. brword b = br->buffer[cwords] << cbits;
  88572. if(b) {
  88573. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  88574. __asm {
  88575. bsr eax, b
  88576. not eax
  88577. and eax, 31
  88578. mov i, eax
  88579. }
  88580. #else
  88581. i = COUNT_ZERO_MSBS(b);
  88582. #endif
  88583. uval += i;
  88584. bits = parameter;
  88585. i++;
  88586. cbits += i;
  88587. if(cbits == FLAC__BITS_PER_WORD) {
  88588. crc16_update_word_(br, br->buffer[cwords]);
  88589. cwords++;
  88590. cbits = 0;
  88591. }
  88592. goto break1;
  88593. }
  88594. else {
  88595. uval += FLAC__BITS_PER_WORD - cbits;
  88596. crc16_update_word_(br, br->buffer[cwords]);
  88597. cwords++;
  88598. cbits = 0;
  88599. /* didn't find stop bit yet, have to keep going... */
  88600. }
  88601. }
  88602. /* at this point we've eaten up all the whole words; have to try
  88603. * reading through any tail bytes before calling the read callback.
  88604. * this is a repeat of the above logic adjusted for the fact we
  88605. * don't have a whole word. note though if the client is feeding
  88606. * us data a byte at a time (unlikely), br->consumed_bits may not
  88607. * be zero.
  88608. */
  88609. if(br->bytes) {
  88610. const unsigned end = br->bytes * 8;
  88611. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  88612. if(b) {
  88613. i = COUNT_ZERO_MSBS(b);
  88614. uval += i;
  88615. bits = parameter;
  88616. i++;
  88617. cbits += i;
  88618. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  88619. goto break1;
  88620. }
  88621. else {
  88622. uval += end - cbits;
  88623. cbits += end;
  88624. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  88625. /* didn't find stop bit yet, have to keep going... */
  88626. }
  88627. }
  88628. /* flush registers and read; bitreader_read_from_client_() does
  88629. * not touch br->consumed_bits at all but we still need to set
  88630. * it in case it fails and we have to return false.
  88631. */
  88632. br->consumed_bits = cbits;
  88633. br->consumed_words = cwords;
  88634. if(!bitreader_read_from_client_(br))
  88635. return false;
  88636. cwords = br->consumed_words;
  88637. }
  88638. break1:
  88639. /* read binary part */
  88640. FLAC__ASSERT(cwords <= br->words);
  88641. if(bits) {
  88642. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  88643. /* flush registers and read; bitreader_read_from_client_() does
  88644. * not touch br->consumed_bits at all but we still need to set
  88645. * it in case it fails and we have to return false.
  88646. */
  88647. br->consumed_bits = cbits;
  88648. br->consumed_words = cwords;
  88649. if(!bitreader_read_from_client_(br))
  88650. return false;
  88651. cwords = br->consumed_words;
  88652. }
  88653. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  88654. if(cbits) {
  88655. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88656. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  88657. const brword word = br->buffer[cwords];
  88658. if(bits < n) {
  88659. uval <<= bits;
  88660. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  88661. cbits += bits;
  88662. goto break2;
  88663. }
  88664. uval <<= n;
  88665. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  88666. bits -= n;
  88667. crc16_update_word_(br, word);
  88668. cwords++;
  88669. cbits = 0;
  88670. 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 */
  88671. uval <<= bits;
  88672. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  88673. cbits = bits;
  88674. }
  88675. goto break2;
  88676. }
  88677. else {
  88678. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  88679. uval <<= bits;
  88680. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  88681. cbits = bits;
  88682. goto break2;
  88683. }
  88684. }
  88685. else {
  88686. /* in this case we're starting our read at a partial tail word;
  88687. * the reader has guaranteed that we have at least 'bits' bits
  88688. * available to read, which makes this case simpler.
  88689. */
  88690. uval <<= bits;
  88691. if(cbits) {
  88692. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88693. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  88694. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  88695. cbits += bits;
  88696. goto break2;
  88697. }
  88698. else {
  88699. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  88700. cbits += bits;
  88701. goto break2;
  88702. }
  88703. }
  88704. }
  88705. break2:
  88706. /* compose the value */
  88707. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  88708. /* are we done? */
  88709. --nvals;
  88710. if(nvals == 0) {
  88711. br->consumed_bits = cbits;
  88712. br->consumed_words = cwords;
  88713. return true;
  88714. }
  88715. uval = 0;
  88716. ++vals;
  88717. }
  88718. }
  88719. #else
  88720. {
  88721. unsigned i;
  88722. unsigned uval = 0;
  88723. /* try and get br->consumed_words and br->consumed_bits into register;
  88724. * must remember to flush them back to *br before calling other
  88725. * bitwriter functions that use them, and before returning */
  88726. register unsigned cwords;
  88727. register unsigned cbits;
  88728. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  88729. FLAC__ASSERT(0 != br);
  88730. FLAC__ASSERT(0 != br->buffer);
  88731. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88732. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88733. FLAC__ASSERT(parameter < 32);
  88734. /* 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 */
  88735. if(nvals == 0)
  88736. return true;
  88737. cbits = br->consumed_bits;
  88738. cwords = br->consumed_words;
  88739. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  88740. while(1) {
  88741. /* read unary part */
  88742. while(1) {
  88743. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  88744. brword b = br->buffer[cwords] << cbits;
  88745. if(b) {
  88746. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  88747. asm volatile (
  88748. "bsrl %1, %0;"
  88749. "notl %0;"
  88750. "andl $31, %0;"
  88751. : "=r"(i)
  88752. : "r"(b)
  88753. );
  88754. #else
  88755. i = COUNT_ZERO_MSBS(b);
  88756. #endif
  88757. uval += i;
  88758. cbits += i;
  88759. cbits++; /* skip over stop bit */
  88760. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  88761. crc16_update_word_(br, br->buffer[cwords]);
  88762. cwords++;
  88763. cbits = 0;
  88764. }
  88765. goto break1;
  88766. }
  88767. else {
  88768. uval += FLAC__BITS_PER_WORD - cbits;
  88769. crc16_update_word_(br, br->buffer[cwords]);
  88770. cwords++;
  88771. cbits = 0;
  88772. /* didn't find stop bit yet, have to keep going... */
  88773. }
  88774. }
  88775. /* at this point we've eaten up all the whole words; have to try
  88776. * reading through any tail bytes before calling the read callback.
  88777. * this is a repeat of the above logic adjusted for the fact we
  88778. * don't have a whole word. note though if the client is feeding
  88779. * us data a byte at a time (unlikely), br->consumed_bits may not
  88780. * be zero.
  88781. */
  88782. if(br->bytes) {
  88783. const unsigned end = br->bytes * 8;
  88784. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  88785. if(b) {
  88786. i = COUNT_ZERO_MSBS(b);
  88787. uval += i;
  88788. cbits += i;
  88789. cbits++; /* skip over stop bit */
  88790. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  88791. goto break1;
  88792. }
  88793. else {
  88794. uval += end - cbits;
  88795. cbits += end;
  88796. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  88797. /* didn't find stop bit yet, have to keep going... */
  88798. }
  88799. }
  88800. /* flush registers and read; bitreader_read_from_client_() does
  88801. * not touch br->consumed_bits at all but we still need to set
  88802. * it in case it fails and we have to return false.
  88803. */
  88804. br->consumed_bits = cbits;
  88805. br->consumed_words = cwords;
  88806. if(!bitreader_read_from_client_(br))
  88807. return false;
  88808. cwords = br->consumed_words;
  88809. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  88810. /* + uval to offset our count by the # of unary bits already
  88811. * consumed before the read, because we will add these back
  88812. * in all at once at break1
  88813. */
  88814. }
  88815. break1:
  88816. ucbits -= uval;
  88817. ucbits--; /* account for stop bit */
  88818. /* read binary part */
  88819. FLAC__ASSERT(cwords <= br->words);
  88820. if(parameter) {
  88821. while(ucbits < parameter) {
  88822. /* flush registers and read; bitreader_read_from_client_() does
  88823. * not touch br->consumed_bits at all but we still need to set
  88824. * it in case it fails and we have to return false.
  88825. */
  88826. br->consumed_bits = cbits;
  88827. br->consumed_words = cwords;
  88828. if(!bitreader_read_from_client_(br))
  88829. return false;
  88830. cwords = br->consumed_words;
  88831. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  88832. }
  88833. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  88834. if(cbits) {
  88835. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  88836. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  88837. const brword word = br->buffer[cwords];
  88838. if(parameter < n) {
  88839. uval <<= parameter;
  88840. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  88841. cbits += parameter;
  88842. }
  88843. else {
  88844. uval <<= n;
  88845. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  88846. crc16_update_word_(br, word);
  88847. cwords++;
  88848. cbits = parameter - n;
  88849. 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 */
  88850. uval <<= cbits;
  88851. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  88852. }
  88853. }
  88854. }
  88855. else {
  88856. cbits = parameter;
  88857. uval <<= parameter;
  88858. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  88859. }
  88860. }
  88861. else {
  88862. /* in this case we're starting our read at a partial tail word;
  88863. * the reader has guaranteed that we have at least 'parameter'
  88864. * bits available to read, which makes this case simpler.
  88865. */
  88866. uval <<= parameter;
  88867. if(cbits) {
  88868. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88869. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  88870. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  88871. cbits += parameter;
  88872. }
  88873. else {
  88874. cbits = parameter;
  88875. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  88876. }
  88877. }
  88878. }
  88879. ucbits -= parameter;
  88880. /* compose the value */
  88881. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  88882. /* are we done? */
  88883. --nvals;
  88884. if(nvals == 0) {
  88885. br->consumed_bits = cbits;
  88886. br->consumed_words = cwords;
  88887. return true;
  88888. }
  88889. uval = 0;
  88890. ++vals;
  88891. }
  88892. }
  88893. #endif
  88894. #if 0 /* UNUSED */
  88895. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  88896. {
  88897. FLAC__uint32 lsbs = 0, msbs = 0;
  88898. unsigned bit, uval, k;
  88899. FLAC__ASSERT(0 != br);
  88900. FLAC__ASSERT(0 != br->buffer);
  88901. k = FLAC__bitmath_ilog2(parameter);
  88902. /* read the unary MSBs and end bit */
  88903. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  88904. return false;
  88905. /* read the binary LSBs */
  88906. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  88907. return false;
  88908. if(parameter == 1u<<k) {
  88909. /* compose the value */
  88910. uval = (msbs << k) | lsbs;
  88911. }
  88912. else {
  88913. unsigned d = (1 << (k+1)) - parameter;
  88914. if(lsbs >= d) {
  88915. if(!FLAC__bitreader_read_bit(br, &bit))
  88916. return false;
  88917. lsbs <<= 1;
  88918. lsbs |= bit;
  88919. lsbs -= d;
  88920. }
  88921. /* compose the value */
  88922. uval = msbs * parameter + lsbs;
  88923. }
  88924. /* unfold unsigned to signed */
  88925. if(uval & 1)
  88926. *val = -((int)(uval >> 1)) - 1;
  88927. else
  88928. *val = (int)(uval >> 1);
  88929. return true;
  88930. }
  88931. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  88932. {
  88933. FLAC__uint32 lsbs, msbs = 0;
  88934. unsigned bit, k;
  88935. FLAC__ASSERT(0 != br);
  88936. FLAC__ASSERT(0 != br->buffer);
  88937. k = FLAC__bitmath_ilog2(parameter);
  88938. /* read the unary MSBs and end bit */
  88939. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  88940. return false;
  88941. /* read the binary LSBs */
  88942. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  88943. return false;
  88944. if(parameter == 1u<<k) {
  88945. /* compose the value */
  88946. *val = (msbs << k) | lsbs;
  88947. }
  88948. else {
  88949. unsigned d = (1 << (k+1)) - parameter;
  88950. if(lsbs >= d) {
  88951. if(!FLAC__bitreader_read_bit(br, &bit))
  88952. return false;
  88953. lsbs <<= 1;
  88954. lsbs |= bit;
  88955. lsbs -= d;
  88956. }
  88957. /* compose the value */
  88958. *val = msbs * parameter + lsbs;
  88959. }
  88960. return true;
  88961. }
  88962. #endif /* UNUSED */
  88963. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  88964. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  88965. {
  88966. FLAC__uint32 v = 0;
  88967. FLAC__uint32 x;
  88968. unsigned i;
  88969. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88970. return false;
  88971. if(raw)
  88972. raw[(*rawlen)++] = (FLAC__byte)x;
  88973. if(!(x & 0x80)) { /* 0xxxxxxx */
  88974. v = x;
  88975. i = 0;
  88976. }
  88977. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  88978. v = x & 0x1F;
  88979. i = 1;
  88980. }
  88981. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  88982. v = x & 0x0F;
  88983. i = 2;
  88984. }
  88985. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  88986. v = x & 0x07;
  88987. i = 3;
  88988. }
  88989. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  88990. v = x & 0x03;
  88991. i = 4;
  88992. }
  88993. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  88994. v = x & 0x01;
  88995. i = 5;
  88996. }
  88997. else {
  88998. *val = 0xffffffff;
  88999. return true;
  89000. }
  89001. for( ; i; i--) {
  89002. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89003. return false;
  89004. if(raw)
  89005. raw[(*rawlen)++] = (FLAC__byte)x;
  89006. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  89007. *val = 0xffffffff;
  89008. return true;
  89009. }
  89010. v <<= 6;
  89011. v |= (x & 0x3F);
  89012. }
  89013. *val = v;
  89014. return true;
  89015. }
  89016. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  89017. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  89018. {
  89019. FLAC__uint64 v = 0;
  89020. FLAC__uint32 x;
  89021. unsigned i;
  89022. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89023. return false;
  89024. if(raw)
  89025. raw[(*rawlen)++] = (FLAC__byte)x;
  89026. if(!(x & 0x80)) { /* 0xxxxxxx */
  89027. v = x;
  89028. i = 0;
  89029. }
  89030. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  89031. v = x & 0x1F;
  89032. i = 1;
  89033. }
  89034. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  89035. v = x & 0x0F;
  89036. i = 2;
  89037. }
  89038. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  89039. v = x & 0x07;
  89040. i = 3;
  89041. }
  89042. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  89043. v = x & 0x03;
  89044. i = 4;
  89045. }
  89046. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  89047. v = x & 0x01;
  89048. i = 5;
  89049. }
  89050. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  89051. v = 0;
  89052. i = 6;
  89053. }
  89054. else {
  89055. *val = FLAC__U64L(0xffffffffffffffff);
  89056. return true;
  89057. }
  89058. for( ; i; i--) {
  89059. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89060. return false;
  89061. if(raw)
  89062. raw[(*rawlen)++] = (FLAC__byte)x;
  89063. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  89064. *val = FLAC__U64L(0xffffffffffffffff);
  89065. return true;
  89066. }
  89067. v <<= 6;
  89068. v |= (x & 0x3F);
  89069. }
  89070. *val = v;
  89071. return true;
  89072. }
  89073. #endif
  89074. /********* End of inlined file: bitreader.c *********/
  89075. /********* Start of inlined file: bitwriter.c *********/
  89076. /********* Start of inlined file: juce_FlacHeader.h *********/
  89077. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89078. // tasks..
  89079. #define VERSION "1.2.1"
  89080. #define FLAC__NO_DLL 1
  89081. #ifdef _MSC_VER
  89082. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89083. #endif
  89084. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89085. #define FLAC__SYS_DARWIN 1
  89086. #endif
  89087. /********* End of inlined file: juce_FlacHeader.h *********/
  89088. #if JUCE_USE_FLAC
  89089. #if HAVE_CONFIG_H
  89090. # include <config.h>
  89091. #endif
  89092. #include <stdlib.h> /* for malloc() */
  89093. #include <string.h> /* for memcpy(), memset() */
  89094. #ifdef _MSC_VER
  89095. #include <winsock.h> /* for ntohl() */
  89096. #elif defined FLAC__SYS_DARWIN
  89097. #include <machine/endian.h> /* for ntohl() */
  89098. #elif defined __MINGW32__
  89099. #include <winsock.h> /* for ntohl() */
  89100. #else
  89101. #include <netinet/in.h> /* for ntohl() */
  89102. #endif
  89103. #if 0 /* UNUSED */
  89104. #endif
  89105. /********* Start of inlined file: bitwriter.h *********/
  89106. #ifndef FLAC__PRIVATE__BITWRITER_H
  89107. #define FLAC__PRIVATE__BITWRITER_H
  89108. #include <stdio.h> /* for FILE */
  89109. /*
  89110. * opaque structure definition
  89111. */
  89112. struct FLAC__BitWriter;
  89113. typedef struct FLAC__BitWriter FLAC__BitWriter;
  89114. /*
  89115. * construction, deletion, initialization, etc functions
  89116. */
  89117. FLAC__BitWriter *FLAC__bitwriter_new(void);
  89118. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  89119. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  89120. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  89121. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  89122. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  89123. /*
  89124. * CRC functions
  89125. *
  89126. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  89127. */
  89128. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  89129. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  89130. /*
  89131. * info functions
  89132. */
  89133. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  89134. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  89135. /*
  89136. * direct buffer access
  89137. *
  89138. * there may be no calls on the bitwriter between get and release.
  89139. * the bitwriter continues to own the returned buffer.
  89140. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  89141. */
  89142. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  89143. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  89144. /*
  89145. * write functions
  89146. */
  89147. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  89148. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  89149. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  89150. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  89151. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  89152. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  89153. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  89154. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  89155. #if 0 /* UNUSED */
  89156. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  89157. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  89158. #endif
  89159. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  89160. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  89161. #if 0 /* UNUSED */
  89162. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  89163. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  89164. #endif
  89165. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  89166. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  89167. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  89168. #endif
  89169. /********* End of inlined file: bitwriter.h *********/
  89170. /********* Start of inlined file: alloc.h *********/
  89171. #ifndef FLAC__SHARE__ALLOC_H
  89172. #define FLAC__SHARE__ALLOC_H
  89173. #if HAVE_CONFIG_H
  89174. # include <config.h>
  89175. #endif
  89176. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  89177. * before #including this file, otherwise SIZE_MAX might not be defined
  89178. */
  89179. #include <limits.h> /* for SIZE_MAX */
  89180. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  89181. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  89182. #endif
  89183. #include <stdlib.h> /* for size_t, malloc(), etc */
  89184. #ifndef SIZE_MAX
  89185. # ifndef SIZE_T_MAX
  89186. # ifdef _MSC_VER
  89187. # define SIZE_T_MAX UINT_MAX
  89188. # else
  89189. # error
  89190. # endif
  89191. # endif
  89192. # define SIZE_MAX SIZE_T_MAX
  89193. #endif
  89194. #ifndef FLaC__INLINE
  89195. #define FLaC__INLINE
  89196. #endif
  89197. /* avoid malloc()ing 0 bytes, see:
  89198. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  89199. */
  89200. static FLaC__INLINE void *safe_malloc_(size_t size)
  89201. {
  89202. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89203. if(!size)
  89204. size++;
  89205. return malloc(size);
  89206. }
  89207. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  89208. {
  89209. if(!nmemb || !size)
  89210. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89211. return calloc(nmemb, size);
  89212. }
  89213. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  89214. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  89215. {
  89216. size2 += size1;
  89217. if(size2 < size1)
  89218. return 0;
  89219. return safe_malloc_(size2);
  89220. }
  89221. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  89222. {
  89223. size2 += size1;
  89224. if(size2 < size1)
  89225. return 0;
  89226. size3 += size2;
  89227. if(size3 < size2)
  89228. return 0;
  89229. return safe_malloc_(size3);
  89230. }
  89231. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  89232. {
  89233. size2 += size1;
  89234. if(size2 < size1)
  89235. return 0;
  89236. size3 += size2;
  89237. if(size3 < size2)
  89238. return 0;
  89239. size4 += size3;
  89240. if(size4 < size3)
  89241. return 0;
  89242. return safe_malloc_(size4);
  89243. }
  89244. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  89245. #if 0
  89246. needs support for cases where sizeof(size_t) != 4
  89247. {
  89248. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  89249. if(sizeof(size_t) == 4) {
  89250. if ((double)size1 * (double)size2 < 4294967296.0)
  89251. return malloc(size1*size2);
  89252. }
  89253. return 0;
  89254. }
  89255. #else
  89256. /* better? */
  89257. {
  89258. if(!size1 || !size2)
  89259. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89260. if(size1 > SIZE_MAX / size2)
  89261. return 0;
  89262. return malloc(size1*size2);
  89263. }
  89264. #endif
  89265. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  89266. {
  89267. if(!size1 || !size2 || !size3)
  89268. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89269. if(size1 > SIZE_MAX / size2)
  89270. return 0;
  89271. size1 *= size2;
  89272. if(size1 > SIZE_MAX / size3)
  89273. return 0;
  89274. return malloc(size1*size3);
  89275. }
  89276. /* size1*size2 + size3 */
  89277. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  89278. {
  89279. if(!size1 || !size2)
  89280. return safe_malloc_(size3);
  89281. if(size1 > SIZE_MAX / size2)
  89282. return 0;
  89283. return safe_malloc_add_2op_(size1*size2, size3);
  89284. }
  89285. /* size1 * (size2 + size3) */
  89286. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  89287. {
  89288. if(!size1 || (!size2 && !size3))
  89289. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89290. size2 += size3;
  89291. if(size2 < size3)
  89292. return 0;
  89293. return safe_malloc_mul_2op_(size1, size2);
  89294. }
  89295. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  89296. {
  89297. size2 += size1;
  89298. if(size2 < size1)
  89299. return 0;
  89300. return realloc(ptr, size2);
  89301. }
  89302. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  89303. {
  89304. size2 += size1;
  89305. if(size2 < size1)
  89306. return 0;
  89307. size3 += size2;
  89308. if(size3 < size2)
  89309. return 0;
  89310. return realloc(ptr, size3);
  89311. }
  89312. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  89313. {
  89314. size2 += size1;
  89315. if(size2 < size1)
  89316. return 0;
  89317. size3 += size2;
  89318. if(size3 < size2)
  89319. return 0;
  89320. size4 += size3;
  89321. if(size4 < size3)
  89322. return 0;
  89323. return realloc(ptr, size4);
  89324. }
  89325. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  89326. {
  89327. if(!size1 || !size2)
  89328. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  89329. if(size1 > SIZE_MAX / size2)
  89330. return 0;
  89331. return realloc(ptr, size1*size2);
  89332. }
  89333. /* size1 * (size2 + size3) */
  89334. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  89335. {
  89336. if(!size1 || (!size2 && !size3))
  89337. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  89338. size2 += size3;
  89339. if(size2 < size3)
  89340. return 0;
  89341. return safe_realloc_mul_2op_(ptr, size1, size2);
  89342. }
  89343. #endif
  89344. /********* End of inlined file: alloc.h *********/
  89345. /* Things should be fastest when this matches the machine word size */
  89346. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  89347. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  89348. typedef FLAC__uint32 bwword;
  89349. #define FLAC__BYTES_PER_WORD 4
  89350. #define FLAC__BITS_PER_WORD 32
  89351. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  89352. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  89353. #if WORDS_BIGENDIAN
  89354. #define SWAP_BE_WORD_TO_HOST(x) (x)
  89355. #else
  89356. #ifdef _MSC_VER
  89357. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  89358. #else
  89359. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  89360. #endif
  89361. #endif
  89362. /*
  89363. * The default capacity here doesn't matter too much. The buffer always grows
  89364. * to hold whatever is written to it. Usually the encoder will stop adding at
  89365. * a frame or metadata block, then write that out and clear the buffer for the
  89366. * next one.
  89367. */
  89368. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  89369. /* When growing, increment 4K at a time */
  89370. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  89371. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  89372. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  89373. #ifdef min
  89374. #undef min
  89375. #endif
  89376. #define min(x,y) ((x)<(y)?(x):(y))
  89377. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  89378. #ifdef _MSC_VER
  89379. #define FLAC__U64L(x) x
  89380. #else
  89381. #define FLAC__U64L(x) x##LLU
  89382. #endif
  89383. #ifndef FLaC__INLINE
  89384. #define FLaC__INLINE
  89385. #endif
  89386. struct FLAC__BitWriter {
  89387. bwword *buffer;
  89388. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  89389. unsigned capacity; /* capacity of buffer in words */
  89390. unsigned words; /* # of complete words in buffer */
  89391. unsigned bits; /* # of used bits in accum */
  89392. };
  89393. /* * WATCHOUT: The current implementation only grows the buffer. */
  89394. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  89395. {
  89396. unsigned new_capacity;
  89397. bwword *new_buffer;
  89398. FLAC__ASSERT(0 != bw);
  89399. FLAC__ASSERT(0 != bw->buffer);
  89400. /* calculate total words needed to store 'bits_to_add' additional bits */
  89401. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  89402. /* it's possible (due to pessimism in the growth estimation that
  89403. * leads to this call) that we don't actually need to grow
  89404. */
  89405. if(bw->capacity >= new_capacity)
  89406. return true;
  89407. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  89408. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  89409. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  89410. /* make sure we got everything right */
  89411. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  89412. FLAC__ASSERT(new_capacity > bw->capacity);
  89413. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  89414. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  89415. if(new_buffer == 0)
  89416. return false;
  89417. bw->buffer = new_buffer;
  89418. bw->capacity = new_capacity;
  89419. return true;
  89420. }
  89421. /***********************************************************************
  89422. *
  89423. * Class constructor/destructor
  89424. *
  89425. ***********************************************************************/
  89426. FLAC__BitWriter *FLAC__bitwriter_new(void)
  89427. {
  89428. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  89429. /* note that calloc() sets all members to 0 for us */
  89430. return bw;
  89431. }
  89432. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  89433. {
  89434. FLAC__ASSERT(0 != bw);
  89435. FLAC__bitwriter_free(bw);
  89436. free(bw);
  89437. }
  89438. /***********************************************************************
  89439. *
  89440. * Public class methods
  89441. *
  89442. ***********************************************************************/
  89443. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  89444. {
  89445. FLAC__ASSERT(0 != bw);
  89446. bw->words = bw->bits = 0;
  89447. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  89448. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  89449. if(bw->buffer == 0)
  89450. return false;
  89451. return true;
  89452. }
  89453. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  89454. {
  89455. FLAC__ASSERT(0 != bw);
  89456. if(0 != bw->buffer)
  89457. free(bw->buffer);
  89458. bw->buffer = 0;
  89459. bw->capacity = 0;
  89460. bw->words = bw->bits = 0;
  89461. }
  89462. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  89463. {
  89464. bw->words = bw->bits = 0;
  89465. }
  89466. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  89467. {
  89468. unsigned i, j;
  89469. if(bw == 0) {
  89470. fprintf(out, "bitwriter is NULL\n");
  89471. }
  89472. else {
  89473. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  89474. for(i = 0; i < bw->words; i++) {
  89475. fprintf(out, "%08X: ", i);
  89476. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  89477. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  89478. fprintf(out, "\n");
  89479. }
  89480. if(bw->bits > 0) {
  89481. fprintf(out, "%08X: ", i);
  89482. for(j = 0; j < bw->bits; j++)
  89483. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  89484. fprintf(out, "\n");
  89485. }
  89486. }
  89487. }
  89488. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  89489. {
  89490. const FLAC__byte *buffer;
  89491. size_t bytes;
  89492. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  89493. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  89494. return false;
  89495. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  89496. FLAC__bitwriter_release_buffer(bw);
  89497. return true;
  89498. }
  89499. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  89500. {
  89501. const FLAC__byte *buffer;
  89502. size_t bytes;
  89503. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  89504. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  89505. return false;
  89506. *crc = FLAC__crc8(buffer, bytes);
  89507. FLAC__bitwriter_release_buffer(bw);
  89508. return true;
  89509. }
  89510. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  89511. {
  89512. return ((bw->bits & 7) == 0);
  89513. }
  89514. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  89515. {
  89516. return FLAC__TOTAL_BITS(bw);
  89517. }
  89518. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  89519. {
  89520. FLAC__ASSERT((bw->bits & 7) == 0);
  89521. /* double protection */
  89522. if(bw->bits & 7)
  89523. return false;
  89524. /* if we have bits in the accumulator we have to flush those to the buffer first */
  89525. if(bw->bits) {
  89526. FLAC__ASSERT(bw->words <= bw->capacity);
  89527. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  89528. return false;
  89529. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  89530. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  89531. }
  89532. /* now we can just return what we have */
  89533. *buffer = (FLAC__byte*)bw->buffer;
  89534. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  89535. return true;
  89536. }
  89537. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  89538. {
  89539. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  89540. * get-mode' flag could be added everywhere and then cleared here
  89541. */
  89542. (void)bw;
  89543. }
  89544. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  89545. {
  89546. unsigned n;
  89547. FLAC__ASSERT(0 != bw);
  89548. FLAC__ASSERT(0 != bw->buffer);
  89549. if(bits == 0)
  89550. return true;
  89551. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  89552. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  89553. return false;
  89554. /* first part gets to word alignment */
  89555. if(bw->bits) {
  89556. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  89557. bw->accum <<= n;
  89558. bits -= n;
  89559. bw->bits += n;
  89560. if(bw->bits == FLAC__BITS_PER_WORD) {
  89561. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89562. bw->bits = 0;
  89563. }
  89564. else
  89565. return true;
  89566. }
  89567. /* do whole words */
  89568. while(bits >= FLAC__BITS_PER_WORD) {
  89569. bw->buffer[bw->words++] = 0;
  89570. bits -= FLAC__BITS_PER_WORD;
  89571. }
  89572. /* do any leftovers */
  89573. if(bits > 0) {
  89574. bw->accum = 0;
  89575. bw->bits = bits;
  89576. }
  89577. return true;
  89578. }
  89579. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  89580. {
  89581. register unsigned left;
  89582. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89583. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89584. FLAC__ASSERT(0 != bw);
  89585. FLAC__ASSERT(0 != bw->buffer);
  89586. FLAC__ASSERT(bits <= 32);
  89587. if(bits == 0)
  89588. return true;
  89589. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  89590. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  89591. return false;
  89592. left = FLAC__BITS_PER_WORD - bw->bits;
  89593. if(bits < left) {
  89594. bw->accum <<= bits;
  89595. bw->accum |= val;
  89596. bw->bits += bits;
  89597. }
  89598. 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 */
  89599. bw->accum <<= left;
  89600. bw->accum |= val >> (bw->bits = bits - left);
  89601. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89602. bw->accum = val;
  89603. }
  89604. else {
  89605. bw->accum = val;
  89606. bw->bits = 0;
  89607. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  89608. }
  89609. return true;
  89610. }
  89611. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  89612. {
  89613. /* zero-out unused bits */
  89614. if(bits < 32)
  89615. val &= (~(0xffffffff << bits));
  89616. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  89617. }
  89618. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  89619. {
  89620. /* this could be a little faster but it's not used for much */
  89621. if(bits > 32) {
  89622. return
  89623. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  89624. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  89625. }
  89626. else
  89627. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  89628. }
  89629. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  89630. {
  89631. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  89632. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  89633. return false;
  89634. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  89635. return false;
  89636. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  89637. return false;
  89638. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  89639. return false;
  89640. return true;
  89641. }
  89642. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  89643. {
  89644. unsigned i;
  89645. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  89646. for(i = 0; i < nvals; i++) {
  89647. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  89648. return false;
  89649. }
  89650. return true;
  89651. }
  89652. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  89653. {
  89654. if(val < 32)
  89655. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  89656. else
  89657. return
  89658. FLAC__bitwriter_write_zeroes(bw, val) &&
  89659. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  89660. }
  89661. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  89662. {
  89663. FLAC__uint32 uval;
  89664. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  89665. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  89666. uval = (val<<1) ^ (val>>31);
  89667. return 1 + parameter + (uval >> parameter);
  89668. }
  89669. #if 0 /* UNUSED */
  89670. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  89671. {
  89672. unsigned bits, msbs, uval;
  89673. unsigned k;
  89674. FLAC__ASSERT(parameter > 0);
  89675. /* fold signed to unsigned */
  89676. if(val < 0)
  89677. uval = (unsigned)(((-(++val)) << 1) + 1);
  89678. else
  89679. uval = (unsigned)(val << 1);
  89680. k = FLAC__bitmath_ilog2(parameter);
  89681. if(parameter == 1u<<k) {
  89682. FLAC__ASSERT(k <= 30);
  89683. msbs = uval >> k;
  89684. bits = 1 + k + msbs;
  89685. }
  89686. else {
  89687. unsigned q, r, d;
  89688. d = (1 << (k+1)) - parameter;
  89689. q = uval / parameter;
  89690. r = uval - (q * parameter);
  89691. bits = 1 + q + k;
  89692. if(r >= d)
  89693. bits++;
  89694. }
  89695. return bits;
  89696. }
  89697. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  89698. {
  89699. unsigned bits, msbs;
  89700. unsigned k;
  89701. FLAC__ASSERT(parameter > 0);
  89702. k = FLAC__bitmath_ilog2(parameter);
  89703. if(parameter == 1u<<k) {
  89704. FLAC__ASSERT(k <= 30);
  89705. msbs = uval >> k;
  89706. bits = 1 + k + msbs;
  89707. }
  89708. else {
  89709. unsigned q, r, d;
  89710. d = (1 << (k+1)) - parameter;
  89711. q = uval / parameter;
  89712. r = uval - (q * parameter);
  89713. bits = 1 + q + k;
  89714. if(r >= d)
  89715. bits++;
  89716. }
  89717. return bits;
  89718. }
  89719. #endif /* UNUSED */
  89720. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  89721. {
  89722. unsigned total_bits, interesting_bits, msbs;
  89723. FLAC__uint32 uval, pattern;
  89724. FLAC__ASSERT(0 != bw);
  89725. FLAC__ASSERT(0 != bw->buffer);
  89726. FLAC__ASSERT(parameter < 8*sizeof(uval));
  89727. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  89728. uval = (val<<1) ^ (val>>31);
  89729. msbs = uval >> parameter;
  89730. interesting_bits = 1 + parameter;
  89731. total_bits = interesting_bits + msbs;
  89732. pattern = 1 << parameter; /* the unary end bit */
  89733. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  89734. if(total_bits <= 32)
  89735. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  89736. else
  89737. return
  89738. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  89739. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  89740. }
  89741. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  89742. {
  89743. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  89744. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  89745. FLAC__uint32 uval;
  89746. unsigned left;
  89747. const unsigned lsbits = 1 + parameter;
  89748. unsigned msbits;
  89749. FLAC__ASSERT(0 != bw);
  89750. FLAC__ASSERT(0 != bw->buffer);
  89751. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  89752. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89753. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89754. while(nvals) {
  89755. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  89756. uval = (*vals<<1) ^ (*vals>>31);
  89757. msbits = uval >> parameter;
  89758. #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) */
  89759. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  89760. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  89761. bw->bits = bw->bits + msbits + lsbits;
  89762. uval |= mask1; /* set stop bit */
  89763. uval &= mask2; /* mask off unused top bits */
  89764. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  89765. bw->accum <<= msbits;
  89766. bw->accum <<= lsbits;
  89767. bw->accum |= uval;
  89768. if(bw->bits == FLAC__BITS_PER_WORD) {
  89769. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89770. bw->bits = 0;
  89771. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  89772. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  89773. FLAC__ASSERT(bw->capacity == bw->words);
  89774. return false;
  89775. }
  89776. }
  89777. }
  89778. else {
  89779. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  89780. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  89781. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  89782. bw->bits = bw->bits + msbits + lsbits;
  89783. uval |= mask1; /* set stop bit */
  89784. uval &= mask2; /* mask off unused top bits */
  89785. bw->accum <<= msbits + lsbits;
  89786. bw->accum |= uval;
  89787. }
  89788. else {
  89789. #endif
  89790. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  89791. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  89792. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  89793. return false;
  89794. if(msbits) {
  89795. /* first part gets to word alignment */
  89796. if(bw->bits) {
  89797. left = FLAC__BITS_PER_WORD - bw->bits;
  89798. if(msbits < left) {
  89799. bw->accum <<= msbits;
  89800. bw->bits += msbits;
  89801. goto break1;
  89802. }
  89803. else {
  89804. bw->accum <<= left;
  89805. msbits -= left;
  89806. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89807. bw->bits = 0;
  89808. }
  89809. }
  89810. /* do whole words */
  89811. while(msbits >= FLAC__BITS_PER_WORD) {
  89812. bw->buffer[bw->words++] = 0;
  89813. msbits -= FLAC__BITS_PER_WORD;
  89814. }
  89815. /* do any leftovers */
  89816. if(msbits > 0) {
  89817. bw->accum = 0;
  89818. bw->bits = msbits;
  89819. }
  89820. }
  89821. break1:
  89822. uval |= mask1; /* set stop bit */
  89823. uval &= mask2; /* mask off unused top bits */
  89824. left = FLAC__BITS_PER_WORD - bw->bits;
  89825. if(lsbits < left) {
  89826. bw->accum <<= lsbits;
  89827. bw->accum |= uval;
  89828. bw->bits += lsbits;
  89829. }
  89830. else {
  89831. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  89832. * be > lsbits (because of previous assertions) so it would have
  89833. * triggered the (lsbits<left) case above.
  89834. */
  89835. FLAC__ASSERT(bw->bits);
  89836. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  89837. bw->accum <<= left;
  89838. bw->accum |= uval >> (bw->bits = lsbits - left);
  89839. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89840. bw->accum = uval;
  89841. }
  89842. #if 1
  89843. }
  89844. #endif
  89845. vals++;
  89846. nvals--;
  89847. }
  89848. return true;
  89849. }
  89850. #if 0 /* UNUSED */
  89851. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  89852. {
  89853. unsigned total_bits, msbs, uval;
  89854. unsigned k;
  89855. FLAC__ASSERT(0 != bw);
  89856. FLAC__ASSERT(0 != bw->buffer);
  89857. FLAC__ASSERT(parameter > 0);
  89858. /* fold signed to unsigned */
  89859. if(val < 0)
  89860. uval = (unsigned)(((-(++val)) << 1) + 1);
  89861. else
  89862. uval = (unsigned)(val << 1);
  89863. k = FLAC__bitmath_ilog2(parameter);
  89864. if(parameter == 1u<<k) {
  89865. unsigned pattern;
  89866. FLAC__ASSERT(k <= 30);
  89867. msbs = uval >> k;
  89868. total_bits = 1 + k + msbs;
  89869. pattern = 1 << k; /* the unary end bit */
  89870. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  89871. if(total_bits <= 32) {
  89872. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  89873. return false;
  89874. }
  89875. else {
  89876. /* write the unary MSBs */
  89877. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  89878. return false;
  89879. /* write the unary end bit and binary LSBs */
  89880. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  89881. return false;
  89882. }
  89883. }
  89884. else {
  89885. unsigned q, r, d;
  89886. d = (1 << (k+1)) - parameter;
  89887. q = uval / parameter;
  89888. r = uval - (q * parameter);
  89889. /* write the unary MSBs */
  89890. if(!FLAC__bitwriter_write_zeroes(bw, q))
  89891. return false;
  89892. /* write the unary end bit */
  89893. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  89894. return false;
  89895. /* write the binary LSBs */
  89896. if(r >= d) {
  89897. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  89898. return false;
  89899. }
  89900. else {
  89901. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  89902. return false;
  89903. }
  89904. }
  89905. return true;
  89906. }
  89907. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  89908. {
  89909. unsigned total_bits, msbs;
  89910. unsigned k;
  89911. FLAC__ASSERT(0 != bw);
  89912. FLAC__ASSERT(0 != bw->buffer);
  89913. FLAC__ASSERT(parameter > 0);
  89914. k = FLAC__bitmath_ilog2(parameter);
  89915. if(parameter == 1u<<k) {
  89916. unsigned pattern;
  89917. FLAC__ASSERT(k <= 30);
  89918. msbs = uval >> k;
  89919. total_bits = 1 + k + msbs;
  89920. pattern = 1 << k; /* the unary end bit */
  89921. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  89922. if(total_bits <= 32) {
  89923. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  89924. return false;
  89925. }
  89926. else {
  89927. /* write the unary MSBs */
  89928. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  89929. return false;
  89930. /* write the unary end bit and binary LSBs */
  89931. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  89932. return false;
  89933. }
  89934. }
  89935. else {
  89936. unsigned q, r, d;
  89937. d = (1 << (k+1)) - parameter;
  89938. q = uval / parameter;
  89939. r = uval - (q * parameter);
  89940. /* write the unary MSBs */
  89941. if(!FLAC__bitwriter_write_zeroes(bw, q))
  89942. return false;
  89943. /* write the unary end bit */
  89944. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  89945. return false;
  89946. /* write the binary LSBs */
  89947. if(r >= d) {
  89948. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  89949. return false;
  89950. }
  89951. else {
  89952. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  89953. return false;
  89954. }
  89955. }
  89956. return true;
  89957. }
  89958. #endif /* UNUSED */
  89959. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  89960. {
  89961. FLAC__bool ok = 1;
  89962. FLAC__ASSERT(0 != bw);
  89963. FLAC__ASSERT(0 != bw->buffer);
  89964. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  89965. if(val < 0x80) {
  89966. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  89967. }
  89968. else if(val < 0x800) {
  89969. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  89970. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89971. }
  89972. else if(val < 0x10000) {
  89973. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  89974. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89975. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89976. }
  89977. else if(val < 0x200000) {
  89978. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  89979. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  89980. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89981. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89982. }
  89983. else if(val < 0x4000000) {
  89984. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  89985. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  89986. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  89987. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89988. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89989. }
  89990. else {
  89991. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  89992. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  89993. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  89994. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  89995. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89996. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89997. }
  89998. return ok;
  89999. }
  90000. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  90001. {
  90002. FLAC__bool ok = 1;
  90003. FLAC__ASSERT(0 != bw);
  90004. FLAC__ASSERT(0 != bw->buffer);
  90005. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  90006. if(val < 0x80) {
  90007. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  90008. }
  90009. else if(val < 0x800) {
  90010. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  90011. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90012. }
  90013. else if(val < 0x10000) {
  90014. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  90015. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90016. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90017. }
  90018. else if(val < 0x200000) {
  90019. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  90020. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90021. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90022. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90023. }
  90024. else if(val < 0x4000000) {
  90025. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  90026. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90027. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90028. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90029. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90030. }
  90031. else if(val < 0x80000000) {
  90032. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  90033. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  90034. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90035. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90036. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90037. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90038. }
  90039. else {
  90040. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  90041. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  90042. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  90043. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90044. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90045. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90046. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90047. }
  90048. return ok;
  90049. }
  90050. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  90051. {
  90052. /* 0-pad to byte boundary */
  90053. if(bw->bits & 7u)
  90054. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  90055. else
  90056. return true;
  90057. }
  90058. #endif
  90059. /********* End of inlined file: bitwriter.c *********/
  90060. /********* Start of inlined file: cpu.c *********/
  90061. /********* Start of inlined file: juce_FlacHeader.h *********/
  90062. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90063. // tasks..
  90064. #define VERSION "1.2.1"
  90065. #define FLAC__NO_DLL 1
  90066. #ifdef _MSC_VER
  90067. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90068. #endif
  90069. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90070. #define FLAC__SYS_DARWIN 1
  90071. #endif
  90072. /********* End of inlined file: juce_FlacHeader.h *********/
  90073. #if JUCE_USE_FLAC
  90074. #if HAVE_CONFIG_H
  90075. # include <config.h>
  90076. #endif
  90077. #include <stdlib.h>
  90078. #include <stdio.h>
  90079. #if defined FLAC__CPU_IA32
  90080. # include <signal.h>
  90081. #elif defined FLAC__CPU_PPC
  90082. # if !defined FLAC__NO_ASM
  90083. # if defined FLAC__SYS_DARWIN
  90084. # include <sys/sysctl.h>
  90085. # include <mach/mach.h>
  90086. # include <mach/mach_host.h>
  90087. # include <mach/host_info.h>
  90088. # include <mach/machine.h>
  90089. # ifndef CPU_SUBTYPE_POWERPC_970
  90090. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  90091. # endif
  90092. # else /* FLAC__SYS_DARWIN */
  90093. # include <signal.h>
  90094. # include <setjmp.h>
  90095. static sigjmp_buf jmpbuf;
  90096. static volatile sig_atomic_t canjump = 0;
  90097. static void sigill_handler (int sig)
  90098. {
  90099. if (!canjump) {
  90100. signal (sig, SIG_DFL);
  90101. raise (sig);
  90102. }
  90103. canjump = 0;
  90104. siglongjmp (jmpbuf, 1);
  90105. }
  90106. # endif /* FLAC__SYS_DARWIN */
  90107. # endif /* FLAC__NO_ASM */
  90108. #endif /* FLAC__CPU_PPC */
  90109. #if defined (__NetBSD__) || defined(__OpenBSD__)
  90110. #include <sys/param.h>
  90111. #include <sys/sysctl.h>
  90112. #include <machine/cpu.h>
  90113. #endif
  90114. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  90115. #include <sys/types.h>
  90116. #include <sys/sysctl.h>
  90117. #endif
  90118. #if defined(__APPLE__)
  90119. /* how to get sysctlbyname()? */
  90120. #endif
  90121. /* these are flags in EDX of CPUID AX=00000001 */
  90122. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  90123. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  90124. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  90125. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  90126. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  90127. /* these are flags in ECX of CPUID AX=00000001 */
  90128. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  90129. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  90130. /* these are flags in EDX of CPUID AX=80000001 */
  90131. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  90132. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  90133. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  90134. /*
  90135. * Extra stuff needed for detection of OS support for SSE on IA-32
  90136. */
  90137. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  90138. # if defined(__linux__)
  90139. /*
  90140. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  90141. * modify the return address to jump over the offending SSE instruction
  90142. * and also the operation following it that indicates the instruction
  90143. * executed successfully. In this way we use no global variables and
  90144. * stay thread-safe.
  90145. *
  90146. * 3 + 3 + 6:
  90147. * 3 bytes for "xorps xmm0,xmm0"
  90148. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  90149. * 6 bytes extra in case our estimate is wrong
  90150. * 12 bytes puts us in the NOP "landing zone"
  90151. */
  90152. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  90153. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  90154. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  90155. {
  90156. (void)signal;
  90157. sc.eip += 3 + 3 + 6;
  90158. }
  90159. # else
  90160. # include <sys/ucontext.h>
  90161. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  90162. {
  90163. (void)signal, (void)si;
  90164. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  90165. }
  90166. # endif
  90167. # elif defined(_MSC_VER)
  90168. # include <windows.h>
  90169. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  90170. # ifdef USE_TRY_CATCH_FLAVOR
  90171. # else
  90172. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  90173. {
  90174. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  90175. ep->ContextRecord->Eip += 3 + 3 + 6;
  90176. return EXCEPTION_CONTINUE_EXECUTION;
  90177. }
  90178. return EXCEPTION_CONTINUE_SEARCH;
  90179. }
  90180. # endif
  90181. # endif
  90182. #endif
  90183. void FLAC__cpu_info(FLAC__CPUInfo *info)
  90184. {
  90185. /*
  90186. * IA32-specific
  90187. */
  90188. #ifdef FLAC__CPU_IA32
  90189. info->type = FLAC__CPUINFO_TYPE_IA32;
  90190. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  90191. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  90192. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  90193. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  90194. info->data.ia32.cmov = false;
  90195. info->data.ia32.mmx = false;
  90196. info->data.ia32.fxsr = false;
  90197. info->data.ia32.sse = false;
  90198. info->data.ia32.sse2 = false;
  90199. info->data.ia32.sse3 = false;
  90200. info->data.ia32.ssse3 = false;
  90201. info->data.ia32._3dnow = false;
  90202. info->data.ia32.ext3dnow = false;
  90203. info->data.ia32.extmmx = false;
  90204. if(info->data.ia32.cpuid) {
  90205. /* http://www.sandpile.org/ia32/cpuid.htm */
  90206. FLAC__uint32 flags_edx, flags_ecx;
  90207. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  90208. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  90209. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  90210. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  90211. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  90212. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  90213. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  90214. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  90215. #ifdef FLAC__USE_3DNOW
  90216. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  90217. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  90218. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  90219. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  90220. #else
  90221. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  90222. #endif
  90223. #ifdef DEBUG
  90224. fprintf(stderr, "CPU info (IA-32):\n");
  90225. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  90226. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  90227. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  90228. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  90229. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  90230. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  90231. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  90232. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  90233. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  90234. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  90235. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  90236. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  90237. #endif
  90238. /*
  90239. * now have to check for OS support of SSE/SSE2
  90240. */
  90241. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  90242. #if defined FLAC__NO_SSE_OS
  90243. /* assume user knows better than us; turn it off */
  90244. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90245. #elif defined FLAC__SSE_OS
  90246. /* assume user knows better than us; leave as detected above */
  90247. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  90248. int sse = 0;
  90249. size_t len;
  90250. /* at least one of these must work: */
  90251. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  90252. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  90253. if(!sse)
  90254. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90255. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  90256. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  90257. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  90258. size_t len = sizeof(val);
  90259. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  90260. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90261. else { /* double-check SSE2 */
  90262. mib[1] = CPU_SSE2;
  90263. len = sizeof(val);
  90264. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  90265. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90266. }
  90267. # else
  90268. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90269. # endif
  90270. #elif defined(__linux__)
  90271. int sse = 0;
  90272. struct sigaction sigill_save;
  90273. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  90274. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  90275. #else
  90276. struct sigaction sigill_sse;
  90277. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  90278. __sigemptyset(&sigill_sse.sa_mask);
  90279. 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 */
  90280. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  90281. #endif
  90282. {
  90283. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  90284. /* see sigill_handler_sse_os() for an explanation of the following: */
  90285. asm volatile (
  90286. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  90287. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  90288. "incl %0\n\t" /* SIGILL handler will jump over this */
  90289. /* landing zone */
  90290. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  90291. "nop\n\t"
  90292. "nop\n\t"
  90293. "nop\n\t"
  90294. "nop\n\t"
  90295. "nop\n\t"
  90296. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  90297. "nop\n\t"
  90298. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  90299. : "=r"(sse)
  90300. : "r"(sse)
  90301. );
  90302. sigaction(SIGILL, &sigill_save, NULL);
  90303. }
  90304. if(!sse)
  90305. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90306. #elif defined(_MSC_VER)
  90307. # ifdef USE_TRY_CATCH_FLAVOR
  90308. _try {
  90309. __asm {
  90310. # if _MSC_VER <= 1200
  90311. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  90312. _emit 0x0F
  90313. _emit 0x57
  90314. _emit 0xC0
  90315. # else
  90316. xorps xmm0,xmm0
  90317. # endif
  90318. }
  90319. }
  90320. _except(EXCEPTION_EXECUTE_HANDLER) {
  90321. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  90322. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90323. }
  90324. # else
  90325. int sse = 0;
  90326. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  90327. /* see GCC version above for explanation */
  90328. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  90329. /* http://www.codeproject.com/cpp/gccasm.asp */
  90330. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  90331. __asm {
  90332. # if _MSC_VER <= 1200
  90333. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  90334. _emit 0x0F
  90335. _emit 0x57
  90336. _emit 0xC0
  90337. # else
  90338. xorps xmm0,xmm0
  90339. # endif
  90340. inc sse
  90341. nop
  90342. nop
  90343. nop
  90344. nop
  90345. nop
  90346. nop
  90347. nop
  90348. nop
  90349. nop
  90350. }
  90351. SetUnhandledExceptionFilter(save);
  90352. if(!sse)
  90353. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90354. # endif
  90355. #else
  90356. /* no way to test, disable to be safe */
  90357. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90358. #endif
  90359. #ifdef DEBUG
  90360. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  90361. #endif
  90362. }
  90363. }
  90364. #else
  90365. info->use_asm = false;
  90366. #endif
  90367. /*
  90368. * PPC-specific
  90369. */
  90370. #elif defined FLAC__CPU_PPC
  90371. info->type = FLAC__CPUINFO_TYPE_PPC;
  90372. # if !defined FLAC__NO_ASM
  90373. info->use_asm = true;
  90374. # ifdef FLAC__USE_ALTIVEC
  90375. # if defined FLAC__SYS_DARWIN
  90376. {
  90377. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  90378. size_t len = sizeof(val);
  90379. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  90380. }
  90381. {
  90382. host_basic_info_data_t hostInfo;
  90383. mach_msg_type_number_t infoCount;
  90384. infoCount = HOST_BASIC_INFO_COUNT;
  90385. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  90386. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  90387. }
  90388. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  90389. {
  90390. /* no Darwin, do it the brute-force way */
  90391. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  90392. info->data.ppc.altivec = 0;
  90393. info->data.ppc.ppc64 = 0;
  90394. signal (SIGILL, sigill_handler);
  90395. canjump = 0;
  90396. if (!sigsetjmp (jmpbuf, 1)) {
  90397. canjump = 1;
  90398. asm volatile (
  90399. "mtspr 256, %0\n\t"
  90400. "vand %%v0, %%v0, %%v0"
  90401. :
  90402. : "r" (-1)
  90403. );
  90404. info->data.ppc.altivec = 1;
  90405. }
  90406. canjump = 0;
  90407. if (!sigsetjmp (jmpbuf, 1)) {
  90408. int x = 0;
  90409. canjump = 1;
  90410. /* PPC64 hardware implements the cntlzd instruction */
  90411. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  90412. info->data.ppc.ppc64 = 1;
  90413. }
  90414. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  90415. }
  90416. # endif
  90417. # else /* !FLAC__USE_ALTIVEC */
  90418. info->data.ppc.altivec = 0;
  90419. info->data.ppc.ppc64 = 0;
  90420. # endif
  90421. # else
  90422. info->use_asm = false;
  90423. # endif
  90424. /*
  90425. * unknown CPI
  90426. */
  90427. #else
  90428. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  90429. info->use_asm = false;
  90430. #endif
  90431. }
  90432. #endif
  90433. /********* End of inlined file: cpu.c *********/
  90434. /********* Start of inlined file: crc.c *********/
  90435. /********* Start of inlined file: juce_FlacHeader.h *********/
  90436. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90437. // tasks..
  90438. #define VERSION "1.2.1"
  90439. #define FLAC__NO_DLL 1
  90440. #ifdef _MSC_VER
  90441. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90442. #endif
  90443. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90444. #define FLAC__SYS_DARWIN 1
  90445. #endif
  90446. /********* End of inlined file: juce_FlacHeader.h *********/
  90447. #if JUCE_USE_FLAC
  90448. #if HAVE_CONFIG_H
  90449. # include <config.h>
  90450. #endif
  90451. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  90452. FLAC__byte const FLAC__crc8_table[256] = {
  90453. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  90454. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  90455. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  90456. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  90457. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  90458. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  90459. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  90460. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  90461. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  90462. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  90463. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  90464. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  90465. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  90466. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  90467. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  90468. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  90469. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  90470. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  90471. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  90472. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  90473. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  90474. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  90475. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  90476. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  90477. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  90478. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  90479. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  90480. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  90481. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  90482. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  90483. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  90484. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  90485. };
  90486. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  90487. unsigned FLAC__crc16_table[256] = {
  90488. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  90489. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  90490. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  90491. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  90492. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  90493. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  90494. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  90495. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  90496. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  90497. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  90498. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  90499. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  90500. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  90501. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  90502. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  90503. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  90504. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  90505. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  90506. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  90507. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  90508. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  90509. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  90510. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  90511. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  90512. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  90513. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  90514. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  90515. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  90516. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  90517. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  90518. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  90519. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  90520. };
  90521. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  90522. {
  90523. *crc = FLAC__crc8_table[*crc ^ data];
  90524. }
  90525. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  90526. {
  90527. while(len--)
  90528. *crc = FLAC__crc8_table[*crc ^ *data++];
  90529. }
  90530. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  90531. {
  90532. FLAC__uint8 crc = 0;
  90533. while(len--)
  90534. crc = FLAC__crc8_table[crc ^ *data++];
  90535. return crc;
  90536. }
  90537. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  90538. {
  90539. unsigned crc = 0;
  90540. while(len--)
  90541. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  90542. return crc;
  90543. }
  90544. #endif
  90545. /********* End of inlined file: crc.c *********/
  90546. /********* Start of inlined file: fixed.c *********/
  90547. /********* Start of inlined file: juce_FlacHeader.h *********/
  90548. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90549. // tasks..
  90550. #define VERSION "1.2.1"
  90551. #define FLAC__NO_DLL 1
  90552. #ifdef _MSC_VER
  90553. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90554. #endif
  90555. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90556. #define FLAC__SYS_DARWIN 1
  90557. #endif
  90558. /********* End of inlined file: juce_FlacHeader.h *********/
  90559. #if JUCE_USE_FLAC
  90560. #if HAVE_CONFIG_H
  90561. # include <config.h>
  90562. #endif
  90563. #include <math.h>
  90564. #include <string.h>
  90565. /********* Start of inlined file: fixed.h *********/
  90566. #ifndef FLAC__PRIVATE__FIXED_H
  90567. #define FLAC__PRIVATE__FIXED_H
  90568. #ifdef HAVE_CONFIG_H
  90569. #include <config.h>
  90570. #endif
  90571. /********* Start of inlined file: float.h *********/
  90572. #ifndef FLAC__PRIVATE__FLOAT_H
  90573. #define FLAC__PRIVATE__FLOAT_H
  90574. #ifdef HAVE_CONFIG_H
  90575. #include <config.h>
  90576. #endif
  90577. /*
  90578. * These typedefs make it easier to ensure that integer versions of
  90579. * the library really only contain integer operations. All the code
  90580. * in libFLAC should use FLAC__float and FLAC__double in place of
  90581. * float and double, and be protected by checks of the macro
  90582. * FLAC__INTEGER_ONLY_LIBRARY.
  90583. *
  90584. * FLAC__real is the basic floating point type used in LPC analysis.
  90585. */
  90586. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90587. typedef double FLAC__double;
  90588. typedef float FLAC__float;
  90589. /*
  90590. * WATCHOUT: changing FLAC__real will change the signatures of many
  90591. * functions that have assembly language equivalents and break them.
  90592. */
  90593. typedef float FLAC__real;
  90594. #else
  90595. /*
  90596. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  90597. * for the integer part and lower 16 bits for the fractional part.
  90598. */
  90599. typedef FLAC__int32 FLAC__fixedpoint;
  90600. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  90601. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  90602. extern const FLAC__fixedpoint FLAC__FP_ONE;
  90603. extern const FLAC__fixedpoint FLAC__FP_LN2;
  90604. extern const FLAC__fixedpoint FLAC__FP_E;
  90605. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  90606. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  90607. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  90608. /*
  90609. * FLAC__fixedpoint_log2()
  90610. * --------------------------------------------------------------------
  90611. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  90612. * algorithm by Knuth for x >= 1.0
  90613. *
  90614. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  90615. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  90616. *
  90617. * 'precision' roughly limits the number of iterations that are done;
  90618. * use (unsigned)(-1) for maximum precision.
  90619. *
  90620. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  90621. * function will punt and return 0.
  90622. *
  90623. * The return value will also have 'fracbits' fractional bits.
  90624. */
  90625. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  90626. #endif
  90627. #endif
  90628. /********* End of inlined file: float.h *********/
  90629. /********* Start of inlined file: format.h *********/
  90630. #ifndef FLAC__PRIVATE__FORMAT_H
  90631. #define FLAC__PRIVATE__FORMAT_H
  90632. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  90633. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  90634. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  90635. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  90636. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  90637. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  90638. #endif
  90639. /********* End of inlined file: format.h *********/
  90640. /*
  90641. * FLAC__fixed_compute_best_predictor()
  90642. * --------------------------------------------------------------------
  90643. * Compute the best fixed predictor and the expected bits-per-sample
  90644. * of the residual signal for each order. The _wide() version uses
  90645. * 64-bit integers which is statistically necessary when bits-per-
  90646. * sample + log2(blocksize) > 30
  90647. *
  90648. * IN data[0,data_len-1]
  90649. * IN data_len
  90650. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  90651. */
  90652. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90653. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  90654. # ifndef FLAC__NO_ASM
  90655. # ifdef FLAC__CPU_IA32
  90656. # ifdef FLAC__HAS_NASM
  90657. 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]);
  90658. # endif
  90659. # endif
  90660. # endif
  90661. 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]);
  90662. #else
  90663. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  90664. 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]);
  90665. #endif
  90666. /*
  90667. * FLAC__fixed_compute_residual()
  90668. * --------------------------------------------------------------------
  90669. * Compute the residual signal obtained from sutracting the predicted
  90670. * signal from the original.
  90671. *
  90672. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  90673. * IN data_len length of original signal
  90674. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  90675. * OUT residual[0,data_len-1] residual signal
  90676. */
  90677. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  90678. /*
  90679. * FLAC__fixed_restore_signal()
  90680. * --------------------------------------------------------------------
  90681. * Restore the original signal by summing the residual and the
  90682. * predictor.
  90683. *
  90684. * IN residual[0,data_len-1] residual signal
  90685. * IN data_len length of original signal
  90686. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  90687. * *** IMPORTANT: the caller must pass in the historical samples:
  90688. * IN data[-order,-1] previously-reconstructed historical samples
  90689. * OUT data[0,data_len-1] original signal
  90690. */
  90691. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  90692. #endif
  90693. /********* End of inlined file: fixed.h *********/
  90694. #ifndef M_LN2
  90695. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  90696. #define M_LN2 0.69314718055994530942
  90697. #endif
  90698. #ifdef min
  90699. #undef min
  90700. #endif
  90701. #define min(x,y) ((x) < (y)? (x) : (y))
  90702. #ifdef local_abs
  90703. #undef local_abs
  90704. #endif
  90705. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  90706. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  90707. /* rbps stands for residual bits per sample
  90708. *
  90709. * (ln(2) * err)
  90710. * rbps = log (-----------)
  90711. * 2 ( n )
  90712. */
  90713. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  90714. {
  90715. FLAC__uint32 rbps;
  90716. unsigned bits; /* the number of bits required to represent a number */
  90717. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  90718. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  90719. FLAC__ASSERT(err > 0);
  90720. FLAC__ASSERT(n > 0);
  90721. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  90722. if(err <= n)
  90723. return 0;
  90724. /*
  90725. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  90726. * These allow us later to know we won't lose too much precision in the
  90727. * fixed-point division (err<<fracbits)/n.
  90728. */
  90729. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  90730. err <<= fracbits;
  90731. err /= n;
  90732. /* err now holds err/n with fracbits fractional bits */
  90733. /*
  90734. * Whittle err down to 16 bits max. 16 significant bits is enough for
  90735. * our purposes.
  90736. */
  90737. FLAC__ASSERT(err > 0);
  90738. bits = FLAC__bitmath_ilog2(err)+1;
  90739. if(bits > 16) {
  90740. err >>= (bits-16);
  90741. fracbits -= (bits-16);
  90742. }
  90743. rbps = (FLAC__uint32)err;
  90744. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  90745. rbps *= FLAC__FP_LN2;
  90746. fracbits += 16;
  90747. FLAC__ASSERT(fracbits >= 0);
  90748. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  90749. {
  90750. const int f = fracbits & 3;
  90751. if(f) {
  90752. rbps >>= f;
  90753. fracbits -= f;
  90754. }
  90755. }
  90756. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  90757. if(rbps == 0)
  90758. return 0;
  90759. /*
  90760. * The return value must have 16 fractional bits. Since the whole part
  90761. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  90762. * must be >= -3, these assertion allows us to be able to shift rbps
  90763. * left if necessary to get 16 fracbits without losing any bits of the
  90764. * whole part of rbps.
  90765. *
  90766. * There is a slight chance due to accumulated error that the whole part
  90767. * will require 6 bits, so we use 6 in the assertion. Really though as
  90768. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  90769. */
  90770. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  90771. FLAC__ASSERT(fracbits >= -3);
  90772. /* now shift the decimal point into place */
  90773. if(fracbits < 16)
  90774. return rbps << (16-fracbits);
  90775. else if(fracbits > 16)
  90776. return rbps >> (fracbits-16);
  90777. else
  90778. return rbps;
  90779. }
  90780. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  90781. {
  90782. FLAC__uint32 rbps;
  90783. unsigned bits; /* the number of bits required to represent a number */
  90784. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  90785. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  90786. FLAC__ASSERT(err > 0);
  90787. FLAC__ASSERT(n > 0);
  90788. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  90789. if(err <= n)
  90790. return 0;
  90791. /*
  90792. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  90793. * These allow us later to know we won't lose too much precision in the
  90794. * fixed-point division (err<<fracbits)/n.
  90795. */
  90796. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  90797. err <<= fracbits;
  90798. err /= n;
  90799. /* err now holds err/n with fracbits fractional bits */
  90800. /*
  90801. * Whittle err down to 16 bits max. 16 significant bits is enough for
  90802. * our purposes.
  90803. */
  90804. FLAC__ASSERT(err > 0);
  90805. bits = FLAC__bitmath_ilog2_wide(err)+1;
  90806. if(bits > 16) {
  90807. err >>= (bits-16);
  90808. fracbits -= (bits-16);
  90809. }
  90810. rbps = (FLAC__uint32)err;
  90811. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  90812. rbps *= FLAC__FP_LN2;
  90813. fracbits += 16;
  90814. FLAC__ASSERT(fracbits >= 0);
  90815. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  90816. {
  90817. const int f = fracbits & 3;
  90818. if(f) {
  90819. rbps >>= f;
  90820. fracbits -= f;
  90821. }
  90822. }
  90823. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  90824. if(rbps == 0)
  90825. return 0;
  90826. /*
  90827. * The return value must have 16 fractional bits. Since the whole part
  90828. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  90829. * must be >= -3, these assertion allows us to be able to shift rbps
  90830. * left if necessary to get 16 fracbits without losing any bits of the
  90831. * whole part of rbps.
  90832. *
  90833. * There is a slight chance due to accumulated error that the whole part
  90834. * will require 6 bits, so we use 6 in the assertion. Really though as
  90835. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  90836. */
  90837. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  90838. FLAC__ASSERT(fracbits >= -3);
  90839. /* now shift the decimal point into place */
  90840. if(fracbits < 16)
  90841. return rbps << (16-fracbits);
  90842. else if(fracbits > 16)
  90843. return rbps >> (fracbits-16);
  90844. else
  90845. return rbps;
  90846. }
  90847. #endif
  90848. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90849. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  90850. #else
  90851. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  90852. #endif
  90853. {
  90854. FLAC__int32 last_error_0 = data[-1];
  90855. FLAC__int32 last_error_1 = data[-1] - data[-2];
  90856. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  90857. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  90858. FLAC__int32 error, save;
  90859. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  90860. unsigned i, order;
  90861. for(i = 0; i < data_len; i++) {
  90862. error = data[i] ; total_error_0 += local_abs(error); save = error;
  90863. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  90864. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  90865. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  90866. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  90867. }
  90868. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  90869. order = 0;
  90870. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  90871. order = 1;
  90872. else if(total_error_2 < min(total_error_3, total_error_4))
  90873. order = 2;
  90874. else if(total_error_3 < total_error_4)
  90875. order = 3;
  90876. else
  90877. order = 4;
  90878. /* Estimate the expected number of bits per residual signal sample. */
  90879. /* 'total_error*' is linearly related to the variance of the residual */
  90880. /* signal, so we use it directly to compute E(|x|) */
  90881. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  90882. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  90883. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  90884. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  90885. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  90886. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90887. 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);
  90888. 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);
  90889. 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);
  90890. 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);
  90891. 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);
  90892. #else
  90893. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  90894. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  90895. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  90896. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  90897. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  90898. #endif
  90899. return order;
  90900. }
  90901. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90902. 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])
  90903. #else
  90904. 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])
  90905. #endif
  90906. {
  90907. FLAC__int32 last_error_0 = data[-1];
  90908. FLAC__int32 last_error_1 = data[-1] - data[-2];
  90909. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  90910. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  90911. FLAC__int32 error, save;
  90912. /* total_error_* are 64-bits to avoid overflow when encoding
  90913. * erratic signals when the bits-per-sample and blocksize are
  90914. * large.
  90915. */
  90916. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  90917. unsigned i, order;
  90918. for(i = 0; i < data_len; i++) {
  90919. error = data[i] ; total_error_0 += local_abs(error); save = error;
  90920. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  90921. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  90922. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  90923. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  90924. }
  90925. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  90926. order = 0;
  90927. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  90928. order = 1;
  90929. else if(total_error_2 < min(total_error_3, total_error_4))
  90930. order = 2;
  90931. else if(total_error_3 < total_error_4)
  90932. order = 3;
  90933. else
  90934. order = 4;
  90935. /* Estimate the expected number of bits per residual signal sample. */
  90936. /* 'total_error*' is linearly related to the variance of the residual */
  90937. /* signal, so we use it directly to compute E(|x|) */
  90938. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  90939. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  90940. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  90941. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  90942. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  90943. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90944. #if defined _MSC_VER || defined __MINGW32__
  90945. /* with MSVC you have to spoon feed it the casting */
  90946. 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);
  90947. 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);
  90948. 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);
  90949. 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);
  90950. 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);
  90951. #else
  90952. 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);
  90953. 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);
  90954. 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);
  90955. 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);
  90956. 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);
  90957. #endif
  90958. #else
  90959. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  90960. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  90961. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  90962. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  90963. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  90964. #endif
  90965. return order;
  90966. }
  90967. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  90968. {
  90969. const int idata_len = (int)data_len;
  90970. int i;
  90971. switch(order) {
  90972. case 0:
  90973. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  90974. memcpy(residual, data, sizeof(residual[0])*data_len);
  90975. break;
  90976. case 1:
  90977. for(i = 0; i < idata_len; i++)
  90978. residual[i] = data[i] - data[i-1];
  90979. break;
  90980. case 2:
  90981. for(i = 0; i < idata_len; i++)
  90982. #if 1 /* OPT: may be faster with some compilers on some systems */
  90983. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  90984. #else
  90985. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  90986. #endif
  90987. break;
  90988. case 3:
  90989. for(i = 0; i < idata_len; i++)
  90990. #if 1 /* OPT: may be faster with some compilers on some systems */
  90991. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  90992. #else
  90993. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  90994. #endif
  90995. break;
  90996. case 4:
  90997. for(i = 0; i < idata_len; i++)
  90998. #if 1 /* OPT: may be faster with some compilers on some systems */
  90999. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  91000. #else
  91001. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  91002. #endif
  91003. break;
  91004. default:
  91005. FLAC__ASSERT(0);
  91006. }
  91007. }
  91008. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  91009. {
  91010. int i, idata_len = (int)data_len;
  91011. switch(order) {
  91012. case 0:
  91013. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  91014. memcpy(data, residual, sizeof(residual[0])*data_len);
  91015. break;
  91016. case 1:
  91017. for(i = 0; i < idata_len; i++)
  91018. data[i] = residual[i] + data[i-1];
  91019. break;
  91020. case 2:
  91021. for(i = 0; i < idata_len; i++)
  91022. #if 1 /* OPT: may be faster with some compilers on some systems */
  91023. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  91024. #else
  91025. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  91026. #endif
  91027. break;
  91028. case 3:
  91029. for(i = 0; i < idata_len; i++)
  91030. #if 1 /* OPT: may be faster with some compilers on some systems */
  91031. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  91032. #else
  91033. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  91034. #endif
  91035. break;
  91036. case 4:
  91037. for(i = 0; i < idata_len; i++)
  91038. #if 1 /* OPT: may be faster with some compilers on some systems */
  91039. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  91040. #else
  91041. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  91042. #endif
  91043. break;
  91044. default:
  91045. FLAC__ASSERT(0);
  91046. }
  91047. }
  91048. #endif
  91049. /********* End of inlined file: fixed.c *********/
  91050. /********* Start of inlined file: float.c *********/
  91051. /********* Start of inlined file: juce_FlacHeader.h *********/
  91052. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91053. // tasks..
  91054. #define VERSION "1.2.1"
  91055. #define FLAC__NO_DLL 1
  91056. #ifdef _MSC_VER
  91057. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91058. #endif
  91059. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91060. #define FLAC__SYS_DARWIN 1
  91061. #endif
  91062. /********* End of inlined file: juce_FlacHeader.h *********/
  91063. #if JUCE_USE_FLAC
  91064. #if HAVE_CONFIG_H
  91065. # include <config.h>
  91066. #endif
  91067. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  91068. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  91069. #ifdef _MSC_VER
  91070. #define FLAC__U64L(x) x
  91071. #else
  91072. #define FLAC__U64L(x) x##LLU
  91073. #endif
  91074. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  91075. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  91076. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  91077. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  91078. const FLAC__fixedpoint FLAC__FP_E = 178145;
  91079. /* Lookup tables for Knuth's logarithm algorithm */
  91080. #define LOG2_LOOKUP_PRECISION 16
  91081. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  91082. {
  91083. /*
  91084. * 0 fraction bits
  91085. */
  91086. /* undefined */ 0x00000000,
  91087. /* lg(2/1) = */ 0x00000001,
  91088. /* lg(4/3) = */ 0x00000000,
  91089. /* lg(8/7) = */ 0x00000000,
  91090. /* lg(16/15) = */ 0x00000000,
  91091. /* lg(32/31) = */ 0x00000000,
  91092. /* lg(64/63) = */ 0x00000000,
  91093. /* lg(128/127) = */ 0x00000000,
  91094. /* lg(256/255) = */ 0x00000000,
  91095. /* lg(512/511) = */ 0x00000000,
  91096. /* lg(1024/1023) = */ 0x00000000,
  91097. /* lg(2048/2047) = */ 0x00000000,
  91098. /* lg(4096/4095) = */ 0x00000000,
  91099. /* lg(8192/8191) = */ 0x00000000,
  91100. /* lg(16384/16383) = */ 0x00000000,
  91101. /* lg(32768/32767) = */ 0x00000000
  91102. },
  91103. {
  91104. /*
  91105. * 4 fraction bits
  91106. */
  91107. /* undefined */ 0x00000000,
  91108. /* lg(2/1) = */ 0x00000010,
  91109. /* lg(4/3) = */ 0x00000007,
  91110. /* lg(8/7) = */ 0x00000003,
  91111. /* lg(16/15) = */ 0x00000001,
  91112. /* lg(32/31) = */ 0x00000001,
  91113. /* lg(64/63) = */ 0x00000000,
  91114. /* lg(128/127) = */ 0x00000000,
  91115. /* lg(256/255) = */ 0x00000000,
  91116. /* lg(512/511) = */ 0x00000000,
  91117. /* lg(1024/1023) = */ 0x00000000,
  91118. /* lg(2048/2047) = */ 0x00000000,
  91119. /* lg(4096/4095) = */ 0x00000000,
  91120. /* lg(8192/8191) = */ 0x00000000,
  91121. /* lg(16384/16383) = */ 0x00000000,
  91122. /* lg(32768/32767) = */ 0x00000000
  91123. },
  91124. {
  91125. /*
  91126. * 8 fraction bits
  91127. */
  91128. /* undefined */ 0x00000000,
  91129. /* lg(2/1) = */ 0x00000100,
  91130. /* lg(4/3) = */ 0x0000006a,
  91131. /* lg(8/7) = */ 0x00000031,
  91132. /* lg(16/15) = */ 0x00000018,
  91133. /* lg(32/31) = */ 0x0000000c,
  91134. /* lg(64/63) = */ 0x00000006,
  91135. /* lg(128/127) = */ 0x00000003,
  91136. /* lg(256/255) = */ 0x00000001,
  91137. /* lg(512/511) = */ 0x00000001,
  91138. /* lg(1024/1023) = */ 0x00000000,
  91139. /* lg(2048/2047) = */ 0x00000000,
  91140. /* lg(4096/4095) = */ 0x00000000,
  91141. /* lg(8192/8191) = */ 0x00000000,
  91142. /* lg(16384/16383) = */ 0x00000000,
  91143. /* lg(32768/32767) = */ 0x00000000
  91144. },
  91145. {
  91146. /*
  91147. * 12 fraction bits
  91148. */
  91149. /* undefined */ 0x00000000,
  91150. /* lg(2/1) = */ 0x00001000,
  91151. /* lg(4/3) = */ 0x000006a4,
  91152. /* lg(8/7) = */ 0x00000315,
  91153. /* lg(16/15) = */ 0x0000017d,
  91154. /* lg(32/31) = */ 0x000000bc,
  91155. /* lg(64/63) = */ 0x0000005d,
  91156. /* lg(128/127) = */ 0x0000002e,
  91157. /* lg(256/255) = */ 0x00000017,
  91158. /* lg(512/511) = */ 0x0000000c,
  91159. /* lg(1024/1023) = */ 0x00000006,
  91160. /* lg(2048/2047) = */ 0x00000003,
  91161. /* lg(4096/4095) = */ 0x00000001,
  91162. /* lg(8192/8191) = */ 0x00000001,
  91163. /* lg(16384/16383) = */ 0x00000000,
  91164. /* lg(32768/32767) = */ 0x00000000
  91165. },
  91166. {
  91167. /*
  91168. * 16 fraction bits
  91169. */
  91170. /* undefined */ 0x00000000,
  91171. /* lg(2/1) = */ 0x00010000,
  91172. /* lg(4/3) = */ 0x00006a40,
  91173. /* lg(8/7) = */ 0x00003151,
  91174. /* lg(16/15) = */ 0x000017d6,
  91175. /* lg(32/31) = */ 0x00000bba,
  91176. /* lg(64/63) = */ 0x000005d1,
  91177. /* lg(128/127) = */ 0x000002e6,
  91178. /* lg(256/255) = */ 0x00000172,
  91179. /* lg(512/511) = */ 0x000000b9,
  91180. /* lg(1024/1023) = */ 0x0000005c,
  91181. /* lg(2048/2047) = */ 0x0000002e,
  91182. /* lg(4096/4095) = */ 0x00000017,
  91183. /* lg(8192/8191) = */ 0x0000000c,
  91184. /* lg(16384/16383) = */ 0x00000006,
  91185. /* lg(32768/32767) = */ 0x00000003
  91186. },
  91187. {
  91188. /*
  91189. * 20 fraction bits
  91190. */
  91191. /* undefined */ 0x00000000,
  91192. /* lg(2/1) = */ 0x00100000,
  91193. /* lg(4/3) = */ 0x0006a3fe,
  91194. /* lg(8/7) = */ 0x00031513,
  91195. /* lg(16/15) = */ 0x00017d60,
  91196. /* lg(32/31) = */ 0x0000bb9d,
  91197. /* lg(64/63) = */ 0x00005d10,
  91198. /* lg(128/127) = */ 0x00002e59,
  91199. /* lg(256/255) = */ 0x00001721,
  91200. /* lg(512/511) = */ 0x00000b8e,
  91201. /* lg(1024/1023) = */ 0x000005c6,
  91202. /* lg(2048/2047) = */ 0x000002e3,
  91203. /* lg(4096/4095) = */ 0x00000171,
  91204. /* lg(8192/8191) = */ 0x000000b9,
  91205. /* lg(16384/16383) = */ 0x0000005c,
  91206. /* lg(32768/32767) = */ 0x0000002e
  91207. },
  91208. {
  91209. /*
  91210. * 24 fraction bits
  91211. */
  91212. /* undefined */ 0x00000000,
  91213. /* lg(2/1) = */ 0x01000000,
  91214. /* lg(4/3) = */ 0x006a3fe6,
  91215. /* lg(8/7) = */ 0x00315130,
  91216. /* lg(16/15) = */ 0x0017d605,
  91217. /* lg(32/31) = */ 0x000bb9ca,
  91218. /* lg(64/63) = */ 0x0005d0fc,
  91219. /* lg(128/127) = */ 0x0002e58f,
  91220. /* lg(256/255) = */ 0x0001720e,
  91221. /* lg(512/511) = */ 0x0000b8d8,
  91222. /* lg(1024/1023) = */ 0x00005c61,
  91223. /* lg(2048/2047) = */ 0x00002e2d,
  91224. /* lg(4096/4095) = */ 0x00001716,
  91225. /* lg(8192/8191) = */ 0x00000b8b,
  91226. /* lg(16384/16383) = */ 0x000005c5,
  91227. /* lg(32768/32767) = */ 0x000002e3
  91228. },
  91229. {
  91230. /*
  91231. * 28 fraction bits
  91232. */
  91233. /* undefined */ 0x00000000,
  91234. /* lg(2/1) = */ 0x10000000,
  91235. /* lg(4/3) = */ 0x06a3fe5c,
  91236. /* lg(8/7) = */ 0x03151301,
  91237. /* lg(16/15) = */ 0x017d6049,
  91238. /* lg(32/31) = */ 0x00bb9ca6,
  91239. /* lg(64/63) = */ 0x005d0fba,
  91240. /* lg(128/127) = */ 0x002e58f7,
  91241. /* lg(256/255) = */ 0x001720da,
  91242. /* lg(512/511) = */ 0x000b8d87,
  91243. /* lg(1024/1023) = */ 0x0005c60b,
  91244. /* lg(2048/2047) = */ 0x0002e2d7,
  91245. /* lg(4096/4095) = */ 0x00017160,
  91246. /* lg(8192/8191) = */ 0x0000b8ad,
  91247. /* lg(16384/16383) = */ 0x00005c56,
  91248. /* lg(32768/32767) = */ 0x00002e2b
  91249. }
  91250. };
  91251. #if 0
  91252. static const FLAC__uint64 log2_lookup_wide[] = {
  91253. {
  91254. /*
  91255. * 32 fraction bits
  91256. */
  91257. /* undefined */ 0x00000000,
  91258. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  91259. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  91260. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  91261. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  91262. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  91263. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  91264. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  91265. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  91266. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  91267. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  91268. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  91269. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  91270. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  91271. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  91272. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  91273. },
  91274. {
  91275. /*
  91276. * 48 fraction bits
  91277. */
  91278. /* undefined */ 0x00000000,
  91279. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  91280. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  91281. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  91282. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  91283. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  91284. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  91285. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  91286. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  91287. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  91288. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  91289. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  91290. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  91291. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  91292. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  91293. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  91294. }
  91295. };
  91296. #endif
  91297. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  91298. {
  91299. const FLAC__uint32 ONE = (1u << fracbits);
  91300. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  91301. FLAC__ASSERT(fracbits < 32);
  91302. FLAC__ASSERT((fracbits & 0x3) == 0);
  91303. if(x < ONE)
  91304. return 0;
  91305. if(precision > LOG2_LOOKUP_PRECISION)
  91306. precision = LOG2_LOOKUP_PRECISION;
  91307. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  91308. {
  91309. FLAC__uint32 y = 0;
  91310. FLAC__uint32 z = x >> 1, k = 1;
  91311. while (x > ONE && k < precision) {
  91312. if (x - z >= ONE) {
  91313. x -= z;
  91314. z = x >> k;
  91315. y += table[k];
  91316. }
  91317. else {
  91318. z >>= 1;
  91319. k++;
  91320. }
  91321. }
  91322. return y;
  91323. }
  91324. }
  91325. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  91326. #endif
  91327. /********* End of inlined file: float.c *********/
  91328. /********* Start of inlined file: format.c *********/
  91329. /********* Start of inlined file: juce_FlacHeader.h *********/
  91330. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91331. // tasks..
  91332. #define VERSION "1.2.1"
  91333. #define FLAC__NO_DLL 1
  91334. #ifdef _MSC_VER
  91335. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91336. #endif
  91337. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91338. #define FLAC__SYS_DARWIN 1
  91339. #endif
  91340. /********* End of inlined file: juce_FlacHeader.h *********/
  91341. #if JUCE_USE_FLAC
  91342. #if HAVE_CONFIG_H
  91343. # include <config.h>
  91344. #endif
  91345. #include <stdio.h>
  91346. #include <stdlib.h> /* for qsort() */
  91347. #include <string.h> /* for memset() */
  91348. #ifndef FLaC__INLINE
  91349. #define FLaC__INLINE
  91350. #endif
  91351. #ifdef min
  91352. #undef min
  91353. #endif
  91354. #define min(a,b) ((a)<(b)?(a):(b))
  91355. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  91356. #ifdef _MSC_VER
  91357. #define FLAC__U64L(x) x
  91358. #else
  91359. #define FLAC__U64L(x) x##LLU
  91360. #endif
  91361. /* VERSION should come from configure */
  91362. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  91363. ;
  91364. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  91365. /* yet one more hack because of MSVC6: */
  91366. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  91367. #else
  91368. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  91369. #endif
  91370. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  91371. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  91372. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  91373. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  91374. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  91375. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  91376. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  91377. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  91378. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  91379. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  91380. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  91381. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  91382. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  91383. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  91384. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  91385. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  91386. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  91387. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  91388. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  91389. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  91390. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  91391. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  91392. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  91393. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  91394. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  91395. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  91396. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  91397. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  91398. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  91399. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  91400. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  91401. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  91402. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  91403. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  91404. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  91405. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  91406. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  91407. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  91408. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  91409. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  91410. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  91411. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  91412. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  91413. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  91414. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  91415. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  91416. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  91417. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  91418. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  91419. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  91420. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  91421. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  91422. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  91423. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  91424. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  91425. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  91426. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  91427. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  91428. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  91429. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  91430. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  91431. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  91432. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  91433. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  91434. "PARTITIONED_RICE",
  91435. "PARTITIONED_RICE2"
  91436. };
  91437. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  91438. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  91439. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  91440. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  91441. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  91442. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  91443. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  91444. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  91445. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  91446. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  91447. "CONSTANT",
  91448. "VERBATIM",
  91449. "FIXED",
  91450. "LPC"
  91451. };
  91452. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  91453. "INDEPENDENT",
  91454. "LEFT_SIDE",
  91455. "RIGHT_SIDE",
  91456. "MID_SIDE"
  91457. };
  91458. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  91459. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  91460. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  91461. };
  91462. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  91463. "STREAMINFO",
  91464. "PADDING",
  91465. "APPLICATION",
  91466. "SEEKTABLE",
  91467. "VORBIS_COMMENT",
  91468. "CUESHEET",
  91469. "PICTURE"
  91470. };
  91471. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  91472. "Other",
  91473. "32x32 pixels 'file icon' (PNG only)",
  91474. "Other file icon",
  91475. "Cover (front)",
  91476. "Cover (back)",
  91477. "Leaflet page",
  91478. "Media (e.g. label side of CD)",
  91479. "Lead artist/lead performer/soloist",
  91480. "Artist/performer",
  91481. "Conductor",
  91482. "Band/Orchestra",
  91483. "Composer",
  91484. "Lyricist/text writer",
  91485. "Recording Location",
  91486. "During recording",
  91487. "During performance",
  91488. "Movie/video screen capture",
  91489. "A bright coloured fish",
  91490. "Illustration",
  91491. "Band/artist logotype",
  91492. "Publisher/Studio logotype"
  91493. };
  91494. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  91495. {
  91496. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  91497. return false;
  91498. }
  91499. else
  91500. return true;
  91501. }
  91502. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  91503. {
  91504. if(
  91505. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  91506. (
  91507. sample_rate >= (1u << 16) &&
  91508. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  91509. )
  91510. ) {
  91511. return false;
  91512. }
  91513. else
  91514. return true;
  91515. }
  91516. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  91517. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  91518. {
  91519. unsigned i;
  91520. FLAC__uint64 prev_sample_number = 0;
  91521. FLAC__bool got_prev = false;
  91522. FLAC__ASSERT(0 != seek_table);
  91523. for(i = 0; i < seek_table->num_points; i++) {
  91524. if(got_prev) {
  91525. if(
  91526. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  91527. seek_table->points[i].sample_number <= prev_sample_number
  91528. )
  91529. return false;
  91530. }
  91531. prev_sample_number = seek_table->points[i].sample_number;
  91532. got_prev = true;
  91533. }
  91534. return true;
  91535. }
  91536. /* used as the sort predicate for qsort() */
  91537. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  91538. {
  91539. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  91540. if(l->sample_number == r->sample_number)
  91541. return 0;
  91542. else if(l->sample_number < r->sample_number)
  91543. return -1;
  91544. else
  91545. return 1;
  91546. }
  91547. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  91548. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  91549. {
  91550. unsigned i, j;
  91551. FLAC__bool first;
  91552. FLAC__ASSERT(0 != seek_table);
  91553. /* sort the seekpoints */
  91554. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  91555. /* uniquify the seekpoints */
  91556. first = true;
  91557. for(i = j = 0; i < seek_table->num_points; i++) {
  91558. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  91559. if(!first) {
  91560. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  91561. continue;
  91562. }
  91563. }
  91564. first = false;
  91565. seek_table->points[j++] = seek_table->points[i];
  91566. }
  91567. for(i = j; i < seek_table->num_points; i++) {
  91568. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  91569. seek_table->points[i].stream_offset = 0;
  91570. seek_table->points[i].frame_samples = 0;
  91571. }
  91572. return j;
  91573. }
  91574. /*
  91575. * also disallows non-shortest-form encodings, c.f.
  91576. * http://www.unicode.org/versions/corrigendum1.html
  91577. * and a more clear explanation at the end of this section:
  91578. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  91579. */
  91580. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  91581. {
  91582. FLAC__ASSERT(0 != utf8);
  91583. if ((utf8[0] & 0x80) == 0) {
  91584. return 1;
  91585. }
  91586. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  91587. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  91588. return 0;
  91589. return 2;
  91590. }
  91591. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  91592. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  91593. return 0;
  91594. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  91595. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  91596. return 0;
  91597. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  91598. return 0;
  91599. return 3;
  91600. }
  91601. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  91602. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  91603. return 0;
  91604. return 4;
  91605. }
  91606. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  91607. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  91608. return 0;
  91609. return 5;
  91610. }
  91611. 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) {
  91612. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  91613. return 0;
  91614. return 6;
  91615. }
  91616. else {
  91617. return 0;
  91618. }
  91619. }
  91620. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  91621. {
  91622. char c;
  91623. for(c = *name; c; c = *(++name))
  91624. if(c < 0x20 || c == 0x3d || c > 0x7d)
  91625. return false;
  91626. return true;
  91627. }
  91628. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  91629. {
  91630. if(length == (unsigned)(-1)) {
  91631. while(*value) {
  91632. unsigned n = utf8len_(value);
  91633. if(n == 0)
  91634. return false;
  91635. value += n;
  91636. }
  91637. }
  91638. else {
  91639. const FLAC__byte *end = value + length;
  91640. while(value < end) {
  91641. unsigned n = utf8len_(value);
  91642. if(n == 0)
  91643. return false;
  91644. value += n;
  91645. }
  91646. if(value != end)
  91647. return false;
  91648. }
  91649. return true;
  91650. }
  91651. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  91652. {
  91653. const FLAC__byte *s, *end;
  91654. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  91655. if(*s < 0x20 || *s > 0x7D)
  91656. return false;
  91657. }
  91658. if(s == end)
  91659. return false;
  91660. s++; /* skip '=' */
  91661. while(s < end) {
  91662. unsigned n = utf8len_(s);
  91663. if(n == 0)
  91664. return false;
  91665. s += n;
  91666. }
  91667. if(s != end)
  91668. return false;
  91669. return true;
  91670. }
  91671. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  91672. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  91673. {
  91674. unsigned i, j;
  91675. if(check_cd_da_subset) {
  91676. if(cue_sheet->lead_in < 2 * 44100) {
  91677. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  91678. return false;
  91679. }
  91680. if(cue_sheet->lead_in % 588 != 0) {
  91681. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  91682. return false;
  91683. }
  91684. }
  91685. if(cue_sheet->num_tracks == 0) {
  91686. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  91687. return false;
  91688. }
  91689. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  91690. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  91691. return false;
  91692. }
  91693. for(i = 0; i < cue_sheet->num_tracks; i++) {
  91694. if(cue_sheet->tracks[i].number == 0) {
  91695. if(violation) *violation = "cue sheet may not have a track number 0";
  91696. return false;
  91697. }
  91698. if(check_cd_da_subset) {
  91699. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  91700. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  91701. return false;
  91702. }
  91703. }
  91704. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  91705. if(violation) {
  91706. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  91707. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  91708. else
  91709. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  91710. }
  91711. return false;
  91712. }
  91713. if(i < cue_sheet->num_tracks - 1) {
  91714. if(cue_sheet->tracks[i].num_indices == 0) {
  91715. if(violation) *violation = "cue sheet track must have at least one index point";
  91716. return false;
  91717. }
  91718. if(cue_sheet->tracks[i].indices[0].number > 1) {
  91719. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  91720. return false;
  91721. }
  91722. }
  91723. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  91724. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  91725. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  91726. return false;
  91727. }
  91728. if(j > 0) {
  91729. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  91730. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  91731. return false;
  91732. }
  91733. }
  91734. }
  91735. }
  91736. return true;
  91737. }
  91738. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  91739. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  91740. {
  91741. char *p;
  91742. FLAC__byte *b;
  91743. for(p = picture->mime_type; *p; p++) {
  91744. if(*p < 0x20 || *p > 0x7e) {
  91745. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  91746. return false;
  91747. }
  91748. }
  91749. for(b = picture->description; *b; ) {
  91750. unsigned n = utf8len_(b);
  91751. if(n == 0) {
  91752. if(violation) *violation = "description string must be valid UTF-8";
  91753. return false;
  91754. }
  91755. b += n;
  91756. }
  91757. return true;
  91758. }
  91759. /*
  91760. * These routines are private to libFLAC
  91761. */
  91762. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  91763. {
  91764. return
  91765. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  91766. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  91767. blocksize,
  91768. predictor_order
  91769. );
  91770. }
  91771. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  91772. {
  91773. unsigned max_rice_partition_order = 0;
  91774. while(!(blocksize & 1)) {
  91775. max_rice_partition_order++;
  91776. blocksize >>= 1;
  91777. }
  91778. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  91779. }
  91780. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  91781. {
  91782. unsigned max_rice_partition_order = limit;
  91783. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  91784. max_rice_partition_order--;
  91785. FLAC__ASSERT(
  91786. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  91787. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  91788. );
  91789. return max_rice_partition_order;
  91790. }
  91791. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  91792. {
  91793. FLAC__ASSERT(0 != object);
  91794. object->parameters = 0;
  91795. object->raw_bits = 0;
  91796. object->capacity_by_order = 0;
  91797. }
  91798. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  91799. {
  91800. FLAC__ASSERT(0 != object);
  91801. if(0 != object->parameters)
  91802. free(object->parameters);
  91803. if(0 != object->raw_bits)
  91804. free(object->raw_bits);
  91805. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  91806. }
  91807. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  91808. {
  91809. FLAC__ASSERT(0 != object);
  91810. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  91811. if(object->capacity_by_order < max_partition_order) {
  91812. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  91813. return false;
  91814. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  91815. return false;
  91816. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  91817. object->capacity_by_order = max_partition_order;
  91818. }
  91819. return true;
  91820. }
  91821. #endif
  91822. /********* End of inlined file: format.c *********/
  91823. /********* Start of inlined file: lpc_flac.c *********/
  91824. /********* Start of inlined file: juce_FlacHeader.h *********/
  91825. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91826. // tasks..
  91827. #define VERSION "1.2.1"
  91828. #define FLAC__NO_DLL 1
  91829. #ifdef _MSC_VER
  91830. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91831. #endif
  91832. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91833. #define FLAC__SYS_DARWIN 1
  91834. #endif
  91835. /********* End of inlined file: juce_FlacHeader.h *********/
  91836. #if JUCE_USE_FLAC
  91837. #if HAVE_CONFIG_H
  91838. # include <config.h>
  91839. #endif
  91840. #include <math.h>
  91841. /********* Start of inlined file: lpc.h *********/
  91842. #ifndef FLAC__PRIVATE__LPC_H
  91843. #define FLAC__PRIVATE__LPC_H
  91844. #ifdef HAVE_CONFIG_H
  91845. #include <config.h>
  91846. #endif
  91847. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91848. /*
  91849. * FLAC__lpc_window_data()
  91850. * --------------------------------------------------------------------
  91851. * Applies the given window to the data.
  91852. * OPT: asm implementation
  91853. *
  91854. * IN in[0,data_len-1]
  91855. * IN window[0,data_len-1]
  91856. * OUT out[0,lag-1]
  91857. * IN data_len
  91858. */
  91859. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  91860. /*
  91861. * FLAC__lpc_compute_autocorrelation()
  91862. * --------------------------------------------------------------------
  91863. * Compute the autocorrelation for lags between 0 and lag-1.
  91864. * Assumes data[] outside of [0,data_len-1] == 0.
  91865. * Asserts that lag > 0.
  91866. *
  91867. * IN data[0,data_len-1]
  91868. * IN data_len
  91869. * IN 0 < lag <= data_len
  91870. * OUT autoc[0,lag-1]
  91871. */
  91872. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91873. #ifndef FLAC__NO_ASM
  91874. # ifdef FLAC__CPU_IA32
  91875. # ifdef FLAC__HAS_NASM
  91876. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91877. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91878. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91879. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91880. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91881. # endif
  91882. # endif
  91883. #endif
  91884. /*
  91885. * FLAC__lpc_compute_lp_coefficients()
  91886. * --------------------------------------------------------------------
  91887. * Computes LP coefficients for orders 1..max_order.
  91888. * Do not call if autoc[0] == 0.0. This means the signal is zero
  91889. * and there is no point in calculating a predictor.
  91890. *
  91891. * IN autoc[0,max_order] autocorrelation values
  91892. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  91893. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  91894. * *** IMPORTANT:
  91895. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  91896. * OUT error[0,max_order-1] error for each order (more
  91897. * specifically, the variance of
  91898. * the error signal times # of
  91899. * samples in the signal)
  91900. *
  91901. * Example: if max_order is 9, the LP coefficients for order 9 will be
  91902. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  91903. * in lp_coeff[7][0,7], etc.
  91904. */
  91905. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  91906. /*
  91907. * FLAC__lpc_quantize_coefficients()
  91908. * --------------------------------------------------------------------
  91909. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  91910. * must be less than 32 (sizeof(FLAC__int32)*8).
  91911. *
  91912. * IN lp_coeff[0,order-1] LP coefficients
  91913. * IN order LP order
  91914. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  91915. * desired precision (in bits, including sign
  91916. * bit) of largest coefficient
  91917. * OUT qlp_coeff[0,order-1] quantized coefficients
  91918. * OUT shift # of bits to shift right to get approximated
  91919. * LP coefficients. NOTE: could be negative.
  91920. * RETURN 0 => quantization OK
  91921. * 1 => coefficients require too much shifting for *shift to
  91922. * fit in the LPC subframe header. 'shift' is unset.
  91923. * 2 => coefficients are all zero, which is bad. 'shift' is
  91924. * unset.
  91925. */
  91926. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  91927. /*
  91928. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  91929. * --------------------------------------------------------------------
  91930. * Compute the residual signal obtained from sutracting the predicted
  91931. * signal from the original.
  91932. *
  91933. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  91934. * IN data_len length of original signal
  91935. * IN qlp_coeff[0,order-1] quantized LP coefficients
  91936. * IN order > 0 LP order
  91937. * IN lp_quantization quantization of LP coefficients in bits
  91938. * OUT residual[0,data_len-1] residual signal
  91939. */
  91940. 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[]);
  91941. 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[]);
  91942. #ifndef FLAC__NO_ASM
  91943. # ifdef FLAC__CPU_IA32
  91944. # ifdef FLAC__HAS_NASM
  91945. 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[]);
  91946. 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[]);
  91947. # endif
  91948. # endif
  91949. #endif
  91950. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  91951. /*
  91952. * FLAC__lpc_restore_signal()
  91953. * --------------------------------------------------------------------
  91954. * Restore the original signal by summing the residual and the
  91955. * predictor.
  91956. *
  91957. * IN residual[0,data_len-1] residual signal
  91958. * IN data_len length of original signal
  91959. * IN qlp_coeff[0,order-1] quantized LP coefficients
  91960. * IN order > 0 LP order
  91961. * IN lp_quantization quantization of LP coefficients in bits
  91962. * *** IMPORTANT: the caller must pass in the historical samples:
  91963. * IN data[-order,-1] previously-reconstructed historical samples
  91964. * OUT data[0,data_len-1] original signal
  91965. */
  91966. 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[]);
  91967. 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[]);
  91968. #ifndef FLAC__NO_ASM
  91969. # ifdef FLAC__CPU_IA32
  91970. # ifdef FLAC__HAS_NASM
  91971. 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[]);
  91972. 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[]);
  91973. # endif /* FLAC__HAS_NASM */
  91974. # elif defined FLAC__CPU_PPC
  91975. 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[]);
  91976. 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[]);
  91977. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  91978. #endif /* FLAC__NO_ASM */
  91979. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91980. /*
  91981. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  91982. * --------------------------------------------------------------------
  91983. * Compute the expected number of bits per residual signal sample
  91984. * based on the LP error (which is related to the residual variance).
  91985. *
  91986. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  91987. * IN total_samples > 0 # of samples in residual signal
  91988. * RETURN expected bits per sample
  91989. */
  91990. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  91991. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  91992. /*
  91993. * FLAC__lpc_compute_best_order()
  91994. * --------------------------------------------------------------------
  91995. * Compute the best order from the array of signal errors returned
  91996. * during coefficient computation.
  91997. *
  91998. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  91999. * IN max_order > 0 max LP order
  92000. * IN total_samples > 0 # of samples in residual signal
  92001. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  92002. * (includes warmup sample size and quantized LP coefficient)
  92003. * RETURN [1,max_order] best order
  92004. */
  92005. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  92006. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92007. #endif
  92008. /********* End of inlined file: lpc.h *********/
  92009. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  92010. #include <stdio.h>
  92011. #endif
  92012. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92013. #ifndef M_LN2
  92014. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  92015. #define M_LN2 0.69314718055994530942
  92016. #endif
  92017. /* OPT: #undef'ing this may improve the speed on some architectures */
  92018. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  92019. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  92020. {
  92021. unsigned i;
  92022. for(i = 0; i < data_len; i++)
  92023. out[i] = in[i] * window[i];
  92024. }
  92025. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  92026. {
  92027. /* a readable, but slower, version */
  92028. #if 0
  92029. FLAC__real d;
  92030. unsigned i;
  92031. FLAC__ASSERT(lag > 0);
  92032. FLAC__ASSERT(lag <= data_len);
  92033. /*
  92034. * Technically we should subtract the mean first like so:
  92035. * for(i = 0; i < data_len; i++)
  92036. * data[i] -= mean;
  92037. * but it appears not to make enough of a difference to matter, and
  92038. * most signals are already closely centered around zero
  92039. */
  92040. while(lag--) {
  92041. for(i = lag, d = 0.0; i < data_len; i++)
  92042. d += data[i] * data[i - lag];
  92043. autoc[lag] = d;
  92044. }
  92045. #endif
  92046. /*
  92047. * this version tends to run faster because of better data locality
  92048. * ('data_len' is usually much larger than 'lag')
  92049. */
  92050. FLAC__real d;
  92051. unsigned sample, coeff;
  92052. const unsigned limit = data_len - lag;
  92053. FLAC__ASSERT(lag > 0);
  92054. FLAC__ASSERT(lag <= data_len);
  92055. for(coeff = 0; coeff < lag; coeff++)
  92056. autoc[coeff] = 0.0;
  92057. for(sample = 0; sample <= limit; sample++) {
  92058. d = data[sample];
  92059. for(coeff = 0; coeff < lag; coeff++)
  92060. autoc[coeff] += d * data[sample+coeff];
  92061. }
  92062. for(; sample < data_len; sample++) {
  92063. d = data[sample];
  92064. for(coeff = 0; coeff < data_len - sample; coeff++)
  92065. autoc[coeff] += d * data[sample+coeff];
  92066. }
  92067. }
  92068. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  92069. {
  92070. unsigned i, j;
  92071. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  92072. FLAC__ASSERT(0 != max_order);
  92073. FLAC__ASSERT(0 < *max_order);
  92074. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  92075. FLAC__ASSERT(autoc[0] != 0.0);
  92076. err = autoc[0];
  92077. for(i = 0; i < *max_order; i++) {
  92078. /* Sum up this iteration's reflection coefficient. */
  92079. r = -autoc[i+1];
  92080. for(j = 0; j < i; j++)
  92081. r -= lpc[j] * autoc[i-j];
  92082. ref[i] = (r/=err);
  92083. /* Update LPC coefficients and total error. */
  92084. lpc[i]=r;
  92085. for(j = 0; j < (i>>1); j++) {
  92086. FLAC__double tmp = lpc[j];
  92087. lpc[j] += r * lpc[i-1-j];
  92088. lpc[i-1-j] += r * tmp;
  92089. }
  92090. if(i & 1)
  92091. lpc[j] += lpc[j] * r;
  92092. err *= (1.0 - r * r);
  92093. /* save this order */
  92094. for(j = 0; j <= i; j++)
  92095. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  92096. error[i] = err;
  92097. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  92098. if(err == 0.0) {
  92099. *max_order = i+1;
  92100. return;
  92101. }
  92102. }
  92103. }
  92104. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  92105. {
  92106. unsigned i;
  92107. FLAC__double cmax;
  92108. FLAC__int32 qmax, qmin;
  92109. FLAC__ASSERT(precision > 0);
  92110. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  92111. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  92112. precision--;
  92113. qmax = 1 << precision;
  92114. qmin = -qmax;
  92115. qmax--;
  92116. /* calc cmax = max( |lp_coeff[i]| ) */
  92117. cmax = 0.0;
  92118. for(i = 0; i < order; i++) {
  92119. const FLAC__double d = fabs(lp_coeff[i]);
  92120. if(d > cmax)
  92121. cmax = d;
  92122. }
  92123. if(cmax <= 0.0) {
  92124. /* => coefficients are all 0, which means our constant-detect didn't work */
  92125. return 2;
  92126. }
  92127. else {
  92128. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  92129. const int min_shiftlimit = -max_shiftlimit - 1;
  92130. int log2cmax;
  92131. (void)frexp(cmax, &log2cmax);
  92132. log2cmax--;
  92133. *shift = (int)precision - log2cmax - 1;
  92134. if(*shift > max_shiftlimit)
  92135. *shift = max_shiftlimit;
  92136. else if(*shift < min_shiftlimit)
  92137. return 1;
  92138. }
  92139. if(*shift >= 0) {
  92140. FLAC__double error = 0.0;
  92141. FLAC__int32 q;
  92142. for(i = 0; i < order; i++) {
  92143. error += lp_coeff[i] * (1 << *shift);
  92144. #if 1 /* unfortunately lround() is C99 */
  92145. if(error >= 0.0)
  92146. q = (FLAC__int32)(error + 0.5);
  92147. else
  92148. q = (FLAC__int32)(error - 0.5);
  92149. #else
  92150. q = lround(error);
  92151. #endif
  92152. #ifdef FLAC__OVERFLOW_DETECT
  92153. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  92154. 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]);
  92155. else if(q < qmin)
  92156. 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]);
  92157. #endif
  92158. if(q > qmax)
  92159. q = qmax;
  92160. else if(q < qmin)
  92161. q = qmin;
  92162. error -= q;
  92163. qlp_coeff[i] = q;
  92164. }
  92165. }
  92166. /* negative shift is very rare but due to design flaw, negative shift is
  92167. * a NOP in the decoder, so it must be handled specially by scaling down
  92168. * coeffs
  92169. */
  92170. else {
  92171. const int nshift = -(*shift);
  92172. FLAC__double error = 0.0;
  92173. FLAC__int32 q;
  92174. #ifdef DEBUG
  92175. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  92176. #endif
  92177. for(i = 0; i < order; i++) {
  92178. error += lp_coeff[i] / (1 << nshift);
  92179. #if 1 /* unfortunately lround() is C99 */
  92180. if(error >= 0.0)
  92181. q = (FLAC__int32)(error + 0.5);
  92182. else
  92183. q = (FLAC__int32)(error - 0.5);
  92184. #else
  92185. q = lround(error);
  92186. #endif
  92187. #ifdef FLAC__OVERFLOW_DETECT
  92188. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  92189. 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]);
  92190. else if(q < qmin)
  92191. 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]);
  92192. #endif
  92193. if(q > qmax)
  92194. q = qmax;
  92195. else if(q < qmin)
  92196. q = qmin;
  92197. error -= q;
  92198. qlp_coeff[i] = q;
  92199. }
  92200. *shift = 0;
  92201. }
  92202. return 0;
  92203. }
  92204. 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[])
  92205. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  92206. {
  92207. FLAC__int64 sumo;
  92208. unsigned i, j;
  92209. FLAC__int32 sum;
  92210. const FLAC__int32 *history;
  92211. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  92212. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  92213. for(i=0;i<order;i++)
  92214. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  92215. fprintf(stderr,"\n");
  92216. #endif
  92217. FLAC__ASSERT(order > 0);
  92218. for(i = 0; i < data_len; i++) {
  92219. sumo = 0;
  92220. sum = 0;
  92221. history = data;
  92222. for(j = 0; j < order; j++) {
  92223. sum += qlp_coeff[j] * (*(--history));
  92224. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  92225. #if defined _MSC_VER
  92226. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  92227. 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);
  92228. #else
  92229. if(sumo > 2147483647ll || sumo < -2147483648ll)
  92230. 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);
  92231. #endif
  92232. }
  92233. *(residual++) = *(data++) - (sum >> lp_quantization);
  92234. }
  92235. /* Here's a slower but clearer version:
  92236. for(i = 0; i < data_len; i++) {
  92237. sum = 0;
  92238. for(j = 0; j < order; j++)
  92239. sum += qlp_coeff[j] * data[i-j-1];
  92240. residual[i] = data[i] - (sum >> lp_quantization);
  92241. }
  92242. */
  92243. }
  92244. #else /* fully unrolled version for normal use */
  92245. {
  92246. int i;
  92247. FLAC__int32 sum;
  92248. FLAC__ASSERT(order > 0);
  92249. FLAC__ASSERT(order <= 32);
  92250. /*
  92251. * We do unique versions up to 12th order since that's the subset limit.
  92252. * Also they are roughly ordered to match frequency of occurrence to
  92253. * minimize branching.
  92254. */
  92255. if(order <= 12) {
  92256. if(order > 8) {
  92257. if(order > 10) {
  92258. if(order == 12) {
  92259. for(i = 0; i < (int)data_len; i++) {
  92260. sum = 0;
  92261. sum += qlp_coeff[11] * data[i-12];
  92262. sum += qlp_coeff[10] * data[i-11];
  92263. sum += qlp_coeff[9] * data[i-10];
  92264. sum += qlp_coeff[8] * data[i-9];
  92265. sum += qlp_coeff[7] * data[i-8];
  92266. sum += qlp_coeff[6] * data[i-7];
  92267. sum += qlp_coeff[5] * data[i-6];
  92268. sum += qlp_coeff[4] * data[i-5];
  92269. sum += qlp_coeff[3] * data[i-4];
  92270. sum += qlp_coeff[2] * data[i-3];
  92271. sum += qlp_coeff[1] * data[i-2];
  92272. sum += qlp_coeff[0] * data[i-1];
  92273. residual[i] = data[i] - (sum >> lp_quantization);
  92274. }
  92275. }
  92276. else { /* order == 11 */
  92277. for(i = 0; i < (int)data_len; i++) {
  92278. sum = 0;
  92279. sum += qlp_coeff[10] * data[i-11];
  92280. sum += qlp_coeff[9] * data[i-10];
  92281. sum += qlp_coeff[8] * data[i-9];
  92282. sum += qlp_coeff[7] * data[i-8];
  92283. sum += qlp_coeff[6] * data[i-7];
  92284. sum += qlp_coeff[5] * data[i-6];
  92285. sum += qlp_coeff[4] * data[i-5];
  92286. sum += qlp_coeff[3] * data[i-4];
  92287. sum += qlp_coeff[2] * data[i-3];
  92288. sum += qlp_coeff[1] * data[i-2];
  92289. sum += qlp_coeff[0] * data[i-1];
  92290. residual[i] = data[i] - (sum >> lp_quantization);
  92291. }
  92292. }
  92293. }
  92294. else {
  92295. if(order == 10) {
  92296. for(i = 0; i < (int)data_len; i++) {
  92297. sum = 0;
  92298. sum += qlp_coeff[9] * data[i-10];
  92299. sum += qlp_coeff[8] * data[i-9];
  92300. sum += qlp_coeff[7] * data[i-8];
  92301. sum += qlp_coeff[6] * data[i-7];
  92302. sum += qlp_coeff[5] * data[i-6];
  92303. sum += qlp_coeff[4] * data[i-5];
  92304. sum += qlp_coeff[3] * data[i-4];
  92305. sum += qlp_coeff[2] * data[i-3];
  92306. sum += qlp_coeff[1] * data[i-2];
  92307. sum += qlp_coeff[0] * data[i-1];
  92308. residual[i] = data[i] - (sum >> lp_quantization);
  92309. }
  92310. }
  92311. else { /* order == 9 */
  92312. for(i = 0; i < (int)data_len; i++) {
  92313. sum = 0;
  92314. sum += qlp_coeff[8] * data[i-9];
  92315. sum += qlp_coeff[7] * data[i-8];
  92316. sum += qlp_coeff[6] * data[i-7];
  92317. sum += qlp_coeff[5] * data[i-6];
  92318. sum += qlp_coeff[4] * data[i-5];
  92319. sum += qlp_coeff[3] * data[i-4];
  92320. sum += qlp_coeff[2] * data[i-3];
  92321. sum += qlp_coeff[1] * data[i-2];
  92322. sum += qlp_coeff[0] * data[i-1];
  92323. residual[i] = data[i] - (sum >> lp_quantization);
  92324. }
  92325. }
  92326. }
  92327. }
  92328. else if(order > 4) {
  92329. if(order > 6) {
  92330. if(order == 8) {
  92331. for(i = 0; i < (int)data_len; i++) {
  92332. sum = 0;
  92333. sum += qlp_coeff[7] * data[i-8];
  92334. sum += qlp_coeff[6] * data[i-7];
  92335. sum += qlp_coeff[5] * data[i-6];
  92336. sum += qlp_coeff[4] * data[i-5];
  92337. sum += qlp_coeff[3] * data[i-4];
  92338. sum += qlp_coeff[2] * data[i-3];
  92339. sum += qlp_coeff[1] * data[i-2];
  92340. sum += qlp_coeff[0] * data[i-1];
  92341. residual[i] = data[i] - (sum >> lp_quantization);
  92342. }
  92343. }
  92344. else { /* order == 7 */
  92345. for(i = 0; i < (int)data_len; i++) {
  92346. sum = 0;
  92347. sum += qlp_coeff[6] * data[i-7];
  92348. sum += qlp_coeff[5] * data[i-6];
  92349. sum += qlp_coeff[4] * data[i-5];
  92350. sum += qlp_coeff[3] * data[i-4];
  92351. sum += qlp_coeff[2] * data[i-3];
  92352. sum += qlp_coeff[1] * data[i-2];
  92353. sum += qlp_coeff[0] * data[i-1];
  92354. residual[i] = data[i] - (sum >> lp_quantization);
  92355. }
  92356. }
  92357. }
  92358. else {
  92359. if(order == 6) {
  92360. for(i = 0; i < (int)data_len; i++) {
  92361. sum = 0;
  92362. sum += qlp_coeff[5] * data[i-6];
  92363. sum += qlp_coeff[4] * data[i-5];
  92364. sum += qlp_coeff[3] * data[i-4];
  92365. sum += qlp_coeff[2] * data[i-3];
  92366. sum += qlp_coeff[1] * data[i-2];
  92367. sum += qlp_coeff[0] * data[i-1];
  92368. residual[i] = data[i] - (sum >> lp_quantization);
  92369. }
  92370. }
  92371. else { /* order == 5 */
  92372. for(i = 0; i < (int)data_len; i++) {
  92373. sum = 0;
  92374. sum += qlp_coeff[4] * data[i-5];
  92375. sum += qlp_coeff[3] * data[i-4];
  92376. sum += qlp_coeff[2] * data[i-3];
  92377. sum += qlp_coeff[1] * data[i-2];
  92378. sum += qlp_coeff[0] * data[i-1];
  92379. residual[i] = data[i] - (sum >> lp_quantization);
  92380. }
  92381. }
  92382. }
  92383. }
  92384. else {
  92385. if(order > 2) {
  92386. if(order == 4) {
  92387. for(i = 0; i < (int)data_len; i++) {
  92388. sum = 0;
  92389. sum += qlp_coeff[3] * data[i-4];
  92390. sum += qlp_coeff[2] * data[i-3];
  92391. sum += qlp_coeff[1] * data[i-2];
  92392. sum += qlp_coeff[0] * data[i-1];
  92393. residual[i] = data[i] - (sum >> lp_quantization);
  92394. }
  92395. }
  92396. else { /* order == 3 */
  92397. for(i = 0; i < (int)data_len; i++) {
  92398. sum = 0;
  92399. sum += qlp_coeff[2] * data[i-3];
  92400. sum += qlp_coeff[1] * data[i-2];
  92401. sum += qlp_coeff[0] * data[i-1];
  92402. residual[i] = data[i] - (sum >> lp_quantization);
  92403. }
  92404. }
  92405. }
  92406. else {
  92407. if(order == 2) {
  92408. for(i = 0; i < (int)data_len; i++) {
  92409. sum = 0;
  92410. sum += qlp_coeff[1] * data[i-2];
  92411. sum += qlp_coeff[0] * data[i-1];
  92412. residual[i] = data[i] - (sum >> lp_quantization);
  92413. }
  92414. }
  92415. else { /* order == 1 */
  92416. for(i = 0; i < (int)data_len; i++)
  92417. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  92418. }
  92419. }
  92420. }
  92421. }
  92422. else { /* order > 12 */
  92423. for(i = 0; i < (int)data_len; i++) {
  92424. sum = 0;
  92425. switch(order) {
  92426. case 32: sum += qlp_coeff[31] * data[i-32];
  92427. case 31: sum += qlp_coeff[30] * data[i-31];
  92428. case 30: sum += qlp_coeff[29] * data[i-30];
  92429. case 29: sum += qlp_coeff[28] * data[i-29];
  92430. case 28: sum += qlp_coeff[27] * data[i-28];
  92431. case 27: sum += qlp_coeff[26] * data[i-27];
  92432. case 26: sum += qlp_coeff[25] * data[i-26];
  92433. case 25: sum += qlp_coeff[24] * data[i-25];
  92434. case 24: sum += qlp_coeff[23] * data[i-24];
  92435. case 23: sum += qlp_coeff[22] * data[i-23];
  92436. case 22: sum += qlp_coeff[21] * data[i-22];
  92437. case 21: sum += qlp_coeff[20] * data[i-21];
  92438. case 20: sum += qlp_coeff[19] * data[i-20];
  92439. case 19: sum += qlp_coeff[18] * data[i-19];
  92440. case 18: sum += qlp_coeff[17] * data[i-18];
  92441. case 17: sum += qlp_coeff[16] * data[i-17];
  92442. case 16: sum += qlp_coeff[15] * data[i-16];
  92443. case 15: sum += qlp_coeff[14] * data[i-15];
  92444. case 14: sum += qlp_coeff[13] * data[i-14];
  92445. case 13: sum += qlp_coeff[12] * data[i-13];
  92446. sum += qlp_coeff[11] * data[i-12];
  92447. sum += qlp_coeff[10] * data[i-11];
  92448. sum += qlp_coeff[ 9] * data[i-10];
  92449. sum += qlp_coeff[ 8] * data[i- 9];
  92450. sum += qlp_coeff[ 7] * data[i- 8];
  92451. sum += qlp_coeff[ 6] * data[i- 7];
  92452. sum += qlp_coeff[ 5] * data[i- 6];
  92453. sum += qlp_coeff[ 4] * data[i- 5];
  92454. sum += qlp_coeff[ 3] * data[i- 4];
  92455. sum += qlp_coeff[ 2] * data[i- 3];
  92456. sum += qlp_coeff[ 1] * data[i- 2];
  92457. sum += qlp_coeff[ 0] * data[i- 1];
  92458. }
  92459. residual[i] = data[i] - (sum >> lp_quantization);
  92460. }
  92461. }
  92462. }
  92463. #endif
  92464. 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[])
  92465. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  92466. {
  92467. unsigned i, j;
  92468. FLAC__int64 sum;
  92469. const FLAC__int32 *history;
  92470. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  92471. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  92472. for(i=0;i<order;i++)
  92473. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  92474. fprintf(stderr,"\n");
  92475. #endif
  92476. FLAC__ASSERT(order > 0);
  92477. for(i = 0; i < data_len; i++) {
  92478. sum = 0;
  92479. history = data;
  92480. for(j = 0; j < order; j++)
  92481. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  92482. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  92483. #if defined _MSC_VER
  92484. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  92485. #else
  92486. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  92487. #endif
  92488. break;
  92489. }
  92490. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  92491. #if defined _MSC_VER
  92492. 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));
  92493. #else
  92494. 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)));
  92495. #endif
  92496. break;
  92497. }
  92498. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  92499. }
  92500. }
  92501. #else /* fully unrolled version for normal use */
  92502. {
  92503. int i;
  92504. FLAC__int64 sum;
  92505. FLAC__ASSERT(order > 0);
  92506. FLAC__ASSERT(order <= 32);
  92507. /*
  92508. * We do unique versions up to 12th order since that's the subset limit.
  92509. * Also they are roughly ordered to match frequency of occurrence to
  92510. * minimize branching.
  92511. */
  92512. if(order <= 12) {
  92513. if(order > 8) {
  92514. if(order > 10) {
  92515. if(order == 12) {
  92516. for(i = 0; i < (int)data_len; i++) {
  92517. sum = 0;
  92518. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  92519. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92520. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92521. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92522. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92523. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92524. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92525. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92526. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92527. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92528. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92529. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92530. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92531. }
  92532. }
  92533. else { /* order == 11 */
  92534. for(i = 0; i < (int)data_len; i++) {
  92535. sum = 0;
  92536. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92537. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92538. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92539. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92540. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92541. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92542. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92543. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92544. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92545. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92546. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92547. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92548. }
  92549. }
  92550. }
  92551. else {
  92552. if(order == 10) {
  92553. for(i = 0; i < (int)data_len; i++) {
  92554. sum = 0;
  92555. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92556. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92557. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92558. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92559. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92560. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92561. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92562. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92563. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92564. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92565. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92566. }
  92567. }
  92568. else { /* order == 9 */
  92569. for(i = 0; i < (int)data_len; i++) {
  92570. sum = 0;
  92571. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92572. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92573. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92574. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92575. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92576. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92577. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92578. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92579. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92580. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92581. }
  92582. }
  92583. }
  92584. }
  92585. else if(order > 4) {
  92586. if(order > 6) {
  92587. if(order == 8) {
  92588. for(i = 0; i < (int)data_len; i++) {
  92589. sum = 0;
  92590. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92591. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92592. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92593. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92594. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92595. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92596. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92597. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92598. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92599. }
  92600. }
  92601. else { /* order == 7 */
  92602. for(i = 0; i < (int)data_len; i++) {
  92603. sum = 0;
  92604. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92605. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92606. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92607. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92608. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92609. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92610. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92611. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92612. }
  92613. }
  92614. }
  92615. else {
  92616. if(order == 6) {
  92617. for(i = 0; i < (int)data_len; i++) {
  92618. sum = 0;
  92619. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92620. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92621. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92622. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92623. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92624. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92625. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92626. }
  92627. }
  92628. else { /* order == 5 */
  92629. for(i = 0; i < (int)data_len; i++) {
  92630. sum = 0;
  92631. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92632. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92633. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92634. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92635. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92636. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92637. }
  92638. }
  92639. }
  92640. }
  92641. else {
  92642. if(order > 2) {
  92643. if(order == 4) {
  92644. for(i = 0; i < (int)data_len; i++) {
  92645. sum = 0;
  92646. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92647. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92648. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92649. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92650. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92651. }
  92652. }
  92653. else { /* order == 3 */
  92654. for(i = 0; i < (int)data_len; i++) {
  92655. sum = 0;
  92656. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92657. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92658. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92659. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92660. }
  92661. }
  92662. }
  92663. else {
  92664. if(order == 2) {
  92665. for(i = 0; i < (int)data_len; i++) {
  92666. sum = 0;
  92667. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92668. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92669. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92670. }
  92671. }
  92672. else { /* order == 1 */
  92673. for(i = 0; i < (int)data_len; i++)
  92674. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  92675. }
  92676. }
  92677. }
  92678. }
  92679. else { /* order > 12 */
  92680. for(i = 0; i < (int)data_len; i++) {
  92681. sum = 0;
  92682. switch(order) {
  92683. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  92684. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  92685. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  92686. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  92687. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  92688. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  92689. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  92690. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  92691. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  92692. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  92693. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  92694. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  92695. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  92696. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  92697. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  92698. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  92699. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  92700. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  92701. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  92702. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  92703. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  92704. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92705. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  92706. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  92707. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  92708. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  92709. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  92710. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  92711. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  92712. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  92713. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  92714. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  92715. }
  92716. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  92717. }
  92718. }
  92719. }
  92720. #endif
  92721. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92722. 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[])
  92723. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  92724. {
  92725. FLAC__int64 sumo;
  92726. unsigned i, j;
  92727. FLAC__int32 sum;
  92728. const FLAC__int32 *r = residual, *history;
  92729. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  92730. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  92731. for(i=0;i<order;i++)
  92732. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  92733. fprintf(stderr,"\n");
  92734. #endif
  92735. FLAC__ASSERT(order > 0);
  92736. for(i = 0; i < data_len; i++) {
  92737. sumo = 0;
  92738. sum = 0;
  92739. history = data;
  92740. for(j = 0; j < order; j++) {
  92741. sum += qlp_coeff[j] * (*(--history));
  92742. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  92743. #if defined _MSC_VER
  92744. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  92745. 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);
  92746. #else
  92747. if(sumo > 2147483647ll || sumo < -2147483648ll)
  92748. 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);
  92749. #endif
  92750. }
  92751. *(data++) = *(r++) + (sum >> lp_quantization);
  92752. }
  92753. /* Here's a slower but clearer version:
  92754. for(i = 0; i < data_len; i++) {
  92755. sum = 0;
  92756. for(j = 0; j < order; j++)
  92757. sum += qlp_coeff[j] * data[i-j-1];
  92758. data[i] = residual[i] + (sum >> lp_quantization);
  92759. }
  92760. */
  92761. }
  92762. #else /* fully unrolled version for normal use */
  92763. {
  92764. int i;
  92765. FLAC__int32 sum;
  92766. FLAC__ASSERT(order > 0);
  92767. FLAC__ASSERT(order <= 32);
  92768. /*
  92769. * We do unique versions up to 12th order since that's the subset limit.
  92770. * Also they are roughly ordered to match frequency of occurrence to
  92771. * minimize branching.
  92772. */
  92773. if(order <= 12) {
  92774. if(order > 8) {
  92775. if(order > 10) {
  92776. if(order == 12) {
  92777. for(i = 0; i < (int)data_len; i++) {
  92778. sum = 0;
  92779. sum += qlp_coeff[11] * data[i-12];
  92780. sum += qlp_coeff[10] * data[i-11];
  92781. sum += qlp_coeff[9] * data[i-10];
  92782. sum += qlp_coeff[8] * data[i-9];
  92783. sum += qlp_coeff[7] * data[i-8];
  92784. sum += qlp_coeff[6] * data[i-7];
  92785. sum += qlp_coeff[5] * data[i-6];
  92786. sum += qlp_coeff[4] * data[i-5];
  92787. sum += qlp_coeff[3] * data[i-4];
  92788. sum += qlp_coeff[2] * data[i-3];
  92789. sum += qlp_coeff[1] * data[i-2];
  92790. sum += qlp_coeff[0] * data[i-1];
  92791. data[i] = residual[i] + (sum >> lp_quantization);
  92792. }
  92793. }
  92794. else { /* order == 11 */
  92795. for(i = 0; i < (int)data_len; i++) {
  92796. sum = 0;
  92797. sum += qlp_coeff[10] * data[i-11];
  92798. sum += qlp_coeff[9] * data[i-10];
  92799. sum += qlp_coeff[8] * data[i-9];
  92800. sum += qlp_coeff[7] * data[i-8];
  92801. sum += qlp_coeff[6] * data[i-7];
  92802. sum += qlp_coeff[5] * data[i-6];
  92803. sum += qlp_coeff[4] * data[i-5];
  92804. sum += qlp_coeff[3] * data[i-4];
  92805. sum += qlp_coeff[2] * data[i-3];
  92806. sum += qlp_coeff[1] * data[i-2];
  92807. sum += qlp_coeff[0] * data[i-1];
  92808. data[i] = residual[i] + (sum >> lp_quantization);
  92809. }
  92810. }
  92811. }
  92812. else {
  92813. if(order == 10) {
  92814. for(i = 0; i < (int)data_len; i++) {
  92815. sum = 0;
  92816. sum += qlp_coeff[9] * data[i-10];
  92817. sum += qlp_coeff[8] * data[i-9];
  92818. sum += qlp_coeff[7] * data[i-8];
  92819. sum += qlp_coeff[6] * data[i-7];
  92820. sum += qlp_coeff[5] * data[i-6];
  92821. sum += qlp_coeff[4] * data[i-5];
  92822. sum += qlp_coeff[3] * data[i-4];
  92823. sum += qlp_coeff[2] * data[i-3];
  92824. sum += qlp_coeff[1] * data[i-2];
  92825. sum += qlp_coeff[0] * data[i-1];
  92826. data[i] = residual[i] + (sum >> lp_quantization);
  92827. }
  92828. }
  92829. else { /* order == 9 */
  92830. for(i = 0; i < (int)data_len; i++) {
  92831. sum = 0;
  92832. sum += qlp_coeff[8] * data[i-9];
  92833. sum += qlp_coeff[7] * data[i-8];
  92834. sum += qlp_coeff[6] * data[i-7];
  92835. sum += qlp_coeff[5] * data[i-6];
  92836. sum += qlp_coeff[4] * data[i-5];
  92837. sum += qlp_coeff[3] * data[i-4];
  92838. sum += qlp_coeff[2] * data[i-3];
  92839. sum += qlp_coeff[1] * data[i-2];
  92840. sum += qlp_coeff[0] * data[i-1];
  92841. data[i] = residual[i] + (sum >> lp_quantization);
  92842. }
  92843. }
  92844. }
  92845. }
  92846. else if(order > 4) {
  92847. if(order > 6) {
  92848. if(order == 8) {
  92849. for(i = 0; i < (int)data_len; i++) {
  92850. sum = 0;
  92851. sum += qlp_coeff[7] * data[i-8];
  92852. sum += qlp_coeff[6] * data[i-7];
  92853. sum += qlp_coeff[5] * data[i-6];
  92854. sum += qlp_coeff[4] * data[i-5];
  92855. sum += qlp_coeff[3] * data[i-4];
  92856. sum += qlp_coeff[2] * data[i-3];
  92857. sum += qlp_coeff[1] * data[i-2];
  92858. sum += qlp_coeff[0] * data[i-1];
  92859. data[i] = residual[i] + (sum >> lp_quantization);
  92860. }
  92861. }
  92862. else { /* order == 7 */
  92863. for(i = 0; i < (int)data_len; i++) {
  92864. sum = 0;
  92865. sum += qlp_coeff[6] * data[i-7];
  92866. sum += qlp_coeff[5] * data[i-6];
  92867. sum += qlp_coeff[4] * data[i-5];
  92868. sum += qlp_coeff[3] * data[i-4];
  92869. sum += qlp_coeff[2] * data[i-3];
  92870. sum += qlp_coeff[1] * data[i-2];
  92871. sum += qlp_coeff[0] * data[i-1];
  92872. data[i] = residual[i] + (sum >> lp_quantization);
  92873. }
  92874. }
  92875. }
  92876. else {
  92877. if(order == 6) {
  92878. for(i = 0; i < (int)data_len; i++) {
  92879. sum = 0;
  92880. sum += qlp_coeff[5] * data[i-6];
  92881. sum += qlp_coeff[4] * data[i-5];
  92882. sum += qlp_coeff[3] * data[i-4];
  92883. sum += qlp_coeff[2] * data[i-3];
  92884. sum += qlp_coeff[1] * data[i-2];
  92885. sum += qlp_coeff[0] * data[i-1];
  92886. data[i] = residual[i] + (sum >> lp_quantization);
  92887. }
  92888. }
  92889. else { /* order == 5 */
  92890. for(i = 0; i < (int)data_len; i++) {
  92891. sum = 0;
  92892. sum += qlp_coeff[4] * data[i-5];
  92893. sum += qlp_coeff[3] * data[i-4];
  92894. sum += qlp_coeff[2] * data[i-3];
  92895. sum += qlp_coeff[1] * data[i-2];
  92896. sum += qlp_coeff[0] * data[i-1];
  92897. data[i] = residual[i] + (sum >> lp_quantization);
  92898. }
  92899. }
  92900. }
  92901. }
  92902. else {
  92903. if(order > 2) {
  92904. if(order == 4) {
  92905. for(i = 0; i < (int)data_len; i++) {
  92906. sum = 0;
  92907. sum += qlp_coeff[3] * data[i-4];
  92908. sum += qlp_coeff[2] * data[i-3];
  92909. sum += qlp_coeff[1] * data[i-2];
  92910. sum += qlp_coeff[0] * data[i-1];
  92911. data[i] = residual[i] + (sum >> lp_quantization);
  92912. }
  92913. }
  92914. else { /* order == 3 */
  92915. for(i = 0; i < (int)data_len; i++) {
  92916. sum = 0;
  92917. sum += qlp_coeff[2] * data[i-3];
  92918. sum += qlp_coeff[1] * data[i-2];
  92919. sum += qlp_coeff[0] * data[i-1];
  92920. data[i] = residual[i] + (sum >> lp_quantization);
  92921. }
  92922. }
  92923. }
  92924. else {
  92925. if(order == 2) {
  92926. for(i = 0; i < (int)data_len; i++) {
  92927. sum = 0;
  92928. sum += qlp_coeff[1] * data[i-2];
  92929. sum += qlp_coeff[0] * data[i-1];
  92930. data[i] = residual[i] + (sum >> lp_quantization);
  92931. }
  92932. }
  92933. else { /* order == 1 */
  92934. for(i = 0; i < (int)data_len; i++)
  92935. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  92936. }
  92937. }
  92938. }
  92939. }
  92940. else { /* order > 12 */
  92941. for(i = 0; i < (int)data_len; i++) {
  92942. sum = 0;
  92943. switch(order) {
  92944. case 32: sum += qlp_coeff[31] * data[i-32];
  92945. case 31: sum += qlp_coeff[30] * data[i-31];
  92946. case 30: sum += qlp_coeff[29] * data[i-30];
  92947. case 29: sum += qlp_coeff[28] * data[i-29];
  92948. case 28: sum += qlp_coeff[27] * data[i-28];
  92949. case 27: sum += qlp_coeff[26] * data[i-27];
  92950. case 26: sum += qlp_coeff[25] * data[i-26];
  92951. case 25: sum += qlp_coeff[24] * data[i-25];
  92952. case 24: sum += qlp_coeff[23] * data[i-24];
  92953. case 23: sum += qlp_coeff[22] * data[i-23];
  92954. case 22: sum += qlp_coeff[21] * data[i-22];
  92955. case 21: sum += qlp_coeff[20] * data[i-21];
  92956. case 20: sum += qlp_coeff[19] * data[i-20];
  92957. case 19: sum += qlp_coeff[18] * data[i-19];
  92958. case 18: sum += qlp_coeff[17] * data[i-18];
  92959. case 17: sum += qlp_coeff[16] * data[i-17];
  92960. case 16: sum += qlp_coeff[15] * data[i-16];
  92961. case 15: sum += qlp_coeff[14] * data[i-15];
  92962. case 14: sum += qlp_coeff[13] * data[i-14];
  92963. case 13: sum += qlp_coeff[12] * data[i-13];
  92964. sum += qlp_coeff[11] * data[i-12];
  92965. sum += qlp_coeff[10] * data[i-11];
  92966. sum += qlp_coeff[ 9] * data[i-10];
  92967. sum += qlp_coeff[ 8] * data[i- 9];
  92968. sum += qlp_coeff[ 7] * data[i- 8];
  92969. sum += qlp_coeff[ 6] * data[i- 7];
  92970. sum += qlp_coeff[ 5] * data[i- 6];
  92971. sum += qlp_coeff[ 4] * data[i- 5];
  92972. sum += qlp_coeff[ 3] * data[i- 4];
  92973. sum += qlp_coeff[ 2] * data[i- 3];
  92974. sum += qlp_coeff[ 1] * data[i- 2];
  92975. sum += qlp_coeff[ 0] * data[i- 1];
  92976. }
  92977. data[i] = residual[i] + (sum >> lp_quantization);
  92978. }
  92979. }
  92980. }
  92981. #endif
  92982. 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[])
  92983. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  92984. {
  92985. unsigned i, j;
  92986. FLAC__int64 sum;
  92987. const FLAC__int32 *r = residual, *history;
  92988. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  92989. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  92990. for(i=0;i<order;i++)
  92991. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  92992. fprintf(stderr,"\n");
  92993. #endif
  92994. FLAC__ASSERT(order > 0);
  92995. for(i = 0; i < data_len; i++) {
  92996. sum = 0;
  92997. history = data;
  92998. for(j = 0; j < order; j++)
  92999. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  93000. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  93001. #ifdef _MSC_VER
  93002. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  93003. #else
  93004. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  93005. #endif
  93006. break;
  93007. }
  93008. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  93009. #ifdef _MSC_VER
  93010. 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));
  93011. #else
  93012. 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)));
  93013. #endif
  93014. break;
  93015. }
  93016. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  93017. }
  93018. }
  93019. #else /* fully unrolled version for normal use */
  93020. {
  93021. int i;
  93022. FLAC__int64 sum;
  93023. FLAC__ASSERT(order > 0);
  93024. FLAC__ASSERT(order <= 32);
  93025. /*
  93026. * We do unique versions up to 12th order since that's the subset limit.
  93027. * Also they are roughly ordered to match frequency of occurrence to
  93028. * minimize branching.
  93029. */
  93030. if(order <= 12) {
  93031. if(order > 8) {
  93032. if(order > 10) {
  93033. if(order == 12) {
  93034. for(i = 0; i < (int)data_len; i++) {
  93035. sum = 0;
  93036. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93037. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93038. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93039. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93040. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93041. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93042. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93043. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93044. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93045. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93046. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93047. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93048. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93049. }
  93050. }
  93051. else { /* order == 11 */
  93052. for(i = 0; i < (int)data_len; i++) {
  93053. sum = 0;
  93054. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93055. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93056. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93057. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93058. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93059. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93060. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93061. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93062. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93063. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93064. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93065. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93066. }
  93067. }
  93068. }
  93069. else {
  93070. if(order == 10) {
  93071. for(i = 0; i < (int)data_len; i++) {
  93072. sum = 0;
  93073. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93074. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93075. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93076. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93077. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93078. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93079. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93080. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93081. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93082. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93083. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93084. }
  93085. }
  93086. else { /* order == 9 */
  93087. for(i = 0; i < (int)data_len; i++) {
  93088. sum = 0;
  93089. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93090. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93091. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93092. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93093. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93094. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93095. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93096. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93097. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93098. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93099. }
  93100. }
  93101. }
  93102. }
  93103. else if(order > 4) {
  93104. if(order > 6) {
  93105. if(order == 8) {
  93106. for(i = 0; i < (int)data_len; i++) {
  93107. sum = 0;
  93108. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93109. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93110. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93111. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93112. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93113. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93114. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93115. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93116. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93117. }
  93118. }
  93119. else { /* order == 7 */
  93120. for(i = 0; i < (int)data_len; i++) {
  93121. sum = 0;
  93122. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93123. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93124. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93125. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93126. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93127. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93128. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93129. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93130. }
  93131. }
  93132. }
  93133. else {
  93134. if(order == 6) {
  93135. for(i = 0; i < (int)data_len; i++) {
  93136. sum = 0;
  93137. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93138. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93139. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93140. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93141. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93142. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93143. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93144. }
  93145. }
  93146. else { /* order == 5 */
  93147. for(i = 0; i < (int)data_len; i++) {
  93148. sum = 0;
  93149. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93150. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93151. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93152. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93153. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93154. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93155. }
  93156. }
  93157. }
  93158. }
  93159. else {
  93160. if(order > 2) {
  93161. if(order == 4) {
  93162. for(i = 0; i < (int)data_len; i++) {
  93163. sum = 0;
  93164. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93165. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93166. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93167. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93168. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93169. }
  93170. }
  93171. else { /* order == 3 */
  93172. for(i = 0; i < (int)data_len; i++) {
  93173. sum = 0;
  93174. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93175. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93176. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93177. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93178. }
  93179. }
  93180. }
  93181. else {
  93182. if(order == 2) {
  93183. for(i = 0; i < (int)data_len; i++) {
  93184. sum = 0;
  93185. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93186. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93187. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93188. }
  93189. }
  93190. else { /* order == 1 */
  93191. for(i = 0; i < (int)data_len; i++)
  93192. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  93193. }
  93194. }
  93195. }
  93196. }
  93197. else { /* order > 12 */
  93198. for(i = 0; i < (int)data_len; i++) {
  93199. sum = 0;
  93200. switch(order) {
  93201. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  93202. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  93203. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  93204. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  93205. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  93206. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  93207. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  93208. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  93209. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  93210. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  93211. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  93212. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  93213. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  93214. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  93215. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  93216. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  93217. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  93218. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  93219. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  93220. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  93221. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93222. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93223. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  93224. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  93225. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  93226. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  93227. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  93228. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  93229. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  93230. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  93231. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  93232. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  93233. }
  93234. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93235. }
  93236. }
  93237. }
  93238. #endif
  93239. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93240. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  93241. {
  93242. FLAC__double error_scale;
  93243. FLAC__ASSERT(total_samples > 0);
  93244. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  93245. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  93246. }
  93247. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  93248. {
  93249. if(lpc_error > 0.0) {
  93250. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  93251. if(bps >= 0.0)
  93252. return bps;
  93253. else
  93254. return 0.0;
  93255. }
  93256. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  93257. return 1e32;
  93258. }
  93259. else {
  93260. return 0.0;
  93261. }
  93262. }
  93263. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  93264. {
  93265. 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 */
  93266. FLAC__double bits, best_bits, error_scale;
  93267. FLAC__ASSERT(max_order > 0);
  93268. FLAC__ASSERT(total_samples > 0);
  93269. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  93270. best_index = 0;
  93271. best_bits = (unsigned)(-1);
  93272. for(index = 0, order = 1; index < max_order; index++, order++) {
  93273. 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);
  93274. if(bits < best_bits) {
  93275. best_index = index;
  93276. best_bits = bits;
  93277. }
  93278. }
  93279. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  93280. }
  93281. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  93282. #endif
  93283. /********* End of inlined file: lpc_flac.c *********/
  93284. /********* Start of inlined file: md5.c *********/
  93285. /********* Start of inlined file: juce_FlacHeader.h *********/
  93286. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93287. // tasks..
  93288. #define VERSION "1.2.1"
  93289. #define FLAC__NO_DLL 1
  93290. #ifdef _MSC_VER
  93291. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93292. #endif
  93293. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  93294. #define FLAC__SYS_DARWIN 1
  93295. #endif
  93296. /********* End of inlined file: juce_FlacHeader.h *********/
  93297. #if JUCE_USE_FLAC
  93298. #if HAVE_CONFIG_H
  93299. # include <config.h>
  93300. #endif
  93301. #include <stdlib.h> /* for malloc() */
  93302. #include <string.h> /* for memcpy() */
  93303. /********* Start of inlined file: md5.h *********/
  93304. #ifndef FLAC__PRIVATE__MD5_H
  93305. #define FLAC__PRIVATE__MD5_H
  93306. /*
  93307. * This is the header file for the MD5 message-digest algorithm.
  93308. * The algorithm is due to Ron Rivest. This code was
  93309. * written by Colin Plumb in 1993, no copyright is claimed.
  93310. * This code is in the public domain; do with it what you wish.
  93311. *
  93312. * Equivalent code is available from RSA Data Security, Inc.
  93313. * This code has been tested against that, and is equivalent,
  93314. * except that you don't need to include two pages of legalese
  93315. * with every copy.
  93316. *
  93317. * To compute the message digest of a chunk of bytes, declare an
  93318. * MD5Context structure, pass it to MD5Init, call MD5Update as
  93319. * needed on buffers full of bytes, and then call MD5Final, which
  93320. * will fill a supplied 16-byte array with the digest.
  93321. *
  93322. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  93323. * header definitions; now uses stuff from dpkg's config.h
  93324. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  93325. * Still in the public domain.
  93326. *
  93327. * Josh Coalson: made some changes to integrate with libFLAC.
  93328. * Still in the public domain, with no warranty.
  93329. */
  93330. typedef struct {
  93331. FLAC__uint32 in[16];
  93332. FLAC__uint32 buf[4];
  93333. FLAC__uint32 bytes[2];
  93334. FLAC__byte *internal_buf;
  93335. size_t capacity;
  93336. } FLAC__MD5Context;
  93337. void FLAC__MD5Init(FLAC__MD5Context *context);
  93338. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  93339. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  93340. #endif
  93341. /********* End of inlined file: md5.h *********/
  93342. #ifndef FLaC__INLINE
  93343. #define FLaC__INLINE
  93344. #endif
  93345. /*
  93346. * This code implements the MD5 message-digest algorithm.
  93347. * The algorithm is due to Ron Rivest. This code was
  93348. * written by Colin Plumb in 1993, no copyright is claimed.
  93349. * This code is in the public domain; do with it what you wish.
  93350. *
  93351. * Equivalent code is available from RSA Data Security, Inc.
  93352. * This code has been tested against that, and is equivalent,
  93353. * except that you don't need to include two pages of legalese
  93354. * with every copy.
  93355. *
  93356. * To compute the message digest of a chunk of bytes, declare an
  93357. * MD5Context structure, pass it to MD5Init, call MD5Update as
  93358. * needed on buffers full of bytes, and then call MD5Final, which
  93359. * will fill a supplied 16-byte array with the digest.
  93360. *
  93361. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  93362. * definitions; now uses stuff from dpkg's config.h.
  93363. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  93364. * Still in the public domain.
  93365. *
  93366. * Josh Coalson: made some changes to integrate with libFLAC.
  93367. * Still in the public domain.
  93368. */
  93369. /* The four core functions - F1 is optimized somewhat */
  93370. /* #define F1(x, y, z) (x & y | ~x & z) */
  93371. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  93372. #define F2(x, y, z) F1(z, x, y)
  93373. #define F3(x, y, z) (x ^ y ^ z)
  93374. #define F4(x, y, z) (y ^ (x | ~z))
  93375. /* This is the central step in the MD5 algorithm. */
  93376. #define MD5STEP(f,w,x,y,z,in,s) \
  93377. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  93378. /*
  93379. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  93380. * reflect the addition of 16 longwords of new data. MD5Update blocks
  93381. * the data and converts bytes into longwords for this routine.
  93382. */
  93383. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  93384. {
  93385. register FLAC__uint32 a, b, c, d;
  93386. a = buf[0];
  93387. b = buf[1];
  93388. c = buf[2];
  93389. d = buf[3];
  93390. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  93391. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  93392. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  93393. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  93394. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  93395. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  93396. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  93397. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  93398. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  93399. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  93400. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  93401. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  93402. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  93403. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  93404. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  93405. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  93406. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  93407. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  93408. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  93409. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  93410. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  93411. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  93412. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  93413. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  93414. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  93415. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  93416. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  93417. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  93418. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  93419. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  93420. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  93421. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  93422. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  93423. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  93424. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  93425. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  93426. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  93427. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  93428. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  93429. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  93430. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  93431. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  93432. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  93433. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  93434. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  93435. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  93436. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  93437. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  93438. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  93439. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  93440. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  93441. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  93442. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  93443. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  93444. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  93445. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  93446. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  93447. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  93448. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  93449. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  93450. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  93451. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  93452. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  93453. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  93454. buf[0] += a;
  93455. buf[1] += b;
  93456. buf[2] += c;
  93457. buf[3] += d;
  93458. }
  93459. #if WORDS_BIGENDIAN
  93460. //@@@@@@ OPT: use bswap/intrinsics
  93461. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  93462. {
  93463. register FLAC__uint32 x;
  93464. do {
  93465. x = *buf;
  93466. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  93467. *buf++ = (x >> 16) | (x << 16);
  93468. } while (--words);
  93469. }
  93470. static void byteSwapX16(FLAC__uint32 *buf)
  93471. {
  93472. register FLAC__uint32 x;
  93473. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93474. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93475. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93476. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93477. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93478. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93479. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93480. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93481. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93482. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93483. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93484. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93485. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93486. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93487. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  93488. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  93489. }
  93490. #else
  93491. #define byteSwap(buf, words)
  93492. #define byteSwapX16(buf)
  93493. #endif
  93494. /*
  93495. * Update context to reflect the concatenation of another buffer full
  93496. * of bytes.
  93497. */
  93498. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  93499. {
  93500. FLAC__uint32 t;
  93501. /* Update byte count */
  93502. t = ctx->bytes[0];
  93503. if ((ctx->bytes[0] = t + len) < t)
  93504. ctx->bytes[1]++; /* Carry from low to high */
  93505. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  93506. if (t > len) {
  93507. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  93508. return;
  93509. }
  93510. /* First chunk is an odd size */
  93511. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  93512. byteSwapX16(ctx->in);
  93513. FLAC__MD5Transform(ctx->buf, ctx->in);
  93514. buf += t;
  93515. len -= t;
  93516. /* Process data in 64-byte chunks */
  93517. while (len >= 64) {
  93518. memcpy(ctx->in, buf, 64);
  93519. byteSwapX16(ctx->in);
  93520. FLAC__MD5Transform(ctx->buf, ctx->in);
  93521. buf += 64;
  93522. len -= 64;
  93523. }
  93524. /* Handle any remaining bytes of data. */
  93525. memcpy(ctx->in, buf, len);
  93526. }
  93527. /*
  93528. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  93529. * initialization constants.
  93530. */
  93531. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  93532. {
  93533. ctx->buf[0] = 0x67452301;
  93534. ctx->buf[1] = 0xefcdab89;
  93535. ctx->buf[2] = 0x98badcfe;
  93536. ctx->buf[3] = 0x10325476;
  93537. ctx->bytes[0] = 0;
  93538. ctx->bytes[1] = 0;
  93539. ctx->internal_buf = 0;
  93540. ctx->capacity = 0;
  93541. }
  93542. /*
  93543. * Final wrapup - pad to 64-byte boundary with the bit pattern
  93544. * 1 0* (64-bit count of bits processed, MSB-first)
  93545. */
  93546. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  93547. {
  93548. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  93549. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  93550. /* Set the first char of padding to 0x80. There is always room. */
  93551. *p++ = 0x80;
  93552. /* Bytes of padding needed to make 56 bytes (-8..55) */
  93553. count = 56 - 1 - count;
  93554. if (count < 0) { /* Padding forces an extra block */
  93555. memset(p, 0, count + 8);
  93556. byteSwapX16(ctx->in);
  93557. FLAC__MD5Transform(ctx->buf, ctx->in);
  93558. p = (FLAC__byte *)ctx->in;
  93559. count = 56;
  93560. }
  93561. memset(p, 0, count);
  93562. byteSwap(ctx->in, 14);
  93563. /* Append length in bits and transform */
  93564. ctx->in[14] = ctx->bytes[0] << 3;
  93565. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  93566. FLAC__MD5Transform(ctx->buf, ctx->in);
  93567. byteSwap(ctx->buf, 4);
  93568. memcpy(digest, ctx->buf, 16);
  93569. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  93570. if(0 != ctx->internal_buf) {
  93571. free(ctx->internal_buf);
  93572. ctx->internal_buf = 0;
  93573. ctx->capacity = 0;
  93574. }
  93575. }
  93576. /*
  93577. * Convert the incoming audio signal to a byte stream
  93578. */
  93579. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  93580. {
  93581. unsigned channel, sample;
  93582. register FLAC__int32 a_word;
  93583. register FLAC__byte *buf_ = buf;
  93584. #if WORDS_BIGENDIAN
  93585. #else
  93586. if(channels == 2 && bytes_per_sample == 2) {
  93587. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  93588. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  93589. for(sample = 0; sample < samples; sample++, buf1_+=2)
  93590. *buf1_ = (FLAC__int16)signal[1][sample];
  93591. }
  93592. else if(channels == 1 && bytes_per_sample == 2) {
  93593. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  93594. for(sample = 0; sample < samples; sample++)
  93595. *buf1_++ = (FLAC__int16)signal[0][sample];
  93596. }
  93597. else
  93598. #endif
  93599. if(bytes_per_sample == 2) {
  93600. if(channels == 2) {
  93601. for(sample = 0; sample < samples; sample++) {
  93602. a_word = signal[0][sample];
  93603. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93604. *buf_++ = (FLAC__byte)a_word;
  93605. a_word = signal[1][sample];
  93606. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93607. *buf_++ = (FLAC__byte)a_word;
  93608. }
  93609. }
  93610. else if(channels == 1) {
  93611. for(sample = 0; sample < samples; sample++) {
  93612. a_word = signal[0][sample];
  93613. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93614. *buf_++ = (FLAC__byte)a_word;
  93615. }
  93616. }
  93617. else {
  93618. for(sample = 0; sample < samples; sample++) {
  93619. for(channel = 0; channel < channels; channel++) {
  93620. a_word = signal[channel][sample];
  93621. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93622. *buf_++ = (FLAC__byte)a_word;
  93623. }
  93624. }
  93625. }
  93626. }
  93627. else if(bytes_per_sample == 3) {
  93628. if(channels == 2) {
  93629. for(sample = 0; sample < samples; sample++) {
  93630. a_word = signal[0][sample];
  93631. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93632. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93633. *buf_++ = (FLAC__byte)a_word;
  93634. a_word = signal[1][sample];
  93635. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93636. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93637. *buf_++ = (FLAC__byte)a_word;
  93638. }
  93639. }
  93640. else if(channels == 1) {
  93641. for(sample = 0; sample < samples; sample++) {
  93642. a_word = signal[0][sample];
  93643. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93644. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93645. *buf_++ = (FLAC__byte)a_word;
  93646. }
  93647. }
  93648. else {
  93649. for(sample = 0; sample < samples; sample++) {
  93650. for(channel = 0; channel < channels; channel++) {
  93651. a_word = signal[channel][sample];
  93652. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93653. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93654. *buf_++ = (FLAC__byte)a_word;
  93655. }
  93656. }
  93657. }
  93658. }
  93659. else if(bytes_per_sample == 1) {
  93660. if(channels == 2) {
  93661. for(sample = 0; sample < samples; sample++) {
  93662. a_word = signal[0][sample];
  93663. *buf_++ = (FLAC__byte)a_word;
  93664. a_word = signal[1][sample];
  93665. *buf_++ = (FLAC__byte)a_word;
  93666. }
  93667. }
  93668. else if(channels == 1) {
  93669. for(sample = 0; sample < samples; sample++) {
  93670. a_word = signal[0][sample];
  93671. *buf_++ = (FLAC__byte)a_word;
  93672. }
  93673. }
  93674. else {
  93675. for(sample = 0; sample < samples; sample++) {
  93676. for(channel = 0; channel < channels; channel++) {
  93677. a_word = signal[channel][sample];
  93678. *buf_++ = (FLAC__byte)a_word;
  93679. }
  93680. }
  93681. }
  93682. }
  93683. else { /* bytes_per_sample == 4, maybe optimize more later */
  93684. for(sample = 0; sample < samples; sample++) {
  93685. for(channel = 0; channel < channels; channel++) {
  93686. a_word = signal[channel][sample];
  93687. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93688. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93689. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  93690. *buf_++ = (FLAC__byte)a_word;
  93691. }
  93692. }
  93693. }
  93694. }
  93695. /*
  93696. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  93697. */
  93698. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  93699. {
  93700. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  93701. /* overflow check */
  93702. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  93703. return false;
  93704. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  93705. return false;
  93706. if(ctx->capacity < bytes_needed) {
  93707. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  93708. if(0 == tmp) {
  93709. free(ctx->internal_buf);
  93710. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  93711. return false;
  93712. }
  93713. ctx->internal_buf = tmp;
  93714. ctx->capacity = bytes_needed;
  93715. }
  93716. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  93717. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  93718. return true;
  93719. }
  93720. #endif
  93721. /********* End of inlined file: md5.c *********/
  93722. /********* Start of inlined file: memory.c *********/
  93723. /********* Start of inlined file: juce_FlacHeader.h *********/
  93724. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93725. // tasks..
  93726. #define VERSION "1.2.1"
  93727. #define FLAC__NO_DLL 1
  93728. #ifdef _MSC_VER
  93729. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93730. #endif
  93731. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  93732. #define FLAC__SYS_DARWIN 1
  93733. #endif
  93734. /********* End of inlined file: juce_FlacHeader.h *********/
  93735. #if JUCE_USE_FLAC
  93736. #if HAVE_CONFIG_H
  93737. # include <config.h>
  93738. #endif
  93739. /********* Start of inlined file: memory.h *********/
  93740. #ifndef FLAC__PRIVATE__MEMORY_H
  93741. #define FLAC__PRIVATE__MEMORY_H
  93742. #ifdef HAVE_CONFIG_H
  93743. #include <config.h>
  93744. #endif
  93745. #include <stdlib.h> /* for size_t */
  93746. /* Returns the unaligned address returned by malloc.
  93747. * Use free() on this address to deallocate.
  93748. */
  93749. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  93750. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  93751. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  93752. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  93753. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  93754. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93755. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  93756. #endif
  93757. #endif
  93758. /********* End of inlined file: memory.h *********/
  93759. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  93760. {
  93761. void *x;
  93762. FLAC__ASSERT(0 != aligned_address);
  93763. #ifdef FLAC__ALIGN_MALLOC_DATA
  93764. /* align on 32-byte (256-bit) boundary */
  93765. x = safe_malloc_add_2op_(bytes, /*+*/31);
  93766. #ifdef SIZEOF_VOIDP
  93767. #if SIZEOF_VOIDP == 4
  93768. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  93769. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  93770. #elif SIZEOF_VOIDP == 8
  93771. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  93772. #else
  93773. # error Unsupported sizeof(void*)
  93774. #endif
  93775. #else
  93776. /* there's got to be a better way to do this right for all archs */
  93777. if(sizeof(void*) == sizeof(unsigned))
  93778. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  93779. else if(sizeof(void*) == sizeof(FLAC__uint64))
  93780. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  93781. else
  93782. return 0;
  93783. #endif
  93784. #else
  93785. x = safe_malloc_(bytes);
  93786. *aligned_address = x;
  93787. #endif
  93788. return x;
  93789. }
  93790. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  93791. {
  93792. FLAC__int32 *pu; /* unaligned pointer */
  93793. union { /* union needed to comply with C99 pointer aliasing rules */
  93794. FLAC__int32 *pa; /* aligned pointer */
  93795. void *pv; /* aligned pointer alias */
  93796. } u;
  93797. FLAC__ASSERT(elements > 0);
  93798. FLAC__ASSERT(0 != unaligned_pointer);
  93799. FLAC__ASSERT(0 != aligned_pointer);
  93800. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93801. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93802. return false;
  93803. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  93804. if(0 == pu) {
  93805. return false;
  93806. }
  93807. else {
  93808. if(*unaligned_pointer != 0)
  93809. free(*unaligned_pointer);
  93810. *unaligned_pointer = pu;
  93811. *aligned_pointer = u.pa;
  93812. return true;
  93813. }
  93814. }
  93815. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  93816. {
  93817. FLAC__uint32 *pu; /* unaligned pointer */
  93818. union { /* union needed to comply with C99 pointer aliasing rules */
  93819. FLAC__uint32 *pa; /* aligned pointer */
  93820. void *pv; /* aligned pointer alias */
  93821. } u;
  93822. FLAC__ASSERT(elements > 0);
  93823. FLAC__ASSERT(0 != unaligned_pointer);
  93824. FLAC__ASSERT(0 != aligned_pointer);
  93825. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93826. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93827. return false;
  93828. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  93829. if(0 == pu) {
  93830. return false;
  93831. }
  93832. else {
  93833. if(*unaligned_pointer != 0)
  93834. free(*unaligned_pointer);
  93835. *unaligned_pointer = pu;
  93836. *aligned_pointer = u.pa;
  93837. return true;
  93838. }
  93839. }
  93840. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  93841. {
  93842. FLAC__uint64 *pu; /* unaligned pointer */
  93843. union { /* union needed to comply with C99 pointer aliasing rules */
  93844. FLAC__uint64 *pa; /* aligned pointer */
  93845. void *pv; /* aligned pointer alias */
  93846. } u;
  93847. FLAC__ASSERT(elements > 0);
  93848. FLAC__ASSERT(0 != unaligned_pointer);
  93849. FLAC__ASSERT(0 != aligned_pointer);
  93850. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93851. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93852. return false;
  93853. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  93854. if(0 == pu) {
  93855. return false;
  93856. }
  93857. else {
  93858. if(*unaligned_pointer != 0)
  93859. free(*unaligned_pointer);
  93860. *unaligned_pointer = pu;
  93861. *aligned_pointer = u.pa;
  93862. return true;
  93863. }
  93864. }
  93865. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  93866. {
  93867. unsigned *pu; /* unaligned pointer */
  93868. union { /* union needed to comply with C99 pointer aliasing rules */
  93869. unsigned *pa; /* aligned pointer */
  93870. void *pv; /* aligned pointer alias */
  93871. } u;
  93872. FLAC__ASSERT(elements > 0);
  93873. FLAC__ASSERT(0 != unaligned_pointer);
  93874. FLAC__ASSERT(0 != aligned_pointer);
  93875. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93876. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93877. return false;
  93878. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  93879. if(0 == pu) {
  93880. return false;
  93881. }
  93882. else {
  93883. if(*unaligned_pointer != 0)
  93884. free(*unaligned_pointer);
  93885. *unaligned_pointer = pu;
  93886. *aligned_pointer = u.pa;
  93887. return true;
  93888. }
  93889. }
  93890. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93891. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  93892. {
  93893. FLAC__real *pu; /* unaligned pointer */
  93894. union { /* union needed to comply with C99 pointer aliasing rules */
  93895. FLAC__real *pa; /* aligned pointer */
  93896. void *pv; /* aligned pointer alias */
  93897. } u;
  93898. FLAC__ASSERT(elements > 0);
  93899. FLAC__ASSERT(0 != unaligned_pointer);
  93900. FLAC__ASSERT(0 != aligned_pointer);
  93901. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93902. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93903. return false;
  93904. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  93905. if(0 == pu) {
  93906. return false;
  93907. }
  93908. else {
  93909. if(*unaligned_pointer != 0)
  93910. free(*unaligned_pointer);
  93911. *unaligned_pointer = pu;
  93912. *aligned_pointer = u.pa;
  93913. return true;
  93914. }
  93915. }
  93916. #endif
  93917. #endif
  93918. /********* End of inlined file: memory.c *********/
  93919. /********* Start of inlined file: stream_decoder.c *********/
  93920. /********* Start of inlined file: juce_FlacHeader.h *********/
  93921. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93922. // tasks..
  93923. #define VERSION "1.2.1"
  93924. #define FLAC__NO_DLL 1
  93925. #ifdef _MSC_VER
  93926. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93927. #endif
  93928. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  93929. #define FLAC__SYS_DARWIN 1
  93930. #endif
  93931. /********* End of inlined file: juce_FlacHeader.h *********/
  93932. #if JUCE_USE_FLAC
  93933. #if HAVE_CONFIG_H
  93934. # include <config.h>
  93935. #endif
  93936. #if defined _MSC_VER || defined __MINGW32__
  93937. #include <io.h> /* for _setmode() */
  93938. #include <fcntl.h> /* for _O_BINARY */
  93939. #endif
  93940. #if defined __CYGWIN__ || defined __EMX__
  93941. #include <io.h> /* for setmode(), O_BINARY */
  93942. #include <fcntl.h> /* for _O_BINARY */
  93943. #endif
  93944. #include <stdio.h>
  93945. #include <stdlib.h> /* for malloc() */
  93946. #include <string.h> /* for memset/memcpy() */
  93947. #include <sys/stat.h> /* for stat() */
  93948. #include <sys/types.h> /* for off_t */
  93949. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  93950. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  93951. #define fseeko fseek
  93952. #define ftello ftell
  93953. #endif
  93954. #endif
  93955. /********* Start of inlined file: stream_decoder.h *********/
  93956. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  93957. #define FLAC__PROTECTED__STREAM_DECODER_H
  93958. #if FLAC__HAS_OGG
  93959. #include "include/private/ogg_decoder_aspect.h"
  93960. #endif
  93961. typedef struct FLAC__StreamDecoderProtected {
  93962. FLAC__StreamDecoderState state;
  93963. unsigned channels;
  93964. FLAC__ChannelAssignment channel_assignment;
  93965. unsigned bits_per_sample;
  93966. unsigned sample_rate; /* in Hz */
  93967. unsigned blocksize; /* in samples (per channel) */
  93968. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  93969. #if FLAC__HAS_OGG
  93970. FLAC__OggDecoderAspect ogg_decoder_aspect;
  93971. #endif
  93972. } FLAC__StreamDecoderProtected;
  93973. /*
  93974. * return the number of input bytes consumed
  93975. */
  93976. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  93977. #endif
  93978. /********* End of inlined file: stream_decoder.h *********/
  93979. #ifdef max
  93980. #undef max
  93981. #endif
  93982. #define max(a,b) ((a)>(b)?(a):(b))
  93983. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93984. #ifdef _MSC_VER
  93985. #define FLAC__U64L(x) x
  93986. #else
  93987. #define FLAC__U64L(x) x##LLU
  93988. #endif
  93989. /* technically this should be in an "export.c" but this is convenient enough */
  93990. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  93991. #if FLAC__HAS_OGG
  93992. 1
  93993. #else
  93994. 0
  93995. #endif
  93996. ;
  93997. /***********************************************************************
  93998. *
  93999. * Private static data
  94000. *
  94001. ***********************************************************************/
  94002. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  94003. /***********************************************************************
  94004. *
  94005. * Private class method prototypes
  94006. *
  94007. ***********************************************************************/
  94008. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  94009. static FILE *get_binary_stdin_(void);
  94010. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  94011. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  94012. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  94013. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  94014. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  94015. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  94016. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  94017. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  94018. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  94019. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  94020. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  94021. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  94022. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  94023. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94024. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94025. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  94026. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  94027. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94028. 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);
  94029. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  94030. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  94031. #if FLAC__HAS_OGG
  94032. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  94033. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  94034. #endif
  94035. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  94036. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  94037. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  94038. #if FLAC__HAS_OGG
  94039. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  94040. #endif
  94041. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  94042. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  94043. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  94044. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  94045. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  94046. /***********************************************************************
  94047. *
  94048. * Private class data
  94049. *
  94050. ***********************************************************************/
  94051. typedef struct FLAC__StreamDecoderPrivate {
  94052. #if FLAC__HAS_OGG
  94053. FLAC__bool is_ogg;
  94054. #endif
  94055. FLAC__StreamDecoderReadCallback read_callback;
  94056. FLAC__StreamDecoderSeekCallback seek_callback;
  94057. FLAC__StreamDecoderTellCallback tell_callback;
  94058. FLAC__StreamDecoderLengthCallback length_callback;
  94059. FLAC__StreamDecoderEofCallback eof_callback;
  94060. FLAC__StreamDecoderWriteCallback write_callback;
  94061. FLAC__StreamDecoderMetadataCallback metadata_callback;
  94062. FLAC__StreamDecoderErrorCallback error_callback;
  94063. /* generic 32-bit datapath: */
  94064. 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[]);
  94065. /* generic 64-bit datapath: */
  94066. 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[]);
  94067. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  94068. 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[]);
  94069. /* 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: */
  94070. 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[]);
  94071. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  94072. void *client_data;
  94073. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  94074. FLAC__BitReader *input;
  94075. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  94076. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  94077. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  94078. unsigned output_capacity, output_channels;
  94079. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  94080. FLAC__uint64 samples_decoded;
  94081. FLAC__bool has_stream_info, has_seek_table;
  94082. FLAC__StreamMetadata stream_info;
  94083. FLAC__StreamMetadata seek_table;
  94084. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  94085. FLAC__byte *metadata_filter_ids;
  94086. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  94087. FLAC__Frame frame;
  94088. FLAC__bool cached; /* true if there is a byte in lookahead */
  94089. FLAC__CPUInfo cpuinfo;
  94090. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  94091. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  94092. /* unaligned (original) pointers to allocated data */
  94093. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  94094. 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 */
  94095. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  94096. FLAC__bool is_seeking;
  94097. FLAC__MD5Context md5context;
  94098. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  94099. /* (the rest of these are only used for seeking) */
  94100. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  94101. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  94102. FLAC__uint64 target_sample;
  94103. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  94104. #if FLAC__HAS_OGG
  94105. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  94106. #endif
  94107. } FLAC__StreamDecoderPrivate;
  94108. /***********************************************************************
  94109. *
  94110. * Public static class data
  94111. *
  94112. ***********************************************************************/
  94113. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  94114. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  94115. "FLAC__STREAM_DECODER_READ_METADATA",
  94116. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  94117. "FLAC__STREAM_DECODER_READ_FRAME",
  94118. "FLAC__STREAM_DECODER_END_OF_STREAM",
  94119. "FLAC__STREAM_DECODER_OGG_ERROR",
  94120. "FLAC__STREAM_DECODER_SEEK_ERROR",
  94121. "FLAC__STREAM_DECODER_ABORTED",
  94122. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  94123. "FLAC__STREAM_DECODER_UNINITIALIZED"
  94124. };
  94125. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  94126. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  94127. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  94128. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  94129. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  94130. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  94131. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  94132. };
  94133. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  94134. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  94135. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  94136. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  94137. };
  94138. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  94139. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  94140. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  94141. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  94142. };
  94143. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  94144. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  94145. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  94146. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  94147. };
  94148. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  94149. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  94150. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  94151. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  94152. };
  94153. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  94154. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  94155. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  94156. };
  94157. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  94158. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  94159. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  94160. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  94161. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  94162. };
  94163. /***********************************************************************
  94164. *
  94165. * Class constructor/destructor
  94166. *
  94167. ***********************************************************************/
  94168. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  94169. {
  94170. FLAC__StreamDecoder *decoder;
  94171. unsigned i;
  94172. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  94173. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  94174. if(decoder == 0) {
  94175. return 0;
  94176. }
  94177. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  94178. if(decoder->protected_ == 0) {
  94179. free(decoder);
  94180. return 0;
  94181. }
  94182. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  94183. if(decoder->private_ == 0) {
  94184. free(decoder->protected_);
  94185. free(decoder);
  94186. return 0;
  94187. }
  94188. decoder->private_->input = FLAC__bitreader_new();
  94189. if(decoder->private_->input == 0) {
  94190. free(decoder->private_);
  94191. free(decoder->protected_);
  94192. free(decoder);
  94193. return 0;
  94194. }
  94195. decoder->private_->metadata_filter_ids_capacity = 16;
  94196. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  94197. FLAC__bitreader_delete(decoder->private_->input);
  94198. free(decoder->private_);
  94199. free(decoder->protected_);
  94200. free(decoder);
  94201. return 0;
  94202. }
  94203. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  94204. decoder->private_->output[i] = 0;
  94205. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  94206. }
  94207. decoder->private_->output_capacity = 0;
  94208. decoder->private_->output_channels = 0;
  94209. decoder->private_->has_seek_table = false;
  94210. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  94211. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  94212. decoder->private_->file = 0;
  94213. set_defaults_dec(decoder);
  94214. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  94215. return decoder;
  94216. }
  94217. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  94218. {
  94219. unsigned i;
  94220. FLAC__ASSERT(0 != decoder);
  94221. FLAC__ASSERT(0 != decoder->protected_);
  94222. FLAC__ASSERT(0 != decoder->private_);
  94223. FLAC__ASSERT(0 != decoder->private_->input);
  94224. (void)FLAC__stream_decoder_finish(decoder);
  94225. if(0 != decoder->private_->metadata_filter_ids)
  94226. free(decoder->private_->metadata_filter_ids);
  94227. FLAC__bitreader_delete(decoder->private_->input);
  94228. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  94229. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  94230. free(decoder->private_);
  94231. free(decoder->protected_);
  94232. free(decoder);
  94233. }
  94234. /***********************************************************************
  94235. *
  94236. * Public class methods
  94237. *
  94238. ***********************************************************************/
  94239. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  94240. FLAC__StreamDecoder *decoder,
  94241. FLAC__StreamDecoderReadCallback read_callback,
  94242. FLAC__StreamDecoderSeekCallback seek_callback,
  94243. FLAC__StreamDecoderTellCallback tell_callback,
  94244. FLAC__StreamDecoderLengthCallback length_callback,
  94245. FLAC__StreamDecoderEofCallback eof_callback,
  94246. FLAC__StreamDecoderWriteCallback write_callback,
  94247. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94248. FLAC__StreamDecoderErrorCallback error_callback,
  94249. void *client_data,
  94250. FLAC__bool is_ogg
  94251. )
  94252. {
  94253. FLAC__ASSERT(0 != decoder);
  94254. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94255. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  94256. #if !FLAC__HAS_OGG
  94257. if(is_ogg)
  94258. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  94259. #endif
  94260. if(
  94261. 0 == read_callback ||
  94262. 0 == write_callback ||
  94263. 0 == error_callback ||
  94264. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  94265. )
  94266. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  94267. #if FLAC__HAS_OGG
  94268. decoder->private_->is_ogg = is_ogg;
  94269. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  94270. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  94271. #endif
  94272. /*
  94273. * get the CPU info and set the function pointers
  94274. */
  94275. FLAC__cpu_info(&decoder->private_->cpuinfo);
  94276. /* first default to the non-asm routines */
  94277. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  94278. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  94279. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  94280. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  94281. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  94282. /* now override with asm where appropriate */
  94283. #ifndef FLAC__NO_ASM
  94284. if(decoder->private_->cpuinfo.use_asm) {
  94285. #ifdef FLAC__CPU_IA32
  94286. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  94287. #ifdef FLAC__HAS_NASM
  94288. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  94289. if(decoder->private_->cpuinfo.data.ia32.bswap)
  94290. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  94291. #endif
  94292. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  94293. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  94294. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  94295. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  94296. }
  94297. else {
  94298. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  94299. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  94300. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  94301. }
  94302. #endif
  94303. #elif defined FLAC__CPU_PPC
  94304. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  94305. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  94306. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  94307. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  94308. }
  94309. #endif
  94310. }
  94311. #endif
  94312. /* from here on, errors are fatal */
  94313. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  94314. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94315. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  94316. }
  94317. decoder->private_->read_callback = read_callback;
  94318. decoder->private_->seek_callback = seek_callback;
  94319. decoder->private_->tell_callback = tell_callback;
  94320. decoder->private_->length_callback = length_callback;
  94321. decoder->private_->eof_callback = eof_callback;
  94322. decoder->private_->write_callback = write_callback;
  94323. decoder->private_->metadata_callback = metadata_callback;
  94324. decoder->private_->error_callback = error_callback;
  94325. decoder->private_->client_data = client_data;
  94326. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  94327. decoder->private_->samples_decoded = 0;
  94328. decoder->private_->has_stream_info = false;
  94329. decoder->private_->cached = false;
  94330. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  94331. decoder->private_->is_seeking = false;
  94332. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  94333. if(!FLAC__stream_decoder_reset(decoder)) {
  94334. /* above call sets the state for us */
  94335. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  94336. }
  94337. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  94338. }
  94339. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  94340. FLAC__StreamDecoder *decoder,
  94341. FLAC__StreamDecoderReadCallback read_callback,
  94342. FLAC__StreamDecoderSeekCallback seek_callback,
  94343. FLAC__StreamDecoderTellCallback tell_callback,
  94344. FLAC__StreamDecoderLengthCallback length_callback,
  94345. FLAC__StreamDecoderEofCallback eof_callback,
  94346. FLAC__StreamDecoderWriteCallback write_callback,
  94347. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94348. FLAC__StreamDecoderErrorCallback error_callback,
  94349. void *client_data
  94350. )
  94351. {
  94352. return init_stream_internal_dec(
  94353. decoder,
  94354. read_callback,
  94355. seek_callback,
  94356. tell_callback,
  94357. length_callback,
  94358. eof_callback,
  94359. write_callback,
  94360. metadata_callback,
  94361. error_callback,
  94362. client_data,
  94363. /*is_ogg=*/false
  94364. );
  94365. }
  94366. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  94367. FLAC__StreamDecoder *decoder,
  94368. FLAC__StreamDecoderReadCallback read_callback,
  94369. FLAC__StreamDecoderSeekCallback seek_callback,
  94370. FLAC__StreamDecoderTellCallback tell_callback,
  94371. FLAC__StreamDecoderLengthCallback length_callback,
  94372. FLAC__StreamDecoderEofCallback eof_callback,
  94373. FLAC__StreamDecoderWriteCallback write_callback,
  94374. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94375. FLAC__StreamDecoderErrorCallback error_callback,
  94376. void *client_data
  94377. )
  94378. {
  94379. return init_stream_internal_dec(
  94380. decoder,
  94381. read_callback,
  94382. seek_callback,
  94383. tell_callback,
  94384. length_callback,
  94385. eof_callback,
  94386. write_callback,
  94387. metadata_callback,
  94388. error_callback,
  94389. client_data,
  94390. /*is_ogg=*/true
  94391. );
  94392. }
  94393. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  94394. FLAC__StreamDecoder *decoder,
  94395. FILE *file,
  94396. FLAC__StreamDecoderWriteCallback write_callback,
  94397. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94398. FLAC__StreamDecoderErrorCallback error_callback,
  94399. void *client_data,
  94400. FLAC__bool is_ogg
  94401. )
  94402. {
  94403. FLAC__ASSERT(0 != decoder);
  94404. FLAC__ASSERT(0 != file);
  94405. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94406. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  94407. if(0 == write_callback || 0 == error_callback)
  94408. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  94409. /*
  94410. * To make sure that our file does not go unclosed after an error, we
  94411. * must assign the FILE pointer before any further error can occur in
  94412. * this routine.
  94413. */
  94414. if(file == stdin)
  94415. file = get_binary_stdin_(); /* just to be safe */
  94416. decoder->private_->file = file;
  94417. return init_stream_internal_dec(
  94418. decoder,
  94419. file_read_callback_dec,
  94420. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  94421. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  94422. decoder->private_->file == stdin? 0: file_length_callback_,
  94423. file_eof_callback_,
  94424. write_callback,
  94425. metadata_callback,
  94426. error_callback,
  94427. client_data,
  94428. is_ogg
  94429. );
  94430. }
  94431. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  94432. FLAC__StreamDecoder *decoder,
  94433. FILE *file,
  94434. FLAC__StreamDecoderWriteCallback write_callback,
  94435. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94436. FLAC__StreamDecoderErrorCallback error_callback,
  94437. void *client_data
  94438. )
  94439. {
  94440. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  94441. }
  94442. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  94443. FLAC__StreamDecoder *decoder,
  94444. FILE *file,
  94445. FLAC__StreamDecoderWriteCallback write_callback,
  94446. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94447. FLAC__StreamDecoderErrorCallback error_callback,
  94448. void *client_data
  94449. )
  94450. {
  94451. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  94452. }
  94453. static FLAC__StreamDecoderInitStatus init_file_internal_(
  94454. FLAC__StreamDecoder *decoder,
  94455. const char *filename,
  94456. FLAC__StreamDecoderWriteCallback write_callback,
  94457. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94458. FLAC__StreamDecoderErrorCallback error_callback,
  94459. void *client_data,
  94460. FLAC__bool is_ogg
  94461. )
  94462. {
  94463. FILE *file;
  94464. FLAC__ASSERT(0 != decoder);
  94465. /*
  94466. * To make sure that our file does not go unclosed after an error, we
  94467. * have to do the same entrance checks here that are later performed
  94468. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  94469. */
  94470. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94471. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  94472. if(0 == write_callback || 0 == error_callback)
  94473. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  94474. file = filename? fopen(filename, "rb") : stdin;
  94475. if(0 == file)
  94476. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  94477. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  94478. }
  94479. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  94480. FLAC__StreamDecoder *decoder,
  94481. const char *filename,
  94482. FLAC__StreamDecoderWriteCallback write_callback,
  94483. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94484. FLAC__StreamDecoderErrorCallback error_callback,
  94485. void *client_data
  94486. )
  94487. {
  94488. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  94489. }
  94490. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  94491. FLAC__StreamDecoder *decoder,
  94492. const char *filename,
  94493. FLAC__StreamDecoderWriteCallback write_callback,
  94494. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94495. FLAC__StreamDecoderErrorCallback error_callback,
  94496. void *client_data
  94497. )
  94498. {
  94499. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  94500. }
  94501. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  94502. {
  94503. FLAC__bool md5_failed = false;
  94504. unsigned i;
  94505. FLAC__ASSERT(0 != decoder);
  94506. FLAC__ASSERT(0 != decoder->private_);
  94507. FLAC__ASSERT(0 != decoder->protected_);
  94508. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  94509. return true;
  94510. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  94511. * always call FLAC__MD5Final()
  94512. */
  94513. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  94514. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  94515. free(decoder->private_->seek_table.data.seek_table.points);
  94516. decoder->private_->seek_table.data.seek_table.points = 0;
  94517. decoder->private_->has_seek_table = false;
  94518. }
  94519. FLAC__bitreader_free(decoder->private_->input);
  94520. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  94521. /* WATCHOUT:
  94522. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  94523. * output arrays have a buffer of up to 3 zeroes in front
  94524. * (at negative indices) for alignment purposes; we use 4
  94525. * to keep the data well-aligned.
  94526. */
  94527. if(0 != decoder->private_->output[i]) {
  94528. free(decoder->private_->output[i]-4);
  94529. decoder->private_->output[i] = 0;
  94530. }
  94531. if(0 != decoder->private_->residual_unaligned[i]) {
  94532. free(decoder->private_->residual_unaligned[i]);
  94533. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  94534. }
  94535. }
  94536. decoder->private_->output_capacity = 0;
  94537. decoder->private_->output_channels = 0;
  94538. #if FLAC__HAS_OGG
  94539. if(decoder->private_->is_ogg)
  94540. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  94541. #endif
  94542. if(0 != decoder->private_->file) {
  94543. if(decoder->private_->file != stdin)
  94544. fclose(decoder->private_->file);
  94545. decoder->private_->file = 0;
  94546. }
  94547. if(decoder->private_->do_md5_checking) {
  94548. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  94549. md5_failed = true;
  94550. }
  94551. decoder->private_->is_seeking = false;
  94552. set_defaults_dec(decoder);
  94553. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  94554. return !md5_failed;
  94555. }
  94556. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  94557. {
  94558. FLAC__ASSERT(0 != decoder);
  94559. FLAC__ASSERT(0 != decoder->private_);
  94560. FLAC__ASSERT(0 != decoder->protected_);
  94561. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94562. return false;
  94563. #if FLAC__HAS_OGG
  94564. /* can't check decoder->private_->is_ogg since that's not set until init time */
  94565. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  94566. return true;
  94567. #else
  94568. (void)value;
  94569. return false;
  94570. #endif
  94571. }
  94572. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  94573. {
  94574. FLAC__ASSERT(0 != decoder);
  94575. FLAC__ASSERT(0 != decoder->protected_);
  94576. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94577. return false;
  94578. decoder->protected_->md5_checking = value;
  94579. return true;
  94580. }
  94581. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  94582. {
  94583. FLAC__ASSERT(0 != decoder);
  94584. FLAC__ASSERT(0 != decoder->private_);
  94585. FLAC__ASSERT(0 != decoder->protected_);
  94586. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  94587. /* double protection */
  94588. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  94589. return false;
  94590. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94591. return false;
  94592. decoder->private_->metadata_filter[type] = true;
  94593. if(type == FLAC__METADATA_TYPE_APPLICATION)
  94594. decoder->private_->metadata_filter_ids_count = 0;
  94595. return true;
  94596. }
  94597. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  94598. {
  94599. FLAC__ASSERT(0 != decoder);
  94600. FLAC__ASSERT(0 != decoder->private_);
  94601. FLAC__ASSERT(0 != decoder->protected_);
  94602. FLAC__ASSERT(0 != id);
  94603. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94604. return false;
  94605. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  94606. return true;
  94607. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  94608. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  94609. 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))) {
  94610. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94611. return false;
  94612. }
  94613. decoder->private_->metadata_filter_ids_capacity *= 2;
  94614. }
  94615. 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));
  94616. decoder->private_->metadata_filter_ids_count++;
  94617. return true;
  94618. }
  94619. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  94620. {
  94621. unsigned i;
  94622. FLAC__ASSERT(0 != decoder);
  94623. FLAC__ASSERT(0 != decoder->private_);
  94624. FLAC__ASSERT(0 != decoder->protected_);
  94625. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94626. return false;
  94627. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  94628. decoder->private_->metadata_filter[i] = true;
  94629. decoder->private_->metadata_filter_ids_count = 0;
  94630. return true;
  94631. }
  94632. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  94633. {
  94634. FLAC__ASSERT(0 != decoder);
  94635. FLAC__ASSERT(0 != decoder->private_);
  94636. FLAC__ASSERT(0 != decoder->protected_);
  94637. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  94638. /* double protection */
  94639. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  94640. return false;
  94641. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94642. return false;
  94643. decoder->private_->metadata_filter[type] = false;
  94644. if(type == FLAC__METADATA_TYPE_APPLICATION)
  94645. decoder->private_->metadata_filter_ids_count = 0;
  94646. return true;
  94647. }
  94648. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  94649. {
  94650. FLAC__ASSERT(0 != decoder);
  94651. FLAC__ASSERT(0 != decoder->private_);
  94652. FLAC__ASSERT(0 != decoder->protected_);
  94653. FLAC__ASSERT(0 != id);
  94654. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94655. return false;
  94656. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  94657. return true;
  94658. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  94659. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  94660. 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))) {
  94661. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94662. return false;
  94663. }
  94664. decoder->private_->metadata_filter_ids_capacity *= 2;
  94665. }
  94666. 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));
  94667. decoder->private_->metadata_filter_ids_count++;
  94668. return true;
  94669. }
  94670. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  94671. {
  94672. FLAC__ASSERT(0 != decoder);
  94673. FLAC__ASSERT(0 != decoder->private_);
  94674. FLAC__ASSERT(0 != decoder->protected_);
  94675. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94676. return false;
  94677. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  94678. decoder->private_->metadata_filter_ids_count = 0;
  94679. return true;
  94680. }
  94681. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  94682. {
  94683. FLAC__ASSERT(0 != decoder);
  94684. FLAC__ASSERT(0 != decoder->protected_);
  94685. return decoder->protected_->state;
  94686. }
  94687. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  94688. {
  94689. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  94690. }
  94691. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  94692. {
  94693. FLAC__ASSERT(0 != decoder);
  94694. FLAC__ASSERT(0 != decoder->protected_);
  94695. return decoder->protected_->md5_checking;
  94696. }
  94697. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  94698. {
  94699. FLAC__ASSERT(0 != decoder);
  94700. FLAC__ASSERT(0 != decoder->protected_);
  94701. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  94702. }
  94703. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  94704. {
  94705. FLAC__ASSERT(0 != decoder);
  94706. FLAC__ASSERT(0 != decoder->protected_);
  94707. return decoder->protected_->channels;
  94708. }
  94709. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  94710. {
  94711. FLAC__ASSERT(0 != decoder);
  94712. FLAC__ASSERT(0 != decoder->protected_);
  94713. return decoder->protected_->channel_assignment;
  94714. }
  94715. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  94716. {
  94717. FLAC__ASSERT(0 != decoder);
  94718. FLAC__ASSERT(0 != decoder->protected_);
  94719. return decoder->protected_->bits_per_sample;
  94720. }
  94721. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  94722. {
  94723. FLAC__ASSERT(0 != decoder);
  94724. FLAC__ASSERT(0 != decoder->protected_);
  94725. return decoder->protected_->sample_rate;
  94726. }
  94727. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  94728. {
  94729. FLAC__ASSERT(0 != decoder);
  94730. FLAC__ASSERT(0 != decoder->protected_);
  94731. return decoder->protected_->blocksize;
  94732. }
  94733. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  94734. {
  94735. FLAC__ASSERT(0 != decoder);
  94736. FLAC__ASSERT(0 != decoder->private_);
  94737. FLAC__ASSERT(0 != position);
  94738. #if FLAC__HAS_OGG
  94739. if(decoder->private_->is_ogg)
  94740. return false;
  94741. #endif
  94742. if(0 == decoder->private_->tell_callback)
  94743. return false;
  94744. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  94745. return false;
  94746. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  94747. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  94748. return false;
  94749. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  94750. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  94751. return true;
  94752. }
  94753. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  94754. {
  94755. FLAC__ASSERT(0 != decoder);
  94756. FLAC__ASSERT(0 != decoder->private_);
  94757. FLAC__ASSERT(0 != decoder->protected_);
  94758. decoder->private_->samples_decoded = 0;
  94759. decoder->private_->do_md5_checking = false;
  94760. #if FLAC__HAS_OGG
  94761. if(decoder->private_->is_ogg)
  94762. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  94763. #endif
  94764. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  94765. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94766. return false;
  94767. }
  94768. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94769. return true;
  94770. }
  94771. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  94772. {
  94773. FLAC__ASSERT(0 != decoder);
  94774. FLAC__ASSERT(0 != decoder->private_);
  94775. FLAC__ASSERT(0 != decoder->protected_);
  94776. if(!FLAC__stream_decoder_flush(decoder)) {
  94777. /* above call sets the state for us */
  94778. return false;
  94779. }
  94780. #if FLAC__HAS_OGG
  94781. /*@@@ could go in !internal_reset_hack block below */
  94782. if(decoder->private_->is_ogg)
  94783. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  94784. #endif
  94785. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  94786. * (internal_reset_hack) don't try to rewind since we are already at
  94787. * the beginning of the stream and don't want to fail if the input is
  94788. * not seekable.
  94789. */
  94790. if(!decoder->private_->internal_reset_hack) {
  94791. if(decoder->private_->file == stdin)
  94792. return false; /* can't rewind stdin, reset fails */
  94793. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  94794. return false; /* seekable and seek fails, reset fails */
  94795. }
  94796. else
  94797. decoder->private_->internal_reset_hack = false;
  94798. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  94799. decoder->private_->has_stream_info = false;
  94800. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  94801. free(decoder->private_->seek_table.data.seek_table.points);
  94802. decoder->private_->seek_table.data.seek_table.points = 0;
  94803. decoder->private_->has_seek_table = false;
  94804. }
  94805. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  94806. /*
  94807. * This goes in reset() and not flush() because according to the spec, a
  94808. * fixed-blocksize stream must stay that way through the whole stream.
  94809. */
  94810. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  94811. /* We initialize the FLAC__MD5Context even though we may never use it. This
  94812. * is because md5 checking may be turned on to start and then turned off if
  94813. * a seek occurs. So we init the context here and finalize it in
  94814. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  94815. * properly.
  94816. */
  94817. FLAC__MD5Init(&decoder->private_->md5context);
  94818. decoder->private_->first_frame_offset = 0;
  94819. decoder->private_->unparseable_frame_count = 0;
  94820. return true;
  94821. }
  94822. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  94823. {
  94824. FLAC__bool got_a_frame;
  94825. FLAC__ASSERT(0 != decoder);
  94826. FLAC__ASSERT(0 != decoder->protected_);
  94827. while(1) {
  94828. switch(decoder->protected_->state) {
  94829. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  94830. if(!find_metadata_(decoder))
  94831. return false; /* above function sets the status for us */
  94832. break;
  94833. case FLAC__STREAM_DECODER_READ_METADATA:
  94834. if(!read_metadata_(decoder))
  94835. return false; /* above function sets the status for us */
  94836. else
  94837. return true;
  94838. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  94839. if(!frame_sync_(decoder))
  94840. return true; /* above function sets the status for us */
  94841. break;
  94842. case FLAC__STREAM_DECODER_READ_FRAME:
  94843. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  94844. return false; /* above function sets the status for us */
  94845. if(got_a_frame)
  94846. return true; /* above function sets the status for us */
  94847. break;
  94848. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94849. case FLAC__STREAM_DECODER_ABORTED:
  94850. return true;
  94851. default:
  94852. FLAC__ASSERT(0);
  94853. return false;
  94854. }
  94855. }
  94856. }
  94857. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  94858. {
  94859. FLAC__ASSERT(0 != decoder);
  94860. FLAC__ASSERT(0 != decoder->protected_);
  94861. while(1) {
  94862. switch(decoder->protected_->state) {
  94863. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  94864. if(!find_metadata_(decoder))
  94865. return false; /* above function sets the status for us */
  94866. break;
  94867. case FLAC__STREAM_DECODER_READ_METADATA:
  94868. if(!read_metadata_(decoder))
  94869. return false; /* above function sets the status for us */
  94870. break;
  94871. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  94872. case FLAC__STREAM_DECODER_READ_FRAME:
  94873. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94874. case FLAC__STREAM_DECODER_ABORTED:
  94875. return true;
  94876. default:
  94877. FLAC__ASSERT(0);
  94878. return false;
  94879. }
  94880. }
  94881. }
  94882. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  94883. {
  94884. FLAC__bool dummy;
  94885. FLAC__ASSERT(0 != decoder);
  94886. FLAC__ASSERT(0 != decoder->protected_);
  94887. while(1) {
  94888. switch(decoder->protected_->state) {
  94889. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  94890. if(!find_metadata_(decoder))
  94891. return false; /* above function sets the status for us */
  94892. break;
  94893. case FLAC__STREAM_DECODER_READ_METADATA:
  94894. if(!read_metadata_(decoder))
  94895. return false; /* above function sets the status for us */
  94896. break;
  94897. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  94898. if(!frame_sync_(decoder))
  94899. return true; /* above function sets the status for us */
  94900. break;
  94901. case FLAC__STREAM_DECODER_READ_FRAME:
  94902. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  94903. return false; /* above function sets the status for us */
  94904. break;
  94905. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94906. case FLAC__STREAM_DECODER_ABORTED:
  94907. return true;
  94908. default:
  94909. FLAC__ASSERT(0);
  94910. return false;
  94911. }
  94912. }
  94913. }
  94914. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  94915. {
  94916. FLAC__bool got_a_frame;
  94917. FLAC__ASSERT(0 != decoder);
  94918. FLAC__ASSERT(0 != decoder->protected_);
  94919. while(1) {
  94920. switch(decoder->protected_->state) {
  94921. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  94922. case FLAC__STREAM_DECODER_READ_METADATA:
  94923. return false; /* above function sets the status for us */
  94924. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  94925. if(!frame_sync_(decoder))
  94926. return true; /* above function sets the status for us */
  94927. break;
  94928. case FLAC__STREAM_DECODER_READ_FRAME:
  94929. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  94930. return false; /* above function sets the status for us */
  94931. if(got_a_frame)
  94932. return true; /* above function sets the status for us */
  94933. break;
  94934. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94935. case FLAC__STREAM_DECODER_ABORTED:
  94936. return true;
  94937. default:
  94938. FLAC__ASSERT(0);
  94939. return false;
  94940. }
  94941. }
  94942. }
  94943. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  94944. {
  94945. FLAC__uint64 length;
  94946. FLAC__ASSERT(0 != decoder);
  94947. if(
  94948. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  94949. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  94950. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  94951. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  94952. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  94953. )
  94954. return false;
  94955. if(0 == decoder->private_->seek_callback)
  94956. return false;
  94957. FLAC__ASSERT(decoder->private_->seek_callback);
  94958. FLAC__ASSERT(decoder->private_->tell_callback);
  94959. FLAC__ASSERT(decoder->private_->length_callback);
  94960. FLAC__ASSERT(decoder->private_->eof_callback);
  94961. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  94962. return false;
  94963. decoder->private_->is_seeking = true;
  94964. /* turn off md5 checking if a seek is attempted */
  94965. decoder->private_->do_md5_checking = false;
  94966. /* 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) */
  94967. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  94968. decoder->private_->is_seeking = false;
  94969. return false;
  94970. }
  94971. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  94972. if(
  94973. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  94974. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  94975. ) {
  94976. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  94977. /* above call sets the state for us */
  94978. decoder->private_->is_seeking = false;
  94979. return false;
  94980. }
  94981. /* check this again in case we didn't know total_samples the first time */
  94982. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  94983. decoder->private_->is_seeking = false;
  94984. return false;
  94985. }
  94986. }
  94987. {
  94988. const FLAC__bool ok =
  94989. #if FLAC__HAS_OGG
  94990. decoder->private_->is_ogg?
  94991. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  94992. #endif
  94993. seek_to_absolute_sample_(decoder, length, sample)
  94994. ;
  94995. decoder->private_->is_seeking = false;
  94996. return ok;
  94997. }
  94998. }
  94999. /***********************************************************************
  95000. *
  95001. * Protected class methods
  95002. *
  95003. ***********************************************************************/
  95004. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  95005. {
  95006. FLAC__ASSERT(0 != decoder);
  95007. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95008. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  95009. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  95010. }
  95011. /***********************************************************************
  95012. *
  95013. * Private class methods
  95014. *
  95015. ***********************************************************************/
  95016. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  95017. {
  95018. #if FLAC__HAS_OGG
  95019. decoder->private_->is_ogg = false;
  95020. #endif
  95021. decoder->private_->read_callback = 0;
  95022. decoder->private_->seek_callback = 0;
  95023. decoder->private_->tell_callback = 0;
  95024. decoder->private_->length_callback = 0;
  95025. decoder->private_->eof_callback = 0;
  95026. decoder->private_->write_callback = 0;
  95027. decoder->private_->metadata_callback = 0;
  95028. decoder->private_->error_callback = 0;
  95029. decoder->private_->client_data = 0;
  95030. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  95031. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  95032. decoder->private_->metadata_filter_ids_count = 0;
  95033. decoder->protected_->md5_checking = false;
  95034. #if FLAC__HAS_OGG
  95035. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  95036. #endif
  95037. }
  95038. /*
  95039. * This will forcibly set stdin to binary mode (for OSes that require it)
  95040. */
  95041. FILE *get_binary_stdin_(void)
  95042. {
  95043. /* if something breaks here it is probably due to the presence or
  95044. * absence of an underscore before the identifiers 'setmode',
  95045. * 'fileno', and/or 'O_BINARY'; check your system header files.
  95046. */
  95047. #if defined _MSC_VER || defined __MINGW32__
  95048. _setmode(_fileno(stdin), _O_BINARY);
  95049. #elif defined __CYGWIN__
  95050. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  95051. setmode(_fileno(stdin), _O_BINARY);
  95052. #elif defined __EMX__
  95053. setmode(fileno(stdin), O_BINARY);
  95054. #endif
  95055. return stdin;
  95056. }
  95057. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  95058. {
  95059. unsigned i;
  95060. FLAC__int32 *tmp;
  95061. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  95062. return true;
  95063. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  95064. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95065. if(0 != decoder->private_->output[i]) {
  95066. free(decoder->private_->output[i]-4);
  95067. decoder->private_->output[i] = 0;
  95068. }
  95069. if(0 != decoder->private_->residual_unaligned[i]) {
  95070. free(decoder->private_->residual_unaligned[i]);
  95071. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95072. }
  95073. }
  95074. for(i = 0; i < channels; i++) {
  95075. /* WATCHOUT:
  95076. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  95077. * output arrays have a buffer of up to 3 zeroes in front
  95078. * (at negative indices) for alignment purposes; we use 4
  95079. * to keep the data well-aligned.
  95080. */
  95081. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  95082. if(tmp == 0) {
  95083. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95084. return false;
  95085. }
  95086. memset(tmp, 0, sizeof(FLAC__int32)*4);
  95087. decoder->private_->output[i] = tmp + 4;
  95088. /* WATCHOUT:
  95089. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  95090. */
  95091. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  95092. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95093. return false;
  95094. }
  95095. }
  95096. decoder->private_->output_capacity = size;
  95097. decoder->private_->output_channels = channels;
  95098. return true;
  95099. }
  95100. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  95101. {
  95102. size_t i;
  95103. FLAC__ASSERT(0 != decoder);
  95104. FLAC__ASSERT(0 != decoder->private_);
  95105. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  95106. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  95107. return true;
  95108. return false;
  95109. }
  95110. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  95111. {
  95112. FLAC__uint32 x;
  95113. unsigned i, id_;
  95114. FLAC__bool first = true;
  95115. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95116. for(i = id_ = 0; i < 4; ) {
  95117. if(decoder->private_->cached) {
  95118. x = (FLAC__uint32)decoder->private_->lookahead;
  95119. decoder->private_->cached = false;
  95120. }
  95121. else {
  95122. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95123. return false; /* read_callback_ sets the state for us */
  95124. }
  95125. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  95126. first = true;
  95127. i++;
  95128. id_ = 0;
  95129. continue;
  95130. }
  95131. if(x == ID3V2_TAG_[id_]) {
  95132. id_++;
  95133. i = 0;
  95134. if(id_ == 3) {
  95135. if(!skip_id3v2_tag_(decoder))
  95136. return false; /* skip_id3v2_tag_ sets the state for us */
  95137. }
  95138. continue;
  95139. }
  95140. id_ = 0;
  95141. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95142. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  95143. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95144. return false; /* read_callback_ sets the state for us */
  95145. /* 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 */
  95146. /* else we have to check if the second byte is the end of a sync code */
  95147. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95148. decoder->private_->lookahead = (FLAC__byte)x;
  95149. decoder->private_->cached = true;
  95150. }
  95151. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  95152. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  95153. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  95154. return true;
  95155. }
  95156. }
  95157. i = 0;
  95158. if(first) {
  95159. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95160. first = false;
  95161. }
  95162. }
  95163. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  95164. return true;
  95165. }
  95166. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  95167. {
  95168. FLAC__bool is_last;
  95169. FLAC__uint32 i, x, type, length;
  95170. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95171. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  95172. return false; /* read_callback_ sets the state for us */
  95173. is_last = x? true : false;
  95174. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  95175. return false; /* read_callback_ sets the state for us */
  95176. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  95177. return false; /* read_callback_ sets the state for us */
  95178. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  95179. if(!read_metadata_streaminfo_(decoder, is_last, length))
  95180. return false;
  95181. decoder->private_->has_stream_info = true;
  95182. 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))
  95183. decoder->private_->do_md5_checking = false;
  95184. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  95185. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  95186. }
  95187. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  95188. if(!read_metadata_seektable_(decoder, is_last, length))
  95189. return false;
  95190. decoder->private_->has_seek_table = true;
  95191. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  95192. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  95193. }
  95194. else {
  95195. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  95196. unsigned real_length = length;
  95197. FLAC__StreamMetadata block;
  95198. block.is_last = is_last;
  95199. block.type = (FLAC__MetadataType)type;
  95200. block.length = length;
  95201. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  95202. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  95203. return false; /* read_callback_ sets the state for us */
  95204. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  95205. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  95206. return false;
  95207. }
  95208. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  95209. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  95210. skip_it = !skip_it;
  95211. }
  95212. if(skip_it) {
  95213. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  95214. return false; /* read_callback_ sets the state for us */
  95215. }
  95216. else {
  95217. switch(type) {
  95218. case FLAC__METADATA_TYPE_PADDING:
  95219. /* skip the padding bytes */
  95220. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  95221. return false; /* read_callback_ sets the state for us */
  95222. break;
  95223. case FLAC__METADATA_TYPE_APPLICATION:
  95224. /* remember, we read the ID already */
  95225. if(real_length > 0) {
  95226. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  95227. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95228. return false;
  95229. }
  95230. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  95231. return false; /* read_callback_ sets the state for us */
  95232. }
  95233. else
  95234. block.data.application.data = 0;
  95235. break;
  95236. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  95237. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  95238. return false;
  95239. break;
  95240. case FLAC__METADATA_TYPE_CUESHEET:
  95241. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  95242. return false;
  95243. break;
  95244. case FLAC__METADATA_TYPE_PICTURE:
  95245. if(!read_metadata_picture_(decoder, &block.data.picture))
  95246. return false;
  95247. break;
  95248. case FLAC__METADATA_TYPE_STREAMINFO:
  95249. case FLAC__METADATA_TYPE_SEEKTABLE:
  95250. FLAC__ASSERT(0);
  95251. break;
  95252. default:
  95253. if(real_length > 0) {
  95254. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  95255. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95256. return false;
  95257. }
  95258. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  95259. return false; /* read_callback_ sets the state for us */
  95260. }
  95261. else
  95262. block.data.unknown.data = 0;
  95263. break;
  95264. }
  95265. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  95266. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  95267. /* now we have to free any malloc()ed data in the block */
  95268. switch(type) {
  95269. case FLAC__METADATA_TYPE_PADDING:
  95270. break;
  95271. case FLAC__METADATA_TYPE_APPLICATION:
  95272. if(0 != block.data.application.data)
  95273. free(block.data.application.data);
  95274. break;
  95275. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  95276. if(0 != block.data.vorbis_comment.vendor_string.entry)
  95277. free(block.data.vorbis_comment.vendor_string.entry);
  95278. if(block.data.vorbis_comment.num_comments > 0)
  95279. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  95280. if(0 != block.data.vorbis_comment.comments[i].entry)
  95281. free(block.data.vorbis_comment.comments[i].entry);
  95282. if(0 != block.data.vorbis_comment.comments)
  95283. free(block.data.vorbis_comment.comments);
  95284. break;
  95285. case FLAC__METADATA_TYPE_CUESHEET:
  95286. if(block.data.cue_sheet.num_tracks > 0)
  95287. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  95288. if(0 != block.data.cue_sheet.tracks[i].indices)
  95289. free(block.data.cue_sheet.tracks[i].indices);
  95290. if(0 != block.data.cue_sheet.tracks)
  95291. free(block.data.cue_sheet.tracks);
  95292. break;
  95293. case FLAC__METADATA_TYPE_PICTURE:
  95294. if(0 != block.data.picture.mime_type)
  95295. free(block.data.picture.mime_type);
  95296. if(0 != block.data.picture.description)
  95297. free(block.data.picture.description);
  95298. if(0 != block.data.picture.data)
  95299. free(block.data.picture.data);
  95300. break;
  95301. case FLAC__METADATA_TYPE_STREAMINFO:
  95302. case FLAC__METADATA_TYPE_SEEKTABLE:
  95303. FLAC__ASSERT(0);
  95304. default:
  95305. if(0 != block.data.unknown.data)
  95306. free(block.data.unknown.data);
  95307. break;
  95308. }
  95309. }
  95310. }
  95311. if(is_last) {
  95312. /* if this fails, it's OK, it's just a hint for the seek routine */
  95313. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  95314. decoder->private_->first_frame_offset = 0;
  95315. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95316. }
  95317. return true;
  95318. }
  95319. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  95320. {
  95321. FLAC__uint32 x;
  95322. unsigned bits, used_bits = 0;
  95323. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95324. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  95325. decoder->private_->stream_info.is_last = is_last;
  95326. decoder->private_->stream_info.length = length;
  95327. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  95328. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  95329. return false; /* read_callback_ sets the state for us */
  95330. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  95331. used_bits += bits;
  95332. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  95333. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  95334. return false; /* read_callback_ sets the state for us */
  95335. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  95336. used_bits += bits;
  95337. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  95338. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  95339. return false; /* read_callback_ sets the state for us */
  95340. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  95341. used_bits += bits;
  95342. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  95343. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  95344. return false; /* read_callback_ sets the state for us */
  95345. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  95346. used_bits += bits;
  95347. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  95348. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  95349. return false; /* read_callback_ sets the state for us */
  95350. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  95351. used_bits += bits;
  95352. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  95353. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  95354. return false; /* read_callback_ sets the state for us */
  95355. decoder->private_->stream_info.data.stream_info.channels = x+1;
  95356. used_bits += bits;
  95357. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  95358. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  95359. return false; /* read_callback_ sets the state for us */
  95360. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  95361. used_bits += bits;
  95362. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  95363. 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))
  95364. return false; /* read_callback_ sets the state for us */
  95365. used_bits += bits;
  95366. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  95367. return false; /* read_callback_ sets the state for us */
  95368. used_bits += 16*8;
  95369. /* skip the rest of the block */
  95370. FLAC__ASSERT(used_bits % 8 == 0);
  95371. length -= (used_bits / 8);
  95372. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  95373. return false; /* read_callback_ sets the state for us */
  95374. return true;
  95375. }
  95376. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  95377. {
  95378. FLAC__uint32 i, x;
  95379. FLAC__uint64 xx;
  95380. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95381. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  95382. decoder->private_->seek_table.is_last = is_last;
  95383. decoder->private_->seek_table.length = length;
  95384. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  95385. /* use realloc since we may pass through here several times (e.g. after seeking) */
  95386. 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)))) {
  95387. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95388. return false;
  95389. }
  95390. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  95391. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  95392. return false; /* read_callback_ sets the state for us */
  95393. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  95394. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  95395. return false; /* read_callback_ sets the state for us */
  95396. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  95397. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  95398. return false; /* read_callback_ sets the state for us */
  95399. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  95400. }
  95401. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  95402. /* if there is a partial point left, skip over it */
  95403. if(length > 0) {
  95404. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  95405. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  95406. return false; /* read_callback_ sets the state for us */
  95407. }
  95408. return true;
  95409. }
  95410. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  95411. {
  95412. FLAC__uint32 i;
  95413. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95414. /* read vendor string */
  95415. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  95416. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  95417. return false; /* read_callback_ sets the state for us */
  95418. if(obj->vendor_string.length > 0) {
  95419. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  95420. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95421. return false;
  95422. }
  95423. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  95424. return false; /* read_callback_ sets the state for us */
  95425. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  95426. }
  95427. else
  95428. obj->vendor_string.entry = 0;
  95429. /* read num comments */
  95430. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  95431. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  95432. return false; /* read_callback_ sets the state for us */
  95433. /* read comments */
  95434. if(obj->num_comments > 0) {
  95435. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  95436. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95437. return false;
  95438. }
  95439. for(i = 0; i < obj->num_comments; i++) {
  95440. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  95441. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  95442. return false; /* read_callback_ sets the state for us */
  95443. if(obj->comments[i].length > 0) {
  95444. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  95445. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95446. return false;
  95447. }
  95448. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  95449. return false; /* read_callback_ sets the state for us */
  95450. obj->comments[i].entry[obj->comments[i].length] = '\0';
  95451. }
  95452. else
  95453. obj->comments[i].entry = 0;
  95454. }
  95455. }
  95456. else {
  95457. obj->comments = 0;
  95458. }
  95459. return true;
  95460. }
  95461. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  95462. {
  95463. FLAC__uint32 i, j, x;
  95464. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95465. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  95466. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  95467. 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))
  95468. return false; /* read_callback_ sets the state for us */
  95469. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  95470. return false; /* read_callback_ sets the state for us */
  95471. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  95472. return false; /* read_callback_ sets the state for us */
  95473. obj->is_cd = x? true : false;
  95474. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  95475. return false; /* read_callback_ sets the state for us */
  95476. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  95477. return false; /* read_callback_ sets the state for us */
  95478. obj->num_tracks = x;
  95479. if(obj->num_tracks > 0) {
  95480. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  95481. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95482. return false;
  95483. }
  95484. for(i = 0; i < obj->num_tracks; i++) {
  95485. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  95486. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  95487. return false; /* read_callback_ sets the state for us */
  95488. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  95489. return false; /* read_callback_ sets the state for us */
  95490. track->number = (FLAC__byte)x;
  95491. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  95492. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  95493. return false; /* read_callback_ sets the state for us */
  95494. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  95495. return false; /* read_callback_ sets the state for us */
  95496. track->type = x;
  95497. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  95498. return false; /* read_callback_ sets the state for us */
  95499. track->pre_emphasis = x;
  95500. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  95501. return false; /* read_callback_ sets the state for us */
  95502. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  95503. return false; /* read_callback_ sets the state for us */
  95504. track->num_indices = (FLAC__byte)x;
  95505. if(track->num_indices > 0) {
  95506. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  95507. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95508. return false;
  95509. }
  95510. for(j = 0; j < track->num_indices; j++) {
  95511. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  95512. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  95513. return false; /* read_callback_ sets the state for us */
  95514. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  95515. return false; /* read_callback_ sets the state for us */
  95516. index->number = (FLAC__byte)x;
  95517. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  95518. return false; /* read_callback_ sets the state for us */
  95519. }
  95520. }
  95521. }
  95522. }
  95523. return true;
  95524. }
  95525. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  95526. {
  95527. FLAC__uint32 x;
  95528. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95529. /* read type */
  95530. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  95531. return false; /* read_callback_ sets the state for us */
  95532. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  95533. /* read MIME type */
  95534. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  95535. return false; /* read_callback_ sets the state for us */
  95536. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  95537. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95538. return false;
  95539. }
  95540. if(x > 0) {
  95541. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  95542. return false; /* read_callback_ sets the state for us */
  95543. }
  95544. obj->mime_type[x] = '\0';
  95545. /* read description */
  95546. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  95547. return false; /* read_callback_ sets the state for us */
  95548. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  95549. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95550. return false;
  95551. }
  95552. if(x > 0) {
  95553. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  95554. return false; /* read_callback_ sets the state for us */
  95555. }
  95556. obj->description[x] = '\0';
  95557. /* read width */
  95558. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  95559. return false; /* read_callback_ sets the state for us */
  95560. /* read height */
  95561. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  95562. return false; /* read_callback_ sets the state for us */
  95563. /* read depth */
  95564. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  95565. return false; /* read_callback_ sets the state for us */
  95566. /* read colors */
  95567. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  95568. return false; /* read_callback_ sets the state for us */
  95569. /* read data */
  95570. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  95571. return false; /* read_callback_ sets the state for us */
  95572. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  95573. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95574. return false;
  95575. }
  95576. if(obj->data_length > 0) {
  95577. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  95578. return false; /* read_callback_ sets the state for us */
  95579. }
  95580. return true;
  95581. }
  95582. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  95583. {
  95584. FLAC__uint32 x;
  95585. unsigned i, skip;
  95586. /* skip the version and flags bytes */
  95587. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  95588. return false; /* read_callback_ sets the state for us */
  95589. /* get the size (in bytes) to skip */
  95590. skip = 0;
  95591. for(i = 0; i < 4; i++) {
  95592. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95593. return false; /* read_callback_ sets the state for us */
  95594. skip <<= 7;
  95595. skip |= (x & 0x7f);
  95596. }
  95597. /* skip the rest of the tag */
  95598. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  95599. return false; /* read_callback_ sets the state for us */
  95600. return true;
  95601. }
  95602. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  95603. {
  95604. FLAC__uint32 x;
  95605. FLAC__bool first = true;
  95606. /* If we know the total number of samples in the stream, stop if we've read that many. */
  95607. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  95608. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  95609. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  95610. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  95611. return true;
  95612. }
  95613. }
  95614. /* make sure we're byte aligned */
  95615. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  95616. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  95617. return false; /* read_callback_ sets the state for us */
  95618. }
  95619. while(1) {
  95620. if(decoder->private_->cached) {
  95621. x = (FLAC__uint32)decoder->private_->lookahead;
  95622. decoder->private_->cached = false;
  95623. }
  95624. else {
  95625. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95626. return false; /* read_callback_ sets the state for us */
  95627. }
  95628. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95629. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  95630. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95631. return false; /* read_callback_ sets the state for us */
  95632. /* 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 */
  95633. /* else we have to check if the second byte is the end of a sync code */
  95634. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95635. decoder->private_->lookahead = (FLAC__byte)x;
  95636. decoder->private_->cached = true;
  95637. }
  95638. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  95639. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  95640. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  95641. return true;
  95642. }
  95643. }
  95644. if(first) {
  95645. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95646. first = false;
  95647. }
  95648. }
  95649. return true;
  95650. }
  95651. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  95652. {
  95653. unsigned channel;
  95654. unsigned i;
  95655. FLAC__int32 mid, side;
  95656. unsigned frame_crc; /* the one we calculate from the input stream */
  95657. FLAC__uint32 x;
  95658. *got_a_frame = false;
  95659. /* init the CRC */
  95660. frame_crc = 0;
  95661. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  95662. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  95663. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  95664. if(!read_frame_header_(decoder))
  95665. return false;
  95666. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  95667. return true;
  95668. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  95669. return false;
  95670. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  95671. /*
  95672. * first figure the correct bits-per-sample of the subframe
  95673. */
  95674. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  95675. switch(decoder->private_->frame.header.channel_assignment) {
  95676. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  95677. /* no adjustment needed */
  95678. break;
  95679. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  95680. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  95681. if(channel == 1)
  95682. bps++;
  95683. break;
  95684. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  95685. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  95686. if(channel == 0)
  95687. bps++;
  95688. break;
  95689. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  95690. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  95691. if(channel == 1)
  95692. bps++;
  95693. break;
  95694. default:
  95695. FLAC__ASSERT(0);
  95696. }
  95697. /*
  95698. * now read it
  95699. */
  95700. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  95701. return false;
  95702. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  95703. return true;
  95704. }
  95705. if(!read_zero_padding_(decoder))
  95706. return false;
  95707. 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) */
  95708. return true;
  95709. /*
  95710. * Read the frame CRC-16 from the footer and check
  95711. */
  95712. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  95713. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  95714. return false; /* read_callback_ sets the state for us */
  95715. if(frame_crc == x) {
  95716. if(do_full_decode) {
  95717. /* Undo any special channel coding */
  95718. switch(decoder->private_->frame.header.channel_assignment) {
  95719. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  95720. /* do nothing */
  95721. break;
  95722. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  95723. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  95724. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  95725. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  95726. break;
  95727. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  95728. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  95729. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  95730. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  95731. break;
  95732. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  95733. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  95734. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  95735. #if 1
  95736. mid = decoder->private_->output[0][i];
  95737. side = decoder->private_->output[1][i];
  95738. mid <<= 1;
  95739. mid |= (side & 1); /* i.e. if 'side' is odd... */
  95740. decoder->private_->output[0][i] = (mid + side) >> 1;
  95741. decoder->private_->output[1][i] = (mid - side) >> 1;
  95742. #else
  95743. /* OPT: without 'side' temp variable */
  95744. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  95745. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  95746. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  95747. #endif
  95748. }
  95749. break;
  95750. default:
  95751. FLAC__ASSERT(0);
  95752. break;
  95753. }
  95754. }
  95755. }
  95756. else {
  95757. /* Bad frame, emit error and zero the output signal */
  95758. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  95759. if(do_full_decode) {
  95760. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  95761. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  95762. }
  95763. }
  95764. }
  95765. *got_a_frame = true;
  95766. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  95767. if(decoder->private_->next_fixed_block_size)
  95768. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  95769. /* put the latest values into the public section of the decoder instance */
  95770. decoder->protected_->channels = decoder->private_->frame.header.channels;
  95771. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  95772. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  95773. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  95774. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  95775. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  95776. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  95777. /* write it */
  95778. if(do_full_decode) {
  95779. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  95780. return false;
  95781. }
  95782. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95783. return true;
  95784. }
  95785. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  95786. {
  95787. FLAC__uint32 x;
  95788. FLAC__uint64 xx;
  95789. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  95790. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  95791. unsigned raw_header_len;
  95792. FLAC__bool is_unparseable = false;
  95793. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95794. /* init the raw header with the saved bits from synchronization */
  95795. raw_header[0] = decoder->private_->header_warmup[0];
  95796. raw_header[1] = decoder->private_->header_warmup[1];
  95797. raw_header_len = 2;
  95798. /* check to make sure that reserved bit is 0 */
  95799. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  95800. is_unparseable = true;
  95801. /*
  95802. * Note that along the way as we read the header, we look for a sync
  95803. * code inside. If we find one it would indicate that our original
  95804. * sync was bad since there cannot be a sync code in a valid header.
  95805. *
  95806. * Three kinds of things can go wrong when reading the frame header:
  95807. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  95808. * If we don't find a sync code, it can end up looking like we read
  95809. * a valid but unparseable header, until getting to the frame header
  95810. * CRC. Even then we could get a false positive on the CRC.
  95811. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  95812. * future encoder).
  95813. * 3) We may be on a damaged frame which appears valid but unparseable.
  95814. *
  95815. * For all these reasons, we try and read a complete frame header as
  95816. * long as it seems valid, even if unparseable, up until the frame
  95817. * header CRC.
  95818. */
  95819. /*
  95820. * read in the raw header as bytes so we can CRC it, and parse it on the way
  95821. */
  95822. for(i = 0; i < 2; i++) {
  95823. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95824. return false; /* read_callback_ sets the state for us */
  95825. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95826. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  95827. decoder->private_->lookahead = (FLAC__byte)x;
  95828. decoder->private_->cached = true;
  95829. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95830. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95831. return true;
  95832. }
  95833. raw_header[raw_header_len++] = (FLAC__byte)x;
  95834. }
  95835. switch(x = raw_header[2] >> 4) {
  95836. case 0:
  95837. is_unparseable = true;
  95838. break;
  95839. case 1:
  95840. decoder->private_->frame.header.blocksize = 192;
  95841. break;
  95842. case 2:
  95843. case 3:
  95844. case 4:
  95845. case 5:
  95846. decoder->private_->frame.header.blocksize = 576 << (x-2);
  95847. break;
  95848. case 6:
  95849. case 7:
  95850. blocksize_hint = x;
  95851. break;
  95852. case 8:
  95853. case 9:
  95854. case 10:
  95855. case 11:
  95856. case 12:
  95857. case 13:
  95858. case 14:
  95859. case 15:
  95860. decoder->private_->frame.header.blocksize = 256 << (x-8);
  95861. break;
  95862. default:
  95863. FLAC__ASSERT(0);
  95864. break;
  95865. }
  95866. switch(x = raw_header[2] & 0x0f) {
  95867. case 0:
  95868. if(decoder->private_->has_stream_info)
  95869. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  95870. else
  95871. is_unparseable = true;
  95872. break;
  95873. case 1:
  95874. decoder->private_->frame.header.sample_rate = 88200;
  95875. break;
  95876. case 2:
  95877. decoder->private_->frame.header.sample_rate = 176400;
  95878. break;
  95879. case 3:
  95880. decoder->private_->frame.header.sample_rate = 192000;
  95881. break;
  95882. case 4:
  95883. decoder->private_->frame.header.sample_rate = 8000;
  95884. break;
  95885. case 5:
  95886. decoder->private_->frame.header.sample_rate = 16000;
  95887. break;
  95888. case 6:
  95889. decoder->private_->frame.header.sample_rate = 22050;
  95890. break;
  95891. case 7:
  95892. decoder->private_->frame.header.sample_rate = 24000;
  95893. break;
  95894. case 8:
  95895. decoder->private_->frame.header.sample_rate = 32000;
  95896. break;
  95897. case 9:
  95898. decoder->private_->frame.header.sample_rate = 44100;
  95899. break;
  95900. case 10:
  95901. decoder->private_->frame.header.sample_rate = 48000;
  95902. break;
  95903. case 11:
  95904. decoder->private_->frame.header.sample_rate = 96000;
  95905. break;
  95906. case 12:
  95907. case 13:
  95908. case 14:
  95909. sample_rate_hint = x;
  95910. break;
  95911. case 15:
  95912. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95913. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95914. return true;
  95915. default:
  95916. FLAC__ASSERT(0);
  95917. }
  95918. x = (unsigned)(raw_header[3] >> 4);
  95919. if(x & 8) {
  95920. decoder->private_->frame.header.channels = 2;
  95921. switch(x & 7) {
  95922. case 0:
  95923. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  95924. break;
  95925. case 1:
  95926. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  95927. break;
  95928. case 2:
  95929. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  95930. break;
  95931. default:
  95932. is_unparseable = true;
  95933. break;
  95934. }
  95935. }
  95936. else {
  95937. decoder->private_->frame.header.channels = (unsigned)x + 1;
  95938. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  95939. }
  95940. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  95941. case 0:
  95942. if(decoder->private_->has_stream_info)
  95943. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  95944. else
  95945. is_unparseable = true;
  95946. break;
  95947. case 1:
  95948. decoder->private_->frame.header.bits_per_sample = 8;
  95949. break;
  95950. case 2:
  95951. decoder->private_->frame.header.bits_per_sample = 12;
  95952. break;
  95953. case 4:
  95954. decoder->private_->frame.header.bits_per_sample = 16;
  95955. break;
  95956. case 5:
  95957. decoder->private_->frame.header.bits_per_sample = 20;
  95958. break;
  95959. case 6:
  95960. decoder->private_->frame.header.bits_per_sample = 24;
  95961. break;
  95962. case 3:
  95963. case 7:
  95964. is_unparseable = true;
  95965. break;
  95966. default:
  95967. FLAC__ASSERT(0);
  95968. break;
  95969. }
  95970. /* check to make sure that reserved bit is 0 */
  95971. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  95972. is_unparseable = true;
  95973. /* read the frame's starting sample number (or frame number as the case may be) */
  95974. if(
  95975. raw_header[1] & 0x01 ||
  95976. /*@@@ 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 */
  95977. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  95978. ) { /* variable blocksize */
  95979. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  95980. return false; /* read_callback_ sets the state for us */
  95981. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  95982. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  95983. decoder->private_->cached = true;
  95984. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95985. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95986. return true;
  95987. }
  95988. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  95989. decoder->private_->frame.header.number.sample_number = xx;
  95990. }
  95991. else { /* fixed blocksize */
  95992. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  95993. return false; /* read_callback_ sets the state for us */
  95994. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  95995. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  95996. decoder->private_->cached = true;
  95997. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95998. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95999. return true;
  96000. }
  96001. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  96002. decoder->private_->frame.header.number.frame_number = x;
  96003. }
  96004. if(blocksize_hint) {
  96005. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96006. return false; /* read_callback_ sets the state for us */
  96007. raw_header[raw_header_len++] = (FLAC__byte)x;
  96008. if(blocksize_hint == 7) {
  96009. FLAC__uint32 _x;
  96010. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  96011. return false; /* read_callback_ sets the state for us */
  96012. raw_header[raw_header_len++] = (FLAC__byte)_x;
  96013. x = (x << 8) | _x;
  96014. }
  96015. decoder->private_->frame.header.blocksize = x+1;
  96016. }
  96017. if(sample_rate_hint) {
  96018. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96019. return false; /* read_callback_ sets the state for us */
  96020. raw_header[raw_header_len++] = (FLAC__byte)x;
  96021. if(sample_rate_hint != 12) {
  96022. FLAC__uint32 _x;
  96023. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  96024. return false; /* read_callback_ sets the state for us */
  96025. raw_header[raw_header_len++] = (FLAC__byte)_x;
  96026. x = (x << 8) | _x;
  96027. }
  96028. if(sample_rate_hint == 12)
  96029. decoder->private_->frame.header.sample_rate = x*1000;
  96030. else if(sample_rate_hint == 13)
  96031. decoder->private_->frame.header.sample_rate = x;
  96032. else
  96033. decoder->private_->frame.header.sample_rate = x*10;
  96034. }
  96035. /* read the CRC-8 byte */
  96036. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96037. return false; /* read_callback_ sets the state for us */
  96038. crc8 = (FLAC__byte)x;
  96039. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  96040. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96041. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96042. return true;
  96043. }
  96044. /* calculate the sample number from the frame number if needed */
  96045. decoder->private_->next_fixed_block_size = 0;
  96046. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  96047. x = decoder->private_->frame.header.number.frame_number;
  96048. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  96049. if(decoder->private_->fixed_block_size)
  96050. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  96051. else if(decoder->private_->has_stream_info) {
  96052. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  96053. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  96054. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  96055. }
  96056. else
  96057. is_unparseable = true;
  96058. }
  96059. else if(x == 0) {
  96060. decoder->private_->frame.header.number.sample_number = 0;
  96061. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  96062. }
  96063. else {
  96064. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  96065. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  96066. }
  96067. }
  96068. if(is_unparseable) {
  96069. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96070. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96071. return true;
  96072. }
  96073. return true;
  96074. }
  96075. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96076. {
  96077. FLAC__uint32 x;
  96078. FLAC__bool wasted_bits;
  96079. unsigned i;
  96080. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  96081. return false; /* read_callback_ sets the state for us */
  96082. wasted_bits = (x & 1);
  96083. x &= 0xfe;
  96084. if(wasted_bits) {
  96085. unsigned u;
  96086. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  96087. return false; /* read_callback_ sets the state for us */
  96088. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  96089. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  96090. }
  96091. else
  96092. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  96093. /*
  96094. * Lots of magic numbers here
  96095. */
  96096. if(x & 0x80) {
  96097. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96098. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96099. return true;
  96100. }
  96101. else if(x == 0) {
  96102. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  96103. return false;
  96104. }
  96105. else if(x == 2) {
  96106. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  96107. return false;
  96108. }
  96109. else if(x < 16) {
  96110. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96111. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96112. return true;
  96113. }
  96114. else if(x <= 24) {
  96115. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  96116. return false;
  96117. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96118. return true;
  96119. }
  96120. else if(x < 64) {
  96121. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96122. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96123. return true;
  96124. }
  96125. else {
  96126. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  96127. return false;
  96128. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96129. return true;
  96130. }
  96131. if(wasted_bits && do_full_decode) {
  96132. x = decoder->private_->frame.subframes[channel].wasted_bits;
  96133. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96134. decoder->private_->output[channel][i] <<= x;
  96135. }
  96136. return true;
  96137. }
  96138. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96139. {
  96140. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  96141. FLAC__int32 x;
  96142. unsigned i;
  96143. FLAC__int32 *output = decoder->private_->output[channel];
  96144. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  96145. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  96146. return false; /* read_callback_ sets the state for us */
  96147. subframe->value = x;
  96148. /* decode the subframe */
  96149. if(do_full_decode) {
  96150. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96151. output[i] = x;
  96152. }
  96153. return true;
  96154. }
  96155. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  96156. {
  96157. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  96158. FLAC__int32 i32;
  96159. FLAC__uint32 u32;
  96160. unsigned u;
  96161. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  96162. subframe->residual = decoder->private_->residual[channel];
  96163. subframe->order = order;
  96164. /* read warm-up samples */
  96165. for(u = 0; u < order; u++) {
  96166. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  96167. return false; /* read_callback_ sets the state for us */
  96168. subframe->warmup[u] = i32;
  96169. }
  96170. /* read entropy coding method info */
  96171. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  96172. return false; /* read_callback_ sets the state for us */
  96173. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  96174. switch(subframe->entropy_coding_method.type) {
  96175. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96176. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96177. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  96178. return false; /* read_callback_ sets the state for us */
  96179. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  96180. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  96181. break;
  96182. default:
  96183. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96184. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96185. return true;
  96186. }
  96187. /* read residual */
  96188. switch(subframe->entropy_coding_method.type) {
  96189. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96190. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96191. 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))
  96192. return false;
  96193. break;
  96194. default:
  96195. FLAC__ASSERT(0);
  96196. }
  96197. /* decode the subframe */
  96198. if(do_full_decode) {
  96199. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  96200. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  96201. }
  96202. return true;
  96203. }
  96204. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  96205. {
  96206. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  96207. FLAC__int32 i32;
  96208. FLAC__uint32 u32;
  96209. unsigned u;
  96210. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  96211. subframe->residual = decoder->private_->residual[channel];
  96212. subframe->order = order;
  96213. /* read warm-up samples */
  96214. for(u = 0; u < order; u++) {
  96215. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  96216. return false; /* read_callback_ sets the state for us */
  96217. subframe->warmup[u] = i32;
  96218. }
  96219. /* read qlp coeff precision */
  96220. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  96221. return false; /* read_callback_ sets the state for us */
  96222. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  96223. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96224. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96225. return true;
  96226. }
  96227. subframe->qlp_coeff_precision = u32+1;
  96228. /* read qlp shift */
  96229. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  96230. return false; /* read_callback_ sets the state for us */
  96231. subframe->quantization_level = i32;
  96232. /* read quantized lp coefficiencts */
  96233. for(u = 0; u < order; u++) {
  96234. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  96235. return false; /* read_callback_ sets the state for us */
  96236. subframe->qlp_coeff[u] = i32;
  96237. }
  96238. /* read entropy coding method info */
  96239. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  96240. return false; /* read_callback_ sets the state for us */
  96241. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  96242. switch(subframe->entropy_coding_method.type) {
  96243. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96244. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96245. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  96246. return false; /* read_callback_ sets the state for us */
  96247. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  96248. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  96249. break;
  96250. default:
  96251. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96252. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96253. return true;
  96254. }
  96255. /* read residual */
  96256. switch(subframe->entropy_coding_method.type) {
  96257. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96258. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96259. 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))
  96260. return false;
  96261. break;
  96262. default:
  96263. FLAC__ASSERT(0);
  96264. }
  96265. /* decode the subframe */
  96266. if(do_full_decode) {
  96267. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  96268. /*@@@@@@ technically not pessimistic enough, should be more like
  96269. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  96270. */
  96271. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  96272. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  96273. if(order <= 8)
  96274. 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);
  96275. else
  96276. 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);
  96277. }
  96278. else
  96279. 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);
  96280. else
  96281. 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);
  96282. }
  96283. return true;
  96284. }
  96285. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96286. {
  96287. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  96288. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  96289. unsigned i;
  96290. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  96291. subframe->data = residual;
  96292. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  96293. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  96294. return false; /* read_callback_ sets the state for us */
  96295. residual[i] = x;
  96296. }
  96297. /* decode the subframe */
  96298. if(do_full_decode)
  96299. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  96300. return true;
  96301. }
  96302. 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)
  96303. {
  96304. FLAC__uint32 rice_parameter;
  96305. int i;
  96306. unsigned partition, sample, u;
  96307. const unsigned partitions = 1u << partition_order;
  96308. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  96309. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  96310. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  96311. /* sanity checks */
  96312. if(partition_order == 0) {
  96313. if(decoder->private_->frame.header.blocksize < predictor_order) {
  96314. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96315. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96316. return true;
  96317. }
  96318. }
  96319. else {
  96320. if(partition_samples < predictor_order) {
  96321. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96322. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96323. return true;
  96324. }
  96325. }
  96326. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  96327. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96328. return false;
  96329. }
  96330. sample = 0;
  96331. for(partition = 0; partition < partitions; partition++) {
  96332. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  96333. return false; /* read_callback_ sets the state for us */
  96334. partitioned_rice_contents->parameters[partition] = rice_parameter;
  96335. if(rice_parameter < pesc) {
  96336. partitioned_rice_contents->raw_bits[partition] = 0;
  96337. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  96338. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  96339. return false; /* read_callback_ sets the state for us */
  96340. sample += u;
  96341. }
  96342. else {
  96343. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  96344. return false; /* read_callback_ sets the state for us */
  96345. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  96346. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  96347. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  96348. return false; /* read_callback_ sets the state for us */
  96349. residual[sample] = i;
  96350. }
  96351. }
  96352. }
  96353. return true;
  96354. }
  96355. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  96356. {
  96357. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  96358. FLAC__uint32 zero = 0;
  96359. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  96360. return false; /* read_callback_ sets the state for us */
  96361. if(zero != 0) {
  96362. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96363. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96364. }
  96365. }
  96366. return true;
  96367. }
  96368. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  96369. {
  96370. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  96371. if(
  96372. #if FLAC__HAS_OGG
  96373. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  96374. !decoder->private_->is_ogg &&
  96375. #endif
  96376. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  96377. ) {
  96378. *bytes = 0;
  96379. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  96380. return false;
  96381. }
  96382. else if(*bytes > 0) {
  96383. /* While seeking, it is possible for our seek to land in the
  96384. * middle of audio data that looks exactly like a frame header
  96385. * from a future version of an encoder. When that happens, our
  96386. * error callback will get an
  96387. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  96388. * unparseable_frame_count. But there is a remote possibility
  96389. * that it is properly synced at such a "future-codec frame",
  96390. * so to make sure, we wait to see many "unparseable" errors in
  96391. * a row before bailing out.
  96392. */
  96393. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  96394. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  96395. return false;
  96396. }
  96397. else {
  96398. const FLAC__StreamDecoderReadStatus status =
  96399. #if FLAC__HAS_OGG
  96400. decoder->private_->is_ogg?
  96401. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  96402. #endif
  96403. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  96404. ;
  96405. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  96406. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  96407. return false;
  96408. }
  96409. else if(*bytes == 0) {
  96410. if(
  96411. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  96412. (
  96413. #if FLAC__HAS_OGG
  96414. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  96415. !decoder->private_->is_ogg &&
  96416. #endif
  96417. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  96418. )
  96419. ) {
  96420. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  96421. return false;
  96422. }
  96423. else
  96424. return true;
  96425. }
  96426. else
  96427. return true;
  96428. }
  96429. }
  96430. else {
  96431. /* abort to avoid a deadlock */
  96432. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  96433. return false;
  96434. }
  96435. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  96436. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  96437. * and at the same time hit the end of the stream (for example, seeking
  96438. * to a point that is after the beginning of the last Ogg page). There
  96439. * is no way to report an Ogg sync loss through the callbacks (see note
  96440. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  96441. * So to keep the decoder from stopping at this point we gate the call
  96442. * to the eof_callback and let the Ogg decoder aspect set the
  96443. * end-of-stream state when it is needed.
  96444. */
  96445. }
  96446. #if FLAC__HAS_OGG
  96447. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  96448. {
  96449. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  96450. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  96451. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  96452. /* we don't really have a way to handle lost sync via read
  96453. * callback so we'll let it pass and let the underlying
  96454. * FLAC decoder catch the error
  96455. */
  96456. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  96457. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  96458. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  96459. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  96460. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  96461. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  96462. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  96463. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  96464. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  96465. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  96466. default:
  96467. FLAC__ASSERT(0);
  96468. /* double protection */
  96469. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  96470. }
  96471. }
  96472. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  96473. {
  96474. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  96475. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  96476. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  96477. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  96478. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  96479. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  96480. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  96481. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  96482. default:
  96483. /* double protection: */
  96484. FLAC__ASSERT(0);
  96485. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  96486. }
  96487. }
  96488. #endif
  96489. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  96490. {
  96491. if(decoder->private_->is_seeking) {
  96492. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  96493. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  96494. FLAC__uint64 target_sample = decoder->private_->target_sample;
  96495. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  96496. #if FLAC__HAS_OGG
  96497. decoder->private_->got_a_frame = true;
  96498. #endif
  96499. decoder->private_->last_frame = *frame; /* save the frame */
  96500. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  96501. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  96502. /* kick out of seek mode */
  96503. decoder->private_->is_seeking = false;
  96504. /* shift out the samples before target_sample */
  96505. if(delta > 0) {
  96506. unsigned channel;
  96507. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  96508. for(channel = 0; channel < frame->header.channels; channel++)
  96509. newbuffer[channel] = buffer[channel] + delta;
  96510. decoder->private_->last_frame.header.blocksize -= delta;
  96511. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  96512. /* write the relevant samples */
  96513. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  96514. }
  96515. else {
  96516. /* write the relevant samples */
  96517. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  96518. }
  96519. }
  96520. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  96521. }
  96522. /*
  96523. * If we never got STREAMINFO, turn off MD5 checking to save
  96524. * cycles since we don't have a sum to compare to anyway
  96525. */
  96526. if(!decoder->private_->has_stream_info)
  96527. decoder->private_->do_md5_checking = false;
  96528. if(decoder->private_->do_md5_checking) {
  96529. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  96530. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  96531. }
  96532. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  96533. }
  96534. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  96535. {
  96536. if(!decoder->private_->is_seeking)
  96537. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  96538. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  96539. decoder->private_->unparseable_frame_count++;
  96540. }
  96541. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  96542. {
  96543. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  96544. FLAC__int64 pos = -1;
  96545. int i;
  96546. unsigned approx_bytes_per_frame;
  96547. FLAC__bool first_seek = true;
  96548. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  96549. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  96550. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  96551. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  96552. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  96553. /* take these from the current frame in case they've changed mid-stream */
  96554. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  96555. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  96556. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  96557. /* use values from stream info if we didn't decode a frame */
  96558. if(channels == 0)
  96559. channels = decoder->private_->stream_info.data.stream_info.channels;
  96560. if(bps == 0)
  96561. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  96562. /* we are just guessing here */
  96563. if(max_framesize > 0)
  96564. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  96565. /*
  96566. * Check if it's a known fixed-blocksize stream. Note that though
  96567. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  96568. * never get a STREAMINFO block when decoding so the value of
  96569. * min_blocksize might be zero.
  96570. */
  96571. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  96572. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  96573. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  96574. }
  96575. else
  96576. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  96577. /*
  96578. * First, we set an upper and lower bound on where in the
  96579. * stream we will search. For now we assume the worst case
  96580. * scenario, which is our best guess at the beginning of
  96581. * the first frame and end of the stream.
  96582. */
  96583. lower_bound = first_frame_offset;
  96584. lower_bound_sample = 0;
  96585. upper_bound = stream_length;
  96586. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  96587. /*
  96588. * Now we refine the bounds if we have a seektable with
  96589. * suitable points. Note that according to the spec they
  96590. * must be ordered by ascending sample number.
  96591. *
  96592. * Note: to protect against invalid seek tables we will ignore points
  96593. * that have frame_samples==0 or sample_number>=total_samples
  96594. */
  96595. if(seek_table) {
  96596. FLAC__uint64 new_lower_bound = lower_bound;
  96597. FLAC__uint64 new_upper_bound = upper_bound;
  96598. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  96599. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  96600. /* find the closest seek point <= target_sample, if it exists */
  96601. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  96602. if(
  96603. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96604. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  96605. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  96606. seek_table->points[i].sample_number <= target_sample
  96607. )
  96608. break;
  96609. }
  96610. if(i >= 0) { /* i.e. we found a suitable seek point... */
  96611. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  96612. new_lower_bound_sample = seek_table->points[i].sample_number;
  96613. }
  96614. /* find the closest seek point > target_sample, if it exists */
  96615. for(i = 0; i < (int)seek_table->num_points; i++) {
  96616. if(
  96617. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96618. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  96619. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  96620. seek_table->points[i].sample_number > target_sample
  96621. )
  96622. break;
  96623. }
  96624. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  96625. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  96626. new_upper_bound_sample = seek_table->points[i].sample_number;
  96627. }
  96628. /* final protection against unsorted seek tables; keep original values if bogus */
  96629. if(new_upper_bound >= new_lower_bound) {
  96630. lower_bound = new_lower_bound;
  96631. upper_bound = new_upper_bound;
  96632. lower_bound_sample = new_lower_bound_sample;
  96633. upper_bound_sample = new_upper_bound_sample;
  96634. }
  96635. }
  96636. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  96637. /* there are 2 insidious ways that the following equality occurs, which
  96638. * we need to fix:
  96639. * 1) total_samples is 0 (unknown) and target_sample is 0
  96640. * 2) total_samples is 0 (unknown) and target_sample happens to be
  96641. * exactly equal to the last seek point in the seek table; this
  96642. * means there is no seek point above it, and upper_bound_samples
  96643. * remains equal to the estimate (of target_samples) we made above
  96644. * in either case it does not hurt to move upper_bound_sample up by 1
  96645. */
  96646. if(upper_bound_sample == lower_bound_sample)
  96647. upper_bound_sample++;
  96648. decoder->private_->target_sample = target_sample;
  96649. while(1) {
  96650. /* check if the bounds are still ok */
  96651. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  96652. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96653. return false;
  96654. }
  96655. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96656. #if defined _MSC_VER || defined __MINGW32__
  96657. /* with VC++ you have to spoon feed it the casting */
  96658. 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;
  96659. #else
  96660. 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;
  96661. #endif
  96662. #else
  96663. /* a little less accurate: */
  96664. if(upper_bound - lower_bound < 0xffffffff)
  96665. 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;
  96666. else /* @@@ WATCHOUT, ~2TB limit */
  96667. 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;
  96668. #endif
  96669. if(pos >= (FLAC__int64)upper_bound)
  96670. pos = (FLAC__int64)upper_bound - 1;
  96671. if(pos < (FLAC__int64)lower_bound)
  96672. pos = (FLAC__int64)lower_bound;
  96673. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  96674. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96675. return false;
  96676. }
  96677. if(!FLAC__stream_decoder_flush(decoder)) {
  96678. /* above call sets the state for us */
  96679. return false;
  96680. }
  96681. /* Now we need to get a frame. First we need to reset our
  96682. * unparseable_frame_count; if we get too many unparseable
  96683. * frames in a row, the read callback will return
  96684. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  96685. * FLAC__stream_decoder_process_single() to return false.
  96686. */
  96687. decoder->private_->unparseable_frame_count = 0;
  96688. if(!FLAC__stream_decoder_process_single(decoder)) {
  96689. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96690. return false;
  96691. }
  96692. /* our write callback will change the state when it gets to the target frame */
  96693. /* 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 */
  96694. #if 0
  96695. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  96696. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  96697. break;
  96698. #endif
  96699. if(!decoder->private_->is_seeking)
  96700. break;
  96701. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  96702. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  96703. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  96704. if (pos == (FLAC__int64)lower_bound) {
  96705. /* can't move back any more than the first frame, something is fatally wrong */
  96706. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96707. return false;
  96708. }
  96709. /* our last move backwards wasn't big enough, try again */
  96710. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  96711. continue;
  96712. }
  96713. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  96714. first_seek = false;
  96715. /* make sure we are not seeking in corrupted stream */
  96716. if (this_frame_sample < lower_bound_sample) {
  96717. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96718. return false;
  96719. }
  96720. /* we need to narrow the search */
  96721. if(target_sample < this_frame_sample) {
  96722. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  96723. /*@@@@@@ what will decode position be if at end of stream? */
  96724. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  96725. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96726. return false;
  96727. }
  96728. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  96729. }
  96730. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  96731. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  96732. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  96733. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96734. return false;
  96735. }
  96736. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  96737. }
  96738. }
  96739. return true;
  96740. }
  96741. #if FLAC__HAS_OGG
  96742. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  96743. {
  96744. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  96745. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  96746. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  96747. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  96748. FLAC__bool did_a_seek;
  96749. unsigned iteration = 0;
  96750. /* In the first iterations, we will calculate the target byte position
  96751. * by the distance from the target sample to left_sample and
  96752. * right_sample (let's call it "proportional search"). After that, we
  96753. * will switch to binary search.
  96754. */
  96755. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  96756. /* We will switch to a linear search once our current sample is less
  96757. * than this number of samples ahead of the target sample
  96758. */
  96759. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  96760. /* If the total number of samples is unknown, use a large value, and
  96761. * force binary search immediately.
  96762. */
  96763. if(right_sample == 0) {
  96764. right_sample = (FLAC__uint64)(-1);
  96765. BINARY_SEARCH_AFTER_ITERATION = 0;
  96766. }
  96767. decoder->private_->target_sample = target_sample;
  96768. for( ; ; iteration++) {
  96769. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  96770. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  96771. pos = (right_pos + left_pos) / 2;
  96772. }
  96773. else {
  96774. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96775. #if defined _MSC_VER || defined __MINGW32__
  96776. /* with MSVC you have to spoon feed it the casting */
  96777. 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));
  96778. #else
  96779. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  96780. #endif
  96781. #else
  96782. /* a little less accurate: */
  96783. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  96784. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  96785. else /* @@@ WATCHOUT, ~2TB limit */
  96786. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  96787. #endif
  96788. /* @@@ TODO: might want to limit pos to some distance
  96789. * before EOF, to make sure we land before the last frame,
  96790. * thereby getting a this_frame_sample and so having a better
  96791. * estimate.
  96792. */
  96793. }
  96794. /* physical seek */
  96795. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  96796. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96797. return false;
  96798. }
  96799. if(!FLAC__stream_decoder_flush(decoder)) {
  96800. /* above call sets the state for us */
  96801. return false;
  96802. }
  96803. did_a_seek = true;
  96804. }
  96805. else
  96806. did_a_seek = false;
  96807. decoder->private_->got_a_frame = false;
  96808. if(!FLAC__stream_decoder_process_single(decoder)) {
  96809. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96810. return false;
  96811. }
  96812. if(!decoder->private_->got_a_frame) {
  96813. if(did_a_seek) {
  96814. /* this can happen if we seek to a point after the last frame; we drop
  96815. * to binary search right away in this case to avoid any wasted
  96816. * iterations of proportional search.
  96817. */
  96818. right_pos = pos;
  96819. BINARY_SEARCH_AFTER_ITERATION = 0;
  96820. }
  96821. else {
  96822. /* this can probably only happen if total_samples is unknown and the
  96823. * target_sample is past the end of the stream
  96824. */
  96825. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96826. return false;
  96827. }
  96828. }
  96829. /* our write callback will change the state when it gets to the target frame */
  96830. else if(!decoder->private_->is_seeking) {
  96831. break;
  96832. }
  96833. else {
  96834. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  96835. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  96836. if (did_a_seek) {
  96837. if (this_frame_sample <= target_sample) {
  96838. /* The 'equal' case should not happen, since
  96839. * FLAC__stream_decoder_process_single()
  96840. * should recognize that it has hit the
  96841. * target sample and we would exit through
  96842. * the 'break' above.
  96843. */
  96844. FLAC__ASSERT(this_frame_sample != target_sample);
  96845. left_sample = this_frame_sample;
  96846. /* sanity check to avoid infinite loop */
  96847. if (left_pos == pos) {
  96848. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96849. return false;
  96850. }
  96851. left_pos = pos;
  96852. }
  96853. else if(this_frame_sample > target_sample) {
  96854. right_sample = this_frame_sample;
  96855. /* sanity check to avoid infinite loop */
  96856. if (right_pos == pos) {
  96857. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96858. return false;
  96859. }
  96860. right_pos = pos;
  96861. }
  96862. }
  96863. }
  96864. }
  96865. return true;
  96866. }
  96867. #endif
  96868. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  96869. {
  96870. (void)client_data;
  96871. if(*bytes > 0) {
  96872. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  96873. if(ferror(decoder->private_->file))
  96874. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  96875. else if(*bytes == 0)
  96876. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  96877. else
  96878. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  96879. }
  96880. else
  96881. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  96882. }
  96883. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  96884. {
  96885. (void)client_data;
  96886. if(decoder->private_->file == stdin)
  96887. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  96888. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  96889. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  96890. else
  96891. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  96892. }
  96893. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  96894. {
  96895. off_t pos;
  96896. (void)client_data;
  96897. if(decoder->private_->file == stdin)
  96898. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  96899. else if((pos = ftello(decoder->private_->file)) < 0)
  96900. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  96901. else {
  96902. *absolute_byte_offset = (FLAC__uint64)pos;
  96903. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  96904. }
  96905. }
  96906. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  96907. {
  96908. struct stat filestats;
  96909. (void)client_data;
  96910. if(decoder->private_->file == stdin)
  96911. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  96912. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  96913. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  96914. else {
  96915. *stream_length = (FLAC__uint64)filestats.st_size;
  96916. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  96917. }
  96918. }
  96919. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  96920. {
  96921. (void)client_data;
  96922. return feof(decoder->private_->file)? true : false;
  96923. }
  96924. #endif
  96925. /********* End of inlined file: stream_decoder.c *********/
  96926. /********* Start of inlined file: stream_encoder.c *********/
  96927. /********* Start of inlined file: juce_FlacHeader.h *********/
  96928. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96929. // tasks..
  96930. #define VERSION "1.2.1"
  96931. #define FLAC__NO_DLL 1
  96932. #ifdef _MSC_VER
  96933. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96934. #endif
  96935. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  96936. #define FLAC__SYS_DARWIN 1
  96937. #endif
  96938. /********* End of inlined file: juce_FlacHeader.h *********/
  96939. #if JUCE_USE_FLAC
  96940. #if HAVE_CONFIG_H
  96941. # include <config.h>
  96942. #endif
  96943. #if defined _MSC_VER || defined __MINGW32__
  96944. #include <io.h> /* for _setmode() */
  96945. #include <fcntl.h> /* for _O_BINARY */
  96946. #endif
  96947. #if defined __CYGWIN__ || defined __EMX__
  96948. #include <io.h> /* for setmode(), O_BINARY */
  96949. #include <fcntl.h> /* for _O_BINARY */
  96950. #endif
  96951. #include <limits.h>
  96952. #include <stdio.h>
  96953. #include <stdlib.h> /* for malloc() */
  96954. #include <string.h> /* for memcpy() */
  96955. #include <sys/types.h> /* for off_t */
  96956. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  96957. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  96958. #define fseeko fseek
  96959. #define ftello ftell
  96960. #endif
  96961. #endif
  96962. /********* Start of inlined file: stream_encoder.h *********/
  96963. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  96964. #define FLAC__PROTECTED__STREAM_ENCODER_H
  96965. #if FLAC__HAS_OGG
  96966. #include "private/ogg_encoder_aspect.h"
  96967. #endif
  96968. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96969. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  96970. typedef enum {
  96971. FLAC__APODIZATION_BARTLETT,
  96972. FLAC__APODIZATION_BARTLETT_HANN,
  96973. FLAC__APODIZATION_BLACKMAN,
  96974. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  96975. FLAC__APODIZATION_CONNES,
  96976. FLAC__APODIZATION_FLATTOP,
  96977. FLAC__APODIZATION_GAUSS,
  96978. FLAC__APODIZATION_HAMMING,
  96979. FLAC__APODIZATION_HANN,
  96980. FLAC__APODIZATION_KAISER_BESSEL,
  96981. FLAC__APODIZATION_NUTTALL,
  96982. FLAC__APODIZATION_RECTANGLE,
  96983. FLAC__APODIZATION_TRIANGLE,
  96984. FLAC__APODIZATION_TUKEY,
  96985. FLAC__APODIZATION_WELCH
  96986. } FLAC__ApodizationFunction;
  96987. typedef struct {
  96988. FLAC__ApodizationFunction type;
  96989. union {
  96990. struct {
  96991. FLAC__real stddev;
  96992. } gauss;
  96993. struct {
  96994. FLAC__real p;
  96995. } tukey;
  96996. } parameters;
  96997. } FLAC__ApodizationSpecification;
  96998. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96999. typedef struct FLAC__StreamEncoderProtected {
  97000. FLAC__StreamEncoderState state;
  97001. FLAC__bool verify;
  97002. FLAC__bool streamable_subset;
  97003. FLAC__bool do_md5;
  97004. FLAC__bool do_mid_side_stereo;
  97005. FLAC__bool loose_mid_side_stereo;
  97006. unsigned channels;
  97007. unsigned bits_per_sample;
  97008. unsigned sample_rate;
  97009. unsigned blocksize;
  97010. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97011. unsigned num_apodizations;
  97012. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  97013. #endif
  97014. unsigned max_lpc_order;
  97015. unsigned qlp_coeff_precision;
  97016. FLAC__bool do_qlp_coeff_prec_search;
  97017. FLAC__bool do_exhaustive_model_search;
  97018. FLAC__bool do_escape_coding;
  97019. unsigned min_residual_partition_order;
  97020. unsigned max_residual_partition_order;
  97021. unsigned rice_parameter_search_dist;
  97022. FLAC__uint64 total_samples_estimate;
  97023. FLAC__StreamMetadata **metadata;
  97024. unsigned num_metadata_blocks;
  97025. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  97026. #if FLAC__HAS_OGG
  97027. FLAC__OggEncoderAspect ogg_encoder_aspect;
  97028. #endif
  97029. } FLAC__StreamEncoderProtected;
  97030. #endif
  97031. /********* End of inlined file: stream_encoder.h *********/
  97032. #if FLAC__HAS_OGG
  97033. #include "include/private/ogg_helper.h"
  97034. #include "include/private/ogg_mapping.h"
  97035. #endif
  97036. /********* Start of inlined file: stream_encoder_framing.h *********/
  97037. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  97038. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  97039. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  97040. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  97041. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97042. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97043. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97044. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97045. #endif
  97046. /********* End of inlined file: stream_encoder_framing.h *********/
  97047. /********* Start of inlined file: window.h *********/
  97048. #ifndef FLAC__PRIVATE__WINDOW_H
  97049. #define FLAC__PRIVATE__WINDOW_H
  97050. #ifdef HAVE_CONFIG_H
  97051. #include <config.h>
  97052. #endif
  97053. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97054. /*
  97055. * FLAC__window_*()
  97056. * --------------------------------------------------------------------
  97057. * Calculates window coefficients according to different apodization
  97058. * functions.
  97059. *
  97060. * OUT window[0,L-1]
  97061. * IN L (number of points in window)
  97062. */
  97063. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  97064. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  97065. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  97066. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  97067. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  97068. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  97069. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  97070. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  97071. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  97072. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  97073. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  97074. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  97075. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  97076. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  97077. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  97078. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97079. #endif
  97080. /********* End of inlined file: window.h *********/
  97081. #ifndef FLaC__INLINE
  97082. #define FLaC__INLINE
  97083. #endif
  97084. #ifdef min
  97085. #undef min
  97086. #endif
  97087. #define min(x,y) ((x)<(y)?(x):(y))
  97088. #ifdef max
  97089. #undef max
  97090. #endif
  97091. #define max(x,y) ((x)>(y)?(x):(y))
  97092. /* Exact Rice codeword length calculation is off by default. The simple
  97093. * (and fast) estimation (of how many bits a residual value will be
  97094. * encoded with) in this encoder is very good, almost always yielding
  97095. * compression within 0.1% of exact calculation.
  97096. */
  97097. #undef EXACT_RICE_BITS_CALCULATION
  97098. /* Rice parameter searching is off by default. The simple (and fast)
  97099. * parameter estimation in this encoder is very good, almost always
  97100. * yielding compression within 0.1% of the optimal parameters.
  97101. */
  97102. #undef ENABLE_RICE_PARAMETER_SEARCH
  97103. typedef struct {
  97104. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  97105. unsigned size; /* of each data[] in samples */
  97106. unsigned tail;
  97107. } verify_input_fifo;
  97108. typedef struct {
  97109. const FLAC__byte *data;
  97110. unsigned capacity;
  97111. unsigned bytes;
  97112. } verify_output;
  97113. typedef enum {
  97114. ENCODER_IN_MAGIC = 0,
  97115. ENCODER_IN_METADATA = 1,
  97116. ENCODER_IN_AUDIO = 2
  97117. } EncoderStateHint;
  97118. static struct CompressionLevels {
  97119. FLAC__bool do_mid_side_stereo;
  97120. FLAC__bool loose_mid_side_stereo;
  97121. unsigned max_lpc_order;
  97122. unsigned qlp_coeff_precision;
  97123. FLAC__bool do_qlp_coeff_prec_search;
  97124. FLAC__bool do_escape_coding;
  97125. FLAC__bool do_exhaustive_model_search;
  97126. unsigned min_residual_partition_order;
  97127. unsigned max_residual_partition_order;
  97128. unsigned rice_parameter_search_dist;
  97129. } compression_levels_[] = {
  97130. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  97131. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  97132. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  97133. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  97134. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  97135. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  97136. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  97137. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  97138. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  97139. };
  97140. /***********************************************************************
  97141. *
  97142. * Private class method prototypes
  97143. *
  97144. ***********************************************************************/
  97145. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  97146. static void free_(FLAC__StreamEncoder *encoder);
  97147. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  97148. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  97149. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  97150. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  97151. #if FLAC__HAS_OGG
  97152. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  97153. #endif
  97154. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  97155. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  97156. static FLAC__bool process_subframe_(
  97157. FLAC__StreamEncoder *encoder,
  97158. unsigned min_partition_order,
  97159. unsigned max_partition_order,
  97160. const FLAC__FrameHeader *frame_header,
  97161. unsigned subframe_bps,
  97162. const FLAC__int32 integer_signal[],
  97163. FLAC__Subframe *subframe[2],
  97164. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  97165. FLAC__int32 *residual[2],
  97166. unsigned *best_subframe,
  97167. unsigned *best_bits
  97168. );
  97169. static FLAC__bool add_subframe_(
  97170. FLAC__StreamEncoder *encoder,
  97171. unsigned blocksize,
  97172. unsigned subframe_bps,
  97173. const FLAC__Subframe *subframe,
  97174. FLAC__BitWriter *frame
  97175. );
  97176. static unsigned evaluate_constant_subframe_(
  97177. FLAC__StreamEncoder *encoder,
  97178. const FLAC__int32 signal,
  97179. unsigned blocksize,
  97180. unsigned subframe_bps,
  97181. FLAC__Subframe *subframe
  97182. );
  97183. static unsigned evaluate_fixed_subframe_(
  97184. FLAC__StreamEncoder *encoder,
  97185. const FLAC__int32 signal[],
  97186. FLAC__int32 residual[],
  97187. FLAC__uint64 abs_residual_partition_sums[],
  97188. unsigned raw_bits_per_partition[],
  97189. unsigned blocksize,
  97190. unsigned subframe_bps,
  97191. unsigned order,
  97192. unsigned rice_parameter,
  97193. unsigned rice_parameter_limit,
  97194. unsigned min_partition_order,
  97195. unsigned max_partition_order,
  97196. FLAC__bool do_escape_coding,
  97197. unsigned rice_parameter_search_dist,
  97198. FLAC__Subframe *subframe,
  97199. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  97200. );
  97201. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97202. static unsigned evaluate_lpc_subframe_(
  97203. FLAC__StreamEncoder *encoder,
  97204. const FLAC__int32 signal[],
  97205. FLAC__int32 residual[],
  97206. FLAC__uint64 abs_residual_partition_sums[],
  97207. unsigned raw_bits_per_partition[],
  97208. const FLAC__real lp_coeff[],
  97209. unsigned blocksize,
  97210. unsigned subframe_bps,
  97211. unsigned order,
  97212. unsigned qlp_coeff_precision,
  97213. unsigned rice_parameter,
  97214. unsigned rice_parameter_limit,
  97215. unsigned min_partition_order,
  97216. unsigned max_partition_order,
  97217. FLAC__bool do_escape_coding,
  97218. unsigned rice_parameter_search_dist,
  97219. FLAC__Subframe *subframe,
  97220. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  97221. );
  97222. #endif
  97223. static unsigned evaluate_verbatim_subframe_(
  97224. FLAC__StreamEncoder *encoder,
  97225. const FLAC__int32 signal[],
  97226. unsigned blocksize,
  97227. unsigned subframe_bps,
  97228. FLAC__Subframe *subframe
  97229. );
  97230. static unsigned find_best_partition_order_(
  97231. struct FLAC__StreamEncoderPrivate *private_,
  97232. const FLAC__int32 residual[],
  97233. FLAC__uint64 abs_residual_partition_sums[],
  97234. unsigned raw_bits_per_partition[],
  97235. unsigned residual_samples,
  97236. unsigned predictor_order,
  97237. unsigned rice_parameter,
  97238. unsigned rice_parameter_limit,
  97239. unsigned min_partition_order,
  97240. unsigned max_partition_order,
  97241. unsigned bps,
  97242. FLAC__bool do_escape_coding,
  97243. unsigned rice_parameter_search_dist,
  97244. FLAC__EntropyCodingMethod *best_ecm
  97245. );
  97246. static void precompute_partition_info_sums_(
  97247. const FLAC__int32 residual[],
  97248. FLAC__uint64 abs_residual_partition_sums[],
  97249. unsigned residual_samples,
  97250. unsigned predictor_order,
  97251. unsigned min_partition_order,
  97252. unsigned max_partition_order,
  97253. unsigned bps
  97254. );
  97255. static void precompute_partition_info_escapes_(
  97256. const FLAC__int32 residual[],
  97257. unsigned raw_bits_per_partition[],
  97258. unsigned residual_samples,
  97259. unsigned predictor_order,
  97260. unsigned min_partition_order,
  97261. unsigned max_partition_order
  97262. );
  97263. static FLAC__bool set_partitioned_rice_(
  97264. #ifdef EXACT_RICE_BITS_CALCULATION
  97265. const FLAC__int32 residual[],
  97266. #endif
  97267. const FLAC__uint64 abs_residual_partition_sums[],
  97268. const unsigned raw_bits_per_partition[],
  97269. const unsigned residual_samples,
  97270. const unsigned predictor_order,
  97271. const unsigned suggested_rice_parameter,
  97272. const unsigned rice_parameter_limit,
  97273. const unsigned rice_parameter_search_dist,
  97274. const unsigned partition_order,
  97275. const FLAC__bool search_for_escapes,
  97276. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  97277. unsigned *bits
  97278. );
  97279. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  97280. /* verify-related routines: */
  97281. static void append_to_verify_fifo_(
  97282. verify_input_fifo *fifo,
  97283. const FLAC__int32 * const input[],
  97284. unsigned input_offset,
  97285. unsigned channels,
  97286. unsigned wide_samples
  97287. );
  97288. static void append_to_verify_fifo_interleaved_(
  97289. verify_input_fifo *fifo,
  97290. const FLAC__int32 input[],
  97291. unsigned input_offset,
  97292. unsigned channels,
  97293. unsigned wide_samples
  97294. );
  97295. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  97296. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  97297. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  97298. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  97299. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  97300. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  97301. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  97302. 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);
  97303. static FILE *get_binary_stdout_(void);
  97304. /***********************************************************************
  97305. *
  97306. * Private class data
  97307. *
  97308. ***********************************************************************/
  97309. typedef struct FLAC__StreamEncoderPrivate {
  97310. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  97311. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  97312. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  97313. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97314. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  97315. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  97316. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  97317. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  97318. #endif
  97319. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  97320. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  97321. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  97322. FLAC__int32 *residual_workspace_mid_side[2][2];
  97323. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  97324. FLAC__Subframe subframe_workspace_mid_side[2][2];
  97325. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  97326. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  97327. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  97328. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  97329. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  97330. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  97331. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  97332. unsigned best_subframe_mid_side[2];
  97333. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  97334. unsigned best_subframe_bits_mid_side[2];
  97335. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  97336. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  97337. FLAC__BitWriter *frame; /* the current frame being worked on */
  97338. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  97339. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  97340. FLAC__ChannelAssignment last_channel_assignment;
  97341. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  97342. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  97343. unsigned current_sample_number;
  97344. unsigned current_frame_number;
  97345. FLAC__MD5Context md5context;
  97346. FLAC__CPUInfo cpuinfo;
  97347. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97348. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  97349. #else
  97350. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  97351. #endif
  97352. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97353. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97354. 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[]);
  97355. 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[]);
  97356. 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[]);
  97357. #endif
  97358. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  97359. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  97360. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  97361. FLAC__bool disable_constant_subframes;
  97362. FLAC__bool disable_fixed_subframes;
  97363. FLAC__bool disable_verbatim_subframes;
  97364. #if FLAC__HAS_OGG
  97365. FLAC__bool is_ogg;
  97366. #endif
  97367. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  97368. FLAC__StreamEncoderSeekCallback seek_callback;
  97369. FLAC__StreamEncoderTellCallback tell_callback;
  97370. FLAC__StreamEncoderWriteCallback write_callback;
  97371. FLAC__StreamEncoderMetadataCallback metadata_callback;
  97372. FLAC__StreamEncoderProgressCallback progress_callback;
  97373. void *client_data;
  97374. unsigned first_seekpoint_to_check;
  97375. FILE *file; /* only used when encoding to a file */
  97376. FLAC__uint64 bytes_written;
  97377. FLAC__uint64 samples_written;
  97378. unsigned frames_written;
  97379. unsigned total_frames_estimate;
  97380. /* unaligned (original) pointers to allocated data */
  97381. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  97382. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  97383. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97384. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  97385. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  97386. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  97387. FLAC__real *windowed_signal_unaligned;
  97388. #endif
  97389. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  97390. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  97391. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  97392. unsigned *raw_bits_per_partition_unaligned;
  97393. /*
  97394. * These fields have been moved here from private function local
  97395. * declarations merely to save stack space during encoding.
  97396. */
  97397. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97398. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  97399. #endif
  97400. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  97401. /*
  97402. * The data for the verify section
  97403. */
  97404. struct {
  97405. FLAC__StreamDecoder *decoder;
  97406. EncoderStateHint state_hint;
  97407. FLAC__bool needs_magic_hack;
  97408. verify_input_fifo input_fifo;
  97409. verify_output output;
  97410. struct {
  97411. FLAC__uint64 absolute_sample;
  97412. unsigned frame_number;
  97413. unsigned channel;
  97414. unsigned sample;
  97415. FLAC__int32 expected;
  97416. FLAC__int32 got;
  97417. } error_stats;
  97418. } verify;
  97419. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  97420. } FLAC__StreamEncoderPrivate;
  97421. /***********************************************************************
  97422. *
  97423. * Public static class data
  97424. *
  97425. ***********************************************************************/
  97426. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  97427. "FLAC__STREAM_ENCODER_OK",
  97428. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  97429. "FLAC__STREAM_ENCODER_OGG_ERROR",
  97430. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  97431. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  97432. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  97433. "FLAC__STREAM_ENCODER_IO_ERROR",
  97434. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  97435. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  97436. };
  97437. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  97438. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  97439. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  97440. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  97441. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  97442. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  97443. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  97444. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  97445. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  97446. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  97447. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  97448. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  97449. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  97450. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  97451. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  97452. };
  97453. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  97454. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  97455. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  97456. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  97457. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  97458. };
  97459. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  97460. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  97461. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  97462. };
  97463. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  97464. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  97465. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  97466. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  97467. };
  97468. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  97469. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  97470. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  97471. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  97472. };
  97473. /* Number of samples that will be overread to watch for end of stream. By
  97474. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  97475. * always try to read blocksize+1 samples before encoding a block, so that
  97476. * even if the stream has a total sample count that is an integral multiple
  97477. * of the blocksize, we will still notice when we are encoding the last
  97478. * block. This is needed, for example, to correctly set the end-of-stream
  97479. * marker in Ogg FLAC.
  97480. *
  97481. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  97482. * not really any reason to change it.
  97483. */
  97484. static const unsigned OVERREAD_ = 1;
  97485. /***********************************************************************
  97486. *
  97487. * Class constructor/destructor
  97488. *
  97489. */
  97490. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  97491. {
  97492. FLAC__StreamEncoder *encoder;
  97493. unsigned i;
  97494. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  97495. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  97496. if(encoder == 0) {
  97497. return 0;
  97498. }
  97499. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  97500. if(encoder->protected_ == 0) {
  97501. free(encoder);
  97502. return 0;
  97503. }
  97504. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  97505. if(encoder->private_ == 0) {
  97506. free(encoder->protected_);
  97507. free(encoder);
  97508. return 0;
  97509. }
  97510. encoder->private_->frame = FLAC__bitwriter_new();
  97511. if(encoder->private_->frame == 0) {
  97512. free(encoder->private_);
  97513. free(encoder->protected_);
  97514. free(encoder);
  97515. return 0;
  97516. }
  97517. encoder->private_->file = 0;
  97518. set_defaults_enc(encoder);
  97519. encoder->private_->is_being_deleted = false;
  97520. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  97521. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  97522. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  97523. }
  97524. for(i = 0; i < 2; i++) {
  97525. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  97526. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  97527. }
  97528. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  97529. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  97530. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  97531. }
  97532. for(i = 0; i < 2; i++) {
  97533. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  97534. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  97535. }
  97536. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  97537. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  97538. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  97539. }
  97540. for(i = 0; i < 2; i++) {
  97541. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  97542. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  97543. }
  97544. for(i = 0; i < 2; i++)
  97545. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  97546. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  97547. return encoder;
  97548. }
  97549. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  97550. {
  97551. unsigned i;
  97552. FLAC__ASSERT(0 != encoder);
  97553. FLAC__ASSERT(0 != encoder->protected_);
  97554. FLAC__ASSERT(0 != encoder->private_);
  97555. FLAC__ASSERT(0 != encoder->private_->frame);
  97556. encoder->private_->is_being_deleted = true;
  97557. (void)FLAC__stream_encoder_finish(encoder);
  97558. if(0 != encoder->private_->verify.decoder)
  97559. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  97560. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  97561. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  97562. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  97563. }
  97564. for(i = 0; i < 2; i++) {
  97565. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  97566. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  97567. }
  97568. for(i = 0; i < 2; i++)
  97569. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  97570. FLAC__bitwriter_delete(encoder->private_->frame);
  97571. free(encoder->private_);
  97572. free(encoder->protected_);
  97573. free(encoder);
  97574. }
  97575. /***********************************************************************
  97576. *
  97577. * Public class methods
  97578. *
  97579. ***********************************************************************/
  97580. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  97581. FLAC__StreamEncoder *encoder,
  97582. FLAC__StreamEncoderReadCallback read_callback,
  97583. FLAC__StreamEncoderWriteCallback write_callback,
  97584. FLAC__StreamEncoderSeekCallback seek_callback,
  97585. FLAC__StreamEncoderTellCallback tell_callback,
  97586. FLAC__StreamEncoderMetadataCallback metadata_callback,
  97587. void *client_data,
  97588. FLAC__bool is_ogg
  97589. )
  97590. {
  97591. unsigned i;
  97592. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  97593. FLAC__ASSERT(0 != encoder);
  97594. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97595. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  97596. #if !FLAC__HAS_OGG
  97597. if(is_ogg)
  97598. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  97599. #endif
  97600. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  97601. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  97602. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  97603. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  97604. if(encoder->protected_->channels != 2) {
  97605. encoder->protected_->do_mid_side_stereo = false;
  97606. encoder->protected_->loose_mid_side_stereo = false;
  97607. }
  97608. else if(!encoder->protected_->do_mid_side_stereo)
  97609. encoder->protected_->loose_mid_side_stereo = false;
  97610. if(encoder->protected_->bits_per_sample >= 32)
  97611. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  97612. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  97613. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  97614. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  97615. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  97616. if(encoder->protected_->blocksize == 0) {
  97617. if(encoder->protected_->max_lpc_order == 0)
  97618. encoder->protected_->blocksize = 1152;
  97619. else
  97620. encoder->protected_->blocksize = 4096;
  97621. }
  97622. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  97623. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  97624. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  97625. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  97626. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  97627. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  97628. if(encoder->protected_->qlp_coeff_precision == 0) {
  97629. if(encoder->protected_->bits_per_sample < 16) {
  97630. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  97631. /* @@@ until then we'll make a guess */
  97632. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  97633. }
  97634. else if(encoder->protected_->bits_per_sample == 16) {
  97635. if(encoder->protected_->blocksize <= 192)
  97636. encoder->protected_->qlp_coeff_precision = 7;
  97637. else if(encoder->protected_->blocksize <= 384)
  97638. encoder->protected_->qlp_coeff_precision = 8;
  97639. else if(encoder->protected_->blocksize <= 576)
  97640. encoder->protected_->qlp_coeff_precision = 9;
  97641. else if(encoder->protected_->blocksize <= 1152)
  97642. encoder->protected_->qlp_coeff_precision = 10;
  97643. else if(encoder->protected_->blocksize <= 2304)
  97644. encoder->protected_->qlp_coeff_precision = 11;
  97645. else if(encoder->protected_->blocksize <= 4608)
  97646. encoder->protected_->qlp_coeff_precision = 12;
  97647. else
  97648. encoder->protected_->qlp_coeff_precision = 13;
  97649. }
  97650. else {
  97651. if(encoder->protected_->blocksize <= 384)
  97652. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  97653. else if(encoder->protected_->blocksize <= 1152)
  97654. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  97655. else
  97656. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  97657. }
  97658. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  97659. }
  97660. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  97661. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  97662. if(encoder->protected_->streamable_subset) {
  97663. if(
  97664. encoder->protected_->blocksize != 192 &&
  97665. encoder->protected_->blocksize != 576 &&
  97666. encoder->protected_->blocksize != 1152 &&
  97667. encoder->protected_->blocksize != 2304 &&
  97668. encoder->protected_->blocksize != 4608 &&
  97669. encoder->protected_->blocksize != 256 &&
  97670. encoder->protected_->blocksize != 512 &&
  97671. encoder->protected_->blocksize != 1024 &&
  97672. encoder->protected_->blocksize != 2048 &&
  97673. encoder->protected_->blocksize != 4096 &&
  97674. encoder->protected_->blocksize != 8192 &&
  97675. encoder->protected_->blocksize != 16384
  97676. )
  97677. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  97678. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  97679. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  97680. if(
  97681. encoder->protected_->bits_per_sample != 8 &&
  97682. encoder->protected_->bits_per_sample != 12 &&
  97683. encoder->protected_->bits_per_sample != 16 &&
  97684. encoder->protected_->bits_per_sample != 20 &&
  97685. encoder->protected_->bits_per_sample != 24
  97686. )
  97687. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  97688. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  97689. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  97690. if(
  97691. encoder->protected_->sample_rate <= 48000 &&
  97692. (
  97693. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  97694. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  97695. )
  97696. ) {
  97697. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  97698. }
  97699. }
  97700. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  97701. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  97702. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  97703. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  97704. #if FLAC__HAS_OGG
  97705. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  97706. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  97707. unsigned i;
  97708. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  97709. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  97710. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  97711. for( ; i > 0; i--)
  97712. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  97713. encoder->protected_->metadata[0] = vc;
  97714. break;
  97715. }
  97716. }
  97717. }
  97718. #endif
  97719. /* keep track of any SEEKTABLE block */
  97720. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  97721. unsigned i;
  97722. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  97723. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  97724. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  97725. break; /* take only the first one */
  97726. }
  97727. }
  97728. }
  97729. /* validate metadata */
  97730. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  97731. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97732. metadata_has_seektable = false;
  97733. metadata_has_vorbis_comment = false;
  97734. metadata_picture_has_type1 = false;
  97735. metadata_picture_has_type2 = false;
  97736. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  97737. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  97738. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  97739. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97740. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  97741. if(metadata_has_seektable) /* only one is allowed */
  97742. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97743. metadata_has_seektable = true;
  97744. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  97745. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97746. }
  97747. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  97748. if(metadata_has_vorbis_comment) /* only one is allowed */
  97749. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97750. metadata_has_vorbis_comment = true;
  97751. }
  97752. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  97753. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  97754. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97755. }
  97756. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  97757. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  97758. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97759. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  97760. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  97761. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97762. metadata_picture_has_type1 = true;
  97763. /* standard icon must be 32x32 pixel PNG */
  97764. if(
  97765. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  97766. (
  97767. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  97768. m->data.picture.width != 32 ||
  97769. m->data.picture.height != 32
  97770. )
  97771. )
  97772. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97773. }
  97774. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  97775. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  97776. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97777. metadata_picture_has_type2 = true;
  97778. }
  97779. }
  97780. }
  97781. encoder->private_->input_capacity = 0;
  97782. for(i = 0; i < encoder->protected_->channels; i++) {
  97783. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  97784. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97785. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  97786. #endif
  97787. }
  97788. for(i = 0; i < 2; i++) {
  97789. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  97790. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97791. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  97792. #endif
  97793. }
  97794. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97795. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  97796. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  97797. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  97798. #endif
  97799. for(i = 0; i < encoder->protected_->channels; i++) {
  97800. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  97801. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  97802. encoder->private_->best_subframe[i] = 0;
  97803. }
  97804. for(i = 0; i < 2; i++) {
  97805. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  97806. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  97807. encoder->private_->best_subframe_mid_side[i] = 0;
  97808. }
  97809. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  97810. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  97811. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97812. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  97813. #else
  97814. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  97815. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  97816. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  97817. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  97818. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  97819. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  97820. 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);
  97821. #endif
  97822. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  97823. encoder->private_->loose_mid_side_stereo_frames = 1;
  97824. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  97825. encoder->private_->current_sample_number = 0;
  97826. encoder->private_->current_frame_number = 0;
  97827. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  97828. 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? */
  97829. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  97830. /*
  97831. * get the CPU info and set the function pointers
  97832. */
  97833. FLAC__cpu_info(&encoder->private_->cpuinfo);
  97834. /* first default to the non-asm routines */
  97835. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97836. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  97837. #endif
  97838. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  97839. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97840. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  97841. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  97842. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  97843. #endif
  97844. /* now override with asm where appropriate */
  97845. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97846. # ifndef FLAC__NO_ASM
  97847. if(encoder->private_->cpuinfo.use_asm) {
  97848. # ifdef FLAC__CPU_IA32
  97849. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  97850. # ifdef FLAC__HAS_NASM
  97851. if(encoder->private_->cpuinfo.data.ia32.sse) {
  97852. if(encoder->protected_->max_lpc_order < 4)
  97853. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  97854. else if(encoder->protected_->max_lpc_order < 8)
  97855. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  97856. else if(encoder->protected_->max_lpc_order < 12)
  97857. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  97858. else
  97859. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  97860. }
  97861. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  97862. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  97863. else
  97864. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  97865. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  97866. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  97867. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  97868. }
  97869. else {
  97870. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  97871. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  97872. }
  97873. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  97874. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  97875. # endif /* FLAC__HAS_NASM */
  97876. # endif /* FLAC__CPU_IA32 */
  97877. }
  97878. # endif /* !FLAC__NO_ASM */
  97879. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  97880. /* finally override based on wide-ness if necessary */
  97881. if(encoder->private_->use_wide_by_block) {
  97882. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  97883. }
  97884. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  97885. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  97886. #if FLAC__HAS_OGG
  97887. encoder->private_->is_ogg = is_ogg;
  97888. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  97889. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  97890. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97891. }
  97892. #endif
  97893. encoder->private_->read_callback = read_callback;
  97894. encoder->private_->write_callback = write_callback;
  97895. encoder->private_->seek_callback = seek_callback;
  97896. encoder->private_->tell_callback = tell_callback;
  97897. encoder->private_->metadata_callback = metadata_callback;
  97898. encoder->private_->client_data = client_data;
  97899. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  97900. /* the above function sets the state for us in case of an error */
  97901. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97902. }
  97903. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  97904. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  97905. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97906. }
  97907. /*
  97908. * Set up the verify stuff if necessary
  97909. */
  97910. if(encoder->protected_->verify) {
  97911. /*
  97912. * First, set up the fifo which will hold the
  97913. * original signal to compare against
  97914. */
  97915. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  97916. for(i = 0; i < encoder->protected_->channels; i++) {
  97917. 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))) {
  97918. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  97919. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97920. }
  97921. }
  97922. encoder->private_->verify.input_fifo.tail = 0;
  97923. /*
  97924. * Now set up a stream decoder for verification
  97925. */
  97926. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  97927. if(0 == encoder->private_->verify.decoder) {
  97928. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  97929. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97930. }
  97931. 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) {
  97932. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  97933. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97934. }
  97935. }
  97936. encoder->private_->verify.error_stats.absolute_sample = 0;
  97937. encoder->private_->verify.error_stats.frame_number = 0;
  97938. encoder->private_->verify.error_stats.channel = 0;
  97939. encoder->private_->verify.error_stats.sample = 0;
  97940. encoder->private_->verify.error_stats.expected = 0;
  97941. encoder->private_->verify.error_stats.got = 0;
  97942. /*
  97943. * These must be done before we write any metadata, because that
  97944. * calls the write_callback, which uses these values.
  97945. */
  97946. encoder->private_->first_seekpoint_to_check = 0;
  97947. encoder->private_->samples_written = 0;
  97948. encoder->protected_->streaminfo_offset = 0;
  97949. encoder->protected_->seektable_offset = 0;
  97950. encoder->protected_->audio_offset = 0;
  97951. /*
  97952. * write the stream header
  97953. */
  97954. if(encoder->protected_->verify)
  97955. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  97956. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  97957. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  97958. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97959. }
  97960. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  97961. /* the above function sets the state for us in case of an error */
  97962. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97963. }
  97964. /*
  97965. * write the STREAMINFO metadata block
  97966. */
  97967. if(encoder->protected_->verify)
  97968. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  97969. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  97970. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  97971. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  97972. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  97973. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  97974. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  97975. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  97976. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  97977. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  97978. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  97979. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  97980. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  97981. if(encoder->protected_->do_md5)
  97982. FLAC__MD5Init(&encoder->private_->md5context);
  97983. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  97984. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  97985. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97986. }
  97987. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  97988. /* the above function sets the state for us in case of an error */
  97989. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97990. }
  97991. /*
  97992. * Now that the STREAMINFO block is written, we can init this to an
  97993. * absurdly-high value...
  97994. */
  97995. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  97996. /* ... and clear this to 0 */
  97997. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  97998. /*
  97999. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  98000. * if not, we will write an empty one (FLAC__add_metadata_block()
  98001. * automatically supplies the vendor string).
  98002. *
  98003. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  98004. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  98005. * true it will have already insured that the metadata list is properly
  98006. * ordered.)
  98007. */
  98008. if(!metadata_has_vorbis_comment) {
  98009. FLAC__StreamMetadata vorbis_comment;
  98010. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  98011. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  98012. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  98013. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  98014. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  98015. vorbis_comment.data.vorbis_comment.num_comments = 0;
  98016. vorbis_comment.data.vorbis_comment.comments = 0;
  98017. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  98018. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98019. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98020. }
  98021. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98022. /* the above function sets the state for us in case of an error */
  98023. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98024. }
  98025. }
  98026. /*
  98027. * write the user's metadata blocks
  98028. */
  98029. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  98030. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  98031. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  98032. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98033. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98034. }
  98035. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98036. /* the above function sets the state for us in case of an error */
  98037. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98038. }
  98039. }
  98040. /* now that all the metadata is written, we save the stream offset */
  98041. 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 */
  98042. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98043. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98044. }
  98045. if(encoder->protected_->verify)
  98046. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  98047. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  98048. }
  98049. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  98050. FLAC__StreamEncoder *encoder,
  98051. FLAC__StreamEncoderWriteCallback write_callback,
  98052. FLAC__StreamEncoderSeekCallback seek_callback,
  98053. FLAC__StreamEncoderTellCallback tell_callback,
  98054. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98055. void *client_data
  98056. )
  98057. {
  98058. return init_stream_internal_enc(
  98059. encoder,
  98060. /*read_callback=*/0,
  98061. write_callback,
  98062. seek_callback,
  98063. tell_callback,
  98064. metadata_callback,
  98065. client_data,
  98066. /*is_ogg=*/false
  98067. );
  98068. }
  98069. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  98070. FLAC__StreamEncoder *encoder,
  98071. FLAC__StreamEncoderReadCallback read_callback,
  98072. FLAC__StreamEncoderWriteCallback write_callback,
  98073. FLAC__StreamEncoderSeekCallback seek_callback,
  98074. FLAC__StreamEncoderTellCallback tell_callback,
  98075. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98076. void *client_data
  98077. )
  98078. {
  98079. return init_stream_internal_enc(
  98080. encoder,
  98081. read_callback,
  98082. write_callback,
  98083. seek_callback,
  98084. tell_callback,
  98085. metadata_callback,
  98086. client_data,
  98087. /*is_ogg=*/true
  98088. );
  98089. }
  98090. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  98091. FLAC__StreamEncoder *encoder,
  98092. FILE *file,
  98093. FLAC__StreamEncoderProgressCallback progress_callback,
  98094. void *client_data,
  98095. FLAC__bool is_ogg
  98096. )
  98097. {
  98098. FLAC__StreamEncoderInitStatus init_status;
  98099. FLAC__ASSERT(0 != encoder);
  98100. FLAC__ASSERT(0 != file);
  98101. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98102. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  98103. /* double protection */
  98104. if(file == 0) {
  98105. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  98106. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98107. }
  98108. /*
  98109. * To make sure that our file does not go unclosed after an error, we
  98110. * must assign the FILE pointer before any further error can occur in
  98111. * this routine.
  98112. */
  98113. if(file == stdout)
  98114. file = get_binary_stdout_(); /* just to be safe */
  98115. encoder->private_->file = file;
  98116. encoder->private_->progress_callback = progress_callback;
  98117. encoder->private_->bytes_written = 0;
  98118. encoder->private_->samples_written = 0;
  98119. encoder->private_->frames_written = 0;
  98120. init_status = init_stream_internal_enc(
  98121. encoder,
  98122. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  98123. file_write_callback_,
  98124. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  98125. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  98126. /*metadata_callback=*/0,
  98127. client_data,
  98128. is_ogg
  98129. );
  98130. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  98131. /* the above function sets the state for us in case of an error */
  98132. return init_status;
  98133. }
  98134. {
  98135. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  98136. FLAC__ASSERT(blocksize != 0);
  98137. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  98138. }
  98139. return init_status;
  98140. }
  98141. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  98142. FLAC__StreamEncoder *encoder,
  98143. FILE *file,
  98144. FLAC__StreamEncoderProgressCallback progress_callback,
  98145. void *client_data
  98146. )
  98147. {
  98148. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  98149. }
  98150. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  98151. FLAC__StreamEncoder *encoder,
  98152. FILE *file,
  98153. FLAC__StreamEncoderProgressCallback progress_callback,
  98154. void *client_data
  98155. )
  98156. {
  98157. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  98158. }
  98159. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  98160. FLAC__StreamEncoder *encoder,
  98161. const char *filename,
  98162. FLAC__StreamEncoderProgressCallback progress_callback,
  98163. void *client_data,
  98164. FLAC__bool is_ogg
  98165. )
  98166. {
  98167. FILE *file;
  98168. FLAC__ASSERT(0 != encoder);
  98169. /*
  98170. * To make sure that our file does not go unclosed after an error, we
  98171. * have to do the same entrance checks here that are later performed
  98172. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  98173. */
  98174. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98175. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  98176. file = filename? fopen(filename, "w+b") : stdout;
  98177. if(file == 0) {
  98178. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  98179. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98180. }
  98181. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  98182. }
  98183. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  98184. FLAC__StreamEncoder *encoder,
  98185. const char *filename,
  98186. FLAC__StreamEncoderProgressCallback progress_callback,
  98187. void *client_data
  98188. )
  98189. {
  98190. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  98191. }
  98192. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  98193. FLAC__StreamEncoder *encoder,
  98194. const char *filename,
  98195. FLAC__StreamEncoderProgressCallback progress_callback,
  98196. void *client_data
  98197. )
  98198. {
  98199. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  98200. }
  98201. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  98202. {
  98203. FLAC__bool error = false;
  98204. FLAC__ASSERT(0 != encoder);
  98205. FLAC__ASSERT(0 != encoder->private_);
  98206. FLAC__ASSERT(0 != encoder->protected_);
  98207. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  98208. return true;
  98209. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  98210. if(encoder->private_->current_sample_number != 0) {
  98211. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  98212. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  98213. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  98214. error = true;
  98215. }
  98216. }
  98217. if(encoder->protected_->do_md5)
  98218. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  98219. if(!encoder->private_->is_being_deleted) {
  98220. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  98221. if(encoder->private_->seek_callback) {
  98222. #if FLAC__HAS_OGG
  98223. if(encoder->private_->is_ogg)
  98224. update_ogg_metadata_(encoder);
  98225. else
  98226. #endif
  98227. update_metadata_(encoder);
  98228. /* check if an error occurred while updating metadata */
  98229. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  98230. error = true;
  98231. }
  98232. if(encoder->private_->metadata_callback)
  98233. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  98234. }
  98235. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  98236. if(!error)
  98237. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  98238. error = true;
  98239. }
  98240. }
  98241. if(0 != encoder->private_->file) {
  98242. if(encoder->private_->file != stdout)
  98243. fclose(encoder->private_->file);
  98244. encoder->private_->file = 0;
  98245. }
  98246. #if FLAC__HAS_OGG
  98247. if(encoder->private_->is_ogg)
  98248. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  98249. #endif
  98250. free_(encoder);
  98251. set_defaults_enc(encoder);
  98252. if(!error)
  98253. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  98254. return !error;
  98255. }
  98256. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  98257. {
  98258. FLAC__ASSERT(0 != encoder);
  98259. FLAC__ASSERT(0 != encoder->private_);
  98260. FLAC__ASSERT(0 != encoder->protected_);
  98261. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98262. return false;
  98263. #if FLAC__HAS_OGG
  98264. /* can't check encoder->private_->is_ogg since that's not set until init time */
  98265. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  98266. return true;
  98267. #else
  98268. (void)value;
  98269. return false;
  98270. #endif
  98271. }
  98272. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98273. {
  98274. FLAC__ASSERT(0 != encoder);
  98275. FLAC__ASSERT(0 != encoder->private_);
  98276. FLAC__ASSERT(0 != encoder->protected_);
  98277. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98278. return false;
  98279. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  98280. encoder->protected_->verify = value;
  98281. #endif
  98282. return true;
  98283. }
  98284. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98285. {
  98286. FLAC__ASSERT(0 != encoder);
  98287. FLAC__ASSERT(0 != encoder->private_);
  98288. FLAC__ASSERT(0 != encoder->protected_);
  98289. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98290. return false;
  98291. encoder->protected_->streamable_subset = value;
  98292. return true;
  98293. }
  98294. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98295. {
  98296. FLAC__ASSERT(0 != encoder);
  98297. FLAC__ASSERT(0 != encoder->private_);
  98298. FLAC__ASSERT(0 != encoder->protected_);
  98299. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98300. return false;
  98301. encoder->protected_->do_md5 = value;
  98302. return true;
  98303. }
  98304. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  98305. {
  98306. FLAC__ASSERT(0 != encoder);
  98307. FLAC__ASSERT(0 != encoder->private_);
  98308. FLAC__ASSERT(0 != encoder->protected_);
  98309. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98310. return false;
  98311. encoder->protected_->channels = value;
  98312. return true;
  98313. }
  98314. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  98315. {
  98316. FLAC__ASSERT(0 != encoder);
  98317. FLAC__ASSERT(0 != encoder->private_);
  98318. FLAC__ASSERT(0 != encoder->protected_);
  98319. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98320. return false;
  98321. encoder->protected_->bits_per_sample = value;
  98322. return true;
  98323. }
  98324. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  98325. {
  98326. FLAC__ASSERT(0 != encoder);
  98327. FLAC__ASSERT(0 != encoder->private_);
  98328. FLAC__ASSERT(0 != encoder->protected_);
  98329. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98330. return false;
  98331. encoder->protected_->sample_rate = value;
  98332. return true;
  98333. }
  98334. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  98335. {
  98336. FLAC__bool ok = true;
  98337. FLAC__ASSERT(0 != encoder);
  98338. FLAC__ASSERT(0 != encoder->private_);
  98339. FLAC__ASSERT(0 != encoder->protected_);
  98340. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98341. return false;
  98342. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  98343. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  98344. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  98345. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  98346. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98347. #if 0
  98348. /* was: */
  98349. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  98350. /* but it's too hard to specify the string in a locale-specific way */
  98351. #else
  98352. encoder->protected_->num_apodizations = 1;
  98353. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  98354. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  98355. #endif
  98356. #endif
  98357. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  98358. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  98359. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  98360. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  98361. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  98362. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  98363. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  98364. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  98365. return ok;
  98366. }
  98367. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  98368. {
  98369. FLAC__ASSERT(0 != encoder);
  98370. FLAC__ASSERT(0 != encoder->private_);
  98371. FLAC__ASSERT(0 != encoder->protected_);
  98372. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98373. return false;
  98374. encoder->protected_->blocksize = value;
  98375. return true;
  98376. }
  98377. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98378. {
  98379. FLAC__ASSERT(0 != encoder);
  98380. FLAC__ASSERT(0 != encoder->private_);
  98381. FLAC__ASSERT(0 != encoder->protected_);
  98382. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98383. return false;
  98384. encoder->protected_->do_mid_side_stereo = value;
  98385. return true;
  98386. }
  98387. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98388. {
  98389. FLAC__ASSERT(0 != encoder);
  98390. FLAC__ASSERT(0 != encoder->private_);
  98391. FLAC__ASSERT(0 != encoder->protected_);
  98392. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98393. return false;
  98394. encoder->protected_->loose_mid_side_stereo = value;
  98395. return true;
  98396. }
  98397. /*@@@@add to tests*/
  98398. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  98399. {
  98400. FLAC__ASSERT(0 != encoder);
  98401. FLAC__ASSERT(0 != encoder->private_);
  98402. FLAC__ASSERT(0 != encoder->protected_);
  98403. FLAC__ASSERT(0 != specification);
  98404. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98405. return false;
  98406. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  98407. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  98408. #else
  98409. encoder->protected_->num_apodizations = 0;
  98410. while(1) {
  98411. const char *s = strchr(specification, ';');
  98412. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  98413. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  98414. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  98415. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  98416. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  98417. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  98418. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  98419. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  98420. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  98421. else if(n==6 && 0 == strncmp("connes" , specification, n))
  98422. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  98423. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  98424. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  98425. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  98426. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  98427. if (stddev > 0.0 && stddev <= 0.5) {
  98428. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  98429. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  98430. }
  98431. }
  98432. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  98433. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  98434. else if(n==4 && 0 == strncmp("hann" , specification, n))
  98435. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  98436. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  98437. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  98438. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  98439. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  98440. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  98441. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  98442. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  98443. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  98444. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  98445. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  98446. if (p >= 0.0 && p <= 1.0) {
  98447. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  98448. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  98449. }
  98450. }
  98451. else if(n==5 && 0 == strncmp("welch" , specification, n))
  98452. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  98453. if (encoder->protected_->num_apodizations == 32)
  98454. break;
  98455. if (s)
  98456. specification = s+1;
  98457. else
  98458. break;
  98459. }
  98460. if(encoder->protected_->num_apodizations == 0) {
  98461. encoder->protected_->num_apodizations = 1;
  98462. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  98463. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  98464. }
  98465. #endif
  98466. return true;
  98467. }
  98468. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  98469. {
  98470. FLAC__ASSERT(0 != encoder);
  98471. FLAC__ASSERT(0 != encoder->private_);
  98472. FLAC__ASSERT(0 != encoder->protected_);
  98473. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98474. return false;
  98475. encoder->protected_->max_lpc_order = value;
  98476. return true;
  98477. }
  98478. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  98479. {
  98480. FLAC__ASSERT(0 != encoder);
  98481. FLAC__ASSERT(0 != encoder->private_);
  98482. FLAC__ASSERT(0 != encoder->protected_);
  98483. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98484. return false;
  98485. encoder->protected_->qlp_coeff_precision = value;
  98486. return true;
  98487. }
  98488. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98489. {
  98490. FLAC__ASSERT(0 != encoder);
  98491. FLAC__ASSERT(0 != encoder->private_);
  98492. FLAC__ASSERT(0 != encoder->protected_);
  98493. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98494. return false;
  98495. encoder->protected_->do_qlp_coeff_prec_search = value;
  98496. return true;
  98497. }
  98498. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98499. {
  98500. FLAC__ASSERT(0 != encoder);
  98501. FLAC__ASSERT(0 != encoder->private_);
  98502. FLAC__ASSERT(0 != encoder->protected_);
  98503. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98504. return false;
  98505. #if 0
  98506. /*@@@ deprecated: */
  98507. encoder->protected_->do_escape_coding = value;
  98508. #else
  98509. (void)value;
  98510. #endif
  98511. return true;
  98512. }
  98513. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98514. {
  98515. FLAC__ASSERT(0 != encoder);
  98516. FLAC__ASSERT(0 != encoder->private_);
  98517. FLAC__ASSERT(0 != encoder->protected_);
  98518. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98519. return false;
  98520. encoder->protected_->do_exhaustive_model_search = value;
  98521. return true;
  98522. }
  98523. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  98524. {
  98525. FLAC__ASSERT(0 != encoder);
  98526. FLAC__ASSERT(0 != encoder->private_);
  98527. FLAC__ASSERT(0 != encoder->protected_);
  98528. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98529. return false;
  98530. encoder->protected_->min_residual_partition_order = value;
  98531. return true;
  98532. }
  98533. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  98534. {
  98535. FLAC__ASSERT(0 != encoder);
  98536. FLAC__ASSERT(0 != encoder->private_);
  98537. FLAC__ASSERT(0 != encoder->protected_);
  98538. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98539. return false;
  98540. encoder->protected_->max_residual_partition_order = value;
  98541. return true;
  98542. }
  98543. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  98544. {
  98545. FLAC__ASSERT(0 != encoder);
  98546. FLAC__ASSERT(0 != encoder->private_);
  98547. FLAC__ASSERT(0 != encoder->protected_);
  98548. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98549. return false;
  98550. #if 0
  98551. /*@@@ deprecated: */
  98552. encoder->protected_->rice_parameter_search_dist = value;
  98553. #else
  98554. (void)value;
  98555. #endif
  98556. return true;
  98557. }
  98558. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  98559. {
  98560. FLAC__ASSERT(0 != encoder);
  98561. FLAC__ASSERT(0 != encoder->private_);
  98562. FLAC__ASSERT(0 != encoder->protected_);
  98563. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98564. return false;
  98565. encoder->protected_->total_samples_estimate = value;
  98566. return true;
  98567. }
  98568. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  98569. {
  98570. FLAC__ASSERT(0 != encoder);
  98571. FLAC__ASSERT(0 != encoder->private_);
  98572. FLAC__ASSERT(0 != encoder->protected_);
  98573. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98574. return false;
  98575. if(0 == metadata)
  98576. num_blocks = 0;
  98577. if(0 == num_blocks)
  98578. metadata = 0;
  98579. /* realloc() does not do exactly what we want so... */
  98580. if(encoder->protected_->metadata) {
  98581. free(encoder->protected_->metadata);
  98582. encoder->protected_->metadata = 0;
  98583. encoder->protected_->num_metadata_blocks = 0;
  98584. }
  98585. if(num_blocks) {
  98586. FLAC__StreamMetadata **m;
  98587. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  98588. return false;
  98589. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  98590. encoder->protected_->metadata = m;
  98591. encoder->protected_->num_metadata_blocks = num_blocks;
  98592. }
  98593. #if FLAC__HAS_OGG
  98594. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  98595. return false;
  98596. #endif
  98597. return true;
  98598. }
  98599. /*
  98600. * These three functions are not static, but not publically exposed in
  98601. * include/FLAC/ either. They are used by the test suite.
  98602. */
  98603. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98604. {
  98605. FLAC__ASSERT(0 != encoder);
  98606. FLAC__ASSERT(0 != encoder->private_);
  98607. FLAC__ASSERT(0 != encoder->protected_);
  98608. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98609. return false;
  98610. encoder->private_->disable_constant_subframes = value;
  98611. return true;
  98612. }
  98613. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98614. {
  98615. FLAC__ASSERT(0 != encoder);
  98616. FLAC__ASSERT(0 != encoder->private_);
  98617. FLAC__ASSERT(0 != encoder->protected_);
  98618. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98619. return false;
  98620. encoder->private_->disable_fixed_subframes = value;
  98621. return true;
  98622. }
  98623. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98624. {
  98625. FLAC__ASSERT(0 != encoder);
  98626. FLAC__ASSERT(0 != encoder->private_);
  98627. FLAC__ASSERT(0 != encoder->protected_);
  98628. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98629. return false;
  98630. encoder->private_->disable_verbatim_subframes = value;
  98631. return true;
  98632. }
  98633. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  98634. {
  98635. FLAC__ASSERT(0 != encoder);
  98636. FLAC__ASSERT(0 != encoder->private_);
  98637. FLAC__ASSERT(0 != encoder->protected_);
  98638. return encoder->protected_->state;
  98639. }
  98640. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  98641. {
  98642. FLAC__ASSERT(0 != encoder);
  98643. FLAC__ASSERT(0 != encoder->private_);
  98644. FLAC__ASSERT(0 != encoder->protected_);
  98645. if(encoder->protected_->verify)
  98646. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  98647. else
  98648. return FLAC__STREAM_DECODER_UNINITIALIZED;
  98649. }
  98650. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  98651. {
  98652. FLAC__ASSERT(0 != encoder);
  98653. FLAC__ASSERT(0 != encoder->private_);
  98654. FLAC__ASSERT(0 != encoder->protected_);
  98655. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  98656. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  98657. else
  98658. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  98659. }
  98660. 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)
  98661. {
  98662. FLAC__ASSERT(0 != encoder);
  98663. FLAC__ASSERT(0 != encoder->private_);
  98664. FLAC__ASSERT(0 != encoder->protected_);
  98665. if(0 != absolute_sample)
  98666. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  98667. if(0 != frame_number)
  98668. *frame_number = encoder->private_->verify.error_stats.frame_number;
  98669. if(0 != channel)
  98670. *channel = encoder->private_->verify.error_stats.channel;
  98671. if(0 != sample)
  98672. *sample = encoder->private_->verify.error_stats.sample;
  98673. if(0 != expected)
  98674. *expected = encoder->private_->verify.error_stats.expected;
  98675. if(0 != got)
  98676. *got = encoder->private_->verify.error_stats.got;
  98677. }
  98678. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  98679. {
  98680. FLAC__ASSERT(0 != encoder);
  98681. FLAC__ASSERT(0 != encoder->private_);
  98682. FLAC__ASSERT(0 != encoder->protected_);
  98683. return encoder->protected_->verify;
  98684. }
  98685. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  98686. {
  98687. FLAC__ASSERT(0 != encoder);
  98688. FLAC__ASSERT(0 != encoder->private_);
  98689. FLAC__ASSERT(0 != encoder->protected_);
  98690. return encoder->protected_->streamable_subset;
  98691. }
  98692. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  98693. {
  98694. FLAC__ASSERT(0 != encoder);
  98695. FLAC__ASSERT(0 != encoder->private_);
  98696. FLAC__ASSERT(0 != encoder->protected_);
  98697. return encoder->protected_->do_md5;
  98698. }
  98699. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  98700. {
  98701. FLAC__ASSERT(0 != encoder);
  98702. FLAC__ASSERT(0 != encoder->private_);
  98703. FLAC__ASSERT(0 != encoder->protected_);
  98704. return encoder->protected_->channels;
  98705. }
  98706. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  98707. {
  98708. FLAC__ASSERT(0 != encoder);
  98709. FLAC__ASSERT(0 != encoder->private_);
  98710. FLAC__ASSERT(0 != encoder->protected_);
  98711. return encoder->protected_->bits_per_sample;
  98712. }
  98713. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  98714. {
  98715. FLAC__ASSERT(0 != encoder);
  98716. FLAC__ASSERT(0 != encoder->private_);
  98717. FLAC__ASSERT(0 != encoder->protected_);
  98718. return encoder->protected_->sample_rate;
  98719. }
  98720. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  98721. {
  98722. FLAC__ASSERT(0 != encoder);
  98723. FLAC__ASSERT(0 != encoder->private_);
  98724. FLAC__ASSERT(0 != encoder->protected_);
  98725. return encoder->protected_->blocksize;
  98726. }
  98727. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  98728. {
  98729. FLAC__ASSERT(0 != encoder);
  98730. FLAC__ASSERT(0 != encoder->private_);
  98731. FLAC__ASSERT(0 != encoder->protected_);
  98732. return encoder->protected_->do_mid_side_stereo;
  98733. }
  98734. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  98735. {
  98736. FLAC__ASSERT(0 != encoder);
  98737. FLAC__ASSERT(0 != encoder->private_);
  98738. FLAC__ASSERT(0 != encoder->protected_);
  98739. return encoder->protected_->loose_mid_side_stereo;
  98740. }
  98741. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  98742. {
  98743. FLAC__ASSERT(0 != encoder);
  98744. FLAC__ASSERT(0 != encoder->private_);
  98745. FLAC__ASSERT(0 != encoder->protected_);
  98746. return encoder->protected_->max_lpc_order;
  98747. }
  98748. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  98749. {
  98750. FLAC__ASSERT(0 != encoder);
  98751. FLAC__ASSERT(0 != encoder->private_);
  98752. FLAC__ASSERT(0 != encoder->protected_);
  98753. return encoder->protected_->qlp_coeff_precision;
  98754. }
  98755. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  98756. {
  98757. FLAC__ASSERT(0 != encoder);
  98758. FLAC__ASSERT(0 != encoder->private_);
  98759. FLAC__ASSERT(0 != encoder->protected_);
  98760. return encoder->protected_->do_qlp_coeff_prec_search;
  98761. }
  98762. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  98763. {
  98764. FLAC__ASSERT(0 != encoder);
  98765. FLAC__ASSERT(0 != encoder->private_);
  98766. FLAC__ASSERT(0 != encoder->protected_);
  98767. return encoder->protected_->do_escape_coding;
  98768. }
  98769. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  98770. {
  98771. FLAC__ASSERT(0 != encoder);
  98772. FLAC__ASSERT(0 != encoder->private_);
  98773. FLAC__ASSERT(0 != encoder->protected_);
  98774. return encoder->protected_->do_exhaustive_model_search;
  98775. }
  98776. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  98777. {
  98778. FLAC__ASSERT(0 != encoder);
  98779. FLAC__ASSERT(0 != encoder->private_);
  98780. FLAC__ASSERT(0 != encoder->protected_);
  98781. return encoder->protected_->min_residual_partition_order;
  98782. }
  98783. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  98784. {
  98785. FLAC__ASSERT(0 != encoder);
  98786. FLAC__ASSERT(0 != encoder->private_);
  98787. FLAC__ASSERT(0 != encoder->protected_);
  98788. return encoder->protected_->max_residual_partition_order;
  98789. }
  98790. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  98791. {
  98792. FLAC__ASSERT(0 != encoder);
  98793. FLAC__ASSERT(0 != encoder->private_);
  98794. FLAC__ASSERT(0 != encoder->protected_);
  98795. return encoder->protected_->rice_parameter_search_dist;
  98796. }
  98797. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  98798. {
  98799. FLAC__ASSERT(0 != encoder);
  98800. FLAC__ASSERT(0 != encoder->private_);
  98801. FLAC__ASSERT(0 != encoder->protected_);
  98802. return encoder->protected_->total_samples_estimate;
  98803. }
  98804. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  98805. {
  98806. unsigned i, j = 0, channel;
  98807. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  98808. FLAC__ASSERT(0 != encoder);
  98809. FLAC__ASSERT(0 != encoder->private_);
  98810. FLAC__ASSERT(0 != encoder->protected_);
  98811. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98812. do {
  98813. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  98814. if(encoder->protected_->verify)
  98815. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  98816. for(channel = 0; channel < channels; channel++)
  98817. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  98818. if(encoder->protected_->do_mid_side_stereo) {
  98819. FLAC__ASSERT(channels == 2);
  98820. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  98821. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  98822. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  98823. 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' ! */
  98824. }
  98825. }
  98826. else
  98827. j += n;
  98828. encoder->private_->current_sample_number += n;
  98829. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  98830. if(encoder->private_->current_sample_number > blocksize) {
  98831. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  98832. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  98833. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  98834. return false;
  98835. /* move unprocessed overread samples to beginnings of arrays */
  98836. for(channel = 0; channel < channels; channel++)
  98837. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  98838. if(encoder->protected_->do_mid_side_stereo) {
  98839. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  98840. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  98841. }
  98842. encoder->private_->current_sample_number = 1;
  98843. }
  98844. } while(j < samples);
  98845. return true;
  98846. }
  98847. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  98848. {
  98849. unsigned i, j, k, channel;
  98850. FLAC__int32 x, mid, side;
  98851. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  98852. FLAC__ASSERT(0 != encoder);
  98853. FLAC__ASSERT(0 != encoder->private_);
  98854. FLAC__ASSERT(0 != encoder->protected_);
  98855. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98856. j = k = 0;
  98857. /*
  98858. * we have several flavors of the same basic loop, optimized for
  98859. * different conditions:
  98860. */
  98861. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  98862. /*
  98863. * stereo coding: unroll channel loop
  98864. */
  98865. do {
  98866. if(encoder->protected_->verify)
  98867. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  98868. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  98869. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  98870. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  98871. x = buffer[k++];
  98872. encoder->private_->integer_signal[1][i] = x;
  98873. mid += x;
  98874. side -= x;
  98875. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  98876. encoder->private_->integer_signal_mid_side[1][i] = side;
  98877. encoder->private_->integer_signal_mid_side[0][i] = mid;
  98878. }
  98879. encoder->private_->current_sample_number = i;
  98880. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  98881. if(i > blocksize) {
  98882. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  98883. return false;
  98884. /* move unprocessed overread samples to beginnings of arrays */
  98885. FLAC__ASSERT(i == blocksize+OVERREAD_);
  98886. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  98887. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  98888. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  98889. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  98890. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  98891. encoder->private_->current_sample_number = 1;
  98892. }
  98893. } while(j < samples);
  98894. }
  98895. else {
  98896. /*
  98897. * independent channel coding: buffer each channel in inner loop
  98898. */
  98899. do {
  98900. if(encoder->protected_->verify)
  98901. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  98902. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  98903. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  98904. for(channel = 0; channel < channels; channel++)
  98905. encoder->private_->integer_signal[channel][i] = buffer[k++];
  98906. }
  98907. encoder->private_->current_sample_number = i;
  98908. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  98909. if(i > blocksize) {
  98910. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  98911. return false;
  98912. /* move unprocessed overread samples to beginnings of arrays */
  98913. FLAC__ASSERT(i == blocksize+OVERREAD_);
  98914. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  98915. for(channel = 0; channel < channels; channel++)
  98916. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  98917. encoder->private_->current_sample_number = 1;
  98918. }
  98919. } while(j < samples);
  98920. }
  98921. return true;
  98922. }
  98923. /***********************************************************************
  98924. *
  98925. * Private class methods
  98926. *
  98927. ***********************************************************************/
  98928. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  98929. {
  98930. FLAC__ASSERT(0 != encoder);
  98931. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  98932. encoder->protected_->verify = true;
  98933. #else
  98934. encoder->protected_->verify = false;
  98935. #endif
  98936. encoder->protected_->streamable_subset = true;
  98937. encoder->protected_->do_md5 = true;
  98938. encoder->protected_->do_mid_side_stereo = false;
  98939. encoder->protected_->loose_mid_side_stereo = false;
  98940. encoder->protected_->channels = 2;
  98941. encoder->protected_->bits_per_sample = 16;
  98942. encoder->protected_->sample_rate = 44100;
  98943. encoder->protected_->blocksize = 0;
  98944. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98945. encoder->protected_->num_apodizations = 1;
  98946. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  98947. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  98948. #endif
  98949. encoder->protected_->max_lpc_order = 0;
  98950. encoder->protected_->qlp_coeff_precision = 0;
  98951. encoder->protected_->do_qlp_coeff_prec_search = false;
  98952. encoder->protected_->do_exhaustive_model_search = false;
  98953. encoder->protected_->do_escape_coding = false;
  98954. encoder->protected_->min_residual_partition_order = 0;
  98955. encoder->protected_->max_residual_partition_order = 0;
  98956. encoder->protected_->rice_parameter_search_dist = 0;
  98957. encoder->protected_->total_samples_estimate = 0;
  98958. encoder->protected_->metadata = 0;
  98959. encoder->protected_->num_metadata_blocks = 0;
  98960. encoder->private_->seek_table = 0;
  98961. encoder->private_->disable_constant_subframes = false;
  98962. encoder->private_->disable_fixed_subframes = false;
  98963. encoder->private_->disable_verbatim_subframes = false;
  98964. #if FLAC__HAS_OGG
  98965. encoder->private_->is_ogg = false;
  98966. #endif
  98967. encoder->private_->read_callback = 0;
  98968. encoder->private_->write_callback = 0;
  98969. encoder->private_->seek_callback = 0;
  98970. encoder->private_->tell_callback = 0;
  98971. encoder->private_->metadata_callback = 0;
  98972. encoder->private_->progress_callback = 0;
  98973. encoder->private_->client_data = 0;
  98974. #if FLAC__HAS_OGG
  98975. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  98976. #endif
  98977. }
  98978. void free_(FLAC__StreamEncoder *encoder)
  98979. {
  98980. unsigned i, channel;
  98981. FLAC__ASSERT(0 != encoder);
  98982. if(encoder->protected_->metadata) {
  98983. free(encoder->protected_->metadata);
  98984. encoder->protected_->metadata = 0;
  98985. encoder->protected_->num_metadata_blocks = 0;
  98986. }
  98987. for(i = 0; i < encoder->protected_->channels; i++) {
  98988. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  98989. free(encoder->private_->integer_signal_unaligned[i]);
  98990. encoder->private_->integer_signal_unaligned[i] = 0;
  98991. }
  98992. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98993. if(0 != encoder->private_->real_signal_unaligned[i]) {
  98994. free(encoder->private_->real_signal_unaligned[i]);
  98995. encoder->private_->real_signal_unaligned[i] = 0;
  98996. }
  98997. #endif
  98998. }
  98999. for(i = 0; i < 2; i++) {
  99000. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  99001. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  99002. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  99003. }
  99004. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99005. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  99006. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  99007. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  99008. }
  99009. #endif
  99010. }
  99011. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99012. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  99013. if(0 != encoder->private_->window_unaligned[i]) {
  99014. free(encoder->private_->window_unaligned[i]);
  99015. encoder->private_->window_unaligned[i] = 0;
  99016. }
  99017. }
  99018. if(0 != encoder->private_->windowed_signal_unaligned) {
  99019. free(encoder->private_->windowed_signal_unaligned);
  99020. encoder->private_->windowed_signal_unaligned = 0;
  99021. }
  99022. #endif
  99023. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  99024. for(i = 0; i < 2; i++) {
  99025. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  99026. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  99027. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  99028. }
  99029. }
  99030. }
  99031. for(channel = 0; channel < 2; channel++) {
  99032. for(i = 0; i < 2; i++) {
  99033. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  99034. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  99035. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  99036. }
  99037. }
  99038. }
  99039. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  99040. free(encoder->private_->abs_residual_partition_sums_unaligned);
  99041. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  99042. }
  99043. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  99044. free(encoder->private_->raw_bits_per_partition_unaligned);
  99045. encoder->private_->raw_bits_per_partition_unaligned = 0;
  99046. }
  99047. if(encoder->protected_->verify) {
  99048. for(i = 0; i < encoder->protected_->channels; i++) {
  99049. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  99050. free(encoder->private_->verify.input_fifo.data[i]);
  99051. encoder->private_->verify.input_fifo.data[i] = 0;
  99052. }
  99053. }
  99054. }
  99055. FLAC__bitwriter_free(encoder->private_->frame);
  99056. }
  99057. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  99058. {
  99059. FLAC__bool ok;
  99060. unsigned i, channel;
  99061. FLAC__ASSERT(new_blocksize > 0);
  99062. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99063. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  99064. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  99065. if(new_blocksize <= encoder->private_->input_capacity)
  99066. return true;
  99067. ok = true;
  99068. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  99069. * requires that the input arrays (in our case the integer signals)
  99070. * have a buffer of up to 3 zeroes in front (at negative indices) for
  99071. * alignment purposes; we use 4 in front to keep the data well-aligned.
  99072. */
  99073. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  99074. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  99075. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  99076. encoder->private_->integer_signal[i] += 4;
  99077. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99078. #if 0 /* @@@ currently unused */
  99079. if(encoder->protected_->max_lpc_order > 0)
  99080. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  99081. #endif
  99082. #endif
  99083. }
  99084. for(i = 0; ok && i < 2; i++) {
  99085. 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]);
  99086. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  99087. encoder->private_->integer_signal_mid_side[i] += 4;
  99088. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99089. #if 0 /* @@@ currently unused */
  99090. if(encoder->protected_->max_lpc_order > 0)
  99091. 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]);
  99092. #endif
  99093. #endif
  99094. }
  99095. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99096. if(ok && encoder->protected_->max_lpc_order > 0) {
  99097. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  99098. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  99099. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  99100. }
  99101. #endif
  99102. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  99103. for(i = 0; ok && i < 2; i++) {
  99104. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  99105. }
  99106. }
  99107. for(channel = 0; ok && channel < 2; channel++) {
  99108. for(i = 0; ok && i < 2; i++) {
  99109. 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]);
  99110. }
  99111. }
  99112. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  99113. /*@@@ 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) */
  99114. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  99115. if(encoder->protected_->do_escape_coding)
  99116. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  99117. /* now adjust the windows if the blocksize has changed */
  99118. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99119. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  99120. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  99121. switch(encoder->protected_->apodizations[i].type) {
  99122. case FLAC__APODIZATION_BARTLETT:
  99123. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  99124. break;
  99125. case FLAC__APODIZATION_BARTLETT_HANN:
  99126. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  99127. break;
  99128. case FLAC__APODIZATION_BLACKMAN:
  99129. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  99130. break;
  99131. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  99132. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  99133. break;
  99134. case FLAC__APODIZATION_CONNES:
  99135. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  99136. break;
  99137. case FLAC__APODIZATION_FLATTOP:
  99138. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  99139. break;
  99140. case FLAC__APODIZATION_GAUSS:
  99141. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  99142. break;
  99143. case FLAC__APODIZATION_HAMMING:
  99144. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  99145. break;
  99146. case FLAC__APODIZATION_HANN:
  99147. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  99148. break;
  99149. case FLAC__APODIZATION_KAISER_BESSEL:
  99150. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  99151. break;
  99152. case FLAC__APODIZATION_NUTTALL:
  99153. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  99154. break;
  99155. case FLAC__APODIZATION_RECTANGLE:
  99156. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  99157. break;
  99158. case FLAC__APODIZATION_TRIANGLE:
  99159. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  99160. break;
  99161. case FLAC__APODIZATION_TUKEY:
  99162. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  99163. break;
  99164. case FLAC__APODIZATION_WELCH:
  99165. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  99166. break;
  99167. default:
  99168. FLAC__ASSERT(0);
  99169. /* double protection */
  99170. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  99171. break;
  99172. }
  99173. }
  99174. }
  99175. #endif
  99176. if(ok)
  99177. encoder->private_->input_capacity = new_blocksize;
  99178. else
  99179. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99180. return ok;
  99181. }
  99182. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  99183. {
  99184. const FLAC__byte *buffer;
  99185. size_t bytes;
  99186. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  99187. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  99188. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99189. return false;
  99190. }
  99191. if(encoder->protected_->verify) {
  99192. encoder->private_->verify.output.data = buffer;
  99193. encoder->private_->verify.output.bytes = bytes;
  99194. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  99195. encoder->private_->verify.needs_magic_hack = true;
  99196. }
  99197. else {
  99198. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  99199. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  99200. FLAC__bitwriter_clear(encoder->private_->frame);
  99201. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  99202. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  99203. return false;
  99204. }
  99205. }
  99206. }
  99207. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99208. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  99209. FLAC__bitwriter_clear(encoder->private_->frame);
  99210. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99211. return false;
  99212. }
  99213. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  99214. FLAC__bitwriter_clear(encoder->private_->frame);
  99215. if(samples > 0) {
  99216. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  99217. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  99218. }
  99219. return true;
  99220. }
  99221. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  99222. {
  99223. FLAC__StreamEncoderWriteStatus status;
  99224. FLAC__uint64 output_position = 0;
  99225. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  99226. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  99227. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99228. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  99229. }
  99230. /*
  99231. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  99232. */
  99233. if(samples == 0) {
  99234. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  99235. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  99236. encoder->protected_->streaminfo_offset = output_position;
  99237. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  99238. encoder->protected_->seektable_offset = output_position;
  99239. }
  99240. /*
  99241. * Mark the current seek point if hit (if audio_offset == 0 that
  99242. * means we're still writing metadata and haven't hit the first
  99243. * frame yet)
  99244. */
  99245. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  99246. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  99247. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  99248. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  99249. FLAC__uint64 test_sample;
  99250. unsigned i;
  99251. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  99252. test_sample = encoder->private_->seek_table->points[i].sample_number;
  99253. if(test_sample > frame_last_sample) {
  99254. break;
  99255. }
  99256. else if(test_sample >= frame_first_sample) {
  99257. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  99258. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  99259. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  99260. encoder->private_->first_seekpoint_to_check++;
  99261. /* DO NOT: "break;" and here's why:
  99262. * The seektable template may contain more than one target
  99263. * sample for any given frame; we will keep looping, generating
  99264. * duplicate seekpoints for them, and we'll clean it up later,
  99265. * just before writing the seektable back to the metadata.
  99266. */
  99267. }
  99268. else {
  99269. encoder->private_->first_seekpoint_to_check++;
  99270. }
  99271. }
  99272. }
  99273. #if FLAC__HAS_OGG
  99274. if(encoder->private_->is_ogg) {
  99275. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  99276. &encoder->protected_->ogg_encoder_aspect,
  99277. buffer,
  99278. bytes,
  99279. samples,
  99280. encoder->private_->current_frame_number,
  99281. is_last_block,
  99282. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  99283. encoder,
  99284. encoder->private_->client_data
  99285. );
  99286. }
  99287. else
  99288. #endif
  99289. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  99290. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99291. encoder->private_->bytes_written += bytes;
  99292. encoder->private_->samples_written += samples;
  99293. /* we keep a high watermark on the number of frames written because
  99294. * when the encoder goes back to write metadata, 'current_frame'
  99295. * will drop back to 0.
  99296. */
  99297. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  99298. }
  99299. else
  99300. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99301. return status;
  99302. }
  99303. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  99304. void update_metadata_(const FLAC__StreamEncoder *encoder)
  99305. {
  99306. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  99307. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  99308. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  99309. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  99310. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  99311. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  99312. FLAC__StreamEncoderSeekStatus seek_status;
  99313. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  99314. /* All this is based on intimate knowledge of the stream header
  99315. * layout, but a change to the header format that would break this
  99316. * would also break all streams encoded in the previous format.
  99317. */
  99318. /*
  99319. * Write MD5 signature
  99320. */
  99321. {
  99322. const unsigned md5_offset =
  99323. FLAC__STREAM_METADATA_HEADER_LENGTH +
  99324. (
  99325. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  99326. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  99327. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  99328. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  99329. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  99330. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  99331. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  99332. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  99333. ) / 8;
  99334. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  99335. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  99336. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99337. return;
  99338. }
  99339. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99340. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99341. return;
  99342. }
  99343. }
  99344. /*
  99345. * Write total samples
  99346. */
  99347. {
  99348. const unsigned total_samples_byte_offset =
  99349. FLAC__STREAM_METADATA_HEADER_LENGTH +
  99350. (
  99351. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  99352. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  99353. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  99354. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  99355. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  99356. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  99357. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  99358. - 4
  99359. ) / 8;
  99360. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  99361. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  99362. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  99363. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  99364. b[4] = (FLAC__byte)(samples & 0xFF);
  99365. 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) {
  99366. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  99367. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99368. return;
  99369. }
  99370. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99371. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99372. return;
  99373. }
  99374. }
  99375. /*
  99376. * Write min/max framesize
  99377. */
  99378. {
  99379. const unsigned min_framesize_offset =
  99380. FLAC__STREAM_METADATA_HEADER_LENGTH +
  99381. (
  99382. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  99383. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  99384. ) / 8;
  99385. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  99386. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  99387. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  99388. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  99389. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  99390. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  99391. 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) {
  99392. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  99393. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99394. return;
  99395. }
  99396. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99397. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99398. return;
  99399. }
  99400. }
  99401. /*
  99402. * Write seektable
  99403. */
  99404. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  99405. unsigned i;
  99406. FLAC__format_seektable_sort(encoder->private_->seek_table);
  99407. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  99408. 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) {
  99409. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  99410. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99411. return;
  99412. }
  99413. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  99414. FLAC__uint64 xx;
  99415. unsigned x;
  99416. xx = encoder->private_->seek_table->points[i].sample_number;
  99417. b[7] = (FLAC__byte)xx; xx >>= 8;
  99418. b[6] = (FLAC__byte)xx; xx >>= 8;
  99419. b[5] = (FLAC__byte)xx; xx >>= 8;
  99420. b[4] = (FLAC__byte)xx; xx >>= 8;
  99421. b[3] = (FLAC__byte)xx; xx >>= 8;
  99422. b[2] = (FLAC__byte)xx; xx >>= 8;
  99423. b[1] = (FLAC__byte)xx; xx >>= 8;
  99424. b[0] = (FLAC__byte)xx; xx >>= 8;
  99425. xx = encoder->private_->seek_table->points[i].stream_offset;
  99426. b[15] = (FLAC__byte)xx; xx >>= 8;
  99427. b[14] = (FLAC__byte)xx; xx >>= 8;
  99428. b[13] = (FLAC__byte)xx; xx >>= 8;
  99429. b[12] = (FLAC__byte)xx; xx >>= 8;
  99430. b[11] = (FLAC__byte)xx; xx >>= 8;
  99431. b[10] = (FLAC__byte)xx; xx >>= 8;
  99432. b[9] = (FLAC__byte)xx; xx >>= 8;
  99433. b[8] = (FLAC__byte)xx; xx >>= 8;
  99434. x = encoder->private_->seek_table->points[i].frame_samples;
  99435. b[17] = (FLAC__byte)x; x >>= 8;
  99436. b[16] = (FLAC__byte)x; x >>= 8;
  99437. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99438. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99439. return;
  99440. }
  99441. }
  99442. }
  99443. }
  99444. #if FLAC__HAS_OGG
  99445. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  99446. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  99447. {
  99448. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  99449. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  99450. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  99451. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  99452. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  99453. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  99454. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  99455. FLAC__STREAM_SYNC_LENGTH
  99456. ;
  99457. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  99458. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  99459. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  99460. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  99461. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  99462. ogg_page page;
  99463. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  99464. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  99465. /* Pre-check that client supports seeking, since we don't want the
  99466. * ogg_helper code to ever have to deal with this condition.
  99467. */
  99468. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  99469. return;
  99470. /* All this is based on intimate knowledge of the stream header
  99471. * layout, but a change to the header format that would break this
  99472. * would also break all streams encoded in the previous format.
  99473. */
  99474. /**
  99475. ** Write STREAMINFO stats
  99476. **/
  99477. simple_ogg_page__init(&page);
  99478. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  99479. simple_ogg_page__clear(&page);
  99480. return; /* state already set */
  99481. }
  99482. /*
  99483. * Write MD5 signature
  99484. */
  99485. {
  99486. const unsigned md5_offset =
  99487. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  99488. FLAC__STREAM_METADATA_HEADER_LENGTH +
  99489. (
  99490. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  99491. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  99492. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  99493. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  99494. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  99495. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  99496. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  99497. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  99498. ) / 8;
  99499. if(md5_offset + 16 > (unsigned)page.body_len) {
  99500. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  99501. simple_ogg_page__clear(&page);
  99502. return;
  99503. }
  99504. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  99505. }
  99506. /*
  99507. * Write total samples
  99508. */
  99509. {
  99510. const unsigned total_samples_byte_offset =
  99511. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  99512. FLAC__STREAM_METADATA_HEADER_LENGTH +
  99513. (
  99514. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  99515. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  99516. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  99517. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  99518. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  99519. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  99520. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  99521. - 4
  99522. ) / 8;
  99523. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  99524. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  99525. simple_ogg_page__clear(&page);
  99526. return;
  99527. }
  99528. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  99529. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  99530. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  99531. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  99532. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  99533. b[4] = (FLAC__byte)(samples & 0xFF);
  99534. memcpy(page.body + total_samples_byte_offset, b, 5);
  99535. }
  99536. /*
  99537. * Write min/max framesize
  99538. */
  99539. {
  99540. const unsigned min_framesize_offset =
  99541. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  99542. FLAC__STREAM_METADATA_HEADER_LENGTH +
  99543. (
  99544. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  99545. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  99546. ) / 8;
  99547. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  99548. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  99549. simple_ogg_page__clear(&page);
  99550. return;
  99551. }
  99552. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  99553. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  99554. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  99555. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  99556. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  99557. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  99558. memcpy(page.body + min_framesize_offset, b, 6);
  99559. }
  99560. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  99561. simple_ogg_page__clear(&page);
  99562. return; /* state already set */
  99563. }
  99564. simple_ogg_page__clear(&page);
  99565. /*
  99566. * Write seektable
  99567. */
  99568. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  99569. unsigned i;
  99570. FLAC__byte *p;
  99571. FLAC__format_seektable_sort(encoder->private_->seek_table);
  99572. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  99573. simple_ogg_page__init(&page);
  99574. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  99575. simple_ogg_page__clear(&page);
  99576. return; /* state already set */
  99577. }
  99578. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  99579. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  99580. simple_ogg_page__clear(&page);
  99581. return;
  99582. }
  99583. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  99584. FLAC__uint64 xx;
  99585. unsigned x;
  99586. xx = encoder->private_->seek_table->points[i].sample_number;
  99587. b[7] = (FLAC__byte)xx; xx >>= 8;
  99588. b[6] = (FLAC__byte)xx; xx >>= 8;
  99589. b[5] = (FLAC__byte)xx; xx >>= 8;
  99590. b[4] = (FLAC__byte)xx; xx >>= 8;
  99591. b[3] = (FLAC__byte)xx; xx >>= 8;
  99592. b[2] = (FLAC__byte)xx; xx >>= 8;
  99593. b[1] = (FLAC__byte)xx; xx >>= 8;
  99594. b[0] = (FLAC__byte)xx; xx >>= 8;
  99595. xx = encoder->private_->seek_table->points[i].stream_offset;
  99596. b[15] = (FLAC__byte)xx; xx >>= 8;
  99597. b[14] = (FLAC__byte)xx; xx >>= 8;
  99598. b[13] = (FLAC__byte)xx; xx >>= 8;
  99599. b[12] = (FLAC__byte)xx; xx >>= 8;
  99600. b[11] = (FLAC__byte)xx; xx >>= 8;
  99601. b[10] = (FLAC__byte)xx; xx >>= 8;
  99602. b[9] = (FLAC__byte)xx; xx >>= 8;
  99603. b[8] = (FLAC__byte)xx; xx >>= 8;
  99604. x = encoder->private_->seek_table->points[i].frame_samples;
  99605. b[17] = (FLAC__byte)x; x >>= 8;
  99606. b[16] = (FLAC__byte)x; x >>= 8;
  99607. memcpy(p, b, 18);
  99608. }
  99609. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  99610. simple_ogg_page__clear(&page);
  99611. return; /* state already set */
  99612. }
  99613. simple_ogg_page__clear(&page);
  99614. }
  99615. }
  99616. #endif
  99617. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  99618. {
  99619. FLAC__uint16 crc;
  99620. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99621. /*
  99622. * Accumulate raw signal to the MD5 signature
  99623. */
  99624. 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)) {
  99625. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99626. return false;
  99627. }
  99628. /*
  99629. * Process the frame header and subframes into the frame bitbuffer
  99630. */
  99631. if(!process_subframes_(encoder, is_fractional_block)) {
  99632. /* the above function sets the state for us in case of an error */
  99633. return false;
  99634. }
  99635. /*
  99636. * Zero-pad the frame to a byte_boundary
  99637. */
  99638. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  99639. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99640. return false;
  99641. }
  99642. /*
  99643. * CRC-16 the whole thing
  99644. */
  99645. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  99646. if(
  99647. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  99648. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  99649. ) {
  99650. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99651. return false;
  99652. }
  99653. /*
  99654. * Write it
  99655. */
  99656. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  99657. /* the above function sets the state for us in case of an error */
  99658. return false;
  99659. }
  99660. /*
  99661. * Get ready for the next frame
  99662. */
  99663. encoder->private_->current_sample_number = 0;
  99664. encoder->private_->current_frame_number++;
  99665. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  99666. return true;
  99667. }
  99668. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  99669. {
  99670. FLAC__FrameHeader frame_header;
  99671. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  99672. FLAC__bool do_independent, do_mid_side;
  99673. /*
  99674. * Calculate the min,max Rice partition orders
  99675. */
  99676. if(is_fractional_block) {
  99677. max_partition_order = 0;
  99678. }
  99679. else {
  99680. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  99681. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  99682. }
  99683. min_partition_order = min(min_partition_order, max_partition_order);
  99684. /*
  99685. * Setup the frame
  99686. */
  99687. frame_header.blocksize = encoder->protected_->blocksize;
  99688. frame_header.sample_rate = encoder->protected_->sample_rate;
  99689. frame_header.channels = encoder->protected_->channels;
  99690. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  99691. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  99692. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  99693. frame_header.number.frame_number = encoder->private_->current_frame_number;
  99694. /*
  99695. * Figure out what channel assignments to try
  99696. */
  99697. if(encoder->protected_->do_mid_side_stereo) {
  99698. if(encoder->protected_->loose_mid_side_stereo) {
  99699. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  99700. do_independent = true;
  99701. do_mid_side = true;
  99702. }
  99703. else {
  99704. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  99705. do_mid_side = !do_independent;
  99706. }
  99707. }
  99708. else {
  99709. do_independent = true;
  99710. do_mid_side = true;
  99711. }
  99712. }
  99713. else {
  99714. do_independent = true;
  99715. do_mid_side = false;
  99716. }
  99717. FLAC__ASSERT(do_independent || do_mid_side);
  99718. /*
  99719. * Check for wasted bits; set effective bps for each subframe
  99720. */
  99721. if(do_independent) {
  99722. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  99723. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  99724. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  99725. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  99726. }
  99727. }
  99728. if(do_mid_side) {
  99729. FLAC__ASSERT(encoder->protected_->channels == 2);
  99730. for(channel = 0; channel < 2; channel++) {
  99731. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  99732. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  99733. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  99734. }
  99735. }
  99736. /*
  99737. * First do a normal encoding pass of each independent channel
  99738. */
  99739. if(do_independent) {
  99740. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  99741. if(!
  99742. process_subframe_(
  99743. encoder,
  99744. min_partition_order,
  99745. max_partition_order,
  99746. &frame_header,
  99747. encoder->private_->subframe_bps[channel],
  99748. encoder->private_->integer_signal[channel],
  99749. encoder->private_->subframe_workspace_ptr[channel],
  99750. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  99751. encoder->private_->residual_workspace[channel],
  99752. encoder->private_->best_subframe+channel,
  99753. encoder->private_->best_subframe_bits+channel
  99754. )
  99755. )
  99756. return false;
  99757. }
  99758. }
  99759. /*
  99760. * Now do mid and side channels if requested
  99761. */
  99762. if(do_mid_side) {
  99763. FLAC__ASSERT(encoder->protected_->channels == 2);
  99764. for(channel = 0; channel < 2; channel++) {
  99765. if(!
  99766. process_subframe_(
  99767. encoder,
  99768. min_partition_order,
  99769. max_partition_order,
  99770. &frame_header,
  99771. encoder->private_->subframe_bps_mid_side[channel],
  99772. encoder->private_->integer_signal_mid_side[channel],
  99773. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  99774. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  99775. encoder->private_->residual_workspace_mid_side[channel],
  99776. encoder->private_->best_subframe_mid_side+channel,
  99777. encoder->private_->best_subframe_bits_mid_side+channel
  99778. )
  99779. )
  99780. return false;
  99781. }
  99782. }
  99783. /*
  99784. * Compose the frame bitbuffer
  99785. */
  99786. if(do_mid_side) {
  99787. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  99788. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  99789. FLAC__ChannelAssignment channel_assignment;
  99790. FLAC__ASSERT(encoder->protected_->channels == 2);
  99791. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  99792. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  99793. }
  99794. else {
  99795. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  99796. unsigned min_bits;
  99797. int ca;
  99798. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  99799. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  99800. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  99801. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  99802. FLAC__ASSERT(do_independent && do_mid_side);
  99803. /* We have to figure out which channel assignent results in the smallest frame */
  99804. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  99805. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  99806. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  99807. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  99808. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  99809. min_bits = bits[channel_assignment];
  99810. for(ca = 1; ca <= 3; ca++) {
  99811. if(bits[ca] < min_bits) {
  99812. min_bits = bits[ca];
  99813. channel_assignment = (FLAC__ChannelAssignment)ca;
  99814. }
  99815. }
  99816. }
  99817. frame_header.channel_assignment = channel_assignment;
  99818. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  99819. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99820. return false;
  99821. }
  99822. switch(channel_assignment) {
  99823. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99824. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  99825. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  99826. break;
  99827. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99828. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  99829. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  99830. break;
  99831. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99832. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  99833. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  99834. break;
  99835. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99836. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  99837. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  99838. break;
  99839. default:
  99840. FLAC__ASSERT(0);
  99841. }
  99842. switch(channel_assignment) {
  99843. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99844. left_bps = encoder->private_->subframe_bps [0];
  99845. right_bps = encoder->private_->subframe_bps [1];
  99846. break;
  99847. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99848. left_bps = encoder->private_->subframe_bps [0];
  99849. right_bps = encoder->private_->subframe_bps_mid_side[1];
  99850. break;
  99851. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99852. left_bps = encoder->private_->subframe_bps_mid_side[1];
  99853. right_bps = encoder->private_->subframe_bps [1];
  99854. break;
  99855. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99856. left_bps = encoder->private_->subframe_bps_mid_side[0];
  99857. right_bps = encoder->private_->subframe_bps_mid_side[1];
  99858. break;
  99859. default:
  99860. FLAC__ASSERT(0);
  99861. }
  99862. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  99863. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  99864. return false;
  99865. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  99866. return false;
  99867. }
  99868. else {
  99869. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  99870. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99871. return false;
  99872. }
  99873. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  99874. 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)) {
  99875. /* the above function sets the state for us in case of an error */
  99876. return false;
  99877. }
  99878. }
  99879. }
  99880. if(encoder->protected_->loose_mid_side_stereo) {
  99881. encoder->private_->loose_mid_side_stereo_frame_count++;
  99882. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  99883. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  99884. }
  99885. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  99886. return true;
  99887. }
  99888. FLAC__bool process_subframe_(
  99889. FLAC__StreamEncoder *encoder,
  99890. unsigned min_partition_order,
  99891. unsigned max_partition_order,
  99892. const FLAC__FrameHeader *frame_header,
  99893. unsigned subframe_bps,
  99894. const FLAC__int32 integer_signal[],
  99895. FLAC__Subframe *subframe[2],
  99896. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  99897. FLAC__int32 *residual[2],
  99898. unsigned *best_subframe,
  99899. unsigned *best_bits
  99900. )
  99901. {
  99902. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99903. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  99904. #else
  99905. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  99906. #endif
  99907. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99908. FLAC__double lpc_residual_bits_per_sample;
  99909. 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 */
  99910. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  99911. unsigned min_lpc_order, max_lpc_order, lpc_order;
  99912. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  99913. #endif
  99914. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  99915. unsigned rice_parameter;
  99916. unsigned _candidate_bits, _best_bits;
  99917. unsigned _best_subframe;
  99918. /* only use RICE2 partitions if stream bps > 16 */
  99919. 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;
  99920. FLAC__ASSERT(frame_header->blocksize > 0);
  99921. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  99922. _best_subframe = 0;
  99923. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  99924. _best_bits = UINT_MAX;
  99925. else
  99926. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  99927. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  99928. unsigned signal_is_constant = false;
  99929. 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);
  99930. /* check for constant subframe */
  99931. if(
  99932. !encoder->private_->disable_constant_subframes &&
  99933. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99934. fixed_residual_bits_per_sample[1] == 0.0
  99935. #else
  99936. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  99937. #endif
  99938. ) {
  99939. /* the above means it's possible all samples are the same value; now double-check it: */
  99940. unsigned i;
  99941. signal_is_constant = true;
  99942. for(i = 1; i < frame_header->blocksize; i++) {
  99943. if(integer_signal[0] != integer_signal[i]) {
  99944. signal_is_constant = false;
  99945. break;
  99946. }
  99947. }
  99948. }
  99949. if(signal_is_constant) {
  99950. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  99951. if(_candidate_bits < _best_bits) {
  99952. _best_subframe = !_best_subframe;
  99953. _best_bits = _candidate_bits;
  99954. }
  99955. }
  99956. else {
  99957. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  99958. /* encode fixed */
  99959. if(encoder->protected_->do_exhaustive_model_search) {
  99960. min_fixed_order = 0;
  99961. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  99962. }
  99963. else {
  99964. min_fixed_order = max_fixed_order = guess_fixed_order;
  99965. }
  99966. if(max_fixed_order >= frame_header->blocksize)
  99967. max_fixed_order = frame_header->blocksize - 1;
  99968. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  99969. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99970. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  99971. continue; /* don't even try */
  99972. 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 */
  99973. #else
  99974. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  99975. continue; /* don't even try */
  99976. 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 */
  99977. #endif
  99978. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  99979. if(rice_parameter >= rice_parameter_limit) {
  99980. #ifdef DEBUG_VERBOSE
  99981. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  99982. #endif
  99983. rice_parameter = rice_parameter_limit - 1;
  99984. }
  99985. _candidate_bits =
  99986. evaluate_fixed_subframe_(
  99987. encoder,
  99988. integer_signal,
  99989. residual[!_best_subframe],
  99990. encoder->private_->abs_residual_partition_sums,
  99991. encoder->private_->raw_bits_per_partition,
  99992. frame_header->blocksize,
  99993. subframe_bps,
  99994. fixed_order,
  99995. rice_parameter,
  99996. rice_parameter_limit,
  99997. min_partition_order,
  99998. max_partition_order,
  99999. encoder->protected_->do_escape_coding,
  100000. encoder->protected_->rice_parameter_search_dist,
  100001. subframe[!_best_subframe],
  100002. partitioned_rice_contents[!_best_subframe]
  100003. );
  100004. if(_candidate_bits < _best_bits) {
  100005. _best_subframe = !_best_subframe;
  100006. _best_bits = _candidate_bits;
  100007. }
  100008. }
  100009. }
  100010. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100011. /* encode lpc */
  100012. if(encoder->protected_->max_lpc_order > 0) {
  100013. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  100014. max_lpc_order = frame_header->blocksize-1;
  100015. else
  100016. max_lpc_order = encoder->protected_->max_lpc_order;
  100017. if(max_lpc_order > 0) {
  100018. unsigned a;
  100019. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  100020. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  100021. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  100022. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  100023. if(autoc[0] != 0.0) {
  100024. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  100025. if(encoder->protected_->do_exhaustive_model_search) {
  100026. min_lpc_order = 1;
  100027. }
  100028. else {
  100029. const unsigned guess_lpc_order =
  100030. FLAC__lpc_compute_best_order(
  100031. lpc_error,
  100032. max_lpc_order,
  100033. frame_header->blocksize,
  100034. subframe_bps + (
  100035. encoder->protected_->do_qlp_coeff_prec_search?
  100036. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  100037. encoder->protected_->qlp_coeff_precision
  100038. )
  100039. );
  100040. min_lpc_order = max_lpc_order = guess_lpc_order;
  100041. }
  100042. if(max_lpc_order >= frame_header->blocksize)
  100043. max_lpc_order = frame_header->blocksize - 1;
  100044. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  100045. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  100046. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  100047. continue; /* don't even try */
  100048. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  100049. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  100050. if(rice_parameter >= rice_parameter_limit) {
  100051. #ifdef DEBUG_VERBOSE
  100052. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  100053. #endif
  100054. rice_parameter = rice_parameter_limit - 1;
  100055. }
  100056. if(encoder->protected_->do_qlp_coeff_prec_search) {
  100057. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  100058. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  100059. if(subframe_bps <= 17) {
  100060. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  100061. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  100062. }
  100063. else
  100064. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  100065. }
  100066. else {
  100067. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  100068. }
  100069. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  100070. _candidate_bits =
  100071. evaluate_lpc_subframe_(
  100072. encoder,
  100073. integer_signal,
  100074. residual[!_best_subframe],
  100075. encoder->private_->abs_residual_partition_sums,
  100076. encoder->private_->raw_bits_per_partition,
  100077. encoder->private_->lp_coeff[lpc_order-1],
  100078. frame_header->blocksize,
  100079. subframe_bps,
  100080. lpc_order,
  100081. qlp_coeff_precision,
  100082. rice_parameter,
  100083. rice_parameter_limit,
  100084. min_partition_order,
  100085. max_partition_order,
  100086. encoder->protected_->do_escape_coding,
  100087. encoder->protected_->rice_parameter_search_dist,
  100088. subframe[!_best_subframe],
  100089. partitioned_rice_contents[!_best_subframe]
  100090. );
  100091. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  100092. if(_candidate_bits < _best_bits) {
  100093. _best_subframe = !_best_subframe;
  100094. _best_bits = _candidate_bits;
  100095. }
  100096. }
  100097. }
  100098. }
  100099. }
  100100. }
  100101. }
  100102. }
  100103. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  100104. }
  100105. }
  100106. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  100107. if(_best_bits == UINT_MAX) {
  100108. FLAC__ASSERT(_best_subframe == 0);
  100109. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  100110. }
  100111. *best_subframe = _best_subframe;
  100112. *best_bits = _best_bits;
  100113. return true;
  100114. }
  100115. FLAC__bool add_subframe_(
  100116. FLAC__StreamEncoder *encoder,
  100117. unsigned blocksize,
  100118. unsigned subframe_bps,
  100119. const FLAC__Subframe *subframe,
  100120. FLAC__BitWriter *frame
  100121. )
  100122. {
  100123. switch(subframe->type) {
  100124. case FLAC__SUBFRAME_TYPE_CONSTANT:
  100125. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  100126. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100127. return false;
  100128. }
  100129. break;
  100130. case FLAC__SUBFRAME_TYPE_FIXED:
  100131. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  100132. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100133. return false;
  100134. }
  100135. break;
  100136. case FLAC__SUBFRAME_TYPE_LPC:
  100137. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  100138. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100139. return false;
  100140. }
  100141. break;
  100142. case FLAC__SUBFRAME_TYPE_VERBATIM:
  100143. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  100144. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100145. return false;
  100146. }
  100147. break;
  100148. default:
  100149. FLAC__ASSERT(0);
  100150. }
  100151. return true;
  100152. }
  100153. #define SPOTCHECK_ESTIMATE 0
  100154. #if SPOTCHECK_ESTIMATE
  100155. static void spotcheck_subframe_estimate_(
  100156. FLAC__StreamEncoder *encoder,
  100157. unsigned blocksize,
  100158. unsigned subframe_bps,
  100159. const FLAC__Subframe *subframe,
  100160. unsigned estimate
  100161. )
  100162. {
  100163. FLAC__bool ret;
  100164. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  100165. if(frame == 0) {
  100166. fprintf(stderr, "EST: can't allocate frame\n");
  100167. return;
  100168. }
  100169. if(!FLAC__bitwriter_init(frame)) {
  100170. fprintf(stderr, "EST: can't init frame\n");
  100171. return;
  100172. }
  100173. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  100174. FLAC__ASSERT(ret);
  100175. {
  100176. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  100177. if(estimate != actual)
  100178. 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);
  100179. }
  100180. FLAC__bitwriter_delete(frame);
  100181. }
  100182. #endif
  100183. unsigned evaluate_constant_subframe_(
  100184. FLAC__StreamEncoder *encoder,
  100185. const FLAC__int32 signal,
  100186. unsigned blocksize,
  100187. unsigned subframe_bps,
  100188. FLAC__Subframe *subframe
  100189. )
  100190. {
  100191. unsigned estimate;
  100192. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100193. subframe->data.constant.value = signal;
  100194. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  100195. #if SPOTCHECK_ESTIMATE
  100196. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  100197. #else
  100198. (void)encoder, (void)blocksize;
  100199. #endif
  100200. return estimate;
  100201. }
  100202. unsigned evaluate_fixed_subframe_(
  100203. FLAC__StreamEncoder *encoder,
  100204. const FLAC__int32 signal[],
  100205. FLAC__int32 residual[],
  100206. FLAC__uint64 abs_residual_partition_sums[],
  100207. unsigned raw_bits_per_partition[],
  100208. unsigned blocksize,
  100209. unsigned subframe_bps,
  100210. unsigned order,
  100211. unsigned rice_parameter,
  100212. unsigned rice_parameter_limit,
  100213. unsigned min_partition_order,
  100214. unsigned max_partition_order,
  100215. FLAC__bool do_escape_coding,
  100216. unsigned rice_parameter_search_dist,
  100217. FLAC__Subframe *subframe,
  100218. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  100219. )
  100220. {
  100221. unsigned i, residual_bits, estimate;
  100222. const unsigned residual_samples = blocksize - order;
  100223. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  100224. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  100225. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  100226. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  100227. subframe->data.fixed.residual = residual;
  100228. residual_bits =
  100229. find_best_partition_order_(
  100230. encoder->private_,
  100231. residual,
  100232. abs_residual_partition_sums,
  100233. raw_bits_per_partition,
  100234. residual_samples,
  100235. order,
  100236. rice_parameter,
  100237. rice_parameter_limit,
  100238. min_partition_order,
  100239. max_partition_order,
  100240. subframe_bps,
  100241. do_escape_coding,
  100242. rice_parameter_search_dist,
  100243. &subframe->data.fixed.entropy_coding_method
  100244. );
  100245. subframe->data.fixed.order = order;
  100246. for(i = 0; i < order; i++)
  100247. subframe->data.fixed.warmup[i] = signal[i];
  100248. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  100249. #if SPOTCHECK_ESTIMATE
  100250. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  100251. #endif
  100252. return estimate;
  100253. }
  100254. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100255. unsigned evaluate_lpc_subframe_(
  100256. FLAC__StreamEncoder *encoder,
  100257. const FLAC__int32 signal[],
  100258. FLAC__int32 residual[],
  100259. FLAC__uint64 abs_residual_partition_sums[],
  100260. unsigned raw_bits_per_partition[],
  100261. const FLAC__real lp_coeff[],
  100262. unsigned blocksize,
  100263. unsigned subframe_bps,
  100264. unsigned order,
  100265. unsigned qlp_coeff_precision,
  100266. unsigned rice_parameter,
  100267. unsigned rice_parameter_limit,
  100268. unsigned min_partition_order,
  100269. unsigned max_partition_order,
  100270. FLAC__bool do_escape_coding,
  100271. unsigned rice_parameter_search_dist,
  100272. FLAC__Subframe *subframe,
  100273. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  100274. )
  100275. {
  100276. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  100277. unsigned i, residual_bits, estimate;
  100278. int quantization, ret;
  100279. const unsigned residual_samples = blocksize - order;
  100280. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  100281. if(subframe_bps <= 16) {
  100282. FLAC__ASSERT(order > 0);
  100283. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  100284. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  100285. }
  100286. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  100287. if(ret != 0)
  100288. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  100289. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  100290. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  100291. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  100292. else
  100293. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  100294. else
  100295. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  100296. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  100297. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  100298. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  100299. subframe->data.lpc.residual = residual;
  100300. residual_bits =
  100301. find_best_partition_order_(
  100302. encoder->private_,
  100303. residual,
  100304. abs_residual_partition_sums,
  100305. raw_bits_per_partition,
  100306. residual_samples,
  100307. order,
  100308. rice_parameter,
  100309. rice_parameter_limit,
  100310. min_partition_order,
  100311. max_partition_order,
  100312. subframe_bps,
  100313. do_escape_coding,
  100314. rice_parameter_search_dist,
  100315. &subframe->data.lpc.entropy_coding_method
  100316. );
  100317. subframe->data.lpc.order = order;
  100318. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  100319. subframe->data.lpc.quantization_level = quantization;
  100320. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  100321. for(i = 0; i < order; i++)
  100322. subframe->data.lpc.warmup[i] = signal[i];
  100323. 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;
  100324. #if SPOTCHECK_ESTIMATE
  100325. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  100326. #endif
  100327. return estimate;
  100328. }
  100329. #endif
  100330. unsigned evaluate_verbatim_subframe_(
  100331. FLAC__StreamEncoder *encoder,
  100332. const FLAC__int32 signal[],
  100333. unsigned blocksize,
  100334. unsigned subframe_bps,
  100335. FLAC__Subframe *subframe
  100336. )
  100337. {
  100338. unsigned estimate;
  100339. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  100340. subframe->data.verbatim.data = signal;
  100341. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  100342. #if SPOTCHECK_ESTIMATE
  100343. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  100344. #else
  100345. (void)encoder;
  100346. #endif
  100347. return estimate;
  100348. }
  100349. unsigned find_best_partition_order_(
  100350. FLAC__StreamEncoderPrivate *private_,
  100351. const FLAC__int32 residual[],
  100352. FLAC__uint64 abs_residual_partition_sums[],
  100353. unsigned raw_bits_per_partition[],
  100354. unsigned residual_samples,
  100355. unsigned predictor_order,
  100356. unsigned rice_parameter,
  100357. unsigned rice_parameter_limit,
  100358. unsigned min_partition_order,
  100359. unsigned max_partition_order,
  100360. unsigned bps,
  100361. FLAC__bool do_escape_coding,
  100362. unsigned rice_parameter_search_dist,
  100363. FLAC__EntropyCodingMethod *best_ecm
  100364. )
  100365. {
  100366. unsigned residual_bits, best_residual_bits = 0;
  100367. unsigned best_parameters_index = 0;
  100368. unsigned best_partition_order = 0;
  100369. const unsigned blocksize = residual_samples + predictor_order;
  100370. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  100371. min_partition_order = min(min_partition_order, max_partition_order);
  100372. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  100373. if(do_escape_coding)
  100374. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  100375. {
  100376. int partition_order;
  100377. unsigned sum;
  100378. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  100379. if(!
  100380. set_partitioned_rice_(
  100381. #ifdef EXACT_RICE_BITS_CALCULATION
  100382. residual,
  100383. #endif
  100384. abs_residual_partition_sums+sum,
  100385. raw_bits_per_partition+sum,
  100386. residual_samples,
  100387. predictor_order,
  100388. rice_parameter,
  100389. rice_parameter_limit,
  100390. rice_parameter_search_dist,
  100391. (unsigned)partition_order,
  100392. do_escape_coding,
  100393. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  100394. &residual_bits
  100395. )
  100396. )
  100397. {
  100398. FLAC__ASSERT(best_residual_bits != 0);
  100399. break;
  100400. }
  100401. sum += 1u << partition_order;
  100402. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  100403. best_residual_bits = residual_bits;
  100404. best_parameters_index = !best_parameters_index;
  100405. best_partition_order = partition_order;
  100406. }
  100407. }
  100408. }
  100409. best_ecm->data.partitioned_rice.order = best_partition_order;
  100410. {
  100411. /*
  100412. * We are allowed to de-const the pointer based on our special
  100413. * knowledge; it is const to the outside world.
  100414. */
  100415. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  100416. unsigned partition;
  100417. /* save best parameters and raw_bits */
  100418. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  100419. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  100420. if(do_escape_coding)
  100421. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  100422. /*
  100423. * Now need to check if the type should be changed to
  100424. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  100425. * size of the rice parameters.
  100426. */
  100427. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  100428. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  100429. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  100430. break;
  100431. }
  100432. }
  100433. }
  100434. return best_residual_bits;
  100435. }
  100436. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  100437. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  100438. const FLAC__int32 residual[],
  100439. FLAC__uint64 abs_residual_partition_sums[],
  100440. unsigned blocksize,
  100441. unsigned predictor_order,
  100442. unsigned min_partition_order,
  100443. unsigned max_partition_order
  100444. );
  100445. #endif
  100446. void precompute_partition_info_sums_(
  100447. const FLAC__int32 residual[],
  100448. FLAC__uint64 abs_residual_partition_sums[],
  100449. unsigned residual_samples,
  100450. unsigned predictor_order,
  100451. unsigned min_partition_order,
  100452. unsigned max_partition_order,
  100453. unsigned bps
  100454. )
  100455. {
  100456. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  100457. unsigned partitions = 1u << max_partition_order;
  100458. FLAC__ASSERT(default_partition_samples > predictor_order);
  100459. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  100460. /* slightly pessimistic but still catches all common cases */
  100461. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  100462. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  100463. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  100464. return;
  100465. }
  100466. #endif
  100467. /* first do max_partition_order */
  100468. {
  100469. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  100470. /* slightly pessimistic but still catches all common cases */
  100471. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  100472. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  100473. FLAC__uint32 abs_residual_partition_sum;
  100474. for(partition = residual_sample = 0; partition < partitions; partition++) {
  100475. end += default_partition_samples;
  100476. abs_residual_partition_sum = 0;
  100477. for( ; residual_sample < end; residual_sample++)
  100478. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  100479. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  100480. }
  100481. }
  100482. else { /* have to pessimistically use 64 bits for accumulator */
  100483. FLAC__uint64 abs_residual_partition_sum;
  100484. for(partition = residual_sample = 0; partition < partitions; partition++) {
  100485. end += default_partition_samples;
  100486. abs_residual_partition_sum = 0;
  100487. for( ; residual_sample < end; residual_sample++)
  100488. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  100489. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  100490. }
  100491. }
  100492. }
  100493. /* now merge partitions for lower orders */
  100494. {
  100495. unsigned from_partition = 0, to_partition = partitions;
  100496. int partition_order;
  100497. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  100498. unsigned i;
  100499. partitions >>= 1;
  100500. for(i = 0; i < partitions; i++) {
  100501. abs_residual_partition_sums[to_partition++] =
  100502. abs_residual_partition_sums[from_partition ] +
  100503. abs_residual_partition_sums[from_partition+1];
  100504. from_partition += 2;
  100505. }
  100506. }
  100507. }
  100508. }
  100509. void precompute_partition_info_escapes_(
  100510. const FLAC__int32 residual[],
  100511. unsigned raw_bits_per_partition[],
  100512. unsigned residual_samples,
  100513. unsigned predictor_order,
  100514. unsigned min_partition_order,
  100515. unsigned max_partition_order
  100516. )
  100517. {
  100518. int partition_order;
  100519. unsigned from_partition, to_partition = 0;
  100520. const unsigned blocksize = residual_samples + predictor_order;
  100521. /* first do max_partition_order */
  100522. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  100523. FLAC__int32 r;
  100524. FLAC__uint32 rmax;
  100525. unsigned partition, partition_sample, partition_samples, residual_sample;
  100526. const unsigned partitions = 1u << partition_order;
  100527. const unsigned default_partition_samples = blocksize >> partition_order;
  100528. FLAC__ASSERT(default_partition_samples > predictor_order);
  100529. for(partition = residual_sample = 0; partition < partitions; partition++) {
  100530. partition_samples = default_partition_samples;
  100531. if(partition == 0)
  100532. partition_samples -= predictor_order;
  100533. rmax = 0;
  100534. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  100535. r = residual[residual_sample++];
  100536. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  100537. if(r < 0)
  100538. rmax |= ~r;
  100539. else
  100540. rmax |= r;
  100541. }
  100542. /* now we know all residual values are in the range [-rmax-1,rmax] */
  100543. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  100544. }
  100545. to_partition = partitions;
  100546. break; /*@@@ yuck, should remove the 'for' loop instead */
  100547. }
  100548. /* now merge partitions for lower orders */
  100549. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  100550. unsigned m;
  100551. unsigned i;
  100552. const unsigned partitions = 1u << partition_order;
  100553. for(i = 0; i < partitions; i++) {
  100554. m = raw_bits_per_partition[from_partition];
  100555. from_partition++;
  100556. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  100557. from_partition++;
  100558. to_partition++;
  100559. }
  100560. }
  100561. }
  100562. #ifdef EXACT_RICE_BITS_CALCULATION
  100563. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  100564. const unsigned rice_parameter,
  100565. const unsigned partition_samples,
  100566. const FLAC__int32 *residual
  100567. )
  100568. {
  100569. unsigned i, partition_bits =
  100570. 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 */
  100571. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  100572. ;
  100573. for(i = 0; i < partition_samples; i++)
  100574. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  100575. return partition_bits;
  100576. }
  100577. #else
  100578. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  100579. const unsigned rice_parameter,
  100580. const unsigned partition_samples,
  100581. const FLAC__uint64 abs_residual_partition_sum
  100582. )
  100583. {
  100584. return
  100585. 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 */
  100586. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  100587. (
  100588. rice_parameter?
  100589. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  100590. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  100591. )
  100592. - (partition_samples >> 1)
  100593. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  100594. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  100595. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  100596. * So the subtraction term tries to guess how many extra bits were contributed.
  100597. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  100598. */
  100599. ;
  100600. }
  100601. #endif
  100602. FLAC__bool set_partitioned_rice_(
  100603. #ifdef EXACT_RICE_BITS_CALCULATION
  100604. const FLAC__int32 residual[],
  100605. #endif
  100606. const FLAC__uint64 abs_residual_partition_sums[],
  100607. const unsigned raw_bits_per_partition[],
  100608. const unsigned residual_samples,
  100609. const unsigned predictor_order,
  100610. const unsigned suggested_rice_parameter,
  100611. const unsigned rice_parameter_limit,
  100612. const unsigned rice_parameter_search_dist,
  100613. const unsigned partition_order,
  100614. const FLAC__bool search_for_escapes,
  100615. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  100616. unsigned *bits
  100617. )
  100618. {
  100619. unsigned rice_parameter, partition_bits;
  100620. unsigned best_partition_bits, best_rice_parameter = 0;
  100621. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  100622. unsigned *parameters, *raw_bits;
  100623. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  100624. unsigned min_rice_parameter, max_rice_parameter;
  100625. #else
  100626. (void)rice_parameter_search_dist;
  100627. #endif
  100628. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  100629. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  100630. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  100631. parameters = partitioned_rice_contents->parameters;
  100632. raw_bits = partitioned_rice_contents->raw_bits;
  100633. if(partition_order == 0) {
  100634. best_partition_bits = (unsigned)(-1);
  100635. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  100636. if(rice_parameter_search_dist) {
  100637. if(suggested_rice_parameter < rice_parameter_search_dist)
  100638. min_rice_parameter = 0;
  100639. else
  100640. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  100641. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  100642. if(max_rice_parameter >= rice_parameter_limit) {
  100643. #ifdef DEBUG_VERBOSE
  100644. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  100645. #endif
  100646. max_rice_parameter = rice_parameter_limit - 1;
  100647. }
  100648. }
  100649. else
  100650. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  100651. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  100652. #else
  100653. rice_parameter = suggested_rice_parameter;
  100654. #endif
  100655. #ifdef EXACT_RICE_BITS_CALCULATION
  100656. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  100657. #else
  100658. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  100659. #endif
  100660. if(partition_bits < best_partition_bits) {
  100661. best_rice_parameter = rice_parameter;
  100662. best_partition_bits = partition_bits;
  100663. }
  100664. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  100665. }
  100666. #endif
  100667. if(search_for_escapes) {
  100668. 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;
  100669. if(partition_bits <= best_partition_bits) {
  100670. raw_bits[0] = raw_bits_per_partition[0];
  100671. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  100672. best_partition_bits = partition_bits;
  100673. }
  100674. else
  100675. raw_bits[0] = 0;
  100676. }
  100677. parameters[0] = best_rice_parameter;
  100678. bits_ += best_partition_bits;
  100679. }
  100680. else {
  100681. unsigned partition, residual_sample;
  100682. unsigned partition_samples;
  100683. FLAC__uint64 mean, k;
  100684. const unsigned partitions = 1u << partition_order;
  100685. for(partition = residual_sample = 0; partition < partitions; partition++) {
  100686. partition_samples = (residual_samples+predictor_order) >> partition_order;
  100687. if(partition == 0) {
  100688. if(partition_samples <= predictor_order)
  100689. return false;
  100690. else
  100691. partition_samples -= predictor_order;
  100692. }
  100693. mean = abs_residual_partition_sums[partition];
  100694. /* we are basically calculating the size in bits of the
  100695. * average residual magnitude in the partition:
  100696. * rice_parameter = floor(log2(mean/partition_samples))
  100697. * 'mean' is not a good name for the variable, it is
  100698. * actually the sum of magnitudes of all residual values
  100699. * in the partition, so the actual mean is
  100700. * mean/partition_samples
  100701. */
  100702. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  100703. ;
  100704. if(rice_parameter >= rice_parameter_limit) {
  100705. #ifdef DEBUG_VERBOSE
  100706. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  100707. #endif
  100708. rice_parameter = rice_parameter_limit - 1;
  100709. }
  100710. best_partition_bits = (unsigned)(-1);
  100711. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  100712. if(rice_parameter_search_dist) {
  100713. if(rice_parameter < rice_parameter_search_dist)
  100714. min_rice_parameter = 0;
  100715. else
  100716. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  100717. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  100718. if(max_rice_parameter >= rice_parameter_limit) {
  100719. #ifdef DEBUG_VERBOSE
  100720. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  100721. #endif
  100722. max_rice_parameter = rice_parameter_limit - 1;
  100723. }
  100724. }
  100725. else
  100726. min_rice_parameter = max_rice_parameter = rice_parameter;
  100727. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  100728. #endif
  100729. #ifdef EXACT_RICE_BITS_CALCULATION
  100730. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  100731. #else
  100732. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  100733. #endif
  100734. if(partition_bits < best_partition_bits) {
  100735. best_rice_parameter = rice_parameter;
  100736. best_partition_bits = partition_bits;
  100737. }
  100738. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  100739. }
  100740. #endif
  100741. if(search_for_escapes) {
  100742. 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;
  100743. if(partition_bits <= best_partition_bits) {
  100744. raw_bits[partition] = raw_bits_per_partition[partition];
  100745. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  100746. best_partition_bits = partition_bits;
  100747. }
  100748. else
  100749. raw_bits[partition] = 0;
  100750. }
  100751. parameters[partition] = best_rice_parameter;
  100752. bits_ += best_partition_bits;
  100753. residual_sample += partition_samples;
  100754. }
  100755. }
  100756. *bits = bits_;
  100757. return true;
  100758. }
  100759. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  100760. {
  100761. unsigned i, shift;
  100762. FLAC__int32 x = 0;
  100763. for(i = 0; i < samples && !(x&1); i++)
  100764. x |= signal[i];
  100765. if(x == 0) {
  100766. shift = 0;
  100767. }
  100768. else {
  100769. for(shift = 0; !(x&1); shift++)
  100770. x >>= 1;
  100771. }
  100772. if(shift > 0) {
  100773. for(i = 0; i < samples; i++)
  100774. signal[i] >>= shift;
  100775. }
  100776. return shift;
  100777. }
  100778. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  100779. {
  100780. unsigned channel;
  100781. for(channel = 0; channel < channels; channel++)
  100782. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  100783. fifo->tail += wide_samples;
  100784. FLAC__ASSERT(fifo->tail <= fifo->size);
  100785. }
  100786. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  100787. {
  100788. unsigned channel;
  100789. unsigned sample, wide_sample;
  100790. unsigned tail = fifo->tail;
  100791. sample = input_offset * channels;
  100792. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  100793. for(channel = 0; channel < channels; channel++)
  100794. fifo->data[channel][tail] = input[sample++];
  100795. tail++;
  100796. }
  100797. fifo->tail = tail;
  100798. FLAC__ASSERT(fifo->tail <= fifo->size);
  100799. }
  100800. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  100801. {
  100802. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  100803. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  100804. (void)decoder;
  100805. if(encoder->private_->verify.needs_magic_hack) {
  100806. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  100807. *bytes = FLAC__STREAM_SYNC_LENGTH;
  100808. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  100809. encoder->private_->verify.needs_magic_hack = false;
  100810. }
  100811. else {
  100812. if(encoded_bytes == 0) {
  100813. /*
  100814. * If we get here, a FIFO underflow has occurred,
  100815. * which means there is a bug somewhere.
  100816. */
  100817. FLAC__ASSERT(0);
  100818. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100819. }
  100820. else if(encoded_bytes < *bytes)
  100821. *bytes = encoded_bytes;
  100822. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  100823. encoder->private_->verify.output.data += *bytes;
  100824. encoder->private_->verify.output.bytes -= *bytes;
  100825. }
  100826. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100827. }
  100828. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  100829. {
  100830. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  100831. unsigned channel;
  100832. const unsigned channels = frame->header.channels;
  100833. const unsigned blocksize = frame->header.blocksize;
  100834. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  100835. (void)decoder;
  100836. for(channel = 0; channel < channels; channel++) {
  100837. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  100838. unsigned i, sample = 0;
  100839. FLAC__int32 expect = 0, got = 0;
  100840. for(i = 0; i < blocksize; i++) {
  100841. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  100842. sample = i;
  100843. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  100844. got = (FLAC__int32)buffer[channel][i];
  100845. break;
  100846. }
  100847. }
  100848. FLAC__ASSERT(i < blocksize);
  100849. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100850. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  100851. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  100852. encoder->private_->verify.error_stats.channel = channel;
  100853. encoder->private_->verify.error_stats.sample = sample;
  100854. encoder->private_->verify.error_stats.expected = expect;
  100855. encoder->private_->verify.error_stats.got = got;
  100856. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  100857. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  100858. }
  100859. }
  100860. /* dequeue the frame from the fifo */
  100861. encoder->private_->verify.input_fifo.tail -= blocksize;
  100862. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  100863. for(channel = 0; channel < channels; channel++)
  100864. 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]));
  100865. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  100866. }
  100867. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  100868. {
  100869. (void)decoder, (void)metadata, (void)client_data;
  100870. }
  100871. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  100872. {
  100873. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  100874. (void)decoder, (void)status;
  100875. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  100876. }
  100877. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  100878. {
  100879. (void)client_data;
  100880. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  100881. if (*bytes == 0) {
  100882. if (feof(encoder->private_->file))
  100883. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  100884. else if (ferror(encoder->private_->file))
  100885. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  100886. }
  100887. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  100888. }
  100889. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  100890. {
  100891. (void)client_data;
  100892. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  100893. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  100894. else
  100895. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  100896. }
  100897. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  100898. {
  100899. off_t offset;
  100900. (void)client_data;
  100901. offset = ftello(encoder->private_->file);
  100902. if(offset < 0) {
  100903. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  100904. }
  100905. else {
  100906. *absolute_byte_offset = (FLAC__uint64)offset;
  100907. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  100908. }
  100909. }
  100910. #ifdef FLAC__VALGRIND_TESTING
  100911. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  100912. {
  100913. size_t ret = fwrite(ptr, size, nmemb, stream);
  100914. if(!ferror(stream))
  100915. fflush(stream);
  100916. return ret;
  100917. }
  100918. #else
  100919. #define local__fwrite fwrite
  100920. #endif
  100921. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  100922. {
  100923. (void)client_data, (void)current_frame;
  100924. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  100925. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  100926. #if FLAC__HAS_OGG
  100927. /* We would like to be able to use 'samples > 0' in the
  100928. * clause here but currently because of the nature of our
  100929. * Ogg writing implementation, 'samples' is always 0 (see
  100930. * ogg_encoder_aspect.c). The downside is extra progress
  100931. * callbacks.
  100932. */
  100933. encoder->private_->is_ogg? true :
  100934. #endif
  100935. samples > 0
  100936. );
  100937. if(call_it) {
  100938. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  100939. * because at this point in the callback chain, the stats
  100940. * have not been updated. Only after we return and control
  100941. * gets back to write_frame_() are the stats updated
  100942. */
  100943. 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);
  100944. }
  100945. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  100946. }
  100947. else
  100948. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  100949. }
  100950. /*
  100951. * This will forcibly set stdout to binary mode (for OSes that require it)
  100952. */
  100953. FILE *get_binary_stdout_(void)
  100954. {
  100955. /* if something breaks here it is probably due to the presence or
  100956. * absence of an underscore before the identifiers 'setmode',
  100957. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100958. */
  100959. #if defined _MSC_VER || defined __MINGW32__
  100960. _setmode(_fileno(stdout), _O_BINARY);
  100961. #elif defined __CYGWIN__
  100962. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100963. setmode(_fileno(stdout), _O_BINARY);
  100964. #elif defined __EMX__
  100965. setmode(fileno(stdout), O_BINARY);
  100966. #endif
  100967. return stdout;
  100968. }
  100969. #endif
  100970. /********* End of inlined file: stream_encoder.c *********/
  100971. /********* Start of inlined file: stream_encoder_framing.c *********/
  100972. /********* Start of inlined file: juce_FlacHeader.h *********/
  100973. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  100974. // tasks..
  100975. #define VERSION "1.2.1"
  100976. #define FLAC__NO_DLL 1
  100977. #ifdef _MSC_VER
  100978. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  100979. #endif
  100980. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  100981. #define FLAC__SYS_DARWIN 1
  100982. #endif
  100983. /********* End of inlined file: juce_FlacHeader.h *********/
  100984. #if JUCE_USE_FLAC
  100985. #if HAVE_CONFIG_H
  100986. # include <config.h>
  100987. #endif
  100988. #include <stdio.h>
  100989. #include <string.h> /* for strlen() */
  100990. #ifdef max
  100991. #undef max
  100992. #endif
  100993. #define max(x,y) ((x)>(y)?(x):(y))
  100994. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  100995. 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);
  100996. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  100997. {
  100998. unsigned i, j;
  100999. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  101000. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  101001. return false;
  101002. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  101003. return false;
  101004. /*
  101005. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  101006. */
  101007. i = metadata->length;
  101008. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  101009. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  101010. i -= metadata->data.vorbis_comment.vendor_string.length;
  101011. i += vendor_string_length;
  101012. }
  101013. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  101014. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  101015. return false;
  101016. switch(metadata->type) {
  101017. case FLAC__METADATA_TYPE_STREAMINFO:
  101018. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  101019. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  101020. return false;
  101021. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  101022. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  101023. return false;
  101024. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  101025. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  101026. return false;
  101027. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  101028. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  101029. return false;
  101030. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  101031. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  101032. return false;
  101033. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  101034. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  101035. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  101036. return false;
  101037. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  101038. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  101039. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  101040. return false;
  101041. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  101042. return false;
  101043. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  101044. return false;
  101045. break;
  101046. case FLAC__METADATA_TYPE_PADDING:
  101047. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  101048. return false;
  101049. break;
  101050. case FLAC__METADATA_TYPE_APPLICATION:
  101051. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  101052. return false;
  101053. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  101054. return false;
  101055. break;
  101056. case FLAC__METADATA_TYPE_SEEKTABLE:
  101057. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  101058. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  101059. return false;
  101060. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  101061. return false;
  101062. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  101063. return false;
  101064. }
  101065. break;
  101066. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  101067. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  101068. return false;
  101069. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  101070. return false;
  101071. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  101072. return false;
  101073. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  101074. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  101075. return false;
  101076. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  101077. return false;
  101078. }
  101079. break;
  101080. case FLAC__METADATA_TYPE_CUESHEET:
  101081. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  101082. 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))
  101083. return false;
  101084. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  101085. return false;
  101086. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  101087. return false;
  101088. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  101089. return false;
  101090. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  101091. return false;
  101092. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  101093. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  101094. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  101095. return false;
  101096. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  101097. return false;
  101098. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  101099. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  101100. return false;
  101101. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  101102. return false;
  101103. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  101104. return false;
  101105. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  101106. return false;
  101107. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  101108. return false;
  101109. for(j = 0; j < track->num_indices; j++) {
  101110. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  101111. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  101112. return false;
  101113. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  101114. return false;
  101115. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  101116. return false;
  101117. }
  101118. }
  101119. break;
  101120. case FLAC__METADATA_TYPE_PICTURE:
  101121. {
  101122. size_t len;
  101123. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  101124. return false;
  101125. len = strlen(metadata->data.picture.mime_type);
  101126. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  101127. return false;
  101128. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  101129. return false;
  101130. len = strlen((const char *)metadata->data.picture.description);
  101131. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  101132. return false;
  101133. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  101134. return false;
  101135. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  101136. return false;
  101137. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  101138. return false;
  101139. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  101140. return false;
  101141. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  101142. return false;
  101143. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  101144. return false;
  101145. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  101146. return false;
  101147. }
  101148. break;
  101149. default:
  101150. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  101151. return false;
  101152. break;
  101153. }
  101154. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  101155. return true;
  101156. }
  101157. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  101158. {
  101159. unsigned u, blocksize_hint, sample_rate_hint;
  101160. FLAC__byte crc;
  101161. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  101162. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  101163. return false;
  101164. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  101165. return false;
  101166. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  101167. return false;
  101168. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  101169. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  101170. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  101171. blocksize_hint = 0;
  101172. switch(header->blocksize) {
  101173. case 192: u = 1; break;
  101174. case 576: u = 2; break;
  101175. case 1152: u = 3; break;
  101176. case 2304: u = 4; break;
  101177. case 4608: u = 5; break;
  101178. case 256: u = 8; break;
  101179. case 512: u = 9; break;
  101180. case 1024: u = 10; break;
  101181. case 2048: u = 11; break;
  101182. case 4096: u = 12; break;
  101183. case 8192: u = 13; break;
  101184. case 16384: u = 14; break;
  101185. case 32768: u = 15; break;
  101186. default:
  101187. if(header->blocksize <= 0x100)
  101188. blocksize_hint = u = 6;
  101189. else
  101190. blocksize_hint = u = 7;
  101191. break;
  101192. }
  101193. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  101194. return false;
  101195. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  101196. sample_rate_hint = 0;
  101197. switch(header->sample_rate) {
  101198. case 88200: u = 1; break;
  101199. case 176400: u = 2; break;
  101200. case 192000: u = 3; break;
  101201. case 8000: u = 4; break;
  101202. case 16000: u = 5; break;
  101203. case 22050: u = 6; break;
  101204. case 24000: u = 7; break;
  101205. case 32000: u = 8; break;
  101206. case 44100: u = 9; break;
  101207. case 48000: u = 10; break;
  101208. case 96000: u = 11; break;
  101209. default:
  101210. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  101211. sample_rate_hint = u = 12;
  101212. else if(header->sample_rate % 10 == 0)
  101213. sample_rate_hint = u = 14;
  101214. else if(header->sample_rate <= 0xffff)
  101215. sample_rate_hint = u = 13;
  101216. else
  101217. u = 0;
  101218. break;
  101219. }
  101220. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  101221. return false;
  101222. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  101223. switch(header->channel_assignment) {
  101224. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101225. u = header->channels - 1;
  101226. break;
  101227. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101228. FLAC__ASSERT(header->channels == 2);
  101229. u = 8;
  101230. break;
  101231. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101232. FLAC__ASSERT(header->channels == 2);
  101233. u = 9;
  101234. break;
  101235. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101236. FLAC__ASSERT(header->channels == 2);
  101237. u = 10;
  101238. break;
  101239. default:
  101240. FLAC__ASSERT(0);
  101241. }
  101242. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  101243. return false;
  101244. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  101245. switch(header->bits_per_sample) {
  101246. case 8 : u = 1; break;
  101247. case 12: u = 2; break;
  101248. case 16: u = 4; break;
  101249. case 20: u = 5; break;
  101250. case 24: u = 6; break;
  101251. default: u = 0; break;
  101252. }
  101253. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  101254. return false;
  101255. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  101256. return false;
  101257. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101258. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  101259. return false;
  101260. }
  101261. else {
  101262. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  101263. return false;
  101264. }
  101265. if(blocksize_hint)
  101266. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  101267. return false;
  101268. switch(sample_rate_hint) {
  101269. case 12:
  101270. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  101271. return false;
  101272. break;
  101273. case 13:
  101274. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  101275. return false;
  101276. break;
  101277. case 14:
  101278. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  101279. return false;
  101280. break;
  101281. }
  101282. /* write the CRC */
  101283. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  101284. return false;
  101285. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  101286. return false;
  101287. return true;
  101288. }
  101289. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  101290. {
  101291. FLAC__bool ok;
  101292. ok =
  101293. 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) &&
  101294. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  101295. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  101296. ;
  101297. return ok;
  101298. }
  101299. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  101300. {
  101301. unsigned i;
  101302. 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))
  101303. return false;
  101304. if(wasted_bits)
  101305. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  101306. return false;
  101307. for(i = 0; i < subframe->order; i++)
  101308. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  101309. return false;
  101310. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  101311. return false;
  101312. switch(subframe->entropy_coding_method.type) {
  101313. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101314. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101315. if(!add_residual_partitioned_rice_(
  101316. bw,
  101317. subframe->residual,
  101318. residual_samples,
  101319. subframe->order,
  101320. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  101321. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  101322. subframe->entropy_coding_method.data.partitioned_rice.order,
  101323. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  101324. ))
  101325. return false;
  101326. break;
  101327. default:
  101328. FLAC__ASSERT(0);
  101329. }
  101330. return true;
  101331. }
  101332. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  101333. {
  101334. unsigned i;
  101335. 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))
  101336. return false;
  101337. if(wasted_bits)
  101338. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  101339. return false;
  101340. for(i = 0; i < subframe->order; i++)
  101341. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  101342. return false;
  101343. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101344. return false;
  101345. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101346. return false;
  101347. for(i = 0; i < subframe->order; i++)
  101348. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  101349. return false;
  101350. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  101351. return false;
  101352. switch(subframe->entropy_coding_method.type) {
  101353. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101354. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101355. if(!add_residual_partitioned_rice_(
  101356. bw,
  101357. subframe->residual,
  101358. residual_samples,
  101359. subframe->order,
  101360. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  101361. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  101362. subframe->entropy_coding_method.data.partitioned_rice.order,
  101363. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  101364. ))
  101365. return false;
  101366. break;
  101367. default:
  101368. FLAC__ASSERT(0);
  101369. }
  101370. return true;
  101371. }
  101372. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  101373. {
  101374. unsigned i;
  101375. const FLAC__int32 *signal = subframe->data;
  101376. 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))
  101377. return false;
  101378. if(wasted_bits)
  101379. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  101380. return false;
  101381. for(i = 0; i < samples; i++)
  101382. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  101383. return false;
  101384. return true;
  101385. }
  101386. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  101387. {
  101388. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101389. return false;
  101390. switch(method->type) {
  101391. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101392. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101393. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101394. return false;
  101395. break;
  101396. default:
  101397. FLAC__ASSERT(0);
  101398. }
  101399. return true;
  101400. }
  101401. 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)
  101402. {
  101403. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101404. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101405. if(partition_order == 0) {
  101406. unsigned i;
  101407. if(raw_bits[0] == 0) {
  101408. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  101409. return false;
  101410. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  101411. return false;
  101412. }
  101413. else {
  101414. FLAC__ASSERT(rice_parameters[0] == 0);
  101415. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  101416. return false;
  101417. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101418. return false;
  101419. for(i = 0; i < residual_samples; i++) {
  101420. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  101421. return false;
  101422. }
  101423. }
  101424. return true;
  101425. }
  101426. else {
  101427. unsigned i, j, k = 0, k_last = 0;
  101428. unsigned partition_samples;
  101429. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  101430. for(i = 0; i < (1u<<partition_order); i++) {
  101431. partition_samples = default_partition_samples;
  101432. if(i == 0)
  101433. partition_samples -= predictor_order;
  101434. k += partition_samples;
  101435. if(raw_bits[i] == 0) {
  101436. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  101437. return false;
  101438. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  101439. return false;
  101440. }
  101441. else {
  101442. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  101443. return false;
  101444. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101445. return false;
  101446. for(j = k_last; j < k; j++) {
  101447. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  101448. return false;
  101449. }
  101450. }
  101451. k_last = k;
  101452. }
  101453. return true;
  101454. }
  101455. }
  101456. #endif
  101457. /********* End of inlined file: stream_encoder_framing.c *********/
  101458. /********* Start of inlined file: window_flac.c *********/
  101459. /********* Start of inlined file: juce_FlacHeader.h *********/
  101460. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101461. // tasks..
  101462. #define VERSION "1.2.1"
  101463. #define FLAC__NO_DLL 1
  101464. #ifdef _MSC_VER
  101465. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101466. #endif
  101467. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  101468. #define FLAC__SYS_DARWIN 1
  101469. #endif
  101470. /********* End of inlined file: juce_FlacHeader.h *********/
  101471. #if JUCE_USE_FLAC
  101472. #if HAVE_CONFIG_H
  101473. # include <config.h>
  101474. #endif
  101475. #include <math.h>
  101476. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101477. #ifndef M_PI
  101478. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  101479. #define M_PI 3.14159265358979323846
  101480. #endif
  101481. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  101482. {
  101483. const FLAC__int32 N = L - 1;
  101484. FLAC__int32 n;
  101485. if (L & 1) {
  101486. for (n = 0; n <= N/2; n++)
  101487. window[n] = 2.0f * n / (float)N;
  101488. for (; n <= N; n++)
  101489. window[n] = 2.0f - 2.0f * n / (float)N;
  101490. }
  101491. else {
  101492. for (n = 0; n <= L/2-1; n++)
  101493. window[n] = 2.0f * n / (float)N;
  101494. for (; n <= N; n++)
  101495. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  101496. }
  101497. }
  101498. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  101499. {
  101500. const FLAC__int32 N = L - 1;
  101501. FLAC__int32 n;
  101502. for (n = 0; n < L; n++)
  101503. 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)));
  101504. }
  101505. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  101506. {
  101507. const FLAC__int32 N = L - 1;
  101508. FLAC__int32 n;
  101509. for (n = 0; n < L; n++)
  101510. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  101511. }
  101512. /* 4-term -92dB side-lobe */
  101513. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  101514. {
  101515. const FLAC__int32 N = L - 1;
  101516. FLAC__int32 n;
  101517. for (n = 0; n <= N; n++)
  101518. 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));
  101519. }
  101520. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  101521. {
  101522. const FLAC__int32 N = L - 1;
  101523. const double N2 = (double)N / 2.;
  101524. FLAC__int32 n;
  101525. for (n = 0; n <= N; n++) {
  101526. double k = ((double)n - N2) / N2;
  101527. k = 1.0f - k * k;
  101528. window[n] = (FLAC__real)(k * k);
  101529. }
  101530. }
  101531. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  101532. {
  101533. const FLAC__int32 N = L - 1;
  101534. FLAC__int32 n;
  101535. for (n = 0; n < L; n++)
  101536. 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));
  101537. }
  101538. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  101539. {
  101540. const FLAC__int32 N = L - 1;
  101541. const double N2 = (double)N / 2.;
  101542. FLAC__int32 n;
  101543. for (n = 0; n <= N; n++) {
  101544. const double k = ((double)n - N2) / (stddev * N2);
  101545. window[n] = (FLAC__real)exp(-0.5f * k * k);
  101546. }
  101547. }
  101548. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  101549. {
  101550. const FLAC__int32 N = L - 1;
  101551. FLAC__int32 n;
  101552. for (n = 0; n < L; n++)
  101553. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  101554. }
  101555. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  101556. {
  101557. const FLAC__int32 N = L - 1;
  101558. FLAC__int32 n;
  101559. for (n = 0; n < L; n++)
  101560. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  101561. }
  101562. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  101563. {
  101564. const FLAC__int32 N = L - 1;
  101565. FLAC__int32 n;
  101566. for (n = 0; n < L; n++)
  101567. 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));
  101568. }
  101569. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  101570. {
  101571. const FLAC__int32 N = L - 1;
  101572. FLAC__int32 n;
  101573. for (n = 0; n < L; n++)
  101574. 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));
  101575. }
  101576. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  101577. {
  101578. FLAC__int32 n;
  101579. for (n = 0; n < L; n++)
  101580. window[n] = 1.0f;
  101581. }
  101582. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  101583. {
  101584. FLAC__int32 n;
  101585. if (L & 1) {
  101586. for (n = 1; n <= L+1/2; n++)
  101587. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  101588. for (; n <= L; n++)
  101589. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  101590. }
  101591. else {
  101592. for (n = 1; n <= L/2; n++)
  101593. window[n-1] = 2.0f * n / (float)L;
  101594. for (; n <= L; n++)
  101595. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  101596. }
  101597. }
  101598. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  101599. {
  101600. if (p <= 0.0)
  101601. FLAC__window_rectangle(window, L);
  101602. else if (p >= 1.0)
  101603. FLAC__window_hann(window, L);
  101604. else {
  101605. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  101606. FLAC__int32 n;
  101607. /* start with rectangle... */
  101608. FLAC__window_rectangle(window, L);
  101609. /* ...replace ends with hann */
  101610. if (Np > 0) {
  101611. for (n = 0; n <= Np; n++) {
  101612. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  101613. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  101614. }
  101615. }
  101616. }
  101617. }
  101618. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  101619. {
  101620. const FLAC__int32 N = L - 1;
  101621. const double N2 = (double)N / 2.;
  101622. FLAC__int32 n;
  101623. for (n = 0; n <= N; n++) {
  101624. const double k = ((double)n - N2) / N2;
  101625. window[n] = (FLAC__real)(1.0f - k * k);
  101626. }
  101627. }
  101628. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101629. #endif
  101630. /********* End of inlined file: window_flac.c *********/
  101631. #else
  101632. #include <FLAC/all.h>
  101633. #endif
  101634. }
  101635. #ifdef _MSC_VER
  101636. #pragma warning (pop)
  101637. #endif
  101638. BEGIN_JUCE_NAMESPACE
  101639. using namespace FlacNamespace;
  101640. #define flacFormatName TRANS("FLAC file")
  101641. static const tchar* const flacExtensions[] = { T(".flac"), 0 };
  101642. class FlacReader : public AudioFormatReader
  101643. {
  101644. FLAC__StreamDecoder* decoder;
  101645. AudioSampleBuffer reservoir;
  101646. int reservoirStart, samplesInReservoir;
  101647. bool ok, scanningForLength;
  101648. public:
  101649. FlacReader (InputStream* const in)
  101650. : AudioFormatReader (in, flacFormatName),
  101651. reservoir (2, 0),
  101652. reservoirStart (0),
  101653. samplesInReservoir (0),
  101654. scanningForLength (false)
  101655. {
  101656. using namespace FlacNamespace;
  101657. lengthInSamples = 0;
  101658. decoder = FLAC__stream_decoder_new();
  101659. ok = FLAC__stream_decoder_init_stream (decoder,
  101660. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  101661. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  101662. (void*) this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  101663. if (ok)
  101664. {
  101665. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  101666. if (lengthInSamples == 0 && sampleRate > 0)
  101667. {
  101668. // the length hasn't been stored in the metadata, so we'll need to
  101669. // work it out the length the hard way, by scanning the whole file..
  101670. scanningForLength = true;
  101671. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  101672. scanningForLength = false;
  101673. const int64 tempLength = lengthInSamples;
  101674. FLAC__stream_decoder_reset (decoder);
  101675. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  101676. lengthInSamples = tempLength;
  101677. }
  101678. }
  101679. }
  101680. ~FlacReader()
  101681. {
  101682. FLAC__stream_decoder_delete (decoder);
  101683. }
  101684. void useMetadata (const FLAC__StreamMetadata_StreamInfo& info)
  101685. {
  101686. sampleRate = info.sample_rate;
  101687. bitsPerSample = info.bits_per_sample;
  101688. lengthInSamples = (unsigned int) info.total_samples;
  101689. numChannels = info.channels;
  101690. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  101691. }
  101692. // returns the number of samples read
  101693. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  101694. int64 startSampleInFile, int numSamples)
  101695. {
  101696. using namespace FlacNamespace;
  101697. if (! ok)
  101698. return false;
  101699. while (numSamples > 0)
  101700. {
  101701. if (startSampleInFile >= reservoirStart
  101702. && startSampleInFile < reservoirStart + samplesInReservoir)
  101703. {
  101704. const int num = (int) jmin ((int64) numSamples,
  101705. reservoirStart + samplesInReservoir - startSampleInFile);
  101706. jassert (num > 0);
  101707. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  101708. if (destSamples[i] != 0)
  101709. memcpy (destSamples[i] + startOffsetInDestBuffer,
  101710. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  101711. sizeof (int) * num);
  101712. startOffsetInDestBuffer += num;
  101713. startSampleInFile += num;
  101714. numSamples -= num;
  101715. }
  101716. else
  101717. {
  101718. if (startSampleInFile < reservoirStart
  101719. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  101720. {
  101721. if (startSampleInFile >= (int) lengthInSamples)
  101722. {
  101723. samplesInReservoir = 0;
  101724. break;
  101725. }
  101726. // had some problems with flac crashing if the read pos is aligned more
  101727. // accurately than this. Probably fixed in newer versions of the library, though.
  101728. reservoirStart = (int) (startSampleInFile & ~511);
  101729. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  101730. }
  101731. else
  101732. {
  101733. reservoirStart += samplesInReservoir;
  101734. }
  101735. samplesInReservoir = 0;
  101736. FLAC__stream_decoder_process_single (decoder);
  101737. if (samplesInReservoir == 0)
  101738. break;
  101739. }
  101740. }
  101741. if (numSamples > 0)
  101742. {
  101743. for (int i = numDestChannels; --i >= 0;)
  101744. if (destSamples[i] != 0)
  101745. zeromem (destSamples[i] + startOffsetInDestBuffer,
  101746. sizeof (int) * numSamples);
  101747. }
  101748. return true;
  101749. }
  101750. void useSamples (const FLAC__int32* const buffer[], int numSamples)
  101751. {
  101752. if (scanningForLength)
  101753. {
  101754. lengthInSamples += numSamples;
  101755. }
  101756. else
  101757. {
  101758. if (numSamples > reservoir.getNumSamples())
  101759. reservoir.setSize (numChannels, numSamples, false, false, true);
  101760. const int bitsToShift = 32 - bitsPerSample;
  101761. for (int i = 0; i < (int) numChannels; ++i)
  101762. {
  101763. const FLAC__int32* src = buffer[i];
  101764. int n = i;
  101765. while (src == 0 && n > 0)
  101766. src = buffer [--n];
  101767. if (src != 0)
  101768. {
  101769. int* dest = (int*) reservoir.getSampleData(i);
  101770. for (int j = 0; j < numSamples; ++j)
  101771. dest[j] = src[j] << bitsToShift;
  101772. }
  101773. }
  101774. samplesInReservoir = numSamples;
  101775. }
  101776. }
  101777. static FLAC__StreamDecoderReadStatus readCallback_ (const FLAC__StreamDecoder*, FLAC__byte buffer[], size_t* bytes, void* client_data)
  101778. {
  101779. *bytes = (unsigned int) ((const FlacReader*) client_data)->input->read (buffer, (int) *bytes);
  101780. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101781. }
  101782. static FLAC__StreamDecoderSeekStatus seekCallback_ (const FLAC__StreamDecoder*, FLAC__uint64 absolute_byte_offset, void* client_data)
  101783. {
  101784. ((const FlacReader*) client_data)->input->setPosition ((int) absolute_byte_offset);
  101785. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101786. }
  101787. static FLAC__StreamDecoderTellStatus tellCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* absolute_byte_offset, void* client_data)
  101788. {
  101789. *absolute_byte_offset = ((const FlacReader*) client_data)->input->getPosition();
  101790. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101791. }
  101792. static FLAC__StreamDecoderLengthStatus lengthCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* stream_length, void* client_data)
  101793. {
  101794. *stream_length = ((const FlacReader*) client_data)->input->getTotalLength();
  101795. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101796. }
  101797. static FLAC__bool eofCallback_ (const FLAC__StreamDecoder*, void* client_data)
  101798. {
  101799. return ((const FlacReader*) client_data)->input->isExhausted();
  101800. }
  101801. static FLAC__StreamDecoderWriteStatus writeCallback_ (const FLAC__StreamDecoder*,
  101802. const FLAC__Frame* frame,
  101803. const FLAC__int32* const buffer[],
  101804. void* client_data)
  101805. {
  101806. ((FlacReader*) client_data)->useSamples (buffer, frame->header.blocksize);
  101807. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101808. }
  101809. static void metadataCallback_ (const FLAC__StreamDecoder*,
  101810. const FLAC__StreamMetadata* metadata,
  101811. void* client_data)
  101812. {
  101813. ((FlacReader*) client_data)->useMetadata (metadata->data.stream_info);
  101814. }
  101815. static void errorCallback_ (const FLAC__StreamDecoder*, FLAC__StreamDecoderErrorStatus, void*)
  101816. {
  101817. }
  101818. juce_UseDebuggingNewOperator
  101819. };
  101820. class FlacWriter : public AudioFormatWriter
  101821. {
  101822. FLAC__StreamEncoder* encoder;
  101823. MemoryBlock temp;
  101824. public:
  101825. bool ok;
  101826. FlacWriter (OutputStream* const out,
  101827. const double sampleRate,
  101828. const int numChannels,
  101829. const int bitsPerSample_)
  101830. : AudioFormatWriter (out, flacFormatName,
  101831. sampleRate,
  101832. numChannels,
  101833. bitsPerSample_)
  101834. {
  101835. using namespace FlacNamespace;
  101836. encoder = FLAC__stream_encoder_new();
  101837. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  101838. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  101839. FLAC__stream_encoder_set_channels (encoder, numChannels);
  101840. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin (24, bitsPerSample));
  101841. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  101842. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  101843. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  101844. ok = FLAC__stream_encoder_init_stream (encoder,
  101845. encodeWriteCallback, encodeSeekCallback,
  101846. encodeTellCallback, encodeMetadataCallback,
  101847. (void*) this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  101848. }
  101849. ~FlacWriter()
  101850. {
  101851. if (ok)
  101852. {
  101853. FLAC__stream_encoder_finish (encoder);
  101854. output->flush();
  101855. }
  101856. else
  101857. {
  101858. output = 0; // to stop the base class deleting this, as it needs to be returned
  101859. // to the caller of createWriter()
  101860. }
  101861. FLAC__stream_encoder_delete (encoder);
  101862. }
  101863. bool write (const int** samplesToWrite, int numSamples)
  101864. {
  101865. if (! ok)
  101866. return false;
  101867. int* buf[3];
  101868. const int bitsToShift = 32 - bitsPerSample;
  101869. if (bitsToShift > 0)
  101870. {
  101871. const int numChannels = (samplesToWrite[1] == 0) ? 1 : 2;
  101872. temp.setSize (sizeof (int) * numSamples * numChannels);
  101873. buf[0] = (int*) temp.getData();
  101874. buf[1] = buf[0] + numSamples;
  101875. buf[2] = 0;
  101876. for (int i = numChannels; --i >= 0;)
  101877. {
  101878. if (samplesToWrite[i] != 0)
  101879. {
  101880. for (int j = 0; j < numSamples; ++j)
  101881. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  101882. }
  101883. }
  101884. samplesToWrite = (const int**) buf;
  101885. }
  101886. return FLAC__stream_encoder_process (encoder,
  101887. (const FLAC__int32**) samplesToWrite,
  101888. numSamples) != 0;
  101889. }
  101890. bool writeData (const void* const data, const int size) const
  101891. {
  101892. return output->write (data, size);
  101893. }
  101894. static void packUint32 (FLAC__uint32 val, FLAC__byte* b, const int bytes)
  101895. {
  101896. b += bytes;
  101897. for (int i = 0; i < bytes; ++i)
  101898. {
  101899. *(--b) = (FLAC__byte) (val & 0xff);
  101900. val >>= 8;
  101901. }
  101902. }
  101903. void writeMetaData (const FLAC__StreamMetadata* metadata)
  101904. {
  101905. using namespace FlacNamespace;
  101906. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  101907. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  101908. const unsigned int channelsMinus1 = info.channels - 1;
  101909. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  101910. packUint32 (info.min_blocksize, buffer, 2);
  101911. packUint32 (info.max_blocksize, buffer + 2, 2);
  101912. packUint32 (info.min_framesize, buffer + 4, 3);
  101913. packUint32 (info.max_framesize, buffer + 7, 3);
  101914. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  101915. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  101916. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  101917. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  101918. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  101919. memcpy (buffer + 18, info.md5sum, 16);
  101920. const bool ok = output->setPosition (4);
  101921. (void) ok;
  101922. // if this fails, you've given it an output stream that can't seek! It needs
  101923. // to be able to seek back to write the header
  101924. jassert (ok);
  101925. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  101926. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  101927. }
  101928. static FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FLAC__StreamEncoder*,
  101929. const FLAC__byte buffer[],
  101930. size_t bytes,
  101931. unsigned int /*samples*/,
  101932. unsigned int /*current_frame*/,
  101933. void* client_data)
  101934. {
  101935. using namespace FlacNamespace;
  101936. return ((FlacWriter*) client_data)->writeData (buffer, (int) bytes)
  101937. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  101938. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  101939. }
  101940. static FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FLAC__StreamEncoder*, FLAC__uint64, void*)
  101941. {
  101942. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  101943. }
  101944. static FLAC__StreamEncoderTellStatus encodeTellCallback (const FLAC__StreamEncoder*, FLAC__uint64*, void*)
  101945. {
  101946. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  101947. }
  101948. static void encodeMetadataCallback (const FLAC__StreamEncoder*,
  101949. const FLAC__StreamMetadata* metadata,
  101950. void* client_data)
  101951. {
  101952. ((FlacWriter*) client_data)->writeMetaData (metadata);
  101953. }
  101954. juce_UseDebuggingNewOperator
  101955. };
  101956. FlacAudioFormat::FlacAudioFormat()
  101957. : AudioFormat (flacFormatName, (const tchar**) flacExtensions)
  101958. {
  101959. }
  101960. FlacAudioFormat::~FlacAudioFormat()
  101961. {
  101962. }
  101963. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  101964. {
  101965. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  101966. return Array <int> (rates);
  101967. }
  101968. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  101969. {
  101970. const int depths[] = { 16, 24, 0 };
  101971. return Array <int> (depths);
  101972. }
  101973. bool FlacAudioFormat::canDoStereo()
  101974. {
  101975. return true;
  101976. }
  101977. bool FlacAudioFormat::canDoMono()
  101978. {
  101979. return true;
  101980. }
  101981. bool FlacAudioFormat::isCompressed()
  101982. {
  101983. return true;
  101984. }
  101985. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  101986. const bool deleteStreamIfOpeningFails)
  101987. {
  101988. FlacReader* r = new FlacReader (in);
  101989. if (r->sampleRate == 0)
  101990. {
  101991. if (! deleteStreamIfOpeningFails)
  101992. r->input = 0;
  101993. deleteAndZero (r);
  101994. }
  101995. return r;
  101996. }
  101997. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  101998. double sampleRate,
  101999. unsigned int numberOfChannels,
  102000. int bitsPerSample,
  102001. const StringPairArray& /*metadataValues*/,
  102002. int /*qualityOptionIndex*/)
  102003. {
  102004. if (getPossibleBitDepths().contains (bitsPerSample))
  102005. {
  102006. FlacWriter* w = new FlacWriter (out,
  102007. sampleRate,
  102008. numberOfChannels,
  102009. bitsPerSample);
  102010. if (! w->ok)
  102011. deleteAndZero (w);
  102012. return w;
  102013. }
  102014. return 0;
  102015. }
  102016. END_JUCE_NAMESPACE
  102017. #endif
  102018. /********* End of inlined file: juce_FlacAudioFormat.cpp *********/
  102019. /********* Start of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  102020. #if JUCE_USE_OGGVORBIS
  102021. #if JUCE_MAC
  102022. #define __MACOSX__ 1
  102023. #endif
  102024. namespace OggVorbisNamespace
  102025. {
  102026. #if JUCE_INCLUDE_OGGVORBIS_CODE
  102027. /********* Start of inlined file: vorbisenc.h *********/
  102028. #ifndef _OV_ENC_H_
  102029. #define _OV_ENC_H_
  102030. #ifdef __cplusplus
  102031. extern "C"
  102032. {
  102033. #endif /* __cplusplus */
  102034. /********* Start of inlined file: codec.h *********/
  102035. #ifndef _vorbis_codec_h_
  102036. #define _vorbis_codec_h_
  102037. #ifdef __cplusplus
  102038. extern "C"
  102039. {
  102040. #endif /* __cplusplus */
  102041. /********* Start of inlined file: ogg.h *********/
  102042. #ifndef _OGG_H
  102043. #define _OGG_H
  102044. #ifdef __cplusplus
  102045. extern "C" {
  102046. #endif
  102047. /********* Start of inlined file: os_types.h *********/
  102048. #ifndef _OS_TYPES_H
  102049. #define _OS_TYPES_H
  102050. /* make it easy on the folks that want to compile the libs with a
  102051. different malloc than stdlib */
  102052. #define _ogg_malloc malloc
  102053. #define _ogg_calloc calloc
  102054. #define _ogg_realloc realloc
  102055. #define _ogg_free free
  102056. #if defined(_WIN32)
  102057. # if defined(__CYGWIN__)
  102058. # include <_G_config.h>
  102059. typedef _G_int64_t ogg_int64_t;
  102060. typedef _G_int32_t ogg_int32_t;
  102061. typedef _G_uint32_t ogg_uint32_t;
  102062. typedef _G_int16_t ogg_int16_t;
  102063. typedef _G_uint16_t ogg_uint16_t;
  102064. # elif defined(__MINGW32__)
  102065. typedef short ogg_int16_t;
  102066. typedef unsigned short ogg_uint16_t;
  102067. typedef int ogg_int32_t;
  102068. typedef unsigned int ogg_uint32_t;
  102069. typedef long long ogg_int64_t;
  102070. typedef unsigned long long ogg_uint64_t;
  102071. # elif defined(__MWERKS__)
  102072. typedef long long ogg_int64_t;
  102073. typedef int ogg_int32_t;
  102074. typedef unsigned int ogg_uint32_t;
  102075. typedef short ogg_int16_t;
  102076. typedef unsigned short ogg_uint16_t;
  102077. # else
  102078. /* MSVC/Borland */
  102079. typedef __int64 ogg_int64_t;
  102080. typedef __int32 ogg_int32_t;
  102081. typedef unsigned __int32 ogg_uint32_t;
  102082. typedef __int16 ogg_int16_t;
  102083. typedef unsigned __int16 ogg_uint16_t;
  102084. # endif
  102085. #elif defined(__MACOS__)
  102086. # include <sys/types.h>
  102087. typedef SInt16 ogg_int16_t;
  102088. typedef UInt16 ogg_uint16_t;
  102089. typedef SInt32 ogg_int32_t;
  102090. typedef UInt32 ogg_uint32_t;
  102091. typedef SInt64 ogg_int64_t;
  102092. #elif defined(__MACOSX__) /* MacOS X Framework build */
  102093. # include <sys/types.h>
  102094. typedef int16_t ogg_int16_t;
  102095. typedef u_int16_t ogg_uint16_t;
  102096. typedef int32_t ogg_int32_t;
  102097. typedef u_int32_t ogg_uint32_t;
  102098. typedef int64_t ogg_int64_t;
  102099. #elif defined(__BEOS__)
  102100. /* Be */
  102101. # include <inttypes.h>
  102102. typedef int16_t ogg_int16_t;
  102103. typedef u_int16_t ogg_uint16_t;
  102104. typedef int32_t ogg_int32_t;
  102105. typedef u_int32_t ogg_uint32_t;
  102106. typedef int64_t ogg_int64_t;
  102107. #elif defined (__EMX__)
  102108. /* OS/2 GCC */
  102109. typedef short ogg_int16_t;
  102110. typedef unsigned short ogg_uint16_t;
  102111. typedef int ogg_int32_t;
  102112. typedef unsigned int ogg_uint32_t;
  102113. typedef long long ogg_int64_t;
  102114. #elif defined (DJGPP)
  102115. /* DJGPP */
  102116. typedef short ogg_int16_t;
  102117. typedef int ogg_int32_t;
  102118. typedef unsigned int ogg_uint32_t;
  102119. typedef long long ogg_int64_t;
  102120. #elif defined(R5900)
  102121. /* PS2 EE */
  102122. typedef long ogg_int64_t;
  102123. typedef int ogg_int32_t;
  102124. typedef unsigned ogg_uint32_t;
  102125. typedef short ogg_int16_t;
  102126. #elif defined(__SYMBIAN32__)
  102127. /* Symbian GCC */
  102128. typedef signed short ogg_int16_t;
  102129. typedef unsigned short ogg_uint16_t;
  102130. typedef signed int ogg_int32_t;
  102131. typedef unsigned int ogg_uint32_t;
  102132. typedef long long int ogg_int64_t;
  102133. #else
  102134. # include <sys/types.h>
  102135. /********* Start of inlined file: config_types.h *********/
  102136. #ifndef __CONFIG_TYPES_H__
  102137. #define __CONFIG_TYPES_H__
  102138. typedef int16_t ogg_int16_t;
  102139. typedef unsigned short ogg_uint16_t;
  102140. typedef int32_t ogg_int32_t;
  102141. typedef unsigned int ogg_uint32_t;
  102142. typedef int64_t ogg_int64_t;
  102143. #endif
  102144. /********* End of inlined file: config_types.h *********/
  102145. #endif
  102146. #endif /* _OS_TYPES_H */
  102147. /********* End of inlined file: os_types.h *********/
  102148. typedef struct {
  102149. long endbyte;
  102150. int endbit;
  102151. unsigned char *buffer;
  102152. unsigned char *ptr;
  102153. long storage;
  102154. } oggpack_buffer;
  102155. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  102156. typedef struct {
  102157. unsigned char *header;
  102158. long header_len;
  102159. unsigned char *body;
  102160. long body_len;
  102161. } ogg_page;
  102162. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  102163. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  102164. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  102165. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  102166. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  102167. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  102168. }
  102169. /* ogg_stream_state contains the current encode/decode state of a logical
  102170. Ogg bitstream **********************************************************/
  102171. typedef struct {
  102172. unsigned char *body_data; /* bytes from packet bodies */
  102173. long body_storage; /* storage elements allocated */
  102174. long body_fill; /* elements stored; fill mark */
  102175. long body_returned; /* elements of fill returned */
  102176. int *lacing_vals; /* The values that will go to the segment table */
  102177. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  102178. this way, but it is simple coupled to the
  102179. lacing fifo */
  102180. long lacing_storage;
  102181. long lacing_fill;
  102182. long lacing_packet;
  102183. long lacing_returned;
  102184. unsigned char header[282]; /* working space for header encode */
  102185. int header_fill;
  102186. int e_o_s; /* set when we have buffered the last packet in the
  102187. logical bitstream */
  102188. int b_o_s; /* set after we've written the initial page
  102189. of a logical bitstream */
  102190. long serialno;
  102191. long pageno;
  102192. ogg_int64_t packetno; /* sequence number for decode; the framing
  102193. knows where there's a hole in the data,
  102194. but we need coupling so that the codec
  102195. (which is in a seperate abstraction
  102196. layer) also knows about the gap */
  102197. ogg_int64_t granulepos;
  102198. } ogg_stream_state;
  102199. /* ogg_packet is used to encapsulate the data and metadata belonging
  102200. to a single raw Ogg/Vorbis packet *************************************/
  102201. typedef struct {
  102202. unsigned char *packet;
  102203. long bytes;
  102204. long b_o_s;
  102205. long e_o_s;
  102206. ogg_int64_t granulepos;
  102207. ogg_int64_t packetno; /* sequence number for decode; the framing
  102208. knows where there's a hole in the data,
  102209. but we need coupling so that the codec
  102210. (which is in a seperate abstraction
  102211. layer) also knows about the gap */
  102212. } ogg_packet;
  102213. typedef struct {
  102214. unsigned char *data;
  102215. int storage;
  102216. int fill;
  102217. int returned;
  102218. int unsynced;
  102219. int headerbytes;
  102220. int bodybytes;
  102221. } ogg_sync_state;
  102222. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  102223. extern void oggpack_writeinit(oggpack_buffer *b);
  102224. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  102225. extern void oggpack_writealign(oggpack_buffer *b);
  102226. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  102227. extern void oggpack_reset(oggpack_buffer *b);
  102228. extern void oggpack_writeclear(oggpack_buffer *b);
  102229. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  102230. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  102231. extern long oggpack_look(oggpack_buffer *b,int bits);
  102232. extern long oggpack_look1(oggpack_buffer *b);
  102233. extern void oggpack_adv(oggpack_buffer *b,int bits);
  102234. extern void oggpack_adv1(oggpack_buffer *b);
  102235. extern long oggpack_read(oggpack_buffer *b,int bits);
  102236. extern long oggpack_read1(oggpack_buffer *b);
  102237. extern long oggpack_bytes(oggpack_buffer *b);
  102238. extern long oggpack_bits(oggpack_buffer *b);
  102239. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  102240. extern void oggpackB_writeinit(oggpack_buffer *b);
  102241. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  102242. extern void oggpackB_writealign(oggpack_buffer *b);
  102243. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  102244. extern void oggpackB_reset(oggpack_buffer *b);
  102245. extern void oggpackB_writeclear(oggpack_buffer *b);
  102246. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  102247. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  102248. extern long oggpackB_look(oggpack_buffer *b,int bits);
  102249. extern long oggpackB_look1(oggpack_buffer *b);
  102250. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  102251. extern void oggpackB_adv1(oggpack_buffer *b);
  102252. extern long oggpackB_read(oggpack_buffer *b,int bits);
  102253. extern long oggpackB_read1(oggpack_buffer *b);
  102254. extern long oggpackB_bytes(oggpack_buffer *b);
  102255. extern long oggpackB_bits(oggpack_buffer *b);
  102256. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  102257. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  102258. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  102259. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  102260. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  102261. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  102262. extern int ogg_sync_init(ogg_sync_state *oy);
  102263. extern int ogg_sync_clear(ogg_sync_state *oy);
  102264. extern int ogg_sync_reset(ogg_sync_state *oy);
  102265. extern int ogg_sync_destroy(ogg_sync_state *oy);
  102266. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  102267. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  102268. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  102269. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  102270. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  102271. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  102272. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  102273. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  102274. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  102275. extern int ogg_stream_clear(ogg_stream_state *os);
  102276. extern int ogg_stream_reset(ogg_stream_state *os);
  102277. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  102278. extern int ogg_stream_destroy(ogg_stream_state *os);
  102279. extern int ogg_stream_eos(ogg_stream_state *os);
  102280. extern void ogg_page_checksum_set(ogg_page *og);
  102281. extern int ogg_page_version(ogg_page *og);
  102282. extern int ogg_page_continued(ogg_page *og);
  102283. extern int ogg_page_bos(ogg_page *og);
  102284. extern int ogg_page_eos(ogg_page *og);
  102285. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  102286. extern int ogg_page_serialno(ogg_page *og);
  102287. extern long ogg_page_pageno(ogg_page *og);
  102288. extern int ogg_page_packets(ogg_page *og);
  102289. extern void ogg_packet_clear(ogg_packet *op);
  102290. #ifdef __cplusplus
  102291. }
  102292. #endif
  102293. #endif /* _OGG_H */
  102294. /********* End of inlined file: ogg.h *********/
  102295. typedef struct vorbis_info{
  102296. int version;
  102297. int channels;
  102298. long rate;
  102299. /* The below bitrate declarations are *hints*.
  102300. Combinations of the three values carry the following implications:
  102301. all three set to the same value:
  102302. implies a fixed rate bitstream
  102303. only nominal set:
  102304. implies a VBR stream that averages the nominal bitrate. No hard
  102305. upper/lower limit
  102306. upper and or lower set:
  102307. implies a VBR bitstream that obeys the bitrate limits. nominal
  102308. may also be set to give a nominal rate.
  102309. none set:
  102310. the coder does not care to speculate.
  102311. */
  102312. long bitrate_upper;
  102313. long bitrate_nominal;
  102314. long bitrate_lower;
  102315. long bitrate_window;
  102316. void *codec_setup;
  102317. } vorbis_info;
  102318. /* vorbis_dsp_state buffers the current vorbis audio
  102319. analysis/synthesis state. The DSP state belongs to a specific
  102320. logical bitstream ****************************************************/
  102321. typedef struct vorbis_dsp_state{
  102322. int analysisp;
  102323. vorbis_info *vi;
  102324. float **pcm;
  102325. float **pcmret;
  102326. int pcm_storage;
  102327. int pcm_current;
  102328. int pcm_returned;
  102329. int preextrapolate;
  102330. int eofflag;
  102331. long lW;
  102332. long W;
  102333. long nW;
  102334. long centerW;
  102335. ogg_int64_t granulepos;
  102336. ogg_int64_t sequence;
  102337. ogg_int64_t glue_bits;
  102338. ogg_int64_t time_bits;
  102339. ogg_int64_t floor_bits;
  102340. ogg_int64_t res_bits;
  102341. void *backend_state;
  102342. } vorbis_dsp_state;
  102343. typedef struct vorbis_block{
  102344. /* necessary stream state for linking to the framing abstraction */
  102345. float **pcm; /* this is a pointer into local storage */
  102346. oggpack_buffer opb;
  102347. long lW;
  102348. long W;
  102349. long nW;
  102350. int pcmend;
  102351. int mode;
  102352. int eofflag;
  102353. ogg_int64_t granulepos;
  102354. ogg_int64_t sequence;
  102355. vorbis_dsp_state *vd; /* For read-only access of configuration */
  102356. /* local storage to avoid remallocing; it's up to the mapping to
  102357. structure it */
  102358. void *localstore;
  102359. long localtop;
  102360. long localalloc;
  102361. long totaluse;
  102362. struct alloc_chain *reap;
  102363. /* bitmetrics for the frame */
  102364. long glue_bits;
  102365. long time_bits;
  102366. long floor_bits;
  102367. long res_bits;
  102368. void *internal;
  102369. } vorbis_block;
  102370. /* vorbis_block is a single block of data to be processed as part of
  102371. the analysis/synthesis stream; it belongs to a specific logical
  102372. bitstream, but is independant from other vorbis_blocks belonging to
  102373. that logical bitstream. *************************************************/
  102374. struct alloc_chain{
  102375. void *ptr;
  102376. struct alloc_chain *next;
  102377. };
  102378. /* vorbis_info contains all the setup information specific to the
  102379. specific compression/decompression mode in progress (eg,
  102380. psychoacoustic settings, channel setup, options, codebook
  102381. etc). vorbis_info and substructures are in backends.h.
  102382. *********************************************************************/
  102383. /* the comments are not part of vorbis_info so that vorbis_info can be
  102384. static storage */
  102385. typedef struct vorbis_comment{
  102386. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  102387. whatever vendor is set to in encode */
  102388. char **user_comments;
  102389. int *comment_lengths;
  102390. int comments;
  102391. char *vendor;
  102392. } vorbis_comment;
  102393. /* libvorbis encodes in two abstraction layers; first we perform DSP
  102394. and produce a packet (see docs/analysis.txt). The packet is then
  102395. coded into a framed OggSquish bitstream by the second layer (see
  102396. docs/framing.txt). Decode is the reverse process; we sync/frame
  102397. the bitstream and extract individual packets, then decode the
  102398. packet back into PCM audio.
  102399. The extra framing/packetizing is used in streaming formats, such as
  102400. files. Over the net (such as with UDP), the framing and
  102401. packetization aren't necessary as they're provided by the transport
  102402. and the streaming layer is not used */
  102403. /* Vorbis PRIMITIVES: general ***************************************/
  102404. extern void vorbis_info_init(vorbis_info *vi);
  102405. extern void vorbis_info_clear(vorbis_info *vi);
  102406. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  102407. extern void vorbis_comment_init(vorbis_comment *vc);
  102408. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  102409. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  102410. const char *tag, char *contents);
  102411. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  102412. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  102413. extern void vorbis_comment_clear(vorbis_comment *vc);
  102414. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  102415. extern int vorbis_block_clear(vorbis_block *vb);
  102416. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  102417. extern double vorbis_granule_time(vorbis_dsp_state *v,
  102418. ogg_int64_t granulepos);
  102419. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  102420. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  102421. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  102422. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  102423. vorbis_comment *vc,
  102424. ogg_packet *op,
  102425. ogg_packet *op_comm,
  102426. ogg_packet *op_code);
  102427. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  102428. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  102429. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  102430. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  102431. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  102432. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  102433. ogg_packet *op);
  102434. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  102435. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  102436. ogg_packet *op);
  102437. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  102438. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  102439. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  102440. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  102441. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  102442. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  102443. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  102444. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  102445. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  102446. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  102447. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  102448. /* Vorbis ERRORS and return codes ***********************************/
  102449. #define OV_FALSE -1
  102450. #define OV_EOF -2
  102451. #define OV_HOLE -3
  102452. #define OV_EREAD -128
  102453. #define OV_EFAULT -129
  102454. #define OV_EIMPL -130
  102455. #define OV_EINVAL -131
  102456. #define OV_ENOTVORBIS -132
  102457. #define OV_EBADHEADER -133
  102458. #define OV_EVERSION -134
  102459. #define OV_ENOTAUDIO -135
  102460. #define OV_EBADPACKET -136
  102461. #define OV_EBADLINK -137
  102462. #define OV_ENOSEEK -138
  102463. #ifdef __cplusplus
  102464. }
  102465. #endif /* __cplusplus */
  102466. #endif
  102467. /********* End of inlined file: codec.h *********/
  102468. extern int vorbis_encode_init(vorbis_info *vi,
  102469. long channels,
  102470. long rate,
  102471. long max_bitrate,
  102472. long nominal_bitrate,
  102473. long min_bitrate);
  102474. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  102475. long channels,
  102476. long rate,
  102477. long max_bitrate,
  102478. long nominal_bitrate,
  102479. long min_bitrate);
  102480. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  102481. long channels,
  102482. long rate,
  102483. float quality /* quality level from 0. (lo) to 1. (hi) */
  102484. );
  102485. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  102486. long channels,
  102487. long rate,
  102488. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  102489. );
  102490. extern int vorbis_encode_setup_init(vorbis_info *vi);
  102491. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  102492. /* deprecated rate management supported only for compatability */
  102493. #define OV_ECTL_RATEMANAGE_GET 0x10
  102494. #define OV_ECTL_RATEMANAGE_SET 0x11
  102495. #define OV_ECTL_RATEMANAGE_AVG 0x12
  102496. #define OV_ECTL_RATEMANAGE_HARD 0x13
  102497. struct ovectl_ratemanage_arg {
  102498. int management_active;
  102499. long bitrate_hard_min;
  102500. long bitrate_hard_max;
  102501. double bitrate_hard_window;
  102502. long bitrate_av_lo;
  102503. long bitrate_av_hi;
  102504. double bitrate_av_window;
  102505. double bitrate_av_window_center;
  102506. };
  102507. /* new rate setup */
  102508. #define OV_ECTL_RATEMANAGE2_GET 0x14
  102509. #define OV_ECTL_RATEMANAGE2_SET 0x15
  102510. struct ovectl_ratemanage2_arg {
  102511. int management_active;
  102512. long bitrate_limit_min_kbps;
  102513. long bitrate_limit_max_kbps;
  102514. long bitrate_limit_reservoir_bits;
  102515. double bitrate_limit_reservoir_bias;
  102516. long bitrate_average_kbps;
  102517. double bitrate_average_damping;
  102518. };
  102519. #define OV_ECTL_LOWPASS_GET 0x20
  102520. #define OV_ECTL_LOWPASS_SET 0x21
  102521. #define OV_ECTL_IBLOCK_GET 0x30
  102522. #define OV_ECTL_IBLOCK_SET 0x31
  102523. #ifdef __cplusplus
  102524. }
  102525. #endif /* __cplusplus */
  102526. #endif
  102527. /********* End of inlined file: vorbisenc.h *********/
  102528. /********* Start of inlined file: vorbisfile.h *********/
  102529. #ifndef _OV_FILE_H_
  102530. #define _OV_FILE_H_
  102531. #ifdef __cplusplus
  102532. extern "C"
  102533. {
  102534. #endif /* __cplusplus */
  102535. #include <stdio.h>
  102536. /* The function prototypes for the callbacks are basically the same as for
  102537. * the stdio functions fread, fseek, fclose, ftell.
  102538. * The one difference is that the FILE * arguments have been replaced with
  102539. * a void * - this is to be used as a pointer to whatever internal data these
  102540. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  102541. *
  102542. * If you use other functions, check the docs for these functions and return
  102543. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  102544. * unseekable
  102545. */
  102546. typedef struct {
  102547. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  102548. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  102549. int (*close_func) (void *datasource);
  102550. long (*tell_func) (void *datasource);
  102551. } ov_callbacks;
  102552. #define NOTOPEN 0
  102553. #define PARTOPEN 1
  102554. #define OPENED 2
  102555. #define STREAMSET 3
  102556. #define INITSET 4
  102557. typedef struct OggVorbis_File {
  102558. void *datasource; /* Pointer to a FILE *, etc. */
  102559. int seekable;
  102560. ogg_int64_t offset;
  102561. ogg_int64_t end;
  102562. ogg_sync_state oy;
  102563. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  102564. stream appears */
  102565. int links;
  102566. ogg_int64_t *offsets;
  102567. ogg_int64_t *dataoffsets;
  102568. long *serialnos;
  102569. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  102570. compatability; x2 size, stores both
  102571. beginning and end values */
  102572. vorbis_info *vi;
  102573. vorbis_comment *vc;
  102574. /* Decoding working state local storage */
  102575. ogg_int64_t pcm_offset;
  102576. int ready_state;
  102577. long current_serialno;
  102578. int current_link;
  102579. double bittrack;
  102580. double samptrack;
  102581. ogg_stream_state os; /* take physical pages, weld into a logical
  102582. stream of packets */
  102583. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  102584. vorbis_block vb; /* local working space for packet->PCM decode */
  102585. ov_callbacks callbacks;
  102586. } OggVorbis_File;
  102587. extern int ov_clear(OggVorbis_File *vf);
  102588. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  102589. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  102590. char *initial, long ibytes, ov_callbacks callbacks);
  102591. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  102592. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  102593. char *initial, long ibytes, ov_callbacks callbacks);
  102594. extern int ov_test_open(OggVorbis_File *vf);
  102595. extern long ov_bitrate(OggVorbis_File *vf,int i);
  102596. extern long ov_bitrate_instant(OggVorbis_File *vf);
  102597. extern long ov_streams(OggVorbis_File *vf);
  102598. extern long ov_seekable(OggVorbis_File *vf);
  102599. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  102600. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  102601. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  102602. extern double ov_time_total(OggVorbis_File *vf,int i);
  102603. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  102604. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  102605. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  102606. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  102607. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  102608. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  102609. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  102610. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  102611. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  102612. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  102613. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  102614. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  102615. extern double ov_time_tell(OggVorbis_File *vf);
  102616. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  102617. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  102618. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  102619. int *bitstream);
  102620. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  102621. int bigendianp,int word,int sgned,int *bitstream);
  102622. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  102623. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  102624. extern int ov_halfrate_p(OggVorbis_File *vf);
  102625. #ifdef __cplusplus
  102626. }
  102627. #endif /* __cplusplus */
  102628. #endif
  102629. /********* End of inlined file: vorbisfile.h *********/
  102630. /********* Start of inlined file: bitwise.c *********/
  102631. /* We're 'LSb' endian; if we write a word but read individual bits,
  102632. then we'll read the lsb first */
  102633. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  102634. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  102635. // tasks..
  102636. #ifdef _MSC_VER
  102637. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  102638. #endif
  102639. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  102640. #if JUCE_USE_OGGVORBIS
  102641. #include <string.h>
  102642. #include <stdlib.h>
  102643. #define BUFFER_INCREMENT 256
  102644. static const unsigned long mask[]=
  102645. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  102646. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  102647. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  102648. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  102649. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  102650. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  102651. 0x3fffffff,0x7fffffff,0xffffffff };
  102652. static const unsigned int mask8B[]=
  102653. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  102654. void oggpack_writeinit(oggpack_buffer *b){
  102655. memset(b,0,sizeof(*b));
  102656. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  102657. b->buffer[0]='\0';
  102658. b->storage=BUFFER_INCREMENT;
  102659. }
  102660. void oggpackB_writeinit(oggpack_buffer *b){
  102661. oggpack_writeinit(b);
  102662. }
  102663. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  102664. long bytes=bits>>3;
  102665. bits-=bytes*8;
  102666. b->ptr=b->buffer+bytes;
  102667. b->endbit=bits;
  102668. b->endbyte=bytes;
  102669. *b->ptr&=mask[bits];
  102670. }
  102671. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  102672. long bytes=bits>>3;
  102673. bits-=bytes*8;
  102674. b->ptr=b->buffer+bytes;
  102675. b->endbit=bits;
  102676. b->endbyte=bytes;
  102677. *b->ptr&=mask8B[bits];
  102678. }
  102679. /* Takes only up to 32 bits. */
  102680. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  102681. if(b->endbyte+4>=b->storage){
  102682. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  102683. b->storage+=BUFFER_INCREMENT;
  102684. b->ptr=b->buffer+b->endbyte;
  102685. }
  102686. value&=mask[bits];
  102687. bits+=b->endbit;
  102688. b->ptr[0]|=value<<b->endbit;
  102689. if(bits>=8){
  102690. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  102691. if(bits>=16){
  102692. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  102693. if(bits>=24){
  102694. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  102695. if(bits>=32){
  102696. if(b->endbit)
  102697. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  102698. else
  102699. b->ptr[4]=0;
  102700. }
  102701. }
  102702. }
  102703. }
  102704. b->endbyte+=bits/8;
  102705. b->ptr+=bits/8;
  102706. b->endbit=bits&7;
  102707. }
  102708. /* Takes only up to 32 bits. */
  102709. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  102710. if(b->endbyte+4>=b->storage){
  102711. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  102712. b->storage+=BUFFER_INCREMENT;
  102713. b->ptr=b->buffer+b->endbyte;
  102714. }
  102715. value=(value&mask[bits])<<(32-bits);
  102716. bits+=b->endbit;
  102717. b->ptr[0]|=value>>(24+b->endbit);
  102718. if(bits>=8){
  102719. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  102720. if(bits>=16){
  102721. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  102722. if(bits>=24){
  102723. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  102724. if(bits>=32){
  102725. if(b->endbit)
  102726. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  102727. else
  102728. b->ptr[4]=0;
  102729. }
  102730. }
  102731. }
  102732. }
  102733. b->endbyte+=bits/8;
  102734. b->ptr+=bits/8;
  102735. b->endbit=bits&7;
  102736. }
  102737. void oggpack_writealign(oggpack_buffer *b){
  102738. int bits=8-b->endbit;
  102739. if(bits<8)
  102740. oggpack_write(b,0,bits);
  102741. }
  102742. void oggpackB_writealign(oggpack_buffer *b){
  102743. int bits=8-b->endbit;
  102744. if(bits<8)
  102745. oggpackB_write(b,0,bits);
  102746. }
  102747. static void oggpack_writecopy_helper(oggpack_buffer *b,
  102748. void *source,
  102749. long bits,
  102750. void (*w)(oggpack_buffer *,
  102751. unsigned long,
  102752. int),
  102753. int msb){
  102754. unsigned char *ptr=(unsigned char *)source;
  102755. long bytes=bits/8;
  102756. bits-=bytes*8;
  102757. if(b->endbit){
  102758. int i;
  102759. /* unaligned copy. Do it the hard way. */
  102760. for(i=0;i<bytes;i++)
  102761. w(b,(unsigned long)(ptr[i]),8);
  102762. }else{
  102763. /* aligned block copy */
  102764. if(b->endbyte+bytes+1>=b->storage){
  102765. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  102766. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  102767. b->ptr=b->buffer+b->endbyte;
  102768. }
  102769. memmove(b->ptr,source,bytes);
  102770. b->ptr+=bytes;
  102771. b->endbyte+=bytes;
  102772. *b->ptr=0;
  102773. }
  102774. if(bits){
  102775. if(msb)
  102776. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  102777. else
  102778. w(b,(unsigned long)(ptr[bytes]),bits);
  102779. }
  102780. }
  102781. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  102782. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  102783. }
  102784. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  102785. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  102786. }
  102787. void oggpack_reset(oggpack_buffer *b){
  102788. b->ptr=b->buffer;
  102789. b->buffer[0]=0;
  102790. b->endbit=b->endbyte=0;
  102791. }
  102792. void oggpackB_reset(oggpack_buffer *b){
  102793. oggpack_reset(b);
  102794. }
  102795. void oggpack_writeclear(oggpack_buffer *b){
  102796. _ogg_free(b->buffer);
  102797. memset(b,0,sizeof(*b));
  102798. }
  102799. void oggpackB_writeclear(oggpack_buffer *b){
  102800. oggpack_writeclear(b);
  102801. }
  102802. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  102803. memset(b,0,sizeof(*b));
  102804. b->buffer=b->ptr=buf;
  102805. b->storage=bytes;
  102806. }
  102807. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  102808. oggpack_readinit(b,buf,bytes);
  102809. }
  102810. /* Read in bits without advancing the bitptr; bits <= 32 */
  102811. long oggpack_look(oggpack_buffer *b,int bits){
  102812. unsigned long ret;
  102813. unsigned long m=mask[bits];
  102814. bits+=b->endbit;
  102815. if(b->endbyte+4>=b->storage){
  102816. /* not the main path */
  102817. if(b->endbyte*8+bits>b->storage*8)return(-1);
  102818. }
  102819. ret=b->ptr[0]>>b->endbit;
  102820. if(bits>8){
  102821. ret|=b->ptr[1]<<(8-b->endbit);
  102822. if(bits>16){
  102823. ret|=b->ptr[2]<<(16-b->endbit);
  102824. if(bits>24){
  102825. ret|=b->ptr[3]<<(24-b->endbit);
  102826. if(bits>32 && b->endbit)
  102827. ret|=b->ptr[4]<<(32-b->endbit);
  102828. }
  102829. }
  102830. }
  102831. return(m&ret);
  102832. }
  102833. /* Read in bits without advancing the bitptr; bits <= 32 */
  102834. long oggpackB_look(oggpack_buffer *b,int bits){
  102835. unsigned long ret;
  102836. int m=32-bits;
  102837. bits+=b->endbit;
  102838. if(b->endbyte+4>=b->storage){
  102839. /* not the main path */
  102840. if(b->endbyte*8+bits>b->storage*8)return(-1);
  102841. }
  102842. ret=b->ptr[0]<<(24+b->endbit);
  102843. if(bits>8){
  102844. ret|=b->ptr[1]<<(16+b->endbit);
  102845. if(bits>16){
  102846. ret|=b->ptr[2]<<(8+b->endbit);
  102847. if(bits>24){
  102848. ret|=b->ptr[3]<<(b->endbit);
  102849. if(bits>32 && b->endbit)
  102850. ret|=b->ptr[4]>>(8-b->endbit);
  102851. }
  102852. }
  102853. }
  102854. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  102855. }
  102856. long oggpack_look1(oggpack_buffer *b){
  102857. if(b->endbyte>=b->storage)return(-1);
  102858. return((b->ptr[0]>>b->endbit)&1);
  102859. }
  102860. long oggpackB_look1(oggpack_buffer *b){
  102861. if(b->endbyte>=b->storage)return(-1);
  102862. return((b->ptr[0]>>(7-b->endbit))&1);
  102863. }
  102864. void oggpack_adv(oggpack_buffer *b,int bits){
  102865. bits+=b->endbit;
  102866. b->ptr+=bits/8;
  102867. b->endbyte+=bits/8;
  102868. b->endbit=bits&7;
  102869. }
  102870. void oggpackB_adv(oggpack_buffer *b,int bits){
  102871. oggpack_adv(b,bits);
  102872. }
  102873. void oggpack_adv1(oggpack_buffer *b){
  102874. if(++(b->endbit)>7){
  102875. b->endbit=0;
  102876. b->ptr++;
  102877. b->endbyte++;
  102878. }
  102879. }
  102880. void oggpackB_adv1(oggpack_buffer *b){
  102881. oggpack_adv1(b);
  102882. }
  102883. /* bits <= 32 */
  102884. long oggpack_read(oggpack_buffer *b,int bits){
  102885. long ret;
  102886. unsigned long m=mask[bits];
  102887. bits+=b->endbit;
  102888. if(b->endbyte+4>=b->storage){
  102889. /* not the main path */
  102890. ret=-1L;
  102891. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  102892. }
  102893. ret=b->ptr[0]>>b->endbit;
  102894. if(bits>8){
  102895. ret|=b->ptr[1]<<(8-b->endbit);
  102896. if(bits>16){
  102897. ret|=b->ptr[2]<<(16-b->endbit);
  102898. if(bits>24){
  102899. ret|=b->ptr[3]<<(24-b->endbit);
  102900. if(bits>32 && b->endbit){
  102901. ret|=b->ptr[4]<<(32-b->endbit);
  102902. }
  102903. }
  102904. }
  102905. }
  102906. ret&=m;
  102907. overflow:
  102908. b->ptr+=bits/8;
  102909. b->endbyte+=bits/8;
  102910. b->endbit=bits&7;
  102911. return(ret);
  102912. }
  102913. /* bits <= 32 */
  102914. long oggpackB_read(oggpack_buffer *b,int bits){
  102915. long ret;
  102916. long m=32-bits;
  102917. bits+=b->endbit;
  102918. if(b->endbyte+4>=b->storage){
  102919. /* not the main path */
  102920. ret=-1L;
  102921. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  102922. }
  102923. ret=b->ptr[0]<<(24+b->endbit);
  102924. if(bits>8){
  102925. ret|=b->ptr[1]<<(16+b->endbit);
  102926. if(bits>16){
  102927. ret|=b->ptr[2]<<(8+b->endbit);
  102928. if(bits>24){
  102929. ret|=b->ptr[3]<<(b->endbit);
  102930. if(bits>32 && b->endbit)
  102931. ret|=b->ptr[4]>>(8-b->endbit);
  102932. }
  102933. }
  102934. }
  102935. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  102936. overflow:
  102937. b->ptr+=bits/8;
  102938. b->endbyte+=bits/8;
  102939. b->endbit=bits&7;
  102940. return(ret);
  102941. }
  102942. long oggpack_read1(oggpack_buffer *b){
  102943. long ret;
  102944. if(b->endbyte>=b->storage){
  102945. /* not the main path */
  102946. ret=-1L;
  102947. goto overflow;
  102948. }
  102949. ret=(b->ptr[0]>>b->endbit)&1;
  102950. overflow:
  102951. b->endbit++;
  102952. if(b->endbit>7){
  102953. b->endbit=0;
  102954. b->ptr++;
  102955. b->endbyte++;
  102956. }
  102957. return(ret);
  102958. }
  102959. long oggpackB_read1(oggpack_buffer *b){
  102960. long ret;
  102961. if(b->endbyte>=b->storage){
  102962. /* not the main path */
  102963. ret=-1L;
  102964. goto overflow;
  102965. }
  102966. ret=(b->ptr[0]>>(7-b->endbit))&1;
  102967. overflow:
  102968. b->endbit++;
  102969. if(b->endbit>7){
  102970. b->endbit=0;
  102971. b->ptr++;
  102972. b->endbyte++;
  102973. }
  102974. return(ret);
  102975. }
  102976. long oggpack_bytes(oggpack_buffer *b){
  102977. return(b->endbyte+(b->endbit+7)/8);
  102978. }
  102979. long oggpack_bits(oggpack_buffer *b){
  102980. return(b->endbyte*8+b->endbit);
  102981. }
  102982. long oggpackB_bytes(oggpack_buffer *b){
  102983. return oggpack_bytes(b);
  102984. }
  102985. long oggpackB_bits(oggpack_buffer *b){
  102986. return oggpack_bits(b);
  102987. }
  102988. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  102989. return(b->buffer);
  102990. }
  102991. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  102992. return oggpack_get_buffer(b);
  102993. }
  102994. /* Self test of the bitwise routines; everything else is based on
  102995. them, so they damned well better be solid. */
  102996. #ifdef _V_SELFTEST
  102997. #include <stdio.h>
  102998. static int ilog(unsigned int v){
  102999. int ret=0;
  103000. while(v){
  103001. ret++;
  103002. v>>=1;
  103003. }
  103004. return(ret);
  103005. }
  103006. oggpack_buffer o;
  103007. oggpack_buffer r;
  103008. void report(char *in){
  103009. fprintf(stderr,"%s",in);
  103010. exit(1);
  103011. }
  103012. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  103013. long bytes,i;
  103014. unsigned char *buffer;
  103015. oggpack_reset(&o);
  103016. for(i=0;i<vals;i++)
  103017. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  103018. buffer=oggpack_get_buffer(&o);
  103019. bytes=oggpack_bytes(&o);
  103020. if(bytes!=compsize)report("wrong number of bytes!\n");
  103021. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  103022. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  103023. report("wrote incorrect value!\n");
  103024. }
  103025. oggpack_readinit(&r,buffer,bytes);
  103026. for(i=0;i<vals;i++){
  103027. int tbit=bits?bits:ilog(b[i]);
  103028. if(oggpack_look(&r,tbit)==-1)
  103029. report("out of data!\n");
  103030. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  103031. report("looked at incorrect value!\n");
  103032. if(tbit==1)
  103033. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  103034. report("looked at single bit incorrect value!\n");
  103035. if(tbit==1){
  103036. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  103037. report("read incorrect single bit value!\n");
  103038. }else{
  103039. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  103040. report("read incorrect value!\n");
  103041. }
  103042. }
  103043. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103044. }
  103045. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  103046. long bytes,i;
  103047. unsigned char *buffer;
  103048. oggpackB_reset(&o);
  103049. for(i=0;i<vals;i++)
  103050. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  103051. buffer=oggpackB_get_buffer(&o);
  103052. bytes=oggpackB_bytes(&o);
  103053. if(bytes!=compsize)report("wrong number of bytes!\n");
  103054. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  103055. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  103056. report("wrote incorrect value!\n");
  103057. }
  103058. oggpackB_readinit(&r,buffer,bytes);
  103059. for(i=0;i<vals;i++){
  103060. int tbit=bits?bits:ilog(b[i]);
  103061. if(oggpackB_look(&r,tbit)==-1)
  103062. report("out of data!\n");
  103063. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  103064. report("looked at incorrect value!\n");
  103065. if(tbit==1)
  103066. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  103067. report("looked at single bit incorrect value!\n");
  103068. if(tbit==1){
  103069. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  103070. report("read incorrect single bit value!\n");
  103071. }else{
  103072. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  103073. report("read incorrect value!\n");
  103074. }
  103075. }
  103076. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103077. }
  103078. int main(void){
  103079. unsigned char *buffer;
  103080. long bytes,i;
  103081. static unsigned long testbuffer1[]=
  103082. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  103083. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  103084. int test1size=43;
  103085. static unsigned long testbuffer2[]=
  103086. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  103087. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  103088. 85525151,0,12321,1,349528352};
  103089. int test2size=21;
  103090. static unsigned long testbuffer3[]=
  103091. {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,
  103092. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  103093. int test3size=56;
  103094. static unsigned long large[]=
  103095. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  103096. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  103097. 85525151,0,12321,1,2146528352};
  103098. int onesize=33;
  103099. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  103100. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  103101. 223,4};
  103102. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  103103. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  103104. 245,251,128};
  103105. int twosize=6;
  103106. static int two[6]={61,255,255,251,231,29};
  103107. static int twoB[6]={247,63,255,253,249,120};
  103108. int threesize=54;
  103109. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  103110. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  103111. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  103112. 100,52,4,14,18,86,77,1};
  103113. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  103114. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  103115. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  103116. 200,20,254,4,58,106,176,144,0};
  103117. int foursize=38;
  103118. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  103119. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  103120. 28,2,133,0,1};
  103121. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  103122. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  103123. 129,10,4,32};
  103124. int fivesize=45;
  103125. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  103126. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  103127. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  103128. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  103129. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  103130. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  103131. int sixsize=7;
  103132. static int six[7]={17,177,170,242,169,19,148};
  103133. static int sixB[7]={136,141,85,79,149,200,41};
  103134. /* Test read/write together */
  103135. /* Later we test against pregenerated bitstreams */
  103136. oggpack_writeinit(&o);
  103137. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  103138. cliptest(testbuffer1,test1size,0,one,onesize);
  103139. fprintf(stderr,"ok.");
  103140. fprintf(stderr,"\nNull bit call (LSb): ");
  103141. cliptest(testbuffer3,test3size,0,two,twosize);
  103142. fprintf(stderr,"ok.");
  103143. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  103144. cliptest(testbuffer2,test2size,0,three,threesize);
  103145. fprintf(stderr,"ok.");
  103146. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  103147. oggpack_reset(&o);
  103148. for(i=0;i<test2size;i++)
  103149. oggpack_write(&o,large[i],32);
  103150. buffer=oggpack_get_buffer(&o);
  103151. bytes=oggpack_bytes(&o);
  103152. oggpack_readinit(&r,buffer,bytes);
  103153. for(i=0;i<test2size;i++){
  103154. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  103155. if(oggpack_look(&r,32)!=large[i]){
  103156. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  103157. oggpack_look(&r,32),large[i]);
  103158. report("read incorrect value!\n");
  103159. }
  103160. oggpack_adv(&r,32);
  103161. }
  103162. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103163. fprintf(stderr,"ok.");
  103164. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  103165. cliptest(testbuffer1,test1size,7,four,foursize);
  103166. fprintf(stderr,"ok.");
  103167. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  103168. cliptest(testbuffer2,test2size,17,five,fivesize);
  103169. fprintf(stderr,"ok.");
  103170. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  103171. cliptest(testbuffer3,test3size,1,six,sixsize);
  103172. fprintf(stderr,"ok.");
  103173. fprintf(stderr,"\nTesting read past end (LSb): ");
  103174. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103175. for(i=0;i<64;i++){
  103176. if(oggpack_read(&r,1)!=0){
  103177. fprintf(stderr,"failed; got -1 prematurely.\n");
  103178. exit(1);
  103179. }
  103180. }
  103181. if(oggpack_look(&r,1)!=-1 ||
  103182. oggpack_read(&r,1)!=-1){
  103183. fprintf(stderr,"failed; read past end without -1.\n");
  103184. exit(1);
  103185. }
  103186. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103187. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  103188. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  103189. exit(1);
  103190. }
  103191. if(oggpack_look(&r,18)!=0 ||
  103192. oggpack_look(&r,18)!=0){
  103193. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  103194. exit(1);
  103195. }
  103196. if(oggpack_look(&r,19)!=-1 ||
  103197. oggpack_look(&r,19)!=-1){
  103198. fprintf(stderr,"failed; read past end without -1.\n");
  103199. exit(1);
  103200. }
  103201. if(oggpack_look(&r,32)!=-1 ||
  103202. oggpack_look(&r,32)!=-1){
  103203. fprintf(stderr,"failed; read past end without -1.\n");
  103204. exit(1);
  103205. }
  103206. oggpack_writeclear(&o);
  103207. fprintf(stderr,"ok.\n");
  103208. /********** lazy, cut-n-paste retest with MSb packing ***********/
  103209. /* Test read/write together */
  103210. /* Later we test against pregenerated bitstreams */
  103211. oggpackB_writeinit(&o);
  103212. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  103213. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  103214. fprintf(stderr,"ok.");
  103215. fprintf(stderr,"\nNull bit call (MSb): ");
  103216. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  103217. fprintf(stderr,"ok.");
  103218. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  103219. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  103220. fprintf(stderr,"ok.");
  103221. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  103222. oggpackB_reset(&o);
  103223. for(i=0;i<test2size;i++)
  103224. oggpackB_write(&o,large[i],32);
  103225. buffer=oggpackB_get_buffer(&o);
  103226. bytes=oggpackB_bytes(&o);
  103227. oggpackB_readinit(&r,buffer,bytes);
  103228. for(i=0;i<test2size;i++){
  103229. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  103230. if(oggpackB_look(&r,32)!=large[i]){
  103231. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  103232. oggpackB_look(&r,32),large[i]);
  103233. report("read incorrect value!\n");
  103234. }
  103235. oggpackB_adv(&r,32);
  103236. }
  103237. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103238. fprintf(stderr,"ok.");
  103239. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  103240. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  103241. fprintf(stderr,"ok.");
  103242. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  103243. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  103244. fprintf(stderr,"ok.");
  103245. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  103246. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  103247. fprintf(stderr,"ok.");
  103248. fprintf(stderr,"\nTesting read past end (MSb): ");
  103249. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103250. for(i=0;i<64;i++){
  103251. if(oggpackB_read(&r,1)!=0){
  103252. fprintf(stderr,"failed; got -1 prematurely.\n");
  103253. exit(1);
  103254. }
  103255. }
  103256. if(oggpackB_look(&r,1)!=-1 ||
  103257. oggpackB_read(&r,1)!=-1){
  103258. fprintf(stderr,"failed; read past end without -1.\n");
  103259. exit(1);
  103260. }
  103261. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103262. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  103263. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  103264. exit(1);
  103265. }
  103266. if(oggpackB_look(&r,18)!=0 ||
  103267. oggpackB_look(&r,18)!=0){
  103268. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  103269. exit(1);
  103270. }
  103271. if(oggpackB_look(&r,19)!=-1 ||
  103272. oggpackB_look(&r,19)!=-1){
  103273. fprintf(stderr,"failed; read past end without -1.\n");
  103274. exit(1);
  103275. }
  103276. if(oggpackB_look(&r,32)!=-1 ||
  103277. oggpackB_look(&r,32)!=-1){
  103278. fprintf(stderr,"failed; read past end without -1.\n");
  103279. exit(1);
  103280. }
  103281. oggpackB_writeclear(&o);
  103282. fprintf(stderr,"ok.\n\n");
  103283. return(0);
  103284. }
  103285. #endif /* _V_SELFTEST */
  103286. #undef BUFFER_INCREMENT
  103287. #endif
  103288. /********* End of inlined file: bitwise.c *********/
  103289. /********* Start of inlined file: framing.c *********/
  103290. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  103291. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  103292. // tasks..
  103293. #ifdef _MSC_VER
  103294. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  103295. #endif
  103296. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  103297. #if JUCE_USE_OGGVORBIS
  103298. #include <stdlib.h>
  103299. #include <string.h>
  103300. /* A complete description of Ogg framing exists in docs/framing.html */
  103301. int ogg_page_version(ogg_page *og){
  103302. return((int)(og->header[4]));
  103303. }
  103304. int ogg_page_continued(ogg_page *og){
  103305. return((int)(og->header[5]&0x01));
  103306. }
  103307. int ogg_page_bos(ogg_page *og){
  103308. return((int)(og->header[5]&0x02));
  103309. }
  103310. int ogg_page_eos(ogg_page *og){
  103311. return((int)(og->header[5]&0x04));
  103312. }
  103313. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  103314. unsigned char *page=og->header;
  103315. ogg_int64_t granulepos=page[13]&(0xff);
  103316. granulepos= (granulepos<<8)|(page[12]&0xff);
  103317. granulepos= (granulepos<<8)|(page[11]&0xff);
  103318. granulepos= (granulepos<<8)|(page[10]&0xff);
  103319. granulepos= (granulepos<<8)|(page[9]&0xff);
  103320. granulepos= (granulepos<<8)|(page[8]&0xff);
  103321. granulepos= (granulepos<<8)|(page[7]&0xff);
  103322. granulepos= (granulepos<<8)|(page[6]&0xff);
  103323. return(granulepos);
  103324. }
  103325. int ogg_page_serialno(ogg_page *og){
  103326. return(og->header[14] |
  103327. (og->header[15]<<8) |
  103328. (og->header[16]<<16) |
  103329. (og->header[17]<<24));
  103330. }
  103331. long ogg_page_pageno(ogg_page *og){
  103332. return(og->header[18] |
  103333. (og->header[19]<<8) |
  103334. (og->header[20]<<16) |
  103335. (og->header[21]<<24));
  103336. }
  103337. /* returns the number of packets that are completed on this page (if
  103338. the leading packet is begun on a previous page, but ends on this
  103339. page, it's counted */
  103340. /* NOTE:
  103341. If a page consists of a packet begun on a previous page, and a new
  103342. packet begun (but not completed) on this page, the return will be:
  103343. ogg_page_packets(page) ==1,
  103344. ogg_page_continued(page) !=0
  103345. If a page happens to be a single packet that was begun on a
  103346. previous page, and spans to the next page (in the case of a three or
  103347. more page packet), the return will be:
  103348. ogg_page_packets(page) ==0,
  103349. ogg_page_continued(page) !=0
  103350. */
  103351. int ogg_page_packets(ogg_page *og){
  103352. int i,n=og->header[26],count=0;
  103353. for(i=0;i<n;i++)
  103354. if(og->header[27+i]<255)count++;
  103355. return(count);
  103356. }
  103357. #if 0
  103358. /* helper to initialize lookup for direct-table CRC (illustrative; we
  103359. use the static init below) */
  103360. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  103361. int i;
  103362. unsigned long r;
  103363. r = index << 24;
  103364. for (i=0; i<8; i++)
  103365. if (r & 0x80000000UL)
  103366. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  103367. polynomial, although we use an
  103368. unreflected alg and an init/final
  103369. of 0, not 0xffffffff */
  103370. else
  103371. r<<=1;
  103372. return (r & 0xffffffffUL);
  103373. }
  103374. #endif
  103375. static const ogg_uint32_t crc_lookup[256]={
  103376. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  103377. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  103378. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  103379. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  103380. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  103381. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  103382. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  103383. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  103384. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  103385. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  103386. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  103387. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  103388. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  103389. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  103390. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  103391. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  103392. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  103393. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  103394. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  103395. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  103396. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  103397. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  103398. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  103399. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  103400. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  103401. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  103402. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  103403. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  103404. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  103405. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  103406. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  103407. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  103408. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  103409. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  103410. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  103411. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  103412. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  103413. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  103414. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  103415. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  103416. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  103417. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  103418. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  103419. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  103420. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  103421. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  103422. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  103423. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  103424. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  103425. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  103426. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  103427. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  103428. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  103429. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  103430. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  103431. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  103432. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  103433. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  103434. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  103435. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  103436. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  103437. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  103438. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  103439. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  103440. /* init the encode/decode logical stream state */
  103441. int ogg_stream_init(ogg_stream_state *os,int serialno){
  103442. if(os){
  103443. memset(os,0,sizeof(*os));
  103444. os->body_storage=16*1024;
  103445. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  103446. os->lacing_storage=1024;
  103447. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  103448. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  103449. os->serialno=serialno;
  103450. return(0);
  103451. }
  103452. return(-1);
  103453. }
  103454. /* _clear does not free os, only the non-flat storage within */
  103455. int ogg_stream_clear(ogg_stream_state *os){
  103456. if(os){
  103457. if(os->body_data)_ogg_free(os->body_data);
  103458. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  103459. if(os->granule_vals)_ogg_free(os->granule_vals);
  103460. memset(os,0,sizeof(*os));
  103461. }
  103462. return(0);
  103463. }
  103464. int ogg_stream_destroy(ogg_stream_state *os){
  103465. if(os){
  103466. ogg_stream_clear(os);
  103467. _ogg_free(os);
  103468. }
  103469. return(0);
  103470. }
  103471. /* Helpers for ogg_stream_encode; this keeps the structure and
  103472. what's happening fairly clear */
  103473. static void _os_body_expand(ogg_stream_state *os,int needed){
  103474. if(os->body_storage<=os->body_fill+needed){
  103475. os->body_storage+=(needed+1024);
  103476. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  103477. }
  103478. }
  103479. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  103480. if(os->lacing_storage<=os->lacing_fill+needed){
  103481. os->lacing_storage+=(needed+32);
  103482. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  103483. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  103484. }
  103485. }
  103486. /* checksum the page */
  103487. /* Direct table CRC; note that this will be faster in the future if we
  103488. perform the checksum silmultaneously with other copies */
  103489. void ogg_page_checksum_set(ogg_page *og){
  103490. if(og){
  103491. ogg_uint32_t crc_reg=0;
  103492. int i;
  103493. /* safety; needed for API behavior, but not framing code */
  103494. og->header[22]=0;
  103495. og->header[23]=0;
  103496. og->header[24]=0;
  103497. og->header[25]=0;
  103498. for(i=0;i<og->header_len;i++)
  103499. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  103500. for(i=0;i<og->body_len;i++)
  103501. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  103502. og->header[22]=(unsigned char)(crc_reg&0xff);
  103503. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  103504. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  103505. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  103506. }
  103507. }
  103508. /* submit data to the internal buffer of the framing engine */
  103509. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  103510. int lacing_vals=op->bytes/255+1,i;
  103511. if(os->body_returned){
  103512. /* advance packet data according to the body_returned pointer. We
  103513. had to keep it around to return a pointer into the buffer last
  103514. call */
  103515. os->body_fill-=os->body_returned;
  103516. if(os->body_fill)
  103517. memmove(os->body_data,os->body_data+os->body_returned,
  103518. os->body_fill);
  103519. os->body_returned=0;
  103520. }
  103521. /* make sure we have the buffer storage */
  103522. _os_body_expand(os,op->bytes);
  103523. _os_lacing_expand(os,lacing_vals);
  103524. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  103525. the liability of overly clean abstraction for the time being. It
  103526. will actually be fairly easy to eliminate the extra copy in the
  103527. future */
  103528. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  103529. os->body_fill+=op->bytes;
  103530. /* Store lacing vals for this packet */
  103531. for(i=0;i<lacing_vals-1;i++){
  103532. os->lacing_vals[os->lacing_fill+i]=255;
  103533. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  103534. }
  103535. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  103536. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  103537. /* flag the first segment as the beginning of the packet */
  103538. os->lacing_vals[os->lacing_fill]|= 0x100;
  103539. os->lacing_fill+=lacing_vals;
  103540. /* for the sake of completeness */
  103541. os->packetno++;
  103542. if(op->e_o_s)os->e_o_s=1;
  103543. return(0);
  103544. }
  103545. /* This will flush remaining packets into a page (returning nonzero),
  103546. even if there is not enough data to trigger a flush normally
  103547. (undersized page). If there are no packets or partial packets to
  103548. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  103549. try to flush a normal sized page like ogg_stream_pageout; a call to
  103550. ogg_stream_flush does not guarantee that all packets have flushed.
  103551. Only a return value of 0 from ogg_stream_flush indicates all packet
  103552. data is flushed into pages.
  103553. since ogg_stream_flush will flush the last page in a stream even if
  103554. it's undersized, you almost certainly want to use ogg_stream_pageout
  103555. (and *not* ogg_stream_flush) unless you specifically need to flush
  103556. an page regardless of size in the middle of a stream. */
  103557. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  103558. int i;
  103559. int vals=0;
  103560. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  103561. int bytes=0;
  103562. long acc=0;
  103563. ogg_int64_t granule_pos=-1;
  103564. if(maxvals==0)return(0);
  103565. /* construct a page */
  103566. /* decide how many segments to include */
  103567. /* If this is the initial header case, the first page must only include
  103568. the initial header packet */
  103569. if(os->b_o_s==0){ /* 'initial header page' case */
  103570. granule_pos=0;
  103571. for(vals=0;vals<maxvals;vals++){
  103572. if((os->lacing_vals[vals]&0x0ff)<255){
  103573. vals++;
  103574. break;
  103575. }
  103576. }
  103577. }else{
  103578. for(vals=0;vals<maxvals;vals++){
  103579. if(acc>4096)break;
  103580. acc+=os->lacing_vals[vals]&0x0ff;
  103581. if((os->lacing_vals[vals]&0xff)<255)
  103582. granule_pos=os->granule_vals[vals];
  103583. }
  103584. }
  103585. /* construct the header in temp storage */
  103586. memcpy(os->header,"OggS",4);
  103587. /* stream structure version */
  103588. os->header[4]=0x00;
  103589. /* continued packet flag? */
  103590. os->header[5]=0x00;
  103591. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  103592. /* first page flag? */
  103593. if(os->b_o_s==0)os->header[5]|=0x02;
  103594. /* last page flag? */
  103595. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  103596. os->b_o_s=1;
  103597. /* 64 bits of PCM position */
  103598. for(i=6;i<14;i++){
  103599. os->header[i]=(unsigned char)(granule_pos&0xff);
  103600. granule_pos>>=8;
  103601. }
  103602. /* 32 bits of stream serial number */
  103603. {
  103604. long serialno=os->serialno;
  103605. for(i=14;i<18;i++){
  103606. os->header[i]=(unsigned char)(serialno&0xff);
  103607. serialno>>=8;
  103608. }
  103609. }
  103610. /* 32 bits of page counter (we have both counter and page header
  103611. because this val can roll over) */
  103612. if(os->pageno==-1)os->pageno=0; /* because someone called
  103613. stream_reset; this would be a
  103614. strange thing to do in an
  103615. encode stream, but it has
  103616. plausible uses */
  103617. {
  103618. long pageno=os->pageno++;
  103619. for(i=18;i<22;i++){
  103620. os->header[i]=(unsigned char)(pageno&0xff);
  103621. pageno>>=8;
  103622. }
  103623. }
  103624. /* zero for computation; filled in later */
  103625. os->header[22]=0;
  103626. os->header[23]=0;
  103627. os->header[24]=0;
  103628. os->header[25]=0;
  103629. /* segment table */
  103630. os->header[26]=(unsigned char)(vals&0xff);
  103631. for(i=0;i<vals;i++)
  103632. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  103633. /* set pointers in the ogg_page struct */
  103634. og->header=os->header;
  103635. og->header_len=os->header_fill=vals+27;
  103636. og->body=os->body_data+os->body_returned;
  103637. og->body_len=bytes;
  103638. /* advance the lacing data and set the body_returned pointer */
  103639. os->lacing_fill-=vals;
  103640. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  103641. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  103642. os->body_returned+=bytes;
  103643. /* calculate the checksum */
  103644. ogg_page_checksum_set(og);
  103645. /* done */
  103646. return(1);
  103647. }
  103648. /* This constructs pages from buffered packet segments. The pointers
  103649. returned are to static buffers; do not free. The returned buffers are
  103650. good only until the next call (using the same ogg_stream_state) */
  103651. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  103652. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  103653. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  103654. os->lacing_fill>=255 || /* 'segment table full' case */
  103655. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  103656. return(ogg_stream_flush(os,og));
  103657. }
  103658. /* not enough data to construct a page and not end of stream */
  103659. return(0);
  103660. }
  103661. int ogg_stream_eos(ogg_stream_state *os){
  103662. return os->e_o_s;
  103663. }
  103664. /* DECODING PRIMITIVES: packet streaming layer **********************/
  103665. /* This has two layers to place more of the multi-serialno and paging
  103666. control in the application's hands. First, we expose a data buffer
  103667. using ogg_sync_buffer(). The app either copies into the
  103668. buffer, or passes it directly to read(), etc. We then call
  103669. ogg_sync_wrote() to tell how many bytes we just added.
  103670. Pages are returned (pointers into the buffer in ogg_sync_state)
  103671. by ogg_sync_pageout(). The page is then submitted to
  103672. ogg_stream_pagein() along with the appropriate
  103673. ogg_stream_state* (ie, matching serialno). We then get raw
  103674. packets out calling ogg_stream_packetout() with a
  103675. ogg_stream_state. */
  103676. /* initialize the struct to a known state */
  103677. int ogg_sync_init(ogg_sync_state *oy){
  103678. if(oy){
  103679. memset(oy,0,sizeof(*oy));
  103680. }
  103681. return(0);
  103682. }
  103683. /* clear non-flat storage within */
  103684. int ogg_sync_clear(ogg_sync_state *oy){
  103685. if(oy){
  103686. if(oy->data)_ogg_free(oy->data);
  103687. ogg_sync_init(oy);
  103688. }
  103689. return(0);
  103690. }
  103691. int ogg_sync_destroy(ogg_sync_state *oy){
  103692. if(oy){
  103693. ogg_sync_clear(oy);
  103694. _ogg_free(oy);
  103695. }
  103696. return(0);
  103697. }
  103698. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  103699. /* first, clear out any space that has been previously returned */
  103700. if(oy->returned){
  103701. oy->fill-=oy->returned;
  103702. if(oy->fill>0)
  103703. memmove(oy->data,oy->data+oy->returned,oy->fill);
  103704. oy->returned=0;
  103705. }
  103706. if(size>oy->storage-oy->fill){
  103707. /* We need to extend the internal buffer */
  103708. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  103709. if(oy->data)
  103710. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  103711. else
  103712. oy->data=(unsigned char*) _ogg_malloc(newsize);
  103713. oy->storage=newsize;
  103714. }
  103715. /* expose a segment at least as large as requested at the fill mark */
  103716. return((char *)oy->data+oy->fill);
  103717. }
  103718. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  103719. if(oy->fill+bytes>oy->storage)return(-1);
  103720. oy->fill+=bytes;
  103721. return(0);
  103722. }
  103723. /* sync the stream. This is meant to be useful for finding page
  103724. boundaries.
  103725. return values for this:
  103726. -n) skipped n bytes
  103727. 0) page not ready; more data (no bytes skipped)
  103728. n) page synced at current location; page length n bytes
  103729. */
  103730. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  103731. unsigned char *page=oy->data+oy->returned;
  103732. unsigned char *next;
  103733. long bytes=oy->fill-oy->returned;
  103734. if(oy->headerbytes==0){
  103735. int headerbytes,i;
  103736. if(bytes<27)return(0); /* not enough for a header */
  103737. /* verify capture pattern */
  103738. if(memcmp(page,"OggS",4))goto sync_fail;
  103739. headerbytes=page[26]+27;
  103740. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  103741. /* count up body length in the segment table */
  103742. for(i=0;i<page[26];i++)
  103743. oy->bodybytes+=page[27+i];
  103744. oy->headerbytes=headerbytes;
  103745. }
  103746. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  103747. /* The whole test page is buffered. Verify the checksum */
  103748. {
  103749. /* Grab the checksum bytes, set the header field to zero */
  103750. char chksum[4];
  103751. ogg_page log;
  103752. memcpy(chksum,page+22,4);
  103753. memset(page+22,0,4);
  103754. /* set up a temp page struct and recompute the checksum */
  103755. log.header=page;
  103756. log.header_len=oy->headerbytes;
  103757. log.body=page+oy->headerbytes;
  103758. log.body_len=oy->bodybytes;
  103759. ogg_page_checksum_set(&log);
  103760. /* Compare */
  103761. if(memcmp(chksum,page+22,4)){
  103762. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  103763. at all) */
  103764. /* replace the computed checksum with the one actually read in */
  103765. memcpy(page+22,chksum,4);
  103766. /* Bad checksum. Lose sync */
  103767. goto sync_fail;
  103768. }
  103769. }
  103770. /* yes, have a whole page all ready to go */
  103771. {
  103772. unsigned char *page=oy->data+oy->returned;
  103773. long bytes;
  103774. if(og){
  103775. og->header=page;
  103776. og->header_len=oy->headerbytes;
  103777. og->body=page+oy->headerbytes;
  103778. og->body_len=oy->bodybytes;
  103779. }
  103780. oy->unsynced=0;
  103781. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  103782. oy->headerbytes=0;
  103783. oy->bodybytes=0;
  103784. return(bytes);
  103785. }
  103786. sync_fail:
  103787. oy->headerbytes=0;
  103788. oy->bodybytes=0;
  103789. /* search for possible capture */
  103790. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  103791. if(!next)
  103792. next=oy->data+oy->fill;
  103793. oy->returned=next-oy->data;
  103794. return(-(next-page));
  103795. }
  103796. /* sync the stream and get a page. Keep trying until we find a page.
  103797. Supress 'sync errors' after reporting the first.
  103798. return values:
  103799. -1) recapture (hole in data)
  103800. 0) need more data
  103801. 1) page returned
  103802. Returns pointers into buffered data; invalidated by next call to
  103803. _stream, _clear, _init, or _buffer */
  103804. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  103805. /* all we need to do is verify a page at the head of the stream
  103806. buffer. If it doesn't verify, we look for the next potential
  103807. frame */
  103808. for(;;){
  103809. long ret=ogg_sync_pageseek(oy,og);
  103810. if(ret>0){
  103811. /* have a page */
  103812. return(1);
  103813. }
  103814. if(ret==0){
  103815. /* need more data */
  103816. return(0);
  103817. }
  103818. /* head did not start a synced page... skipped some bytes */
  103819. if(!oy->unsynced){
  103820. oy->unsynced=1;
  103821. return(-1);
  103822. }
  103823. /* loop. keep looking */
  103824. }
  103825. }
  103826. /* add the incoming page to the stream state; we decompose the page
  103827. into packet segments here as well. */
  103828. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  103829. unsigned char *header=og->header;
  103830. unsigned char *body=og->body;
  103831. long bodysize=og->body_len;
  103832. int segptr=0;
  103833. int version=ogg_page_version(og);
  103834. int continued=ogg_page_continued(og);
  103835. int bos=ogg_page_bos(og);
  103836. int eos=ogg_page_eos(og);
  103837. ogg_int64_t granulepos=ogg_page_granulepos(og);
  103838. int serialno=ogg_page_serialno(og);
  103839. long pageno=ogg_page_pageno(og);
  103840. int segments=header[26];
  103841. /* clean up 'returned data' */
  103842. {
  103843. long lr=os->lacing_returned;
  103844. long br=os->body_returned;
  103845. /* body data */
  103846. if(br){
  103847. os->body_fill-=br;
  103848. if(os->body_fill)
  103849. memmove(os->body_data,os->body_data+br,os->body_fill);
  103850. os->body_returned=0;
  103851. }
  103852. if(lr){
  103853. /* segment table */
  103854. if(os->lacing_fill-lr){
  103855. memmove(os->lacing_vals,os->lacing_vals+lr,
  103856. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  103857. memmove(os->granule_vals,os->granule_vals+lr,
  103858. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  103859. }
  103860. os->lacing_fill-=lr;
  103861. os->lacing_packet-=lr;
  103862. os->lacing_returned=0;
  103863. }
  103864. }
  103865. /* check the serial number */
  103866. if(serialno!=os->serialno)return(-1);
  103867. if(version>0)return(-1);
  103868. _os_lacing_expand(os,segments+1);
  103869. /* are we in sequence? */
  103870. if(pageno!=os->pageno){
  103871. int i;
  103872. /* unroll previous partial packet (if any) */
  103873. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  103874. os->body_fill-=os->lacing_vals[i]&0xff;
  103875. os->lacing_fill=os->lacing_packet;
  103876. /* make a note of dropped data in segment table */
  103877. if(os->pageno!=-1){
  103878. os->lacing_vals[os->lacing_fill++]=0x400;
  103879. os->lacing_packet++;
  103880. }
  103881. }
  103882. /* are we a 'continued packet' page? If so, we may need to skip
  103883. some segments */
  103884. if(continued){
  103885. if(os->lacing_fill<1 ||
  103886. os->lacing_vals[os->lacing_fill-1]==0x400){
  103887. bos=0;
  103888. for(;segptr<segments;segptr++){
  103889. int val=header[27+segptr];
  103890. body+=val;
  103891. bodysize-=val;
  103892. if(val<255){
  103893. segptr++;
  103894. break;
  103895. }
  103896. }
  103897. }
  103898. }
  103899. if(bodysize){
  103900. _os_body_expand(os,bodysize);
  103901. memcpy(os->body_data+os->body_fill,body,bodysize);
  103902. os->body_fill+=bodysize;
  103903. }
  103904. {
  103905. int saved=-1;
  103906. while(segptr<segments){
  103907. int val=header[27+segptr];
  103908. os->lacing_vals[os->lacing_fill]=val;
  103909. os->granule_vals[os->lacing_fill]=-1;
  103910. if(bos){
  103911. os->lacing_vals[os->lacing_fill]|=0x100;
  103912. bos=0;
  103913. }
  103914. if(val<255)saved=os->lacing_fill;
  103915. os->lacing_fill++;
  103916. segptr++;
  103917. if(val<255)os->lacing_packet=os->lacing_fill;
  103918. }
  103919. /* set the granulepos on the last granuleval of the last full packet */
  103920. if(saved!=-1){
  103921. os->granule_vals[saved]=granulepos;
  103922. }
  103923. }
  103924. if(eos){
  103925. os->e_o_s=1;
  103926. if(os->lacing_fill>0)
  103927. os->lacing_vals[os->lacing_fill-1]|=0x200;
  103928. }
  103929. os->pageno=pageno+1;
  103930. return(0);
  103931. }
  103932. /* clear things to an initial state. Good to call, eg, before seeking */
  103933. int ogg_sync_reset(ogg_sync_state *oy){
  103934. oy->fill=0;
  103935. oy->returned=0;
  103936. oy->unsynced=0;
  103937. oy->headerbytes=0;
  103938. oy->bodybytes=0;
  103939. return(0);
  103940. }
  103941. int ogg_stream_reset(ogg_stream_state *os){
  103942. os->body_fill=0;
  103943. os->body_returned=0;
  103944. os->lacing_fill=0;
  103945. os->lacing_packet=0;
  103946. os->lacing_returned=0;
  103947. os->header_fill=0;
  103948. os->e_o_s=0;
  103949. os->b_o_s=0;
  103950. os->pageno=-1;
  103951. os->packetno=0;
  103952. os->granulepos=0;
  103953. return(0);
  103954. }
  103955. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  103956. ogg_stream_reset(os);
  103957. os->serialno=serialno;
  103958. return(0);
  103959. }
  103960. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  103961. /* The last part of decode. We have the stream broken into packet
  103962. segments. Now we need to group them into packets (or return the
  103963. out of sync markers) */
  103964. int ptr=os->lacing_returned;
  103965. if(os->lacing_packet<=ptr)return(0);
  103966. if(os->lacing_vals[ptr]&0x400){
  103967. /* we need to tell the codec there's a gap; it might need to
  103968. handle previous packet dependencies. */
  103969. os->lacing_returned++;
  103970. os->packetno++;
  103971. return(-1);
  103972. }
  103973. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  103974. to ask if there's a whole packet
  103975. waiting */
  103976. /* Gather the whole packet. We'll have no holes or a partial packet */
  103977. {
  103978. int size=os->lacing_vals[ptr]&0xff;
  103979. int bytes=size;
  103980. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  103981. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  103982. while(size==255){
  103983. int val=os->lacing_vals[++ptr];
  103984. size=val&0xff;
  103985. if(val&0x200)eos=0x200;
  103986. bytes+=size;
  103987. }
  103988. if(op){
  103989. op->e_o_s=eos;
  103990. op->b_o_s=bos;
  103991. op->packet=os->body_data+os->body_returned;
  103992. op->packetno=os->packetno;
  103993. op->granulepos=os->granule_vals[ptr];
  103994. op->bytes=bytes;
  103995. }
  103996. if(adv){
  103997. os->body_returned+=bytes;
  103998. os->lacing_returned=ptr+1;
  103999. os->packetno++;
  104000. }
  104001. }
  104002. return(1);
  104003. }
  104004. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  104005. return _packetout(os,op,1);
  104006. }
  104007. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  104008. return _packetout(os,op,0);
  104009. }
  104010. void ogg_packet_clear(ogg_packet *op) {
  104011. _ogg_free(op->packet);
  104012. memset(op, 0, sizeof(*op));
  104013. }
  104014. #ifdef _V_SELFTEST
  104015. #include <stdio.h>
  104016. ogg_stream_state os_en, os_de;
  104017. ogg_sync_state oy;
  104018. void checkpacket(ogg_packet *op,int len, int no, int pos){
  104019. long j;
  104020. static int sequence=0;
  104021. static int lastno=0;
  104022. if(op->bytes!=len){
  104023. fprintf(stderr,"incorrect packet length!\n");
  104024. exit(1);
  104025. }
  104026. if(op->granulepos!=pos){
  104027. fprintf(stderr,"incorrect packet position!\n");
  104028. exit(1);
  104029. }
  104030. /* packet number just follows sequence/gap; adjust the input number
  104031. for that */
  104032. if(no==0){
  104033. sequence=0;
  104034. }else{
  104035. sequence++;
  104036. if(no>lastno+1)
  104037. sequence++;
  104038. }
  104039. lastno=no;
  104040. if(op->packetno!=sequence){
  104041. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  104042. (long)(op->packetno),sequence);
  104043. exit(1);
  104044. }
  104045. /* Test data */
  104046. for(j=0;j<op->bytes;j++)
  104047. if(op->packet[j]!=((j+no)&0xff)){
  104048. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  104049. j,op->packet[j],(j+no)&0xff);
  104050. exit(1);
  104051. }
  104052. }
  104053. void check_page(unsigned char *data,const int *header,ogg_page *og){
  104054. long j;
  104055. /* Test data */
  104056. for(j=0;j<og->body_len;j++)
  104057. if(og->body[j]!=data[j]){
  104058. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  104059. j,data[j],og->body[j]);
  104060. exit(1);
  104061. }
  104062. /* Test header */
  104063. for(j=0;j<og->header_len;j++){
  104064. if(og->header[j]!=header[j]){
  104065. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  104066. for(j=0;j<header[26]+27;j++)
  104067. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  104068. fprintf(stderr,"\n");
  104069. exit(1);
  104070. }
  104071. }
  104072. if(og->header_len!=header[26]+27){
  104073. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  104074. og->header_len,header[26]+27);
  104075. exit(1);
  104076. }
  104077. }
  104078. void print_header(ogg_page *og){
  104079. int j;
  104080. fprintf(stderr,"\nHEADER:\n");
  104081. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  104082. og->header[0],og->header[1],og->header[2],og->header[3],
  104083. (int)og->header[4],(int)og->header[5]);
  104084. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  104085. (og->header[9]<<24)|(og->header[8]<<16)|
  104086. (og->header[7]<<8)|og->header[6],
  104087. (og->header[17]<<24)|(og->header[16]<<16)|
  104088. (og->header[15]<<8)|og->header[14],
  104089. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  104090. (og->header[19]<<8)|og->header[18]);
  104091. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  104092. (int)og->header[22],(int)og->header[23],
  104093. (int)og->header[24],(int)og->header[25],
  104094. (int)og->header[26]);
  104095. for(j=27;j<og->header_len;j++)
  104096. fprintf(stderr,"%d ",(int)og->header[j]);
  104097. fprintf(stderr,")\n\n");
  104098. }
  104099. void copy_page(ogg_page *og){
  104100. unsigned char *temp=_ogg_malloc(og->header_len);
  104101. memcpy(temp,og->header,og->header_len);
  104102. og->header=temp;
  104103. temp=_ogg_malloc(og->body_len);
  104104. memcpy(temp,og->body,og->body_len);
  104105. og->body=temp;
  104106. }
  104107. void free_page(ogg_page *og){
  104108. _ogg_free (og->header);
  104109. _ogg_free (og->body);
  104110. }
  104111. void error(void){
  104112. fprintf(stderr,"error!\n");
  104113. exit(1);
  104114. }
  104115. /* 17 only */
  104116. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  104117. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104118. 0x01,0x02,0x03,0x04,0,0,0,0,
  104119. 0x15,0xed,0xec,0x91,
  104120. 1,
  104121. 17};
  104122. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  104123. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104124. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104125. 0x01,0x02,0x03,0x04,0,0,0,0,
  104126. 0x59,0x10,0x6c,0x2c,
  104127. 1,
  104128. 17};
  104129. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104130. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  104131. 0x01,0x02,0x03,0x04,1,0,0,0,
  104132. 0x89,0x33,0x85,0xce,
  104133. 13,
  104134. 254,255,0,255,1,255,245,255,255,0,
  104135. 255,255,90};
  104136. /* nil packets; beginning,middle,end */
  104137. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104138. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104139. 0x01,0x02,0x03,0x04,0,0,0,0,
  104140. 0xff,0x7b,0x23,0x17,
  104141. 1,
  104142. 0};
  104143. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104144. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  104145. 0x01,0x02,0x03,0x04,1,0,0,0,
  104146. 0x5c,0x3f,0x66,0xcb,
  104147. 17,
  104148. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  104149. 255,255,90,0};
  104150. /* large initial packet */
  104151. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104152. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104153. 0x01,0x02,0x03,0x04,0,0,0,0,
  104154. 0x01,0x27,0x31,0xaa,
  104155. 18,
  104156. 255,255,255,255,255,255,255,255,
  104157. 255,255,255,255,255,255,255,255,255,10};
  104158. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104159. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  104160. 0x01,0x02,0x03,0x04,1,0,0,0,
  104161. 0x7f,0x4e,0x8a,0xd2,
  104162. 4,
  104163. 255,4,255,0};
  104164. /* continuing packet test */
  104165. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104166. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104167. 0x01,0x02,0x03,0x04,0,0,0,0,
  104168. 0xff,0x7b,0x23,0x17,
  104169. 1,
  104170. 0};
  104171. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104172. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  104173. 0x01,0x02,0x03,0x04,1,0,0,0,
  104174. 0x54,0x05,0x51,0xc8,
  104175. 17,
  104176. 255,255,255,255,255,255,255,255,
  104177. 255,255,255,255,255,255,255,255,255};
  104178. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  104179. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  104180. 0x01,0x02,0x03,0x04,2,0,0,0,
  104181. 0xc8,0xc3,0xcb,0xed,
  104182. 5,
  104183. 10,255,4,255,0};
  104184. /* page with the 255 segment limit */
  104185. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104186. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104187. 0x01,0x02,0x03,0x04,0,0,0,0,
  104188. 0xff,0x7b,0x23,0x17,
  104189. 1,
  104190. 0};
  104191. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104192. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  104193. 0x01,0x02,0x03,0x04,1,0,0,0,
  104194. 0xed,0x2a,0x2e,0xa7,
  104195. 255,
  104196. 10,10,10,10,10,10,10,10,
  104197. 10,10,10,10,10,10,10,10,
  104198. 10,10,10,10,10,10,10,10,
  104199. 10,10,10,10,10,10,10,10,
  104200. 10,10,10,10,10,10,10,10,
  104201. 10,10,10,10,10,10,10,10,
  104202. 10,10,10,10,10,10,10,10,
  104203. 10,10,10,10,10,10,10,10,
  104204. 10,10,10,10,10,10,10,10,
  104205. 10,10,10,10,10,10,10,10,
  104206. 10,10,10,10,10,10,10,10,
  104207. 10,10,10,10,10,10,10,10,
  104208. 10,10,10,10,10,10,10,10,
  104209. 10,10,10,10,10,10,10,10,
  104210. 10,10,10,10,10,10,10,10,
  104211. 10,10,10,10,10,10,10,10,
  104212. 10,10,10,10,10,10,10,10,
  104213. 10,10,10,10,10,10,10,10,
  104214. 10,10,10,10,10,10,10,10,
  104215. 10,10,10,10,10,10,10,10,
  104216. 10,10,10,10,10,10,10,10,
  104217. 10,10,10,10,10,10,10,10,
  104218. 10,10,10,10,10,10,10,10,
  104219. 10,10,10,10,10,10,10,10,
  104220. 10,10,10,10,10,10,10,10,
  104221. 10,10,10,10,10,10,10,10,
  104222. 10,10,10,10,10,10,10,10,
  104223. 10,10,10,10,10,10,10,10,
  104224. 10,10,10,10,10,10,10,10,
  104225. 10,10,10,10,10,10,10,10,
  104226. 10,10,10,10,10,10,10,10,
  104227. 10,10,10,10,10,10,10};
  104228. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104229. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  104230. 0x01,0x02,0x03,0x04,2,0,0,0,
  104231. 0x6c,0x3b,0x82,0x3d,
  104232. 1,
  104233. 50};
  104234. /* packet that overspans over an entire page */
  104235. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104236. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104237. 0x01,0x02,0x03,0x04,0,0,0,0,
  104238. 0xff,0x7b,0x23,0x17,
  104239. 1,
  104240. 0};
  104241. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104242. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  104243. 0x01,0x02,0x03,0x04,1,0,0,0,
  104244. 0x3c,0xd9,0x4d,0x3f,
  104245. 17,
  104246. 100,255,255,255,255,255,255,255,255,
  104247. 255,255,255,255,255,255,255,255};
  104248. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  104249. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  104250. 0x01,0x02,0x03,0x04,2,0,0,0,
  104251. 0x01,0xd2,0xe5,0xe5,
  104252. 17,
  104253. 255,255,255,255,255,255,255,255,
  104254. 255,255,255,255,255,255,255,255,255};
  104255. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  104256. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  104257. 0x01,0x02,0x03,0x04,3,0,0,0,
  104258. 0xef,0xdd,0x88,0xde,
  104259. 7,
  104260. 255,255,75,255,4,255,0};
  104261. /* packet that overspans over an entire page */
  104262. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104263. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104264. 0x01,0x02,0x03,0x04,0,0,0,0,
  104265. 0xff,0x7b,0x23,0x17,
  104266. 1,
  104267. 0};
  104268. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104269. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  104270. 0x01,0x02,0x03,0x04,1,0,0,0,
  104271. 0x3c,0xd9,0x4d,0x3f,
  104272. 17,
  104273. 100,255,255,255,255,255,255,255,255,
  104274. 255,255,255,255,255,255,255,255};
  104275. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  104276. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  104277. 0x01,0x02,0x03,0x04,2,0,0,0,
  104278. 0xd4,0xe0,0x60,0xe5,
  104279. 1,0};
  104280. void test_pack(const int *pl, const int **headers, int byteskip,
  104281. int pageskip, int packetskip){
  104282. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  104283. long inptr=0;
  104284. long outptr=0;
  104285. long deptr=0;
  104286. long depacket=0;
  104287. long granule_pos=7,pageno=0;
  104288. int i,j,packets,pageout=pageskip;
  104289. int eosflag=0;
  104290. int bosflag=0;
  104291. int byteskipcount=0;
  104292. ogg_stream_reset(&os_en);
  104293. ogg_stream_reset(&os_de);
  104294. ogg_sync_reset(&oy);
  104295. for(packets=0;packets<packetskip;packets++)
  104296. depacket+=pl[packets];
  104297. for(packets=0;;packets++)if(pl[packets]==-1)break;
  104298. for(i=0;i<packets;i++){
  104299. /* construct a test packet */
  104300. ogg_packet op;
  104301. int len=pl[i];
  104302. op.packet=data+inptr;
  104303. op.bytes=len;
  104304. op.e_o_s=(pl[i+1]<0?1:0);
  104305. op.granulepos=granule_pos;
  104306. granule_pos+=1024;
  104307. for(j=0;j<len;j++)data[inptr++]=i+j;
  104308. /* submit the test packet */
  104309. ogg_stream_packetin(&os_en,&op);
  104310. /* retrieve any finished pages */
  104311. {
  104312. ogg_page og;
  104313. while(ogg_stream_pageout(&os_en,&og)){
  104314. /* We have a page. Check it carefully */
  104315. fprintf(stderr,"%ld, ",pageno);
  104316. if(headers[pageno]==NULL){
  104317. fprintf(stderr,"coded too many pages!\n");
  104318. exit(1);
  104319. }
  104320. check_page(data+outptr,headers[pageno],&og);
  104321. outptr+=og.body_len;
  104322. pageno++;
  104323. if(pageskip){
  104324. bosflag=1;
  104325. pageskip--;
  104326. deptr+=og.body_len;
  104327. }
  104328. /* have a complete page; submit it to sync/decode */
  104329. {
  104330. ogg_page og_de;
  104331. ogg_packet op_de,op_de2;
  104332. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  104333. char *next=buf;
  104334. byteskipcount+=og.header_len;
  104335. if(byteskipcount>byteskip){
  104336. memcpy(next,og.header,byteskipcount-byteskip);
  104337. next+=byteskipcount-byteskip;
  104338. byteskipcount=byteskip;
  104339. }
  104340. byteskipcount+=og.body_len;
  104341. if(byteskipcount>byteskip){
  104342. memcpy(next,og.body,byteskipcount-byteskip);
  104343. next+=byteskipcount-byteskip;
  104344. byteskipcount=byteskip;
  104345. }
  104346. ogg_sync_wrote(&oy,next-buf);
  104347. while(1){
  104348. int ret=ogg_sync_pageout(&oy,&og_de);
  104349. if(ret==0)break;
  104350. if(ret<0)continue;
  104351. /* got a page. Happy happy. Verify that it's good. */
  104352. fprintf(stderr,"(%ld), ",pageout);
  104353. check_page(data+deptr,headers[pageout],&og_de);
  104354. deptr+=og_de.body_len;
  104355. pageout++;
  104356. /* submit it to deconstitution */
  104357. ogg_stream_pagein(&os_de,&og_de);
  104358. /* packets out? */
  104359. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  104360. ogg_stream_packetpeek(&os_de,NULL);
  104361. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  104362. /* verify peek and out match */
  104363. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  104364. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  104365. depacket);
  104366. exit(1);
  104367. }
  104368. /* verify the packet! */
  104369. /* check data */
  104370. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  104371. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  104372. depacket);
  104373. exit(1);
  104374. }
  104375. /* check bos flag */
  104376. if(bosflag==0 && op_de.b_o_s==0){
  104377. fprintf(stderr,"b_o_s flag not set on packet!\n");
  104378. exit(1);
  104379. }
  104380. if(bosflag && op_de.b_o_s){
  104381. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  104382. exit(1);
  104383. }
  104384. bosflag=1;
  104385. depacket+=op_de.bytes;
  104386. /* check eos flag */
  104387. if(eosflag){
  104388. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  104389. exit(1);
  104390. }
  104391. if(op_de.e_o_s)eosflag=1;
  104392. /* check granulepos flag */
  104393. if(op_de.granulepos!=-1){
  104394. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  104395. }
  104396. }
  104397. }
  104398. }
  104399. }
  104400. }
  104401. }
  104402. _ogg_free(data);
  104403. if(headers[pageno]!=NULL){
  104404. fprintf(stderr,"did not write last page!\n");
  104405. exit(1);
  104406. }
  104407. if(headers[pageout]!=NULL){
  104408. fprintf(stderr,"did not decode last page!\n");
  104409. exit(1);
  104410. }
  104411. if(inptr!=outptr){
  104412. fprintf(stderr,"encoded page data incomplete!\n");
  104413. exit(1);
  104414. }
  104415. if(inptr!=deptr){
  104416. fprintf(stderr,"decoded page data incomplete!\n");
  104417. exit(1);
  104418. }
  104419. if(inptr!=depacket){
  104420. fprintf(stderr,"decoded packet data incomplete!\n");
  104421. exit(1);
  104422. }
  104423. if(!eosflag){
  104424. fprintf(stderr,"Never got a packet with EOS set!\n");
  104425. exit(1);
  104426. }
  104427. fprintf(stderr,"ok.\n");
  104428. }
  104429. int main(void){
  104430. ogg_stream_init(&os_en,0x04030201);
  104431. ogg_stream_init(&os_de,0x04030201);
  104432. ogg_sync_init(&oy);
  104433. /* Exercise each code path in the framing code. Also verify that
  104434. the checksums are working. */
  104435. {
  104436. /* 17 only */
  104437. const int packets[]={17, -1};
  104438. const int *headret[]={head1_0,NULL};
  104439. fprintf(stderr,"testing single page encoding... ");
  104440. test_pack(packets,headret,0,0,0);
  104441. }
  104442. {
  104443. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  104444. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  104445. const int *headret[]={head1_1,head2_1,NULL};
  104446. fprintf(stderr,"testing basic page encoding... ");
  104447. test_pack(packets,headret,0,0,0);
  104448. }
  104449. {
  104450. /* nil packets; beginning,middle,end */
  104451. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  104452. const int *headret[]={head1_2,head2_2,NULL};
  104453. fprintf(stderr,"testing basic nil packets... ");
  104454. test_pack(packets,headret,0,0,0);
  104455. }
  104456. {
  104457. /* large initial packet */
  104458. const int packets[]={4345,259,255,-1};
  104459. const int *headret[]={head1_3,head2_3,NULL};
  104460. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  104461. test_pack(packets,headret,0,0,0);
  104462. }
  104463. {
  104464. /* continuing packet test */
  104465. const int packets[]={0,4345,259,255,-1};
  104466. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  104467. fprintf(stderr,"testing single packet page span... ");
  104468. test_pack(packets,headret,0,0,0);
  104469. }
  104470. /* page with the 255 segment limit */
  104471. {
  104472. const int packets[]={0,10,10,10,10,10,10,10,10,
  104473. 10,10,10,10,10,10,10,10,
  104474. 10,10,10,10,10,10,10,10,
  104475. 10,10,10,10,10,10,10,10,
  104476. 10,10,10,10,10,10,10,10,
  104477. 10,10,10,10,10,10,10,10,
  104478. 10,10,10,10,10,10,10,10,
  104479. 10,10,10,10,10,10,10,10,
  104480. 10,10,10,10,10,10,10,10,
  104481. 10,10,10,10,10,10,10,10,
  104482. 10,10,10,10,10,10,10,10,
  104483. 10,10,10,10,10,10,10,10,
  104484. 10,10,10,10,10,10,10,10,
  104485. 10,10,10,10,10,10,10,10,
  104486. 10,10,10,10,10,10,10,10,
  104487. 10,10,10,10,10,10,10,10,
  104488. 10,10,10,10,10,10,10,10,
  104489. 10,10,10,10,10,10,10,10,
  104490. 10,10,10,10,10,10,10,10,
  104491. 10,10,10,10,10,10,10,10,
  104492. 10,10,10,10,10,10,10,10,
  104493. 10,10,10,10,10,10,10,10,
  104494. 10,10,10,10,10,10,10,10,
  104495. 10,10,10,10,10,10,10,10,
  104496. 10,10,10,10,10,10,10,10,
  104497. 10,10,10,10,10,10,10,10,
  104498. 10,10,10,10,10,10,10,10,
  104499. 10,10,10,10,10,10,10,10,
  104500. 10,10,10,10,10,10,10,10,
  104501. 10,10,10,10,10,10,10,10,
  104502. 10,10,10,10,10,10,10,10,
  104503. 10,10,10,10,10,10,10,50,-1};
  104504. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  104505. fprintf(stderr,"testing max packet segments... ");
  104506. test_pack(packets,headret,0,0,0);
  104507. }
  104508. {
  104509. /* packet that overspans over an entire page */
  104510. const int packets[]={0,100,9000,259,255,-1};
  104511. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  104512. fprintf(stderr,"testing very large packets... ");
  104513. test_pack(packets,headret,0,0,0);
  104514. }
  104515. {
  104516. /* test for the libogg 1.1.1 resync in large continuation bug
  104517. found by Josh Coalson) */
  104518. const int packets[]={0,100,9000,259,255,-1};
  104519. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  104520. fprintf(stderr,"testing continuation resync in very large packets... ");
  104521. test_pack(packets,headret,100,2,3);
  104522. }
  104523. {
  104524. /* term only page. why not? */
  104525. const int packets[]={0,100,4080,-1};
  104526. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  104527. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  104528. test_pack(packets,headret,0,0,0);
  104529. }
  104530. {
  104531. /* build a bunch of pages for testing */
  104532. unsigned char *data=_ogg_malloc(1024*1024);
  104533. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  104534. int inptr=0,i,j;
  104535. ogg_page og[5];
  104536. ogg_stream_reset(&os_en);
  104537. for(i=0;pl[i]!=-1;i++){
  104538. ogg_packet op;
  104539. int len=pl[i];
  104540. op.packet=data+inptr;
  104541. op.bytes=len;
  104542. op.e_o_s=(pl[i+1]<0?1:0);
  104543. op.granulepos=(i+1)*1000;
  104544. for(j=0;j<len;j++)data[inptr++]=i+j;
  104545. ogg_stream_packetin(&os_en,&op);
  104546. }
  104547. _ogg_free(data);
  104548. /* retrieve finished pages */
  104549. for(i=0;i<5;i++){
  104550. if(ogg_stream_pageout(&os_en,&og[i])==0){
  104551. fprintf(stderr,"Too few pages output building sync tests!\n");
  104552. exit(1);
  104553. }
  104554. copy_page(&og[i]);
  104555. }
  104556. /* Test lost pages on pagein/packetout: no rollback */
  104557. {
  104558. ogg_page temp;
  104559. ogg_packet test;
  104560. fprintf(stderr,"Testing loss of pages... ");
  104561. ogg_sync_reset(&oy);
  104562. ogg_stream_reset(&os_de);
  104563. for(i=0;i<5;i++){
  104564. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  104565. og[i].header_len);
  104566. ogg_sync_wrote(&oy,og[i].header_len);
  104567. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  104568. ogg_sync_wrote(&oy,og[i].body_len);
  104569. }
  104570. ogg_sync_pageout(&oy,&temp);
  104571. ogg_stream_pagein(&os_de,&temp);
  104572. ogg_sync_pageout(&oy,&temp);
  104573. ogg_stream_pagein(&os_de,&temp);
  104574. ogg_sync_pageout(&oy,&temp);
  104575. /* skip */
  104576. ogg_sync_pageout(&oy,&temp);
  104577. ogg_stream_pagein(&os_de,&temp);
  104578. /* do we get the expected results/packets? */
  104579. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104580. checkpacket(&test,0,0,0);
  104581. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104582. checkpacket(&test,100,1,-1);
  104583. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104584. checkpacket(&test,4079,2,3000);
  104585. if(ogg_stream_packetout(&os_de,&test)!=-1){
  104586. fprintf(stderr,"Error: loss of page did not return error\n");
  104587. exit(1);
  104588. }
  104589. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104590. checkpacket(&test,76,5,-1);
  104591. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104592. checkpacket(&test,34,6,-1);
  104593. fprintf(stderr,"ok.\n");
  104594. }
  104595. /* Test lost pages on pagein/packetout: rollback with continuation */
  104596. {
  104597. ogg_page temp;
  104598. ogg_packet test;
  104599. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  104600. ogg_sync_reset(&oy);
  104601. ogg_stream_reset(&os_de);
  104602. for(i=0;i<5;i++){
  104603. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  104604. og[i].header_len);
  104605. ogg_sync_wrote(&oy,og[i].header_len);
  104606. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  104607. ogg_sync_wrote(&oy,og[i].body_len);
  104608. }
  104609. ogg_sync_pageout(&oy,&temp);
  104610. ogg_stream_pagein(&os_de,&temp);
  104611. ogg_sync_pageout(&oy,&temp);
  104612. ogg_stream_pagein(&os_de,&temp);
  104613. ogg_sync_pageout(&oy,&temp);
  104614. ogg_stream_pagein(&os_de,&temp);
  104615. ogg_sync_pageout(&oy,&temp);
  104616. /* skip */
  104617. ogg_sync_pageout(&oy,&temp);
  104618. ogg_stream_pagein(&os_de,&temp);
  104619. /* do we get the expected results/packets? */
  104620. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104621. checkpacket(&test,0,0,0);
  104622. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104623. checkpacket(&test,100,1,-1);
  104624. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104625. checkpacket(&test,4079,2,3000);
  104626. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104627. checkpacket(&test,2956,3,4000);
  104628. if(ogg_stream_packetout(&os_de,&test)!=-1){
  104629. fprintf(stderr,"Error: loss of page did not return error\n");
  104630. exit(1);
  104631. }
  104632. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  104633. checkpacket(&test,300,13,14000);
  104634. fprintf(stderr,"ok.\n");
  104635. }
  104636. /* the rest only test sync */
  104637. {
  104638. ogg_page og_de;
  104639. /* Test fractional page inputs: incomplete capture */
  104640. fprintf(stderr,"Testing sync on partial inputs... ");
  104641. ogg_sync_reset(&oy);
  104642. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  104643. 3);
  104644. ogg_sync_wrote(&oy,3);
  104645. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104646. /* Test fractional page inputs: incomplete fixed header */
  104647. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  104648. 20);
  104649. ogg_sync_wrote(&oy,20);
  104650. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104651. /* Test fractional page inputs: incomplete header */
  104652. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  104653. 5);
  104654. ogg_sync_wrote(&oy,5);
  104655. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104656. /* Test fractional page inputs: incomplete body */
  104657. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  104658. og[1].header_len-28);
  104659. ogg_sync_wrote(&oy,og[1].header_len-28);
  104660. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104661. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  104662. ogg_sync_wrote(&oy,1000);
  104663. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104664. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  104665. og[1].body_len-1000);
  104666. ogg_sync_wrote(&oy,og[1].body_len-1000);
  104667. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104668. fprintf(stderr,"ok.\n");
  104669. }
  104670. /* Test fractional page inputs: page + incomplete capture */
  104671. {
  104672. ogg_page og_de;
  104673. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  104674. ogg_sync_reset(&oy);
  104675. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  104676. og[1].header_len);
  104677. ogg_sync_wrote(&oy,og[1].header_len);
  104678. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  104679. og[1].body_len);
  104680. ogg_sync_wrote(&oy,og[1].body_len);
  104681. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  104682. 20);
  104683. ogg_sync_wrote(&oy,20);
  104684. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104685. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104686. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  104687. og[1].header_len-20);
  104688. ogg_sync_wrote(&oy,og[1].header_len-20);
  104689. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  104690. og[1].body_len);
  104691. ogg_sync_wrote(&oy,og[1].body_len);
  104692. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104693. fprintf(stderr,"ok.\n");
  104694. }
  104695. /* Test recapture: garbage + page */
  104696. {
  104697. ogg_page og_de;
  104698. fprintf(stderr,"Testing search for capture... ");
  104699. ogg_sync_reset(&oy);
  104700. /* 'garbage' */
  104701. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  104702. og[1].body_len);
  104703. ogg_sync_wrote(&oy,og[1].body_len);
  104704. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  104705. og[1].header_len);
  104706. ogg_sync_wrote(&oy,og[1].header_len);
  104707. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  104708. og[1].body_len);
  104709. ogg_sync_wrote(&oy,og[1].body_len);
  104710. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  104711. 20);
  104712. ogg_sync_wrote(&oy,20);
  104713. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104714. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104715. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104716. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  104717. og[2].header_len-20);
  104718. ogg_sync_wrote(&oy,og[2].header_len-20);
  104719. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  104720. og[2].body_len);
  104721. ogg_sync_wrote(&oy,og[2].body_len);
  104722. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104723. fprintf(stderr,"ok.\n");
  104724. }
  104725. /* Test recapture: page + garbage + page */
  104726. {
  104727. ogg_page og_de;
  104728. fprintf(stderr,"Testing recapture... ");
  104729. ogg_sync_reset(&oy);
  104730. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  104731. og[1].header_len);
  104732. ogg_sync_wrote(&oy,og[1].header_len);
  104733. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  104734. og[1].body_len);
  104735. ogg_sync_wrote(&oy,og[1].body_len);
  104736. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  104737. og[2].header_len);
  104738. ogg_sync_wrote(&oy,og[2].header_len);
  104739. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  104740. og[2].header_len);
  104741. ogg_sync_wrote(&oy,og[2].header_len);
  104742. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104743. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  104744. og[2].body_len-5);
  104745. ogg_sync_wrote(&oy,og[2].body_len-5);
  104746. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  104747. og[3].header_len);
  104748. ogg_sync_wrote(&oy,og[3].header_len);
  104749. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  104750. og[3].body_len);
  104751. ogg_sync_wrote(&oy,og[3].body_len);
  104752. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  104753. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104754. fprintf(stderr,"ok.\n");
  104755. }
  104756. /* Free page data that was previously copied */
  104757. {
  104758. for(i=0;i<5;i++){
  104759. free_page(&og[i]);
  104760. }
  104761. }
  104762. }
  104763. return(0);
  104764. }
  104765. #endif
  104766. #endif
  104767. /********* End of inlined file: framing.c *********/
  104768. /********* Start of inlined file: analysis.c *********/
  104769. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  104770. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104771. // tasks..
  104772. #ifdef _MSC_VER
  104773. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104774. #endif
  104775. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  104776. #if JUCE_USE_OGGVORBIS
  104777. #include <stdio.h>
  104778. #include <string.h>
  104779. #include <math.h>
  104780. /********* Start of inlined file: codec_internal.h *********/
  104781. #ifndef _V_CODECI_H_
  104782. #define _V_CODECI_H_
  104783. /********* Start of inlined file: envelope.h *********/
  104784. #ifndef _V_ENVELOPE_
  104785. #define _V_ENVELOPE_
  104786. /********* Start of inlined file: mdct.h *********/
  104787. #ifndef _OGG_mdct_H_
  104788. #define _OGG_mdct_H_
  104789. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  104790. #ifdef MDCT_INTEGERIZED
  104791. #define DATA_TYPE int
  104792. #define REG_TYPE register int
  104793. #define TRIGBITS 14
  104794. #define cPI3_8 6270
  104795. #define cPI2_8 11585
  104796. #define cPI1_8 15137
  104797. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  104798. #define MULT_NORM(x) ((x)>>TRIGBITS)
  104799. #define HALVE(x) ((x)>>1)
  104800. #else
  104801. #define DATA_TYPE float
  104802. #define REG_TYPE float
  104803. #define cPI3_8 .38268343236508977175F
  104804. #define cPI2_8 .70710678118654752441F
  104805. #define cPI1_8 .92387953251128675613F
  104806. #define FLOAT_CONV(x) (x)
  104807. #define MULT_NORM(x) (x)
  104808. #define HALVE(x) ((x)*.5f)
  104809. #endif
  104810. typedef struct {
  104811. int n;
  104812. int log2n;
  104813. DATA_TYPE *trig;
  104814. int *bitrev;
  104815. DATA_TYPE scale;
  104816. } mdct_lookup;
  104817. extern void mdct_init(mdct_lookup *lookup,int n);
  104818. extern void mdct_clear(mdct_lookup *l);
  104819. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  104820. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  104821. #endif
  104822. /********* End of inlined file: mdct.h *********/
  104823. #define VE_PRE 16
  104824. #define VE_WIN 4
  104825. #define VE_POST 2
  104826. #define VE_AMP (VE_PRE+VE_POST-1)
  104827. #define VE_BANDS 7
  104828. #define VE_NEARDC 15
  104829. #define VE_MINSTRETCH 2 /* a bit less than short block */
  104830. #define VE_MAXSTRETCH 12 /* one-third full block */
  104831. typedef struct {
  104832. float ampbuf[VE_AMP];
  104833. int ampptr;
  104834. float nearDC[VE_NEARDC];
  104835. float nearDC_acc;
  104836. float nearDC_partialacc;
  104837. int nearptr;
  104838. } envelope_filter_state;
  104839. typedef struct {
  104840. int begin;
  104841. int end;
  104842. float *window;
  104843. float total;
  104844. } envelope_band;
  104845. typedef struct {
  104846. int ch;
  104847. int winlength;
  104848. int searchstep;
  104849. float minenergy;
  104850. mdct_lookup mdct;
  104851. float *mdct_win;
  104852. envelope_band band[VE_BANDS];
  104853. envelope_filter_state *filter;
  104854. int stretch;
  104855. int *mark;
  104856. long storage;
  104857. long current;
  104858. long curmark;
  104859. long cursor;
  104860. } envelope_lookup;
  104861. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  104862. extern void _ve_envelope_clear(envelope_lookup *e);
  104863. extern long _ve_envelope_search(vorbis_dsp_state *v);
  104864. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  104865. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  104866. #endif
  104867. /********* End of inlined file: envelope.h *********/
  104868. /********* Start of inlined file: codebook.h *********/
  104869. #ifndef _V_CODEBOOK_H_
  104870. #define _V_CODEBOOK_H_
  104871. /* This structure encapsulates huffman and VQ style encoding books; it
  104872. doesn't do anything specific to either.
  104873. valuelist/quantlist are nonNULL (and q_* significant) only if
  104874. there's entry->value mapping to be done.
  104875. If encode-side mapping must be done (and thus the entry needs to be
  104876. hunted), the auxiliary encode pointer will point to a decision
  104877. tree. This is true of both VQ and huffman, but is mostly useful
  104878. with VQ.
  104879. */
  104880. typedef struct static_codebook{
  104881. long dim; /* codebook dimensions (elements per vector) */
  104882. long entries; /* codebook entries */
  104883. long *lengthlist; /* codeword lengths in bits */
  104884. /* mapping ***************************************************************/
  104885. int maptype; /* 0=none
  104886. 1=implicitly populated values from map column
  104887. 2=listed arbitrary values */
  104888. /* The below does a linear, single monotonic sequence mapping. */
  104889. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  104890. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  104891. int q_quant; /* bits: 0 < quant <= 16 */
  104892. int q_sequencep; /* bitflag */
  104893. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  104894. map == 2: list of dim*entries quantized entry vals
  104895. */
  104896. /* encode helpers ********************************************************/
  104897. struct encode_aux_nearestmatch *nearest_tree;
  104898. struct encode_aux_threshmatch *thresh_tree;
  104899. struct encode_aux_pigeonhole *pigeon_tree;
  104900. int allocedp;
  104901. } static_codebook;
  104902. /* this structures an arbitrary trained book to quickly find the
  104903. nearest cell match */
  104904. typedef struct encode_aux_nearestmatch{
  104905. /* pre-calculated partitioning tree */
  104906. long *ptr0;
  104907. long *ptr1;
  104908. long *p; /* decision points (each is an entry) */
  104909. long *q; /* decision points (each is an entry) */
  104910. long aux; /* number of tree entries */
  104911. long alloc;
  104912. } encode_aux_nearestmatch;
  104913. /* assumes a maptype of 1; encode side only, so that's OK */
  104914. typedef struct encode_aux_threshmatch{
  104915. float *quantthresh;
  104916. long *quantmap;
  104917. int quantvals;
  104918. int threshvals;
  104919. } encode_aux_threshmatch;
  104920. typedef struct encode_aux_pigeonhole{
  104921. float min;
  104922. float del;
  104923. int mapentries;
  104924. int quantvals;
  104925. long *pigeonmap;
  104926. long fittotal;
  104927. long *fitlist;
  104928. long *fitmap;
  104929. long *fitlength;
  104930. } encode_aux_pigeonhole;
  104931. typedef struct codebook{
  104932. long dim; /* codebook dimensions (elements per vector) */
  104933. long entries; /* codebook entries */
  104934. long used_entries; /* populated codebook entries */
  104935. const static_codebook *c;
  104936. /* for encode, the below are entry-ordered, fully populated */
  104937. /* for decode, the below are ordered by bitreversed codeword and only
  104938. used entries are populated */
  104939. float *valuelist; /* list of dim*entries actual entry values */
  104940. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  104941. int *dec_index; /* only used if sparseness collapsed */
  104942. char *dec_codelengths;
  104943. ogg_uint32_t *dec_firsttable;
  104944. int dec_firsttablen;
  104945. int dec_maxlength;
  104946. } codebook;
  104947. extern void vorbis_staticbook_clear(static_codebook *b);
  104948. extern void vorbis_staticbook_destroy(static_codebook *b);
  104949. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  104950. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  104951. extern void vorbis_book_clear(codebook *b);
  104952. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  104953. extern float *_book_logdist(const static_codebook *b,float *vals);
  104954. extern float _float32_unpack(long val);
  104955. extern long _float32_pack(float val);
  104956. extern int _best(codebook *book, float *a, int step);
  104957. extern int _ilog(unsigned int v);
  104958. extern long _book_maptype1_quantvals(const static_codebook *b);
  104959. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  104960. extern long vorbis_book_codeword(codebook *book,int entry);
  104961. extern long vorbis_book_codelen(codebook *book,int entry);
  104962. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  104963. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  104964. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  104965. extern int vorbis_book_errorv(codebook *book, float *a);
  104966. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  104967. oggpack_buffer *b);
  104968. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  104969. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  104970. oggpack_buffer *b,int n);
  104971. extern long vorbis_book_decodev_set(codebook *book, float *a,
  104972. oggpack_buffer *b,int n);
  104973. extern long vorbis_book_decodev_add(codebook *book, float *a,
  104974. oggpack_buffer *b,int n);
  104975. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  104976. long off,int ch,
  104977. oggpack_buffer *b,int n);
  104978. #endif
  104979. /********* End of inlined file: codebook.h *********/
  104980. #define BLOCKTYPE_IMPULSE 0
  104981. #define BLOCKTYPE_PADDING 1
  104982. #define BLOCKTYPE_TRANSITION 0
  104983. #define BLOCKTYPE_LONG 1
  104984. #define PACKETBLOBS 15
  104985. typedef struct vorbis_block_internal{
  104986. float **pcmdelay; /* this is a pointer into local storage */
  104987. float ampmax;
  104988. int blocktype;
  104989. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  104990. blob [PACKETBLOBS/2] points to
  104991. the oggpack_buffer in the
  104992. main vorbis_block */
  104993. } vorbis_block_internal;
  104994. typedef void vorbis_look_floor;
  104995. typedef void vorbis_look_residue;
  104996. typedef void vorbis_look_transform;
  104997. /* mode ************************************************************/
  104998. typedef struct {
  104999. int blockflag;
  105000. int windowtype;
  105001. int transformtype;
  105002. int mapping;
  105003. } vorbis_info_mode;
  105004. typedef void vorbis_info_floor;
  105005. typedef void vorbis_info_residue;
  105006. typedef void vorbis_info_mapping;
  105007. /********* Start of inlined file: psy.h *********/
  105008. #ifndef _V_PSY_H_
  105009. #define _V_PSY_H_
  105010. /********* Start of inlined file: smallft.h *********/
  105011. #ifndef _V_SMFT_H_
  105012. #define _V_SMFT_H_
  105013. typedef struct {
  105014. int n;
  105015. float *trigcache;
  105016. int *splitcache;
  105017. } drft_lookup;
  105018. extern void drft_forward(drft_lookup *l,float *data);
  105019. extern void drft_backward(drft_lookup *l,float *data);
  105020. extern void drft_init(drft_lookup *l,int n);
  105021. extern void drft_clear(drft_lookup *l);
  105022. #endif
  105023. /********* End of inlined file: smallft.h *********/
  105024. /********* Start of inlined file: backends.h *********/
  105025. /* this is exposed up here because we need it for static modes.
  105026. Lookups for each backend aren't exposed because there's no reason
  105027. to do so */
  105028. #ifndef _vorbis_backend_h_
  105029. #define _vorbis_backend_h_
  105030. /* this would all be simpler/shorter with templates, but.... */
  105031. /* Floor backend generic *****************************************/
  105032. typedef struct{
  105033. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  105034. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  105035. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  105036. void (*free_info) (vorbis_info_floor *);
  105037. void (*free_look) (vorbis_look_floor *);
  105038. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  105039. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  105040. void *buffer,float *);
  105041. } vorbis_func_floor;
  105042. typedef struct{
  105043. int order;
  105044. long rate;
  105045. long barkmap;
  105046. int ampbits;
  105047. int ampdB;
  105048. int numbooks; /* <= 16 */
  105049. int books[16];
  105050. float lessthan; /* encode-only config setting hacks for libvorbis */
  105051. float greaterthan; /* encode-only config setting hacks for libvorbis */
  105052. } vorbis_info_floor0;
  105053. #define VIF_POSIT 63
  105054. #define VIF_CLASS 16
  105055. #define VIF_PARTS 31
  105056. typedef struct{
  105057. int partitions; /* 0 to 31 */
  105058. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  105059. int class_dim[VIF_CLASS]; /* 1 to 8 */
  105060. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  105061. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  105062. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  105063. int mult; /* 1 2 3 or 4 */
  105064. int postlist[VIF_POSIT+2]; /* first two implicit */
  105065. /* encode side analysis parameters */
  105066. float maxover;
  105067. float maxunder;
  105068. float maxerr;
  105069. float twofitweight;
  105070. float twofitatten;
  105071. int n;
  105072. } vorbis_info_floor1;
  105073. /* Residue backend generic *****************************************/
  105074. typedef struct{
  105075. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  105076. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  105077. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  105078. vorbis_info_residue *);
  105079. void (*free_info) (vorbis_info_residue *);
  105080. void (*free_look) (vorbis_look_residue *);
  105081. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  105082. float **,int *,int);
  105083. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  105084. vorbis_look_residue *,
  105085. float **,float **,int *,int,long **);
  105086. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  105087. float **,int *,int);
  105088. } vorbis_func_residue;
  105089. typedef struct vorbis_info_residue0{
  105090. /* block-partitioned VQ coded straight residue */
  105091. long begin;
  105092. long end;
  105093. /* first stage (lossless partitioning) */
  105094. int grouping; /* group n vectors per partition */
  105095. int partitions; /* possible codebooks for a partition */
  105096. int groupbook; /* huffbook for partitioning */
  105097. int secondstages[64]; /* expanded out to pointers in lookup */
  105098. int booklist[256]; /* list of second stage books */
  105099. float classmetric1[64];
  105100. float classmetric2[64];
  105101. } vorbis_info_residue0;
  105102. /* Mapping backend generic *****************************************/
  105103. typedef struct{
  105104. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  105105. oggpack_buffer *);
  105106. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  105107. void (*free_info) (vorbis_info_mapping *);
  105108. int (*forward) (struct vorbis_block *vb);
  105109. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  105110. } vorbis_func_mapping;
  105111. typedef struct vorbis_info_mapping0{
  105112. int submaps; /* <= 16 */
  105113. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  105114. int floorsubmap[16]; /* [mux] submap to floors */
  105115. int residuesubmap[16]; /* [mux] submap to residue */
  105116. int coupling_steps;
  105117. int coupling_mag[256];
  105118. int coupling_ang[256];
  105119. } vorbis_info_mapping0;
  105120. #endif
  105121. /********* End of inlined file: backends.h *********/
  105122. #ifndef EHMER_MAX
  105123. #define EHMER_MAX 56
  105124. #endif
  105125. /* psychoacoustic setup ********************************************/
  105126. #define P_BANDS 17 /* 62Hz to 16kHz */
  105127. #define P_LEVELS 8 /* 30dB to 100dB */
  105128. #define P_LEVEL_0 30. /* 30 dB */
  105129. #define P_NOISECURVES 3
  105130. #define NOISE_COMPAND_LEVELS 40
  105131. typedef struct vorbis_info_psy{
  105132. int blockflag;
  105133. float ath_adjatt;
  105134. float ath_maxatt;
  105135. float tone_masteratt[P_NOISECURVES];
  105136. float tone_centerboost;
  105137. float tone_decay;
  105138. float tone_abs_limit;
  105139. float toneatt[P_BANDS];
  105140. int noisemaskp;
  105141. float noisemaxsupp;
  105142. float noisewindowlo;
  105143. float noisewindowhi;
  105144. int noisewindowlomin;
  105145. int noisewindowhimin;
  105146. int noisewindowfixed;
  105147. float noiseoff[P_NOISECURVES][P_BANDS];
  105148. float noisecompand[NOISE_COMPAND_LEVELS];
  105149. float max_curve_dB;
  105150. int normal_channel_p;
  105151. int normal_point_p;
  105152. int normal_start;
  105153. int normal_partition;
  105154. double normal_thresh;
  105155. } vorbis_info_psy;
  105156. typedef struct{
  105157. int eighth_octave_lines;
  105158. /* for block long/short tuning; encode only */
  105159. float preecho_thresh[VE_BANDS];
  105160. float postecho_thresh[VE_BANDS];
  105161. float stretch_penalty;
  105162. float preecho_minenergy;
  105163. float ampmax_att_per_sec;
  105164. /* channel coupling config */
  105165. int coupling_pkHz[PACKETBLOBS];
  105166. int coupling_pointlimit[2][PACKETBLOBS];
  105167. int coupling_prepointamp[PACKETBLOBS];
  105168. int coupling_postpointamp[PACKETBLOBS];
  105169. int sliding_lowpass[2][PACKETBLOBS];
  105170. } vorbis_info_psy_global;
  105171. typedef struct {
  105172. float ampmax;
  105173. int channels;
  105174. vorbis_info_psy_global *gi;
  105175. int coupling_pointlimit[2][P_NOISECURVES];
  105176. } vorbis_look_psy_global;
  105177. typedef struct {
  105178. int n;
  105179. struct vorbis_info_psy *vi;
  105180. float ***tonecurves;
  105181. float **noiseoffset;
  105182. float *ath;
  105183. long *octave; /* in n.ocshift format */
  105184. long *bark;
  105185. long firstoc;
  105186. long shiftoc;
  105187. int eighth_octave_lines; /* power of two, please */
  105188. int total_octave_lines;
  105189. long rate; /* cache it */
  105190. float m_val; /* Masking compensation value */
  105191. } vorbis_look_psy;
  105192. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  105193. vorbis_info_psy_global *gi,int n,long rate);
  105194. extern void _vp_psy_clear(vorbis_look_psy *p);
  105195. extern void *_vi_psy_dup(void *source);
  105196. extern void _vi_psy_free(vorbis_info_psy *i);
  105197. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  105198. extern void _vp_remove_floor(vorbis_look_psy *p,
  105199. float *mdct,
  105200. int *icodedflr,
  105201. float *residue,
  105202. int sliding_lowpass);
  105203. extern void _vp_noisemask(vorbis_look_psy *p,
  105204. float *logmdct,
  105205. float *logmask);
  105206. extern void _vp_tonemask(vorbis_look_psy *p,
  105207. float *logfft,
  105208. float *logmask,
  105209. float global_specmax,
  105210. float local_specmax);
  105211. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  105212. float *noise,
  105213. float *tone,
  105214. int offset_select,
  105215. float *logmask,
  105216. float *mdct,
  105217. float *logmdct);
  105218. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  105219. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  105220. vorbis_info_psy_global *g,
  105221. vorbis_look_psy *p,
  105222. vorbis_info_mapping0 *vi,
  105223. float **mdct);
  105224. extern void _vp_couple(int blobno,
  105225. vorbis_info_psy_global *g,
  105226. vorbis_look_psy *p,
  105227. vorbis_info_mapping0 *vi,
  105228. float **res,
  105229. float **mag_memo,
  105230. int **mag_sort,
  105231. int **ifloor,
  105232. int *nonzero,
  105233. int sliding_lowpass);
  105234. extern void _vp_noise_normalize(vorbis_look_psy *p,
  105235. float *in,float *out,int *sortedindex);
  105236. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  105237. float *magnitudes,int *sortedindex);
  105238. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  105239. vorbis_look_psy *p,
  105240. vorbis_info_mapping0 *vi,
  105241. float **mags);
  105242. extern void hf_reduction(vorbis_info_psy_global *g,
  105243. vorbis_look_psy *p,
  105244. vorbis_info_mapping0 *vi,
  105245. float **mdct);
  105246. #endif
  105247. /********* End of inlined file: psy.h *********/
  105248. /********* Start of inlined file: bitrate.h *********/
  105249. #ifndef _V_BITRATE_H_
  105250. #define _V_BITRATE_H_
  105251. /********* Start of inlined file: os.h *********/
  105252. #ifndef _OS_H
  105253. #define _OS_H
  105254. /********************************************************************
  105255. * *
  105256. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  105257. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  105258. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  105259. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  105260. * *
  105261. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  105262. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  105263. * *
  105264. ********************************************************************
  105265. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  105266. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  105267. ********************************************************************/
  105268. #ifdef HAVE_CONFIG_H
  105269. #include "config.h"
  105270. #endif
  105271. #include <math.h>
  105272. /********* Start of inlined file: misc.h *********/
  105273. #ifndef _V_RANDOM_H_
  105274. #define _V_RANDOM_H_
  105275. extern int analysis_noisy;
  105276. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  105277. extern void _vorbis_block_ripcord(vorbis_block *vb);
  105278. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  105279. ogg_int64_t off);
  105280. #ifdef DEBUG_MALLOC
  105281. #define _VDBG_GRAPHFILE "malloc.m"
  105282. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  105283. extern void _VDBG_free(void *ptr,char *file,long line);
  105284. #ifndef MISC_C
  105285. #undef _ogg_malloc
  105286. #undef _ogg_calloc
  105287. #undef _ogg_realloc
  105288. #undef _ogg_free
  105289. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  105290. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  105291. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  105292. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  105293. #endif
  105294. #endif
  105295. #endif
  105296. /********* End of inlined file: misc.h *********/
  105297. #ifndef _V_IFDEFJAIL_H_
  105298. # define _V_IFDEFJAIL_H_
  105299. # ifdef __GNUC__
  105300. # define STIN static __inline__
  105301. # elif _WIN32
  105302. # define STIN static __inline
  105303. # else
  105304. # define STIN static
  105305. # endif
  105306. #ifdef DJGPP
  105307. # define rint(x) (floor((x)+0.5f))
  105308. #endif
  105309. #ifndef M_PI
  105310. # define M_PI (3.1415926536f)
  105311. #endif
  105312. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  105313. # include <malloc.h>
  105314. # define rint(x) (floor((x)+0.5f))
  105315. # define NO_FLOAT_MATH_LIB
  105316. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  105317. #endif
  105318. #if defined(__SYMBIAN32__) && defined(__WINS__)
  105319. void *_alloca(size_t size);
  105320. # define alloca _alloca
  105321. #endif
  105322. #ifndef FAST_HYPOT
  105323. # define FAST_HYPOT hypot
  105324. #endif
  105325. #endif
  105326. #ifdef HAVE_ALLOCA_H
  105327. # include <alloca.h>
  105328. #endif
  105329. #ifdef USE_MEMORY_H
  105330. # include <memory.h>
  105331. #endif
  105332. #ifndef min
  105333. # define min(x,y) ((x)>(y)?(y):(x))
  105334. #endif
  105335. #ifndef max
  105336. # define max(x,y) ((x)<(y)?(y):(x))
  105337. #endif
  105338. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  105339. # define VORBIS_FPU_CONTROL
  105340. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  105341. Because of encapsulation constraints (GCC can't see inside the asm
  105342. block and so we end up doing stupid things like a store/load that
  105343. is collectively a noop), we do it this way */
  105344. /* we must set up the fpu before this works!! */
  105345. typedef ogg_int16_t vorbis_fpu_control;
  105346. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  105347. ogg_int16_t ret;
  105348. ogg_int16_t temp;
  105349. __asm__ __volatile__("fnstcw %0\n\t"
  105350. "movw %0,%%dx\n\t"
  105351. "orw $62463,%%dx\n\t"
  105352. "movw %%dx,%1\n\t"
  105353. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  105354. *fpu=ret;
  105355. }
  105356. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  105357. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  105358. }
  105359. /* assumes the FPU is in round mode! */
  105360. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  105361. we get extra fst/fld to
  105362. truncate precision */
  105363. int i;
  105364. __asm__("fistl %0": "=m"(i) : "t"(f));
  105365. return(i);
  105366. }
  105367. #endif
  105368. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  105369. # define VORBIS_FPU_CONTROL
  105370. typedef ogg_int16_t vorbis_fpu_control;
  105371. static __inline int vorbis_ftoi(double f){
  105372. int i;
  105373. __asm{
  105374. fld f
  105375. fistp i
  105376. }
  105377. return i;
  105378. }
  105379. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  105380. }
  105381. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  105382. }
  105383. #endif
  105384. #ifndef VORBIS_FPU_CONTROL
  105385. typedef int vorbis_fpu_control;
  105386. static int vorbis_ftoi(double f){
  105387. return (int)(f+.5);
  105388. }
  105389. /* We don't have special code for this compiler/arch, so do it the slow way */
  105390. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  105391. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  105392. #endif
  105393. #endif /* _OS_H */
  105394. /********* End of inlined file: os.h *********/
  105395. /* encode side bitrate tracking */
  105396. typedef struct bitrate_manager_state {
  105397. int managed;
  105398. long avg_reservoir;
  105399. long minmax_reservoir;
  105400. long avg_bitsper;
  105401. long min_bitsper;
  105402. long max_bitsper;
  105403. long short_per_long;
  105404. double avgfloat;
  105405. vorbis_block *vb;
  105406. int choice;
  105407. } bitrate_manager_state;
  105408. typedef struct bitrate_manager_info{
  105409. long avg_rate;
  105410. long min_rate;
  105411. long max_rate;
  105412. long reservoir_bits;
  105413. double reservoir_bias;
  105414. double slew_damp;
  105415. } bitrate_manager_info;
  105416. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  105417. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  105418. extern int vorbis_bitrate_managed(vorbis_block *vb);
  105419. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  105420. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  105421. #endif
  105422. /********* End of inlined file: bitrate.h *********/
  105423. static int ilog(unsigned int v){
  105424. int ret=0;
  105425. while(v){
  105426. ret++;
  105427. v>>=1;
  105428. }
  105429. return(ret);
  105430. }
  105431. static int ilog2(unsigned int v){
  105432. int ret=0;
  105433. if(v)--v;
  105434. while(v){
  105435. ret++;
  105436. v>>=1;
  105437. }
  105438. return(ret);
  105439. }
  105440. typedef struct private_state {
  105441. /* local lookup storage */
  105442. envelope_lookup *ve; /* envelope lookup */
  105443. int window[2];
  105444. vorbis_look_transform **transform[2]; /* block, type */
  105445. drft_lookup fft_look[2];
  105446. int modebits;
  105447. vorbis_look_floor **flr;
  105448. vorbis_look_residue **residue;
  105449. vorbis_look_psy *psy;
  105450. vorbis_look_psy_global *psy_g_look;
  105451. /* local storage, only used on the encoding side. This way the
  105452. application does not need to worry about freeing some packets'
  105453. memory and not others'; packet storage is always tracked.
  105454. Cleared next call to a _dsp_ function */
  105455. unsigned char *header;
  105456. unsigned char *header1;
  105457. unsigned char *header2;
  105458. bitrate_manager_state bms;
  105459. ogg_int64_t sample_count;
  105460. } private_state;
  105461. /* codec_setup_info contains all the setup information specific to the
  105462. specific compression/decompression mode in progress (eg,
  105463. psychoacoustic settings, channel setup, options, codebook
  105464. etc).
  105465. *********************************************************************/
  105466. /********* Start of inlined file: highlevel.h *********/
  105467. typedef struct highlevel_byblocktype {
  105468. double tone_mask_setting;
  105469. double tone_peaklimit_setting;
  105470. double noise_bias_setting;
  105471. double noise_compand_setting;
  105472. } highlevel_byblocktype;
  105473. typedef struct highlevel_encode_setup {
  105474. void *setup;
  105475. int set_in_stone;
  105476. double base_setting;
  105477. double long_setting;
  105478. double short_setting;
  105479. double impulse_noisetune;
  105480. int managed;
  105481. long bitrate_min;
  105482. long bitrate_av;
  105483. double bitrate_av_damp;
  105484. long bitrate_max;
  105485. long bitrate_reservoir;
  105486. double bitrate_reservoir_bias;
  105487. int impulse_block_p;
  105488. int noise_normalize_p;
  105489. double stereo_point_setting;
  105490. double lowpass_kHz;
  105491. double ath_floating_dB;
  105492. double ath_absolute_dB;
  105493. double amplitude_track_dBpersec;
  105494. double trigger_setting;
  105495. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  105496. } highlevel_encode_setup;
  105497. /********* End of inlined file: highlevel.h *********/
  105498. typedef struct codec_setup_info {
  105499. /* Vorbis supports only short and long blocks, but allows the
  105500. encoder to choose the sizes */
  105501. long blocksizes[2];
  105502. /* modes are the primary means of supporting on-the-fly different
  105503. blocksizes, different channel mappings (LR or M/A),
  105504. different residue backends, etc. Each mode consists of a
  105505. blocksize flag and a mapping (along with the mapping setup */
  105506. int modes;
  105507. int maps;
  105508. int floors;
  105509. int residues;
  105510. int books;
  105511. int psys; /* encode only */
  105512. vorbis_info_mode *mode_param[64];
  105513. int map_type[64];
  105514. vorbis_info_mapping *map_param[64];
  105515. int floor_type[64];
  105516. vorbis_info_floor *floor_param[64];
  105517. int residue_type[64];
  105518. vorbis_info_residue *residue_param[64];
  105519. static_codebook *book_param[256];
  105520. codebook *fullbooks;
  105521. vorbis_info_psy *psy_param[4]; /* encode only */
  105522. vorbis_info_psy_global psy_g_param;
  105523. bitrate_manager_info bi;
  105524. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  105525. highly redundant structure, but
  105526. improves clarity of program flow. */
  105527. int halfrate_flag; /* painless downsample for decode */
  105528. } codec_setup_info;
  105529. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  105530. extern void _vp_global_free(vorbis_look_psy_global *look);
  105531. #endif
  105532. /********* End of inlined file: codec_internal.h *********/
  105533. /********* Start of inlined file: registry.h *********/
  105534. #ifndef _V_REG_H_
  105535. #define _V_REG_H_
  105536. #define VI_TRANSFORMB 1
  105537. #define VI_WINDOWB 1
  105538. #define VI_TIMEB 1
  105539. #define VI_FLOORB 2
  105540. #define VI_RESB 3
  105541. #define VI_MAPB 1
  105542. extern vorbis_func_floor *_floor_P[];
  105543. extern vorbis_func_residue *_residue_P[];
  105544. extern vorbis_func_mapping *_mapping_P[];
  105545. #endif
  105546. /********* End of inlined file: registry.h *********/
  105547. /********* Start of inlined file: scales.h *********/
  105548. #ifndef _V_SCALES_H_
  105549. #define _V_SCALES_H_
  105550. #include <math.h>
  105551. /* 20log10(x) */
  105552. #define VORBIS_IEEE_FLOAT32 1
  105553. #ifdef VORBIS_IEEE_FLOAT32
  105554. static float unitnorm(float x){
  105555. union {
  105556. ogg_uint32_t i;
  105557. float f;
  105558. } ix;
  105559. ix.f = x;
  105560. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  105561. return ix.f;
  105562. }
  105563. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  105564. static float todB(const float *x){
  105565. union {
  105566. ogg_uint32_t i;
  105567. float f;
  105568. } ix;
  105569. ix.f = *x;
  105570. ix.i = ix.i&0x7fffffff;
  105571. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  105572. }
  105573. #define todB_nn(x) todB(x)
  105574. #else
  105575. static float unitnorm(float x){
  105576. if(x<0)return(-1.f);
  105577. return(1.f);
  105578. }
  105579. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  105580. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  105581. #endif
  105582. #define fromdB(x) (exp((x)*.11512925f))
  105583. /* The bark scale equations are approximations, since the original
  105584. table was somewhat hand rolled. The below are chosen to have the
  105585. best possible fit to the rolled tables, thus their somewhat odd
  105586. appearance (these are more accurate and over a longer range than
  105587. the oft-quoted bark equations found in the texts I have). The
  105588. approximations are valid from 0 - 30kHz (nyquist) or so.
  105589. all f in Hz, z in Bark */
  105590. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  105591. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  105592. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  105593. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  105594. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  105595. 0.0 */
  105596. #define toOC(n) (log(n)*1.442695f-5.965784f)
  105597. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  105598. #endif
  105599. /********* End of inlined file: scales.h *********/
  105600. int analysis_noisy=1;
  105601. /* decides between modes, dispatches to the appropriate mapping. */
  105602. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  105603. int ret,i;
  105604. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  105605. vb->glue_bits=0;
  105606. vb->time_bits=0;
  105607. vb->floor_bits=0;
  105608. vb->res_bits=0;
  105609. /* first things first. Make sure encode is ready */
  105610. for(i=0;i<PACKETBLOBS;i++)
  105611. oggpack_reset(vbi->packetblob[i]);
  105612. /* we only have one mapping type (0), and we let the mapping code
  105613. itself figure out what soft mode to use. This allows easier
  105614. bitrate management */
  105615. if((ret=_mapping_P[0]->forward(vb)))
  105616. return(ret);
  105617. if(op){
  105618. if(vorbis_bitrate_managed(vb))
  105619. /* The app is using a bitmanaged mode... but not using the
  105620. bitrate management interface. */
  105621. return(OV_EINVAL);
  105622. op->packet=oggpack_get_buffer(&vb->opb);
  105623. op->bytes=oggpack_bytes(&vb->opb);
  105624. op->b_o_s=0;
  105625. op->e_o_s=vb->eofflag;
  105626. op->granulepos=vb->granulepos;
  105627. op->packetno=vb->sequence; /* for sake of completeness */
  105628. }
  105629. return(0);
  105630. }
  105631. /* there was no great place to put this.... */
  105632. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  105633. int j;
  105634. FILE *of;
  105635. char buffer[80];
  105636. /* if(i==5870){*/
  105637. sprintf(buffer,"%s_%d.m",base,i);
  105638. of=fopen(buffer,"w");
  105639. if(!of)perror("failed to open data dump file");
  105640. for(j=0;j<n;j++){
  105641. if(bark){
  105642. float b=toBARK((4000.f*j/n)+.25);
  105643. fprintf(of,"%f ",b);
  105644. }else
  105645. if(off!=0)
  105646. fprintf(of,"%f ",(double)(j+off)/8000.);
  105647. else
  105648. fprintf(of,"%f ",(double)j);
  105649. if(dB){
  105650. float val;
  105651. if(v[j]==0.)
  105652. val=-140.;
  105653. else
  105654. val=todB(v+j);
  105655. fprintf(of,"%f\n",val);
  105656. }else{
  105657. fprintf(of,"%f\n",v[j]);
  105658. }
  105659. }
  105660. fclose(of);
  105661. /* } */
  105662. }
  105663. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  105664. ogg_int64_t off){
  105665. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  105666. }
  105667. #endif
  105668. /********* End of inlined file: analysis.c *********/
  105669. /********* Start of inlined file: bitrate.c *********/
  105670. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105671. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105672. // tasks..
  105673. #ifdef _MSC_VER
  105674. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105675. #endif
  105676. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105677. #if JUCE_USE_OGGVORBIS
  105678. #include <stdlib.h>
  105679. #include <string.h>
  105680. #include <math.h>
  105681. /* compute bitrate tracking setup */
  105682. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  105683. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  105684. bitrate_manager_info *bi=&ci->bi;
  105685. memset(bm,0,sizeof(*bm));
  105686. if(bi && (bi->reservoir_bits>0)){
  105687. long ratesamples=vi->rate;
  105688. int halfsamples=ci->blocksizes[0]>>1;
  105689. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  105690. bm->managed=1;
  105691. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  105692. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  105693. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  105694. bm->avgfloat=PACKETBLOBS/2;
  105695. /* not a necessary fix, but one that leads to a more balanced
  105696. typical initialization */
  105697. {
  105698. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  105699. bm->minmax_reservoir=desired_fill;
  105700. bm->avg_reservoir=desired_fill;
  105701. }
  105702. }
  105703. }
  105704. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  105705. memset(bm,0,sizeof(*bm));
  105706. return;
  105707. }
  105708. int vorbis_bitrate_managed(vorbis_block *vb){
  105709. vorbis_dsp_state *vd=vb->vd;
  105710. private_state *b=(private_state*)vd->backend_state;
  105711. bitrate_manager_state *bm=&b->bms;
  105712. if(bm && bm->managed)return(1);
  105713. return(0);
  105714. }
  105715. /* finish taking in the block we just processed */
  105716. int vorbis_bitrate_addblock(vorbis_block *vb){
  105717. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  105718. vorbis_dsp_state *vd=vb->vd;
  105719. private_state *b=(private_state*)vd->backend_state;
  105720. bitrate_manager_state *bm=&b->bms;
  105721. vorbis_info *vi=vd->vi;
  105722. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105723. bitrate_manager_info *bi=&ci->bi;
  105724. int choice=rint(bm->avgfloat);
  105725. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105726. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  105727. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  105728. int samples=ci->blocksizes[vb->W]>>1;
  105729. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  105730. if(!bm->managed){
  105731. /* not a bitrate managed stream, but for API simplicity, we'll
  105732. buffer the packet to keep the code path clean */
  105733. if(bm->vb)return(-1); /* one has been submitted without
  105734. being claimed */
  105735. bm->vb=vb;
  105736. return(0);
  105737. }
  105738. bm->vb=vb;
  105739. /* look ahead for avg floater */
  105740. if(bm->avg_bitsper>0){
  105741. double slew=0.;
  105742. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  105743. double slewlimit= 15./bi->slew_damp;
  105744. /* choosing a new floater:
  105745. if we're over target, we slew down
  105746. if we're under target, we slew up
  105747. choose slew as follows: look through packetblobs of this frame
  105748. and set slew as the first in the appropriate direction that
  105749. gives us the slew we want. This may mean no slew if delta is
  105750. already favorable.
  105751. Then limit slew to slew max */
  105752. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  105753. while(choice>0 && this_bits>avg_target_bits &&
  105754. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  105755. choice--;
  105756. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105757. }
  105758. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  105759. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  105760. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  105761. choice++;
  105762. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105763. }
  105764. }
  105765. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  105766. if(slew<-slewlimit)slew=-slewlimit;
  105767. if(slew>slewlimit)slew=slewlimit;
  105768. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  105769. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105770. }
  105771. /* enforce min(if used) on the current floater (if used) */
  105772. if(bm->min_bitsper>0){
  105773. /* do we need to force the bitrate up? */
  105774. if(this_bits<min_target_bits){
  105775. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  105776. choice++;
  105777. if(choice>=PACKETBLOBS)break;
  105778. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105779. }
  105780. }
  105781. }
  105782. /* enforce max (if used) on the current floater (if used) */
  105783. if(bm->max_bitsper>0){
  105784. /* do we need to force the bitrate down? */
  105785. if(this_bits>max_target_bits){
  105786. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  105787. choice--;
  105788. if(choice<0)break;
  105789. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105790. }
  105791. }
  105792. }
  105793. /* Choice of packetblobs now made based on floater, and min/max
  105794. requirements. Now boundary check extreme choices */
  105795. if(choice<0){
  105796. /* choosing a smaller packetblob is insufficient to trim bitrate.
  105797. frame will need to be truncated */
  105798. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  105799. bm->choice=choice=0;
  105800. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  105801. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  105802. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105803. }
  105804. }else{
  105805. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  105806. if(choice>=PACKETBLOBS)
  105807. choice=PACKETBLOBS-1;
  105808. bm->choice=choice;
  105809. /* prop up bitrate according to demand. pad this frame out with zeroes */
  105810. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  105811. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  105812. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105813. }
  105814. /* now we have the final packet and the final packet size. Update statistics */
  105815. /* min and max reservoir */
  105816. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  105817. if(max_target_bits>0 && this_bits>max_target_bits){
  105818. bm->minmax_reservoir+=(this_bits-max_target_bits);
  105819. }else if(min_target_bits>0 && this_bits<min_target_bits){
  105820. bm->minmax_reservoir+=(this_bits-min_target_bits);
  105821. }else{
  105822. /* inbetween; we want to take reservoir toward but not past desired_fill */
  105823. if(bm->minmax_reservoir>desired_fill){
  105824. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  105825. bm->minmax_reservoir+=(this_bits-max_target_bits);
  105826. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  105827. }else{
  105828. bm->minmax_reservoir=desired_fill;
  105829. }
  105830. }else{
  105831. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  105832. bm->minmax_reservoir+=(this_bits-min_target_bits);
  105833. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  105834. }else{
  105835. bm->minmax_reservoir=desired_fill;
  105836. }
  105837. }
  105838. }
  105839. }
  105840. /* avg reservoir */
  105841. if(bm->avg_bitsper>0){
  105842. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  105843. bm->avg_reservoir+=this_bits-avg_target_bits;
  105844. }
  105845. return(0);
  105846. }
  105847. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  105848. private_state *b=(private_state*)vd->backend_state;
  105849. bitrate_manager_state *bm=&b->bms;
  105850. vorbis_block *vb=bm->vb;
  105851. int choice=PACKETBLOBS/2;
  105852. if(!vb)return 0;
  105853. if(op){
  105854. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  105855. if(vorbis_bitrate_managed(vb))
  105856. choice=bm->choice;
  105857. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  105858. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  105859. op->b_o_s=0;
  105860. op->e_o_s=vb->eofflag;
  105861. op->granulepos=vb->granulepos;
  105862. op->packetno=vb->sequence; /* for sake of completeness */
  105863. }
  105864. bm->vb=0;
  105865. return(1);
  105866. }
  105867. #endif
  105868. /********* End of inlined file: bitrate.c *********/
  105869. /********* Start of inlined file: block.c *********/
  105870. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105871. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105872. // tasks..
  105873. #ifdef _MSC_VER
  105874. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105875. #endif
  105876. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105877. #if JUCE_USE_OGGVORBIS
  105878. #include <stdio.h>
  105879. #include <stdlib.h>
  105880. #include <string.h>
  105881. /********* Start of inlined file: window.h *********/
  105882. #ifndef _V_WINDOW_
  105883. #define _V_WINDOW_
  105884. extern float *_vorbis_window_get(int n);
  105885. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  105886. int lW,int W,int nW);
  105887. #endif
  105888. /********* End of inlined file: window.h *********/
  105889. /********* Start of inlined file: lpc.h *********/
  105890. #ifndef _V_LPC_H_
  105891. #define _V_LPC_H_
  105892. /* simple linear scale LPC code */
  105893. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  105894. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  105895. float *data,long n);
  105896. #endif
  105897. /********* End of inlined file: lpc.h *********/
  105898. /* pcm accumulator examples (not exhaustive):
  105899. <-------------- lW ---------------->
  105900. <--------------- W ---------------->
  105901. : .....|..... _______________ |
  105902. : .''' | '''_--- | |\ |
  105903. :.....''' |_____--- '''......| | \_______|
  105904. :.................|__________________|_______|__|______|
  105905. |<------ Sl ------>| > Sr < |endW
  105906. |beginSl |endSl | |endSr
  105907. |beginW |endlW |beginSr
  105908. |< lW >|
  105909. <--------------- W ---------------->
  105910. | | .. ______________ |
  105911. | | ' `/ | ---_ |
  105912. |___.'___/`. | ---_____|
  105913. |_______|__|_______|_________________|
  105914. | >|Sl|< |<------ Sr ----->|endW
  105915. | | |endSl |beginSr |endSr
  105916. |beginW | |endlW
  105917. mult[0] |beginSl mult[n]
  105918. <-------------- lW ----------------->
  105919. |<--W-->|
  105920. : .............. ___ | |
  105921. : .''' |`/ \ | |
  105922. :.....''' |/`....\|...|
  105923. :.........................|___|___|___|
  105924. |Sl |Sr |endW
  105925. | | |endSr
  105926. | |beginSr
  105927. | |endSl
  105928. |beginSl
  105929. |beginW
  105930. */
  105931. /* block abstraction setup *********************************************/
  105932. #ifndef WORD_ALIGN
  105933. #define WORD_ALIGN 8
  105934. #endif
  105935. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  105936. int i;
  105937. memset(vb,0,sizeof(*vb));
  105938. vb->vd=v;
  105939. vb->localalloc=0;
  105940. vb->localstore=NULL;
  105941. if(v->analysisp){
  105942. vorbis_block_internal *vbi=(vorbis_block_internal*)
  105943. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  105944. vbi->ampmax=-9999;
  105945. for(i=0;i<PACKETBLOBS;i++){
  105946. if(i==PACKETBLOBS/2){
  105947. vbi->packetblob[i]=&vb->opb;
  105948. }else{
  105949. vbi->packetblob[i]=
  105950. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  105951. }
  105952. oggpack_writeinit(vbi->packetblob[i]);
  105953. }
  105954. }
  105955. return(0);
  105956. }
  105957. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  105958. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  105959. if(bytes+vb->localtop>vb->localalloc){
  105960. /* can't just _ogg_realloc... there are outstanding pointers */
  105961. if(vb->localstore){
  105962. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  105963. vb->totaluse+=vb->localtop;
  105964. link->next=vb->reap;
  105965. link->ptr=vb->localstore;
  105966. vb->reap=link;
  105967. }
  105968. /* highly conservative */
  105969. vb->localalloc=bytes;
  105970. vb->localstore=_ogg_malloc(vb->localalloc);
  105971. vb->localtop=0;
  105972. }
  105973. {
  105974. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  105975. vb->localtop+=bytes;
  105976. return ret;
  105977. }
  105978. }
  105979. /* reap the chain, pull the ripcord */
  105980. void _vorbis_block_ripcord(vorbis_block *vb){
  105981. /* reap the chain */
  105982. struct alloc_chain *reap=vb->reap;
  105983. while(reap){
  105984. struct alloc_chain *next=reap->next;
  105985. _ogg_free(reap->ptr);
  105986. memset(reap,0,sizeof(*reap));
  105987. _ogg_free(reap);
  105988. reap=next;
  105989. }
  105990. /* consolidate storage */
  105991. if(vb->totaluse){
  105992. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  105993. vb->localalloc+=vb->totaluse;
  105994. vb->totaluse=0;
  105995. }
  105996. /* pull the ripcord */
  105997. vb->localtop=0;
  105998. vb->reap=NULL;
  105999. }
  106000. int vorbis_block_clear(vorbis_block *vb){
  106001. int i;
  106002. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106003. _vorbis_block_ripcord(vb);
  106004. if(vb->localstore)_ogg_free(vb->localstore);
  106005. if(vbi){
  106006. for(i=0;i<PACKETBLOBS;i++){
  106007. oggpack_writeclear(vbi->packetblob[i]);
  106008. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  106009. }
  106010. _ogg_free(vbi);
  106011. }
  106012. memset(vb,0,sizeof(*vb));
  106013. return(0);
  106014. }
  106015. /* Analysis side code, but directly related to blocking. Thus it's
  106016. here and not in analysis.c (which is for analysis transforms only).
  106017. The init is here because some of it is shared */
  106018. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  106019. int i;
  106020. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106021. private_state *b=NULL;
  106022. int hs;
  106023. if(ci==NULL) return 1;
  106024. hs=ci->halfrate_flag;
  106025. memset(v,0,sizeof(*v));
  106026. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  106027. v->vi=vi;
  106028. b->modebits=ilog2(ci->modes);
  106029. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  106030. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  106031. /* MDCT is tranform 0 */
  106032. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  106033. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  106034. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  106035. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  106036. /* Vorbis I uses only window type 0 */
  106037. b->window[0]=ilog2(ci->blocksizes[0])-6;
  106038. b->window[1]=ilog2(ci->blocksizes[1])-6;
  106039. if(encp){ /* encode/decode differ here */
  106040. /* analysis always needs an fft */
  106041. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  106042. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  106043. /* finish the codebooks */
  106044. if(!ci->fullbooks){
  106045. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  106046. for(i=0;i<ci->books;i++)
  106047. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  106048. }
  106049. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  106050. for(i=0;i<ci->psys;i++){
  106051. _vp_psy_init(b->psy+i,
  106052. ci->psy_param[i],
  106053. &ci->psy_g_param,
  106054. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  106055. vi->rate);
  106056. }
  106057. v->analysisp=1;
  106058. }else{
  106059. /* finish the codebooks */
  106060. if(!ci->fullbooks){
  106061. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  106062. for(i=0;i<ci->books;i++){
  106063. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  106064. /* decode codebooks are now standalone after init */
  106065. vorbis_staticbook_destroy(ci->book_param[i]);
  106066. ci->book_param[i]=NULL;
  106067. }
  106068. }
  106069. }
  106070. /* initialize the storage vectors. blocksize[1] is small for encode,
  106071. but the correct size for decode */
  106072. v->pcm_storage=ci->blocksizes[1];
  106073. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  106074. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  106075. {
  106076. int i;
  106077. for(i=0;i<vi->channels;i++)
  106078. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  106079. }
  106080. /* all 1 (large block) or 0 (small block) */
  106081. /* explicitly set for the sake of clarity */
  106082. v->lW=0; /* previous window size */
  106083. v->W=0; /* current window size */
  106084. /* all vector indexes */
  106085. v->centerW=ci->blocksizes[1]/2;
  106086. v->pcm_current=v->centerW;
  106087. /* initialize all the backend lookups */
  106088. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  106089. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  106090. for(i=0;i<ci->floors;i++)
  106091. b->flr[i]=_floor_P[ci->floor_type[i]]->
  106092. look(v,ci->floor_param[i]);
  106093. for(i=0;i<ci->residues;i++)
  106094. b->residue[i]=_residue_P[ci->residue_type[i]]->
  106095. look(v,ci->residue_param[i]);
  106096. return 0;
  106097. }
  106098. /* arbitrary settings and spec-mandated numbers get filled in here */
  106099. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  106100. private_state *b=NULL;
  106101. if(_vds_shared_init(v,vi,1))return 1;
  106102. b=(private_state*)v->backend_state;
  106103. b->psy_g_look=_vp_global_look(vi);
  106104. /* Initialize the envelope state storage */
  106105. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  106106. _ve_envelope_init(b->ve,vi);
  106107. vorbis_bitrate_init(vi,&b->bms);
  106108. /* compressed audio packets start after the headers
  106109. with sequence number 3 */
  106110. v->sequence=3;
  106111. return(0);
  106112. }
  106113. void vorbis_dsp_clear(vorbis_dsp_state *v){
  106114. int i;
  106115. if(v){
  106116. vorbis_info *vi=v->vi;
  106117. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  106118. private_state *b=(private_state*)v->backend_state;
  106119. if(b){
  106120. if(b->ve){
  106121. _ve_envelope_clear(b->ve);
  106122. _ogg_free(b->ve);
  106123. }
  106124. if(b->transform[0]){
  106125. mdct_clear((mdct_lookup*) b->transform[0][0]);
  106126. _ogg_free(b->transform[0][0]);
  106127. _ogg_free(b->transform[0]);
  106128. }
  106129. if(b->transform[1]){
  106130. mdct_clear((mdct_lookup*) b->transform[1][0]);
  106131. _ogg_free(b->transform[1][0]);
  106132. _ogg_free(b->transform[1]);
  106133. }
  106134. if(b->flr){
  106135. for(i=0;i<ci->floors;i++)
  106136. _floor_P[ci->floor_type[i]]->
  106137. free_look(b->flr[i]);
  106138. _ogg_free(b->flr);
  106139. }
  106140. if(b->residue){
  106141. for(i=0;i<ci->residues;i++)
  106142. _residue_P[ci->residue_type[i]]->
  106143. free_look(b->residue[i]);
  106144. _ogg_free(b->residue);
  106145. }
  106146. if(b->psy){
  106147. for(i=0;i<ci->psys;i++)
  106148. _vp_psy_clear(b->psy+i);
  106149. _ogg_free(b->psy);
  106150. }
  106151. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  106152. vorbis_bitrate_clear(&b->bms);
  106153. drft_clear(&b->fft_look[0]);
  106154. drft_clear(&b->fft_look[1]);
  106155. }
  106156. if(v->pcm){
  106157. for(i=0;i<vi->channels;i++)
  106158. if(v->pcm[i])_ogg_free(v->pcm[i]);
  106159. _ogg_free(v->pcm);
  106160. if(v->pcmret)_ogg_free(v->pcmret);
  106161. }
  106162. if(b){
  106163. /* free header, header1, header2 */
  106164. if(b->header)_ogg_free(b->header);
  106165. if(b->header1)_ogg_free(b->header1);
  106166. if(b->header2)_ogg_free(b->header2);
  106167. _ogg_free(b);
  106168. }
  106169. memset(v,0,sizeof(*v));
  106170. }
  106171. }
  106172. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  106173. int i;
  106174. vorbis_info *vi=v->vi;
  106175. private_state *b=(private_state*)v->backend_state;
  106176. /* free header, header1, header2 */
  106177. if(b->header)_ogg_free(b->header);b->header=NULL;
  106178. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  106179. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  106180. /* Do we have enough storage space for the requested buffer? If not,
  106181. expand the PCM (and envelope) storage */
  106182. if(v->pcm_current+vals>=v->pcm_storage){
  106183. v->pcm_storage=v->pcm_current+vals*2;
  106184. for(i=0;i<vi->channels;i++){
  106185. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  106186. }
  106187. }
  106188. for(i=0;i<vi->channels;i++)
  106189. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  106190. return(v->pcmret);
  106191. }
  106192. static void _preextrapolate_helper(vorbis_dsp_state *v){
  106193. int i;
  106194. int order=32;
  106195. float *lpc=(float*)alloca(order*sizeof(*lpc));
  106196. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  106197. long j;
  106198. v->preextrapolate=1;
  106199. if(v->pcm_current-v->centerW>order*2){ /* safety */
  106200. for(i=0;i<v->vi->channels;i++){
  106201. /* need to run the extrapolation in reverse! */
  106202. for(j=0;j<v->pcm_current;j++)
  106203. work[j]=v->pcm[i][v->pcm_current-j-1];
  106204. /* prime as above */
  106205. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  106206. /* run the predictor filter */
  106207. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  106208. order,
  106209. work+v->pcm_current-v->centerW,
  106210. v->centerW);
  106211. for(j=0;j<v->pcm_current;j++)
  106212. v->pcm[i][v->pcm_current-j-1]=work[j];
  106213. }
  106214. }
  106215. }
  106216. /* call with val<=0 to set eof */
  106217. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  106218. vorbis_info *vi=v->vi;
  106219. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106220. if(vals<=0){
  106221. int order=32;
  106222. int i;
  106223. float *lpc=(float*) alloca(order*sizeof(*lpc));
  106224. /* if it wasn't done earlier (very short sample) */
  106225. if(!v->preextrapolate)
  106226. _preextrapolate_helper(v);
  106227. /* We're encoding the end of the stream. Just make sure we have
  106228. [at least] a few full blocks of zeroes at the end. */
  106229. /* actually, we don't want zeroes; that could drop a large
  106230. amplitude off a cliff, creating spread spectrum noise that will
  106231. suck to encode. Extrapolate for the sake of cleanliness. */
  106232. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  106233. v->eofflag=v->pcm_current;
  106234. v->pcm_current+=ci->blocksizes[1]*3;
  106235. for(i=0;i<vi->channels;i++){
  106236. if(v->eofflag>order*2){
  106237. /* extrapolate with LPC to fill in */
  106238. long n;
  106239. /* make a predictor filter */
  106240. n=v->eofflag;
  106241. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  106242. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  106243. /* run the predictor filter */
  106244. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  106245. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  106246. }else{
  106247. /* not enough data to extrapolate (unlikely to happen due to
  106248. guarding the overlap, but bulletproof in case that
  106249. assumtion goes away). zeroes will do. */
  106250. memset(v->pcm[i]+v->eofflag,0,
  106251. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  106252. }
  106253. }
  106254. }else{
  106255. if(v->pcm_current+vals>v->pcm_storage)
  106256. return(OV_EINVAL);
  106257. v->pcm_current+=vals;
  106258. /* we may want to reverse extrapolate the beginning of a stream
  106259. too... in case we're beginning on a cliff! */
  106260. /* clumsy, but simple. It only runs once, so simple is good. */
  106261. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  106262. _preextrapolate_helper(v);
  106263. }
  106264. return(0);
  106265. }
  106266. /* do the deltas, envelope shaping, pre-echo and determine the size of
  106267. the next block on which to continue analysis */
  106268. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  106269. int i;
  106270. vorbis_info *vi=v->vi;
  106271. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106272. private_state *b=(private_state*)v->backend_state;
  106273. vorbis_look_psy_global *g=b->psy_g_look;
  106274. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  106275. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  106276. /* check to see if we're started... */
  106277. if(!v->preextrapolate)return(0);
  106278. /* check to see if we're done... */
  106279. if(v->eofflag==-1)return(0);
  106280. /* By our invariant, we have lW, W and centerW set. Search for
  106281. the next boundary so we can determine nW (the next window size)
  106282. which lets us compute the shape of the current block's window */
  106283. /* we do an envelope search even on a single blocksize; we may still
  106284. be throwing more bits at impulses, and envelope search handles
  106285. marking impulses too. */
  106286. {
  106287. long bp=_ve_envelope_search(v);
  106288. if(bp==-1){
  106289. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  106290. full long block */
  106291. v->nW=0;
  106292. }else{
  106293. if(ci->blocksizes[0]==ci->blocksizes[1])
  106294. v->nW=0;
  106295. else
  106296. v->nW=bp;
  106297. }
  106298. }
  106299. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  106300. {
  106301. /* center of next block + next block maximum right side. */
  106302. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  106303. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  106304. although this check is
  106305. less strict that the
  106306. _ve_envelope_search,
  106307. the search is not run
  106308. if we only use one
  106309. block size */
  106310. }
  106311. /* fill in the block. Note that for a short window, lW and nW are *short*
  106312. regardless of actual settings in the stream */
  106313. _vorbis_block_ripcord(vb);
  106314. vb->lW=v->lW;
  106315. vb->W=v->W;
  106316. vb->nW=v->nW;
  106317. if(v->W){
  106318. if(!v->lW || !v->nW){
  106319. vbi->blocktype=BLOCKTYPE_TRANSITION;
  106320. /*fprintf(stderr,"-");*/
  106321. }else{
  106322. vbi->blocktype=BLOCKTYPE_LONG;
  106323. /*fprintf(stderr,"_");*/
  106324. }
  106325. }else{
  106326. if(_ve_envelope_mark(v)){
  106327. vbi->blocktype=BLOCKTYPE_IMPULSE;
  106328. /*fprintf(stderr,"|");*/
  106329. }else{
  106330. vbi->blocktype=BLOCKTYPE_PADDING;
  106331. /*fprintf(stderr,".");*/
  106332. }
  106333. }
  106334. vb->vd=v;
  106335. vb->sequence=v->sequence++;
  106336. vb->granulepos=v->granulepos;
  106337. vb->pcmend=ci->blocksizes[v->W];
  106338. /* copy the vectors; this uses the local storage in vb */
  106339. /* this tracks 'strongest peak' for later psychoacoustics */
  106340. /* moved to the global psy state; clean this mess up */
  106341. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  106342. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  106343. vbi->ampmax=g->ampmax;
  106344. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  106345. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  106346. for(i=0;i<vi->channels;i++){
  106347. vbi->pcmdelay[i]=
  106348. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  106349. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  106350. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  106351. /* before we added the delay
  106352. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  106353. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  106354. */
  106355. }
  106356. /* handle eof detection: eof==0 means that we've not yet received EOF
  106357. eof>0 marks the last 'real' sample in pcm[]
  106358. eof<0 'no more to do'; doesn't get here */
  106359. if(v->eofflag){
  106360. if(v->centerW>=v->eofflag){
  106361. v->eofflag=-1;
  106362. vb->eofflag=1;
  106363. return(1);
  106364. }
  106365. }
  106366. /* advance storage vectors and clean up */
  106367. {
  106368. int new_centerNext=ci->blocksizes[1]/2;
  106369. int movementW=centerNext-new_centerNext;
  106370. if(movementW>0){
  106371. _ve_envelope_shift(b->ve,movementW);
  106372. v->pcm_current-=movementW;
  106373. for(i=0;i<vi->channels;i++)
  106374. memmove(v->pcm[i],v->pcm[i]+movementW,
  106375. v->pcm_current*sizeof(*v->pcm[i]));
  106376. v->lW=v->W;
  106377. v->W=v->nW;
  106378. v->centerW=new_centerNext;
  106379. if(v->eofflag){
  106380. v->eofflag-=movementW;
  106381. if(v->eofflag<=0)v->eofflag=-1;
  106382. /* do not add padding to end of stream! */
  106383. if(v->centerW>=v->eofflag){
  106384. v->granulepos+=movementW-(v->centerW-v->eofflag);
  106385. }else{
  106386. v->granulepos+=movementW;
  106387. }
  106388. }else{
  106389. v->granulepos+=movementW;
  106390. }
  106391. }
  106392. }
  106393. /* done */
  106394. return(1);
  106395. }
  106396. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  106397. vorbis_info *vi=v->vi;
  106398. codec_setup_info *ci;
  106399. int hs;
  106400. if(!v->backend_state)return -1;
  106401. if(!vi)return -1;
  106402. ci=(codec_setup_info*) vi->codec_setup;
  106403. if(!ci)return -1;
  106404. hs=ci->halfrate_flag;
  106405. v->centerW=ci->blocksizes[1]>>(hs+1);
  106406. v->pcm_current=v->centerW>>hs;
  106407. v->pcm_returned=-1;
  106408. v->granulepos=-1;
  106409. v->sequence=-1;
  106410. v->eofflag=0;
  106411. ((private_state *)(v->backend_state))->sample_count=-1;
  106412. return(0);
  106413. }
  106414. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  106415. if(_vds_shared_init(v,vi,0)) return 1;
  106416. vorbis_synthesis_restart(v);
  106417. return 0;
  106418. }
  106419. /* Unlike in analysis, the window is only partially applied for each
  106420. block. The time domain envelope is not yet handled at the point of
  106421. calling (as it relies on the previous block). */
  106422. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  106423. vorbis_info *vi=v->vi;
  106424. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106425. private_state *b=(private_state*)v->backend_state;
  106426. int hs=ci->halfrate_flag;
  106427. int i,j;
  106428. if(!vb)return(OV_EINVAL);
  106429. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  106430. v->lW=v->W;
  106431. v->W=vb->W;
  106432. v->nW=-1;
  106433. if((v->sequence==-1)||
  106434. (v->sequence+1 != vb->sequence)){
  106435. v->granulepos=-1; /* out of sequence; lose count */
  106436. b->sample_count=-1;
  106437. }
  106438. v->sequence=vb->sequence;
  106439. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  106440. was called on block */
  106441. int n=ci->blocksizes[v->W]>>(hs+1);
  106442. int n0=ci->blocksizes[0]>>(hs+1);
  106443. int n1=ci->blocksizes[1]>>(hs+1);
  106444. int thisCenter;
  106445. int prevCenter;
  106446. v->glue_bits+=vb->glue_bits;
  106447. v->time_bits+=vb->time_bits;
  106448. v->floor_bits+=vb->floor_bits;
  106449. v->res_bits+=vb->res_bits;
  106450. if(v->centerW){
  106451. thisCenter=n1;
  106452. prevCenter=0;
  106453. }else{
  106454. thisCenter=0;
  106455. prevCenter=n1;
  106456. }
  106457. /* v->pcm is now used like a two-stage double buffer. We don't want
  106458. to have to constantly shift *or* adjust memory usage. Don't
  106459. accept a new block until the old is shifted out */
  106460. for(j=0;j<vi->channels;j++){
  106461. /* the overlap/add section */
  106462. if(v->lW){
  106463. if(v->W){
  106464. /* large/large */
  106465. float *w=_vorbis_window_get(b->window[1]-hs);
  106466. float *pcm=v->pcm[j]+prevCenter;
  106467. float *p=vb->pcm[j];
  106468. for(i=0;i<n1;i++)
  106469. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  106470. }else{
  106471. /* large/small */
  106472. float *w=_vorbis_window_get(b->window[0]-hs);
  106473. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  106474. float *p=vb->pcm[j];
  106475. for(i=0;i<n0;i++)
  106476. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  106477. }
  106478. }else{
  106479. if(v->W){
  106480. /* small/large */
  106481. float *w=_vorbis_window_get(b->window[0]-hs);
  106482. float *pcm=v->pcm[j]+prevCenter;
  106483. float *p=vb->pcm[j]+n1/2-n0/2;
  106484. for(i=0;i<n0;i++)
  106485. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  106486. for(;i<n1/2+n0/2;i++)
  106487. pcm[i]=p[i];
  106488. }else{
  106489. /* small/small */
  106490. float *w=_vorbis_window_get(b->window[0]-hs);
  106491. float *pcm=v->pcm[j]+prevCenter;
  106492. float *p=vb->pcm[j];
  106493. for(i=0;i<n0;i++)
  106494. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  106495. }
  106496. }
  106497. /* the copy section */
  106498. {
  106499. float *pcm=v->pcm[j]+thisCenter;
  106500. float *p=vb->pcm[j]+n;
  106501. for(i=0;i<n;i++)
  106502. pcm[i]=p[i];
  106503. }
  106504. }
  106505. if(v->centerW)
  106506. v->centerW=0;
  106507. else
  106508. v->centerW=n1;
  106509. /* deal with initial packet state; we do this using the explicit
  106510. pcm_returned==-1 flag otherwise we're sensitive to first block
  106511. being short or long */
  106512. if(v->pcm_returned==-1){
  106513. v->pcm_returned=thisCenter;
  106514. v->pcm_current=thisCenter;
  106515. }else{
  106516. v->pcm_returned=prevCenter;
  106517. v->pcm_current=prevCenter+
  106518. ((ci->blocksizes[v->lW]/4+
  106519. ci->blocksizes[v->W]/4)>>hs);
  106520. }
  106521. }
  106522. /* track the frame number... This is for convenience, but also
  106523. making sure our last packet doesn't end with added padding. If
  106524. the last packet is partial, the number of samples we'll have to
  106525. return will be past the vb->granulepos.
  106526. This is not foolproof! It will be confused if we begin
  106527. decoding at the last page after a seek or hole. In that case,
  106528. we don't have a starting point to judge where the last frame
  106529. is. For this reason, vorbisfile will always try to make sure
  106530. it reads the last two marked pages in proper sequence */
  106531. if(b->sample_count==-1){
  106532. b->sample_count=0;
  106533. }else{
  106534. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  106535. }
  106536. if(v->granulepos==-1){
  106537. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  106538. v->granulepos=vb->granulepos;
  106539. /* is this a short page? */
  106540. if(b->sample_count>v->granulepos){
  106541. /* corner case; if this is both the first and last audio page,
  106542. then spec says the end is cut, not beginning */
  106543. if(vb->eofflag){
  106544. /* trim the end */
  106545. /* no preceeding granulepos; assume we started at zero (we'd
  106546. have to in a short single-page stream) */
  106547. /* granulepos could be -1 due to a seek, but that would result
  106548. in a long count, not short count */
  106549. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  106550. }else{
  106551. /* trim the beginning */
  106552. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  106553. if(v->pcm_returned>v->pcm_current)
  106554. v->pcm_returned=v->pcm_current;
  106555. }
  106556. }
  106557. }
  106558. }else{
  106559. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  106560. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  106561. if(v->granulepos>vb->granulepos){
  106562. long extra=v->granulepos-vb->granulepos;
  106563. if(extra)
  106564. if(vb->eofflag){
  106565. /* partial last frame. Strip the extra samples off */
  106566. v->pcm_current-=extra>>hs;
  106567. } /* else {Shouldn't happen *unless* the bitstream is out of
  106568. spec. Either way, believe the bitstream } */
  106569. } /* else {Shouldn't happen *unless* the bitstream is out of
  106570. spec. Either way, believe the bitstream } */
  106571. v->granulepos=vb->granulepos;
  106572. }
  106573. }
  106574. /* Update, cleanup */
  106575. if(vb->eofflag)v->eofflag=1;
  106576. return(0);
  106577. }
  106578. /* pcm==NULL indicates we just want the pending samples, no more */
  106579. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  106580. vorbis_info *vi=v->vi;
  106581. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  106582. if(pcm){
  106583. int i;
  106584. for(i=0;i<vi->channels;i++)
  106585. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  106586. *pcm=v->pcmret;
  106587. }
  106588. return(v->pcm_current-v->pcm_returned);
  106589. }
  106590. return(0);
  106591. }
  106592. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  106593. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  106594. v->pcm_returned+=n;
  106595. return(0);
  106596. }
  106597. /* intended for use with a specific vorbisfile feature; we want access
  106598. to the [usually synthetic/postextrapolated] buffer and lapping at
  106599. the end of a decode cycle, specifically, a half-short-block worth.
  106600. This funtion works like pcmout above, except it will also expose
  106601. this implicit buffer data not normally decoded. */
  106602. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  106603. vorbis_info *vi=v->vi;
  106604. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  106605. int hs=ci->halfrate_flag;
  106606. int n=ci->blocksizes[v->W]>>(hs+1);
  106607. int n0=ci->blocksizes[0]>>(hs+1);
  106608. int n1=ci->blocksizes[1]>>(hs+1);
  106609. int i,j;
  106610. if(v->pcm_returned<0)return 0;
  106611. /* our returned data ends at pcm_returned; because the synthesis pcm
  106612. buffer is a two-fragment ring, that means our data block may be
  106613. fragmented by buffering, wrapping or a short block not filling
  106614. out a buffer. To simplify things, we unfragment if it's at all
  106615. possibly needed. Otherwise, we'd need to call lapout more than
  106616. once as well as hold additional dsp state. Opt for
  106617. simplicity. */
  106618. /* centerW was advanced by blockin; it would be the center of the
  106619. *next* block */
  106620. if(v->centerW==n1){
  106621. /* the data buffer wraps; swap the halves */
  106622. /* slow, sure, small */
  106623. for(j=0;j<vi->channels;j++){
  106624. float *p=v->pcm[j];
  106625. for(i=0;i<n1;i++){
  106626. float temp=p[i];
  106627. p[i]=p[i+n1];
  106628. p[i+n1]=temp;
  106629. }
  106630. }
  106631. v->pcm_current-=n1;
  106632. v->pcm_returned-=n1;
  106633. v->centerW=0;
  106634. }
  106635. /* solidify buffer into contiguous space */
  106636. if((v->lW^v->W)==1){
  106637. /* long/short or short/long */
  106638. for(j=0;j<vi->channels;j++){
  106639. float *s=v->pcm[j];
  106640. float *d=v->pcm[j]+(n1-n0)/2;
  106641. for(i=(n1+n0)/2-1;i>=0;--i)
  106642. d[i]=s[i];
  106643. }
  106644. v->pcm_returned+=(n1-n0)/2;
  106645. v->pcm_current+=(n1-n0)/2;
  106646. }else{
  106647. if(v->lW==0){
  106648. /* short/short */
  106649. for(j=0;j<vi->channels;j++){
  106650. float *s=v->pcm[j];
  106651. float *d=v->pcm[j]+n1-n0;
  106652. for(i=n0-1;i>=0;--i)
  106653. d[i]=s[i];
  106654. }
  106655. v->pcm_returned+=n1-n0;
  106656. v->pcm_current+=n1-n0;
  106657. }
  106658. }
  106659. if(pcm){
  106660. int i;
  106661. for(i=0;i<vi->channels;i++)
  106662. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  106663. *pcm=v->pcmret;
  106664. }
  106665. return(n1+n-v->pcm_returned);
  106666. }
  106667. float *vorbis_window(vorbis_dsp_state *v,int W){
  106668. vorbis_info *vi=v->vi;
  106669. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  106670. int hs=ci->halfrate_flag;
  106671. private_state *b=(private_state*)v->backend_state;
  106672. if(b->window[W]-1<0)return NULL;
  106673. return _vorbis_window_get(b->window[W]-hs);
  106674. }
  106675. #endif
  106676. /********* End of inlined file: block.c *********/
  106677. /********* Start of inlined file: codebook.c *********/
  106678. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106679. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106680. // tasks..
  106681. #ifdef _MSC_VER
  106682. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106683. #endif
  106684. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106685. #if JUCE_USE_OGGVORBIS
  106686. #include <stdlib.h>
  106687. #include <string.h>
  106688. #include <math.h>
  106689. /* packs the given codebook into the bitstream **************************/
  106690. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  106691. long i,j;
  106692. int ordered=0;
  106693. /* first the basic parameters */
  106694. oggpack_write(opb,0x564342,24);
  106695. oggpack_write(opb,c->dim,16);
  106696. oggpack_write(opb,c->entries,24);
  106697. /* pack the codewords. There are two packings; length ordered and
  106698. length random. Decide between the two now. */
  106699. for(i=1;i<c->entries;i++)
  106700. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  106701. if(i==c->entries)ordered=1;
  106702. if(ordered){
  106703. /* length ordered. We only need to say how many codewords of
  106704. each length. The actual codewords are generated
  106705. deterministically */
  106706. long count=0;
  106707. oggpack_write(opb,1,1); /* ordered */
  106708. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  106709. for(i=1;i<c->entries;i++){
  106710. long thisx=c->lengthlist[i];
  106711. long last=c->lengthlist[i-1];
  106712. if(thisx>last){
  106713. for(j=last;j<thisx;j++){
  106714. oggpack_write(opb,i-count,_ilog(c->entries-count));
  106715. count=i;
  106716. }
  106717. }
  106718. }
  106719. oggpack_write(opb,i-count,_ilog(c->entries-count));
  106720. }else{
  106721. /* length random. Again, we don't code the codeword itself, just
  106722. the length. This time, though, we have to encode each length */
  106723. oggpack_write(opb,0,1); /* unordered */
  106724. /* algortihmic mapping has use for 'unused entries', which we tag
  106725. here. The algorithmic mapping happens as usual, but the unused
  106726. entry has no codeword. */
  106727. for(i=0;i<c->entries;i++)
  106728. if(c->lengthlist[i]==0)break;
  106729. if(i==c->entries){
  106730. oggpack_write(opb,0,1); /* no unused entries */
  106731. for(i=0;i<c->entries;i++)
  106732. oggpack_write(opb,c->lengthlist[i]-1,5);
  106733. }else{
  106734. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  106735. for(i=0;i<c->entries;i++){
  106736. if(c->lengthlist[i]==0){
  106737. oggpack_write(opb,0,1);
  106738. }else{
  106739. oggpack_write(opb,1,1);
  106740. oggpack_write(opb,c->lengthlist[i]-1,5);
  106741. }
  106742. }
  106743. }
  106744. }
  106745. /* is the entry number the desired return value, or do we have a
  106746. mapping? If we have a mapping, what type? */
  106747. oggpack_write(opb,c->maptype,4);
  106748. switch(c->maptype){
  106749. case 0:
  106750. /* no mapping */
  106751. break;
  106752. case 1:case 2:
  106753. /* implicitly populated value mapping */
  106754. /* explicitly populated value mapping */
  106755. if(!c->quantlist){
  106756. /* no quantlist? error */
  106757. return(-1);
  106758. }
  106759. /* values that define the dequantization */
  106760. oggpack_write(opb,c->q_min,32);
  106761. oggpack_write(opb,c->q_delta,32);
  106762. oggpack_write(opb,c->q_quant-1,4);
  106763. oggpack_write(opb,c->q_sequencep,1);
  106764. {
  106765. int quantvals;
  106766. switch(c->maptype){
  106767. case 1:
  106768. /* a single column of (c->entries/c->dim) quantized values for
  106769. building a full value list algorithmically (square lattice) */
  106770. quantvals=_book_maptype1_quantvals(c);
  106771. break;
  106772. case 2:
  106773. /* every value (c->entries*c->dim total) specified explicitly */
  106774. quantvals=c->entries*c->dim;
  106775. break;
  106776. default: /* NOT_REACHABLE */
  106777. quantvals=-1;
  106778. }
  106779. /* quantized values */
  106780. for(i=0;i<quantvals;i++)
  106781. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  106782. }
  106783. break;
  106784. default:
  106785. /* error case; we don't have any other map types now */
  106786. return(-1);
  106787. }
  106788. return(0);
  106789. }
  106790. /* unpacks a codebook from the packet buffer into the codebook struct,
  106791. readies the codebook auxiliary structures for decode *************/
  106792. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  106793. long i,j;
  106794. memset(s,0,sizeof(*s));
  106795. s->allocedp=1;
  106796. /* make sure alignment is correct */
  106797. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  106798. /* first the basic parameters */
  106799. s->dim=oggpack_read(opb,16);
  106800. s->entries=oggpack_read(opb,24);
  106801. if(s->entries==-1)goto _eofout;
  106802. /* codeword ordering.... length ordered or unordered? */
  106803. switch((int)oggpack_read(opb,1)){
  106804. case 0:
  106805. /* unordered */
  106806. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  106807. /* allocated but unused entries? */
  106808. if(oggpack_read(opb,1)){
  106809. /* yes, unused entries */
  106810. for(i=0;i<s->entries;i++){
  106811. if(oggpack_read(opb,1)){
  106812. long num=oggpack_read(opb,5);
  106813. if(num==-1)goto _eofout;
  106814. s->lengthlist[i]=num+1;
  106815. }else
  106816. s->lengthlist[i]=0;
  106817. }
  106818. }else{
  106819. /* all entries used; no tagging */
  106820. for(i=0;i<s->entries;i++){
  106821. long num=oggpack_read(opb,5);
  106822. if(num==-1)goto _eofout;
  106823. s->lengthlist[i]=num+1;
  106824. }
  106825. }
  106826. break;
  106827. case 1:
  106828. /* ordered */
  106829. {
  106830. long length=oggpack_read(opb,5)+1;
  106831. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  106832. for(i=0;i<s->entries;){
  106833. long num=oggpack_read(opb,_ilog(s->entries-i));
  106834. if(num==-1)goto _eofout;
  106835. for(j=0;j<num && i<s->entries;j++,i++)
  106836. s->lengthlist[i]=length;
  106837. length++;
  106838. }
  106839. }
  106840. break;
  106841. default:
  106842. /* EOF */
  106843. return(-1);
  106844. }
  106845. /* Do we have a mapping to unpack? */
  106846. switch((s->maptype=oggpack_read(opb,4))){
  106847. case 0:
  106848. /* no mapping */
  106849. break;
  106850. case 1: case 2:
  106851. /* implicitly populated value mapping */
  106852. /* explicitly populated value mapping */
  106853. s->q_min=oggpack_read(opb,32);
  106854. s->q_delta=oggpack_read(opb,32);
  106855. s->q_quant=oggpack_read(opb,4)+1;
  106856. s->q_sequencep=oggpack_read(opb,1);
  106857. {
  106858. int quantvals=0;
  106859. switch(s->maptype){
  106860. case 1:
  106861. quantvals=_book_maptype1_quantvals(s);
  106862. break;
  106863. case 2:
  106864. quantvals=s->entries*s->dim;
  106865. break;
  106866. }
  106867. /* quantized values */
  106868. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  106869. for(i=0;i<quantvals;i++)
  106870. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  106871. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  106872. }
  106873. break;
  106874. default:
  106875. goto _errout;
  106876. }
  106877. /* all set */
  106878. return(0);
  106879. _errout:
  106880. _eofout:
  106881. vorbis_staticbook_clear(s);
  106882. return(-1);
  106883. }
  106884. /* returns the number of bits ************************************************/
  106885. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  106886. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  106887. return(book->c->lengthlist[a]);
  106888. }
  106889. /* One the encode side, our vector writers are each designed for a
  106890. specific purpose, and the encoder is not flexible without modification:
  106891. The LSP vector coder uses a single stage nearest-match with no
  106892. interleave, so no step and no error return. This is specced by floor0
  106893. and doesn't change.
  106894. Residue0 encoding interleaves, uses multiple stages, and each stage
  106895. peels of a specific amount of resolution from a lattice (thus we want
  106896. to match by threshold, not nearest match). Residue doesn't *have* to
  106897. be encoded that way, but to change it, one will need to add more
  106898. infrastructure on the encode side (decode side is specced and simpler) */
  106899. /* floor0 LSP (single stage, non interleaved, nearest match) */
  106900. /* returns entry number and *modifies a* to the quantization value *****/
  106901. int vorbis_book_errorv(codebook *book,float *a){
  106902. int dim=book->dim,k;
  106903. int best=_best(book,a,1);
  106904. for(k=0;k<dim;k++)
  106905. a[k]=(book->valuelist+best*dim)[k];
  106906. return(best);
  106907. }
  106908. /* returns the number of bits and *modifies a* to the quantization value *****/
  106909. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  106910. int k,dim=book->dim;
  106911. for(k=0;k<dim;k++)
  106912. a[k]=(book->valuelist+best*dim)[k];
  106913. return(vorbis_book_encode(book,best,b));
  106914. }
  106915. /* the 'eliminate the decode tree' optimization actually requires the
  106916. codewords to be MSb first, not LSb. This is an annoying inelegancy
  106917. (and one of the first places where carefully thought out design
  106918. turned out to be wrong; Vorbis II and future Ogg codecs should go
  106919. to an MSb bitpacker), but not actually the huge hit it appears to
  106920. be. The first-stage decode table catches most words so that
  106921. bitreverse is not in the main execution path. */
  106922. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  106923. int read=book->dec_maxlength;
  106924. long lo,hi;
  106925. long lok = oggpack_look(b,book->dec_firsttablen);
  106926. if (lok >= 0) {
  106927. long entry = book->dec_firsttable[lok];
  106928. if(entry&0x80000000UL){
  106929. lo=(entry>>15)&0x7fff;
  106930. hi=book->used_entries-(entry&0x7fff);
  106931. }else{
  106932. oggpack_adv(b, book->dec_codelengths[entry-1]);
  106933. return(entry-1);
  106934. }
  106935. }else{
  106936. lo=0;
  106937. hi=book->used_entries;
  106938. }
  106939. lok = oggpack_look(b, read);
  106940. while(lok<0 && read>1)
  106941. lok = oggpack_look(b, --read);
  106942. if(lok<0)return -1;
  106943. /* bisect search for the codeword in the ordered list */
  106944. {
  106945. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  106946. while(hi-lo>1){
  106947. long p=(hi-lo)>>1;
  106948. long test=book->codelist[lo+p]>testword;
  106949. lo+=p&(test-1);
  106950. hi-=p&(-test);
  106951. }
  106952. if(book->dec_codelengths[lo]<=read){
  106953. oggpack_adv(b, book->dec_codelengths[lo]);
  106954. return(lo);
  106955. }
  106956. }
  106957. oggpack_adv(b, read);
  106958. return(-1);
  106959. }
  106960. /* Decode side is specced and easier, because we don't need to find
  106961. matches using different criteria; we simply read and map. There are
  106962. two things we need to do 'depending':
  106963. We may need to support interleave. We don't really, but it's
  106964. convenient to do it here rather than rebuild the vector later.
  106965. Cascades may be additive or multiplicitive; this is not inherent in
  106966. the codebook, but set in the code using the codebook. Like
  106967. interleaving, it's easiest to do it here.
  106968. addmul==0 -> declarative (set the value)
  106969. addmul==1 -> additive
  106970. addmul==2 -> multiplicitive */
  106971. /* returns the [original, not compacted] entry number or -1 on eof *********/
  106972. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  106973. long packed_entry=decode_packed_entry_number(book,b);
  106974. if(packed_entry>=0)
  106975. return(book->dec_index[packed_entry]);
  106976. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  106977. return(packed_entry);
  106978. }
  106979. /* returns 0 on OK or -1 on eof *************************************/
  106980. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  106981. int step=n/book->dim;
  106982. long *entry = (long*)alloca(sizeof(*entry)*step);
  106983. float **t = (float**)alloca(sizeof(*t)*step);
  106984. int i,j,o;
  106985. for (i = 0; i < step; i++) {
  106986. entry[i]=decode_packed_entry_number(book,b);
  106987. if(entry[i]==-1)return(-1);
  106988. t[i] = book->valuelist+entry[i]*book->dim;
  106989. }
  106990. for(i=0,o=0;i<book->dim;i++,o+=step)
  106991. for (j=0;j<step;j++)
  106992. a[o+j]+=t[j][i];
  106993. return(0);
  106994. }
  106995. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  106996. int i,j,entry;
  106997. float *t;
  106998. if(book->dim>8){
  106999. for(i=0;i<n;){
  107000. entry = decode_packed_entry_number(book,b);
  107001. if(entry==-1)return(-1);
  107002. t = book->valuelist+entry*book->dim;
  107003. for (j=0;j<book->dim;)
  107004. a[i++]+=t[j++];
  107005. }
  107006. }else{
  107007. for(i=0;i<n;){
  107008. entry = decode_packed_entry_number(book,b);
  107009. if(entry==-1)return(-1);
  107010. t = book->valuelist+entry*book->dim;
  107011. j=0;
  107012. switch((int)book->dim){
  107013. case 8:
  107014. a[i++]+=t[j++];
  107015. case 7:
  107016. a[i++]+=t[j++];
  107017. case 6:
  107018. a[i++]+=t[j++];
  107019. case 5:
  107020. a[i++]+=t[j++];
  107021. case 4:
  107022. a[i++]+=t[j++];
  107023. case 3:
  107024. a[i++]+=t[j++];
  107025. case 2:
  107026. a[i++]+=t[j++];
  107027. case 1:
  107028. a[i++]+=t[j++];
  107029. case 0:
  107030. break;
  107031. }
  107032. }
  107033. }
  107034. return(0);
  107035. }
  107036. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  107037. int i,j,entry;
  107038. float *t;
  107039. for(i=0;i<n;){
  107040. entry = decode_packed_entry_number(book,b);
  107041. if(entry==-1)return(-1);
  107042. t = book->valuelist+entry*book->dim;
  107043. for (j=0;j<book->dim;)
  107044. a[i++]=t[j++];
  107045. }
  107046. return(0);
  107047. }
  107048. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  107049. oggpack_buffer *b,int n){
  107050. long i,j,entry;
  107051. int chptr=0;
  107052. for(i=offset/ch;i<(offset+n)/ch;){
  107053. entry = decode_packed_entry_number(book,b);
  107054. if(entry==-1)return(-1);
  107055. {
  107056. const float *t = book->valuelist+entry*book->dim;
  107057. for (j=0;j<book->dim;j++){
  107058. a[chptr++][i]+=t[j];
  107059. if(chptr==ch){
  107060. chptr=0;
  107061. i++;
  107062. }
  107063. }
  107064. }
  107065. }
  107066. return(0);
  107067. }
  107068. #ifdef _V_SELFTEST
  107069. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  107070. number of vectors through (keeping track of the quantized values),
  107071. and decode using the unpacked book. quantized version of in should
  107072. exactly equal out */
  107073. #include <stdio.h>
  107074. #include "vorbis/book/lsp20_0.vqh"
  107075. #include "vorbis/book/res0a_13.vqh"
  107076. #define TESTSIZE 40
  107077. float test1[TESTSIZE]={
  107078. 0.105939f,
  107079. 0.215373f,
  107080. 0.429117f,
  107081. 0.587974f,
  107082. 0.181173f,
  107083. 0.296583f,
  107084. 0.515707f,
  107085. 0.715261f,
  107086. 0.162327f,
  107087. 0.263834f,
  107088. 0.342876f,
  107089. 0.406025f,
  107090. 0.103571f,
  107091. 0.223561f,
  107092. 0.368513f,
  107093. 0.540313f,
  107094. 0.136672f,
  107095. 0.395882f,
  107096. 0.587183f,
  107097. 0.652476f,
  107098. 0.114338f,
  107099. 0.417300f,
  107100. 0.525486f,
  107101. 0.698679f,
  107102. 0.147492f,
  107103. 0.324481f,
  107104. 0.643089f,
  107105. 0.757582f,
  107106. 0.139556f,
  107107. 0.215795f,
  107108. 0.324559f,
  107109. 0.399387f,
  107110. 0.120236f,
  107111. 0.267420f,
  107112. 0.446940f,
  107113. 0.608760f,
  107114. 0.115587f,
  107115. 0.287234f,
  107116. 0.571081f,
  107117. 0.708603f,
  107118. };
  107119. float test3[TESTSIZE]={
  107120. 0,1,-2,3,4,-5,6,7,8,9,
  107121. 8,-2,7,-1,4,6,8,3,1,-9,
  107122. 10,11,12,13,14,15,26,17,18,19,
  107123. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  107124. static_codebook *testlist[]={&_vq_book_lsp20_0,
  107125. &_vq_book_res0a_13,NULL};
  107126. float *testvec[]={test1,test3};
  107127. int main(){
  107128. oggpack_buffer write;
  107129. oggpack_buffer read;
  107130. long ptr=0,i;
  107131. oggpack_writeinit(&write);
  107132. fprintf(stderr,"Testing codebook abstraction...:\n");
  107133. while(testlist[ptr]){
  107134. codebook c;
  107135. static_codebook s;
  107136. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  107137. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  107138. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  107139. memset(iv,0,sizeof(*iv)*TESTSIZE);
  107140. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  107141. /* pack the codebook, write the testvector */
  107142. oggpack_reset(&write);
  107143. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  107144. we can write */
  107145. vorbis_staticbook_pack(testlist[ptr],&write);
  107146. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  107147. for(i=0;i<TESTSIZE;i+=c.dim){
  107148. int best=_best(&c,qv+i,1);
  107149. vorbis_book_encodev(&c,best,qv+i,&write);
  107150. }
  107151. vorbis_book_clear(&c);
  107152. fprintf(stderr,"OK.\n");
  107153. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  107154. /* transfer the write data to a read buffer and unpack/read */
  107155. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  107156. if(vorbis_staticbook_unpack(&read,&s)){
  107157. fprintf(stderr,"Error unpacking codebook.\n");
  107158. exit(1);
  107159. }
  107160. if(vorbis_book_init_decode(&c,&s)){
  107161. fprintf(stderr,"Error initializing codebook.\n");
  107162. exit(1);
  107163. }
  107164. for(i=0;i<TESTSIZE;i+=c.dim)
  107165. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  107166. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  107167. exit(1);
  107168. }
  107169. for(i=0;i<TESTSIZE;i++)
  107170. if(fabs(qv[i]-iv[i])>.000001){
  107171. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  107172. iv[i],qv[i],i);
  107173. exit(1);
  107174. }
  107175. fprintf(stderr,"OK\n");
  107176. ptr++;
  107177. }
  107178. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  107179. exit(0);
  107180. }
  107181. #endif
  107182. #endif
  107183. /********* End of inlined file: codebook.c *********/
  107184. /********* Start of inlined file: envelope.c *********/
  107185. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107186. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107187. // tasks..
  107188. #ifdef _MSC_VER
  107189. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107190. #endif
  107191. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107192. #if JUCE_USE_OGGVORBIS
  107193. #include <stdlib.h>
  107194. #include <string.h>
  107195. #include <stdio.h>
  107196. #include <math.h>
  107197. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  107198. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107199. vorbis_info_psy_global *gi=&ci->psy_g_param;
  107200. int ch=vi->channels;
  107201. int i,j;
  107202. int n=e->winlength=128;
  107203. e->searchstep=64; /* not random */
  107204. e->minenergy=gi->preecho_minenergy;
  107205. e->ch=ch;
  107206. e->storage=128;
  107207. e->cursor=ci->blocksizes[1]/2;
  107208. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  107209. mdct_init(&e->mdct,n);
  107210. for(i=0;i<n;i++){
  107211. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  107212. e->mdct_win[i]*=e->mdct_win[i];
  107213. }
  107214. /* magic follows */
  107215. e->band[0].begin=2; e->band[0].end=4;
  107216. e->band[1].begin=4; e->band[1].end=5;
  107217. e->band[2].begin=6; e->band[2].end=6;
  107218. e->band[3].begin=9; e->band[3].end=8;
  107219. e->band[4].begin=13; e->band[4].end=8;
  107220. e->band[5].begin=17; e->band[5].end=8;
  107221. e->band[6].begin=22; e->band[6].end=8;
  107222. for(j=0;j<VE_BANDS;j++){
  107223. n=e->band[j].end;
  107224. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  107225. for(i=0;i<n;i++){
  107226. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  107227. e->band[j].total+=e->band[j].window[i];
  107228. }
  107229. e->band[j].total=1./e->band[j].total;
  107230. }
  107231. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  107232. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  107233. }
  107234. void _ve_envelope_clear(envelope_lookup *e){
  107235. int i;
  107236. mdct_clear(&e->mdct);
  107237. for(i=0;i<VE_BANDS;i++)
  107238. _ogg_free(e->band[i].window);
  107239. _ogg_free(e->mdct_win);
  107240. _ogg_free(e->filter);
  107241. _ogg_free(e->mark);
  107242. memset(e,0,sizeof(*e));
  107243. }
  107244. /* fairly straight threshhold-by-band based until we find something
  107245. that works better and isn't patented. */
  107246. static int _ve_amp(envelope_lookup *ve,
  107247. vorbis_info_psy_global *gi,
  107248. float *data,
  107249. envelope_band *bands,
  107250. envelope_filter_state *filters,
  107251. long pos){
  107252. long n=ve->winlength;
  107253. int ret=0;
  107254. long i,j;
  107255. float decay;
  107256. /* we want to have a 'minimum bar' for energy, else we're just
  107257. basing blocks on quantization noise that outweighs the signal
  107258. itself (for low power signals) */
  107259. float minV=ve->minenergy;
  107260. float *vec=(float*) alloca(n*sizeof(*vec));
  107261. /* stretch is used to gradually lengthen the number of windows
  107262. considered prevoius-to-potential-trigger */
  107263. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  107264. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  107265. if(penalty<0.f)penalty=0.f;
  107266. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  107267. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  107268. totalshift+pos*ve->searchstep);*/
  107269. /* window and transform */
  107270. for(i=0;i<n;i++)
  107271. vec[i]=data[i]*ve->mdct_win[i];
  107272. mdct_forward(&ve->mdct,vec,vec);
  107273. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  107274. /* near-DC spreading function; this has nothing to do with
  107275. psychoacoustics, just sidelobe leakage and window size */
  107276. {
  107277. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  107278. int ptr=filters->nearptr;
  107279. /* the accumulation is regularly refreshed from scratch to avoid
  107280. floating point creep */
  107281. if(ptr==0){
  107282. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  107283. filters->nearDC_partialacc=temp;
  107284. }else{
  107285. decay=filters->nearDC_acc+=temp;
  107286. filters->nearDC_partialacc+=temp;
  107287. }
  107288. filters->nearDC_acc-=filters->nearDC[ptr];
  107289. filters->nearDC[ptr]=temp;
  107290. decay*=(1./(VE_NEARDC+1));
  107291. filters->nearptr++;
  107292. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  107293. decay=todB(&decay)*.5-15.f;
  107294. }
  107295. /* perform spreading and limiting, also smooth the spectrum. yes,
  107296. the MDCT results in all real coefficients, but it still *behaves*
  107297. like real/imaginary pairs */
  107298. for(i=0;i<n/2;i+=2){
  107299. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  107300. val=todB(&val)*.5f;
  107301. if(val<decay)val=decay;
  107302. if(val<minV)val=minV;
  107303. vec[i>>1]=val;
  107304. decay-=8.;
  107305. }
  107306. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  107307. /* perform preecho/postecho triggering by band */
  107308. for(j=0;j<VE_BANDS;j++){
  107309. float acc=0.;
  107310. float valmax,valmin;
  107311. /* accumulate amplitude */
  107312. for(i=0;i<bands[j].end;i++)
  107313. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  107314. acc*=bands[j].total;
  107315. /* convert amplitude to delta */
  107316. {
  107317. int p,thisx=filters[j].ampptr;
  107318. float postmax,postmin,premax=-99999.f,premin=99999.f;
  107319. p=thisx;
  107320. p--;
  107321. if(p<0)p+=VE_AMP;
  107322. postmax=max(acc,filters[j].ampbuf[p]);
  107323. postmin=min(acc,filters[j].ampbuf[p]);
  107324. for(i=0;i<stretch;i++){
  107325. p--;
  107326. if(p<0)p+=VE_AMP;
  107327. premax=max(premax,filters[j].ampbuf[p]);
  107328. premin=min(premin,filters[j].ampbuf[p]);
  107329. }
  107330. valmin=postmin-premin;
  107331. valmax=postmax-premax;
  107332. /*filters[j].markers[pos]=valmax;*/
  107333. filters[j].ampbuf[thisx]=acc;
  107334. filters[j].ampptr++;
  107335. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  107336. }
  107337. /* look at min/max, decide trigger */
  107338. if(valmax>gi->preecho_thresh[j]+penalty){
  107339. ret|=1;
  107340. ret|=4;
  107341. }
  107342. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  107343. }
  107344. return(ret);
  107345. }
  107346. #if 0
  107347. static int seq=0;
  107348. static ogg_int64_t totalshift=-1024;
  107349. #endif
  107350. long _ve_envelope_search(vorbis_dsp_state *v){
  107351. vorbis_info *vi=v->vi;
  107352. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  107353. vorbis_info_psy_global *gi=&ci->psy_g_param;
  107354. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  107355. long i,j;
  107356. int first=ve->current/ve->searchstep;
  107357. int last=v->pcm_current/ve->searchstep-VE_WIN;
  107358. if(first<0)first=0;
  107359. /* make sure we have enough storage to match the PCM */
  107360. if(last+VE_WIN+VE_POST>ve->storage){
  107361. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  107362. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  107363. }
  107364. for(j=first;j<last;j++){
  107365. int ret=0;
  107366. ve->stretch++;
  107367. if(ve->stretch>VE_MAXSTRETCH*2)
  107368. ve->stretch=VE_MAXSTRETCH*2;
  107369. for(i=0;i<ve->ch;i++){
  107370. float *pcm=v->pcm[i]+ve->searchstep*(j);
  107371. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  107372. }
  107373. ve->mark[j+VE_POST]=0;
  107374. if(ret&1){
  107375. ve->mark[j]=1;
  107376. ve->mark[j+1]=1;
  107377. }
  107378. if(ret&2){
  107379. ve->mark[j]=1;
  107380. if(j>0)ve->mark[j-1]=1;
  107381. }
  107382. if(ret&4)ve->stretch=-1;
  107383. }
  107384. ve->current=last*ve->searchstep;
  107385. {
  107386. long centerW=v->centerW;
  107387. long testW=
  107388. centerW+
  107389. ci->blocksizes[v->W]/4+
  107390. ci->blocksizes[1]/2+
  107391. ci->blocksizes[0]/4;
  107392. j=ve->cursor;
  107393. while(j<ve->current-(ve->searchstep)){/* account for postecho
  107394. working back one window */
  107395. if(j>=testW)return(1);
  107396. ve->cursor=j;
  107397. if(ve->mark[j/ve->searchstep]){
  107398. if(j>centerW){
  107399. #if 0
  107400. if(j>ve->curmark){
  107401. float *marker=alloca(v->pcm_current*sizeof(*marker));
  107402. int l,m;
  107403. memset(marker,0,sizeof(*marker)*v->pcm_current);
  107404. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  107405. seq,
  107406. (totalshift+ve->cursor)/44100.,
  107407. (totalshift+j)/44100.);
  107408. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  107409. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  107410. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  107411. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  107412. for(m=0;m<VE_BANDS;m++){
  107413. char buf[80];
  107414. sprintf(buf,"delL%d",m);
  107415. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  107416. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  107417. }
  107418. for(m=0;m<VE_BANDS;m++){
  107419. char buf[80];
  107420. sprintf(buf,"delR%d",m);
  107421. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  107422. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  107423. }
  107424. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  107425. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  107426. seq++;
  107427. }
  107428. #endif
  107429. ve->curmark=j;
  107430. if(j>=testW)return(1);
  107431. return(0);
  107432. }
  107433. }
  107434. j+=ve->searchstep;
  107435. }
  107436. }
  107437. return(-1);
  107438. }
  107439. int _ve_envelope_mark(vorbis_dsp_state *v){
  107440. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  107441. vorbis_info *vi=v->vi;
  107442. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107443. long centerW=v->centerW;
  107444. long beginW=centerW-ci->blocksizes[v->W]/4;
  107445. long endW=centerW+ci->blocksizes[v->W]/4;
  107446. if(v->W){
  107447. beginW-=ci->blocksizes[v->lW]/4;
  107448. endW+=ci->blocksizes[v->nW]/4;
  107449. }else{
  107450. beginW-=ci->blocksizes[0]/4;
  107451. endW+=ci->blocksizes[0]/4;
  107452. }
  107453. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  107454. {
  107455. long first=beginW/ve->searchstep;
  107456. long last=endW/ve->searchstep;
  107457. long i;
  107458. for(i=first;i<last;i++)
  107459. if(ve->mark[i])return(1);
  107460. }
  107461. return(0);
  107462. }
  107463. void _ve_envelope_shift(envelope_lookup *e,long shift){
  107464. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  107465. ahead of ve->current */
  107466. int smallshift=shift/e->searchstep;
  107467. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  107468. #if 0
  107469. for(i=0;i<VE_BANDS*e->ch;i++)
  107470. memmove(e->filter[i].markers,
  107471. e->filter[i].markers+smallshift,
  107472. (1024-smallshift)*sizeof(*(*e->filter).markers));
  107473. totalshift+=shift;
  107474. #endif
  107475. e->current-=shift;
  107476. if(e->curmark>=0)
  107477. e->curmark-=shift;
  107478. e->cursor-=shift;
  107479. }
  107480. #endif
  107481. /********* End of inlined file: envelope.c *********/
  107482. /********* Start of inlined file: floor0.c *********/
  107483. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107484. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107485. // tasks..
  107486. #ifdef _MSC_VER
  107487. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107488. #endif
  107489. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107490. #if JUCE_USE_OGGVORBIS
  107491. #include <stdlib.h>
  107492. #include <string.h>
  107493. #include <math.h>
  107494. /********* Start of inlined file: lsp.h *********/
  107495. #ifndef _V_LSP_H_
  107496. #define _V_LSP_H_
  107497. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  107498. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  107499. float *lsp,int m,
  107500. float amp,float ampoffset);
  107501. #endif
  107502. /********* End of inlined file: lsp.h *********/
  107503. #include <stdio.h>
  107504. typedef struct {
  107505. int ln;
  107506. int m;
  107507. int **linearmap;
  107508. int n[2];
  107509. vorbis_info_floor0 *vi;
  107510. long bits;
  107511. long frames;
  107512. } vorbis_look_floor0;
  107513. /***********************************************/
  107514. static void floor0_free_info(vorbis_info_floor *i){
  107515. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  107516. if(info){
  107517. memset(info,0,sizeof(*info));
  107518. _ogg_free(info);
  107519. }
  107520. }
  107521. static void floor0_free_look(vorbis_look_floor *i){
  107522. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  107523. if(look){
  107524. if(look->linearmap){
  107525. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  107526. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  107527. _ogg_free(look->linearmap);
  107528. }
  107529. memset(look,0,sizeof(*look));
  107530. _ogg_free(look);
  107531. }
  107532. }
  107533. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  107534. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107535. int j;
  107536. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  107537. info->order=oggpack_read(opb,8);
  107538. info->rate=oggpack_read(opb,16);
  107539. info->barkmap=oggpack_read(opb,16);
  107540. info->ampbits=oggpack_read(opb,6);
  107541. info->ampdB=oggpack_read(opb,8);
  107542. info->numbooks=oggpack_read(opb,4)+1;
  107543. if(info->order<1)goto err_out;
  107544. if(info->rate<1)goto err_out;
  107545. if(info->barkmap<1)goto err_out;
  107546. if(info->numbooks<1)goto err_out;
  107547. for(j=0;j<info->numbooks;j++){
  107548. info->books[j]=oggpack_read(opb,8);
  107549. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  107550. }
  107551. return(info);
  107552. err_out:
  107553. floor0_free_info(info);
  107554. return(NULL);
  107555. }
  107556. /* initialize Bark scale and normalization lookups. We could do this
  107557. with static tables, but Vorbis allows a number of possible
  107558. combinations, so it's best to do it computationally.
  107559. The below is authoritative in terms of defining scale mapping.
  107560. Note that the scale depends on the sampling rate as well as the
  107561. linear block and mapping sizes */
  107562. static void floor0_map_lazy_init(vorbis_block *vb,
  107563. vorbis_info_floor *infoX,
  107564. vorbis_look_floor0 *look){
  107565. if(!look->linearmap[vb->W]){
  107566. vorbis_dsp_state *vd=vb->vd;
  107567. vorbis_info *vi=vd->vi;
  107568. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107569. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  107570. int W=vb->W;
  107571. int n=ci->blocksizes[W]/2,j;
  107572. /* we choose a scaling constant so that:
  107573. floor(bark(rate/2-1)*C)=mapped-1
  107574. floor(bark(rate/2)*C)=mapped */
  107575. float scale=look->ln/toBARK(info->rate/2.f);
  107576. /* the mapping from a linear scale to a smaller bark scale is
  107577. straightforward. We do *not* make sure that the linear mapping
  107578. does not skip bark-scale bins; the decoder simply skips them and
  107579. the encoder may do what it wishes in filling them. They're
  107580. necessary in some mapping combinations to keep the scale spacing
  107581. accurate */
  107582. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  107583. for(j=0;j<n;j++){
  107584. int val=floor( toBARK((info->rate/2.f)/n*j)
  107585. *scale); /* bark numbers represent band edges */
  107586. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  107587. look->linearmap[W][j]=val;
  107588. }
  107589. look->linearmap[W][j]=-1;
  107590. look->n[W]=n;
  107591. }
  107592. }
  107593. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  107594. vorbis_info_floor *i){
  107595. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  107596. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  107597. look->m=info->order;
  107598. look->ln=info->barkmap;
  107599. look->vi=info;
  107600. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  107601. return look;
  107602. }
  107603. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  107604. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  107605. vorbis_info_floor0 *info=look->vi;
  107606. int j,k;
  107607. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  107608. if(ampraw>0){ /* also handles the -1 out of data case */
  107609. long maxval=(1<<info->ampbits)-1;
  107610. float amp=(float)ampraw/maxval*info->ampdB;
  107611. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  107612. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  107613. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  107614. codebook *b=ci->fullbooks+info->books[booknum];
  107615. float last=0.f;
  107616. /* the additional b->dim is a guard against any possible stack
  107617. smash; b->dim is provably more than we can overflow the
  107618. vector */
  107619. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  107620. for(j=0;j<look->m;j+=b->dim)
  107621. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  107622. for(j=0;j<look->m;){
  107623. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  107624. last=lsp[j-1];
  107625. }
  107626. lsp[look->m]=amp;
  107627. return(lsp);
  107628. }
  107629. }
  107630. eop:
  107631. return(NULL);
  107632. }
  107633. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  107634. void *memo,float *out){
  107635. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  107636. vorbis_info_floor0 *info=look->vi;
  107637. floor0_map_lazy_init(vb,info,look);
  107638. if(memo){
  107639. float *lsp=(float *)memo;
  107640. float amp=lsp[look->m];
  107641. /* take the coefficients back to a spectral envelope curve */
  107642. vorbis_lsp_to_curve(out,
  107643. look->linearmap[vb->W],
  107644. look->n[vb->W],
  107645. look->ln,
  107646. lsp,look->m,amp,(float)info->ampdB);
  107647. return(1);
  107648. }
  107649. memset(out,0,sizeof(*out)*look->n[vb->W]);
  107650. return(0);
  107651. }
  107652. /* export hooks */
  107653. vorbis_func_floor floor0_exportbundle={
  107654. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  107655. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  107656. };
  107657. #endif
  107658. /********* End of inlined file: floor0.c *********/
  107659. /********* Start of inlined file: floor1.c *********/
  107660. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107661. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107662. // tasks..
  107663. #ifdef _MSC_VER
  107664. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107665. #endif
  107666. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107667. #if JUCE_USE_OGGVORBIS
  107668. #include <stdlib.h>
  107669. #include <string.h>
  107670. #include <math.h>
  107671. #include <stdio.h>
  107672. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  107673. typedef struct {
  107674. int sorted_index[VIF_POSIT+2];
  107675. int forward_index[VIF_POSIT+2];
  107676. int reverse_index[VIF_POSIT+2];
  107677. int hineighbor[VIF_POSIT];
  107678. int loneighbor[VIF_POSIT];
  107679. int posts;
  107680. int n;
  107681. int quant_q;
  107682. vorbis_info_floor1 *vi;
  107683. long phrasebits;
  107684. long postbits;
  107685. long frames;
  107686. } vorbis_look_floor1;
  107687. typedef struct lsfit_acc{
  107688. long x0;
  107689. long x1;
  107690. long xa;
  107691. long ya;
  107692. long x2a;
  107693. long y2a;
  107694. long xya;
  107695. long an;
  107696. } lsfit_acc;
  107697. /***********************************************/
  107698. static void floor1_free_info(vorbis_info_floor *i){
  107699. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  107700. if(info){
  107701. memset(info,0,sizeof(*info));
  107702. _ogg_free(info);
  107703. }
  107704. }
  107705. static void floor1_free_look(vorbis_look_floor *i){
  107706. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  107707. if(look){
  107708. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  107709. (float)look->phrasebits/look->frames,
  107710. (float)look->postbits/look->frames,
  107711. (float)(look->postbits+look->phrasebits)/look->frames);*/
  107712. memset(look,0,sizeof(*look));
  107713. _ogg_free(look);
  107714. }
  107715. }
  107716. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  107717. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  107718. int j,k;
  107719. int count=0;
  107720. int rangebits;
  107721. int maxposit=info->postlist[1];
  107722. int maxclass=-1;
  107723. /* save out partitions */
  107724. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  107725. for(j=0;j<info->partitions;j++){
  107726. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  107727. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  107728. }
  107729. /* save out partition classes */
  107730. for(j=0;j<maxclass+1;j++){
  107731. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  107732. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  107733. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  107734. for(k=0;k<(1<<info->class_subs[j]);k++)
  107735. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  107736. }
  107737. /* save out the post list */
  107738. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  107739. oggpack_write(opb,ilog2(maxposit),4);
  107740. rangebits=ilog2(maxposit);
  107741. for(j=0,k=0;j<info->partitions;j++){
  107742. count+=info->class_dim[info->partitionclass[j]];
  107743. for(;k<count;k++)
  107744. oggpack_write(opb,info->postlist[k+2],rangebits);
  107745. }
  107746. }
  107747. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  107748. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107749. int j,k,count=0,maxclass=-1,rangebits;
  107750. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  107751. /* read partitions */
  107752. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  107753. for(j=0;j<info->partitions;j++){
  107754. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  107755. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  107756. }
  107757. /* read partition classes */
  107758. for(j=0;j<maxclass+1;j++){
  107759. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  107760. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  107761. if(info->class_subs[j]<0)
  107762. goto err_out;
  107763. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  107764. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  107765. goto err_out;
  107766. for(k=0;k<(1<<info->class_subs[j]);k++){
  107767. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  107768. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  107769. goto err_out;
  107770. }
  107771. }
  107772. /* read the post list */
  107773. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  107774. rangebits=oggpack_read(opb,4);
  107775. for(j=0,k=0;j<info->partitions;j++){
  107776. count+=info->class_dim[info->partitionclass[j]];
  107777. for(;k<count;k++){
  107778. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  107779. if(t<0 || t>=(1<<rangebits))
  107780. goto err_out;
  107781. }
  107782. }
  107783. info->postlist[0]=0;
  107784. info->postlist[1]=1<<rangebits;
  107785. return(info);
  107786. err_out:
  107787. floor1_free_info(info);
  107788. return(NULL);
  107789. }
  107790. static int icomp(const void *a,const void *b){
  107791. return(**(int **)a-**(int **)b);
  107792. }
  107793. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  107794. vorbis_info_floor *in){
  107795. int *sortpointer[VIF_POSIT+2];
  107796. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  107797. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  107798. int i,j,n=0;
  107799. look->vi=info;
  107800. look->n=info->postlist[1];
  107801. /* we drop each position value in-between already decoded values,
  107802. and use linear interpolation to predict each new value past the
  107803. edges. The positions are read in the order of the position
  107804. list... we precompute the bounding positions in the lookup. Of
  107805. course, the neighbors can change (if a position is declined), but
  107806. this is an initial mapping */
  107807. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  107808. n+=2;
  107809. look->posts=n;
  107810. /* also store a sorted position index */
  107811. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  107812. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  107813. /* points from sort order back to range number */
  107814. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  107815. /* points from range order to sorted position */
  107816. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  107817. /* we actually need the post values too */
  107818. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  107819. /* quantize values to multiplier spec */
  107820. switch(info->mult){
  107821. case 1: /* 1024 -> 256 */
  107822. look->quant_q=256;
  107823. break;
  107824. case 2: /* 1024 -> 128 */
  107825. look->quant_q=128;
  107826. break;
  107827. case 3: /* 1024 -> 86 */
  107828. look->quant_q=86;
  107829. break;
  107830. case 4: /* 1024 -> 64 */
  107831. look->quant_q=64;
  107832. break;
  107833. }
  107834. /* discover our neighbors for decode where we don't use fit flags
  107835. (that would push the neighbors outward) */
  107836. for(i=0;i<n-2;i++){
  107837. int lo=0;
  107838. int hi=1;
  107839. int lx=0;
  107840. int hx=look->n;
  107841. int currentx=info->postlist[i+2];
  107842. for(j=0;j<i+2;j++){
  107843. int x=info->postlist[j];
  107844. if(x>lx && x<currentx){
  107845. lo=j;
  107846. lx=x;
  107847. }
  107848. if(x<hx && x>currentx){
  107849. hi=j;
  107850. hx=x;
  107851. }
  107852. }
  107853. look->loneighbor[i]=lo;
  107854. look->hineighbor[i]=hi;
  107855. }
  107856. return(look);
  107857. }
  107858. static int render_point(int x0,int x1,int y0,int y1,int x){
  107859. y0&=0x7fff; /* mask off flag */
  107860. y1&=0x7fff;
  107861. {
  107862. int dy=y1-y0;
  107863. int adx=x1-x0;
  107864. int ady=abs(dy);
  107865. int err=ady*(x-x0);
  107866. int off=err/adx;
  107867. if(dy<0)return(y0-off);
  107868. return(y0+off);
  107869. }
  107870. }
  107871. static int vorbis_dBquant(const float *x){
  107872. int i= *x*7.3142857f+1023.5f;
  107873. if(i>1023)return(1023);
  107874. if(i<0)return(0);
  107875. return i;
  107876. }
  107877. static float FLOOR1_fromdB_LOOKUP[256]={
  107878. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  107879. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  107880. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  107881. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  107882. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  107883. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  107884. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  107885. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  107886. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  107887. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  107888. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  107889. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  107890. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  107891. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  107892. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  107893. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  107894. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  107895. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  107896. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  107897. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  107898. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  107899. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  107900. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  107901. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  107902. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  107903. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  107904. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  107905. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  107906. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  107907. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  107908. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  107909. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  107910. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  107911. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  107912. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  107913. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  107914. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  107915. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  107916. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  107917. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  107918. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  107919. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  107920. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  107921. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  107922. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  107923. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  107924. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  107925. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  107926. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  107927. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  107928. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  107929. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  107930. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  107931. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  107932. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  107933. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  107934. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  107935. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  107936. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  107937. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  107938. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  107939. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  107940. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  107941. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  107942. };
  107943. static void render_line(int x0,int x1,int y0,int y1,float *d){
  107944. int dy=y1-y0;
  107945. int adx=x1-x0;
  107946. int ady=abs(dy);
  107947. int base=dy/adx;
  107948. int sy=(dy<0?base-1:base+1);
  107949. int x=x0;
  107950. int y=y0;
  107951. int err=0;
  107952. ady-=abs(base*adx);
  107953. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  107954. while(++x<x1){
  107955. err=err+ady;
  107956. if(err>=adx){
  107957. err-=adx;
  107958. y+=sy;
  107959. }else{
  107960. y+=base;
  107961. }
  107962. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  107963. }
  107964. }
  107965. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  107966. int dy=y1-y0;
  107967. int adx=x1-x0;
  107968. int ady=abs(dy);
  107969. int base=dy/adx;
  107970. int sy=(dy<0?base-1:base+1);
  107971. int x=x0;
  107972. int y=y0;
  107973. int err=0;
  107974. ady-=abs(base*adx);
  107975. d[x]=y;
  107976. while(++x<x1){
  107977. err=err+ady;
  107978. if(err>=adx){
  107979. err-=adx;
  107980. y+=sy;
  107981. }else{
  107982. y+=base;
  107983. }
  107984. d[x]=y;
  107985. }
  107986. }
  107987. /* the floor has already been filtered to only include relevant sections */
  107988. static int accumulate_fit(const float *flr,const float *mdct,
  107989. int x0, int x1,lsfit_acc *a,
  107990. int n,vorbis_info_floor1 *info){
  107991. long i;
  107992. 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;
  107993. memset(a,0,sizeof(*a));
  107994. a->x0=x0;
  107995. a->x1=x1;
  107996. if(x1>=n)x1=n-1;
  107997. for(i=x0;i<=x1;i++){
  107998. int quantized=vorbis_dBquant(flr+i);
  107999. if(quantized){
  108000. if(mdct[i]+info->twofitatten>=flr[i]){
  108001. xa += i;
  108002. ya += quantized;
  108003. x2a += i*i;
  108004. y2a += quantized*quantized;
  108005. xya += i*quantized;
  108006. na++;
  108007. }else{
  108008. xb += i;
  108009. yb += quantized;
  108010. x2b += i*i;
  108011. y2b += quantized*quantized;
  108012. xyb += i*quantized;
  108013. nb++;
  108014. }
  108015. }
  108016. }
  108017. xb+=xa;
  108018. yb+=ya;
  108019. x2b+=x2a;
  108020. y2b+=y2a;
  108021. xyb+=xya;
  108022. nb+=na;
  108023. /* weight toward the actually used frequencies if we meet the threshhold */
  108024. {
  108025. int weight=nb*info->twofitweight/(na+1);
  108026. a->xa=xa*weight+xb;
  108027. a->ya=ya*weight+yb;
  108028. a->x2a=x2a*weight+x2b;
  108029. a->y2a=y2a*weight+y2b;
  108030. a->xya=xya*weight+xyb;
  108031. a->an=na*weight+nb;
  108032. }
  108033. return(na);
  108034. }
  108035. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  108036. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  108037. long x0=a[0].x0;
  108038. long x1=a[fits-1].x1;
  108039. for(i=0;i<fits;i++){
  108040. x+=a[i].xa;
  108041. y+=a[i].ya;
  108042. x2+=a[i].x2a;
  108043. y2+=a[i].y2a;
  108044. xy+=a[i].xya;
  108045. an+=a[i].an;
  108046. }
  108047. if(*y0>=0){
  108048. x+= x0;
  108049. y+= *y0;
  108050. x2+= x0 * x0;
  108051. y2+= *y0 * *y0;
  108052. xy+= *y0 * x0;
  108053. an++;
  108054. }
  108055. if(*y1>=0){
  108056. x+= x1;
  108057. y+= *y1;
  108058. x2+= x1 * x1;
  108059. y2+= *y1 * *y1;
  108060. xy+= *y1 * x1;
  108061. an++;
  108062. }
  108063. if(an){
  108064. /* need 64 bit multiplies, which C doesn't give portably as int */
  108065. double fx=x;
  108066. double fy=y;
  108067. double fx2=x2;
  108068. double fxy=xy;
  108069. double denom=1./(an*fx2-fx*fx);
  108070. double a=(fy*fx2-fxy*fx)*denom;
  108071. double b=(an*fxy-fx*fy)*denom;
  108072. *y0=rint(a+b*x0);
  108073. *y1=rint(a+b*x1);
  108074. /* limit to our range! */
  108075. if(*y0>1023)*y0=1023;
  108076. if(*y1>1023)*y1=1023;
  108077. if(*y0<0)*y0=0;
  108078. if(*y1<0)*y1=0;
  108079. }else{
  108080. *y0=0;
  108081. *y1=0;
  108082. }
  108083. }
  108084. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  108085. long y=0;
  108086. int i;
  108087. for(i=0;i<fits && y==0;i++)
  108088. y+=a[i].ya;
  108089. *y0=*y1=y;
  108090. }*/
  108091. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  108092. const float *mdct,
  108093. vorbis_info_floor1 *info){
  108094. int dy=y1-y0;
  108095. int adx=x1-x0;
  108096. int ady=abs(dy);
  108097. int base=dy/adx;
  108098. int sy=(dy<0?base-1:base+1);
  108099. int x=x0;
  108100. int y=y0;
  108101. int err=0;
  108102. int val=vorbis_dBquant(mask+x);
  108103. int mse=0;
  108104. int n=0;
  108105. ady-=abs(base*adx);
  108106. mse=(y-val);
  108107. mse*=mse;
  108108. n++;
  108109. if(mdct[x]+info->twofitatten>=mask[x]){
  108110. if(y+info->maxover<val)return(1);
  108111. if(y-info->maxunder>val)return(1);
  108112. }
  108113. while(++x<x1){
  108114. err=err+ady;
  108115. if(err>=adx){
  108116. err-=adx;
  108117. y+=sy;
  108118. }else{
  108119. y+=base;
  108120. }
  108121. val=vorbis_dBquant(mask+x);
  108122. mse+=((y-val)*(y-val));
  108123. n++;
  108124. if(mdct[x]+info->twofitatten>=mask[x]){
  108125. if(val){
  108126. if(y+info->maxover<val)return(1);
  108127. if(y-info->maxunder>val)return(1);
  108128. }
  108129. }
  108130. }
  108131. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  108132. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  108133. if(mse/n>info->maxerr)return(1);
  108134. return(0);
  108135. }
  108136. static int post_Y(int *A,int *B,int pos){
  108137. if(A[pos]<0)
  108138. return B[pos];
  108139. if(B[pos]<0)
  108140. return A[pos];
  108141. return (A[pos]+B[pos])>>1;
  108142. }
  108143. int *floor1_fit(vorbis_block *vb,void *look_,
  108144. const float *logmdct, /* in */
  108145. const float *logmask){
  108146. long i,j;
  108147. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  108148. vorbis_info_floor1 *info=look->vi;
  108149. long n=look->n;
  108150. long posts=look->posts;
  108151. long nonzero=0;
  108152. lsfit_acc fits[VIF_POSIT+1];
  108153. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  108154. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  108155. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  108156. int hineighbor[VIF_POSIT+2];
  108157. int *output=NULL;
  108158. int memo[VIF_POSIT+2];
  108159. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  108160. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  108161. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  108162. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  108163. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  108164. /* quantize the relevant floor points and collect them into line fit
  108165. structures (one per minimal division) at the same time */
  108166. if(posts==0){
  108167. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  108168. }else{
  108169. for(i=0;i<posts-1;i++)
  108170. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  108171. look->sorted_index[i+1],fits+i,
  108172. n,info);
  108173. }
  108174. if(nonzero){
  108175. /* start by fitting the implicit base case.... */
  108176. int y0=-200;
  108177. int y1=-200;
  108178. fit_line(fits,posts-1,&y0,&y1);
  108179. fit_valueA[0]=y0;
  108180. fit_valueB[0]=y0;
  108181. fit_valueB[1]=y1;
  108182. fit_valueA[1]=y1;
  108183. /* Non degenerate case */
  108184. /* start progressive splitting. This is a greedy, non-optimal
  108185. algorithm, but simple and close enough to the best
  108186. answer. */
  108187. for(i=2;i<posts;i++){
  108188. int sortpos=look->reverse_index[i];
  108189. int ln=loneighbor[sortpos];
  108190. int hn=hineighbor[sortpos];
  108191. /* eliminate repeat searches of a particular range with a memo */
  108192. if(memo[ln]!=hn){
  108193. /* haven't performed this error search yet */
  108194. int lsortpos=look->reverse_index[ln];
  108195. int hsortpos=look->reverse_index[hn];
  108196. memo[ln]=hn;
  108197. {
  108198. /* A note: we want to bound/minimize *local*, not global, error */
  108199. int lx=info->postlist[ln];
  108200. int hx=info->postlist[hn];
  108201. int ly=post_Y(fit_valueA,fit_valueB,ln);
  108202. int hy=post_Y(fit_valueA,fit_valueB,hn);
  108203. if(ly==-1 || hy==-1){
  108204. exit(1);
  108205. }
  108206. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  108207. /* outside error bounds/begin search area. Split it. */
  108208. int ly0=-200;
  108209. int ly1=-200;
  108210. int hy0=-200;
  108211. int hy1=-200;
  108212. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  108213. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  108214. /* store new edge values */
  108215. fit_valueB[ln]=ly0;
  108216. if(ln==0)fit_valueA[ln]=ly0;
  108217. fit_valueA[i]=ly1;
  108218. fit_valueB[i]=hy0;
  108219. fit_valueA[hn]=hy1;
  108220. if(hn==1)fit_valueB[hn]=hy1;
  108221. if(ly1>=0 || hy0>=0){
  108222. /* store new neighbor values */
  108223. for(j=sortpos-1;j>=0;j--)
  108224. if(hineighbor[j]==hn)
  108225. hineighbor[j]=i;
  108226. else
  108227. break;
  108228. for(j=sortpos+1;j<posts;j++)
  108229. if(loneighbor[j]==ln)
  108230. loneighbor[j]=i;
  108231. else
  108232. break;
  108233. }
  108234. }else{
  108235. fit_valueA[i]=-200;
  108236. fit_valueB[i]=-200;
  108237. }
  108238. }
  108239. }
  108240. }
  108241. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  108242. output[0]=post_Y(fit_valueA,fit_valueB,0);
  108243. output[1]=post_Y(fit_valueA,fit_valueB,1);
  108244. /* fill in posts marked as not using a fit; we will zero
  108245. back out to 'unused' when encoding them so long as curve
  108246. interpolation doesn't force them into use */
  108247. for(i=2;i<posts;i++){
  108248. int ln=look->loneighbor[i-2];
  108249. int hn=look->hineighbor[i-2];
  108250. int x0=info->postlist[ln];
  108251. int x1=info->postlist[hn];
  108252. int y0=output[ln];
  108253. int y1=output[hn];
  108254. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  108255. int vx=post_Y(fit_valueA,fit_valueB,i);
  108256. if(vx>=0 && predicted!=vx){
  108257. output[i]=vx;
  108258. }else{
  108259. output[i]= predicted|0x8000;
  108260. }
  108261. }
  108262. }
  108263. return(output);
  108264. }
  108265. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  108266. int *A,int *B,
  108267. int del){
  108268. long i;
  108269. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  108270. long posts=look->posts;
  108271. int *output=NULL;
  108272. if(A && B){
  108273. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  108274. for(i=0;i<posts;i++){
  108275. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  108276. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  108277. }
  108278. }
  108279. return(output);
  108280. }
  108281. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  108282. void*look_,
  108283. int *post,int *ilogmask){
  108284. long i,j;
  108285. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  108286. vorbis_info_floor1 *info=look->vi;
  108287. long posts=look->posts;
  108288. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  108289. int out[VIF_POSIT+2];
  108290. static_codebook **sbooks=ci->book_param;
  108291. codebook *books=ci->fullbooks;
  108292. static long seq=0;
  108293. /* quantize values to multiplier spec */
  108294. if(post){
  108295. for(i=0;i<posts;i++){
  108296. int val=post[i]&0x7fff;
  108297. switch(info->mult){
  108298. case 1: /* 1024 -> 256 */
  108299. val>>=2;
  108300. break;
  108301. case 2: /* 1024 -> 128 */
  108302. val>>=3;
  108303. break;
  108304. case 3: /* 1024 -> 86 */
  108305. val/=12;
  108306. break;
  108307. case 4: /* 1024 -> 64 */
  108308. val>>=4;
  108309. break;
  108310. }
  108311. post[i]=val | (post[i]&0x8000);
  108312. }
  108313. out[0]=post[0];
  108314. out[1]=post[1];
  108315. /* find prediction values for each post and subtract them */
  108316. for(i=2;i<posts;i++){
  108317. int ln=look->loneighbor[i-2];
  108318. int hn=look->hineighbor[i-2];
  108319. int x0=info->postlist[ln];
  108320. int x1=info->postlist[hn];
  108321. int y0=post[ln];
  108322. int y1=post[hn];
  108323. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  108324. if((post[i]&0x8000) || (predicted==post[i])){
  108325. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  108326. in interpolation */
  108327. out[i]=0;
  108328. }else{
  108329. int headroom=(look->quant_q-predicted<predicted?
  108330. look->quant_q-predicted:predicted);
  108331. int val=post[i]-predicted;
  108332. /* at this point the 'deviation' value is in the range +/- max
  108333. range, but the real, unique range can always be mapped to
  108334. only [0-maxrange). So we want to wrap the deviation into
  108335. this limited range, but do it in the way that least screws
  108336. an essentially gaussian probability distribution. */
  108337. if(val<0)
  108338. if(val<-headroom)
  108339. val=headroom-val-1;
  108340. else
  108341. val=-1-(val<<1);
  108342. else
  108343. if(val>=headroom)
  108344. val= val+headroom;
  108345. else
  108346. val<<=1;
  108347. out[i]=val;
  108348. post[ln]&=0x7fff;
  108349. post[hn]&=0x7fff;
  108350. }
  108351. }
  108352. /* we have everything we need. pack it out */
  108353. /* mark nontrivial floor */
  108354. oggpack_write(opb,1,1);
  108355. /* beginning/end post */
  108356. look->frames++;
  108357. look->postbits+=ilog(look->quant_q-1)*2;
  108358. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  108359. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  108360. /* partition by partition */
  108361. for(i=0,j=2;i<info->partitions;i++){
  108362. int classx=info->partitionclass[i];
  108363. int cdim=info->class_dim[classx];
  108364. int csubbits=info->class_subs[classx];
  108365. int csub=1<<csubbits;
  108366. int bookas[8]={0,0,0,0,0,0,0,0};
  108367. int cval=0;
  108368. int cshift=0;
  108369. int k,l;
  108370. /* generate the partition's first stage cascade value */
  108371. if(csubbits){
  108372. int maxval[8];
  108373. for(k=0;k<csub;k++){
  108374. int booknum=info->class_subbook[classx][k];
  108375. if(booknum<0){
  108376. maxval[k]=1;
  108377. }else{
  108378. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  108379. }
  108380. }
  108381. for(k=0;k<cdim;k++){
  108382. for(l=0;l<csub;l++){
  108383. int val=out[j+k];
  108384. if(val<maxval[l]){
  108385. bookas[k]=l;
  108386. break;
  108387. }
  108388. }
  108389. cval|= bookas[k]<<cshift;
  108390. cshift+=csubbits;
  108391. }
  108392. /* write it */
  108393. look->phrasebits+=
  108394. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  108395. #ifdef TRAIN_FLOOR1
  108396. {
  108397. FILE *of;
  108398. char buffer[80];
  108399. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  108400. vb->pcmend/2,posts-2,class);
  108401. of=fopen(buffer,"a");
  108402. fprintf(of,"%d\n",cval);
  108403. fclose(of);
  108404. }
  108405. #endif
  108406. }
  108407. /* write post values */
  108408. for(k=0;k<cdim;k++){
  108409. int book=info->class_subbook[classx][bookas[k]];
  108410. if(book>=0){
  108411. /* hack to allow training with 'bad' books */
  108412. if(out[j+k]<(books+book)->entries)
  108413. look->postbits+=vorbis_book_encode(books+book,
  108414. out[j+k],opb);
  108415. /*else
  108416. fprintf(stderr,"+!");*/
  108417. #ifdef TRAIN_FLOOR1
  108418. {
  108419. FILE *of;
  108420. char buffer[80];
  108421. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  108422. vb->pcmend/2,posts-2,class,bookas[k]);
  108423. of=fopen(buffer,"a");
  108424. fprintf(of,"%d\n",out[j+k]);
  108425. fclose(of);
  108426. }
  108427. #endif
  108428. }
  108429. }
  108430. j+=cdim;
  108431. }
  108432. {
  108433. /* generate quantized floor equivalent to what we'd unpack in decode */
  108434. /* render the lines */
  108435. int hx=0;
  108436. int lx=0;
  108437. int ly=post[0]*info->mult;
  108438. for(j=1;j<look->posts;j++){
  108439. int current=look->forward_index[j];
  108440. int hy=post[current]&0x7fff;
  108441. if(hy==post[current]){
  108442. hy*=info->mult;
  108443. hx=info->postlist[current];
  108444. render_line0(lx,hx,ly,hy,ilogmask);
  108445. lx=hx;
  108446. ly=hy;
  108447. }
  108448. }
  108449. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  108450. seq++;
  108451. return(1);
  108452. }
  108453. }else{
  108454. oggpack_write(opb,0,1);
  108455. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  108456. seq++;
  108457. return(0);
  108458. }
  108459. }
  108460. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  108461. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  108462. vorbis_info_floor1 *info=look->vi;
  108463. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  108464. int i,j,k;
  108465. codebook *books=ci->fullbooks;
  108466. /* unpack wrapped/predicted values from stream */
  108467. if(oggpack_read(&vb->opb,1)==1){
  108468. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  108469. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  108470. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  108471. /* partition by partition */
  108472. for(i=0,j=2;i<info->partitions;i++){
  108473. int classx=info->partitionclass[i];
  108474. int cdim=info->class_dim[classx];
  108475. int csubbits=info->class_subs[classx];
  108476. int csub=1<<csubbits;
  108477. int cval=0;
  108478. /* decode the partition's first stage cascade value */
  108479. if(csubbits){
  108480. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  108481. if(cval==-1)goto eop;
  108482. }
  108483. for(k=0;k<cdim;k++){
  108484. int book=info->class_subbook[classx][cval&(csub-1)];
  108485. cval>>=csubbits;
  108486. if(book>=0){
  108487. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  108488. goto eop;
  108489. }else{
  108490. fit_value[j+k]=0;
  108491. }
  108492. }
  108493. j+=cdim;
  108494. }
  108495. /* unwrap positive values and reconsitute via linear interpolation */
  108496. for(i=2;i<look->posts;i++){
  108497. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  108498. info->postlist[look->hineighbor[i-2]],
  108499. fit_value[look->loneighbor[i-2]],
  108500. fit_value[look->hineighbor[i-2]],
  108501. info->postlist[i]);
  108502. int hiroom=look->quant_q-predicted;
  108503. int loroom=predicted;
  108504. int room=(hiroom<loroom?hiroom:loroom)<<1;
  108505. int val=fit_value[i];
  108506. if(val){
  108507. if(val>=room){
  108508. if(hiroom>loroom){
  108509. val = val-loroom;
  108510. }else{
  108511. val = -1-(val-hiroom);
  108512. }
  108513. }else{
  108514. if(val&1){
  108515. val= -((val+1)>>1);
  108516. }else{
  108517. val>>=1;
  108518. }
  108519. }
  108520. fit_value[i]=val+predicted;
  108521. fit_value[look->loneighbor[i-2]]&=0x7fff;
  108522. fit_value[look->hineighbor[i-2]]&=0x7fff;
  108523. }else{
  108524. fit_value[i]=predicted|0x8000;
  108525. }
  108526. }
  108527. return(fit_value);
  108528. }
  108529. eop:
  108530. return(NULL);
  108531. }
  108532. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  108533. float *out){
  108534. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  108535. vorbis_info_floor1 *info=look->vi;
  108536. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  108537. int n=ci->blocksizes[vb->W]/2;
  108538. int j;
  108539. if(memo){
  108540. /* render the lines */
  108541. int *fit_value=(int *)memo;
  108542. int hx=0;
  108543. int lx=0;
  108544. int ly=fit_value[0]*info->mult;
  108545. for(j=1;j<look->posts;j++){
  108546. int current=look->forward_index[j];
  108547. int hy=fit_value[current]&0x7fff;
  108548. if(hy==fit_value[current]){
  108549. hy*=info->mult;
  108550. hx=info->postlist[current];
  108551. render_line(lx,hx,ly,hy,out);
  108552. lx=hx;
  108553. ly=hy;
  108554. }
  108555. }
  108556. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  108557. return(1);
  108558. }
  108559. memset(out,0,sizeof(*out)*n);
  108560. return(0);
  108561. }
  108562. /* export hooks */
  108563. vorbis_func_floor floor1_exportbundle={
  108564. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  108565. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  108566. };
  108567. #endif
  108568. /********* End of inlined file: floor1.c *********/
  108569. /********* Start of inlined file: info.c *********/
  108570. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108571. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108572. // tasks..
  108573. #ifdef _MSC_VER
  108574. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108575. #endif
  108576. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108577. #if JUCE_USE_OGGVORBIS
  108578. /* general handling of the header and the vorbis_info structure (and
  108579. substructures) */
  108580. #include <stdlib.h>
  108581. #include <string.h>
  108582. #include <ctype.h>
  108583. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  108584. while(bytes--){
  108585. oggpack_write(o,*s++,8);
  108586. }
  108587. }
  108588. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  108589. while(bytes--){
  108590. *buf++=oggpack_read(o,8);
  108591. }
  108592. }
  108593. void vorbis_comment_init(vorbis_comment *vc){
  108594. memset(vc,0,sizeof(*vc));
  108595. }
  108596. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  108597. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  108598. (vc->comments+2)*sizeof(*vc->user_comments));
  108599. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  108600. (vc->comments+2)*sizeof(*vc->comment_lengths));
  108601. vc->comment_lengths[vc->comments]=strlen(comment);
  108602. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  108603. strcpy(vc->user_comments[vc->comments], comment);
  108604. vc->comments++;
  108605. vc->user_comments[vc->comments]=NULL;
  108606. }
  108607. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  108608. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  108609. strcpy(comment, tag);
  108610. strcat(comment, "=");
  108611. strcat(comment, contents);
  108612. vorbis_comment_add(vc, comment);
  108613. }
  108614. /* This is more or less the same as strncasecmp - but that doesn't exist
  108615. * everywhere, and this is a fairly trivial function, so we include it */
  108616. static int tagcompare(const char *s1, const char *s2, int n){
  108617. int c=0;
  108618. while(c < n){
  108619. if(toupper(s1[c]) != toupper(s2[c]))
  108620. return !0;
  108621. c++;
  108622. }
  108623. return 0;
  108624. }
  108625. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  108626. long i;
  108627. int found = 0;
  108628. int taglen = strlen(tag)+1; /* +1 for the = we append */
  108629. char *fulltag = (char*)alloca(taglen+ 1);
  108630. strcpy(fulltag, tag);
  108631. strcat(fulltag, "=");
  108632. for(i=0;i<vc->comments;i++){
  108633. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  108634. if(count == found)
  108635. /* We return a pointer to the data, not a copy */
  108636. return vc->user_comments[i] + taglen;
  108637. else
  108638. found++;
  108639. }
  108640. }
  108641. return NULL; /* didn't find anything */
  108642. }
  108643. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  108644. int i,count=0;
  108645. int taglen = strlen(tag)+1; /* +1 for the = we append */
  108646. char *fulltag = (char*)alloca(taglen+1);
  108647. strcpy(fulltag,tag);
  108648. strcat(fulltag, "=");
  108649. for(i=0;i<vc->comments;i++){
  108650. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  108651. count++;
  108652. }
  108653. return count;
  108654. }
  108655. void vorbis_comment_clear(vorbis_comment *vc){
  108656. if(vc){
  108657. long i;
  108658. for(i=0;i<vc->comments;i++)
  108659. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  108660. if(vc->user_comments)_ogg_free(vc->user_comments);
  108661. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  108662. if(vc->vendor)_ogg_free(vc->vendor);
  108663. }
  108664. memset(vc,0,sizeof(*vc));
  108665. }
  108666. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  108667. They may be equal, but short will never ge greater than long */
  108668. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  108669. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  108670. return ci ? ci->blocksizes[zo] : -1;
  108671. }
  108672. /* used by synthesis, which has a full, alloced vi */
  108673. void vorbis_info_init(vorbis_info *vi){
  108674. memset(vi,0,sizeof(*vi));
  108675. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  108676. }
  108677. void vorbis_info_clear(vorbis_info *vi){
  108678. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108679. int i;
  108680. if(ci){
  108681. for(i=0;i<ci->modes;i++)
  108682. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  108683. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  108684. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  108685. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  108686. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  108687. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  108688. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  108689. for(i=0;i<ci->books;i++){
  108690. if(ci->book_param[i]){
  108691. /* knows if the book was not alloced */
  108692. vorbis_staticbook_destroy(ci->book_param[i]);
  108693. }
  108694. if(ci->fullbooks)
  108695. vorbis_book_clear(ci->fullbooks+i);
  108696. }
  108697. if(ci->fullbooks)
  108698. _ogg_free(ci->fullbooks);
  108699. for(i=0;i<ci->psys;i++)
  108700. _vi_psy_free(ci->psy_param[i]);
  108701. _ogg_free(ci);
  108702. }
  108703. memset(vi,0,sizeof(*vi));
  108704. }
  108705. /* Header packing/unpacking ********************************************/
  108706. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  108707. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108708. if(!ci)return(OV_EFAULT);
  108709. vi->version=oggpack_read(opb,32);
  108710. if(vi->version!=0)return(OV_EVERSION);
  108711. vi->channels=oggpack_read(opb,8);
  108712. vi->rate=oggpack_read(opb,32);
  108713. vi->bitrate_upper=oggpack_read(opb,32);
  108714. vi->bitrate_nominal=oggpack_read(opb,32);
  108715. vi->bitrate_lower=oggpack_read(opb,32);
  108716. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  108717. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  108718. if(vi->rate<1)goto err_out;
  108719. if(vi->channels<1)goto err_out;
  108720. if(ci->blocksizes[0]<8)goto err_out;
  108721. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  108722. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  108723. return(0);
  108724. err_out:
  108725. vorbis_info_clear(vi);
  108726. return(OV_EBADHEADER);
  108727. }
  108728. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  108729. int i;
  108730. int vendorlen=oggpack_read(opb,32);
  108731. if(vendorlen<0)goto err_out;
  108732. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  108733. _v_readstring(opb,vc->vendor,vendorlen);
  108734. vc->comments=oggpack_read(opb,32);
  108735. if(vc->comments<0)goto err_out;
  108736. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  108737. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  108738. for(i=0;i<vc->comments;i++){
  108739. int len=oggpack_read(opb,32);
  108740. if(len<0)goto err_out;
  108741. vc->comment_lengths[i]=len;
  108742. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  108743. _v_readstring(opb,vc->user_comments[i],len);
  108744. }
  108745. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  108746. return(0);
  108747. err_out:
  108748. vorbis_comment_clear(vc);
  108749. return(OV_EBADHEADER);
  108750. }
  108751. /* all of the real encoding details are here. The modes, books,
  108752. everything */
  108753. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  108754. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108755. int i;
  108756. if(!ci)return(OV_EFAULT);
  108757. /* codebooks */
  108758. ci->books=oggpack_read(opb,8)+1;
  108759. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  108760. for(i=0;i<ci->books;i++){
  108761. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  108762. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  108763. }
  108764. /* time backend settings; hooks are unused */
  108765. {
  108766. int times=oggpack_read(opb,6)+1;
  108767. for(i=0;i<times;i++){
  108768. int test=oggpack_read(opb,16);
  108769. if(test<0 || test>=VI_TIMEB)goto err_out;
  108770. }
  108771. }
  108772. /* floor backend settings */
  108773. ci->floors=oggpack_read(opb,6)+1;
  108774. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  108775. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  108776. for(i=0;i<ci->floors;i++){
  108777. ci->floor_type[i]=oggpack_read(opb,16);
  108778. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  108779. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  108780. if(!ci->floor_param[i])goto err_out;
  108781. }
  108782. /* residue backend settings */
  108783. ci->residues=oggpack_read(opb,6)+1;
  108784. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  108785. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  108786. for(i=0;i<ci->residues;i++){
  108787. ci->residue_type[i]=oggpack_read(opb,16);
  108788. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  108789. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  108790. if(!ci->residue_param[i])goto err_out;
  108791. }
  108792. /* map backend settings */
  108793. ci->maps=oggpack_read(opb,6)+1;
  108794. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  108795. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  108796. for(i=0;i<ci->maps;i++){
  108797. ci->map_type[i]=oggpack_read(opb,16);
  108798. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  108799. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  108800. if(!ci->map_param[i])goto err_out;
  108801. }
  108802. /* mode settings */
  108803. ci->modes=oggpack_read(opb,6)+1;
  108804. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  108805. for(i=0;i<ci->modes;i++){
  108806. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  108807. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  108808. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  108809. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  108810. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  108811. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  108812. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  108813. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  108814. }
  108815. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  108816. return(0);
  108817. err_out:
  108818. vorbis_info_clear(vi);
  108819. return(OV_EBADHEADER);
  108820. }
  108821. /* The Vorbis header is in three packets; the initial small packet in
  108822. the first page that identifies basic parameters, a second packet
  108823. with bitstream comments and a third packet that holds the
  108824. codebook. */
  108825. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  108826. oggpack_buffer opb;
  108827. if(op){
  108828. oggpack_readinit(&opb,op->packet,op->bytes);
  108829. /* Which of the three types of header is this? */
  108830. /* Also verify header-ness, vorbis */
  108831. {
  108832. char buffer[6];
  108833. int packtype=oggpack_read(&opb,8);
  108834. memset(buffer,0,6);
  108835. _v_readstring(&opb,buffer,6);
  108836. if(memcmp(buffer,"vorbis",6)){
  108837. /* not a vorbis header */
  108838. return(OV_ENOTVORBIS);
  108839. }
  108840. switch(packtype){
  108841. case 0x01: /* least significant *bit* is read first */
  108842. if(!op->b_o_s){
  108843. /* Not the initial packet */
  108844. return(OV_EBADHEADER);
  108845. }
  108846. if(vi->rate!=0){
  108847. /* previously initialized info header */
  108848. return(OV_EBADHEADER);
  108849. }
  108850. return(_vorbis_unpack_info(vi,&opb));
  108851. case 0x03: /* least significant *bit* is read first */
  108852. if(vi->rate==0){
  108853. /* um... we didn't get the initial header */
  108854. return(OV_EBADHEADER);
  108855. }
  108856. return(_vorbis_unpack_comment(vc,&opb));
  108857. case 0x05: /* least significant *bit* is read first */
  108858. if(vi->rate==0 || vc->vendor==NULL){
  108859. /* um... we didn;t get the initial header or comments yet */
  108860. return(OV_EBADHEADER);
  108861. }
  108862. return(_vorbis_unpack_books(vi,&opb));
  108863. default:
  108864. /* Not a valid vorbis header type */
  108865. return(OV_EBADHEADER);
  108866. break;
  108867. }
  108868. }
  108869. }
  108870. return(OV_EBADHEADER);
  108871. }
  108872. /* pack side **********************************************************/
  108873. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  108874. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108875. if(!ci)return(OV_EFAULT);
  108876. /* preamble */
  108877. oggpack_write(opb,0x01,8);
  108878. _v_writestring(opb,"vorbis", 6);
  108879. /* basic information about the stream */
  108880. oggpack_write(opb,0x00,32);
  108881. oggpack_write(opb,vi->channels,8);
  108882. oggpack_write(opb,vi->rate,32);
  108883. oggpack_write(opb,vi->bitrate_upper,32);
  108884. oggpack_write(opb,vi->bitrate_nominal,32);
  108885. oggpack_write(opb,vi->bitrate_lower,32);
  108886. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  108887. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  108888. oggpack_write(opb,1,1);
  108889. return(0);
  108890. }
  108891. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  108892. char temp[]="Xiph.Org libVorbis I 20050304";
  108893. int bytes = strlen(temp);
  108894. /* preamble */
  108895. oggpack_write(opb,0x03,8);
  108896. _v_writestring(opb,"vorbis", 6);
  108897. /* vendor */
  108898. oggpack_write(opb,bytes,32);
  108899. _v_writestring(opb,temp, bytes);
  108900. /* comments */
  108901. oggpack_write(opb,vc->comments,32);
  108902. if(vc->comments){
  108903. int i;
  108904. for(i=0;i<vc->comments;i++){
  108905. if(vc->user_comments[i]){
  108906. oggpack_write(opb,vc->comment_lengths[i],32);
  108907. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  108908. }else{
  108909. oggpack_write(opb,0,32);
  108910. }
  108911. }
  108912. }
  108913. oggpack_write(opb,1,1);
  108914. return(0);
  108915. }
  108916. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  108917. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108918. int i;
  108919. if(!ci)return(OV_EFAULT);
  108920. oggpack_write(opb,0x05,8);
  108921. _v_writestring(opb,"vorbis", 6);
  108922. /* books */
  108923. oggpack_write(opb,ci->books-1,8);
  108924. for(i=0;i<ci->books;i++)
  108925. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  108926. /* times; hook placeholders */
  108927. oggpack_write(opb,0,6);
  108928. oggpack_write(opb,0,16);
  108929. /* floors */
  108930. oggpack_write(opb,ci->floors-1,6);
  108931. for(i=0;i<ci->floors;i++){
  108932. oggpack_write(opb,ci->floor_type[i],16);
  108933. if(_floor_P[ci->floor_type[i]]->pack)
  108934. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  108935. else
  108936. goto err_out;
  108937. }
  108938. /* residues */
  108939. oggpack_write(opb,ci->residues-1,6);
  108940. for(i=0;i<ci->residues;i++){
  108941. oggpack_write(opb,ci->residue_type[i],16);
  108942. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  108943. }
  108944. /* maps */
  108945. oggpack_write(opb,ci->maps-1,6);
  108946. for(i=0;i<ci->maps;i++){
  108947. oggpack_write(opb,ci->map_type[i],16);
  108948. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  108949. }
  108950. /* modes */
  108951. oggpack_write(opb,ci->modes-1,6);
  108952. for(i=0;i<ci->modes;i++){
  108953. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  108954. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  108955. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  108956. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  108957. }
  108958. oggpack_write(opb,1,1);
  108959. return(0);
  108960. err_out:
  108961. return(-1);
  108962. }
  108963. int vorbis_commentheader_out(vorbis_comment *vc,
  108964. ogg_packet *op){
  108965. oggpack_buffer opb;
  108966. oggpack_writeinit(&opb);
  108967. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  108968. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  108969. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  108970. op->bytes=oggpack_bytes(&opb);
  108971. op->b_o_s=0;
  108972. op->e_o_s=0;
  108973. op->granulepos=0;
  108974. op->packetno=1;
  108975. return 0;
  108976. }
  108977. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  108978. vorbis_comment *vc,
  108979. ogg_packet *op,
  108980. ogg_packet *op_comm,
  108981. ogg_packet *op_code){
  108982. int ret=OV_EIMPL;
  108983. vorbis_info *vi=v->vi;
  108984. oggpack_buffer opb;
  108985. private_state *b=(private_state*)v->backend_state;
  108986. if(!b){
  108987. ret=OV_EFAULT;
  108988. goto err_out;
  108989. }
  108990. /* first header packet **********************************************/
  108991. oggpack_writeinit(&opb);
  108992. if(_vorbis_pack_info(&opb,vi))goto err_out;
  108993. /* build the packet */
  108994. if(b->header)_ogg_free(b->header);
  108995. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  108996. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  108997. op->packet=b->header;
  108998. op->bytes=oggpack_bytes(&opb);
  108999. op->b_o_s=1;
  109000. op->e_o_s=0;
  109001. op->granulepos=0;
  109002. op->packetno=0;
  109003. /* second header packet (comments) **********************************/
  109004. oggpack_reset(&opb);
  109005. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  109006. if(b->header1)_ogg_free(b->header1);
  109007. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109008. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  109009. op_comm->packet=b->header1;
  109010. op_comm->bytes=oggpack_bytes(&opb);
  109011. op_comm->b_o_s=0;
  109012. op_comm->e_o_s=0;
  109013. op_comm->granulepos=0;
  109014. op_comm->packetno=1;
  109015. /* third header packet (modes/codebooks) ****************************/
  109016. oggpack_reset(&opb);
  109017. if(_vorbis_pack_books(&opb,vi))goto err_out;
  109018. if(b->header2)_ogg_free(b->header2);
  109019. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109020. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  109021. op_code->packet=b->header2;
  109022. op_code->bytes=oggpack_bytes(&opb);
  109023. op_code->b_o_s=0;
  109024. op_code->e_o_s=0;
  109025. op_code->granulepos=0;
  109026. op_code->packetno=2;
  109027. oggpack_writeclear(&opb);
  109028. return(0);
  109029. err_out:
  109030. oggpack_writeclear(&opb);
  109031. memset(op,0,sizeof(*op));
  109032. memset(op_comm,0,sizeof(*op_comm));
  109033. memset(op_code,0,sizeof(*op_code));
  109034. if(b->header)_ogg_free(b->header);
  109035. if(b->header1)_ogg_free(b->header1);
  109036. if(b->header2)_ogg_free(b->header2);
  109037. b->header=NULL;
  109038. b->header1=NULL;
  109039. b->header2=NULL;
  109040. return(ret);
  109041. }
  109042. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  109043. if(granulepos>=0)
  109044. return((double)granulepos/v->vi->rate);
  109045. return(-1);
  109046. }
  109047. #endif
  109048. /********* End of inlined file: info.c *********/
  109049. /********* Start of inlined file: lpc.c *********/
  109050. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  109051. are derived from code written by Jutta Degener and Carsten Bormann;
  109052. thus we include their copyright below. The entirety of this file
  109053. is freely redistributable on the condition that both of these
  109054. copyright notices are preserved without modification. */
  109055. /* Preserved Copyright: *********************************************/
  109056. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  109057. Technische Universita"t Berlin
  109058. Any use of this software is permitted provided that this notice is not
  109059. removed and that neither the authors nor the Technische Universita"t
  109060. Berlin are deemed to have made any representations as to the
  109061. suitability of this software for any purpose nor are held responsible
  109062. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  109063. THIS SOFTWARE.
  109064. As a matter of courtesy, the authors request to be informed about uses
  109065. this software has found, about bugs in this software, and about any
  109066. improvements that may be of general interest.
  109067. Berlin, 28.11.1994
  109068. Jutta Degener
  109069. Carsten Bormann
  109070. *********************************************************************/
  109071. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109072. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109073. // tasks..
  109074. #ifdef _MSC_VER
  109075. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109076. #endif
  109077. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109078. #if JUCE_USE_OGGVORBIS
  109079. #include <stdlib.h>
  109080. #include <string.h>
  109081. #include <math.h>
  109082. /* Autocorrelation LPC coeff generation algorithm invented by
  109083. N. Levinson in 1947, modified by J. Durbin in 1959. */
  109084. /* Input : n elements of time doamin data
  109085. Output: m lpc coefficients, excitation energy */
  109086. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  109087. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  109088. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  109089. double error;
  109090. int i,j;
  109091. /* autocorrelation, p+1 lag coefficients */
  109092. j=m+1;
  109093. while(j--){
  109094. double d=0; /* double needed for accumulator depth */
  109095. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  109096. aut[j]=d;
  109097. }
  109098. /* Generate lpc coefficients from autocorr values */
  109099. error=aut[0];
  109100. for(i=0;i<m;i++){
  109101. double r= -aut[i+1];
  109102. if(error==0){
  109103. memset(lpci,0,m*sizeof(*lpci));
  109104. return 0;
  109105. }
  109106. /* Sum up this iteration's reflection coefficient; note that in
  109107. Vorbis we don't save it. If anyone wants to recycle this code
  109108. and needs reflection coefficients, save the results of 'r' from
  109109. each iteration. */
  109110. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  109111. r/=error;
  109112. /* Update LPC coefficients and total error */
  109113. lpc[i]=r;
  109114. for(j=0;j<i/2;j++){
  109115. double tmp=lpc[j];
  109116. lpc[j]+=r*lpc[i-1-j];
  109117. lpc[i-1-j]+=r*tmp;
  109118. }
  109119. if(i%2)lpc[j]+=lpc[j]*r;
  109120. error*=1.f-r*r;
  109121. }
  109122. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  109123. /* we need the error value to know how big an impulse to hit the
  109124. filter with later */
  109125. return error;
  109126. }
  109127. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  109128. float *data,long n){
  109129. /* in: coeff[0...m-1] LPC coefficients
  109130. prime[0...m-1] initial values (allocated size of n+m-1)
  109131. out: data[0...n-1] data samples */
  109132. long i,j,o,p;
  109133. float y;
  109134. float *work=(float*)alloca(sizeof(*work)*(m+n));
  109135. if(!prime)
  109136. for(i=0;i<m;i++)
  109137. work[i]=0.f;
  109138. else
  109139. for(i=0;i<m;i++)
  109140. work[i]=prime[i];
  109141. for(i=0;i<n;i++){
  109142. y=0;
  109143. o=i;
  109144. p=m;
  109145. for(j=0;j<m;j++)
  109146. y-=work[o++]*coeff[--p];
  109147. data[i]=work[o]=y;
  109148. }
  109149. }
  109150. #endif
  109151. /********* End of inlined file: lpc.c *********/
  109152. /********* Start of inlined file: lsp.c *********/
  109153. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  109154. an iterative root polisher (CACM algorithm 283). It *is* possible
  109155. to confuse this algorithm into not converging; that should only
  109156. happen with absurdly closely spaced roots (very sharp peaks in the
  109157. LPC f response) which in turn should be impossible in our use of
  109158. the code. If this *does* happen anyway, it's a bug in the floor
  109159. finder; find the cause of the confusion (probably a single bin
  109160. spike or accidental near-float-limit resolution problems) and
  109161. correct it. */
  109162. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109163. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109164. // tasks..
  109165. #ifdef _MSC_VER
  109166. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109167. #endif
  109168. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109169. #if JUCE_USE_OGGVORBIS
  109170. #include <math.h>
  109171. #include <string.h>
  109172. #include <stdlib.h>
  109173. /********* Start of inlined file: lookup.h *********/
  109174. #ifndef _V_LOOKUP_H_
  109175. #ifdef FLOAT_LOOKUP
  109176. extern float vorbis_coslook(float a);
  109177. extern float vorbis_invsqlook(float a);
  109178. extern float vorbis_invsq2explook(int a);
  109179. extern float vorbis_fromdBlook(float a);
  109180. #endif
  109181. #ifdef INT_LOOKUP
  109182. extern long vorbis_invsqlook_i(long a,long e);
  109183. extern long vorbis_coslook_i(long a);
  109184. extern float vorbis_fromdBlook_i(long a);
  109185. #endif
  109186. #endif
  109187. /********* End of inlined file: lookup.h *********/
  109188. /* three possible LSP to f curve functions; the exact computation
  109189. (float), a lookup based float implementation, and an integer
  109190. implementation. The float lookup is likely the optimal choice on
  109191. any machine with an FPU. The integer implementation is *not* fixed
  109192. point (due to the need for a large dynamic range and thus a
  109193. seperately tracked exponent) and thus much more complex than the
  109194. relatively simple float implementations. It's mostly for future
  109195. work on a fully fixed point implementation for processors like the
  109196. ARM family. */
  109197. /* undefine both for the 'old' but more precise implementation */
  109198. #define FLOAT_LOOKUP
  109199. #undef INT_LOOKUP
  109200. #ifdef FLOAT_LOOKUP
  109201. /********* Start of inlined file: lookup.c *********/
  109202. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109203. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109204. // tasks..
  109205. #ifdef _MSC_VER
  109206. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109207. #endif
  109208. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109209. #if JUCE_USE_OGGVORBIS
  109210. #include <math.h>
  109211. /********* Start of inlined file: lookup.h *********/
  109212. #ifndef _V_LOOKUP_H_
  109213. #ifdef FLOAT_LOOKUP
  109214. extern float vorbis_coslook(float a);
  109215. extern float vorbis_invsqlook(float a);
  109216. extern float vorbis_invsq2explook(int a);
  109217. extern float vorbis_fromdBlook(float a);
  109218. #endif
  109219. #ifdef INT_LOOKUP
  109220. extern long vorbis_invsqlook_i(long a,long e);
  109221. extern long vorbis_coslook_i(long a);
  109222. extern float vorbis_fromdBlook_i(long a);
  109223. #endif
  109224. #endif
  109225. /********* End of inlined file: lookup.h *********/
  109226. /********* Start of inlined file: lookup_data.h *********/
  109227. #ifndef _V_LOOKUP_DATA_H_
  109228. #ifdef FLOAT_LOOKUP
  109229. #define COS_LOOKUP_SZ 128
  109230. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  109231. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  109232. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  109233. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  109234. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  109235. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  109236. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  109237. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  109238. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  109239. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  109240. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  109241. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  109242. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  109243. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  109244. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  109245. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  109246. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  109247. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  109248. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  109249. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  109250. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  109251. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  109252. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  109253. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  109254. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  109255. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  109256. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  109257. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  109258. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  109259. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  109260. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  109261. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  109262. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  109263. -1.0000000000000f,
  109264. };
  109265. #define INVSQ_LOOKUP_SZ 32
  109266. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  109267. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  109268. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  109269. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  109270. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  109271. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  109272. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  109273. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  109274. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  109275. 1.000000000000f,
  109276. };
  109277. #define INVSQ2EXP_LOOKUP_MIN (-32)
  109278. #define INVSQ2EXP_LOOKUP_MAX 32
  109279. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  109280. INVSQ2EXP_LOOKUP_MIN+1]={
  109281. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  109282. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  109283. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  109284. 1024.f, 724.0773439f, 512.f, 362.038672f,
  109285. 256.f, 181.019336f, 128.f, 90.50966799f,
  109286. 64.f, 45.254834f, 32.f, 22.627417f,
  109287. 16.f, 11.3137085f, 8.f, 5.656854249f,
  109288. 4.f, 2.828427125f, 2.f, 1.414213562f,
  109289. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  109290. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  109291. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  109292. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  109293. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  109294. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  109295. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  109296. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  109297. 1.525878906e-05f,
  109298. };
  109299. #endif
  109300. #define FROMdB_LOOKUP_SZ 35
  109301. #define FROMdB2_LOOKUP_SZ 32
  109302. #define FROMdB_SHIFT 5
  109303. #define FROMdB2_SHIFT 3
  109304. #define FROMdB2_MASK 31
  109305. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  109306. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  109307. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  109308. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  109309. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  109310. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  109311. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  109312. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  109313. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  109314. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  109315. };
  109316. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  109317. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  109318. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  109319. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  109320. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  109321. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  109322. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  109323. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  109324. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  109325. };
  109326. #ifdef INT_LOOKUP
  109327. #define INVSQ_LOOKUP_I_SHIFT 10
  109328. #define INVSQ_LOOKUP_I_MASK 1023
  109329. static long INVSQ_LOOKUP_I[64+1]={
  109330. 92682l, 91966l, 91267l, 90583l,
  109331. 89915l, 89261l, 88621l, 87995l,
  109332. 87381l, 86781l, 86192l, 85616l,
  109333. 85051l, 84497l, 83953l, 83420l,
  109334. 82897l, 82384l, 81880l, 81385l,
  109335. 80899l, 80422l, 79953l, 79492l,
  109336. 79039l, 78594l, 78156l, 77726l,
  109337. 77302l, 76885l, 76475l, 76072l,
  109338. 75674l, 75283l, 74898l, 74519l,
  109339. 74146l, 73778l, 73415l, 73058l,
  109340. 72706l, 72359l, 72016l, 71679l,
  109341. 71347l, 71019l, 70695l, 70376l,
  109342. 70061l, 69750l, 69444l, 69141l,
  109343. 68842l, 68548l, 68256l, 67969l,
  109344. 67685l, 67405l, 67128l, 66855l,
  109345. 66585l, 66318l, 66054l, 65794l,
  109346. 65536l,
  109347. };
  109348. #define COS_LOOKUP_I_SHIFT 9
  109349. #define COS_LOOKUP_I_MASK 511
  109350. #define COS_LOOKUP_I_SZ 128
  109351. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  109352. 16384l, 16379l, 16364l, 16340l,
  109353. 16305l, 16261l, 16207l, 16143l,
  109354. 16069l, 15986l, 15893l, 15791l,
  109355. 15679l, 15557l, 15426l, 15286l,
  109356. 15137l, 14978l, 14811l, 14635l,
  109357. 14449l, 14256l, 14053l, 13842l,
  109358. 13623l, 13395l, 13160l, 12916l,
  109359. 12665l, 12406l, 12140l, 11866l,
  109360. 11585l, 11297l, 11003l, 10702l,
  109361. 10394l, 10080l, 9760l, 9434l,
  109362. 9102l, 8765l, 8423l, 8076l,
  109363. 7723l, 7366l, 7005l, 6639l,
  109364. 6270l, 5897l, 5520l, 5139l,
  109365. 4756l, 4370l, 3981l, 3590l,
  109366. 3196l, 2801l, 2404l, 2006l,
  109367. 1606l, 1205l, 804l, 402l,
  109368. 0l, -401l, -803l, -1204l,
  109369. -1605l, -2005l, -2403l, -2800l,
  109370. -3195l, -3589l, -3980l, -4369l,
  109371. -4755l, -5138l, -5519l, -5896l,
  109372. -6269l, -6638l, -7004l, -7365l,
  109373. -7722l, -8075l, -8422l, -8764l,
  109374. -9101l, -9433l, -9759l, -10079l,
  109375. -10393l, -10701l, -11002l, -11296l,
  109376. -11584l, -11865l, -12139l, -12405l,
  109377. -12664l, -12915l, -13159l, -13394l,
  109378. -13622l, -13841l, -14052l, -14255l,
  109379. -14448l, -14634l, -14810l, -14977l,
  109380. -15136l, -15285l, -15425l, -15556l,
  109381. -15678l, -15790l, -15892l, -15985l,
  109382. -16068l, -16142l, -16206l, -16260l,
  109383. -16304l, -16339l, -16363l, -16378l,
  109384. -16383l,
  109385. };
  109386. #endif
  109387. #endif
  109388. /********* End of inlined file: lookup_data.h *********/
  109389. #ifdef FLOAT_LOOKUP
  109390. /* interpolated lookup based cos function, domain 0 to PI only */
  109391. float vorbis_coslook(float a){
  109392. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  109393. int i=vorbis_ftoi(d-.5);
  109394. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  109395. }
  109396. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  109397. float vorbis_invsqlook(float a){
  109398. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  109399. int i=vorbis_ftoi(d-.5f);
  109400. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  109401. }
  109402. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  109403. float vorbis_invsq2explook(int a){
  109404. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  109405. }
  109406. #include <stdio.h>
  109407. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  109408. float vorbis_fromdBlook(float a){
  109409. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  109410. return (i<0)?1.f:
  109411. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  109412. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  109413. }
  109414. #endif
  109415. #ifdef INT_LOOKUP
  109416. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  109417. 16.16 format
  109418. returns in m.8 format */
  109419. long vorbis_invsqlook_i(long a,long e){
  109420. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  109421. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  109422. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  109423. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  109424. d)>>16); /* result 1.16 */
  109425. e+=32;
  109426. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  109427. e=(e>>1)-8;
  109428. return(val>>e);
  109429. }
  109430. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  109431. /* a is in n.12 format */
  109432. float vorbis_fromdBlook_i(long a){
  109433. int i=(-a)>>(12-FROMdB2_SHIFT);
  109434. return (i<0)?1.f:
  109435. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  109436. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  109437. }
  109438. /* interpolated lookup based cos function, domain 0 to PI only */
  109439. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  109440. long vorbis_coslook_i(long a){
  109441. int i=a>>COS_LOOKUP_I_SHIFT;
  109442. int d=a&COS_LOOKUP_I_MASK;
  109443. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  109444. COS_LOOKUP_I_SHIFT);
  109445. }
  109446. #endif
  109447. #endif
  109448. /********* End of inlined file: lookup.c *********/
  109449. /* catch this in the build system; we #include for
  109450. compilers (like gcc) that can't inline across
  109451. modules */
  109452. /* side effect: changes *lsp to cosines of lsp */
  109453. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  109454. float amp,float ampoffset){
  109455. int i;
  109456. float wdel=M_PI/ln;
  109457. vorbis_fpu_control fpu;
  109458. (void) fpu; // to avoid an unused variable warning
  109459. vorbis_fpu_setround(&fpu);
  109460. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  109461. i=0;
  109462. while(i<n){
  109463. int k=map[i];
  109464. int qexp;
  109465. float p=.7071067812f;
  109466. float q=.7071067812f;
  109467. float w=vorbis_coslook(wdel*k);
  109468. float *ftmp=lsp;
  109469. int c=m>>1;
  109470. do{
  109471. q*=ftmp[0]-w;
  109472. p*=ftmp[1]-w;
  109473. ftmp+=2;
  109474. }while(--c);
  109475. if(m&1){
  109476. /* odd order filter; slightly assymetric */
  109477. /* the last coefficient */
  109478. q*=ftmp[0]-w;
  109479. q*=q;
  109480. p*=p*(1.f-w*w);
  109481. }else{
  109482. /* even order filter; still symmetric */
  109483. q*=q*(1.f+w);
  109484. p*=p*(1.f-w);
  109485. }
  109486. q=frexp(p+q,&qexp);
  109487. q=vorbis_fromdBlook(amp*
  109488. vorbis_invsqlook(q)*
  109489. vorbis_invsq2explook(qexp+m)-
  109490. ampoffset);
  109491. do{
  109492. curve[i++]*=q;
  109493. }while(map[i]==k);
  109494. }
  109495. vorbis_fpu_restore(fpu);
  109496. }
  109497. #else
  109498. #ifdef INT_LOOKUP
  109499. /********* Start of inlined file: lookup.c *********/
  109500. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109501. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109502. // tasks..
  109503. #ifdef _MSC_VER
  109504. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109505. #endif
  109506. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109507. #if JUCE_USE_OGGVORBIS
  109508. #include <math.h>
  109509. /********* Start of inlined file: lookup.h *********/
  109510. #ifndef _V_LOOKUP_H_
  109511. #ifdef FLOAT_LOOKUP
  109512. extern float vorbis_coslook(float a);
  109513. extern float vorbis_invsqlook(float a);
  109514. extern float vorbis_invsq2explook(int a);
  109515. extern float vorbis_fromdBlook(float a);
  109516. #endif
  109517. #ifdef INT_LOOKUP
  109518. extern long vorbis_invsqlook_i(long a,long e);
  109519. extern long vorbis_coslook_i(long a);
  109520. extern float vorbis_fromdBlook_i(long a);
  109521. #endif
  109522. #endif
  109523. /********* End of inlined file: lookup.h *********/
  109524. /********* Start of inlined file: lookup_data.h *********/
  109525. #ifndef _V_LOOKUP_DATA_H_
  109526. #ifdef FLOAT_LOOKUP
  109527. #define COS_LOOKUP_SZ 128
  109528. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  109529. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  109530. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  109531. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  109532. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  109533. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  109534. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  109535. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  109536. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  109537. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  109538. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  109539. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  109540. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  109541. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  109542. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  109543. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  109544. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  109545. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  109546. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  109547. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  109548. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  109549. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  109550. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  109551. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  109552. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  109553. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  109554. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  109555. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  109556. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  109557. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  109558. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  109559. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  109560. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  109561. -1.0000000000000f,
  109562. };
  109563. #define INVSQ_LOOKUP_SZ 32
  109564. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  109565. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  109566. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  109567. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  109568. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  109569. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  109570. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  109571. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  109572. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  109573. 1.000000000000f,
  109574. };
  109575. #define INVSQ2EXP_LOOKUP_MIN (-32)
  109576. #define INVSQ2EXP_LOOKUP_MAX 32
  109577. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  109578. INVSQ2EXP_LOOKUP_MIN+1]={
  109579. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  109580. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  109581. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  109582. 1024.f, 724.0773439f, 512.f, 362.038672f,
  109583. 256.f, 181.019336f, 128.f, 90.50966799f,
  109584. 64.f, 45.254834f, 32.f, 22.627417f,
  109585. 16.f, 11.3137085f, 8.f, 5.656854249f,
  109586. 4.f, 2.828427125f, 2.f, 1.414213562f,
  109587. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  109588. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  109589. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  109590. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  109591. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  109592. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  109593. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  109594. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  109595. 1.525878906e-05f,
  109596. };
  109597. #endif
  109598. #define FROMdB_LOOKUP_SZ 35
  109599. #define FROMdB2_LOOKUP_SZ 32
  109600. #define FROMdB_SHIFT 5
  109601. #define FROMdB2_SHIFT 3
  109602. #define FROMdB2_MASK 31
  109603. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  109604. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  109605. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  109606. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  109607. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  109608. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  109609. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  109610. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  109611. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  109612. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  109613. };
  109614. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  109615. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  109616. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  109617. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  109618. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  109619. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  109620. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  109621. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  109622. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  109623. };
  109624. #ifdef INT_LOOKUP
  109625. #define INVSQ_LOOKUP_I_SHIFT 10
  109626. #define INVSQ_LOOKUP_I_MASK 1023
  109627. static long INVSQ_LOOKUP_I[64+1]={
  109628. 92682l, 91966l, 91267l, 90583l,
  109629. 89915l, 89261l, 88621l, 87995l,
  109630. 87381l, 86781l, 86192l, 85616l,
  109631. 85051l, 84497l, 83953l, 83420l,
  109632. 82897l, 82384l, 81880l, 81385l,
  109633. 80899l, 80422l, 79953l, 79492l,
  109634. 79039l, 78594l, 78156l, 77726l,
  109635. 77302l, 76885l, 76475l, 76072l,
  109636. 75674l, 75283l, 74898l, 74519l,
  109637. 74146l, 73778l, 73415l, 73058l,
  109638. 72706l, 72359l, 72016l, 71679l,
  109639. 71347l, 71019l, 70695l, 70376l,
  109640. 70061l, 69750l, 69444l, 69141l,
  109641. 68842l, 68548l, 68256l, 67969l,
  109642. 67685l, 67405l, 67128l, 66855l,
  109643. 66585l, 66318l, 66054l, 65794l,
  109644. 65536l,
  109645. };
  109646. #define COS_LOOKUP_I_SHIFT 9
  109647. #define COS_LOOKUP_I_MASK 511
  109648. #define COS_LOOKUP_I_SZ 128
  109649. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  109650. 16384l, 16379l, 16364l, 16340l,
  109651. 16305l, 16261l, 16207l, 16143l,
  109652. 16069l, 15986l, 15893l, 15791l,
  109653. 15679l, 15557l, 15426l, 15286l,
  109654. 15137l, 14978l, 14811l, 14635l,
  109655. 14449l, 14256l, 14053l, 13842l,
  109656. 13623l, 13395l, 13160l, 12916l,
  109657. 12665l, 12406l, 12140l, 11866l,
  109658. 11585l, 11297l, 11003l, 10702l,
  109659. 10394l, 10080l, 9760l, 9434l,
  109660. 9102l, 8765l, 8423l, 8076l,
  109661. 7723l, 7366l, 7005l, 6639l,
  109662. 6270l, 5897l, 5520l, 5139l,
  109663. 4756l, 4370l, 3981l, 3590l,
  109664. 3196l, 2801l, 2404l, 2006l,
  109665. 1606l, 1205l, 804l, 402l,
  109666. 0l, -401l, -803l, -1204l,
  109667. -1605l, -2005l, -2403l, -2800l,
  109668. -3195l, -3589l, -3980l, -4369l,
  109669. -4755l, -5138l, -5519l, -5896l,
  109670. -6269l, -6638l, -7004l, -7365l,
  109671. -7722l, -8075l, -8422l, -8764l,
  109672. -9101l, -9433l, -9759l, -10079l,
  109673. -10393l, -10701l, -11002l, -11296l,
  109674. -11584l, -11865l, -12139l, -12405l,
  109675. -12664l, -12915l, -13159l, -13394l,
  109676. -13622l, -13841l, -14052l, -14255l,
  109677. -14448l, -14634l, -14810l, -14977l,
  109678. -15136l, -15285l, -15425l, -15556l,
  109679. -15678l, -15790l, -15892l, -15985l,
  109680. -16068l, -16142l, -16206l, -16260l,
  109681. -16304l, -16339l, -16363l, -16378l,
  109682. -16383l,
  109683. };
  109684. #endif
  109685. #endif
  109686. /********* End of inlined file: lookup_data.h *********/
  109687. #ifdef FLOAT_LOOKUP
  109688. /* interpolated lookup based cos function, domain 0 to PI only */
  109689. float vorbis_coslook(float a){
  109690. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  109691. int i=vorbis_ftoi(d-.5);
  109692. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  109693. }
  109694. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  109695. float vorbis_invsqlook(float a){
  109696. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  109697. int i=vorbis_ftoi(d-.5f);
  109698. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  109699. }
  109700. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  109701. float vorbis_invsq2explook(int a){
  109702. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  109703. }
  109704. #include <stdio.h>
  109705. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  109706. float vorbis_fromdBlook(float a){
  109707. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  109708. return (i<0)?1.f:
  109709. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  109710. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  109711. }
  109712. #endif
  109713. #ifdef INT_LOOKUP
  109714. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  109715. 16.16 format
  109716. returns in m.8 format */
  109717. long vorbis_invsqlook_i(long a,long e){
  109718. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  109719. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  109720. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  109721. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  109722. d)>>16); /* result 1.16 */
  109723. e+=32;
  109724. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  109725. e=(e>>1)-8;
  109726. return(val>>e);
  109727. }
  109728. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  109729. /* a is in n.12 format */
  109730. float vorbis_fromdBlook_i(long a){
  109731. int i=(-a)>>(12-FROMdB2_SHIFT);
  109732. return (i<0)?1.f:
  109733. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  109734. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  109735. }
  109736. /* interpolated lookup based cos function, domain 0 to PI only */
  109737. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  109738. long vorbis_coslook_i(long a){
  109739. int i=a>>COS_LOOKUP_I_SHIFT;
  109740. int d=a&COS_LOOKUP_I_MASK;
  109741. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  109742. COS_LOOKUP_I_SHIFT);
  109743. }
  109744. #endif
  109745. #endif
  109746. /********* End of inlined file: lookup.c *********/
  109747. /* catch this in the build system; we #include for
  109748. compilers (like gcc) that can't inline across
  109749. modules */
  109750. static int MLOOP_1[64]={
  109751. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  109752. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  109753. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  109754. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  109755. };
  109756. static int MLOOP_2[64]={
  109757. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  109758. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  109759. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  109760. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  109761. };
  109762. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  109763. /* side effect: changes *lsp to cosines of lsp */
  109764. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  109765. float amp,float ampoffset){
  109766. /* 0 <= m < 256 */
  109767. /* set up for using all int later */
  109768. int i;
  109769. int ampoffseti=rint(ampoffset*4096.f);
  109770. int ampi=rint(amp*16.f);
  109771. long *ilsp=alloca(m*sizeof(*ilsp));
  109772. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  109773. i=0;
  109774. while(i<n){
  109775. int j,k=map[i];
  109776. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  109777. unsigned long qi=46341;
  109778. int qexp=0,shift;
  109779. long wi=vorbis_coslook_i(k*65536/ln);
  109780. qi*=labs(ilsp[0]-wi);
  109781. pi*=labs(ilsp[1]-wi);
  109782. for(j=3;j<m;j+=2){
  109783. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  109784. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  109785. shift=MLOOP_3[(pi|qi)>>16];
  109786. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  109787. pi=(pi>>shift)*labs(ilsp[j]-wi);
  109788. qexp+=shift;
  109789. }
  109790. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  109791. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  109792. shift=MLOOP_3[(pi|qi)>>16];
  109793. /* pi,qi normalized collectively, both tracked using qexp */
  109794. if(m&1){
  109795. /* odd order filter; slightly assymetric */
  109796. /* the last coefficient */
  109797. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  109798. pi=(pi>>shift)<<14;
  109799. qexp+=shift;
  109800. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  109801. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  109802. shift=MLOOP_3[(pi|qi)>>16];
  109803. pi>>=shift;
  109804. qi>>=shift;
  109805. qexp+=shift-14*((m+1)>>1);
  109806. pi=((pi*pi)>>16);
  109807. qi=((qi*qi)>>16);
  109808. qexp=qexp*2+m;
  109809. pi*=(1<<14)-((wi*wi)>>14);
  109810. qi+=pi>>14;
  109811. }else{
  109812. /* even order filter; still symmetric */
  109813. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  109814. worth tracking step by step */
  109815. pi>>=shift;
  109816. qi>>=shift;
  109817. qexp+=shift-7*m;
  109818. pi=((pi*pi)>>16);
  109819. qi=((qi*qi)>>16);
  109820. qexp=qexp*2+m;
  109821. pi*=(1<<14)-wi;
  109822. qi*=(1<<14)+wi;
  109823. qi=(qi+pi)>>14;
  109824. }
  109825. /* we've let the normalization drift because it wasn't important;
  109826. however, for the lookup, things must be normalized again. We
  109827. need at most one right shift or a number of left shifts */
  109828. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  109829. qi>>=1; qexp++;
  109830. }else
  109831. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  109832. qi<<=1; qexp--;
  109833. }
  109834. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  109835. vorbis_invsqlook_i(qi,qexp)-
  109836. /* m.8, m+n<=8 */
  109837. ampoffseti); /* 8.12[0] */
  109838. curve[i]*=amp;
  109839. while(map[++i]==k)curve[i]*=amp;
  109840. }
  109841. }
  109842. #else
  109843. /* old, nonoptimized but simple version for any poor sap who needs to
  109844. figure out what the hell this code does, or wants the other
  109845. fraction of a dB precision */
  109846. /* side effect: changes *lsp to cosines of lsp */
  109847. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  109848. float amp,float ampoffset){
  109849. int i;
  109850. float wdel=M_PI/ln;
  109851. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  109852. i=0;
  109853. while(i<n){
  109854. int j,k=map[i];
  109855. float p=.5f;
  109856. float q=.5f;
  109857. float w=2.f*cos(wdel*k);
  109858. for(j=1;j<m;j+=2){
  109859. q *= w-lsp[j-1];
  109860. p *= w-lsp[j];
  109861. }
  109862. if(j==m){
  109863. /* odd order filter; slightly assymetric */
  109864. /* the last coefficient */
  109865. q*=w-lsp[j-1];
  109866. p*=p*(4.f-w*w);
  109867. q*=q;
  109868. }else{
  109869. /* even order filter; still symmetric */
  109870. p*=p*(2.f-w);
  109871. q*=q*(2.f+w);
  109872. }
  109873. q=fromdB(amp/sqrt(p+q)-ampoffset);
  109874. curve[i]*=q;
  109875. while(map[++i]==k)curve[i]*=q;
  109876. }
  109877. }
  109878. #endif
  109879. #endif
  109880. static void cheby(float *g, int ord) {
  109881. int i, j;
  109882. g[0] *= .5f;
  109883. for(i=2; i<= ord; i++) {
  109884. for(j=ord; j >= i; j--) {
  109885. g[j-2] -= g[j];
  109886. g[j] += g[j];
  109887. }
  109888. }
  109889. }
  109890. static int comp(const void *a,const void *b){
  109891. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  109892. }
  109893. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  109894. but there are root sets for which it gets into limit cycles
  109895. (exacerbated by zero suppression) and fails. We can't afford to
  109896. fail, even if the failure is 1 in 100,000,000, so we now use
  109897. Laguerre and later polish with Newton-Raphson (which can then
  109898. afford to fail) */
  109899. #define EPSILON 10e-7
  109900. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  109901. int i,m;
  109902. double lastdelta=0.f;
  109903. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  109904. for(i=0;i<=ord;i++)defl[i]=a[i];
  109905. for(m=ord;m>0;m--){
  109906. double newx=0.f,delta;
  109907. /* iterate a root */
  109908. while(1){
  109909. double p=defl[m],pp=0.f,ppp=0.f,denom;
  109910. /* eval the polynomial and its first two derivatives */
  109911. for(i=m;i>0;i--){
  109912. ppp = newx*ppp + pp;
  109913. pp = newx*pp + p;
  109914. p = newx*p + defl[i-1];
  109915. }
  109916. /* Laguerre's method */
  109917. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  109918. if(denom<0)
  109919. return(-1); /* complex root! The LPC generator handed us a bad filter */
  109920. if(pp>0){
  109921. denom = pp + sqrt(denom);
  109922. if(denom<EPSILON)denom=EPSILON;
  109923. }else{
  109924. denom = pp - sqrt(denom);
  109925. if(denom>-(EPSILON))denom=-(EPSILON);
  109926. }
  109927. delta = m*p/denom;
  109928. newx -= delta;
  109929. if(delta<0.f)delta*=-1;
  109930. if(fabs(delta/newx)<10e-12)break;
  109931. lastdelta=delta;
  109932. }
  109933. r[m-1]=newx;
  109934. /* forward deflation */
  109935. for(i=m;i>0;i--)
  109936. defl[i-1]+=newx*defl[i];
  109937. defl++;
  109938. }
  109939. return(0);
  109940. }
  109941. /* for spit-and-polish only */
  109942. static int Newton_Raphson(float *a,int ord,float *r){
  109943. int i, k, count=0;
  109944. double error=1.f;
  109945. double *root=(double*)alloca(ord*sizeof(*root));
  109946. for(i=0; i<ord;i++) root[i] = r[i];
  109947. while(error>1e-20){
  109948. error=0;
  109949. for(i=0; i<ord; i++) { /* Update each point. */
  109950. double pp=0.,delta;
  109951. double rooti=root[i];
  109952. double p=a[ord];
  109953. for(k=ord-1; k>= 0; k--) {
  109954. pp= pp* rooti + p;
  109955. p = p * rooti + a[k];
  109956. }
  109957. delta = p/pp;
  109958. root[i] -= delta;
  109959. error+= delta*delta;
  109960. }
  109961. if(count>40)return(-1);
  109962. count++;
  109963. }
  109964. /* Replaced the original bubble sort with a real sort. With your
  109965. help, we can eliminate the bubble sort in our lifetime. --Monty */
  109966. for(i=0; i<ord;i++) r[i] = root[i];
  109967. return(0);
  109968. }
  109969. /* Convert lpc coefficients to lsp coefficients */
  109970. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  109971. int order2=(m+1)>>1;
  109972. int g1_order,g2_order;
  109973. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  109974. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  109975. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  109976. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  109977. int i;
  109978. /* even and odd are slightly different base cases */
  109979. g1_order=(m+1)>>1;
  109980. g2_order=(m) >>1;
  109981. /* Compute the lengths of the x polynomials. */
  109982. /* Compute the first half of K & R F1 & F2 polynomials. */
  109983. /* Compute half of the symmetric and antisymmetric polynomials. */
  109984. /* Remove the roots at +1 and -1. */
  109985. g1[g1_order] = 1.f;
  109986. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  109987. g2[g2_order] = 1.f;
  109988. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  109989. if(g1_order>g2_order){
  109990. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  109991. }else{
  109992. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  109993. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  109994. }
  109995. /* Convert into polynomials in cos(alpha) */
  109996. cheby(g1,g1_order);
  109997. cheby(g2,g2_order);
  109998. /* Find the roots of the 2 even polynomials.*/
  109999. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  110000. Laguerre_With_Deflation(g2,g2_order,g2r))
  110001. return(-1);
  110002. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  110003. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  110004. qsort(g1r,g1_order,sizeof(*g1r),comp);
  110005. qsort(g2r,g2_order,sizeof(*g2r),comp);
  110006. for(i=0;i<g1_order;i++)
  110007. lsp[i*2] = acos(g1r[i]);
  110008. for(i=0;i<g2_order;i++)
  110009. lsp[i*2+1] = acos(g2r[i]);
  110010. return(0);
  110011. }
  110012. #endif
  110013. /********* End of inlined file: lsp.c *********/
  110014. /********* Start of inlined file: mapping0.c *********/
  110015. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110016. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110017. // tasks..
  110018. #ifdef _MSC_VER
  110019. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110020. #endif
  110021. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110022. #if JUCE_USE_OGGVORBIS
  110023. #include <stdlib.h>
  110024. #include <stdio.h>
  110025. #include <string.h>
  110026. #include <math.h>
  110027. /* simplistic, wasteful way of doing this (unique lookup for each
  110028. mode/submapping); there should be a central repository for
  110029. identical lookups. That will require minor work, so I'm putting it
  110030. off as low priority.
  110031. Why a lookup for each backend in a given mode? Because the
  110032. blocksize is set by the mode, and low backend lookups may require
  110033. parameters from other areas of the mode/mapping */
  110034. static void mapping0_free_info(vorbis_info_mapping *i){
  110035. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  110036. if(info){
  110037. memset(info,0,sizeof(*info));
  110038. _ogg_free(info);
  110039. }
  110040. }
  110041. static int ilog3(unsigned int v){
  110042. int ret=0;
  110043. if(v)--v;
  110044. while(v){
  110045. ret++;
  110046. v>>=1;
  110047. }
  110048. return(ret);
  110049. }
  110050. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  110051. oggpack_buffer *opb){
  110052. int i;
  110053. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  110054. /* another 'we meant to do it this way' hack... up to beta 4, we
  110055. packed 4 binary zeros here to signify one submapping in use. We
  110056. now redefine that to mean four bitflags that indicate use of
  110057. deeper features; bit0:submappings, bit1:coupling,
  110058. bit2,3:reserved. This is backward compatable with all actual uses
  110059. of the beta code. */
  110060. if(info->submaps>1){
  110061. oggpack_write(opb,1,1);
  110062. oggpack_write(opb,info->submaps-1,4);
  110063. }else
  110064. oggpack_write(opb,0,1);
  110065. if(info->coupling_steps>0){
  110066. oggpack_write(opb,1,1);
  110067. oggpack_write(opb,info->coupling_steps-1,8);
  110068. for(i=0;i<info->coupling_steps;i++){
  110069. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  110070. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  110071. }
  110072. }else
  110073. oggpack_write(opb,0,1);
  110074. oggpack_write(opb,0,2); /* 2,3:reserved */
  110075. /* we don't write the channel submappings if we only have one... */
  110076. if(info->submaps>1){
  110077. for(i=0;i<vi->channels;i++)
  110078. oggpack_write(opb,info->chmuxlist[i],4);
  110079. }
  110080. for(i=0;i<info->submaps;i++){
  110081. oggpack_write(opb,0,8); /* time submap unused */
  110082. oggpack_write(opb,info->floorsubmap[i],8);
  110083. oggpack_write(opb,info->residuesubmap[i],8);
  110084. }
  110085. }
  110086. /* also responsible for range checking */
  110087. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  110088. int i;
  110089. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  110090. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110091. memset(info,0,sizeof(*info));
  110092. if(oggpack_read(opb,1))
  110093. info->submaps=oggpack_read(opb,4)+1;
  110094. else
  110095. info->submaps=1;
  110096. if(oggpack_read(opb,1)){
  110097. info->coupling_steps=oggpack_read(opb,8)+1;
  110098. for(i=0;i<info->coupling_steps;i++){
  110099. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  110100. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  110101. if(testM<0 ||
  110102. testA<0 ||
  110103. testM==testA ||
  110104. testM>=vi->channels ||
  110105. testA>=vi->channels) goto err_out;
  110106. }
  110107. }
  110108. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  110109. if(info->submaps>1){
  110110. for(i=0;i<vi->channels;i++){
  110111. info->chmuxlist[i]=oggpack_read(opb,4);
  110112. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  110113. }
  110114. }
  110115. for(i=0;i<info->submaps;i++){
  110116. oggpack_read(opb,8); /* time submap unused */
  110117. info->floorsubmap[i]=oggpack_read(opb,8);
  110118. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  110119. info->residuesubmap[i]=oggpack_read(opb,8);
  110120. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  110121. }
  110122. return info;
  110123. err_out:
  110124. mapping0_free_info(info);
  110125. return(NULL);
  110126. }
  110127. #if 0
  110128. static long seq=0;
  110129. static ogg_int64_t total=0;
  110130. static float FLOOR1_fromdB_LOOKUP[256]={
  110131. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  110132. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  110133. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  110134. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  110135. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  110136. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  110137. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  110138. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  110139. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  110140. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  110141. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  110142. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  110143. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  110144. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  110145. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  110146. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  110147. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  110148. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  110149. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  110150. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  110151. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  110152. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  110153. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  110154. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  110155. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  110156. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  110157. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  110158. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  110159. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  110160. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  110161. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  110162. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  110163. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  110164. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  110165. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  110166. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  110167. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  110168. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  110169. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  110170. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  110171. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  110172. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  110173. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  110174. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  110175. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  110176. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  110177. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  110178. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  110179. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  110180. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  110181. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  110182. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  110183. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  110184. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  110185. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  110186. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  110187. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  110188. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  110189. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  110190. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  110191. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  110192. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  110193. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  110194. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  110195. };
  110196. #endif
  110197. extern int *floor1_fit(vorbis_block *vb,void *look,
  110198. const float *logmdct, /* in */
  110199. const float *logmask);
  110200. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  110201. int *A,int *B,
  110202. int del);
  110203. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  110204. void*look,
  110205. int *post,int *ilogmask);
  110206. static int mapping0_forward(vorbis_block *vb){
  110207. vorbis_dsp_state *vd=vb->vd;
  110208. vorbis_info *vi=vd->vi;
  110209. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110210. private_state *b=(private_state*)vb->vd->backend_state;
  110211. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110212. int n=vb->pcmend;
  110213. int i,j,k;
  110214. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  110215. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  110216. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  110217. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  110218. float global_ampmax=vbi->ampmax;
  110219. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  110220. int blocktype=vbi->blocktype;
  110221. int modenumber=vb->W;
  110222. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  110223. vorbis_look_psy *psy_look=
  110224. b->psy+blocktype+(vb->W?2:0);
  110225. vb->mode=modenumber;
  110226. for(i=0;i<vi->channels;i++){
  110227. float scale=4.f/n;
  110228. float scale_dB;
  110229. float *pcm =vb->pcm[i];
  110230. float *logfft =pcm;
  110231. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  110232. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  110233. todB estimation used on IEEE 754
  110234. compliant machines had a bug that
  110235. returned dB values about a third
  110236. of a decibel too high. The bug
  110237. was harmless because tunings
  110238. implicitly took that into
  110239. account. However, fixing the bug
  110240. in the estimator requires
  110241. changing all the tunings as well.
  110242. For now, it's easier to sync
  110243. things back up here, and
  110244. recalibrate the tunings in the
  110245. next major model upgrade. */
  110246. #if 0
  110247. if(vi->channels==2)
  110248. if(i==0)
  110249. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  110250. else
  110251. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  110252. #endif
  110253. /* window the PCM data */
  110254. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  110255. #if 0
  110256. if(vi->channels==2)
  110257. if(i==0)
  110258. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  110259. else
  110260. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  110261. #endif
  110262. /* transform the PCM data */
  110263. /* only MDCT right now.... */
  110264. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  110265. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  110266. drft_forward(&b->fft_look[vb->W],pcm);
  110267. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  110268. original todB estimation used on
  110269. IEEE 754 compliant machines had a
  110270. bug that returned dB values about
  110271. a third of a decibel too high.
  110272. The bug was harmless because
  110273. tunings implicitly took that into
  110274. account. However, fixing the bug
  110275. in the estimator requires
  110276. changing all the tunings as well.
  110277. For now, it's easier to sync
  110278. things back up here, and
  110279. recalibrate the tunings in the
  110280. next major model upgrade. */
  110281. local_ampmax[i]=logfft[0];
  110282. for(j=1;j<n-1;j+=2){
  110283. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  110284. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  110285. .345 is a hack; the original todB
  110286. estimation used on IEEE 754
  110287. compliant machines had a bug that
  110288. returned dB values about a third
  110289. of a decibel too high. The bug
  110290. was harmless because tunings
  110291. implicitly took that into
  110292. account. However, fixing the bug
  110293. in the estimator requires
  110294. changing all the tunings as well.
  110295. For now, it's easier to sync
  110296. things back up here, and
  110297. recalibrate the tunings in the
  110298. next major model upgrade. */
  110299. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  110300. }
  110301. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  110302. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  110303. #if 0
  110304. if(vi->channels==2){
  110305. if(i==0){
  110306. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  110307. }else{
  110308. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  110309. }
  110310. }
  110311. #endif
  110312. }
  110313. {
  110314. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  110315. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  110316. for(i=0;i<vi->channels;i++){
  110317. /* the encoder setup assumes that all the modes used by any
  110318. specific bitrate tweaking use the same floor */
  110319. int submap=info->chmuxlist[i];
  110320. /* the following makes things clearer to *me* anyway */
  110321. float *mdct =gmdct[i];
  110322. float *logfft =vb->pcm[i];
  110323. float *logmdct =logfft+n/2;
  110324. float *logmask =logfft;
  110325. vb->mode=modenumber;
  110326. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  110327. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  110328. for(j=0;j<n/2;j++)
  110329. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  110330. todB estimation used on IEEE 754
  110331. compliant machines had a bug that
  110332. returned dB values about a third
  110333. of a decibel too high. The bug
  110334. was harmless because tunings
  110335. implicitly took that into
  110336. account. However, fixing the bug
  110337. in the estimator requires
  110338. changing all the tunings as well.
  110339. For now, it's easier to sync
  110340. things back up here, and
  110341. recalibrate the tunings in the
  110342. next major model upgrade. */
  110343. #if 0
  110344. if(vi->channels==2){
  110345. if(i==0)
  110346. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  110347. else
  110348. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  110349. }else{
  110350. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  110351. }
  110352. #endif
  110353. /* first step; noise masking. Not only does 'noise masking'
  110354. give us curves from which we can decide how much resolution
  110355. to give noise parts of the spectrum, it also implicitly hands
  110356. us a tonality estimate (the larger the value in the
  110357. 'noise_depth' vector, the more tonal that area is) */
  110358. _vp_noisemask(psy_look,
  110359. logmdct,
  110360. noise); /* noise does not have by-frequency offset
  110361. bias applied yet */
  110362. #if 0
  110363. if(vi->channels==2){
  110364. if(i==0)
  110365. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  110366. else
  110367. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  110368. }
  110369. #endif
  110370. /* second step: 'all the other crap'; all the stuff that isn't
  110371. computed/fit for bitrate management goes in the second psy
  110372. vector. This includes tone masking, peak limiting and ATH */
  110373. _vp_tonemask(psy_look,
  110374. logfft,
  110375. tone,
  110376. global_ampmax,
  110377. local_ampmax[i]);
  110378. #if 0
  110379. if(vi->channels==2){
  110380. if(i==0)
  110381. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  110382. else
  110383. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  110384. }
  110385. #endif
  110386. /* third step; we offset the noise vectors, overlay tone
  110387. masking. We then do a floor1-specific line fit. If we're
  110388. performing bitrate management, the line fit is performed
  110389. multiple times for up/down tweakage on demand. */
  110390. #if 0
  110391. {
  110392. float aotuv[psy_look->n];
  110393. #endif
  110394. _vp_offset_and_mix(psy_look,
  110395. noise,
  110396. tone,
  110397. 1,
  110398. logmask,
  110399. mdct,
  110400. logmdct);
  110401. #if 0
  110402. if(vi->channels==2){
  110403. if(i==0)
  110404. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  110405. else
  110406. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  110407. }
  110408. }
  110409. #endif
  110410. #if 0
  110411. if(vi->channels==2){
  110412. if(i==0)
  110413. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  110414. else
  110415. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  110416. }
  110417. #endif
  110418. /* this algorithm is hardwired to floor 1 for now; abort out if
  110419. we're *not* floor1. This won't happen unless someone has
  110420. broken the encode setup lib. Guard it anyway. */
  110421. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  110422. floor_posts[i][PACKETBLOBS/2]=
  110423. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  110424. logmdct,
  110425. logmask);
  110426. /* are we managing bitrate? If so, perform two more fits for
  110427. later rate tweaking (fits represent hi/lo) */
  110428. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  110429. /* higher rate by way of lower noise curve */
  110430. _vp_offset_and_mix(psy_look,
  110431. noise,
  110432. tone,
  110433. 2,
  110434. logmask,
  110435. mdct,
  110436. logmdct);
  110437. #if 0
  110438. if(vi->channels==2){
  110439. if(i==0)
  110440. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  110441. else
  110442. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  110443. }
  110444. #endif
  110445. floor_posts[i][PACKETBLOBS-1]=
  110446. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  110447. logmdct,
  110448. logmask);
  110449. /* lower rate by way of higher noise curve */
  110450. _vp_offset_and_mix(psy_look,
  110451. noise,
  110452. tone,
  110453. 0,
  110454. logmask,
  110455. mdct,
  110456. logmdct);
  110457. #if 0
  110458. if(vi->channels==2)
  110459. if(i==0)
  110460. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  110461. else
  110462. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  110463. #endif
  110464. floor_posts[i][0]=
  110465. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  110466. logmdct,
  110467. logmask);
  110468. /* we also interpolate a range of intermediate curves for
  110469. intermediate rates */
  110470. for(k=1;k<PACKETBLOBS/2;k++)
  110471. floor_posts[i][k]=
  110472. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  110473. floor_posts[i][0],
  110474. floor_posts[i][PACKETBLOBS/2],
  110475. k*65536/(PACKETBLOBS/2));
  110476. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  110477. floor_posts[i][k]=
  110478. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  110479. floor_posts[i][PACKETBLOBS/2],
  110480. floor_posts[i][PACKETBLOBS-1],
  110481. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  110482. }
  110483. }
  110484. }
  110485. vbi->ampmax=global_ampmax;
  110486. /*
  110487. the next phases are performed once for vbr-only and PACKETBLOB
  110488. times for bitrate managed modes.
  110489. 1) encode actual mode being used
  110490. 2) encode the floor for each channel, compute coded mask curve/res
  110491. 3) normalize and couple.
  110492. 4) encode residue
  110493. 5) save packet bytes to the packetblob vector
  110494. */
  110495. /* iterate over the many masking curve fits we've created */
  110496. {
  110497. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  110498. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  110499. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  110500. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  110501. float **mag_memo;
  110502. int **mag_sort;
  110503. if(info->coupling_steps){
  110504. mag_memo=_vp_quantize_couple_memo(vb,
  110505. &ci->psy_g_param,
  110506. psy_look,
  110507. info,
  110508. gmdct);
  110509. mag_sort=_vp_quantize_couple_sort(vb,
  110510. psy_look,
  110511. info,
  110512. mag_memo);
  110513. hf_reduction(&ci->psy_g_param,
  110514. psy_look,
  110515. info,
  110516. mag_memo);
  110517. }
  110518. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  110519. if(psy_look->vi->normal_channel_p){
  110520. for(i=0;i<vi->channels;i++){
  110521. float *mdct =gmdct[i];
  110522. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  110523. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  110524. }
  110525. }
  110526. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  110527. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  110528. k++){
  110529. oggpack_buffer *opb=vbi->packetblob[k];
  110530. /* start out our new packet blob with packet type and mode */
  110531. /* Encode the packet type */
  110532. oggpack_write(opb,0,1);
  110533. /* Encode the modenumber */
  110534. /* Encode frame mode, pre,post windowsize, then dispatch */
  110535. oggpack_write(opb,modenumber,b->modebits);
  110536. if(vb->W){
  110537. oggpack_write(opb,vb->lW,1);
  110538. oggpack_write(opb,vb->nW,1);
  110539. }
  110540. /* encode floor, compute masking curve, sep out residue */
  110541. for(i=0;i<vi->channels;i++){
  110542. int submap=info->chmuxlist[i];
  110543. float *mdct =gmdct[i];
  110544. float *res =vb->pcm[i];
  110545. int *ilogmask=ilogmaskch[i]=
  110546. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  110547. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  110548. floor_posts[i][k],
  110549. ilogmask);
  110550. #if 0
  110551. {
  110552. char buf[80];
  110553. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  110554. float work[n/2];
  110555. for(j=0;j<n/2;j++)
  110556. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  110557. _analysis_output(buf,seq,work,n/2,1,1,0);
  110558. }
  110559. #endif
  110560. _vp_remove_floor(psy_look,
  110561. mdct,
  110562. ilogmask,
  110563. res,
  110564. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  110565. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  110566. #if 0
  110567. {
  110568. char buf[80];
  110569. float work[n/2];
  110570. for(j=0;j<n/2;j++)
  110571. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  110572. sprintf(buf,"resI%c%d",i?'R':'L',k);
  110573. _analysis_output(buf,seq,work,n/2,1,1,0);
  110574. }
  110575. #endif
  110576. }
  110577. /* our iteration is now based on masking curve, not prequant and
  110578. coupling. Only one prequant/coupling step */
  110579. /* quantize/couple */
  110580. /* incomplete implementation that assumes the tree is all depth
  110581. one, or no tree at all */
  110582. if(info->coupling_steps){
  110583. _vp_couple(k,
  110584. &ci->psy_g_param,
  110585. psy_look,
  110586. info,
  110587. vb->pcm,
  110588. mag_memo,
  110589. mag_sort,
  110590. ilogmaskch,
  110591. nonzero,
  110592. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  110593. }
  110594. /* classify and encode by submap */
  110595. for(i=0;i<info->submaps;i++){
  110596. int ch_in_bundle=0;
  110597. long **classifications;
  110598. int resnum=info->residuesubmap[i];
  110599. for(j=0;j<vi->channels;j++){
  110600. if(info->chmuxlist[j]==i){
  110601. zerobundle[ch_in_bundle]=0;
  110602. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  110603. res_bundle[ch_in_bundle]=vb->pcm[j];
  110604. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  110605. }
  110606. }
  110607. classifications=_residue_P[ci->residue_type[resnum]]->
  110608. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  110609. _residue_P[ci->residue_type[resnum]]->
  110610. forward(opb,vb,b->residue[resnum],
  110611. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  110612. }
  110613. /* ok, done encoding. Next protopacket. */
  110614. }
  110615. }
  110616. #if 0
  110617. seq++;
  110618. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  110619. #endif
  110620. return(0);
  110621. }
  110622. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  110623. vorbis_dsp_state *vd=vb->vd;
  110624. vorbis_info *vi=vd->vi;
  110625. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  110626. private_state *b=(private_state*)vd->backend_state;
  110627. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  110628. int i,j;
  110629. long n=vb->pcmend=ci->blocksizes[vb->W];
  110630. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  110631. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  110632. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  110633. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  110634. /* recover the spectral envelope; store it in the PCM vector for now */
  110635. for(i=0;i<vi->channels;i++){
  110636. int submap=info->chmuxlist[i];
  110637. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  110638. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  110639. if(floormemo[i])
  110640. nonzero[i]=1;
  110641. else
  110642. nonzero[i]=0;
  110643. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  110644. }
  110645. /* channel coupling can 'dirty' the nonzero listing */
  110646. for(i=0;i<info->coupling_steps;i++){
  110647. if(nonzero[info->coupling_mag[i]] ||
  110648. nonzero[info->coupling_ang[i]]){
  110649. nonzero[info->coupling_mag[i]]=1;
  110650. nonzero[info->coupling_ang[i]]=1;
  110651. }
  110652. }
  110653. /* recover the residue into our working vectors */
  110654. for(i=0;i<info->submaps;i++){
  110655. int ch_in_bundle=0;
  110656. for(j=0;j<vi->channels;j++){
  110657. if(info->chmuxlist[j]==i){
  110658. if(nonzero[j])
  110659. zerobundle[ch_in_bundle]=1;
  110660. else
  110661. zerobundle[ch_in_bundle]=0;
  110662. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  110663. }
  110664. }
  110665. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  110666. inverse(vb,b->residue[info->residuesubmap[i]],
  110667. pcmbundle,zerobundle,ch_in_bundle);
  110668. }
  110669. /* channel coupling */
  110670. for(i=info->coupling_steps-1;i>=0;i--){
  110671. float *pcmM=vb->pcm[info->coupling_mag[i]];
  110672. float *pcmA=vb->pcm[info->coupling_ang[i]];
  110673. for(j=0;j<n/2;j++){
  110674. float mag=pcmM[j];
  110675. float ang=pcmA[j];
  110676. if(mag>0)
  110677. if(ang>0){
  110678. pcmM[j]=mag;
  110679. pcmA[j]=mag-ang;
  110680. }else{
  110681. pcmA[j]=mag;
  110682. pcmM[j]=mag+ang;
  110683. }
  110684. else
  110685. if(ang>0){
  110686. pcmM[j]=mag;
  110687. pcmA[j]=mag+ang;
  110688. }else{
  110689. pcmA[j]=mag;
  110690. pcmM[j]=mag-ang;
  110691. }
  110692. }
  110693. }
  110694. /* compute and apply spectral envelope */
  110695. for(i=0;i<vi->channels;i++){
  110696. float *pcm=vb->pcm[i];
  110697. int submap=info->chmuxlist[i];
  110698. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  110699. inverse2(vb,b->flr[info->floorsubmap[submap]],
  110700. floormemo[i],pcm);
  110701. }
  110702. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  110703. /* only MDCT right now.... */
  110704. for(i=0;i<vi->channels;i++){
  110705. float *pcm=vb->pcm[i];
  110706. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  110707. }
  110708. /* all done! */
  110709. return(0);
  110710. }
  110711. /* export hooks */
  110712. vorbis_func_mapping mapping0_exportbundle={
  110713. &mapping0_pack,
  110714. &mapping0_unpack,
  110715. &mapping0_free_info,
  110716. &mapping0_forward,
  110717. &mapping0_inverse
  110718. };
  110719. #endif
  110720. /********* End of inlined file: mapping0.c *********/
  110721. /********* Start of inlined file: mdct.c *********/
  110722. /* this can also be run as an integer transform by uncommenting a
  110723. define in mdct.h; the integerization is a first pass and although
  110724. it's likely stable for Vorbis, the dynamic range is constrained and
  110725. roundoff isn't done (so it's noisy). Consider it functional, but
  110726. only a starting point. There's no point on a machine with an FPU */
  110727. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110728. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110729. // tasks..
  110730. #ifdef _MSC_VER
  110731. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110732. #endif
  110733. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110734. #if JUCE_USE_OGGVORBIS
  110735. #include <stdio.h>
  110736. #include <stdlib.h>
  110737. #include <string.h>
  110738. #include <math.h>
  110739. /* build lookups for trig functions; also pre-figure scaling and
  110740. some window function algebra. */
  110741. void mdct_init(mdct_lookup *lookup,int n){
  110742. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  110743. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  110744. int i;
  110745. int n2=n>>1;
  110746. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  110747. lookup->n=n;
  110748. lookup->trig=T;
  110749. lookup->bitrev=bitrev;
  110750. /* trig lookups... */
  110751. for(i=0;i<n/4;i++){
  110752. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  110753. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  110754. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  110755. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  110756. }
  110757. for(i=0;i<n/8;i++){
  110758. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  110759. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  110760. }
  110761. /* bitreverse lookup... */
  110762. {
  110763. int mask=(1<<(log2n-1))-1,i,j;
  110764. int msb=1<<(log2n-2);
  110765. for(i=0;i<n/8;i++){
  110766. int acc=0;
  110767. for(j=0;msb>>j;j++)
  110768. if((msb>>j)&i)acc|=1<<j;
  110769. bitrev[i*2]=((~acc)&mask)-1;
  110770. bitrev[i*2+1]=acc;
  110771. }
  110772. }
  110773. lookup->scale=FLOAT_CONV(4.f/n);
  110774. }
  110775. /* 8 point butterfly (in place, 4 register) */
  110776. STIN void mdct_butterfly_8(DATA_TYPE *x){
  110777. REG_TYPE r0 = x[6] + x[2];
  110778. REG_TYPE r1 = x[6] - x[2];
  110779. REG_TYPE r2 = x[4] + x[0];
  110780. REG_TYPE r3 = x[4] - x[0];
  110781. x[6] = r0 + r2;
  110782. x[4] = r0 - r2;
  110783. r0 = x[5] - x[1];
  110784. r2 = x[7] - x[3];
  110785. x[0] = r1 + r0;
  110786. x[2] = r1 - r0;
  110787. r0 = x[5] + x[1];
  110788. r1 = x[7] + x[3];
  110789. x[3] = r2 + r3;
  110790. x[1] = r2 - r3;
  110791. x[7] = r1 + r0;
  110792. x[5] = r1 - r0;
  110793. }
  110794. /* 16 point butterfly (in place, 4 register) */
  110795. STIN void mdct_butterfly_16(DATA_TYPE *x){
  110796. REG_TYPE r0 = x[1] - x[9];
  110797. REG_TYPE r1 = x[0] - x[8];
  110798. x[8] += x[0];
  110799. x[9] += x[1];
  110800. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  110801. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  110802. r0 = x[3] - x[11];
  110803. r1 = x[10] - x[2];
  110804. x[10] += x[2];
  110805. x[11] += x[3];
  110806. x[2] = r0;
  110807. x[3] = r1;
  110808. r0 = x[12] - x[4];
  110809. r1 = x[13] - x[5];
  110810. x[12] += x[4];
  110811. x[13] += x[5];
  110812. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  110813. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  110814. r0 = x[14] - x[6];
  110815. r1 = x[15] - x[7];
  110816. x[14] += x[6];
  110817. x[15] += x[7];
  110818. x[6] = r0;
  110819. x[7] = r1;
  110820. mdct_butterfly_8(x);
  110821. mdct_butterfly_8(x+8);
  110822. }
  110823. /* 32 point butterfly (in place, 4 register) */
  110824. STIN void mdct_butterfly_32(DATA_TYPE *x){
  110825. REG_TYPE r0 = x[30] - x[14];
  110826. REG_TYPE r1 = x[31] - x[15];
  110827. x[30] += x[14];
  110828. x[31] += x[15];
  110829. x[14] = r0;
  110830. x[15] = r1;
  110831. r0 = x[28] - x[12];
  110832. r1 = x[29] - x[13];
  110833. x[28] += x[12];
  110834. x[29] += x[13];
  110835. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  110836. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  110837. r0 = x[26] - x[10];
  110838. r1 = x[27] - x[11];
  110839. x[26] += x[10];
  110840. x[27] += x[11];
  110841. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  110842. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  110843. r0 = x[24] - x[8];
  110844. r1 = x[25] - x[9];
  110845. x[24] += x[8];
  110846. x[25] += x[9];
  110847. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  110848. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  110849. r0 = x[22] - x[6];
  110850. r1 = x[7] - x[23];
  110851. x[22] += x[6];
  110852. x[23] += x[7];
  110853. x[6] = r1;
  110854. x[7] = r0;
  110855. r0 = x[4] - x[20];
  110856. r1 = x[5] - x[21];
  110857. x[20] += x[4];
  110858. x[21] += x[5];
  110859. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  110860. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  110861. r0 = x[2] - x[18];
  110862. r1 = x[3] - x[19];
  110863. x[18] += x[2];
  110864. x[19] += x[3];
  110865. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  110866. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  110867. r0 = x[0] - x[16];
  110868. r1 = x[1] - x[17];
  110869. x[16] += x[0];
  110870. x[17] += x[1];
  110871. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  110872. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  110873. mdct_butterfly_16(x);
  110874. mdct_butterfly_16(x+16);
  110875. }
  110876. /* N point first stage butterfly (in place, 2 register) */
  110877. STIN void mdct_butterfly_first(DATA_TYPE *T,
  110878. DATA_TYPE *x,
  110879. int points){
  110880. DATA_TYPE *x1 = x + points - 8;
  110881. DATA_TYPE *x2 = x + (points>>1) - 8;
  110882. REG_TYPE r0;
  110883. REG_TYPE r1;
  110884. do{
  110885. r0 = x1[6] - x2[6];
  110886. r1 = x1[7] - x2[7];
  110887. x1[6] += x2[6];
  110888. x1[7] += x2[7];
  110889. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110890. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110891. r0 = x1[4] - x2[4];
  110892. r1 = x1[5] - x2[5];
  110893. x1[4] += x2[4];
  110894. x1[5] += x2[5];
  110895. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  110896. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  110897. r0 = x1[2] - x2[2];
  110898. r1 = x1[3] - x2[3];
  110899. x1[2] += x2[2];
  110900. x1[3] += x2[3];
  110901. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  110902. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  110903. r0 = x1[0] - x2[0];
  110904. r1 = x1[1] - x2[1];
  110905. x1[0] += x2[0];
  110906. x1[1] += x2[1];
  110907. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  110908. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  110909. x1-=8;
  110910. x2-=8;
  110911. T+=16;
  110912. }while(x2>=x);
  110913. }
  110914. /* N/stage point generic N stage butterfly (in place, 2 register) */
  110915. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  110916. DATA_TYPE *x,
  110917. int points,
  110918. int trigint){
  110919. DATA_TYPE *x1 = x + points - 8;
  110920. DATA_TYPE *x2 = x + (points>>1) - 8;
  110921. REG_TYPE r0;
  110922. REG_TYPE r1;
  110923. do{
  110924. r0 = x1[6] - x2[6];
  110925. r1 = x1[7] - x2[7];
  110926. x1[6] += x2[6];
  110927. x1[7] += x2[7];
  110928. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110929. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110930. T+=trigint;
  110931. r0 = x1[4] - x2[4];
  110932. r1 = x1[5] - x2[5];
  110933. x1[4] += x2[4];
  110934. x1[5] += x2[5];
  110935. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110936. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110937. T+=trigint;
  110938. r0 = x1[2] - x2[2];
  110939. r1 = x1[3] - x2[3];
  110940. x1[2] += x2[2];
  110941. x1[3] += x2[3];
  110942. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110943. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110944. T+=trigint;
  110945. r0 = x1[0] - x2[0];
  110946. r1 = x1[1] - x2[1];
  110947. x1[0] += x2[0];
  110948. x1[1] += x2[1];
  110949. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110950. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110951. T+=trigint;
  110952. x1-=8;
  110953. x2-=8;
  110954. }while(x2>=x);
  110955. }
  110956. STIN void mdct_butterflies(mdct_lookup *init,
  110957. DATA_TYPE *x,
  110958. int points){
  110959. DATA_TYPE *T=init->trig;
  110960. int stages=init->log2n-5;
  110961. int i,j;
  110962. if(--stages>0){
  110963. mdct_butterfly_first(T,x,points);
  110964. }
  110965. for(i=1;--stages>0;i++){
  110966. for(j=0;j<(1<<i);j++)
  110967. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  110968. }
  110969. for(j=0;j<points;j+=32)
  110970. mdct_butterfly_32(x+j);
  110971. }
  110972. void mdct_clear(mdct_lookup *l){
  110973. if(l){
  110974. if(l->trig)_ogg_free(l->trig);
  110975. if(l->bitrev)_ogg_free(l->bitrev);
  110976. memset(l,0,sizeof(*l));
  110977. }
  110978. }
  110979. STIN void mdct_bitreverse(mdct_lookup *init,
  110980. DATA_TYPE *x){
  110981. int n = init->n;
  110982. int *bit = init->bitrev;
  110983. DATA_TYPE *w0 = x;
  110984. DATA_TYPE *w1 = x = w0+(n>>1);
  110985. DATA_TYPE *T = init->trig+n;
  110986. do{
  110987. DATA_TYPE *x0 = x+bit[0];
  110988. DATA_TYPE *x1 = x+bit[1];
  110989. REG_TYPE r0 = x0[1] - x1[1];
  110990. REG_TYPE r1 = x0[0] + x1[0];
  110991. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  110992. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  110993. w1 -= 4;
  110994. r0 = HALVE(x0[1] + x1[1]);
  110995. r1 = HALVE(x0[0] - x1[0]);
  110996. w0[0] = r0 + r2;
  110997. w1[2] = r0 - r2;
  110998. w0[1] = r1 + r3;
  110999. w1[3] = r3 - r1;
  111000. x0 = x+bit[2];
  111001. x1 = x+bit[3];
  111002. r0 = x0[1] - x1[1];
  111003. r1 = x0[0] + x1[0];
  111004. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  111005. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  111006. r0 = HALVE(x0[1] + x1[1]);
  111007. r1 = HALVE(x0[0] - x1[0]);
  111008. w0[2] = r0 + r2;
  111009. w1[0] = r0 - r2;
  111010. w0[3] = r1 + r3;
  111011. w1[1] = r3 - r1;
  111012. T += 4;
  111013. bit += 4;
  111014. w0 += 4;
  111015. }while(w0<w1);
  111016. }
  111017. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  111018. int n=init->n;
  111019. int n2=n>>1;
  111020. int n4=n>>2;
  111021. /* rotate */
  111022. DATA_TYPE *iX = in+n2-7;
  111023. DATA_TYPE *oX = out+n2+n4;
  111024. DATA_TYPE *T = init->trig+n4;
  111025. do{
  111026. oX -= 4;
  111027. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  111028. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  111029. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  111030. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  111031. iX -= 8;
  111032. T += 4;
  111033. }while(iX>=in);
  111034. iX = in+n2-8;
  111035. oX = out+n2+n4;
  111036. T = init->trig+n4;
  111037. do{
  111038. T -= 4;
  111039. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  111040. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  111041. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  111042. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  111043. iX -= 8;
  111044. oX += 4;
  111045. }while(iX>=in);
  111046. mdct_butterflies(init,out+n2,n2);
  111047. mdct_bitreverse(init,out);
  111048. /* roatate + window */
  111049. {
  111050. DATA_TYPE *oX1=out+n2+n4;
  111051. DATA_TYPE *oX2=out+n2+n4;
  111052. DATA_TYPE *iX =out;
  111053. T =init->trig+n2;
  111054. do{
  111055. oX1-=4;
  111056. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  111057. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  111058. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  111059. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  111060. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  111061. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  111062. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  111063. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  111064. oX2+=4;
  111065. iX += 8;
  111066. T += 8;
  111067. }while(iX<oX1);
  111068. iX=out+n2+n4;
  111069. oX1=out+n4;
  111070. oX2=oX1;
  111071. do{
  111072. oX1-=4;
  111073. iX-=4;
  111074. oX2[0] = -(oX1[3] = iX[3]);
  111075. oX2[1] = -(oX1[2] = iX[2]);
  111076. oX2[2] = -(oX1[1] = iX[1]);
  111077. oX2[3] = -(oX1[0] = iX[0]);
  111078. oX2+=4;
  111079. }while(oX2<iX);
  111080. iX=out+n2+n4;
  111081. oX1=out+n2+n4;
  111082. oX2=out+n2;
  111083. do{
  111084. oX1-=4;
  111085. oX1[0]= iX[3];
  111086. oX1[1]= iX[2];
  111087. oX1[2]= iX[1];
  111088. oX1[3]= iX[0];
  111089. iX+=4;
  111090. }while(oX1>oX2);
  111091. }
  111092. }
  111093. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  111094. int n=init->n;
  111095. int n2=n>>1;
  111096. int n4=n>>2;
  111097. int n8=n>>3;
  111098. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  111099. DATA_TYPE *w2=w+n2;
  111100. /* rotate */
  111101. /* window + rotate + step 1 */
  111102. REG_TYPE r0;
  111103. REG_TYPE r1;
  111104. DATA_TYPE *x0=in+n2+n4;
  111105. DATA_TYPE *x1=x0+1;
  111106. DATA_TYPE *T=init->trig+n2;
  111107. int i=0;
  111108. for(i=0;i<n8;i+=2){
  111109. x0 -=4;
  111110. T-=2;
  111111. r0= x0[2] + x1[0];
  111112. r1= x0[0] + x1[2];
  111113. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111114. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111115. x1 +=4;
  111116. }
  111117. x1=in+1;
  111118. for(;i<n2-n8;i+=2){
  111119. T-=2;
  111120. x0 -=4;
  111121. r0= x0[2] - x1[0];
  111122. r1= x0[0] - x1[2];
  111123. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111124. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111125. x1 +=4;
  111126. }
  111127. x0=in+n;
  111128. for(;i<n2;i+=2){
  111129. T-=2;
  111130. x0 -=4;
  111131. r0= -x0[2] - x1[0];
  111132. r1= -x0[0] - x1[2];
  111133. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111134. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111135. x1 +=4;
  111136. }
  111137. mdct_butterflies(init,w+n2,n2);
  111138. mdct_bitreverse(init,w);
  111139. /* roatate + window */
  111140. T=init->trig+n2;
  111141. x0=out+n2;
  111142. for(i=0;i<n4;i++){
  111143. x0--;
  111144. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  111145. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  111146. w+=2;
  111147. T+=2;
  111148. }
  111149. }
  111150. #endif
  111151. /********* End of inlined file: mdct.c *********/
  111152. /********* Start of inlined file: psy.c *********/
  111153. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  111154. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111155. // tasks..
  111156. #ifdef _MSC_VER
  111157. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111158. #endif
  111159. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  111160. #if JUCE_USE_OGGVORBIS
  111161. #include <stdlib.h>
  111162. #include <math.h>
  111163. #include <string.h>
  111164. /********* Start of inlined file: masking.h *********/
  111165. #ifndef _V_MASKING_H_
  111166. #define _V_MASKING_H_
  111167. /* more detailed ATH; the bass if flat to save stressing the floor
  111168. overly for only a bin or two of savings. */
  111169. #define MAX_ATH 88
  111170. static float ATH[]={
  111171. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  111172. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  111173. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  111174. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  111175. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  111176. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  111177. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  111178. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  111179. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  111180. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  111181. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  111182. };
  111183. /* The tone masking curves from Ehmer's and Fielder's papers have been
  111184. replaced by an empirically collected data set. The previously
  111185. published values were, far too often, simply on crack. */
  111186. #define EHMER_OFFSET 16
  111187. #define EHMER_MAX 56
  111188. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  111189. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  111190. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  111191. for collection of these curves) */
  111192. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  111193. /* 62.5 Hz */
  111194. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  111195. -60, -60, -60, -60, -62, -62, -65, -73,
  111196. -69, -68, -68, -67, -70, -70, -72, -74,
  111197. -75, -79, -79, -80, -83, -88, -93, -100,
  111198. -110, -999, -999, -999, -999, -999, -999, -999,
  111199. -999, -999, -999, -999, -999, -999, -999, -999,
  111200. -999, -999, -999, -999, -999, -999, -999, -999},
  111201. { -48, -48, -48, -48, -48, -48, -48, -48,
  111202. -48, -48, -48, -48, -48, -53, -61, -66,
  111203. -66, -68, -67, -70, -76, -76, -72, -73,
  111204. -75, -76, -78, -79, -83, -88, -93, -100,
  111205. -110, -999, -999, -999, -999, -999, -999, -999,
  111206. -999, -999, -999, -999, -999, -999, -999, -999,
  111207. -999, -999, -999, -999, -999, -999, -999, -999},
  111208. { -37, -37, -37, -37, -37, -37, -37, -37,
  111209. -38, -40, -42, -46, -48, -53, -55, -62,
  111210. -65, -58, -56, -56, -61, -60, -65, -67,
  111211. -69, -71, -77, -77, -78, -80, -82, -84,
  111212. -88, -93, -98, -106, -112, -999, -999, -999,
  111213. -999, -999, -999, -999, -999, -999, -999, -999,
  111214. -999, -999, -999, -999, -999, -999, -999, -999},
  111215. { -25, -25, -25, -25, -25, -25, -25, -25,
  111216. -25, -26, -27, -29, -32, -38, -48, -52,
  111217. -52, -50, -48, -48, -51, -52, -54, -60,
  111218. -67, -67, -66, -68, -69, -73, -73, -76,
  111219. -80, -81, -81, -85, -85, -86, -88, -93,
  111220. -100, -110, -999, -999, -999, -999, -999, -999,
  111221. -999, -999, -999, -999, -999, -999, -999, -999},
  111222. { -16, -16, -16, -16, -16, -16, -16, -16,
  111223. -17, -19, -20, -22, -26, -28, -31, -40,
  111224. -47, -39, -39, -40, -42, -43, -47, -51,
  111225. -57, -52, -55, -55, -60, -58, -62, -63,
  111226. -70, -67, -69, -72, -73, -77, -80, -82,
  111227. -83, -87, -90, -94, -98, -104, -115, -999,
  111228. -999, -999, -999, -999, -999, -999, -999, -999},
  111229. { -8, -8, -8, -8, -8, -8, -8, -8,
  111230. -8, -8, -10, -11, -15, -19, -25, -30,
  111231. -34, -31, -30, -31, -29, -32, -35, -42,
  111232. -48, -42, -44, -46, -50, -50, -51, -52,
  111233. -59, -54, -55, -55, -58, -62, -63, -66,
  111234. -72, -73, -76, -75, -78, -80, -80, -81,
  111235. -84, -88, -90, -94, -98, -101, -106, -110}},
  111236. /* 88Hz */
  111237. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  111238. -66, -66, -66, -66, -66, -67, -67, -67,
  111239. -76, -72, -71, -74, -76, -76, -75, -78,
  111240. -79, -79, -81, -83, -86, -89, -93, -97,
  111241. -100, -105, -110, -999, -999, -999, -999, -999,
  111242. -999, -999, -999, -999, -999, -999, -999, -999,
  111243. -999, -999, -999, -999, -999, -999, -999, -999},
  111244. { -47, -47, -47, -47, -47, -47, -47, -47,
  111245. -47, -47, -47, -48, -51, -55, -59, -66,
  111246. -66, -66, -67, -66, -68, -69, -70, -74,
  111247. -79, -77, -77, -78, -80, -81, -82, -84,
  111248. -86, -88, -91, -95, -100, -108, -116, -999,
  111249. -999, -999, -999, -999, -999, -999, -999, -999,
  111250. -999, -999, -999, -999, -999, -999, -999, -999},
  111251. { -36, -36, -36, -36, -36, -36, -36, -36,
  111252. -36, -37, -37, -41, -44, -48, -51, -58,
  111253. -62, -60, -57, -59, -59, -60, -63, -65,
  111254. -72, -71, -70, -72, -74, -77, -76, -78,
  111255. -81, -81, -80, -83, -86, -91, -96, -100,
  111256. -105, -110, -999, -999, -999, -999, -999, -999,
  111257. -999, -999, -999, -999, -999, -999, -999, -999},
  111258. { -28, -28, -28, -28, -28, -28, -28, -28,
  111259. -28, -30, -32, -32, -33, -35, -41, -49,
  111260. -50, -49, -47, -48, -48, -52, -51, -57,
  111261. -65, -61, -59, -61, -64, -69, -70, -74,
  111262. -77, -77, -78, -81, -84, -85, -87, -90,
  111263. -92, -96, -100, -107, -112, -999, -999, -999,
  111264. -999, -999, -999, -999, -999, -999, -999, -999},
  111265. { -19, -19, -19, -19, -19, -19, -19, -19,
  111266. -20, -21, -23, -27, -30, -35, -36, -41,
  111267. -46, -44, -42, -40, -41, -41, -43, -48,
  111268. -55, -53, -52, -53, -56, -59, -58, -60,
  111269. -67, -66, -69, -71, -72, -75, -79, -81,
  111270. -84, -87, -90, -93, -97, -101, -107, -114,
  111271. -999, -999, -999, -999, -999, -999, -999, -999},
  111272. { -9, -9, -9, -9, -9, -9, -9, -9,
  111273. -11, -12, -12, -15, -16, -20, -23, -30,
  111274. -37, -34, -33, -34, -31, -32, -32, -38,
  111275. -47, -44, -41, -40, -47, -49, -46, -46,
  111276. -58, -50, -50, -54, -58, -62, -64, -67,
  111277. -67, -70, -72, -76, -79, -83, -87, -91,
  111278. -96, -100, -104, -110, -999, -999, -999, -999}},
  111279. /* 125 Hz */
  111280. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  111281. -62, -62, -63, -64, -66, -67, -66, -68,
  111282. -75, -72, -76, -75, -76, -78, -79, -82,
  111283. -84, -85, -90, -94, -101, -110, -999, -999,
  111284. -999, -999, -999, -999, -999, -999, -999, -999,
  111285. -999, -999, -999, -999, -999, -999, -999, -999,
  111286. -999, -999, -999, -999, -999, -999, -999, -999},
  111287. { -59, -59, -59, -59, -59, -59, -59, -59,
  111288. -59, -59, -59, -60, -60, -61, -63, -66,
  111289. -71, -68, -70, -70, -71, -72, -72, -75,
  111290. -81, -78, -79, -82, -83, -86, -90, -97,
  111291. -103, -113, -999, -999, -999, -999, -999, -999,
  111292. -999, -999, -999, -999, -999, -999, -999, -999,
  111293. -999, -999, -999, -999, -999, -999, -999, -999},
  111294. { -53, -53, -53, -53, -53, -53, -53, -53,
  111295. -53, -54, -55, -57, -56, -57, -55, -61,
  111296. -65, -60, -60, -62, -63, -63, -66, -68,
  111297. -74, -73, -75, -75, -78, -80, -80, -82,
  111298. -85, -90, -96, -101, -108, -999, -999, -999,
  111299. -999, -999, -999, -999, -999, -999, -999, -999,
  111300. -999, -999, -999, -999, -999, -999, -999, -999},
  111301. { -46, -46, -46, -46, -46, -46, -46, -46,
  111302. -46, -46, -47, -47, -47, -47, -48, -51,
  111303. -57, -51, -49, -50, -51, -53, -54, -59,
  111304. -66, -60, -62, -67, -67, -70, -72, -75,
  111305. -76, -78, -81, -85, -88, -94, -97, -104,
  111306. -112, -999, -999, -999, -999, -999, -999, -999,
  111307. -999, -999, -999, -999, -999, -999, -999, -999},
  111308. { -36, -36, -36, -36, -36, -36, -36, -36,
  111309. -39, -41, -42, -42, -39, -38, -41, -43,
  111310. -52, -44, -40, -39, -37, -37, -40, -47,
  111311. -54, -50, -48, -50, -55, -61, -59, -62,
  111312. -66, -66, -66, -69, -69, -73, -74, -74,
  111313. -75, -77, -79, -82, -87, -91, -95, -100,
  111314. -108, -115, -999, -999, -999, -999, -999, -999},
  111315. { -28, -26, -24, -22, -20, -20, -23, -29,
  111316. -30, -31, -28, -27, -28, -28, -28, -35,
  111317. -40, -33, -32, -29, -30, -30, -30, -37,
  111318. -45, -41, -37, -38, -45, -47, -47, -48,
  111319. -53, -49, -48, -50, -49, -49, -51, -52,
  111320. -58, -56, -57, -56, -60, -61, -62, -70,
  111321. -72, -74, -78, -83, -88, -93, -100, -106}},
  111322. /* 177 Hz */
  111323. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111324. -999, -110, -105, -100, -95, -91, -87, -83,
  111325. -80, -78, -76, -78, -78, -81, -83, -85,
  111326. -86, -85, -86, -87, -90, -97, -107, -999,
  111327. -999, -999, -999, -999, -999, -999, -999, -999,
  111328. -999, -999, -999, -999, -999, -999, -999, -999,
  111329. -999, -999, -999, -999, -999, -999, -999, -999},
  111330. {-999, -999, -999, -110, -105, -100, -95, -90,
  111331. -85, -81, -77, -73, -70, -67, -67, -68,
  111332. -75, -73, -70, -69, -70, -72, -75, -79,
  111333. -84, -83, -84, -86, -88, -89, -89, -93,
  111334. -98, -105, -112, -999, -999, -999, -999, -999,
  111335. -999, -999, -999, -999, -999, -999, -999, -999,
  111336. -999, -999, -999, -999, -999, -999, -999, -999},
  111337. {-105, -100, -95, -90, -85, -80, -76, -71,
  111338. -68, -68, -65, -63, -63, -62, -62, -64,
  111339. -65, -64, -61, -62, -63, -64, -66, -68,
  111340. -73, -73, -74, -75, -76, -81, -83, -85,
  111341. -88, -89, -92, -95, -100, -108, -999, -999,
  111342. -999, -999, -999, -999, -999, -999, -999, -999,
  111343. -999, -999, -999, -999, -999, -999, -999, -999},
  111344. { -80, -75, -71, -68, -65, -63, -62, -61,
  111345. -61, -61, -61, -59, -56, -57, -53, -50,
  111346. -58, -52, -50, -50, -52, -53, -54, -58,
  111347. -67, -63, -67, -68, -72, -75, -78, -80,
  111348. -81, -81, -82, -85, -89, -90, -93, -97,
  111349. -101, -107, -114, -999, -999, -999, -999, -999,
  111350. -999, -999, -999, -999, -999, -999, -999, -999},
  111351. { -65, -61, -59, -57, -56, -55, -55, -56,
  111352. -56, -57, -55, -53, -52, -47, -44, -44,
  111353. -50, -44, -41, -39, -39, -42, -40, -46,
  111354. -51, -49, -50, -53, -54, -63, -60, -61,
  111355. -62, -66, -66, -66, -70, -73, -74, -75,
  111356. -76, -75, -79, -85, -89, -91, -96, -102,
  111357. -110, -999, -999, -999, -999, -999, -999, -999},
  111358. { -52, -50, -49, -49, -48, -48, -48, -49,
  111359. -50, -50, -49, -46, -43, -39, -35, -33,
  111360. -38, -36, -32, -29, -32, -32, -32, -35,
  111361. -44, -39, -38, -38, -46, -50, -45, -46,
  111362. -53, -50, -50, -50, -54, -54, -53, -53,
  111363. -56, -57, -59, -66, -70, -72, -74, -79,
  111364. -83, -85, -90, -97, -114, -999, -999, -999}},
  111365. /* 250 Hz */
  111366. {{-999, -999, -999, -999, -999, -999, -110, -105,
  111367. -100, -95, -90, -86, -80, -75, -75, -79,
  111368. -80, -79, -80, -81, -82, -88, -95, -103,
  111369. -110, -999, -999, -999, -999, -999, -999, -999,
  111370. -999, -999, -999, -999, -999, -999, -999, -999,
  111371. -999, -999, -999, -999, -999, -999, -999, -999,
  111372. -999, -999, -999, -999, -999, -999, -999, -999},
  111373. {-999, -999, -999, -999, -108, -103, -98, -93,
  111374. -88, -83, -79, -78, -75, -71, -67, -68,
  111375. -73, -73, -72, -73, -75, -77, -80, -82,
  111376. -88, -93, -100, -107, -114, -999, -999, -999,
  111377. -999, -999, -999, -999, -999, -999, -999, -999,
  111378. -999, -999, -999, -999, -999, -999, -999, -999,
  111379. -999, -999, -999, -999, -999, -999, -999, -999},
  111380. {-999, -999, -999, -110, -105, -101, -96, -90,
  111381. -86, -81, -77, -73, -69, -66, -61, -62,
  111382. -66, -64, -62, -65, -66, -70, -72, -76,
  111383. -81, -80, -84, -90, -95, -102, -110, -999,
  111384. -999, -999, -999, -999, -999, -999, -999, -999,
  111385. -999, -999, -999, -999, -999, -999, -999, -999,
  111386. -999, -999, -999, -999, -999, -999, -999, -999},
  111387. {-999, -999, -999, -107, -103, -97, -92, -88,
  111388. -83, -79, -74, -70, -66, -59, -53, -58,
  111389. -62, -55, -54, -54, -54, -58, -61, -62,
  111390. -72, -70, -72, -75, -78, -80, -81, -80,
  111391. -83, -83, -88, -93, -100, -107, -115, -999,
  111392. -999, -999, -999, -999, -999, -999, -999, -999,
  111393. -999, -999, -999, -999, -999, -999, -999, -999},
  111394. {-999, -999, -999, -105, -100, -95, -90, -85,
  111395. -80, -75, -70, -66, -62, -56, -48, -44,
  111396. -48, -46, -46, -43, -46, -48, -48, -51,
  111397. -58, -58, -59, -60, -62, -62, -61, -61,
  111398. -65, -64, -65, -68, -70, -74, -75, -78,
  111399. -81, -86, -95, -110, -999, -999, -999, -999,
  111400. -999, -999, -999, -999, -999, -999, -999, -999},
  111401. {-999, -999, -105, -100, -95, -90, -85, -80,
  111402. -75, -70, -65, -61, -55, -49, -39, -33,
  111403. -40, -35, -32, -38, -40, -33, -35, -37,
  111404. -46, -41, -45, -44, -46, -42, -45, -46,
  111405. -52, -50, -50, -50, -54, -54, -55, -57,
  111406. -62, -64, -66, -68, -70, -76, -81, -90,
  111407. -100, -110, -999, -999, -999, -999, -999, -999}},
  111408. /* 354 hz */
  111409. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111410. -105, -98, -90, -85, -82, -83, -80, -78,
  111411. -84, -79, -80, -83, -87, -89, -91, -93,
  111412. -99, -106, -117, -999, -999, -999, -999, -999,
  111413. -999, -999, -999, -999, -999, -999, -999, -999,
  111414. -999, -999, -999, -999, -999, -999, -999, -999,
  111415. -999, -999, -999, -999, -999, -999, -999, -999},
  111416. {-999, -999, -999, -999, -999, -999, -999, -999,
  111417. -105, -98, -90, -85, -80, -75, -70, -68,
  111418. -74, -72, -74, -77, -80, -82, -85, -87,
  111419. -92, -89, -91, -95, -100, -106, -112, -999,
  111420. -999, -999, -999, -999, -999, -999, -999, -999,
  111421. -999, -999, -999, -999, -999, -999, -999, -999,
  111422. -999, -999, -999, -999, -999, -999, -999, -999},
  111423. {-999, -999, -999, -999, -999, -999, -999, -999,
  111424. -105, -98, -90, -83, -75, -71, -63, -64,
  111425. -67, -62, -64, -67, -70, -73, -77, -81,
  111426. -84, -83, -85, -89, -90, -93, -98, -104,
  111427. -109, -114, -999, -999, -999, -999, -999, -999,
  111428. -999, -999, -999, -999, -999, -999, -999, -999,
  111429. -999, -999, -999, -999, -999, -999, -999, -999},
  111430. {-999, -999, -999, -999, -999, -999, -999, -999,
  111431. -103, -96, -88, -81, -75, -68, -58, -54,
  111432. -56, -54, -56, -56, -58, -60, -63, -66,
  111433. -74, -69, -72, -72, -75, -74, -77, -81,
  111434. -81, -82, -84, -87, -93, -96, -99, -104,
  111435. -110, -999, -999, -999, -999, -999, -999, -999,
  111436. -999, -999, -999, -999, -999, -999, -999, -999},
  111437. {-999, -999, -999, -999, -999, -108, -102, -96,
  111438. -91, -85, -80, -74, -68, -60, -51, -46,
  111439. -48, -46, -43, -45, -47, -47, -49, -48,
  111440. -56, -53, -55, -58, -57, -63, -58, -60,
  111441. -66, -64, -67, -70, -70, -74, -77, -84,
  111442. -86, -89, -91, -93, -94, -101, -109, -118,
  111443. -999, -999, -999, -999, -999, -999, -999, -999},
  111444. {-999, -999, -999, -108, -103, -98, -93, -88,
  111445. -83, -78, -73, -68, -60, -53, -44, -35,
  111446. -38, -38, -34, -34, -36, -40, -41, -44,
  111447. -51, -45, -46, -47, -46, -54, -50, -49,
  111448. -50, -50, -50, -51, -54, -57, -58, -60,
  111449. -66, -66, -66, -64, -65, -68, -77, -82,
  111450. -87, -95, -110, -999, -999, -999, -999, -999}},
  111451. /* 500 Hz */
  111452. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111453. -107, -102, -97, -92, -87, -83, -78, -75,
  111454. -82, -79, -83, -85, -89, -92, -95, -98,
  111455. -101, -105, -109, -113, -999, -999, -999, -999,
  111456. -999, -999, -999, -999, -999, -999, -999, -999,
  111457. -999, -999, -999, -999, -999, -999, -999, -999,
  111458. -999, -999, -999, -999, -999, -999, -999, -999},
  111459. {-999, -999, -999, -999, -999, -999, -999, -106,
  111460. -100, -95, -90, -86, -81, -78, -74, -69,
  111461. -74, -74, -76, -79, -83, -84, -86, -89,
  111462. -92, -97, -93, -100, -103, -107, -110, -999,
  111463. -999, -999, -999, -999, -999, -999, -999, -999,
  111464. -999, -999, -999, -999, -999, -999, -999, -999,
  111465. -999, -999, -999, -999, -999, -999, -999, -999},
  111466. {-999, -999, -999, -999, -999, -999, -106, -100,
  111467. -95, -90, -87, -83, -80, -75, -69, -60,
  111468. -66, -66, -68, -70, -74, -78, -79, -81,
  111469. -81, -83, -84, -87, -93, -96, -99, -103,
  111470. -107, -110, -999, -999, -999, -999, -999, -999,
  111471. -999, -999, -999, -999, -999, -999, -999, -999,
  111472. -999, -999, -999, -999, -999, -999, -999, -999},
  111473. {-999, -999, -999, -999, -999, -108, -103, -98,
  111474. -93, -89, -85, -82, -78, -71, -62, -55,
  111475. -58, -58, -54, -54, -55, -59, -61, -62,
  111476. -70, -66, -66, -67, -70, -72, -75, -78,
  111477. -84, -84, -84, -88, -91, -90, -95, -98,
  111478. -102, -103, -106, -110, -999, -999, -999, -999,
  111479. -999, -999, -999, -999, -999, -999, -999, -999},
  111480. {-999, -999, -999, -999, -108, -103, -98, -94,
  111481. -90, -87, -82, -79, -73, -67, -58, -47,
  111482. -50, -45, -41, -45, -48, -44, -44, -49,
  111483. -54, -51, -48, -47, -49, -50, -51, -57,
  111484. -58, -60, -63, -69, -70, -69, -71, -74,
  111485. -78, -82, -90, -95, -101, -105, -110, -999,
  111486. -999, -999, -999, -999, -999, -999, -999, -999},
  111487. {-999, -999, -999, -105, -101, -97, -93, -90,
  111488. -85, -80, -77, -72, -65, -56, -48, -37,
  111489. -40, -36, -34, -40, -50, -47, -38, -41,
  111490. -47, -38, -35, -39, -38, -43, -40, -45,
  111491. -50, -45, -44, -47, -50, -55, -48, -48,
  111492. -52, -66, -70, -76, -82, -90, -97, -105,
  111493. -110, -999, -999, -999, -999, -999, -999, -999}},
  111494. /* 707 Hz */
  111495. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111496. -999, -108, -103, -98, -93, -86, -79, -76,
  111497. -83, -81, -85, -87, -89, -93, -98, -102,
  111498. -107, -112, -999, -999, -999, -999, -999, -999,
  111499. -999, -999, -999, -999, -999, -999, -999, -999,
  111500. -999, -999, -999, -999, -999, -999, -999, -999,
  111501. -999, -999, -999, -999, -999, -999, -999, -999},
  111502. {-999, -999, -999, -999, -999, -999, -999, -999,
  111503. -999, -108, -103, -98, -93, -86, -79, -71,
  111504. -77, -74, -77, -79, -81, -84, -85, -90,
  111505. -92, -93, -92, -98, -101, -108, -112, -999,
  111506. -999, -999, -999, -999, -999, -999, -999, -999,
  111507. -999, -999, -999, -999, -999, -999, -999, -999,
  111508. -999, -999, -999, -999, -999, -999, -999, -999},
  111509. {-999, -999, -999, -999, -999, -999, -999, -999,
  111510. -108, -103, -98, -93, -87, -78, -68, -65,
  111511. -66, -62, -65, -67, -70, -73, -75, -78,
  111512. -82, -82, -83, -84, -91, -93, -98, -102,
  111513. -106, -110, -999, -999, -999, -999, -999, -999,
  111514. -999, -999, -999, -999, -999, -999, -999, -999,
  111515. -999, -999, -999, -999, -999, -999, -999, -999},
  111516. {-999, -999, -999, -999, -999, -999, -999, -999,
  111517. -105, -100, -95, -90, -82, -74, -62, -57,
  111518. -58, -56, -51, -52, -52, -54, -54, -58,
  111519. -66, -59, -60, -63, -66, -69, -73, -79,
  111520. -83, -84, -80, -81, -81, -82, -88, -92,
  111521. -98, -105, -113, -999, -999, -999, -999, -999,
  111522. -999, -999, -999, -999, -999, -999, -999, -999},
  111523. {-999, -999, -999, -999, -999, -999, -999, -107,
  111524. -102, -97, -92, -84, -79, -69, -57, -47,
  111525. -52, -47, -44, -45, -50, -52, -42, -42,
  111526. -53, -43, -43, -48, -51, -56, -55, -52,
  111527. -57, -59, -61, -62, -67, -71, -78, -83,
  111528. -86, -94, -98, -103, -110, -999, -999, -999,
  111529. -999, -999, -999, -999, -999, -999, -999, -999},
  111530. {-999, -999, -999, -999, -999, -999, -105, -100,
  111531. -95, -90, -84, -78, -70, -61, -51, -41,
  111532. -40, -38, -40, -46, -52, -51, -41, -40,
  111533. -46, -40, -38, -38, -41, -46, -41, -46,
  111534. -47, -43, -43, -45, -41, -45, -56, -67,
  111535. -68, -83, -87, -90, -95, -102, -107, -113,
  111536. -999, -999, -999, -999, -999, -999, -999, -999}},
  111537. /* 1000 Hz */
  111538. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111539. -999, -109, -105, -101, -96, -91, -84, -77,
  111540. -82, -82, -85, -89, -94, -100, -106, -110,
  111541. -999, -999, -999, -999, -999, -999, -999, -999,
  111542. -999, -999, -999, -999, -999, -999, -999, -999,
  111543. -999, -999, -999, -999, -999, -999, -999, -999,
  111544. -999, -999, -999, -999, -999, -999, -999, -999},
  111545. {-999, -999, -999, -999, -999, -999, -999, -999,
  111546. -999, -106, -103, -98, -92, -85, -80, -71,
  111547. -75, -72, -76, -80, -84, -86, -89, -93,
  111548. -100, -107, -113, -999, -999, -999, -999, -999,
  111549. -999, -999, -999, -999, -999, -999, -999, -999,
  111550. -999, -999, -999, -999, -999, -999, -999, -999,
  111551. -999, -999, -999, -999, -999, -999, -999, -999},
  111552. {-999, -999, -999, -999, -999, -999, -999, -107,
  111553. -104, -101, -97, -92, -88, -84, -80, -64,
  111554. -66, -63, -64, -66, -69, -73, -77, -83,
  111555. -83, -86, -91, -98, -104, -111, -999, -999,
  111556. -999, -999, -999, -999, -999, -999, -999, -999,
  111557. -999, -999, -999, -999, -999, -999, -999, -999,
  111558. -999, -999, -999, -999, -999, -999, -999, -999},
  111559. {-999, -999, -999, -999, -999, -999, -999, -107,
  111560. -104, -101, -97, -92, -90, -84, -74, -57,
  111561. -58, -52, -55, -54, -50, -52, -50, -52,
  111562. -63, -62, -69, -76, -77, -78, -78, -79,
  111563. -82, -88, -94, -100, -106, -111, -999, -999,
  111564. -999, -999, -999, -999, -999, -999, -999, -999,
  111565. -999, -999, -999, -999, -999, -999, -999, -999},
  111566. {-999, -999, -999, -999, -999, -999, -106, -102,
  111567. -98, -95, -90, -85, -83, -78, -70, -50,
  111568. -50, -41, -44, -49, -47, -50, -50, -44,
  111569. -55, -46, -47, -48, -48, -54, -49, -49,
  111570. -58, -62, -71, -81, -87, -92, -97, -102,
  111571. -108, -114, -999, -999, -999, -999, -999, -999,
  111572. -999, -999, -999, -999, -999, -999, -999, -999},
  111573. {-999, -999, -999, -999, -999, -999, -106, -102,
  111574. -98, -95, -90, -85, -83, -78, -70, -45,
  111575. -43, -41, -47, -50, -51, -50, -49, -45,
  111576. -47, -41, -44, -41, -39, -43, -38, -37,
  111577. -40, -41, -44, -50, -58, -65, -73, -79,
  111578. -85, -92, -97, -101, -105, -109, -113, -999,
  111579. -999, -999, -999, -999, -999, -999, -999, -999}},
  111580. /* 1414 Hz */
  111581. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111582. -999, -999, -999, -107, -100, -95, -87, -81,
  111583. -85, -83, -88, -93, -100, -107, -114, -999,
  111584. -999, -999, -999, -999, -999, -999, -999, -999,
  111585. -999, -999, -999, -999, -999, -999, -999, -999,
  111586. -999, -999, -999, -999, -999, -999, -999, -999,
  111587. -999, -999, -999, -999, -999, -999, -999, -999},
  111588. {-999, -999, -999, -999, -999, -999, -999, -999,
  111589. -999, -999, -107, -101, -95, -88, -83, -76,
  111590. -73, -72, -79, -84, -90, -95, -100, -105,
  111591. -110, -115, -999, -999, -999, -999, -999, -999,
  111592. -999, -999, -999, -999, -999, -999, -999, -999,
  111593. -999, -999, -999, -999, -999, -999, -999, -999,
  111594. -999, -999, -999, -999, -999, -999, -999, -999},
  111595. {-999, -999, -999, -999, -999, -999, -999, -999,
  111596. -999, -999, -104, -98, -92, -87, -81, -70,
  111597. -65, -62, -67, -71, -74, -80, -85, -91,
  111598. -95, -99, -103, -108, -111, -114, -999, -999,
  111599. -999, -999, -999, -999, -999, -999, -999, -999,
  111600. -999, -999, -999, -999, -999, -999, -999, -999,
  111601. -999, -999, -999, -999, -999, -999, -999, -999},
  111602. {-999, -999, -999, -999, -999, -999, -999, -999,
  111603. -999, -999, -103, -97, -90, -85, -76, -60,
  111604. -56, -54, -60, -62, -61, -56, -63, -65,
  111605. -73, -74, -77, -75, -78, -81, -86, -87,
  111606. -88, -91, -94, -98, -103, -110, -999, -999,
  111607. -999, -999, -999, -999, -999, -999, -999, -999,
  111608. -999, -999, -999, -999, -999, -999, -999, -999},
  111609. {-999, -999, -999, -999, -999, -999, -999, -105,
  111610. -100, -97, -92, -86, -81, -79, -70, -57,
  111611. -51, -47, -51, -58, -60, -56, -53, -50,
  111612. -58, -52, -50, -50, -53, -55, -64, -69,
  111613. -71, -85, -82, -78, -81, -85, -95, -102,
  111614. -112, -999, -999, -999, -999, -999, -999, -999,
  111615. -999, -999, -999, -999, -999, -999, -999, -999},
  111616. {-999, -999, -999, -999, -999, -999, -999, -105,
  111617. -100, -97, -92, -85, -83, -79, -72, -49,
  111618. -40, -43, -43, -54, -56, -51, -50, -40,
  111619. -43, -38, -36, -35, -37, -38, -37, -44,
  111620. -54, -60, -57, -60, -70, -75, -84, -92,
  111621. -103, -112, -999, -999, -999, -999, -999, -999,
  111622. -999, -999, -999, -999, -999, -999, -999, -999}},
  111623. /* 2000 Hz */
  111624. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111625. -999, -999, -999, -110, -102, -95, -89, -82,
  111626. -83, -84, -90, -92, -99, -107, -113, -999,
  111627. -999, -999, -999, -999, -999, -999, -999, -999,
  111628. -999, -999, -999, -999, -999, -999, -999, -999,
  111629. -999, -999, -999, -999, -999, -999, -999, -999,
  111630. -999, -999, -999, -999, -999, -999, -999, -999},
  111631. {-999, -999, -999, -999, -999, -999, -999, -999,
  111632. -999, -999, -107, -101, -95, -89, -83, -72,
  111633. -74, -78, -85, -88, -88, -90, -92, -98,
  111634. -105, -111, -999, -999, -999, -999, -999, -999,
  111635. -999, -999, -999, -999, -999, -999, -999, -999,
  111636. -999, -999, -999, -999, -999, -999, -999, -999,
  111637. -999, -999, -999, -999, -999, -999, -999, -999},
  111638. {-999, -999, -999, -999, -999, -999, -999, -999,
  111639. -999, -109, -103, -97, -93, -87, -81, -70,
  111640. -70, -67, -75, -73, -76, -79, -81, -83,
  111641. -88, -89, -97, -103, -110, -999, -999, -999,
  111642. -999, -999, -999, -999, -999, -999, -999, -999,
  111643. -999, -999, -999, -999, -999, -999, -999, -999,
  111644. -999, -999, -999, -999, -999, -999, -999, -999},
  111645. {-999, -999, -999, -999, -999, -999, -999, -999,
  111646. -999, -107, -100, -94, -88, -83, -75, -63,
  111647. -59, -59, -63, -66, -60, -62, -67, -67,
  111648. -77, -76, -81, -88, -86, -92, -96, -102,
  111649. -109, -116, -999, -999, -999, -999, -999, -999,
  111650. -999, -999, -999, -999, -999, -999, -999, -999,
  111651. -999, -999, -999, -999, -999, -999, -999, -999},
  111652. {-999, -999, -999, -999, -999, -999, -999, -999,
  111653. -999, -105, -98, -92, -86, -81, -73, -56,
  111654. -52, -47, -55, -60, -58, -52, -51, -45,
  111655. -49, -50, -53, -54, -61, -71, -70, -69,
  111656. -78, -79, -87, -90, -96, -104, -112, -999,
  111657. -999, -999, -999, -999, -999, -999, -999, -999,
  111658. -999, -999, -999, -999, -999, -999, -999, -999},
  111659. {-999, -999, -999, -999, -999, -999, -999, -999,
  111660. -999, -103, -96, -90, -86, -78, -70, -51,
  111661. -42, -47, -48, -55, -54, -54, -53, -42,
  111662. -35, -28, -33, -38, -37, -44, -47, -49,
  111663. -54, -63, -68, -78, -82, -89, -94, -99,
  111664. -104, -109, -114, -999, -999, -999, -999, -999,
  111665. -999, -999, -999, -999, -999, -999, -999, -999}},
  111666. /* 2828 Hz */
  111667. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111668. -999, -999, -999, -999, -110, -100, -90, -79,
  111669. -85, -81, -82, -82, -89, -94, -99, -103,
  111670. -109, -115, -999, -999, -999, -999, -999, -999,
  111671. -999, -999, -999, -999, -999, -999, -999, -999,
  111672. -999, -999, -999, -999, -999, -999, -999, -999,
  111673. -999, -999, -999, -999, -999, -999, -999, -999},
  111674. {-999, -999, -999, -999, -999, -999, -999, -999,
  111675. -999, -999, -999, -999, -105, -97, -85, -72,
  111676. -74, -70, -70, -70, -76, -85, -91, -93,
  111677. -97, -103, -109, -115, -999, -999, -999, -999,
  111678. -999, -999, -999, -999, -999, -999, -999, -999,
  111679. -999, -999, -999, -999, -999, -999, -999, -999,
  111680. -999, -999, -999, -999, -999, -999, -999, -999},
  111681. {-999, -999, -999, -999, -999, -999, -999, -999,
  111682. -999, -999, -999, -999, -112, -93, -81, -68,
  111683. -62, -60, -60, -57, -63, -70, -77, -82,
  111684. -90, -93, -98, -104, -109, -113, -999, -999,
  111685. -999, -999, -999, -999, -999, -999, -999, -999,
  111686. -999, -999, -999, -999, -999, -999, -999, -999,
  111687. -999, -999, -999, -999, -999, -999, -999, -999},
  111688. {-999, -999, -999, -999, -999, -999, -999, -999,
  111689. -999, -999, -999, -113, -100, -93, -84, -63,
  111690. -58, -48, -53, -54, -52, -52, -57, -64,
  111691. -66, -76, -83, -81, -85, -85, -90, -95,
  111692. -98, -101, -103, -106, -108, -111, -999, -999,
  111693. -999, -999, -999, -999, -999, -999, -999, -999,
  111694. -999, -999, -999, -999, -999, -999, -999, -999},
  111695. {-999, -999, -999, -999, -999, -999, -999, -999,
  111696. -999, -999, -999, -105, -95, -86, -74, -53,
  111697. -50, -38, -43, -49, -43, -42, -39, -39,
  111698. -46, -52, -57, -56, -72, -69, -74, -81,
  111699. -87, -92, -94, -97, -99, -102, -105, -108,
  111700. -999, -999, -999, -999, -999, -999, -999, -999,
  111701. -999, -999, -999, -999, -999, -999, -999, -999},
  111702. {-999, -999, -999, -999, -999, -999, -999, -999,
  111703. -999, -999, -108, -99, -90, -76, -66, -45,
  111704. -43, -41, -44, -47, -43, -47, -40, -30,
  111705. -31, -31, -39, -33, -40, -41, -43, -53,
  111706. -59, -70, -73, -77, -79, -82, -84, -87,
  111707. -999, -999, -999, -999, -999, -999, -999, -999,
  111708. -999, -999, -999, -999, -999, -999, -999, -999}},
  111709. /* 4000 Hz */
  111710. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111711. -999, -999, -999, -999, -999, -110, -91, -76,
  111712. -75, -85, -93, -98, -104, -110, -999, -999,
  111713. -999, -999, -999, -999, -999, -999, -999, -999,
  111714. -999, -999, -999, -999, -999, -999, -999, -999,
  111715. -999, -999, -999, -999, -999, -999, -999, -999,
  111716. -999, -999, -999, -999, -999, -999, -999, -999},
  111717. {-999, -999, -999, -999, -999, -999, -999, -999,
  111718. -999, -999, -999, -999, -999, -110, -91, -70,
  111719. -70, -75, -86, -89, -94, -98, -101, -106,
  111720. -110, -999, -999, -999, -999, -999, -999, -999,
  111721. -999, -999, -999, -999, -999, -999, -999, -999,
  111722. -999, -999, -999, -999, -999, -999, -999, -999,
  111723. -999, -999, -999, -999, -999, -999, -999, -999},
  111724. {-999, -999, -999, -999, -999, -999, -999, -999,
  111725. -999, -999, -999, -999, -110, -95, -80, -60,
  111726. -65, -64, -74, -83, -88, -91, -95, -99,
  111727. -103, -107, -110, -999, -999, -999, -999, -999,
  111728. -999, -999, -999, -999, -999, -999, -999, -999,
  111729. -999, -999, -999, -999, -999, -999, -999, -999,
  111730. -999, -999, -999, -999, -999, -999, -999, -999},
  111731. {-999, -999, -999, -999, -999, -999, -999, -999,
  111732. -999, -999, -999, -999, -110, -95, -80, -58,
  111733. -55, -49, -66, -68, -71, -78, -78, -80,
  111734. -88, -85, -89, -97, -100, -105, -110, -999,
  111735. -999, -999, -999, -999, -999, -999, -999, -999,
  111736. -999, -999, -999, -999, -999, -999, -999, -999,
  111737. -999, -999, -999, -999, -999, -999, -999, -999},
  111738. {-999, -999, -999, -999, -999, -999, -999, -999,
  111739. -999, -999, -999, -999, -110, -95, -80, -53,
  111740. -52, -41, -59, -59, -49, -58, -56, -63,
  111741. -86, -79, -90, -93, -98, -103, -107, -112,
  111742. -999, -999, -999, -999, -999, -999, -999, -999,
  111743. -999, -999, -999, -999, -999, -999, -999, -999,
  111744. -999, -999, -999, -999, -999, -999, -999, -999},
  111745. {-999, -999, -999, -999, -999, -999, -999, -999,
  111746. -999, -999, -999, -110, -97, -91, -73, -45,
  111747. -40, -33, -53, -61, -49, -54, -50, -50,
  111748. -60, -52, -67, -74, -81, -92, -96, -100,
  111749. -105, -110, -999, -999, -999, -999, -999, -999,
  111750. -999, -999, -999, -999, -999, -999, -999, -999,
  111751. -999, -999, -999, -999, -999, -999, -999, -999}},
  111752. /* 5657 Hz */
  111753. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111754. -999, -999, -999, -113, -106, -99, -92, -77,
  111755. -80, -88, -97, -106, -115, -999, -999, -999,
  111756. -999, -999, -999, -999, -999, -999, -999, -999,
  111757. -999, -999, -999, -999, -999, -999, -999, -999,
  111758. -999, -999, -999, -999, -999, -999, -999, -999,
  111759. -999, -999, -999, -999, -999, -999, -999, -999},
  111760. {-999, -999, -999, -999, -999, -999, -999, -999,
  111761. -999, -999, -116, -109, -102, -95, -89, -74,
  111762. -72, -88, -87, -95, -102, -109, -116, -999,
  111763. -999, -999, -999, -999, -999, -999, -999, -999,
  111764. -999, -999, -999, -999, -999, -999, -999, -999,
  111765. -999, -999, -999, -999, -999, -999, -999, -999,
  111766. -999, -999, -999, -999, -999, -999, -999, -999},
  111767. {-999, -999, -999, -999, -999, -999, -999, -999,
  111768. -999, -999, -116, -109, -102, -95, -89, -75,
  111769. -66, -74, -77, -78, -86, -87, -90, -96,
  111770. -105, -115, -999, -999, -999, -999, -999, -999,
  111771. -999, -999, -999, -999, -999, -999, -999, -999,
  111772. -999, -999, -999, -999, -999, -999, -999, -999,
  111773. -999, -999, -999, -999, -999, -999, -999, -999},
  111774. {-999, -999, -999, -999, -999, -999, -999, -999,
  111775. -999, -999, -115, -108, -101, -94, -88, -66,
  111776. -56, -61, -70, -65, -78, -72, -83, -84,
  111777. -93, -98, -105, -110, -999, -999, -999, -999,
  111778. -999, -999, -999, -999, -999, -999, -999, -999,
  111779. -999, -999, -999, -999, -999, -999, -999, -999,
  111780. -999, -999, -999, -999, -999, -999, -999, -999},
  111781. {-999, -999, -999, -999, -999, -999, -999, -999,
  111782. -999, -999, -110, -105, -95, -89, -82, -57,
  111783. -52, -52, -59, -56, -59, -58, -69, -67,
  111784. -88, -82, -82, -89, -94, -100, -108, -999,
  111785. -999, -999, -999, -999, -999, -999, -999, -999,
  111786. -999, -999, -999, -999, -999, -999, -999, -999,
  111787. -999, -999, -999, -999, -999, -999, -999, -999},
  111788. {-999, -999, -999, -999, -999, -999, -999, -999,
  111789. -999, -110, -101, -96, -90, -83, -77, -54,
  111790. -43, -38, -50, -48, -52, -48, -42, -42,
  111791. -51, -52, -53, -59, -65, -71, -78, -85,
  111792. -95, -999, -999, -999, -999, -999, -999, -999,
  111793. -999, -999, -999, -999, -999, -999, -999, -999,
  111794. -999, -999, -999, -999, -999, -999, -999, -999}},
  111795. /* 8000 Hz */
  111796. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111797. -999, -999, -999, -999, -120, -105, -86, -68,
  111798. -78, -79, -90, -100, -110, -999, -999, -999,
  111799. -999, -999, -999, -999, -999, -999, -999, -999,
  111800. -999, -999, -999, -999, -999, -999, -999, -999,
  111801. -999, -999, -999, -999, -999, -999, -999, -999,
  111802. -999, -999, -999, -999, -999, -999, -999, -999},
  111803. {-999, -999, -999, -999, -999, -999, -999, -999,
  111804. -999, -999, -999, -999, -120, -105, -86, -66,
  111805. -73, -77, -88, -96, -105, -115, -999, -999,
  111806. -999, -999, -999, -999, -999, -999, -999, -999,
  111807. -999, -999, -999, -999, -999, -999, -999, -999,
  111808. -999, -999, -999, -999, -999, -999, -999, -999,
  111809. -999, -999, -999, -999, -999, -999, -999, -999},
  111810. {-999, -999, -999, -999, -999, -999, -999, -999,
  111811. -999, -999, -999, -120, -105, -92, -80, -61,
  111812. -64, -68, -80, -87, -92, -100, -110, -999,
  111813. -999, -999, -999, -999, -999, -999, -999, -999,
  111814. -999, -999, -999, -999, -999, -999, -999, -999,
  111815. -999, -999, -999, -999, -999, -999, -999, -999,
  111816. -999, -999, -999, -999, -999, -999, -999, -999},
  111817. {-999, -999, -999, -999, -999, -999, -999, -999,
  111818. -999, -999, -999, -120, -104, -91, -79, -52,
  111819. -60, -54, -64, -69, -77, -80, -82, -84,
  111820. -85, -87, -88, -90, -999, -999, -999, -999,
  111821. -999, -999, -999, -999, -999, -999, -999, -999,
  111822. -999, -999, -999, -999, -999, -999, -999, -999,
  111823. -999, -999, -999, -999, -999, -999, -999, -999},
  111824. {-999, -999, -999, -999, -999, -999, -999, -999,
  111825. -999, -999, -999, -118, -100, -87, -77, -49,
  111826. -50, -44, -58, -61, -61, -67, -65, -62,
  111827. -62, -62, -65, -68, -999, -999, -999, -999,
  111828. -999, -999, -999, -999, -999, -999, -999, -999,
  111829. -999, -999, -999, -999, -999, -999, -999, -999,
  111830. -999, -999, -999, -999, -999, -999, -999, -999},
  111831. {-999, -999, -999, -999, -999, -999, -999, -999,
  111832. -999, -999, -999, -115, -98, -84, -62, -49,
  111833. -44, -38, -46, -49, -49, -46, -39, -37,
  111834. -39, -40, -42, -43, -999, -999, -999, -999,
  111835. -999, -999, -999, -999, -999, -999, -999, -999,
  111836. -999, -999, -999, -999, -999, -999, -999, -999,
  111837. -999, -999, -999, -999, -999, -999, -999, -999}},
  111838. /* 11314 Hz */
  111839. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111840. -999, -999, -999, -999, -999, -110, -88, -74,
  111841. -77, -82, -82, -85, -90, -94, -99, -104,
  111842. -999, -999, -999, -999, -999, -999, -999, -999,
  111843. -999, -999, -999, -999, -999, -999, -999, -999,
  111844. -999, -999, -999, -999, -999, -999, -999, -999,
  111845. -999, -999, -999, -999, -999, -999, -999, -999},
  111846. {-999, -999, -999, -999, -999, -999, -999, -999,
  111847. -999, -999, -999, -999, -999, -110, -88, -66,
  111848. -70, -81, -80, -81, -84, -88, -91, -93,
  111849. -999, -999, -999, -999, -999, -999, -999, -999,
  111850. -999, -999, -999, -999, -999, -999, -999, -999,
  111851. -999, -999, -999, -999, -999, -999, -999, -999,
  111852. -999, -999, -999, -999, -999, -999, -999, -999},
  111853. {-999, -999, -999, -999, -999, -999, -999, -999,
  111854. -999, -999, -999, -999, -999, -110, -88, -61,
  111855. -63, -70, -71, -74, -77, -80, -83, -85,
  111856. -999, -999, -999, -999, -999, -999, -999, -999,
  111857. -999, -999, -999, -999, -999, -999, -999, -999,
  111858. -999, -999, -999, -999, -999, -999, -999, -999,
  111859. -999, -999, -999, -999, -999, -999, -999, -999},
  111860. {-999, -999, -999, -999, -999, -999, -999, -999,
  111861. -999, -999, -999, -999, -999, -110, -86, -62,
  111862. -63, -62, -62, -58, -52, -50, -50, -52,
  111863. -54, -999, -999, -999, -999, -999, -999, -999,
  111864. -999, -999, -999, -999, -999, -999, -999, -999,
  111865. -999, -999, -999, -999, -999, -999, -999, -999,
  111866. -999, -999, -999, -999, -999, -999, -999, -999},
  111867. {-999, -999, -999, -999, -999, -999, -999, -999,
  111868. -999, -999, -999, -999, -118, -108, -84, -53,
  111869. -50, -50, -50, -55, -47, -45, -40, -40,
  111870. -40, -999, -999, -999, -999, -999, -999, -999,
  111871. -999, -999, -999, -999, -999, -999, -999, -999,
  111872. -999, -999, -999, -999, -999, -999, -999, -999,
  111873. -999, -999, -999, -999, -999, -999, -999, -999},
  111874. {-999, -999, -999, -999, -999, -999, -999, -999,
  111875. -999, -999, -999, -999, -118, -100, -73, -43,
  111876. -37, -42, -43, -53, -38, -37, -35, -35,
  111877. -38, -999, -999, -999, -999, -999, -999, -999,
  111878. -999, -999, -999, -999, -999, -999, -999, -999,
  111879. -999, -999, -999, -999, -999, -999, -999, -999,
  111880. -999, -999, -999, -999, -999, -999, -999, -999}},
  111881. /* 16000 Hz */
  111882. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111883. -999, -999, -999, -110, -100, -91, -84, -74,
  111884. -80, -80, -80, -80, -80, -999, -999, -999,
  111885. -999, -999, -999, -999, -999, -999, -999, -999,
  111886. -999, -999, -999, -999, -999, -999, -999, -999,
  111887. -999, -999, -999, -999, -999, -999, -999, -999,
  111888. -999, -999, -999, -999, -999, -999, -999, -999},
  111889. {-999, -999, -999, -999, -999, -999, -999, -999,
  111890. -999, -999, -999, -110, -100, -91, -84, -74,
  111891. -68, -68, -68, -68, -68, -999, -999, -999,
  111892. -999, -999, -999, -999, -999, -999, -999, -999,
  111893. -999, -999, -999, -999, -999, -999, -999, -999,
  111894. -999, -999, -999, -999, -999, -999, -999, -999,
  111895. -999, -999, -999, -999, -999, -999, -999, -999},
  111896. {-999, -999, -999, -999, -999, -999, -999, -999,
  111897. -999, -999, -999, -110, -100, -86, -78, -70,
  111898. -60, -45, -30, -21, -999, -999, -999, -999,
  111899. -999, -999, -999, -999, -999, -999, -999, -999,
  111900. -999, -999, -999, -999, -999, -999, -999, -999,
  111901. -999, -999, -999, -999, -999, -999, -999, -999,
  111902. -999, -999, -999, -999, -999, -999, -999, -999},
  111903. {-999, -999, -999, -999, -999, -999, -999, -999,
  111904. -999, -999, -999, -110, -100, -87, -78, -67,
  111905. -48, -38, -29, -21, -999, -999, -999, -999,
  111906. -999, -999, -999, -999, -999, -999, -999, -999,
  111907. -999, -999, -999, -999, -999, -999, -999, -999,
  111908. -999, -999, -999, -999, -999, -999, -999, -999,
  111909. -999, -999, -999, -999, -999, -999, -999, -999},
  111910. {-999, -999, -999, -999, -999, -999, -999, -999,
  111911. -999, -999, -999, -110, -100, -86, -69, -56,
  111912. -45, -35, -33, -29, -999, -999, -999, -999,
  111913. -999, -999, -999, -999, -999, -999, -999, -999,
  111914. -999, -999, -999, -999, -999, -999, -999, -999,
  111915. -999, -999, -999, -999, -999, -999, -999, -999,
  111916. -999, -999, -999, -999, -999, -999, -999, -999},
  111917. {-999, -999, -999, -999, -999, -999, -999, -999,
  111918. -999, -999, -999, -110, -100, -83, -71, -48,
  111919. -27, -38, -37, -34, -999, -999, -999, -999,
  111920. -999, -999, -999, -999, -999, -999, -999, -999,
  111921. -999, -999, -999, -999, -999, -999, -999, -999,
  111922. -999, -999, -999, -999, -999, -999, -999, -999,
  111923. -999, -999, -999, -999, -999, -999, -999, -999}}
  111924. };
  111925. #endif
  111926. /********* End of inlined file: masking.h *********/
  111927. #define NEGINF -9999.f
  111928. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  111929. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  111930. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  111931. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111932. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111933. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  111934. look->channels=vi->channels;
  111935. look->ampmax=-9999.;
  111936. look->gi=gi;
  111937. return(look);
  111938. }
  111939. void _vp_global_free(vorbis_look_psy_global *look){
  111940. if(look){
  111941. memset(look,0,sizeof(*look));
  111942. _ogg_free(look);
  111943. }
  111944. }
  111945. void _vi_gpsy_free(vorbis_info_psy_global *i){
  111946. if(i){
  111947. memset(i,0,sizeof(*i));
  111948. _ogg_free(i);
  111949. }
  111950. }
  111951. void _vi_psy_free(vorbis_info_psy *i){
  111952. if(i){
  111953. memset(i,0,sizeof(*i));
  111954. _ogg_free(i);
  111955. }
  111956. }
  111957. static void min_curve(float *c,
  111958. float *c2){
  111959. int i;
  111960. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  111961. }
  111962. static void max_curve(float *c,
  111963. float *c2){
  111964. int i;
  111965. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  111966. }
  111967. static void attenuate_curve(float *c,float att){
  111968. int i;
  111969. for(i=0;i<EHMER_MAX;i++)
  111970. c[i]+=att;
  111971. }
  111972. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  111973. float center_boost, float center_decay_rate){
  111974. int i,j,k,m;
  111975. float ath[EHMER_MAX];
  111976. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  111977. float athc[P_LEVELS][EHMER_MAX];
  111978. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  111979. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  111980. memset(workc,0,sizeof(workc));
  111981. for(i=0;i<P_BANDS;i++){
  111982. /* we add back in the ATH to avoid low level curves falling off to
  111983. -infinity and unnecessarily cutting off high level curves in the
  111984. curve limiting (last step). */
  111985. /* A half-band's settings must be valid over the whole band, and
  111986. it's better to mask too little than too much */
  111987. int ath_offset=i*4;
  111988. for(j=0;j<EHMER_MAX;j++){
  111989. float min=999.;
  111990. for(k=0;k<4;k++)
  111991. if(j+k+ath_offset<MAX_ATH){
  111992. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  111993. }else{
  111994. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  111995. }
  111996. ath[j]=min;
  111997. }
  111998. /* copy curves into working space, replicate the 50dB curve to 30
  111999. and 40, replicate the 100dB curve to 110 */
  112000. for(j=0;j<6;j++)
  112001. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  112002. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  112003. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  112004. /* apply centered curve boost/decay */
  112005. for(j=0;j<P_LEVELS;j++){
  112006. for(k=0;k<EHMER_MAX;k++){
  112007. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  112008. if(adj<0. && center_boost>0)adj=0.;
  112009. if(adj>0. && center_boost<0)adj=0.;
  112010. workc[i][j][k]+=adj;
  112011. }
  112012. }
  112013. /* normalize curves so the driving amplitude is 0dB */
  112014. /* make temp curves with the ATH overlayed */
  112015. for(j=0;j<P_LEVELS;j++){
  112016. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  112017. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  112018. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  112019. max_curve(athc[j],workc[i][j]);
  112020. }
  112021. /* Now limit the louder curves.
  112022. the idea is this: We don't know what the playback attenuation
  112023. will be; 0dB SL moves every time the user twiddles the volume
  112024. knob. So that means we have to use a single 'most pessimal' curve
  112025. for all masking amplitudes, right? Wrong. The *loudest* sound
  112026. can be in (we assume) a range of ...+100dB] SL. However, sounds
  112027. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  112028. etc... */
  112029. for(j=1;j<P_LEVELS;j++){
  112030. min_curve(athc[j],athc[j-1]);
  112031. min_curve(workc[i][j],athc[j]);
  112032. }
  112033. }
  112034. for(i=0;i<P_BANDS;i++){
  112035. int hi_curve,lo_curve,bin;
  112036. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  112037. /* low frequency curves are measured with greater resolution than
  112038. the MDCT/FFT will actually give us; we want the curve applied
  112039. to the tone data to be pessimistic and thus apply the minimum
  112040. masking possible for a given bin. That means that a single bin
  112041. could span more than one octave and that the curve will be a
  112042. composite of multiple octaves. It also may mean that a single
  112043. bin may span > an eighth of an octave and that the eighth
  112044. octave values may also be composited. */
  112045. /* which octave curves will we be compositing? */
  112046. bin=floor(fromOC(i*.5)/binHz);
  112047. lo_curve= ceil(toOC(bin*binHz+1)*2);
  112048. hi_curve= floor(toOC((bin+1)*binHz)*2);
  112049. if(lo_curve>i)lo_curve=i;
  112050. if(lo_curve<0)lo_curve=0;
  112051. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  112052. for(m=0;m<P_LEVELS;m++){
  112053. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  112054. for(j=0;j<n;j++)brute_buffer[j]=999.;
  112055. /* render the curve into bins, then pull values back into curve.
  112056. The point is that any inherent subsampling aliasing results in
  112057. a safe minimum */
  112058. for(k=lo_curve;k<=hi_curve;k++){
  112059. int l=0;
  112060. for(j=0;j<EHMER_MAX;j++){
  112061. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  112062. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  112063. if(lo_bin<0)lo_bin=0;
  112064. if(lo_bin>n)lo_bin=n;
  112065. if(lo_bin<l)l=lo_bin;
  112066. if(hi_bin<0)hi_bin=0;
  112067. if(hi_bin>n)hi_bin=n;
  112068. for(;l<hi_bin && l<n;l++)
  112069. if(brute_buffer[l]>workc[k][m][j])
  112070. brute_buffer[l]=workc[k][m][j];
  112071. }
  112072. for(;l<n;l++)
  112073. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  112074. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  112075. }
  112076. /* be equally paranoid about being valid up to next half ocatve */
  112077. if(i+1<P_BANDS){
  112078. int l=0;
  112079. k=i+1;
  112080. for(j=0;j<EHMER_MAX;j++){
  112081. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  112082. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  112083. if(lo_bin<0)lo_bin=0;
  112084. if(lo_bin>n)lo_bin=n;
  112085. if(lo_bin<l)l=lo_bin;
  112086. if(hi_bin<0)hi_bin=0;
  112087. if(hi_bin>n)hi_bin=n;
  112088. for(;l<hi_bin && l<n;l++)
  112089. if(brute_buffer[l]>workc[k][m][j])
  112090. brute_buffer[l]=workc[k][m][j];
  112091. }
  112092. for(;l<n;l++)
  112093. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  112094. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  112095. }
  112096. for(j=0;j<EHMER_MAX;j++){
  112097. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  112098. if(bin<0){
  112099. ret[i][m][j+2]=-999.;
  112100. }else{
  112101. if(bin>=n){
  112102. ret[i][m][j+2]=-999.;
  112103. }else{
  112104. ret[i][m][j+2]=brute_buffer[bin];
  112105. }
  112106. }
  112107. }
  112108. /* add fenceposts */
  112109. for(j=0;j<EHMER_OFFSET;j++)
  112110. if(ret[i][m][j+2]>-200.f)break;
  112111. ret[i][m][0]=j;
  112112. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  112113. if(ret[i][m][j+2]>-200.f)
  112114. break;
  112115. ret[i][m][1]=j;
  112116. }
  112117. }
  112118. return(ret);
  112119. }
  112120. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  112121. vorbis_info_psy_global *gi,int n,long rate){
  112122. long i,j,lo=-99,hi=1;
  112123. long maxoc;
  112124. memset(p,0,sizeof(*p));
  112125. p->eighth_octave_lines=gi->eighth_octave_lines;
  112126. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  112127. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  112128. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  112129. p->total_octave_lines=maxoc-p->firstoc+1;
  112130. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  112131. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  112132. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  112133. p->vi=vi;
  112134. p->n=n;
  112135. p->rate=rate;
  112136. /* AoTuV HF weighting */
  112137. p->m_val = 1.;
  112138. if(rate < 26000) p->m_val = 0;
  112139. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  112140. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  112141. /* set up the lookups for a given blocksize and sample rate */
  112142. for(i=0,j=0;i<MAX_ATH-1;i++){
  112143. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  112144. float base=ATH[i];
  112145. if(j<endpos){
  112146. float delta=(ATH[i+1]-base)/(endpos-j);
  112147. for(;j<endpos && j<n;j++){
  112148. p->ath[j]=base+100.;
  112149. base+=delta;
  112150. }
  112151. }
  112152. }
  112153. for(i=0;i<n;i++){
  112154. float bark=toBARK(rate/(2*n)*i);
  112155. for(;lo+vi->noisewindowlomin<i &&
  112156. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  112157. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  112158. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  112159. p->bark[i]=((lo-1)<<16)+(hi-1);
  112160. }
  112161. for(i=0;i<n;i++)
  112162. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  112163. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  112164. vi->tone_centerboost,vi->tone_decay);
  112165. /* set up rolling noise median */
  112166. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  112167. for(i=0;i<P_NOISECURVES;i++)
  112168. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  112169. for(i=0;i<n;i++){
  112170. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  112171. int inthalfoc;
  112172. float del;
  112173. if(halfoc<0)halfoc=0;
  112174. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  112175. inthalfoc=(int)halfoc;
  112176. del=halfoc-inthalfoc;
  112177. for(j=0;j<P_NOISECURVES;j++)
  112178. p->noiseoffset[j][i]=
  112179. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  112180. p->vi->noiseoff[j][inthalfoc+1]*del;
  112181. }
  112182. #if 0
  112183. {
  112184. static int ls=0;
  112185. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  112186. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  112187. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  112188. }
  112189. #endif
  112190. }
  112191. void _vp_psy_clear(vorbis_look_psy *p){
  112192. int i,j;
  112193. if(p){
  112194. if(p->ath)_ogg_free(p->ath);
  112195. if(p->octave)_ogg_free(p->octave);
  112196. if(p->bark)_ogg_free(p->bark);
  112197. if(p->tonecurves){
  112198. for(i=0;i<P_BANDS;i++){
  112199. for(j=0;j<P_LEVELS;j++){
  112200. _ogg_free(p->tonecurves[i][j]);
  112201. }
  112202. _ogg_free(p->tonecurves[i]);
  112203. }
  112204. _ogg_free(p->tonecurves);
  112205. }
  112206. if(p->noiseoffset){
  112207. for(i=0;i<P_NOISECURVES;i++){
  112208. _ogg_free(p->noiseoffset[i]);
  112209. }
  112210. _ogg_free(p->noiseoffset);
  112211. }
  112212. memset(p,0,sizeof(*p));
  112213. }
  112214. }
  112215. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  112216. static void seed_curve(float *seed,
  112217. const float **curves,
  112218. float amp,
  112219. int oc, int n,
  112220. int linesper,float dBoffset){
  112221. int i,post1;
  112222. int seedptr;
  112223. const float *posts,*curve;
  112224. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  112225. choice=max(choice,0);
  112226. choice=min(choice,P_LEVELS-1);
  112227. posts=curves[choice];
  112228. curve=posts+2;
  112229. post1=(int)posts[1];
  112230. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  112231. for(i=posts[0];i<post1;i++){
  112232. if(seedptr>0){
  112233. float lin=amp+curve[i];
  112234. if(seed[seedptr]<lin)seed[seedptr]=lin;
  112235. }
  112236. seedptr+=linesper;
  112237. if(seedptr>=n)break;
  112238. }
  112239. }
  112240. static void seed_loop(vorbis_look_psy *p,
  112241. const float ***curves,
  112242. const float *f,
  112243. const float *flr,
  112244. float *seed,
  112245. float specmax){
  112246. vorbis_info_psy *vi=p->vi;
  112247. long n=p->n,i;
  112248. float dBoffset=vi->max_curve_dB-specmax;
  112249. /* prime the working vector with peak values */
  112250. for(i=0;i<n;i++){
  112251. float max=f[i];
  112252. long oc=p->octave[i];
  112253. while(i+1<n && p->octave[i+1]==oc){
  112254. i++;
  112255. if(f[i]>max)max=f[i];
  112256. }
  112257. if(max+6.f>flr[i]){
  112258. oc=oc>>p->shiftoc;
  112259. if(oc>=P_BANDS)oc=P_BANDS-1;
  112260. if(oc<0)oc=0;
  112261. seed_curve(seed,
  112262. curves[oc],
  112263. max,
  112264. p->octave[i]-p->firstoc,
  112265. p->total_octave_lines,
  112266. p->eighth_octave_lines,
  112267. dBoffset);
  112268. }
  112269. }
  112270. }
  112271. static void seed_chase(float *seeds, int linesper, long n){
  112272. long *posstack=(long*)alloca(n*sizeof(*posstack));
  112273. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  112274. long stack=0;
  112275. long pos=0;
  112276. long i;
  112277. for(i=0;i<n;i++){
  112278. if(stack<2){
  112279. posstack[stack]=i;
  112280. ampstack[stack++]=seeds[i];
  112281. }else{
  112282. while(1){
  112283. if(seeds[i]<ampstack[stack-1]){
  112284. posstack[stack]=i;
  112285. ampstack[stack++]=seeds[i];
  112286. break;
  112287. }else{
  112288. if(i<posstack[stack-1]+linesper){
  112289. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  112290. i<posstack[stack-2]+linesper){
  112291. /* we completely overlap, making stack-1 irrelevant. pop it */
  112292. stack--;
  112293. continue;
  112294. }
  112295. }
  112296. posstack[stack]=i;
  112297. ampstack[stack++]=seeds[i];
  112298. break;
  112299. }
  112300. }
  112301. }
  112302. }
  112303. /* the stack now contains only the positions that are relevant. Scan
  112304. 'em straight through */
  112305. for(i=0;i<stack;i++){
  112306. long endpos;
  112307. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  112308. endpos=posstack[i+1];
  112309. }else{
  112310. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  112311. discarded in short frames */
  112312. }
  112313. if(endpos>n)endpos=n;
  112314. for(;pos<endpos;pos++)
  112315. seeds[pos]=ampstack[i];
  112316. }
  112317. /* there. Linear time. I now remember this was on a problem set I
  112318. had in Grad Skool... I didn't solve it at the time ;-) */
  112319. }
  112320. /* bleaugh, this is more complicated than it needs to be */
  112321. #include<stdio.h>
  112322. static void max_seeds(vorbis_look_psy *p,
  112323. float *seed,
  112324. float *flr){
  112325. long n=p->total_octave_lines;
  112326. int linesper=p->eighth_octave_lines;
  112327. long linpos=0;
  112328. long pos;
  112329. seed_chase(seed,linesper,n); /* for masking */
  112330. pos=p->octave[0]-p->firstoc-(linesper>>1);
  112331. while(linpos+1<p->n){
  112332. float minV=seed[pos];
  112333. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  112334. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  112335. while(pos+1<=end){
  112336. pos++;
  112337. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  112338. minV=seed[pos];
  112339. }
  112340. end=pos+p->firstoc;
  112341. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  112342. if(flr[linpos]<minV)flr[linpos]=minV;
  112343. }
  112344. {
  112345. float minV=seed[p->total_octave_lines-1];
  112346. for(;linpos<p->n;linpos++)
  112347. if(flr[linpos]<minV)flr[linpos]=minV;
  112348. }
  112349. }
  112350. static void bark_noise_hybridmp(int n,const long *b,
  112351. const float *f,
  112352. float *noise,
  112353. const float offset,
  112354. const int fixed){
  112355. float *N=(float*) alloca(n*sizeof(*N));
  112356. float *X=(float*) alloca(n*sizeof(*N));
  112357. float *XX=(float*) alloca(n*sizeof(*N));
  112358. float *Y=(float*) alloca(n*sizeof(*N));
  112359. float *XY=(float*) alloca(n*sizeof(*N));
  112360. float tN, tX, tXX, tY, tXY;
  112361. int i;
  112362. int lo, hi;
  112363. float R, A, B, D;
  112364. float w, x, y;
  112365. tN = tX = tXX = tY = tXY = 0.f;
  112366. y = f[0] + offset;
  112367. if (y < 1.f) y = 1.f;
  112368. w = y * y * .5;
  112369. tN += w;
  112370. tX += w;
  112371. tY += w * y;
  112372. N[0] = tN;
  112373. X[0] = tX;
  112374. XX[0] = tXX;
  112375. Y[0] = tY;
  112376. XY[0] = tXY;
  112377. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  112378. y = f[i] + offset;
  112379. if (y < 1.f) y = 1.f;
  112380. w = y * y;
  112381. tN += w;
  112382. tX += w * x;
  112383. tXX += w * x * x;
  112384. tY += w * y;
  112385. tXY += w * x * y;
  112386. N[i] = tN;
  112387. X[i] = tX;
  112388. XX[i] = tXX;
  112389. Y[i] = tY;
  112390. XY[i] = tXY;
  112391. }
  112392. for (i = 0, x = 0.f;; i++, x += 1.f) {
  112393. lo = b[i] >> 16;
  112394. if( lo>=0 ) break;
  112395. hi = b[i] & 0xffff;
  112396. tN = N[hi] + N[-lo];
  112397. tX = X[hi] - X[-lo];
  112398. tXX = XX[hi] + XX[-lo];
  112399. tY = Y[hi] + Y[-lo];
  112400. tXY = XY[hi] - XY[-lo];
  112401. A = tY * tXX - tX * tXY;
  112402. B = tN * tXY - tX * tY;
  112403. D = tN * tXX - tX * tX;
  112404. R = (A + x * B) / D;
  112405. if (R < 0.f)
  112406. R = 0.f;
  112407. noise[i] = R - offset;
  112408. }
  112409. for ( ;; i++, x += 1.f) {
  112410. lo = b[i] >> 16;
  112411. hi = b[i] & 0xffff;
  112412. if(hi>=n)break;
  112413. tN = N[hi] - N[lo];
  112414. tX = X[hi] - X[lo];
  112415. tXX = XX[hi] - XX[lo];
  112416. tY = Y[hi] - Y[lo];
  112417. tXY = XY[hi] - XY[lo];
  112418. A = tY * tXX - tX * tXY;
  112419. B = tN * tXY - tX * tY;
  112420. D = tN * tXX - tX * tX;
  112421. R = (A + x * B) / D;
  112422. if (R < 0.f) R = 0.f;
  112423. noise[i] = R - offset;
  112424. }
  112425. for ( ; i < n; i++, x += 1.f) {
  112426. R = (A + x * B) / D;
  112427. if (R < 0.f) R = 0.f;
  112428. noise[i] = R - offset;
  112429. }
  112430. if (fixed <= 0) return;
  112431. for (i = 0, x = 0.f;; i++, x += 1.f) {
  112432. hi = i + fixed / 2;
  112433. lo = hi - fixed;
  112434. if(lo>=0)break;
  112435. tN = N[hi] + N[-lo];
  112436. tX = X[hi] - X[-lo];
  112437. tXX = XX[hi] + XX[-lo];
  112438. tY = Y[hi] + Y[-lo];
  112439. tXY = XY[hi] - XY[-lo];
  112440. A = tY * tXX - tX * tXY;
  112441. B = tN * tXY - tX * tY;
  112442. D = tN * tXX - tX * tX;
  112443. R = (A + x * B) / D;
  112444. if (R - offset < noise[i]) noise[i] = R - offset;
  112445. }
  112446. for ( ;; i++, x += 1.f) {
  112447. hi = i + fixed / 2;
  112448. lo = hi - fixed;
  112449. if(hi>=n)break;
  112450. tN = N[hi] - N[lo];
  112451. tX = X[hi] - X[lo];
  112452. tXX = XX[hi] - XX[lo];
  112453. tY = Y[hi] - Y[lo];
  112454. tXY = XY[hi] - XY[lo];
  112455. A = tY * tXX - tX * tXY;
  112456. B = tN * tXY - tX * tY;
  112457. D = tN * tXX - tX * tX;
  112458. R = (A + x * B) / D;
  112459. if (R - offset < noise[i]) noise[i] = R - offset;
  112460. }
  112461. for ( ; i < n; i++, x += 1.f) {
  112462. R = (A + x * B) / D;
  112463. if (R - offset < noise[i]) noise[i] = R - offset;
  112464. }
  112465. }
  112466. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  112467. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  112468. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  112469. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  112470. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  112471. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  112472. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  112473. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  112474. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  112475. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  112476. 973377.F, 913981.F, 858210.F, 805842.F,
  112477. 756669.F, 710497.F, 667142.F, 626433.F,
  112478. 588208.F, 552316.F, 518613.F, 486967.F,
  112479. 457252.F, 429351.F, 403152.F, 378551.F,
  112480. 355452.F, 333762.F, 313396.F, 294273.F,
  112481. 276316.F, 259455.F, 243623.F, 228757.F,
  112482. 214798.F, 201691.F, 189384.F, 177828.F,
  112483. 166977.F, 156788.F, 147221.F, 138237.F,
  112484. 129802.F, 121881.F, 114444.F, 107461.F,
  112485. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  112486. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  112487. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  112488. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  112489. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  112490. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  112491. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  112492. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  112493. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  112494. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  112495. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  112496. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  112497. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  112498. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  112499. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  112500. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  112501. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  112502. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  112503. 1084.32F, 1018.15F, 956.024F, 897.687F,
  112504. 842.910F, 791.475F, 743.179F, 697.830F,
  112505. 655.249F, 615.265F, 577.722F, 542.469F,
  112506. 509.367F, 478.286F, 449.101F, 421.696F,
  112507. 395.964F, 371.803F, 349.115F, 327.812F,
  112508. 307.809F, 289.026F, 271.390F, 254.830F,
  112509. 239.280F, 224.679F, 210.969F, 198.096F,
  112510. 186.008F, 174.658F, 164.000F, 153.993F,
  112511. 144.596F, 135.773F, 127.488F, 119.708F,
  112512. 112.404F, 105.545F, 99.1046F, 93.0572F,
  112513. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  112514. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  112515. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  112516. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  112517. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  112518. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  112519. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  112520. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  112521. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  112522. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  112523. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  112524. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  112525. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  112526. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  112527. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  112528. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  112529. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  112530. 1.20790F, 1.13419F, 1.06499F, 1.F
  112531. };
  112532. void _vp_remove_floor(vorbis_look_psy *p,
  112533. float *mdct,
  112534. int *codedflr,
  112535. float *residue,
  112536. int sliding_lowpass){
  112537. int i,n=p->n;
  112538. if(sliding_lowpass>n)sliding_lowpass=n;
  112539. for(i=0;i<sliding_lowpass;i++){
  112540. residue[i]=
  112541. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  112542. }
  112543. for(;i<n;i++)
  112544. residue[i]=0.;
  112545. }
  112546. void _vp_noisemask(vorbis_look_psy *p,
  112547. float *logmdct,
  112548. float *logmask){
  112549. int i,n=p->n;
  112550. float *work=(float*) alloca(n*sizeof(*work));
  112551. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  112552. 140.,-1);
  112553. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  112554. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  112555. p->vi->noisewindowfixed);
  112556. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  112557. #if 0
  112558. {
  112559. static int seq=0;
  112560. float work2[n];
  112561. for(i=0;i<n;i++){
  112562. work2[i]=logmask[i]+work[i];
  112563. }
  112564. if(seq&1)
  112565. _analysis_output("median2R",seq/2,work,n,1,0,0);
  112566. else
  112567. _analysis_output("median2L",seq/2,work,n,1,0,0);
  112568. if(seq&1)
  112569. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  112570. else
  112571. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  112572. seq++;
  112573. }
  112574. #endif
  112575. for(i=0;i<n;i++){
  112576. int dB=logmask[i]+.5;
  112577. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  112578. if(dB<0)dB=0;
  112579. logmask[i]= work[i]+p->vi->noisecompand[dB];
  112580. }
  112581. }
  112582. void _vp_tonemask(vorbis_look_psy *p,
  112583. float *logfft,
  112584. float *logmask,
  112585. float global_specmax,
  112586. float local_specmax){
  112587. int i,n=p->n;
  112588. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  112589. float att=local_specmax+p->vi->ath_adjatt;
  112590. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  112591. /* set the ATH (floating below localmax, not global max by a
  112592. specified att) */
  112593. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  112594. for(i=0;i<n;i++)
  112595. logmask[i]=p->ath[i]+att;
  112596. /* tone masking */
  112597. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  112598. max_seeds(p,seed,logmask);
  112599. }
  112600. void _vp_offset_and_mix(vorbis_look_psy *p,
  112601. float *noise,
  112602. float *tone,
  112603. int offset_select,
  112604. float *logmask,
  112605. float *mdct,
  112606. float *logmdct){
  112607. int i,n=p->n;
  112608. float de, coeffi, cx;/* AoTuV */
  112609. float toneatt=p->vi->tone_masteratt[offset_select];
  112610. cx = p->m_val;
  112611. for(i=0;i<n;i++){
  112612. float val= noise[i]+p->noiseoffset[offset_select][i];
  112613. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  112614. logmask[i]=max(val,tone[i]+toneatt);
  112615. /* AoTuV */
  112616. /** @ M1 **
  112617. The following codes improve a noise problem.
  112618. A fundamental idea uses the value of masking and carries out
  112619. the relative compensation of the MDCT.
  112620. However, this code is not perfect and all noise problems cannot be solved.
  112621. by Aoyumi @ 2004/04/18
  112622. */
  112623. if(offset_select == 1) {
  112624. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  112625. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  112626. if(val > coeffi){
  112627. /* mdct value is > -17.2 dB below floor */
  112628. de = 1.0-((val-coeffi)*0.005*cx);
  112629. /* pro-rated attenuation:
  112630. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  112631. -0.77 dB boost if mdct value is 0dB (relative to floor)
  112632. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  112633. etc... */
  112634. if(de < 0) de = 0.0001;
  112635. }else
  112636. /* mdct value is <= -17.2 dB below floor */
  112637. de = 1.0-((val-coeffi)*0.0003*cx);
  112638. /* pro-rated attenuation:
  112639. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  112640. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  112641. etc... */
  112642. mdct[i] *= de;
  112643. }
  112644. }
  112645. }
  112646. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  112647. vorbis_info *vi=vd->vi;
  112648. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112649. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112650. int n=ci->blocksizes[vd->W]/2;
  112651. float secs=(float)n/vi->rate;
  112652. amp+=secs*gi->ampmax_att_per_sec;
  112653. if(amp<-9999)amp=-9999;
  112654. return(amp);
  112655. }
  112656. static void couple_lossless(float A, float B,
  112657. float *qA, float *qB){
  112658. int test1=fabs(*qA)>fabs(*qB);
  112659. test1-= fabs(*qA)<fabs(*qB);
  112660. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  112661. if(test1==1){
  112662. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  112663. }else{
  112664. float temp=*qB;
  112665. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  112666. *qA=temp;
  112667. }
  112668. if(*qB>fabs(*qA)*1.9999f){
  112669. *qB= -fabs(*qA)*2.f;
  112670. *qA= -*qA;
  112671. }
  112672. }
  112673. static float hypot_lookup[32]={
  112674. -0.009935, -0.011245, -0.012726, -0.014397,
  112675. -0.016282, -0.018407, -0.020800, -0.023494,
  112676. -0.026522, -0.029923, -0.033737, -0.038010,
  112677. -0.042787, -0.048121, -0.054064, -0.060671,
  112678. -0.068000, -0.076109, -0.085054, -0.094892,
  112679. -0.105675, -0.117451, -0.130260, -0.144134,
  112680. -0.159093, -0.175146, -0.192286, -0.210490,
  112681. -0.229718, -0.249913, -0.271001, -0.292893};
  112682. static void precomputed_couple_point(float premag,
  112683. int floorA,int floorB,
  112684. float *mag, float *ang){
  112685. int test=(floorA>floorB)-1;
  112686. int offset=31-abs(floorA-floorB);
  112687. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  112688. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  112689. *mag=premag*floormag;
  112690. *ang=0.f;
  112691. }
  112692. /* just like below, this is currently set up to only do
  112693. single-step-depth coupling. Otherwise, we'd have to do more
  112694. copying (which will be inevitable later) */
  112695. /* doing the real circular magnitude calculation is audibly superior
  112696. to (A+B)/sqrt(2) */
  112697. static float dipole_hypot(float a, float b){
  112698. if(a>0.){
  112699. if(b>0.)return sqrt(a*a+b*b);
  112700. if(a>-b)return sqrt(a*a-b*b);
  112701. return -sqrt(b*b-a*a);
  112702. }
  112703. if(b<0.)return -sqrt(a*a+b*b);
  112704. if(-a>b)return -sqrt(a*a-b*b);
  112705. return sqrt(b*b-a*a);
  112706. }
  112707. static float round_hypot(float a, float b){
  112708. if(a>0.){
  112709. if(b>0.)return sqrt(a*a+b*b);
  112710. if(a>-b)return sqrt(a*a+b*b);
  112711. return -sqrt(b*b+a*a);
  112712. }
  112713. if(b<0.)return -sqrt(a*a+b*b);
  112714. if(-a>b)return -sqrt(a*a+b*b);
  112715. return sqrt(b*b+a*a);
  112716. }
  112717. /* revert to round hypot for now */
  112718. float **_vp_quantize_couple_memo(vorbis_block *vb,
  112719. vorbis_info_psy_global *g,
  112720. vorbis_look_psy *p,
  112721. vorbis_info_mapping0 *vi,
  112722. float **mdct){
  112723. int i,j,n=p->n;
  112724. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  112725. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  112726. for(i=0;i<vi->coupling_steps;i++){
  112727. float *mdctM=mdct[vi->coupling_mag[i]];
  112728. float *mdctA=mdct[vi->coupling_ang[i]];
  112729. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  112730. for(j=0;j<limit;j++)
  112731. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  112732. for(;j<n;j++)
  112733. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  112734. }
  112735. return(ret);
  112736. }
  112737. /* this is for per-channel noise normalization */
  112738. static int apsort(const void *a, const void *b){
  112739. float f1=fabs(**(float**)a);
  112740. float f2=fabs(**(float**)b);
  112741. return (f1<f2)-(f1>f2);
  112742. }
  112743. int **_vp_quantize_couple_sort(vorbis_block *vb,
  112744. vorbis_look_psy *p,
  112745. vorbis_info_mapping0 *vi,
  112746. float **mags){
  112747. if(p->vi->normal_point_p){
  112748. int i,j,k,n=p->n;
  112749. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  112750. int partition=p->vi->normal_partition;
  112751. float **work=(float**) alloca(sizeof(*work)*partition);
  112752. for(i=0;i<vi->coupling_steps;i++){
  112753. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  112754. for(j=0;j<n;j+=partition){
  112755. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  112756. qsort(work,partition,sizeof(*work),apsort);
  112757. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  112758. }
  112759. }
  112760. return(ret);
  112761. }
  112762. return(NULL);
  112763. }
  112764. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  112765. float *magnitudes,int *sortedindex){
  112766. int i,j,n=p->n;
  112767. vorbis_info_psy *vi=p->vi;
  112768. int partition=vi->normal_partition;
  112769. float **work=(float**) alloca(sizeof(*work)*partition);
  112770. int start=vi->normal_start;
  112771. for(j=start;j<n;j+=partition){
  112772. if(j+partition>n)partition=n-j;
  112773. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  112774. qsort(work,partition,sizeof(*work),apsort);
  112775. for(i=0;i<partition;i++){
  112776. sortedindex[i+j-start]=work[i]-magnitudes;
  112777. }
  112778. }
  112779. }
  112780. void _vp_noise_normalize(vorbis_look_psy *p,
  112781. float *in,float *out,int *sortedindex){
  112782. int flag=0,i,j=0,n=p->n;
  112783. vorbis_info_psy *vi=p->vi;
  112784. int partition=vi->normal_partition;
  112785. int start=vi->normal_start;
  112786. if(start>n)start=n;
  112787. if(vi->normal_channel_p){
  112788. for(;j<start;j++)
  112789. out[j]=rint(in[j]);
  112790. for(;j+partition<=n;j+=partition){
  112791. float acc=0.;
  112792. int k;
  112793. for(i=j;i<j+partition;i++)
  112794. acc+=in[i]*in[i];
  112795. for(i=0;i<partition;i++){
  112796. k=sortedindex[i+j-start];
  112797. if(in[k]*in[k]>=.25f){
  112798. out[k]=rint(in[k]);
  112799. acc-=in[k]*in[k];
  112800. flag=1;
  112801. }else{
  112802. if(acc<vi->normal_thresh)break;
  112803. out[k]=unitnorm(in[k]);
  112804. acc-=1.;
  112805. }
  112806. }
  112807. for(;i<partition;i++){
  112808. k=sortedindex[i+j-start];
  112809. out[k]=0.;
  112810. }
  112811. }
  112812. }
  112813. for(;j<n;j++)
  112814. out[j]=rint(in[j]);
  112815. }
  112816. void _vp_couple(int blobno,
  112817. vorbis_info_psy_global *g,
  112818. vorbis_look_psy *p,
  112819. vorbis_info_mapping0 *vi,
  112820. float **res,
  112821. float **mag_memo,
  112822. int **mag_sort,
  112823. int **ifloor,
  112824. int *nonzero,
  112825. int sliding_lowpass){
  112826. int i,j,k,n=p->n;
  112827. /* perform any requested channel coupling */
  112828. /* point stereo can only be used in a first stage (in this encoder)
  112829. because of the dependency on floor lookups */
  112830. for(i=0;i<vi->coupling_steps;i++){
  112831. /* once we're doing multistage coupling in which a channel goes
  112832. through more than one coupling step, the floor vector
  112833. magnitudes will also have to be recalculated an propogated
  112834. along with PCM. Right now, we're not (that will wait until 5.1
  112835. most likely), so the code isn't here yet. The memory management
  112836. here is all assuming single depth couplings anyway. */
  112837. /* make sure coupling a zero and a nonzero channel results in two
  112838. nonzero channels. */
  112839. if(nonzero[vi->coupling_mag[i]] ||
  112840. nonzero[vi->coupling_ang[i]]){
  112841. float *rM=res[vi->coupling_mag[i]];
  112842. float *rA=res[vi->coupling_ang[i]];
  112843. float *qM=rM+n;
  112844. float *qA=rA+n;
  112845. int *floorM=ifloor[vi->coupling_mag[i]];
  112846. int *floorA=ifloor[vi->coupling_ang[i]];
  112847. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  112848. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  112849. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  112850. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  112851. int pointlimit=limit;
  112852. nonzero[vi->coupling_mag[i]]=1;
  112853. nonzero[vi->coupling_ang[i]]=1;
  112854. /* The threshold of a stereo is changed with the size of n */
  112855. if(n > 1000)
  112856. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  112857. for(j=0;j<p->n;j+=partition){
  112858. float acc=0.f;
  112859. for(k=0;k<partition;k++){
  112860. int l=k+j;
  112861. if(l<sliding_lowpass){
  112862. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  112863. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  112864. precomputed_couple_point(mag_memo[i][l],
  112865. floorM[l],floorA[l],
  112866. qM+l,qA+l);
  112867. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  112868. }else{
  112869. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  112870. }
  112871. }else{
  112872. qM[l]=0.;
  112873. qA[l]=0.;
  112874. }
  112875. }
  112876. if(p->vi->normal_point_p){
  112877. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  112878. int l=mag_sort[i][j+k];
  112879. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  112880. qM[l]=unitnorm(qM[l]);
  112881. acc-=1.f;
  112882. }
  112883. }
  112884. }
  112885. }
  112886. }
  112887. }
  112888. }
  112889. /* AoTuV */
  112890. /** @ M2 **
  112891. The boost problem by the combination of noise normalization and point stereo is eased.
  112892. However, this is a temporary patch.
  112893. by Aoyumi @ 2004/04/18
  112894. */
  112895. void hf_reduction(vorbis_info_psy_global *g,
  112896. vorbis_look_psy *p,
  112897. vorbis_info_mapping0 *vi,
  112898. float **mdct){
  112899. int i,j,n=p->n, de=0.3*p->m_val;
  112900. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  112901. for(i=0; i<vi->coupling_steps; i++){
  112902. /* for(j=start; j<limit; j++){} // ???*/
  112903. for(j=limit; j<n; j++)
  112904. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  112905. }
  112906. }
  112907. #endif
  112908. /********* End of inlined file: psy.c *********/
  112909. /********* Start of inlined file: registry.c *********/
  112910. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112911. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112912. // tasks..
  112913. #ifdef _MSC_VER
  112914. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112915. #endif
  112916. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112917. #if JUCE_USE_OGGVORBIS
  112918. /* seems like major overkill now; the backend numbers will grow into
  112919. the infrastructure soon enough */
  112920. extern vorbis_func_floor floor0_exportbundle;
  112921. extern vorbis_func_floor floor1_exportbundle;
  112922. extern vorbis_func_residue residue0_exportbundle;
  112923. extern vorbis_func_residue residue1_exportbundle;
  112924. extern vorbis_func_residue residue2_exportbundle;
  112925. extern vorbis_func_mapping mapping0_exportbundle;
  112926. vorbis_func_floor *_floor_P[]={
  112927. &floor0_exportbundle,
  112928. &floor1_exportbundle,
  112929. };
  112930. vorbis_func_residue *_residue_P[]={
  112931. &residue0_exportbundle,
  112932. &residue1_exportbundle,
  112933. &residue2_exportbundle,
  112934. };
  112935. vorbis_func_mapping *_mapping_P[]={
  112936. &mapping0_exportbundle,
  112937. };
  112938. #endif
  112939. /********* End of inlined file: registry.c *********/
  112940. /********* Start of inlined file: res0.c *********/
  112941. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  112942. encode/decode loops are coded for clarity and performance is not
  112943. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  112944. it's slow. */
  112945. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112946. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112947. // tasks..
  112948. #ifdef _MSC_VER
  112949. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112950. #endif
  112951. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112952. #if JUCE_USE_OGGVORBIS
  112953. #include <stdlib.h>
  112954. #include <string.h>
  112955. #include <math.h>
  112956. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  112957. #include <stdio.h>
  112958. #endif
  112959. typedef struct {
  112960. vorbis_info_residue0 *info;
  112961. int parts;
  112962. int stages;
  112963. codebook *fullbooks;
  112964. codebook *phrasebook;
  112965. codebook ***partbooks;
  112966. int partvals;
  112967. int **decodemap;
  112968. long postbits;
  112969. long phrasebits;
  112970. long frames;
  112971. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  112972. int train_seq;
  112973. long *training_data[8][64];
  112974. float training_max[8][64];
  112975. float training_min[8][64];
  112976. float tmin;
  112977. float tmax;
  112978. #endif
  112979. } vorbis_look_residue0;
  112980. void res0_free_info(vorbis_info_residue *i){
  112981. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  112982. if(info){
  112983. memset(info,0,sizeof(*info));
  112984. _ogg_free(info);
  112985. }
  112986. }
  112987. void res0_free_look(vorbis_look_residue *i){
  112988. int j;
  112989. if(i){
  112990. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  112991. #ifdef TRAIN_RES
  112992. {
  112993. int j,k,l;
  112994. for(j=0;j<look->parts;j++){
  112995. /*fprintf(stderr,"partition %d: ",j);*/
  112996. for(k=0;k<8;k++)
  112997. if(look->training_data[k][j]){
  112998. char buffer[80];
  112999. FILE *of;
  113000. codebook *statebook=look->partbooks[j][k];
  113001. /* long and short into the same bucket by current convention */
  113002. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  113003. of=fopen(buffer,"a");
  113004. for(l=0;l<statebook->entries;l++)
  113005. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  113006. fclose(of);
  113007. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  113008. look->training_min[k][j],look->training_max[k][j]);*/
  113009. _ogg_free(look->training_data[k][j]);
  113010. look->training_data[k][j]=NULL;
  113011. }
  113012. /*fprintf(stderr,"\n");*/
  113013. }
  113014. }
  113015. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  113016. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  113017. (float)look->phrasebits/look->frames,
  113018. (float)look->postbits/look->frames,
  113019. (float)(look->postbits+look->phrasebits)/look->frames);*/
  113020. #endif
  113021. /*vorbis_info_residue0 *info=look->info;
  113022. fprintf(stderr,
  113023. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  113024. "(%g/frame) \n",look->frames,look->phrasebits,
  113025. look->resbitsflat,
  113026. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  113027. for(j=0;j<look->parts;j++){
  113028. long acc=0;
  113029. fprintf(stderr,"\t[%d] == ",j);
  113030. for(k=0;k<look->stages;k++)
  113031. if((info->secondstages[j]>>k)&1){
  113032. fprintf(stderr,"%ld,",look->resbits[j][k]);
  113033. acc+=look->resbits[j][k];
  113034. }
  113035. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  113036. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  113037. }
  113038. fprintf(stderr,"\n");*/
  113039. for(j=0;j<look->parts;j++)
  113040. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  113041. _ogg_free(look->partbooks);
  113042. for(j=0;j<look->partvals;j++)
  113043. _ogg_free(look->decodemap[j]);
  113044. _ogg_free(look->decodemap);
  113045. memset(look,0,sizeof(*look));
  113046. _ogg_free(look);
  113047. }
  113048. }
  113049. static int icount(unsigned int v){
  113050. int ret=0;
  113051. while(v){
  113052. ret+=v&1;
  113053. v>>=1;
  113054. }
  113055. return(ret);
  113056. }
  113057. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  113058. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  113059. int j,acc=0;
  113060. oggpack_write(opb,info->begin,24);
  113061. oggpack_write(opb,info->end,24);
  113062. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  113063. code with a partitioned book */
  113064. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  113065. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  113066. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  113067. bitmask of one indicates this partition class has bits to write
  113068. this pass */
  113069. for(j=0;j<info->partitions;j++){
  113070. if(ilog(info->secondstages[j])>3){
  113071. /* yes, this is a minor hack due to not thinking ahead */
  113072. oggpack_write(opb,info->secondstages[j],3);
  113073. oggpack_write(opb,1,1);
  113074. oggpack_write(opb,info->secondstages[j]>>3,5);
  113075. }else
  113076. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  113077. acc+=icount(info->secondstages[j]);
  113078. }
  113079. for(j=0;j<acc;j++)
  113080. oggpack_write(opb,info->booklist[j],8);
  113081. }
  113082. /* vorbis_info is for range checking */
  113083. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  113084. int j,acc=0;
  113085. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  113086. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  113087. info->begin=oggpack_read(opb,24);
  113088. info->end=oggpack_read(opb,24);
  113089. info->grouping=oggpack_read(opb,24)+1;
  113090. info->partitions=oggpack_read(opb,6)+1;
  113091. info->groupbook=oggpack_read(opb,8);
  113092. for(j=0;j<info->partitions;j++){
  113093. int cascade=oggpack_read(opb,3);
  113094. if(oggpack_read(opb,1))
  113095. cascade|=(oggpack_read(opb,5)<<3);
  113096. info->secondstages[j]=cascade;
  113097. acc+=icount(cascade);
  113098. }
  113099. for(j=0;j<acc;j++)
  113100. info->booklist[j]=oggpack_read(opb,8);
  113101. if(info->groupbook>=ci->books)goto errout;
  113102. for(j=0;j<acc;j++)
  113103. if(info->booklist[j]>=ci->books)goto errout;
  113104. return(info);
  113105. errout:
  113106. res0_free_info(info);
  113107. return(NULL);
  113108. }
  113109. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  113110. vorbis_info_residue *vr){
  113111. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  113112. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  113113. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  113114. int j,k,acc=0;
  113115. int dim;
  113116. int maxstage=0;
  113117. look->info=info;
  113118. look->parts=info->partitions;
  113119. look->fullbooks=ci->fullbooks;
  113120. look->phrasebook=ci->fullbooks+info->groupbook;
  113121. dim=look->phrasebook->dim;
  113122. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  113123. for(j=0;j<look->parts;j++){
  113124. int stages=ilog(info->secondstages[j]);
  113125. if(stages){
  113126. if(stages>maxstage)maxstage=stages;
  113127. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  113128. for(k=0;k<stages;k++)
  113129. if(info->secondstages[j]&(1<<k)){
  113130. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  113131. #ifdef TRAIN_RES
  113132. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  113133. sizeof(***look->training_data));
  113134. #endif
  113135. }
  113136. }
  113137. }
  113138. look->partvals=rint(pow((float)look->parts,(float)dim));
  113139. look->stages=maxstage;
  113140. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  113141. for(j=0;j<look->partvals;j++){
  113142. long val=j;
  113143. long mult=look->partvals/look->parts;
  113144. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  113145. for(k=0;k<dim;k++){
  113146. long deco=val/mult;
  113147. val-=deco*mult;
  113148. mult/=look->parts;
  113149. look->decodemap[j][k]=deco;
  113150. }
  113151. }
  113152. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  113153. {
  113154. static int train_seq=0;
  113155. look->train_seq=train_seq++;
  113156. }
  113157. #endif
  113158. return(look);
  113159. }
  113160. /* break an abstraction and copy some code for performance purposes */
  113161. static int local_book_besterror(codebook *book,float *a){
  113162. int dim=book->dim,i,k,o;
  113163. int best=0;
  113164. encode_aux_threshmatch *tt=book->c->thresh_tree;
  113165. /* find the quant val of each scalar */
  113166. for(k=0,o=dim;k<dim;++k){
  113167. float val=a[--o];
  113168. i=tt->threshvals>>1;
  113169. if(val<tt->quantthresh[i]){
  113170. if(val<tt->quantthresh[i-1]){
  113171. for(--i;i>0;--i)
  113172. if(val>=tt->quantthresh[i-1])
  113173. break;
  113174. }
  113175. }else{
  113176. for(++i;i<tt->threshvals-1;++i)
  113177. if(val<tt->quantthresh[i])break;
  113178. }
  113179. best=(best*tt->quantvals)+tt->quantmap[i];
  113180. }
  113181. /* regular lattices are easy :-) */
  113182. if(book->c->lengthlist[best]<=0){
  113183. const static_codebook *c=book->c;
  113184. int i,j;
  113185. float bestf=0.f;
  113186. float *e=book->valuelist;
  113187. best=-1;
  113188. for(i=0;i<book->entries;i++){
  113189. if(c->lengthlist[i]>0){
  113190. float thisx=0.f;
  113191. for(j=0;j<dim;j++){
  113192. float val=(e[j]-a[j]);
  113193. thisx+=val*val;
  113194. }
  113195. if(best==-1 || thisx<bestf){
  113196. bestf=thisx;
  113197. best=i;
  113198. }
  113199. }
  113200. e+=dim;
  113201. }
  113202. }
  113203. {
  113204. float *ptr=book->valuelist+best*dim;
  113205. for(i=0;i<dim;i++)
  113206. *a++ -= *ptr++;
  113207. }
  113208. return(best);
  113209. }
  113210. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  113211. codebook *book,long *acc){
  113212. int i,bits=0;
  113213. int dim=book->dim;
  113214. int step=n/dim;
  113215. for(i=0;i<step;i++){
  113216. int entry=local_book_besterror(book,vec+i*dim);
  113217. #ifdef TRAIN_RES
  113218. acc[entry]++;
  113219. #endif
  113220. bits+=vorbis_book_encode(book,entry,opb);
  113221. }
  113222. return(bits);
  113223. }
  113224. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  113225. float **in,int ch){
  113226. long i,j,k;
  113227. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  113228. vorbis_info_residue0 *info=look->info;
  113229. /* move all this setup out later */
  113230. int samples_per_partition=info->grouping;
  113231. int possible_partitions=info->partitions;
  113232. int n=info->end-info->begin;
  113233. int partvals=n/samples_per_partition;
  113234. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  113235. float scale=100./samples_per_partition;
  113236. /* we find the partition type for each partition of each
  113237. channel. We'll go back and do the interleaved encoding in a
  113238. bit. For now, clarity */
  113239. for(i=0;i<ch;i++){
  113240. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  113241. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  113242. }
  113243. for(i=0;i<partvals;i++){
  113244. int offset=i*samples_per_partition+info->begin;
  113245. for(j=0;j<ch;j++){
  113246. float max=0.;
  113247. float ent=0.;
  113248. for(k=0;k<samples_per_partition;k++){
  113249. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  113250. ent+=fabs(rint(in[j][offset+k]));
  113251. }
  113252. ent*=scale;
  113253. for(k=0;k<possible_partitions-1;k++)
  113254. if(max<=info->classmetric1[k] &&
  113255. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  113256. break;
  113257. partword[j][i]=k;
  113258. }
  113259. }
  113260. #ifdef TRAIN_RESAUX
  113261. {
  113262. FILE *of;
  113263. char buffer[80];
  113264. for(i=0;i<ch;i++){
  113265. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  113266. of=fopen(buffer,"a");
  113267. for(j=0;j<partvals;j++)
  113268. fprintf(of,"%ld, ",partword[i][j]);
  113269. fprintf(of,"\n");
  113270. fclose(of);
  113271. }
  113272. }
  113273. #endif
  113274. look->frames++;
  113275. return(partword);
  113276. }
  113277. /* designed for stereo or other modes where the partition size is an
  113278. integer multiple of the number of channels encoded in the current
  113279. submap */
  113280. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  113281. int ch){
  113282. long i,j,k,l;
  113283. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  113284. vorbis_info_residue0 *info=look->info;
  113285. /* move all this setup out later */
  113286. int samples_per_partition=info->grouping;
  113287. int possible_partitions=info->partitions;
  113288. int n=info->end-info->begin;
  113289. int partvals=n/samples_per_partition;
  113290. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  113291. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  113292. FILE *of;
  113293. char buffer[80];
  113294. #endif
  113295. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  113296. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  113297. for(i=0,l=info->begin/ch;i<partvals;i++){
  113298. float magmax=0.f;
  113299. float angmax=0.f;
  113300. for(j=0;j<samples_per_partition;j+=ch){
  113301. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  113302. for(k=1;k<ch;k++)
  113303. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  113304. l++;
  113305. }
  113306. for(j=0;j<possible_partitions-1;j++)
  113307. if(magmax<=info->classmetric1[j] &&
  113308. angmax<=info->classmetric2[j])
  113309. break;
  113310. partword[0][i]=j;
  113311. }
  113312. #ifdef TRAIN_RESAUX
  113313. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  113314. of=fopen(buffer,"a");
  113315. for(i=0;i<partvals;i++)
  113316. fprintf(of,"%ld, ",partword[0][i]);
  113317. fprintf(of,"\n");
  113318. fclose(of);
  113319. #endif
  113320. look->frames++;
  113321. return(partword);
  113322. }
  113323. static int _01forward(oggpack_buffer *opb,
  113324. vorbis_block *vb,vorbis_look_residue *vl,
  113325. float **in,int ch,
  113326. long **partword,
  113327. int (*encode)(oggpack_buffer *,float *,int,
  113328. codebook *,long *)){
  113329. long i,j,k,s;
  113330. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  113331. vorbis_info_residue0 *info=look->info;
  113332. /* move all this setup out later */
  113333. int samples_per_partition=info->grouping;
  113334. int possible_partitions=info->partitions;
  113335. int partitions_per_word=look->phrasebook->dim;
  113336. int n=info->end-info->begin;
  113337. int partvals=n/samples_per_partition;
  113338. long resbits[128];
  113339. long resvals[128];
  113340. #ifdef TRAIN_RES
  113341. for(i=0;i<ch;i++)
  113342. for(j=info->begin;j<info->end;j++){
  113343. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  113344. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  113345. }
  113346. #endif
  113347. memset(resbits,0,sizeof(resbits));
  113348. memset(resvals,0,sizeof(resvals));
  113349. /* we code the partition words for each channel, then the residual
  113350. words for a partition per channel until we've written all the
  113351. residual words for that partition word. Then write the next
  113352. partition channel words... */
  113353. for(s=0;s<look->stages;s++){
  113354. for(i=0;i<partvals;){
  113355. /* first we encode a partition codeword for each channel */
  113356. if(s==0){
  113357. for(j=0;j<ch;j++){
  113358. long val=partword[j][i];
  113359. for(k=1;k<partitions_per_word;k++){
  113360. val*=possible_partitions;
  113361. if(i+k<partvals)
  113362. val+=partword[j][i+k];
  113363. }
  113364. /* training hack */
  113365. if(val<look->phrasebook->entries)
  113366. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  113367. #if 0 /*def TRAIN_RES*/
  113368. else
  113369. fprintf(stderr,"!");
  113370. #endif
  113371. }
  113372. }
  113373. /* now we encode interleaved residual values for the partitions */
  113374. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  113375. long offset=i*samples_per_partition+info->begin;
  113376. for(j=0;j<ch;j++){
  113377. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  113378. if(info->secondstages[partword[j][i]]&(1<<s)){
  113379. codebook *statebook=look->partbooks[partword[j][i]][s];
  113380. if(statebook){
  113381. int ret;
  113382. long *accumulator=NULL;
  113383. #ifdef TRAIN_RES
  113384. accumulator=look->training_data[s][partword[j][i]];
  113385. {
  113386. int l;
  113387. float *samples=in[j]+offset;
  113388. for(l=0;l<samples_per_partition;l++){
  113389. if(samples[l]<look->training_min[s][partword[j][i]])
  113390. look->training_min[s][partword[j][i]]=samples[l];
  113391. if(samples[l]>look->training_max[s][partword[j][i]])
  113392. look->training_max[s][partword[j][i]]=samples[l];
  113393. }
  113394. }
  113395. #endif
  113396. ret=encode(opb,in[j]+offset,samples_per_partition,
  113397. statebook,accumulator);
  113398. look->postbits+=ret;
  113399. resbits[partword[j][i]]+=ret;
  113400. }
  113401. }
  113402. }
  113403. }
  113404. }
  113405. }
  113406. /*{
  113407. long total=0;
  113408. long totalbits=0;
  113409. fprintf(stderr,"%d :: ",vb->mode);
  113410. for(k=0;k<possible_partitions;k++){
  113411. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  113412. total+=resvals[k];
  113413. totalbits+=resbits[k];
  113414. }
  113415. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  113416. }*/
  113417. return(0);
  113418. }
  113419. /* a truncated packet here just means 'stop working'; it's not an error */
  113420. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  113421. float **in,int ch,
  113422. long (*decodepart)(codebook *, float *,
  113423. oggpack_buffer *,int)){
  113424. long i,j,k,l,s;
  113425. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  113426. vorbis_info_residue0 *info=look->info;
  113427. /* move all this setup out later */
  113428. int samples_per_partition=info->grouping;
  113429. int partitions_per_word=look->phrasebook->dim;
  113430. int n=info->end-info->begin;
  113431. int partvals=n/samples_per_partition;
  113432. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  113433. int ***partword=(int***)alloca(ch*sizeof(*partword));
  113434. for(j=0;j<ch;j++)
  113435. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  113436. for(s=0;s<look->stages;s++){
  113437. /* each loop decodes on partition codeword containing
  113438. partitions_pre_word partitions */
  113439. for(i=0,l=0;i<partvals;l++){
  113440. if(s==0){
  113441. /* fetch the partition word for each channel */
  113442. for(j=0;j<ch;j++){
  113443. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  113444. if(temp==-1)goto eopbreak;
  113445. partword[j][l]=look->decodemap[temp];
  113446. if(partword[j][l]==NULL)goto errout;
  113447. }
  113448. }
  113449. /* now we decode residual values for the partitions */
  113450. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  113451. for(j=0;j<ch;j++){
  113452. long offset=info->begin+i*samples_per_partition;
  113453. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  113454. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  113455. if(stagebook){
  113456. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  113457. samples_per_partition)==-1)goto eopbreak;
  113458. }
  113459. }
  113460. }
  113461. }
  113462. }
  113463. errout:
  113464. eopbreak:
  113465. return(0);
  113466. }
  113467. #if 0
  113468. /* residue 0 and 1 are just slight variants of one another. 0 is
  113469. interleaved, 1 is not */
  113470. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  113471. float **in,int *nonzero,int ch){
  113472. /* we encode only the nonzero parts of a bundle */
  113473. int i,used=0;
  113474. for(i=0;i<ch;i++)
  113475. if(nonzero[i])
  113476. in[used++]=in[i];
  113477. if(used)
  113478. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  113479. return(_01class(vb,vl,in,used));
  113480. else
  113481. return(0);
  113482. }
  113483. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  113484. float **in,float **out,int *nonzero,int ch,
  113485. long **partword){
  113486. /* we encode only the nonzero parts of a bundle */
  113487. int i,j,used=0,n=vb->pcmend/2;
  113488. for(i=0;i<ch;i++)
  113489. if(nonzero[i]){
  113490. if(out)
  113491. for(j=0;j<n;j++)
  113492. out[i][j]+=in[i][j];
  113493. in[used++]=in[i];
  113494. }
  113495. if(used){
  113496. int ret=_01forward(vb,vl,in,used,partword,
  113497. _interleaved_encodepart);
  113498. if(out){
  113499. used=0;
  113500. for(i=0;i<ch;i++)
  113501. if(nonzero[i]){
  113502. for(j=0;j<n;j++)
  113503. out[i][j]-=in[used][j];
  113504. used++;
  113505. }
  113506. }
  113507. return(ret);
  113508. }else{
  113509. return(0);
  113510. }
  113511. }
  113512. #endif
  113513. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  113514. float **in,int *nonzero,int ch){
  113515. int i,used=0;
  113516. for(i=0;i<ch;i++)
  113517. if(nonzero[i])
  113518. in[used++]=in[i];
  113519. if(used)
  113520. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  113521. else
  113522. return(0);
  113523. }
  113524. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  113525. float **in,float **out,int *nonzero,int ch,
  113526. long **partword){
  113527. int i,j,used=0,n=vb->pcmend/2;
  113528. for(i=0;i<ch;i++)
  113529. if(nonzero[i]){
  113530. if(out)
  113531. for(j=0;j<n;j++)
  113532. out[i][j]+=in[i][j];
  113533. in[used++]=in[i];
  113534. }
  113535. if(used){
  113536. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  113537. if(out){
  113538. used=0;
  113539. for(i=0;i<ch;i++)
  113540. if(nonzero[i]){
  113541. for(j=0;j<n;j++)
  113542. out[i][j]-=in[used][j];
  113543. used++;
  113544. }
  113545. }
  113546. return(ret);
  113547. }else{
  113548. return(0);
  113549. }
  113550. }
  113551. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  113552. float **in,int *nonzero,int ch){
  113553. int i,used=0;
  113554. for(i=0;i<ch;i++)
  113555. if(nonzero[i])
  113556. in[used++]=in[i];
  113557. if(used)
  113558. return(_01class(vb,vl,in,used));
  113559. else
  113560. return(0);
  113561. }
  113562. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  113563. float **in,int *nonzero,int ch){
  113564. int i,used=0;
  113565. for(i=0;i<ch;i++)
  113566. if(nonzero[i])
  113567. in[used++]=in[i];
  113568. if(used)
  113569. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  113570. else
  113571. return(0);
  113572. }
  113573. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  113574. float **in,int *nonzero,int ch){
  113575. int i,used=0;
  113576. for(i=0;i<ch;i++)
  113577. if(nonzero[i])used++;
  113578. if(used)
  113579. return(_2class(vb,vl,in,ch));
  113580. else
  113581. return(0);
  113582. }
  113583. /* res2 is slightly more different; all the channels are interleaved
  113584. into a single vector and encoded. */
  113585. int res2_forward(oggpack_buffer *opb,
  113586. vorbis_block *vb,vorbis_look_residue *vl,
  113587. float **in,float **out,int *nonzero,int ch,
  113588. long **partword){
  113589. long i,j,k,n=vb->pcmend/2,used=0;
  113590. /* don't duplicate the code; use a working vector hack for now and
  113591. reshape ourselves into a single channel res1 */
  113592. /* ugly; reallocs for each coupling pass :-( */
  113593. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  113594. for(i=0;i<ch;i++){
  113595. float *pcm=in[i];
  113596. if(nonzero[i])used++;
  113597. for(j=0,k=i;j<n;j++,k+=ch)
  113598. work[k]=pcm[j];
  113599. }
  113600. if(used){
  113601. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  113602. /* update the sofar vector */
  113603. if(out){
  113604. for(i=0;i<ch;i++){
  113605. float *pcm=in[i];
  113606. float *sofar=out[i];
  113607. for(j=0,k=i;j<n;j++,k+=ch)
  113608. sofar[j]+=pcm[j]-work[k];
  113609. }
  113610. }
  113611. return(ret);
  113612. }else{
  113613. return(0);
  113614. }
  113615. }
  113616. /* duplicate code here as speed is somewhat more important */
  113617. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  113618. float **in,int *nonzero,int ch){
  113619. long i,k,l,s;
  113620. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  113621. vorbis_info_residue0 *info=look->info;
  113622. /* move all this setup out later */
  113623. int samples_per_partition=info->grouping;
  113624. int partitions_per_word=look->phrasebook->dim;
  113625. int n=info->end-info->begin;
  113626. int partvals=n/samples_per_partition;
  113627. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  113628. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  113629. for(i=0;i<ch;i++)if(nonzero[i])break;
  113630. if(i==ch)return(0); /* no nonzero vectors */
  113631. for(s=0;s<look->stages;s++){
  113632. for(i=0,l=0;i<partvals;l++){
  113633. if(s==0){
  113634. /* fetch the partition word */
  113635. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  113636. if(temp==-1)goto eopbreak;
  113637. partword[l]=look->decodemap[temp];
  113638. if(partword[l]==NULL)goto errout;
  113639. }
  113640. /* now we decode residual values for the partitions */
  113641. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  113642. if(info->secondstages[partword[l][k]]&(1<<s)){
  113643. codebook *stagebook=look->partbooks[partword[l][k]][s];
  113644. if(stagebook){
  113645. if(vorbis_book_decodevv_add(stagebook,in,
  113646. i*samples_per_partition+info->begin,ch,
  113647. &vb->opb,samples_per_partition)==-1)
  113648. goto eopbreak;
  113649. }
  113650. }
  113651. }
  113652. }
  113653. errout:
  113654. eopbreak:
  113655. return(0);
  113656. }
  113657. vorbis_func_residue residue0_exportbundle={
  113658. NULL,
  113659. &res0_unpack,
  113660. &res0_look,
  113661. &res0_free_info,
  113662. &res0_free_look,
  113663. NULL,
  113664. NULL,
  113665. &res0_inverse
  113666. };
  113667. vorbis_func_residue residue1_exportbundle={
  113668. &res0_pack,
  113669. &res0_unpack,
  113670. &res0_look,
  113671. &res0_free_info,
  113672. &res0_free_look,
  113673. &res1_class,
  113674. &res1_forward,
  113675. &res1_inverse
  113676. };
  113677. vorbis_func_residue residue2_exportbundle={
  113678. &res0_pack,
  113679. &res0_unpack,
  113680. &res0_look,
  113681. &res0_free_info,
  113682. &res0_free_look,
  113683. &res2_class,
  113684. &res2_forward,
  113685. &res2_inverse
  113686. };
  113687. #endif
  113688. /********* End of inlined file: res0.c *********/
  113689. /********* Start of inlined file: sharedbook.c *********/
  113690. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113691. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113692. // tasks..
  113693. #ifdef _MSC_VER
  113694. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113695. #endif
  113696. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113697. #if JUCE_USE_OGGVORBIS
  113698. #include <stdlib.h>
  113699. #include <math.h>
  113700. #include <string.h>
  113701. /**** pack/unpack helpers ******************************************/
  113702. int _ilog(unsigned int v){
  113703. int ret=0;
  113704. while(v){
  113705. ret++;
  113706. v>>=1;
  113707. }
  113708. return(ret);
  113709. }
  113710. /* 32 bit float (not IEEE; nonnormalized mantissa +
  113711. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  113712. Why not IEEE? It's just not that important here. */
  113713. #define VQ_FEXP 10
  113714. #define VQ_FMAN 21
  113715. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  113716. /* doesn't currently guard under/overflow */
  113717. long _float32_pack(float val){
  113718. int sign=0;
  113719. long exp;
  113720. long mant;
  113721. if(val<0){
  113722. sign=0x80000000;
  113723. val= -val;
  113724. }
  113725. exp= floor(log(val)/log(2.f));
  113726. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  113727. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  113728. return(sign|exp|mant);
  113729. }
  113730. float _float32_unpack(long val){
  113731. double mant=val&0x1fffff;
  113732. int sign=val&0x80000000;
  113733. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  113734. if(sign)mant= -mant;
  113735. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  113736. }
  113737. /* given a list of word lengths, generate a list of codewords. Works
  113738. for length ordered or unordered, always assigns the lowest valued
  113739. codewords first. Extended to handle unused entries (length 0) */
  113740. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  113741. long i,j,count=0;
  113742. ogg_uint32_t marker[33];
  113743. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  113744. memset(marker,0,sizeof(marker));
  113745. for(i=0;i<n;i++){
  113746. long length=l[i];
  113747. if(length>0){
  113748. ogg_uint32_t entry=marker[length];
  113749. /* when we claim a node for an entry, we also claim the nodes
  113750. below it (pruning off the imagined tree that may have dangled
  113751. from it) as well as blocking the use of any nodes directly
  113752. above for leaves */
  113753. /* update ourself */
  113754. if(length<32 && (entry>>length)){
  113755. /* error condition; the lengths must specify an overpopulated tree */
  113756. _ogg_free(r);
  113757. return(NULL);
  113758. }
  113759. r[count++]=entry;
  113760. /* Look to see if the next shorter marker points to the node
  113761. above. if so, update it and repeat. */
  113762. {
  113763. for(j=length;j>0;j--){
  113764. if(marker[j]&1){
  113765. /* have to jump branches */
  113766. if(j==1)
  113767. marker[1]++;
  113768. else
  113769. marker[j]=marker[j-1]<<1;
  113770. break; /* invariant says next upper marker would already
  113771. have been moved if it was on the same path */
  113772. }
  113773. marker[j]++;
  113774. }
  113775. }
  113776. /* prune the tree; the implicit invariant says all the longer
  113777. markers were dangling from our just-taken node. Dangle them
  113778. from our *new* node. */
  113779. for(j=length+1;j<33;j++)
  113780. if((marker[j]>>1) == entry){
  113781. entry=marker[j];
  113782. marker[j]=marker[j-1]<<1;
  113783. }else
  113784. break;
  113785. }else
  113786. if(sparsecount==0)count++;
  113787. }
  113788. /* bitreverse the words because our bitwise packer/unpacker is LSb
  113789. endian */
  113790. for(i=0,count=0;i<n;i++){
  113791. ogg_uint32_t temp=0;
  113792. for(j=0;j<l[i];j++){
  113793. temp<<=1;
  113794. temp|=(r[count]>>j)&1;
  113795. }
  113796. if(sparsecount){
  113797. if(l[i])
  113798. r[count++]=temp;
  113799. }else
  113800. r[count++]=temp;
  113801. }
  113802. return(r);
  113803. }
  113804. /* there might be a straightforward one-line way to do the below
  113805. that's portable and totally safe against roundoff, but I haven't
  113806. thought of it. Therefore, we opt on the side of caution */
  113807. long _book_maptype1_quantvals(const static_codebook *b){
  113808. long vals=floor(pow((float)b->entries,1.f/b->dim));
  113809. /* the above *should* be reliable, but we'll not assume that FP is
  113810. ever reliable when bitstream sync is at stake; verify via integer
  113811. means that vals really is the greatest value of dim for which
  113812. vals^b->bim <= b->entries */
  113813. /* treat the above as an initial guess */
  113814. while(1){
  113815. long acc=1;
  113816. long acc1=1;
  113817. int i;
  113818. for(i=0;i<b->dim;i++){
  113819. acc*=vals;
  113820. acc1*=vals+1;
  113821. }
  113822. if(acc<=b->entries && acc1>b->entries){
  113823. return(vals);
  113824. }else{
  113825. if(acc>b->entries){
  113826. vals--;
  113827. }else{
  113828. vals++;
  113829. }
  113830. }
  113831. }
  113832. }
  113833. /* unpack the quantized list of values for encode/decode ***********/
  113834. /* we need to deal with two map types: in map type 1, the values are
  113835. generated algorithmically (each column of the vector counts through
  113836. the values in the quant vector). in map type 2, all the values came
  113837. in in an explicit list. Both value lists must be unpacked */
  113838. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  113839. long j,k,count=0;
  113840. if(b->maptype==1 || b->maptype==2){
  113841. int quantvals;
  113842. float mindel=_float32_unpack(b->q_min);
  113843. float delta=_float32_unpack(b->q_delta);
  113844. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  113845. /* maptype 1 and 2 both use a quantized value vector, but
  113846. different sizes */
  113847. switch(b->maptype){
  113848. case 1:
  113849. /* most of the time, entries%dimensions == 0, but we need to be
  113850. well defined. We define that the possible vales at each
  113851. scalar is values == entries/dim. If entries%dim != 0, we'll
  113852. have 'too few' values (values*dim<entries), which means that
  113853. we'll have 'left over' entries; left over entries use zeroed
  113854. values (and are wasted). So don't generate codebooks like
  113855. that */
  113856. quantvals=_book_maptype1_quantvals(b);
  113857. for(j=0;j<b->entries;j++){
  113858. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  113859. float last=0.f;
  113860. int indexdiv=1;
  113861. for(k=0;k<b->dim;k++){
  113862. int index= (j/indexdiv)%quantvals;
  113863. float val=b->quantlist[index];
  113864. val=fabs(val)*delta+mindel+last;
  113865. if(b->q_sequencep)last=val;
  113866. if(sparsemap)
  113867. r[sparsemap[count]*b->dim+k]=val;
  113868. else
  113869. r[count*b->dim+k]=val;
  113870. indexdiv*=quantvals;
  113871. }
  113872. count++;
  113873. }
  113874. }
  113875. break;
  113876. case 2:
  113877. for(j=0;j<b->entries;j++){
  113878. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  113879. float last=0.f;
  113880. for(k=0;k<b->dim;k++){
  113881. float val=b->quantlist[j*b->dim+k];
  113882. val=fabs(val)*delta+mindel+last;
  113883. if(b->q_sequencep)last=val;
  113884. if(sparsemap)
  113885. r[sparsemap[count]*b->dim+k]=val;
  113886. else
  113887. r[count*b->dim+k]=val;
  113888. }
  113889. count++;
  113890. }
  113891. }
  113892. break;
  113893. }
  113894. return(r);
  113895. }
  113896. return(NULL);
  113897. }
  113898. void vorbis_staticbook_clear(static_codebook *b){
  113899. if(b->allocedp){
  113900. if(b->quantlist)_ogg_free(b->quantlist);
  113901. if(b->lengthlist)_ogg_free(b->lengthlist);
  113902. if(b->nearest_tree){
  113903. _ogg_free(b->nearest_tree->ptr0);
  113904. _ogg_free(b->nearest_tree->ptr1);
  113905. _ogg_free(b->nearest_tree->p);
  113906. _ogg_free(b->nearest_tree->q);
  113907. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  113908. _ogg_free(b->nearest_tree);
  113909. }
  113910. if(b->thresh_tree){
  113911. _ogg_free(b->thresh_tree->quantthresh);
  113912. _ogg_free(b->thresh_tree->quantmap);
  113913. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  113914. _ogg_free(b->thresh_tree);
  113915. }
  113916. memset(b,0,sizeof(*b));
  113917. }
  113918. }
  113919. void vorbis_staticbook_destroy(static_codebook *b){
  113920. if(b->allocedp){
  113921. vorbis_staticbook_clear(b);
  113922. _ogg_free(b);
  113923. }
  113924. }
  113925. void vorbis_book_clear(codebook *b){
  113926. /* static book is not cleared; we're likely called on the lookup and
  113927. the static codebook belongs to the info struct */
  113928. if(b->valuelist)_ogg_free(b->valuelist);
  113929. if(b->codelist)_ogg_free(b->codelist);
  113930. if(b->dec_index)_ogg_free(b->dec_index);
  113931. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  113932. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  113933. memset(b,0,sizeof(*b));
  113934. }
  113935. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  113936. memset(c,0,sizeof(*c));
  113937. c->c=s;
  113938. c->entries=s->entries;
  113939. c->used_entries=s->entries;
  113940. c->dim=s->dim;
  113941. c->codelist=_make_words(s->lengthlist,s->entries,0);
  113942. c->valuelist=_book_unquantize(s,s->entries,NULL);
  113943. return(0);
  113944. }
  113945. static int sort32a(const void *a,const void *b){
  113946. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  113947. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  113948. }
  113949. /* decode codebook arrangement is more heavily optimized than encode */
  113950. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  113951. int i,j,n=0,tabn;
  113952. int *sortindex;
  113953. memset(c,0,sizeof(*c));
  113954. /* count actually used entries */
  113955. for(i=0;i<s->entries;i++)
  113956. if(s->lengthlist[i]>0)
  113957. n++;
  113958. c->entries=s->entries;
  113959. c->used_entries=n;
  113960. c->dim=s->dim;
  113961. /* two different remappings go on here.
  113962. First, we collapse the likely sparse codebook down only to
  113963. actually represented values/words. This collapsing needs to be
  113964. indexed as map-valueless books are used to encode original entry
  113965. positions as integers.
  113966. Second, we reorder all vectors, including the entry index above,
  113967. by sorted bitreversed codeword to allow treeless decode. */
  113968. {
  113969. /* perform sort */
  113970. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  113971. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  113972. if(codes==NULL)goto err_out;
  113973. for(i=0;i<n;i++){
  113974. codes[i]=ogg_bitreverse(codes[i]);
  113975. codep[i]=codes+i;
  113976. }
  113977. qsort(codep,n,sizeof(*codep),sort32a);
  113978. sortindex=(int*)alloca(n*sizeof(*sortindex));
  113979. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  113980. /* the index is a reverse index */
  113981. for(i=0;i<n;i++){
  113982. int position=codep[i]-codes;
  113983. sortindex[position]=i;
  113984. }
  113985. for(i=0;i<n;i++)
  113986. c->codelist[sortindex[i]]=codes[i];
  113987. _ogg_free(codes);
  113988. }
  113989. c->valuelist=_book_unquantize(s,n,sortindex);
  113990. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  113991. for(n=0,i=0;i<s->entries;i++)
  113992. if(s->lengthlist[i]>0)
  113993. c->dec_index[sortindex[n++]]=i;
  113994. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  113995. for(n=0,i=0;i<s->entries;i++)
  113996. if(s->lengthlist[i]>0)
  113997. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  113998. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  113999. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  114000. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  114001. tabn=1<<c->dec_firsttablen;
  114002. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  114003. c->dec_maxlength=0;
  114004. for(i=0;i<n;i++){
  114005. if(c->dec_maxlength<c->dec_codelengths[i])
  114006. c->dec_maxlength=c->dec_codelengths[i];
  114007. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  114008. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  114009. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  114010. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  114011. }
  114012. }
  114013. /* now fill in 'unused' entries in the firsttable with hi/lo search
  114014. hints for the non-direct-hits */
  114015. {
  114016. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  114017. long lo=0,hi=0;
  114018. for(i=0;i<tabn;i++){
  114019. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  114020. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  114021. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  114022. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  114023. /* we only actually have 15 bits per hint to play with here.
  114024. In order to overflow gracefully (nothing breaks, efficiency
  114025. just drops), encode as the difference from the extremes. */
  114026. {
  114027. unsigned long loval=lo;
  114028. unsigned long hival=n-hi;
  114029. if(loval>0x7fff)loval=0x7fff;
  114030. if(hival>0x7fff)hival=0x7fff;
  114031. c->dec_firsttable[ogg_bitreverse(word)]=
  114032. 0x80000000UL | (loval<<15) | hival;
  114033. }
  114034. }
  114035. }
  114036. }
  114037. return(0);
  114038. err_out:
  114039. vorbis_book_clear(c);
  114040. return(-1);
  114041. }
  114042. static float _dist(int el,float *ref, float *b,int step){
  114043. int i;
  114044. float acc=0.f;
  114045. for(i=0;i<el;i++){
  114046. float val=(ref[i]-b[i*step]);
  114047. acc+=val*val;
  114048. }
  114049. return(acc);
  114050. }
  114051. int _best(codebook *book, float *a, int step){
  114052. encode_aux_threshmatch *tt=book->c->thresh_tree;
  114053. #if 0
  114054. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  114055. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  114056. #endif
  114057. int dim=book->dim;
  114058. int k,o;
  114059. /*int savebest=-1;
  114060. float saverr;*/
  114061. /* do we have a threshhold encode hint? */
  114062. if(tt){
  114063. int index=0,i;
  114064. /* find the quant val of each scalar */
  114065. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  114066. i=tt->threshvals>>1;
  114067. if(a[o]<tt->quantthresh[i]){
  114068. for(;i>0;i--)
  114069. if(a[o]>=tt->quantthresh[i-1])
  114070. break;
  114071. }else{
  114072. for(i++;i<tt->threshvals-1;i++)
  114073. if(a[o]<tt->quantthresh[i])break;
  114074. }
  114075. index=(index*tt->quantvals)+tt->quantmap[i];
  114076. }
  114077. /* regular lattices are easy :-) */
  114078. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  114079. use a decision tree after all
  114080. and fall through*/
  114081. return(index);
  114082. }
  114083. #if 0
  114084. /* do we have a pigeonhole encode hint? */
  114085. if(pt){
  114086. const static_codebook *c=book->c;
  114087. int i,besti=-1;
  114088. float best=0.f;
  114089. int entry=0;
  114090. /* dealing with sequentialness is a pain in the ass */
  114091. if(c->q_sequencep){
  114092. int pv;
  114093. long mul=1;
  114094. float qlast=0;
  114095. for(k=0,o=0;k<dim;k++,o+=step){
  114096. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  114097. if(pv<0 || pv>=pt->mapentries)break;
  114098. entry+=pt->pigeonmap[pv]*mul;
  114099. mul*=pt->quantvals;
  114100. qlast+=pv*pt->del+pt->min;
  114101. }
  114102. }else{
  114103. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  114104. int pv=(int)((a[o]-pt->min)/pt->del);
  114105. if(pv<0 || pv>=pt->mapentries)break;
  114106. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  114107. }
  114108. }
  114109. /* must be within the pigeonholable range; if we quant outside (or
  114110. in an entry that we define no list for), brute force it */
  114111. if(k==dim && pt->fitlength[entry]){
  114112. /* search the abbreviated list */
  114113. long *list=pt->fitlist+pt->fitmap[entry];
  114114. for(i=0;i<pt->fitlength[entry];i++){
  114115. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  114116. if(besti==-1 || this<best){
  114117. best=this;
  114118. besti=list[i];
  114119. }
  114120. }
  114121. return(besti);
  114122. }
  114123. }
  114124. if(nt){
  114125. /* optimized using the decision tree */
  114126. while(1){
  114127. float c=0.f;
  114128. float *p=book->valuelist+nt->p[ptr];
  114129. float *q=book->valuelist+nt->q[ptr];
  114130. for(k=0,o=0;k<dim;k++,o+=step)
  114131. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  114132. if(c>0.f) /* in A */
  114133. ptr= -nt->ptr0[ptr];
  114134. else /* in B */
  114135. ptr= -nt->ptr1[ptr];
  114136. if(ptr<=0)break;
  114137. }
  114138. return(-ptr);
  114139. }
  114140. #endif
  114141. /* brute force it! */
  114142. {
  114143. const static_codebook *c=book->c;
  114144. int i,besti=-1;
  114145. float best=0.f;
  114146. float *e=book->valuelist;
  114147. for(i=0;i<book->entries;i++){
  114148. if(c->lengthlist[i]>0){
  114149. float thisx=_dist(dim,e,a,step);
  114150. if(besti==-1 || thisx<best){
  114151. best=thisx;
  114152. besti=i;
  114153. }
  114154. }
  114155. e+=dim;
  114156. }
  114157. /*if(savebest!=-1 && savebest!=besti){
  114158. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  114159. "original:");
  114160. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  114161. fprintf(stderr,"\n"
  114162. "pigeonhole (entry %d, err %g):",savebest,saverr);
  114163. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  114164. (book->valuelist+savebest*dim)[i]);
  114165. fprintf(stderr,"\n"
  114166. "bruteforce (entry %d, err %g):",besti,best);
  114167. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  114168. (book->valuelist+besti*dim)[i]);
  114169. fprintf(stderr,"\n");
  114170. }*/
  114171. return(besti);
  114172. }
  114173. }
  114174. long vorbis_book_codeword(codebook *book,int entry){
  114175. if(book->c) /* only use with encode; decode optimizations are
  114176. allowed to break this */
  114177. return book->codelist[entry];
  114178. return -1;
  114179. }
  114180. long vorbis_book_codelen(codebook *book,int entry){
  114181. if(book->c) /* only use with encode; decode optimizations are
  114182. allowed to break this */
  114183. return book->c->lengthlist[entry];
  114184. return -1;
  114185. }
  114186. #ifdef _V_SELFTEST
  114187. /* Unit tests of the dequantizer; this stuff will be OK
  114188. cross-platform, I simply want to be sure that special mapping cases
  114189. actually work properly; a bug could go unnoticed for a while */
  114190. #include <stdio.h>
  114191. /* cases:
  114192. no mapping
  114193. full, explicit mapping
  114194. algorithmic mapping
  114195. nonsequential
  114196. sequential
  114197. */
  114198. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  114199. static long partial_quantlist1[]={0,7,2};
  114200. /* no mapping */
  114201. static_codebook test1={
  114202. 4,16,
  114203. NULL,
  114204. 0,
  114205. 0,0,0,0,
  114206. NULL,
  114207. NULL,NULL
  114208. };
  114209. static float *test1_result=NULL;
  114210. /* linear, full mapping, nonsequential */
  114211. static_codebook test2={
  114212. 4,3,
  114213. NULL,
  114214. 2,
  114215. -533200896,1611661312,4,0,
  114216. full_quantlist1,
  114217. NULL,NULL
  114218. };
  114219. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  114220. /* linear, full mapping, sequential */
  114221. static_codebook test3={
  114222. 4,3,
  114223. NULL,
  114224. 2,
  114225. -533200896,1611661312,4,1,
  114226. full_quantlist1,
  114227. NULL,NULL
  114228. };
  114229. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  114230. /* linear, algorithmic mapping, nonsequential */
  114231. static_codebook test4={
  114232. 3,27,
  114233. NULL,
  114234. 1,
  114235. -533200896,1611661312,4,0,
  114236. partial_quantlist1,
  114237. NULL,NULL
  114238. };
  114239. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  114240. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  114241. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  114242. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  114243. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  114244. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  114245. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  114246. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  114247. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  114248. /* linear, algorithmic mapping, sequential */
  114249. static_codebook test5={
  114250. 3,27,
  114251. NULL,
  114252. 1,
  114253. -533200896,1611661312,4,1,
  114254. partial_quantlist1,
  114255. NULL,NULL
  114256. };
  114257. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  114258. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  114259. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  114260. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  114261. -3, 1, 5, 4, 8,12, -1, 3, 7,
  114262. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  114263. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  114264. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  114265. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  114266. void run_test(static_codebook *b,float *comp){
  114267. float *out=_book_unquantize(b,b->entries,NULL);
  114268. int i;
  114269. if(comp){
  114270. if(!out){
  114271. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  114272. exit(1);
  114273. }
  114274. for(i=0;i<b->entries*b->dim;i++)
  114275. if(fabs(out[i]-comp[i])>.0001){
  114276. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  114277. "position %d, %g != %g\n",i,out[i],comp[i]);
  114278. exit(1);
  114279. }
  114280. }else{
  114281. if(out){
  114282. fprintf(stderr,"_book_unquantize returned a value array: \n"
  114283. " correct result should have been NULL\n");
  114284. exit(1);
  114285. }
  114286. }
  114287. }
  114288. int main(){
  114289. /* run the nine dequant tests, and compare to the hand-rolled results */
  114290. fprintf(stderr,"Dequant test 1... ");
  114291. run_test(&test1,test1_result);
  114292. fprintf(stderr,"OK\nDequant test 2... ");
  114293. run_test(&test2,test2_result);
  114294. fprintf(stderr,"OK\nDequant test 3... ");
  114295. run_test(&test3,test3_result);
  114296. fprintf(stderr,"OK\nDequant test 4... ");
  114297. run_test(&test4,test4_result);
  114298. fprintf(stderr,"OK\nDequant test 5... ");
  114299. run_test(&test5,test5_result);
  114300. fprintf(stderr,"OK\n\n");
  114301. return(0);
  114302. }
  114303. #endif
  114304. #endif
  114305. /********* End of inlined file: sharedbook.c *********/
  114306. /********* Start of inlined file: smallft.c *********/
  114307. /* FFT implementation from OggSquish, minus cosine transforms,
  114308. * minus all but radix 2/4 case. In Vorbis we only need this
  114309. * cut-down version.
  114310. *
  114311. * To do more than just power-of-two sized vectors, see the full
  114312. * version I wrote for NetLib.
  114313. *
  114314. * Note that the packing is a little strange; rather than the FFT r/i
  114315. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  114316. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  114317. * FORTRAN version
  114318. */
  114319. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114320. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114321. // tasks..
  114322. #ifdef _MSC_VER
  114323. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114324. #endif
  114325. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114326. #if JUCE_USE_OGGVORBIS
  114327. #include <stdlib.h>
  114328. #include <string.h>
  114329. #include <math.h>
  114330. static void drfti1(int n, float *wa, int *ifac){
  114331. static int ntryh[4] = { 4,2,3,5 };
  114332. static float tpi = 6.28318530717958648f;
  114333. float arg,argh,argld,fi;
  114334. int ntry=0,i,j=-1;
  114335. int k1, l1, l2, ib;
  114336. int ld, ii, ip, is, nq, nr;
  114337. int ido, ipm, nfm1;
  114338. int nl=n;
  114339. int nf=0;
  114340. L101:
  114341. j++;
  114342. if (j < 4)
  114343. ntry=ntryh[j];
  114344. else
  114345. ntry+=2;
  114346. L104:
  114347. nq=nl/ntry;
  114348. nr=nl-ntry*nq;
  114349. if (nr!=0) goto L101;
  114350. nf++;
  114351. ifac[nf+1]=ntry;
  114352. nl=nq;
  114353. if(ntry!=2)goto L107;
  114354. if(nf==1)goto L107;
  114355. for (i=1;i<nf;i++){
  114356. ib=nf-i+1;
  114357. ifac[ib+1]=ifac[ib];
  114358. }
  114359. ifac[2] = 2;
  114360. L107:
  114361. if(nl!=1)goto L104;
  114362. ifac[0]=n;
  114363. ifac[1]=nf;
  114364. argh=tpi/n;
  114365. is=0;
  114366. nfm1=nf-1;
  114367. l1=1;
  114368. if(nfm1==0)return;
  114369. for (k1=0;k1<nfm1;k1++){
  114370. ip=ifac[k1+2];
  114371. ld=0;
  114372. l2=l1*ip;
  114373. ido=n/l2;
  114374. ipm=ip-1;
  114375. for (j=0;j<ipm;j++){
  114376. ld+=l1;
  114377. i=is;
  114378. argld=(float)ld*argh;
  114379. fi=0.f;
  114380. for (ii=2;ii<ido;ii+=2){
  114381. fi+=1.f;
  114382. arg=fi*argld;
  114383. wa[i++]=cos(arg);
  114384. wa[i++]=sin(arg);
  114385. }
  114386. is+=ido;
  114387. }
  114388. l1=l2;
  114389. }
  114390. }
  114391. static void fdrffti(int n, float *wsave, int *ifac){
  114392. if (n == 1) return;
  114393. drfti1(n, wsave+n, ifac);
  114394. }
  114395. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  114396. int i,k;
  114397. float ti2,tr2;
  114398. int t0,t1,t2,t3,t4,t5,t6;
  114399. t1=0;
  114400. t0=(t2=l1*ido);
  114401. t3=ido<<1;
  114402. for(k=0;k<l1;k++){
  114403. ch[t1<<1]=cc[t1]+cc[t2];
  114404. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  114405. t1+=ido;
  114406. t2+=ido;
  114407. }
  114408. if(ido<2)return;
  114409. if(ido==2)goto L105;
  114410. t1=0;
  114411. t2=t0;
  114412. for(k=0;k<l1;k++){
  114413. t3=t2;
  114414. t4=(t1<<1)+(ido<<1);
  114415. t5=t1;
  114416. t6=t1+t1;
  114417. for(i=2;i<ido;i+=2){
  114418. t3+=2;
  114419. t4-=2;
  114420. t5+=2;
  114421. t6+=2;
  114422. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  114423. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  114424. ch[t6]=cc[t5]+ti2;
  114425. ch[t4]=ti2-cc[t5];
  114426. ch[t6-1]=cc[t5-1]+tr2;
  114427. ch[t4-1]=cc[t5-1]-tr2;
  114428. }
  114429. t1+=ido;
  114430. t2+=ido;
  114431. }
  114432. if(ido%2==1)return;
  114433. L105:
  114434. t3=(t2=(t1=ido)-1);
  114435. t2+=t0;
  114436. for(k=0;k<l1;k++){
  114437. ch[t1]=-cc[t2];
  114438. ch[t1-1]=cc[t3];
  114439. t1+=ido<<1;
  114440. t2+=ido;
  114441. t3+=ido;
  114442. }
  114443. }
  114444. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  114445. float *wa2,float *wa3){
  114446. static float hsqt2 = .70710678118654752f;
  114447. int i,k,t0,t1,t2,t3,t4,t5,t6;
  114448. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  114449. t0=l1*ido;
  114450. t1=t0;
  114451. t4=t1<<1;
  114452. t2=t1+(t1<<1);
  114453. t3=0;
  114454. for(k=0;k<l1;k++){
  114455. tr1=cc[t1]+cc[t2];
  114456. tr2=cc[t3]+cc[t4];
  114457. ch[t5=t3<<2]=tr1+tr2;
  114458. ch[(ido<<2)+t5-1]=tr2-tr1;
  114459. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  114460. ch[t5]=cc[t2]-cc[t1];
  114461. t1+=ido;
  114462. t2+=ido;
  114463. t3+=ido;
  114464. t4+=ido;
  114465. }
  114466. if(ido<2)return;
  114467. if(ido==2)goto L105;
  114468. t1=0;
  114469. for(k=0;k<l1;k++){
  114470. t2=t1;
  114471. t4=t1<<2;
  114472. t5=(t6=ido<<1)+t4;
  114473. for(i=2;i<ido;i+=2){
  114474. t3=(t2+=2);
  114475. t4+=2;
  114476. t5-=2;
  114477. t3+=t0;
  114478. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  114479. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  114480. t3+=t0;
  114481. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  114482. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  114483. t3+=t0;
  114484. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  114485. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  114486. tr1=cr2+cr4;
  114487. tr4=cr4-cr2;
  114488. ti1=ci2+ci4;
  114489. ti4=ci2-ci4;
  114490. ti2=cc[t2]+ci3;
  114491. ti3=cc[t2]-ci3;
  114492. tr2=cc[t2-1]+cr3;
  114493. tr3=cc[t2-1]-cr3;
  114494. ch[t4-1]=tr1+tr2;
  114495. ch[t4]=ti1+ti2;
  114496. ch[t5-1]=tr3-ti4;
  114497. ch[t5]=tr4-ti3;
  114498. ch[t4+t6-1]=ti4+tr3;
  114499. ch[t4+t6]=tr4+ti3;
  114500. ch[t5+t6-1]=tr2-tr1;
  114501. ch[t5+t6]=ti1-ti2;
  114502. }
  114503. t1+=ido;
  114504. }
  114505. if(ido&1)return;
  114506. L105:
  114507. t2=(t1=t0+ido-1)+(t0<<1);
  114508. t3=ido<<2;
  114509. t4=ido;
  114510. t5=ido<<1;
  114511. t6=ido;
  114512. for(k=0;k<l1;k++){
  114513. ti1=-hsqt2*(cc[t1]+cc[t2]);
  114514. tr1=hsqt2*(cc[t1]-cc[t2]);
  114515. ch[t4-1]=tr1+cc[t6-1];
  114516. ch[t4+t5-1]=cc[t6-1]-tr1;
  114517. ch[t4]=ti1-cc[t1+t0];
  114518. ch[t4+t5]=ti1+cc[t1+t0];
  114519. t1+=ido;
  114520. t2+=ido;
  114521. t4+=t3;
  114522. t6+=ido;
  114523. }
  114524. }
  114525. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  114526. float *c2,float *ch,float *ch2,float *wa){
  114527. static float tpi=6.283185307179586f;
  114528. int idij,ipph,i,j,k,l,ic,ik,is;
  114529. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  114530. float dc2,ai1,ai2,ar1,ar2,ds2;
  114531. int nbd;
  114532. float dcp,arg,dsp,ar1h,ar2h;
  114533. int idp2,ipp2;
  114534. arg=tpi/(float)ip;
  114535. dcp=cos(arg);
  114536. dsp=sin(arg);
  114537. ipph=(ip+1)>>1;
  114538. ipp2=ip;
  114539. idp2=ido;
  114540. nbd=(ido-1)>>1;
  114541. t0=l1*ido;
  114542. t10=ip*ido;
  114543. if(ido==1)goto L119;
  114544. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  114545. t1=0;
  114546. for(j=1;j<ip;j++){
  114547. t1+=t0;
  114548. t2=t1;
  114549. for(k=0;k<l1;k++){
  114550. ch[t2]=c1[t2];
  114551. t2+=ido;
  114552. }
  114553. }
  114554. is=-ido;
  114555. t1=0;
  114556. if(nbd>l1){
  114557. for(j=1;j<ip;j++){
  114558. t1+=t0;
  114559. is+=ido;
  114560. t2= -ido+t1;
  114561. for(k=0;k<l1;k++){
  114562. idij=is-1;
  114563. t2+=ido;
  114564. t3=t2;
  114565. for(i=2;i<ido;i+=2){
  114566. idij+=2;
  114567. t3+=2;
  114568. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  114569. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  114570. }
  114571. }
  114572. }
  114573. }else{
  114574. for(j=1;j<ip;j++){
  114575. is+=ido;
  114576. idij=is-1;
  114577. t1+=t0;
  114578. t2=t1;
  114579. for(i=2;i<ido;i+=2){
  114580. idij+=2;
  114581. t2+=2;
  114582. t3=t2;
  114583. for(k=0;k<l1;k++){
  114584. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  114585. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  114586. t3+=ido;
  114587. }
  114588. }
  114589. }
  114590. }
  114591. t1=0;
  114592. t2=ipp2*t0;
  114593. if(nbd<l1){
  114594. for(j=1;j<ipph;j++){
  114595. t1+=t0;
  114596. t2-=t0;
  114597. t3=t1;
  114598. t4=t2;
  114599. for(i=2;i<ido;i+=2){
  114600. t3+=2;
  114601. t4+=2;
  114602. t5=t3-ido;
  114603. t6=t4-ido;
  114604. for(k=0;k<l1;k++){
  114605. t5+=ido;
  114606. t6+=ido;
  114607. c1[t5-1]=ch[t5-1]+ch[t6-1];
  114608. c1[t6-1]=ch[t5]-ch[t6];
  114609. c1[t5]=ch[t5]+ch[t6];
  114610. c1[t6]=ch[t6-1]-ch[t5-1];
  114611. }
  114612. }
  114613. }
  114614. }else{
  114615. for(j=1;j<ipph;j++){
  114616. t1+=t0;
  114617. t2-=t0;
  114618. t3=t1;
  114619. t4=t2;
  114620. for(k=0;k<l1;k++){
  114621. t5=t3;
  114622. t6=t4;
  114623. for(i=2;i<ido;i+=2){
  114624. t5+=2;
  114625. t6+=2;
  114626. c1[t5-1]=ch[t5-1]+ch[t6-1];
  114627. c1[t6-1]=ch[t5]-ch[t6];
  114628. c1[t5]=ch[t5]+ch[t6];
  114629. c1[t6]=ch[t6-1]-ch[t5-1];
  114630. }
  114631. t3+=ido;
  114632. t4+=ido;
  114633. }
  114634. }
  114635. }
  114636. L119:
  114637. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  114638. t1=0;
  114639. t2=ipp2*idl1;
  114640. for(j=1;j<ipph;j++){
  114641. t1+=t0;
  114642. t2-=t0;
  114643. t3=t1-ido;
  114644. t4=t2-ido;
  114645. for(k=0;k<l1;k++){
  114646. t3+=ido;
  114647. t4+=ido;
  114648. c1[t3]=ch[t3]+ch[t4];
  114649. c1[t4]=ch[t4]-ch[t3];
  114650. }
  114651. }
  114652. ar1=1.f;
  114653. ai1=0.f;
  114654. t1=0;
  114655. t2=ipp2*idl1;
  114656. t3=(ip-1)*idl1;
  114657. for(l=1;l<ipph;l++){
  114658. t1+=idl1;
  114659. t2-=idl1;
  114660. ar1h=dcp*ar1-dsp*ai1;
  114661. ai1=dcp*ai1+dsp*ar1;
  114662. ar1=ar1h;
  114663. t4=t1;
  114664. t5=t2;
  114665. t6=t3;
  114666. t7=idl1;
  114667. for(ik=0;ik<idl1;ik++){
  114668. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  114669. ch2[t5++]=ai1*c2[t6++];
  114670. }
  114671. dc2=ar1;
  114672. ds2=ai1;
  114673. ar2=ar1;
  114674. ai2=ai1;
  114675. t4=idl1;
  114676. t5=(ipp2-1)*idl1;
  114677. for(j=2;j<ipph;j++){
  114678. t4+=idl1;
  114679. t5-=idl1;
  114680. ar2h=dc2*ar2-ds2*ai2;
  114681. ai2=dc2*ai2+ds2*ar2;
  114682. ar2=ar2h;
  114683. t6=t1;
  114684. t7=t2;
  114685. t8=t4;
  114686. t9=t5;
  114687. for(ik=0;ik<idl1;ik++){
  114688. ch2[t6++]+=ar2*c2[t8++];
  114689. ch2[t7++]+=ai2*c2[t9++];
  114690. }
  114691. }
  114692. }
  114693. t1=0;
  114694. for(j=1;j<ipph;j++){
  114695. t1+=idl1;
  114696. t2=t1;
  114697. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  114698. }
  114699. if(ido<l1)goto L132;
  114700. t1=0;
  114701. t2=0;
  114702. for(k=0;k<l1;k++){
  114703. t3=t1;
  114704. t4=t2;
  114705. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  114706. t1+=ido;
  114707. t2+=t10;
  114708. }
  114709. goto L135;
  114710. L132:
  114711. for(i=0;i<ido;i++){
  114712. t1=i;
  114713. t2=i;
  114714. for(k=0;k<l1;k++){
  114715. cc[t2]=ch[t1];
  114716. t1+=ido;
  114717. t2+=t10;
  114718. }
  114719. }
  114720. L135:
  114721. t1=0;
  114722. t2=ido<<1;
  114723. t3=0;
  114724. t4=ipp2*t0;
  114725. for(j=1;j<ipph;j++){
  114726. t1+=t2;
  114727. t3+=t0;
  114728. t4-=t0;
  114729. t5=t1;
  114730. t6=t3;
  114731. t7=t4;
  114732. for(k=0;k<l1;k++){
  114733. cc[t5-1]=ch[t6];
  114734. cc[t5]=ch[t7];
  114735. t5+=t10;
  114736. t6+=ido;
  114737. t7+=ido;
  114738. }
  114739. }
  114740. if(ido==1)return;
  114741. if(nbd<l1)goto L141;
  114742. t1=-ido;
  114743. t3=0;
  114744. t4=0;
  114745. t5=ipp2*t0;
  114746. for(j=1;j<ipph;j++){
  114747. t1+=t2;
  114748. t3+=t2;
  114749. t4+=t0;
  114750. t5-=t0;
  114751. t6=t1;
  114752. t7=t3;
  114753. t8=t4;
  114754. t9=t5;
  114755. for(k=0;k<l1;k++){
  114756. for(i=2;i<ido;i+=2){
  114757. ic=idp2-i;
  114758. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  114759. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  114760. cc[i+t7]=ch[i+t8]+ch[i+t9];
  114761. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  114762. }
  114763. t6+=t10;
  114764. t7+=t10;
  114765. t8+=ido;
  114766. t9+=ido;
  114767. }
  114768. }
  114769. return;
  114770. L141:
  114771. t1=-ido;
  114772. t3=0;
  114773. t4=0;
  114774. t5=ipp2*t0;
  114775. for(j=1;j<ipph;j++){
  114776. t1+=t2;
  114777. t3+=t2;
  114778. t4+=t0;
  114779. t5-=t0;
  114780. for(i=2;i<ido;i+=2){
  114781. t6=idp2+t1-i;
  114782. t7=i+t3;
  114783. t8=i+t4;
  114784. t9=i+t5;
  114785. for(k=0;k<l1;k++){
  114786. cc[t7-1]=ch[t8-1]+ch[t9-1];
  114787. cc[t6-1]=ch[t8-1]-ch[t9-1];
  114788. cc[t7]=ch[t8]+ch[t9];
  114789. cc[t6]=ch[t9]-ch[t8];
  114790. t6+=t10;
  114791. t7+=t10;
  114792. t8+=ido;
  114793. t9+=ido;
  114794. }
  114795. }
  114796. }
  114797. }
  114798. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  114799. int i,k1,l1,l2;
  114800. int na,kh,nf;
  114801. int ip,iw,ido,idl1,ix2,ix3;
  114802. nf=ifac[1];
  114803. na=1;
  114804. l2=n;
  114805. iw=n;
  114806. for(k1=0;k1<nf;k1++){
  114807. kh=nf-k1;
  114808. ip=ifac[kh+1];
  114809. l1=l2/ip;
  114810. ido=n/l2;
  114811. idl1=ido*l1;
  114812. iw-=(ip-1)*ido;
  114813. na=1-na;
  114814. if(ip!=4)goto L102;
  114815. ix2=iw+ido;
  114816. ix3=ix2+ido;
  114817. if(na!=0)
  114818. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  114819. else
  114820. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  114821. goto L110;
  114822. L102:
  114823. if(ip!=2)goto L104;
  114824. if(na!=0)goto L103;
  114825. dradf2(ido,l1,c,ch,wa+iw-1);
  114826. goto L110;
  114827. L103:
  114828. dradf2(ido,l1,ch,c,wa+iw-1);
  114829. goto L110;
  114830. L104:
  114831. if(ido==1)na=1-na;
  114832. if(na!=0)goto L109;
  114833. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  114834. na=1;
  114835. goto L110;
  114836. L109:
  114837. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  114838. na=0;
  114839. L110:
  114840. l2=l1;
  114841. }
  114842. if(na==1)return;
  114843. for(i=0;i<n;i++)c[i]=ch[i];
  114844. }
  114845. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  114846. int i,k,t0,t1,t2,t3,t4,t5,t6;
  114847. float ti2,tr2;
  114848. t0=l1*ido;
  114849. t1=0;
  114850. t2=0;
  114851. t3=(ido<<1)-1;
  114852. for(k=0;k<l1;k++){
  114853. ch[t1]=cc[t2]+cc[t3+t2];
  114854. ch[t1+t0]=cc[t2]-cc[t3+t2];
  114855. t2=(t1+=ido)<<1;
  114856. }
  114857. if(ido<2)return;
  114858. if(ido==2)goto L105;
  114859. t1=0;
  114860. t2=0;
  114861. for(k=0;k<l1;k++){
  114862. t3=t1;
  114863. t5=(t4=t2)+(ido<<1);
  114864. t6=t0+t1;
  114865. for(i=2;i<ido;i+=2){
  114866. t3+=2;
  114867. t4+=2;
  114868. t5-=2;
  114869. t6+=2;
  114870. ch[t3-1]=cc[t4-1]+cc[t5-1];
  114871. tr2=cc[t4-1]-cc[t5-1];
  114872. ch[t3]=cc[t4]-cc[t5];
  114873. ti2=cc[t4]+cc[t5];
  114874. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  114875. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  114876. }
  114877. t2=(t1+=ido)<<1;
  114878. }
  114879. if(ido%2==1)return;
  114880. L105:
  114881. t1=ido-1;
  114882. t2=ido-1;
  114883. for(k=0;k<l1;k++){
  114884. ch[t1]=cc[t2]+cc[t2];
  114885. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  114886. t1+=ido;
  114887. t2+=ido<<1;
  114888. }
  114889. }
  114890. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  114891. float *wa2){
  114892. static float taur = -.5f;
  114893. static float taui = .8660254037844386f;
  114894. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  114895. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  114896. t0=l1*ido;
  114897. t1=0;
  114898. t2=t0<<1;
  114899. t3=ido<<1;
  114900. t4=ido+(ido<<1);
  114901. t5=0;
  114902. for(k=0;k<l1;k++){
  114903. tr2=cc[t3-1]+cc[t3-1];
  114904. cr2=cc[t5]+(taur*tr2);
  114905. ch[t1]=cc[t5]+tr2;
  114906. ci3=taui*(cc[t3]+cc[t3]);
  114907. ch[t1+t0]=cr2-ci3;
  114908. ch[t1+t2]=cr2+ci3;
  114909. t1+=ido;
  114910. t3+=t4;
  114911. t5+=t4;
  114912. }
  114913. if(ido==1)return;
  114914. t1=0;
  114915. t3=ido<<1;
  114916. for(k=0;k<l1;k++){
  114917. t7=t1+(t1<<1);
  114918. t6=(t5=t7+t3);
  114919. t8=t1;
  114920. t10=(t9=t1+t0)+t0;
  114921. for(i=2;i<ido;i+=2){
  114922. t5+=2;
  114923. t6-=2;
  114924. t7+=2;
  114925. t8+=2;
  114926. t9+=2;
  114927. t10+=2;
  114928. tr2=cc[t5-1]+cc[t6-1];
  114929. cr2=cc[t7-1]+(taur*tr2);
  114930. ch[t8-1]=cc[t7-1]+tr2;
  114931. ti2=cc[t5]-cc[t6];
  114932. ci2=cc[t7]+(taur*ti2);
  114933. ch[t8]=cc[t7]+ti2;
  114934. cr3=taui*(cc[t5-1]-cc[t6-1]);
  114935. ci3=taui*(cc[t5]+cc[t6]);
  114936. dr2=cr2-ci3;
  114937. dr3=cr2+ci3;
  114938. di2=ci2+cr3;
  114939. di3=ci2-cr3;
  114940. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  114941. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  114942. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  114943. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  114944. }
  114945. t1+=ido;
  114946. }
  114947. }
  114948. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  114949. float *wa2,float *wa3){
  114950. static float sqrt2=1.414213562373095f;
  114951. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  114952. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  114953. t0=l1*ido;
  114954. t1=0;
  114955. t2=ido<<2;
  114956. t3=0;
  114957. t6=ido<<1;
  114958. for(k=0;k<l1;k++){
  114959. t4=t3+t6;
  114960. t5=t1;
  114961. tr3=cc[t4-1]+cc[t4-1];
  114962. tr4=cc[t4]+cc[t4];
  114963. tr1=cc[t3]-cc[(t4+=t6)-1];
  114964. tr2=cc[t3]+cc[t4-1];
  114965. ch[t5]=tr2+tr3;
  114966. ch[t5+=t0]=tr1-tr4;
  114967. ch[t5+=t0]=tr2-tr3;
  114968. ch[t5+=t0]=tr1+tr4;
  114969. t1+=ido;
  114970. t3+=t2;
  114971. }
  114972. if(ido<2)return;
  114973. if(ido==2)goto L105;
  114974. t1=0;
  114975. for(k=0;k<l1;k++){
  114976. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  114977. t7=t1;
  114978. for(i=2;i<ido;i+=2){
  114979. t2+=2;
  114980. t3+=2;
  114981. t4-=2;
  114982. t5-=2;
  114983. t7+=2;
  114984. ti1=cc[t2]+cc[t5];
  114985. ti2=cc[t2]-cc[t5];
  114986. ti3=cc[t3]-cc[t4];
  114987. tr4=cc[t3]+cc[t4];
  114988. tr1=cc[t2-1]-cc[t5-1];
  114989. tr2=cc[t2-1]+cc[t5-1];
  114990. ti4=cc[t3-1]-cc[t4-1];
  114991. tr3=cc[t3-1]+cc[t4-1];
  114992. ch[t7-1]=tr2+tr3;
  114993. cr3=tr2-tr3;
  114994. ch[t7]=ti2+ti3;
  114995. ci3=ti2-ti3;
  114996. cr2=tr1-tr4;
  114997. cr4=tr1+tr4;
  114998. ci2=ti1+ti4;
  114999. ci4=ti1-ti4;
  115000. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  115001. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  115002. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  115003. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  115004. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  115005. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  115006. }
  115007. t1+=ido;
  115008. }
  115009. if(ido%2 == 1)return;
  115010. L105:
  115011. t1=ido;
  115012. t2=ido<<2;
  115013. t3=ido-1;
  115014. t4=ido+(ido<<1);
  115015. for(k=0;k<l1;k++){
  115016. t5=t3;
  115017. ti1=cc[t1]+cc[t4];
  115018. ti2=cc[t4]-cc[t1];
  115019. tr1=cc[t1-1]-cc[t4-1];
  115020. tr2=cc[t1-1]+cc[t4-1];
  115021. ch[t5]=tr2+tr2;
  115022. ch[t5+=t0]=sqrt2*(tr1-ti1);
  115023. ch[t5+=t0]=ti2+ti2;
  115024. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  115025. t3+=ido;
  115026. t1+=t2;
  115027. t4+=t2;
  115028. }
  115029. }
  115030. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  115031. float *c2,float *ch,float *ch2,float *wa){
  115032. static float tpi=6.283185307179586f;
  115033. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  115034. t11,t12;
  115035. float dc2,ai1,ai2,ar1,ar2,ds2;
  115036. int nbd;
  115037. float dcp,arg,dsp,ar1h,ar2h;
  115038. int ipp2;
  115039. t10=ip*ido;
  115040. t0=l1*ido;
  115041. arg=tpi/(float)ip;
  115042. dcp=cos(arg);
  115043. dsp=sin(arg);
  115044. nbd=(ido-1)>>1;
  115045. ipp2=ip;
  115046. ipph=(ip+1)>>1;
  115047. if(ido<l1)goto L103;
  115048. t1=0;
  115049. t2=0;
  115050. for(k=0;k<l1;k++){
  115051. t3=t1;
  115052. t4=t2;
  115053. for(i=0;i<ido;i++){
  115054. ch[t3]=cc[t4];
  115055. t3++;
  115056. t4++;
  115057. }
  115058. t1+=ido;
  115059. t2+=t10;
  115060. }
  115061. goto L106;
  115062. L103:
  115063. t1=0;
  115064. for(i=0;i<ido;i++){
  115065. t2=t1;
  115066. t3=t1;
  115067. for(k=0;k<l1;k++){
  115068. ch[t2]=cc[t3];
  115069. t2+=ido;
  115070. t3+=t10;
  115071. }
  115072. t1++;
  115073. }
  115074. L106:
  115075. t1=0;
  115076. t2=ipp2*t0;
  115077. t7=(t5=ido<<1);
  115078. for(j=1;j<ipph;j++){
  115079. t1+=t0;
  115080. t2-=t0;
  115081. t3=t1;
  115082. t4=t2;
  115083. t6=t5;
  115084. for(k=0;k<l1;k++){
  115085. ch[t3]=cc[t6-1]+cc[t6-1];
  115086. ch[t4]=cc[t6]+cc[t6];
  115087. t3+=ido;
  115088. t4+=ido;
  115089. t6+=t10;
  115090. }
  115091. t5+=t7;
  115092. }
  115093. if (ido == 1)goto L116;
  115094. if(nbd<l1)goto L112;
  115095. t1=0;
  115096. t2=ipp2*t0;
  115097. t7=0;
  115098. for(j=1;j<ipph;j++){
  115099. t1+=t0;
  115100. t2-=t0;
  115101. t3=t1;
  115102. t4=t2;
  115103. t7+=(ido<<1);
  115104. t8=t7;
  115105. for(k=0;k<l1;k++){
  115106. t5=t3;
  115107. t6=t4;
  115108. t9=t8;
  115109. t11=t8;
  115110. for(i=2;i<ido;i+=2){
  115111. t5+=2;
  115112. t6+=2;
  115113. t9+=2;
  115114. t11-=2;
  115115. ch[t5-1]=cc[t9-1]+cc[t11-1];
  115116. ch[t6-1]=cc[t9-1]-cc[t11-1];
  115117. ch[t5]=cc[t9]-cc[t11];
  115118. ch[t6]=cc[t9]+cc[t11];
  115119. }
  115120. t3+=ido;
  115121. t4+=ido;
  115122. t8+=t10;
  115123. }
  115124. }
  115125. goto L116;
  115126. L112:
  115127. t1=0;
  115128. t2=ipp2*t0;
  115129. t7=0;
  115130. for(j=1;j<ipph;j++){
  115131. t1+=t0;
  115132. t2-=t0;
  115133. t3=t1;
  115134. t4=t2;
  115135. t7+=(ido<<1);
  115136. t8=t7;
  115137. t9=t7;
  115138. for(i=2;i<ido;i+=2){
  115139. t3+=2;
  115140. t4+=2;
  115141. t8+=2;
  115142. t9-=2;
  115143. t5=t3;
  115144. t6=t4;
  115145. t11=t8;
  115146. t12=t9;
  115147. for(k=0;k<l1;k++){
  115148. ch[t5-1]=cc[t11-1]+cc[t12-1];
  115149. ch[t6-1]=cc[t11-1]-cc[t12-1];
  115150. ch[t5]=cc[t11]-cc[t12];
  115151. ch[t6]=cc[t11]+cc[t12];
  115152. t5+=ido;
  115153. t6+=ido;
  115154. t11+=t10;
  115155. t12+=t10;
  115156. }
  115157. }
  115158. }
  115159. L116:
  115160. ar1=1.f;
  115161. ai1=0.f;
  115162. t1=0;
  115163. t9=(t2=ipp2*idl1);
  115164. t3=(ip-1)*idl1;
  115165. for(l=1;l<ipph;l++){
  115166. t1+=idl1;
  115167. t2-=idl1;
  115168. ar1h=dcp*ar1-dsp*ai1;
  115169. ai1=dcp*ai1+dsp*ar1;
  115170. ar1=ar1h;
  115171. t4=t1;
  115172. t5=t2;
  115173. t6=0;
  115174. t7=idl1;
  115175. t8=t3;
  115176. for(ik=0;ik<idl1;ik++){
  115177. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  115178. c2[t5++]=ai1*ch2[t8++];
  115179. }
  115180. dc2=ar1;
  115181. ds2=ai1;
  115182. ar2=ar1;
  115183. ai2=ai1;
  115184. t6=idl1;
  115185. t7=t9-idl1;
  115186. for(j=2;j<ipph;j++){
  115187. t6+=idl1;
  115188. t7-=idl1;
  115189. ar2h=dc2*ar2-ds2*ai2;
  115190. ai2=dc2*ai2+ds2*ar2;
  115191. ar2=ar2h;
  115192. t4=t1;
  115193. t5=t2;
  115194. t11=t6;
  115195. t12=t7;
  115196. for(ik=0;ik<idl1;ik++){
  115197. c2[t4++]+=ar2*ch2[t11++];
  115198. c2[t5++]+=ai2*ch2[t12++];
  115199. }
  115200. }
  115201. }
  115202. t1=0;
  115203. for(j=1;j<ipph;j++){
  115204. t1+=idl1;
  115205. t2=t1;
  115206. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  115207. }
  115208. t1=0;
  115209. t2=ipp2*t0;
  115210. for(j=1;j<ipph;j++){
  115211. t1+=t0;
  115212. t2-=t0;
  115213. t3=t1;
  115214. t4=t2;
  115215. for(k=0;k<l1;k++){
  115216. ch[t3]=c1[t3]-c1[t4];
  115217. ch[t4]=c1[t3]+c1[t4];
  115218. t3+=ido;
  115219. t4+=ido;
  115220. }
  115221. }
  115222. if(ido==1)goto L132;
  115223. if(nbd<l1)goto L128;
  115224. t1=0;
  115225. t2=ipp2*t0;
  115226. for(j=1;j<ipph;j++){
  115227. t1+=t0;
  115228. t2-=t0;
  115229. t3=t1;
  115230. t4=t2;
  115231. for(k=0;k<l1;k++){
  115232. t5=t3;
  115233. t6=t4;
  115234. for(i=2;i<ido;i+=2){
  115235. t5+=2;
  115236. t6+=2;
  115237. ch[t5-1]=c1[t5-1]-c1[t6];
  115238. ch[t6-1]=c1[t5-1]+c1[t6];
  115239. ch[t5]=c1[t5]+c1[t6-1];
  115240. ch[t6]=c1[t5]-c1[t6-1];
  115241. }
  115242. t3+=ido;
  115243. t4+=ido;
  115244. }
  115245. }
  115246. goto L132;
  115247. L128:
  115248. t1=0;
  115249. t2=ipp2*t0;
  115250. for(j=1;j<ipph;j++){
  115251. t1+=t0;
  115252. t2-=t0;
  115253. t3=t1;
  115254. t4=t2;
  115255. for(i=2;i<ido;i+=2){
  115256. t3+=2;
  115257. t4+=2;
  115258. t5=t3;
  115259. t6=t4;
  115260. for(k=0;k<l1;k++){
  115261. ch[t5-1]=c1[t5-1]-c1[t6];
  115262. ch[t6-1]=c1[t5-1]+c1[t6];
  115263. ch[t5]=c1[t5]+c1[t6-1];
  115264. ch[t6]=c1[t5]-c1[t6-1];
  115265. t5+=ido;
  115266. t6+=ido;
  115267. }
  115268. }
  115269. }
  115270. L132:
  115271. if(ido==1)return;
  115272. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  115273. t1=0;
  115274. for(j=1;j<ip;j++){
  115275. t2=(t1+=t0);
  115276. for(k=0;k<l1;k++){
  115277. c1[t2]=ch[t2];
  115278. t2+=ido;
  115279. }
  115280. }
  115281. if(nbd>l1)goto L139;
  115282. is= -ido-1;
  115283. t1=0;
  115284. for(j=1;j<ip;j++){
  115285. is+=ido;
  115286. t1+=t0;
  115287. idij=is;
  115288. t2=t1;
  115289. for(i=2;i<ido;i+=2){
  115290. t2+=2;
  115291. idij+=2;
  115292. t3=t2;
  115293. for(k=0;k<l1;k++){
  115294. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  115295. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  115296. t3+=ido;
  115297. }
  115298. }
  115299. }
  115300. return;
  115301. L139:
  115302. is= -ido-1;
  115303. t1=0;
  115304. for(j=1;j<ip;j++){
  115305. is+=ido;
  115306. t1+=t0;
  115307. t2=t1;
  115308. for(k=0;k<l1;k++){
  115309. idij=is;
  115310. t3=t2;
  115311. for(i=2;i<ido;i+=2){
  115312. idij+=2;
  115313. t3+=2;
  115314. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  115315. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  115316. }
  115317. t2+=ido;
  115318. }
  115319. }
  115320. }
  115321. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  115322. int i,k1,l1,l2;
  115323. int na;
  115324. int nf,ip,iw,ix2,ix3,ido,idl1;
  115325. nf=ifac[1];
  115326. na=0;
  115327. l1=1;
  115328. iw=1;
  115329. for(k1=0;k1<nf;k1++){
  115330. ip=ifac[k1 + 2];
  115331. l2=ip*l1;
  115332. ido=n/l2;
  115333. idl1=ido*l1;
  115334. if(ip!=4)goto L103;
  115335. ix2=iw+ido;
  115336. ix3=ix2+ido;
  115337. if(na!=0)
  115338. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  115339. else
  115340. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  115341. na=1-na;
  115342. goto L115;
  115343. L103:
  115344. if(ip!=2)goto L106;
  115345. if(na!=0)
  115346. dradb2(ido,l1,ch,c,wa+iw-1);
  115347. else
  115348. dradb2(ido,l1,c,ch,wa+iw-1);
  115349. na=1-na;
  115350. goto L115;
  115351. L106:
  115352. if(ip!=3)goto L109;
  115353. ix2=iw+ido;
  115354. if(na!=0)
  115355. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  115356. else
  115357. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  115358. na=1-na;
  115359. goto L115;
  115360. L109:
  115361. /* The radix five case can be translated later..... */
  115362. /* if(ip!=5)goto L112;
  115363. ix2=iw+ido;
  115364. ix3=ix2+ido;
  115365. ix4=ix3+ido;
  115366. if(na!=0)
  115367. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  115368. else
  115369. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  115370. na=1-na;
  115371. goto L115;
  115372. L112:*/
  115373. if(na!=0)
  115374. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  115375. else
  115376. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  115377. if(ido==1)na=1-na;
  115378. L115:
  115379. l1=l2;
  115380. iw+=(ip-1)*ido;
  115381. }
  115382. if(na==0)return;
  115383. for(i=0;i<n;i++)c[i]=ch[i];
  115384. }
  115385. void drft_forward(drft_lookup *l,float *data){
  115386. if(l->n==1)return;
  115387. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  115388. }
  115389. void drft_backward(drft_lookup *l,float *data){
  115390. if (l->n==1)return;
  115391. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  115392. }
  115393. void drft_init(drft_lookup *l,int n){
  115394. l->n=n;
  115395. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  115396. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  115397. fdrffti(n, l->trigcache, l->splitcache);
  115398. }
  115399. void drft_clear(drft_lookup *l){
  115400. if(l){
  115401. if(l->trigcache)_ogg_free(l->trigcache);
  115402. if(l->splitcache)_ogg_free(l->splitcache);
  115403. memset(l,0,sizeof(*l));
  115404. }
  115405. }
  115406. #endif
  115407. /********* End of inlined file: smallft.c *********/
  115408. /********* Start of inlined file: synthesis.c *********/
  115409. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  115410. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115411. // tasks..
  115412. #ifdef _MSC_VER
  115413. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115414. #endif
  115415. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  115416. #if JUCE_USE_OGGVORBIS
  115417. #include <stdio.h>
  115418. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  115419. vorbis_dsp_state *vd=vb->vd;
  115420. private_state *b=(private_state*)vd->backend_state;
  115421. vorbis_info *vi=vd->vi;
  115422. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115423. oggpack_buffer *opb=&vb->opb;
  115424. int type,mode,i;
  115425. /* first things first. Make sure decode is ready */
  115426. _vorbis_block_ripcord(vb);
  115427. oggpack_readinit(opb,op->packet,op->bytes);
  115428. /* Check the packet type */
  115429. if(oggpack_read(opb,1)!=0){
  115430. /* Oops. This is not an audio data packet */
  115431. return(OV_ENOTAUDIO);
  115432. }
  115433. /* read our mode and pre/post windowsize */
  115434. mode=oggpack_read(opb,b->modebits);
  115435. if(mode==-1)return(OV_EBADPACKET);
  115436. vb->mode=mode;
  115437. vb->W=ci->mode_param[mode]->blockflag;
  115438. if(vb->W){
  115439. /* this doesn;t get mapped through mode selection as it's used
  115440. only for window selection */
  115441. vb->lW=oggpack_read(opb,1);
  115442. vb->nW=oggpack_read(opb,1);
  115443. if(vb->nW==-1) return(OV_EBADPACKET);
  115444. }else{
  115445. vb->lW=0;
  115446. vb->nW=0;
  115447. }
  115448. /* more setup */
  115449. vb->granulepos=op->granulepos;
  115450. vb->sequence=op->packetno;
  115451. vb->eofflag=op->e_o_s;
  115452. /* alloc pcm passback storage */
  115453. vb->pcmend=ci->blocksizes[vb->W];
  115454. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  115455. for(i=0;i<vi->channels;i++)
  115456. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  115457. /* unpack_header enforces range checking */
  115458. type=ci->map_type[ci->mode_param[mode]->mapping];
  115459. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  115460. mapping]));
  115461. }
  115462. /* used to track pcm position without actually performing decode.
  115463. Useful for sequential 'fast forward' */
  115464. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  115465. vorbis_dsp_state *vd=vb->vd;
  115466. private_state *b=(private_state*)vd->backend_state;
  115467. vorbis_info *vi=vd->vi;
  115468. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115469. oggpack_buffer *opb=&vb->opb;
  115470. int mode;
  115471. /* first things first. Make sure decode is ready */
  115472. _vorbis_block_ripcord(vb);
  115473. oggpack_readinit(opb,op->packet,op->bytes);
  115474. /* Check the packet type */
  115475. if(oggpack_read(opb,1)!=0){
  115476. /* Oops. This is not an audio data packet */
  115477. return(OV_ENOTAUDIO);
  115478. }
  115479. /* read our mode and pre/post windowsize */
  115480. mode=oggpack_read(opb,b->modebits);
  115481. if(mode==-1)return(OV_EBADPACKET);
  115482. vb->mode=mode;
  115483. vb->W=ci->mode_param[mode]->blockflag;
  115484. if(vb->W){
  115485. vb->lW=oggpack_read(opb,1);
  115486. vb->nW=oggpack_read(opb,1);
  115487. if(vb->nW==-1) return(OV_EBADPACKET);
  115488. }else{
  115489. vb->lW=0;
  115490. vb->nW=0;
  115491. }
  115492. /* more setup */
  115493. vb->granulepos=op->granulepos;
  115494. vb->sequence=op->packetno;
  115495. vb->eofflag=op->e_o_s;
  115496. /* no pcm */
  115497. vb->pcmend=0;
  115498. vb->pcm=NULL;
  115499. return(0);
  115500. }
  115501. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  115502. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115503. oggpack_buffer opb;
  115504. int mode;
  115505. oggpack_readinit(&opb,op->packet,op->bytes);
  115506. /* Check the packet type */
  115507. if(oggpack_read(&opb,1)!=0){
  115508. /* Oops. This is not an audio data packet */
  115509. return(OV_ENOTAUDIO);
  115510. }
  115511. {
  115512. int modebits=0;
  115513. int v=ci->modes;
  115514. while(v>1){
  115515. modebits++;
  115516. v>>=1;
  115517. }
  115518. /* read our mode and pre/post windowsize */
  115519. mode=oggpack_read(&opb,modebits);
  115520. }
  115521. if(mode==-1)return(OV_EBADPACKET);
  115522. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  115523. }
  115524. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  115525. /* set / clear half-sample-rate mode */
  115526. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115527. /* right now, our MDCT can't handle < 64 sample windows. */
  115528. if(ci->blocksizes[0]<=64 && flag)return -1;
  115529. ci->halfrate_flag=(flag?1:0);
  115530. return 0;
  115531. }
  115532. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  115533. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115534. return ci->halfrate_flag;
  115535. }
  115536. #endif
  115537. /********* End of inlined file: synthesis.c *********/
  115538. /********* Start of inlined file: vorbisenc.c *********/
  115539. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  115540. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115541. // tasks..
  115542. #ifdef _MSC_VER
  115543. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115544. #endif
  115545. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  115546. #if JUCE_USE_OGGVORBIS
  115547. #include <stdlib.h>
  115548. #include <string.h>
  115549. #include <math.h>
  115550. /* careful with this; it's using static array sizing to make managing
  115551. all the modes a little less annoying. If we use a residue backend
  115552. with > 12 partition types, or a different division of iteration,
  115553. this needs to be updated. */
  115554. typedef struct {
  115555. static_codebook *books[12][3];
  115556. } static_bookblock;
  115557. typedef struct {
  115558. int res_type;
  115559. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  115560. vorbis_info_residue0 *res;
  115561. static_codebook *book_aux;
  115562. static_codebook *book_aux_managed;
  115563. static_bookblock *books_base;
  115564. static_bookblock *books_base_managed;
  115565. } vorbis_residue_template;
  115566. typedef struct {
  115567. vorbis_info_mapping0 *map;
  115568. vorbis_residue_template *res;
  115569. } vorbis_mapping_template;
  115570. typedef struct vp_adjblock{
  115571. int block[P_BANDS];
  115572. } vp_adjblock;
  115573. typedef struct {
  115574. int data[NOISE_COMPAND_LEVELS];
  115575. } compandblock;
  115576. /* high level configuration information for setting things up
  115577. step-by-step with the detailed vorbis_encode_ctl interface.
  115578. There's a fair amount of redundancy such that interactive setup
  115579. does not directly deal with any vorbis_info or codec_setup_info
  115580. initialization; it's all stored (until full init) in this highlevel
  115581. setup, then flushed out to the real codec setup structs later. */
  115582. typedef struct {
  115583. int att[P_NOISECURVES];
  115584. float boost;
  115585. float decay;
  115586. } att3;
  115587. typedef struct { int data[P_NOISECURVES]; } adj3;
  115588. typedef struct {
  115589. int pre[PACKETBLOBS];
  115590. int post[PACKETBLOBS];
  115591. float kHz[PACKETBLOBS];
  115592. float lowpasskHz[PACKETBLOBS];
  115593. } adj_stereo;
  115594. typedef struct {
  115595. int lo;
  115596. int hi;
  115597. int fixed;
  115598. } noiseguard;
  115599. typedef struct {
  115600. int data[P_NOISECURVES][17];
  115601. } noise3;
  115602. typedef struct {
  115603. int mappings;
  115604. double *rate_mapping;
  115605. double *quality_mapping;
  115606. int coupling_restriction;
  115607. long samplerate_min_restriction;
  115608. long samplerate_max_restriction;
  115609. int *blocksize_short;
  115610. int *blocksize_long;
  115611. att3 *psy_tone_masteratt;
  115612. int *psy_tone_0dB;
  115613. int *psy_tone_dBsuppress;
  115614. vp_adjblock *psy_tone_adj_impulse;
  115615. vp_adjblock *psy_tone_adj_long;
  115616. vp_adjblock *psy_tone_adj_other;
  115617. noiseguard *psy_noiseguards;
  115618. noise3 *psy_noise_bias_impulse;
  115619. noise3 *psy_noise_bias_padding;
  115620. noise3 *psy_noise_bias_trans;
  115621. noise3 *psy_noise_bias_long;
  115622. int *psy_noise_dBsuppress;
  115623. compandblock *psy_noise_compand;
  115624. double *psy_noise_compand_short_mapping;
  115625. double *psy_noise_compand_long_mapping;
  115626. int *psy_noise_normal_start[2];
  115627. int *psy_noise_normal_partition[2];
  115628. double *psy_noise_normal_thresh;
  115629. int *psy_ath_float;
  115630. int *psy_ath_abs;
  115631. double *psy_lowpass;
  115632. vorbis_info_psy_global *global_params;
  115633. double *global_mapping;
  115634. adj_stereo *stereo_modes;
  115635. static_codebook ***floor_books;
  115636. vorbis_info_floor1 *floor_params;
  115637. int *floor_short_mapping;
  115638. int *floor_long_mapping;
  115639. vorbis_mapping_template *maps;
  115640. } ve_setup_data_template;
  115641. /* a few static coder conventions */
  115642. static vorbis_info_mode _mode_template[2]={
  115643. {0,0,0,0},
  115644. {1,0,0,1}
  115645. };
  115646. static vorbis_info_mapping0 _map_nominal[2]={
  115647. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  115648. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  115649. };
  115650. /********* Start of inlined file: setup_44.h *********/
  115651. /********* Start of inlined file: floor_all.h *********/
  115652. /********* Start of inlined file: floor_books.h *********/
  115653. static long _huff_lengthlist_line_256x7_0sub1[] = {
  115654. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  115655. };
  115656. static static_codebook _huff_book_line_256x7_0sub1 = {
  115657. 1, 9,
  115658. _huff_lengthlist_line_256x7_0sub1,
  115659. 0, 0, 0, 0, 0,
  115660. NULL,
  115661. NULL,
  115662. NULL,
  115663. NULL,
  115664. 0
  115665. };
  115666. static long _huff_lengthlist_line_256x7_0sub2[] = {
  115667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  115668. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  115669. };
  115670. static static_codebook _huff_book_line_256x7_0sub2 = {
  115671. 1, 25,
  115672. _huff_lengthlist_line_256x7_0sub2,
  115673. 0, 0, 0, 0, 0,
  115674. NULL,
  115675. NULL,
  115676. NULL,
  115677. NULL,
  115678. 0
  115679. };
  115680. static long _huff_lengthlist_line_256x7_0sub3[] = {
  115681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  115683. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  115684. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  115685. };
  115686. static static_codebook _huff_book_line_256x7_0sub3 = {
  115687. 1, 64,
  115688. _huff_lengthlist_line_256x7_0sub3,
  115689. 0, 0, 0, 0, 0,
  115690. NULL,
  115691. NULL,
  115692. NULL,
  115693. NULL,
  115694. 0
  115695. };
  115696. static long _huff_lengthlist_line_256x7_1sub1[] = {
  115697. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  115698. };
  115699. static static_codebook _huff_book_line_256x7_1sub1 = {
  115700. 1, 9,
  115701. _huff_lengthlist_line_256x7_1sub1,
  115702. 0, 0, 0, 0, 0,
  115703. NULL,
  115704. NULL,
  115705. NULL,
  115706. NULL,
  115707. 0
  115708. };
  115709. static long _huff_lengthlist_line_256x7_1sub2[] = {
  115710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  115711. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  115712. };
  115713. static static_codebook _huff_book_line_256x7_1sub2 = {
  115714. 1, 25,
  115715. _huff_lengthlist_line_256x7_1sub2,
  115716. 0, 0, 0, 0, 0,
  115717. NULL,
  115718. NULL,
  115719. NULL,
  115720. NULL,
  115721. 0
  115722. };
  115723. static long _huff_lengthlist_line_256x7_1sub3[] = {
  115724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  115726. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  115727. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  115728. };
  115729. static static_codebook _huff_book_line_256x7_1sub3 = {
  115730. 1, 64,
  115731. _huff_lengthlist_line_256x7_1sub3,
  115732. 0, 0, 0, 0, 0,
  115733. NULL,
  115734. NULL,
  115735. NULL,
  115736. NULL,
  115737. 0
  115738. };
  115739. static long _huff_lengthlist_line_256x7_class0[] = {
  115740. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  115741. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  115742. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  115743. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  115744. };
  115745. static static_codebook _huff_book_line_256x7_class0 = {
  115746. 1, 64,
  115747. _huff_lengthlist_line_256x7_class0,
  115748. 0, 0, 0, 0, 0,
  115749. NULL,
  115750. NULL,
  115751. NULL,
  115752. NULL,
  115753. 0
  115754. };
  115755. static long _huff_lengthlist_line_256x7_class1[] = {
  115756. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  115757. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  115758. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  115759. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  115760. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  115761. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  115762. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  115763. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  115764. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  115765. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  115766. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  115767. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  115768. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  115769. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  115770. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  115771. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  115772. };
  115773. static static_codebook _huff_book_line_256x7_class1 = {
  115774. 1, 256,
  115775. _huff_lengthlist_line_256x7_class1,
  115776. 0, 0, 0, 0, 0,
  115777. NULL,
  115778. NULL,
  115779. NULL,
  115780. NULL,
  115781. 0
  115782. };
  115783. static long _huff_lengthlist_line_512x17_0sub0[] = {
  115784. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  115785. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  115786. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  115787. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  115788. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  115789. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  115790. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  115791. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  115792. };
  115793. static static_codebook _huff_book_line_512x17_0sub0 = {
  115794. 1, 128,
  115795. _huff_lengthlist_line_512x17_0sub0,
  115796. 0, 0, 0, 0, 0,
  115797. NULL,
  115798. NULL,
  115799. NULL,
  115800. NULL,
  115801. 0
  115802. };
  115803. static long _huff_lengthlist_line_512x17_1sub0[] = {
  115804. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  115805. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  115806. };
  115807. static static_codebook _huff_book_line_512x17_1sub0 = {
  115808. 1, 32,
  115809. _huff_lengthlist_line_512x17_1sub0,
  115810. 0, 0, 0, 0, 0,
  115811. NULL,
  115812. NULL,
  115813. NULL,
  115814. NULL,
  115815. 0
  115816. };
  115817. static long _huff_lengthlist_line_512x17_1sub1[] = {
  115818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115820. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  115821. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  115822. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  115823. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  115824. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  115825. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  115826. };
  115827. static static_codebook _huff_book_line_512x17_1sub1 = {
  115828. 1, 128,
  115829. _huff_lengthlist_line_512x17_1sub1,
  115830. 0, 0, 0, 0, 0,
  115831. NULL,
  115832. NULL,
  115833. NULL,
  115834. NULL,
  115835. 0
  115836. };
  115837. static long _huff_lengthlist_line_512x17_2sub1[] = {
  115838. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  115839. 5, 3,
  115840. };
  115841. static static_codebook _huff_book_line_512x17_2sub1 = {
  115842. 1, 18,
  115843. _huff_lengthlist_line_512x17_2sub1,
  115844. 0, 0, 0, 0, 0,
  115845. NULL,
  115846. NULL,
  115847. NULL,
  115848. NULL,
  115849. 0
  115850. };
  115851. static long _huff_lengthlist_line_512x17_2sub2[] = {
  115852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115853. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  115854. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  115855. 9, 8,
  115856. };
  115857. static static_codebook _huff_book_line_512x17_2sub2 = {
  115858. 1, 50,
  115859. _huff_lengthlist_line_512x17_2sub2,
  115860. 0, 0, 0, 0, 0,
  115861. NULL,
  115862. NULL,
  115863. NULL,
  115864. NULL,
  115865. 0
  115866. };
  115867. static long _huff_lengthlist_line_512x17_2sub3[] = {
  115868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115871. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  115872. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  115873. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115874. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115875. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115876. };
  115877. static static_codebook _huff_book_line_512x17_2sub3 = {
  115878. 1, 128,
  115879. _huff_lengthlist_line_512x17_2sub3,
  115880. 0, 0, 0, 0, 0,
  115881. NULL,
  115882. NULL,
  115883. NULL,
  115884. NULL,
  115885. 0
  115886. };
  115887. static long _huff_lengthlist_line_512x17_3sub1[] = {
  115888. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  115889. 5, 5,
  115890. };
  115891. static static_codebook _huff_book_line_512x17_3sub1 = {
  115892. 1, 18,
  115893. _huff_lengthlist_line_512x17_3sub1,
  115894. 0, 0, 0, 0, 0,
  115895. NULL,
  115896. NULL,
  115897. NULL,
  115898. NULL,
  115899. 0
  115900. };
  115901. static long _huff_lengthlist_line_512x17_3sub2[] = {
  115902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115903. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  115904. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  115905. 11,14,
  115906. };
  115907. static static_codebook _huff_book_line_512x17_3sub2 = {
  115908. 1, 50,
  115909. _huff_lengthlist_line_512x17_3sub2,
  115910. 0, 0, 0, 0, 0,
  115911. NULL,
  115912. NULL,
  115913. NULL,
  115914. NULL,
  115915. 0
  115916. };
  115917. static long _huff_lengthlist_line_512x17_3sub3[] = {
  115918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115921. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  115922. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115923. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115924. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115925. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115926. };
  115927. static static_codebook _huff_book_line_512x17_3sub3 = {
  115928. 1, 128,
  115929. _huff_lengthlist_line_512x17_3sub3,
  115930. 0, 0, 0, 0, 0,
  115931. NULL,
  115932. NULL,
  115933. NULL,
  115934. NULL,
  115935. 0
  115936. };
  115937. static long _huff_lengthlist_line_512x17_class1[] = {
  115938. 1, 2, 3, 6, 5, 4, 7, 7,
  115939. };
  115940. static static_codebook _huff_book_line_512x17_class1 = {
  115941. 1, 8,
  115942. _huff_lengthlist_line_512x17_class1,
  115943. 0, 0, 0, 0, 0,
  115944. NULL,
  115945. NULL,
  115946. NULL,
  115947. NULL,
  115948. 0
  115949. };
  115950. static long _huff_lengthlist_line_512x17_class2[] = {
  115951. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  115952. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  115953. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  115954. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  115955. };
  115956. static static_codebook _huff_book_line_512x17_class2 = {
  115957. 1, 64,
  115958. _huff_lengthlist_line_512x17_class2,
  115959. 0, 0, 0, 0, 0,
  115960. NULL,
  115961. NULL,
  115962. NULL,
  115963. NULL,
  115964. 0
  115965. };
  115966. static long _huff_lengthlist_line_512x17_class3[] = {
  115967. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  115968. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  115969. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  115970. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  115971. };
  115972. static static_codebook _huff_book_line_512x17_class3 = {
  115973. 1, 64,
  115974. _huff_lengthlist_line_512x17_class3,
  115975. 0, 0, 0, 0, 0,
  115976. NULL,
  115977. NULL,
  115978. NULL,
  115979. NULL,
  115980. 0
  115981. };
  115982. static long _huff_lengthlist_line_128x4_class0[] = {
  115983. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  115984. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  115985. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  115986. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  115987. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  115988. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  115989. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  115990. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  115991. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  115992. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  115993. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  115994. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  115995. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  115996. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  115997. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  115998. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  115999. };
  116000. static static_codebook _huff_book_line_128x4_class0 = {
  116001. 1, 256,
  116002. _huff_lengthlist_line_128x4_class0,
  116003. 0, 0, 0, 0, 0,
  116004. NULL,
  116005. NULL,
  116006. NULL,
  116007. NULL,
  116008. 0
  116009. };
  116010. static long _huff_lengthlist_line_128x4_0sub0[] = {
  116011. 2, 2, 2, 2,
  116012. };
  116013. static static_codebook _huff_book_line_128x4_0sub0 = {
  116014. 1, 4,
  116015. _huff_lengthlist_line_128x4_0sub0,
  116016. 0, 0, 0, 0, 0,
  116017. NULL,
  116018. NULL,
  116019. NULL,
  116020. NULL,
  116021. 0
  116022. };
  116023. static long _huff_lengthlist_line_128x4_0sub1[] = {
  116024. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  116025. };
  116026. static static_codebook _huff_book_line_128x4_0sub1 = {
  116027. 1, 10,
  116028. _huff_lengthlist_line_128x4_0sub1,
  116029. 0, 0, 0, 0, 0,
  116030. NULL,
  116031. NULL,
  116032. NULL,
  116033. NULL,
  116034. 0
  116035. };
  116036. static long _huff_lengthlist_line_128x4_0sub2[] = {
  116037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  116038. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  116039. };
  116040. static static_codebook _huff_book_line_128x4_0sub2 = {
  116041. 1, 25,
  116042. _huff_lengthlist_line_128x4_0sub2,
  116043. 0, 0, 0, 0, 0,
  116044. NULL,
  116045. NULL,
  116046. NULL,
  116047. NULL,
  116048. 0
  116049. };
  116050. static long _huff_lengthlist_line_128x4_0sub3[] = {
  116051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  116053. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  116054. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  116055. };
  116056. static static_codebook _huff_book_line_128x4_0sub3 = {
  116057. 1, 64,
  116058. _huff_lengthlist_line_128x4_0sub3,
  116059. 0, 0, 0, 0, 0,
  116060. NULL,
  116061. NULL,
  116062. NULL,
  116063. NULL,
  116064. 0
  116065. };
  116066. static long _huff_lengthlist_line_256x4_class0[] = {
  116067. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  116068. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  116069. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  116070. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  116071. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  116072. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  116073. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  116074. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  116075. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  116076. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  116077. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  116078. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  116079. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  116080. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  116081. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  116082. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  116083. };
  116084. static static_codebook _huff_book_line_256x4_class0 = {
  116085. 1, 256,
  116086. _huff_lengthlist_line_256x4_class0,
  116087. 0, 0, 0, 0, 0,
  116088. NULL,
  116089. NULL,
  116090. NULL,
  116091. NULL,
  116092. 0
  116093. };
  116094. static long _huff_lengthlist_line_256x4_0sub0[] = {
  116095. 2, 2, 2, 2,
  116096. };
  116097. static static_codebook _huff_book_line_256x4_0sub0 = {
  116098. 1, 4,
  116099. _huff_lengthlist_line_256x4_0sub0,
  116100. 0, 0, 0, 0, 0,
  116101. NULL,
  116102. NULL,
  116103. NULL,
  116104. NULL,
  116105. 0
  116106. };
  116107. static long _huff_lengthlist_line_256x4_0sub1[] = {
  116108. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  116109. };
  116110. static static_codebook _huff_book_line_256x4_0sub1 = {
  116111. 1, 10,
  116112. _huff_lengthlist_line_256x4_0sub1,
  116113. 0, 0, 0, 0, 0,
  116114. NULL,
  116115. NULL,
  116116. NULL,
  116117. NULL,
  116118. 0
  116119. };
  116120. static long _huff_lengthlist_line_256x4_0sub2[] = {
  116121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  116122. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  116123. };
  116124. static static_codebook _huff_book_line_256x4_0sub2 = {
  116125. 1, 25,
  116126. _huff_lengthlist_line_256x4_0sub2,
  116127. 0, 0, 0, 0, 0,
  116128. NULL,
  116129. NULL,
  116130. NULL,
  116131. NULL,
  116132. 0
  116133. };
  116134. static long _huff_lengthlist_line_256x4_0sub3[] = {
  116135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  116137. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  116138. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  116139. };
  116140. static static_codebook _huff_book_line_256x4_0sub3 = {
  116141. 1, 64,
  116142. _huff_lengthlist_line_256x4_0sub3,
  116143. 0, 0, 0, 0, 0,
  116144. NULL,
  116145. NULL,
  116146. NULL,
  116147. NULL,
  116148. 0
  116149. };
  116150. static long _huff_lengthlist_line_128x7_class0[] = {
  116151. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  116152. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  116153. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  116154. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  116155. };
  116156. static static_codebook _huff_book_line_128x7_class0 = {
  116157. 1, 64,
  116158. _huff_lengthlist_line_128x7_class0,
  116159. 0, 0, 0, 0, 0,
  116160. NULL,
  116161. NULL,
  116162. NULL,
  116163. NULL,
  116164. 0
  116165. };
  116166. static long _huff_lengthlist_line_128x7_class1[] = {
  116167. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  116168. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  116169. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  116170. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  116171. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  116172. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  116173. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  116174. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  116175. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  116176. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  116177. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  116178. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  116179. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  116180. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  116181. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  116182. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  116183. };
  116184. static static_codebook _huff_book_line_128x7_class1 = {
  116185. 1, 256,
  116186. _huff_lengthlist_line_128x7_class1,
  116187. 0, 0, 0, 0, 0,
  116188. NULL,
  116189. NULL,
  116190. NULL,
  116191. NULL,
  116192. 0
  116193. };
  116194. static long _huff_lengthlist_line_128x7_0sub1[] = {
  116195. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  116196. };
  116197. static static_codebook _huff_book_line_128x7_0sub1 = {
  116198. 1, 9,
  116199. _huff_lengthlist_line_128x7_0sub1,
  116200. 0, 0, 0, 0, 0,
  116201. NULL,
  116202. NULL,
  116203. NULL,
  116204. NULL,
  116205. 0
  116206. };
  116207. static long _huff_lengthlist_line_128x7_0sub2[] = {
  116208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  116209. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  116210. };
  116211. static static_codebook _huff_book_line_128x7_0sub2 = {
  116212. 1, 25,
  116213. _huff_lengthlist_line_128x7_0sub2,
  116214. 0, 0, 0, 0, 0,
  116215. NULL,
  116216. NULL,
  116217. NULL,
  116218. NULL,
  116219. 0
  116220. };
  116221. static long _huff_lengthlist_line_128x7_0sub3[] = {
  116222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  116224. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116225. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  116226. };
  116227. static static_codebook _huff_book_line_128x7_0sub3 = {
  116228. 1, 64,
  116229. _huff_lengthlist_line_128x7_0sub3,
  116230. 0, 0, 0, 0, 0,
  116231. NULL,
  116232. NULL,
  116233. NULL,
  116234. NULL,
  116235. 0
  116236. };
  116237. static long _huff_lengthlist_line_128x7_1sub1[] = {
  116238. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  116239. };
  116240. static static_codebook _huff_book_line_128x7_1sub1 = {
  116241. 1, 9,
  116242. _huff_lengthlist_line_128x7_1sub1,
  116243. 0, 0, 0, 0, 0,
  116244. NULL,
  116245. NULL,
  116246. NULL,
  116247. NULL,
  116248. 0
  116249. };
  116250. static long _huff_lengthlist_line_128x7_1sub2[] = {
  116251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  116252. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  116253. };
  116254. static static_codebook _huff_book_line_128x7_1sub2 = {
  116255. 1, 25,
  116256. _huff_lengthlist_line_128x7_1sub2,
  116257. 0, 0, 0, 0, 0,
  116258. NULL,
  116259. NULL,
  116260. NULL,
  116261. NULL,
  116262. 0
  116263. };
  116264. static long _huff_lengthlist_line_128x7_1sub3[] = {
  116265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  116267. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  116268. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  116269. };
  116270. static static_codebook _huff_book_line_128x7_1sub3 = {
  116271. 1, 64,
  116272. _huff_lengthlist_line_128x7_1sub3,
  116273. 0, 0, 0, 0, 0,
  116274. NULL,
  116275. NULL,
  116276. NULL,
  116277. NULL,
  116278. 0
  116279. };
  116280. static long _huff_lengthlist_line_128x11_class1[] = {
  116281. 1, 6, 3, 7, 2, 4, 5, 7,
  116282. };
  116283. static static_codebook _huff_book_line_128x11_class1 = {
  116284. 1, 8,
  116285. _huff_lengthlist_line_128x11_class1,
  116286. 0, 0, 0, 0, 0,
  116287. NULL,
  116288. NULL,
  116289. NULL,
  116290. NULL,
  116291. 0
  116292. };
  116293. static long _huff_lengthlist_line_128x11_class2[] = {
  116294. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  116295. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  116296. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  116297. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  116298. };
  116299. static static_codebook _huff_book_line_128x11_class2 = {
  116300. 1, 64,
  116301. _huff_lengthlist_line_128x11_class2,
  116302. 0, 0, 0, 0, 0,
  116303. NULL,
  116304. NULL,
  116305. NULL,
  116306. NULL,
  116307. 0
  116308. };
  116309. static long _huff_lengthlist_line_128x11_class3[] = {
  116310. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  116311. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  116312. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  116313. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  116314. };
  116315. static static_codebook _huff_book_line_128x11_class3 = {
  116316. 1, 64,
  116317. _huff_lengthlist_line_128x11_class3,
  116318. 0, 0, 0, 0, 0,
  116319. NULL,
  116320. NULL,
  116321. NULL,
  116322. NULL,
  116323. 0
  116324. };
  116325. static long _huff_lengthlist_line_128x11_0sub0[] = {
  116326. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116327. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  116328. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  116329. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  116330. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  116331. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  116332. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  116333. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  116334. };
  116335. static static_codebook _huff_book_line_128x11_0sub0 = {
  116336. 1, 128,
  116337. _huff_lengthlist_line_128x11_0sub0,
  116338. 0, 0, 0, 0, 0,
  116339. NULL,
  116340. NULL,
  116341. NULL,
  116342. NULL,
  116343. 0
  116344. };
  116345. static long _huff_lengthlist_line_128x11_1sub0[] = {
  116346. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  116347. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  116348. };
  116349. static static_codebook _huff_book_line_128x11_1sub0 = {
  116350. 1, 32,
  116351. _huff_lengthlist_line_128x11_1sub0,
  116352. 0, 0, 0, 0, 0,
  116353. NULL,
  116354. NULL,
  116355. NULL,
  116356. NULL,
  116357. 0
  116358. };
  116359. static long _huff_lengthlist_line_128x11_1sub1[] = {
  116360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116362. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  116363. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  116364. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  116365. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  116366. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  116367. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  116368. };
  116369. static static_codebook _huff_book_line_128x11_1sub1 = {
  116370. 1, 128,
  116371. _huff_lengthlist_line_128x11_1sub1,
  116372. 0, 0, 0, 0, 0,
  116373. NULL,
  116374. NULL,
  116375. NULL,
  116376. NULL,
  116377. 0
  116378. };
  116379. static long _huff_lengthlist_line_128x11_2sub1[] = {
  116380. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  116381. 5, 5,
  116382. };
  116383. static static_codebook _huff_book_line_128x11_2sub1 = {
  116384. 1, 18,
  116385. _huff_lengthlist_line_128x11_2sub1,
  116386. 0, 0, 0, 0, 0,
  116387. NULL,
  116388. NULL,
  116389. NULL,
  116390. NULL,
  116391. 0
  116392. };
  116393. static long _huff_lengthlist_line_128x11_2sub2[] = {
  116394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116395. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  116396. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  116397. 8,11,
  116398. };
  116399. static static_codebook _huff_book_line_128x11_2sub2 = {
  116400. 1, 50,
  116401. _huff_lengthlist_line_128x11_2sub2,
  116402. 0, 0, 0, 0, 0,
  116403. NULL,
  116404. NULL,
  116405. NULL,
  116406. NULL,
  116407. 0
  116408. };
  116409. static long _huff_lengthlist_line_128x11_2sub3[] = {
  116410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116413. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  116414. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116415. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116416. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116417. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116418. };
  116419. static static_codebook _huff_book_line_128x11_2sub3 = {
  116420. 1, 128,
  116421. _huff_lengthlist_line_128x11_2sub3,
  116422. 0, 0, 0, 0, 0,
  116423. NULL,
  116424. NULL,
  116425. NULL,
  116426. NULL,
  116427. 0
  116428. };
  116429. static long _huff_lengthlist_line_128x11_3sub1[] = {
  116430. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  116431. 5, 4,
  116432. };
  116433. static static_codebook _huff_book_line_128x11_3sub1 = {
  116434. 1, 18,
  116435. _huff_lengthlist_line_128x11_3sub1,
  116436. 0, 0, 0, 0, 0,
  116437. NULL,
  116438. NULL,
  116439. NULL,
  116440. NULL,
  116441. 0
  116442. };
  116443. static long _huff_lengthlist_line_128x11_3sub2[] = {
  116444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116445. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  116446. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  116447. 12, 6,
  116448. };
  116449. static static_codebook _huff_book_line_128x11_3sub2 = {
  116450. 1, 50,
  116451. _huff_lengthlist_line_128x11_3sub2,
  116452. 0, 0, 0, 0, 0,
  116453. NULL,
  116454. NULL,
  116455. NULL,
  116456. NULL,
  116457. 0
  116458. };
  116459. static long _huff_lengthlist_line_128x11_3sub3[] = {
  116460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116463. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  116464. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  116465. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116466. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116467. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  116468. };
  116469. static static_codebook _huff_book_line_128x11_3sub3 = {
  116470. 1, 128,
  116471. _huff_lengthlist_line_128x11_3sub3,
  116472. 0, 0, 0, 0, 0,
  116473. NULL,
  116474. NULL,
  116475. NULL,
  116476. NULL,
  116477. 0
  116478. };
  116479. static long _huff_lengthlist_line_128x17_class1[] = {
  116480. 1, 3, 4, 7, 2, 5, 6, 7,
  116481. };
  116482. static static_codebook _huff_book_line_128x17_class1 = {
  116483. 1, 8,
  116484. _huff_lengthlist_line_128x17_class1,
  116485. 0, 0, 0, 0, 0,
  116486. NULL,
  116487. NULL,
  116488. NULL,
  116489. NULL,
  116490. 0
  116491. };
  116492. static long _huff_lengthlist_line_128x17_class2[] = {
  116493. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  116494. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  116495. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  116496. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  116497. };
  116498. static static_codebook _huff_book_line_128x17_class2 = {
  116499. 1, 64,
  116500. _huff_lengthlist_line_128x17_class2,
  116501. 0, 0, 0, 0, 0,
  116502. NULL,
  116503. NULL,
  116504. NULL,
  116505. NULL,
  116506. 0
  116507. };
  116508. static long _huff_lengthlist_line_128x17_class3[] = {
  116509. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  116510. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  116511. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  116512. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  116513. };
  116514. static static_codebook _huff_book_line_128x17_class3 = {
  116515. 1, 64,
  116516. _huff_lengthlist_line_128x17_class3,
  116517. 0, 0, 0, 0, 0,
  116518. NULL,
  116519. NULL,
  116520. NULL,
  116521. NULL,
  116522. 0
  116523. };
  116524. static long _huff_lengthlist_line_128x17_0sub0[] = {
  116525. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116526. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  116527. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  116528. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  116529. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  116530. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  116531. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  116532. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  116533. };
  116534. static static_codebook _huff_book_line_128x17_0sub0 = {
  116535. 1, 128,
  116536. _huff_lengthlist_line_128x17_0sub0,
  116537. 0, 0, 0, 0, 0,
  116538. NULL,
  116539. NULL,
  116540. NULL,
  116541. NULL,
  116542. 0
  116543. };
  116544. static long _huff_lengthlist_line_128x17_1sub0[] = {
  116545. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  116546. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  116547. };
  116548. static static_codebook _huff_book_line_128x17_1sub0 = {
  116549. 1, 32,
  116550. _huff_lengthlist_line_128x17_1sub0,
  116551. 0, 0, 0, 0, 0,
  116552. NULL,
  116553. NULL,
  116554. NULL,
  116555. NULL,
  116556. 0
  116557. };
  116558. static long _huff_lengthlist_line_128x17_1sub1[] = {
  116559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116561. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  116562. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  116563. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  116564. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  116565. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  116566. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  116567. };
  116568. static static_codebook _huff_book_line_128x17_1sub1 = {
  116569. 1, 128,
  116570. _huff_lengthlist_line_128x17_1sub1,
  116571. 0, 0, 0, 0, 0,
  116572. NULL,
  116573. NULL,
  116574. NULL,
  116575. NULL,
  116576. 0
  116577. };
  116578. static long _huff_lengthlist_line_128x17_2sub1[] = {
  116579. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  116580. 9, 4,
  116581. };
  116582. static static_codebook _huff_book_line_128x17_2sub1 = {
  116583. 1, 18,
  116584. _huff_lengthlist_line_128x17_2sub1,
  116585. 0, 0, 0, 0, 0,
  116586. NULL,
  116587. NULL,
  116588. NULL,
  116589. NULL,
  116590. 0
  116591. };
  116592. static long _huff_lengthlist_line_128x17_2sub2[] = {
  116593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116594. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  116595. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  116596. 13,13,
  116597. };
  116598. static static_codebook _huff_book_line_128x17_2sub2 = {
  116599. 1, 50,
  116600. _huff_lengthlist_line_128x17_2sub2,
  116601. 0, 0, 0, 0, 0,
  116602. NULL,
  116603. NULL,
  116604. NULL,
  116605. NULL,
  116606. 0
  116607. };
  116608. static long _huff_lengthlist_line_128x17_2sub3[] = {
  116609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116612. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116613. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  116614. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  116615. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  116616. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  116617. };
  116618. static static_codebook _huff_book_line_128x17_2sub3 = {
  116619. 1, 128,
  116620. _huff_lengthlist_line_128x17_2sub3,
  116621. 0, 0, 0, 0, 0,
  116622. NULL,
  116623. NULL,
  116624. NULL,
  116625. NULL,
  116626. 0
  116627. };
  116628. static long _huff_lengthlist_line_128x17_3sub1[] = {
  116629. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  116630. 6, 4,
  116631. };
  116632. static static_codebook _huff_book_line_128x17_3sub1 = {
  116633. 1, 18,
  116634. _huff_lengthlist_line_128x17_3sub1,
  116635. 0, 0, 0, 0, 0,
  116636. NULL,
  116637. NULL,
  116638. NULL,
  116639. NULL,
  116640. 0
  116641. };
  116642. static long _huff_lengthlist_line_128x17_3sub2[] = {
  116643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116644. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  116645. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  116646. 10, 8,
  116647. };
  116648. static static_codebook _huff_book_line_128x17_3sub2 = {
  116649. 1, 50,
  116650. _huff_lengthlist_line_128x17_3sub2,
  116651. 0, 0, 0, 0, 0,
  116652. NULL,
  116653. NULL,
  116654. NULL,
  116655. NULL,
  116656. 0
  116657. };
  116658. static long _huff_lengthlist_line_128x17_3sub3[] = {
  116659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116662. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  116663. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  116664. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  116665. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  116666. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  116667. };
  116668. static static_codebook _huff_book_line_128x17_3sub3 = {
  116669. 1, 128,
  116670. _huff_lengthlist_line_128x17_3sub3,
  116671. 0, 0, 0, 0, 0,
  116672. NULL,
  116673. NULL,
  116674. NULL,
  116675. NULL,
  116676. 0
  116677. };
  116678. static long _huff_lengthlist_line_1024x27_class1[] = {
  116679. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  116680. };
  116681. static static_codebook _huff_book_line_1024x27_class1 = {
  116682. 1, 16,
  116683. _huff_lengthlist_line_1024x27_class1,
  116684. 0, 0, 0, 0, 0,
  116685. NULL,
  116686. NULL,
  116687. NULL,
  116688. NULL,
  116689. 0
  116690. };
  116691. static long _huff_lengthlist_line_1024x27_class2[] = {
  116692. 1, 4, 2, 6, 3, 7, 5, 7,
  116693. };
  116694. static static_codebook _huff_book_line_1024x27_class2 = {
  116695. 1, 8,
  116696. _huff_lengthlist_line_1024x27_class2,
  116697. 0, 0, 0, 0, 0,
  116698. NULL,
  116699. NULL,
  116700. NULL,
  116701. NULL,
  116702. 0
  116703. };
  116704. static long _huff_lengthlist_line_1024x27_class3[] = {
  116705. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  116706. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  116707. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  116708. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  116709. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  116710. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  116711. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  116712. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  116713. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  116714. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  116715. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  116716. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  116717. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  116718. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  116719. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  116720. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  116721. };
  116722. static static_codebook _huff_book_line_1024x27_class3 = {
  116723. 1, 256,
  116724. _huff_lengthlist_line_1024x27_class3,
  116725. 0, 0, 0, 0, 0,
  116726. NULL,
  116727. NULL,
  116728. NULL,
  116729. NULL,
  116730. 0
  116731. };
  116732. static long _huff_lengthlist_line_1024x27_class4[] = {
  116733. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  116734. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  116735. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  116736. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  116737. };
  116738. static static_codebook _huff_book_line_1024x27_class4 = {
  116739. 1, 64,
  116740. _huff_lengthlist_line_1024x27_class4,
  116741. 0, 0, 0, 0, 0,
  116742. NULL,
  116743. NULL,
  116744. NULL,
  116745. NULL,
  116746. 0
  116747. };
  116748. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  116749. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116750. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  116751. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  116752. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  116753. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  116754. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  116755. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  116756. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  116757. };
  116758. static static_codebook _huff_book_line_1024x27_0sub0 = {
  116759. 1, 128,
  116760. _huff_lengthlist_line_1024x27_0sub0,
  116761. 0, 0, 0, 0, 0,
  116762. NULL,
  116763. NULL,
  116764. NULL,
  116765. NULL,
  116766. 0
  116767. };
  116768. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  116769. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  116770. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  116771. };
  116772. static static_codebook _huff_book_line_1024x27_1sub0 = {
  116773. 1, 32,
  116774. _huff_lengthlist_line_1024x27_1sub0,
  116775. 0, 0, 0, 0, 0,
  116776. NULL,
  116777. NULL,
  116778. NULL,
  116779. NULL,
  116780. 0
  116781. };
  116782. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  116783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116785. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  116786. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  116787. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  116788. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  116789. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  116790. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  116791. };
  116792. static static_codebook _huff_book_line_1024x27_1sub1 = {
  116793. 1, 128,
  116794. _huff_lengthlist_line_1024x27_1sub1,
  116795. 0, 0, 0, 0, 0,
  116796. NULL,
  116797. NULL,
  116798. NULL,
  116799. NULL,
  116800. 0
  116801. };
  116802. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  116803. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116804. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  116805. };
  116806. static static_codebook _huff_book_line_1024x27_2sub0 = {
  116807. 1, 32,
  116808. _huff_lengthlist_line_1024x27_2sub0,
  116809. 0, 0, 0, 0, 0,
  116810. NULL,
  116811. NULL,
  116812. NULL,
  116813. NULL,
  116814. 0
  116815. };
  116816. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  116817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116819. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  116820. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  116821. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  116822. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  116823. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  116824. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  116825. };
  116826. static static_codebook _huff_book_line_1024x27_2sub1 = {
  116827. 1, 128,
  116828. _huff_lengthlist_line_1024x27_2sub1,
  116829. 0, 0, 0, 0, 0,
  116830. NULL,
  116831. NULL,
  116832. NULL,
  116833. NULL,
  116834. 0
  116835. };
  116836. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  116837. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  116838. 5, 5,
  116839. };
  116840. static static_codebook _huff_book_line_1024x27_3sub1 = {
  116841. 1, 18,
  116842. _huff_lengthlist_line_1024x27_3sub1,
  116843. 0, 0, 0, 0, 0,
  116844. NULL,
  116845. NULL,
  116846. NULL,
  116847. NULL,
  116848. 0
  116849. };
  116850. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  116851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116852. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  116853. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  116854. 9,11,
  116855. };
  116856. static static_codebook _huff_book_line_1024x27_3sub2 = {
  116857. 1, 50,
  116858. _huff_lengthlist_line_1024x27_3sub2,
  116859. 0, 0, 0, 0, 0,
  116860. NULL,
  116861. NULL,
  116862. NULL,
  116863. NULL,
  116864. 0
  116865. };
  116866. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  116867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116870. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  116871. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  116872. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116873. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116874. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116875. };
  116876. static static_codebook _huff_book_line_1024x27_3sub3 = {
  116877. 1, 128,
  116878. _huff_lengthlist_line_1024x27_3sub3,
  116879. 0, 0, 0, 0, 0,
  116880. NULL,
  116881. NULL,
  116882. NULL,
  116883. NULL,
  116884. 0
  116885. };
  116886. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  116887. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  116888. 5, 4,
  116889. };
  116890. static static_codebook _huff_book_line_1024x27_4sub1 = {
  116891. 1, 18,
  116892. _huff_lengthlist_line_1024x27_4sub1,
  116893. 0, 0, 0, 0, 0,
  116894. NULL,
  116895. NULL,
  116896. NULL,
  116897. NULL,
  116898. 0
  116899. };
  116900. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  116901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116902. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  116903. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  116904. 9,12,
  116905. };
  116906. static static_codebook _huff_book_line_1024x27_4sub2 = {
  116907. 1, 50,
  116908. _huff_lengthlist_line_1024x27_4sub2,
  116909. 0, 0, 0, 0, 0,
  116910. NULL,
  116911. NULL,
  116912. NULL,
  116913. NULL,
  116914. 0
  116915. };
  116916. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  116917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116920. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  116921. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  116922. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  116923. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  116924. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  116925. };
  116926. static static_codebook _huff_book_line_1024x27_4sub3 = {
  116927. 1, 128,
  116928. _huff_lengthlist_line_1024x27_4sub3,
  116929. 0, 0, 0, 0, 0,
  116930. NULL,
  116931. NULL,
  116932. NULL,
  116933. NULL,
  116934. 0
  116935. };
  116936. static long _huff_lengthlist_line_2048x27_class1[] = {
  116937. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  116938. };
  116939. static static_codebook _huff_book_line_2048x27_class1 = {
  116940. 1, 16,
  116941. _huff_lengthlist_line_2048x27_class1,
  116942. 0, 0, 0, 0, 0,
  116943. NULL,
  116944. NULL,
  116945. NULL,
  116946. NULL,
  116947. 0
  116948. };
  116949. static long _huff_lengthlist_line_2048x27_class2[] = {
  116950. 1, 2, 3, 6, 4, 7, 5, 7,
  116951. };
  116952. static static_codebook _huff_book_line_2048x27_class2 = {
  116953. 1, 8,
  116954. _huff_lengthlist_line_2048x27_class2,
  116955. 0, 0, 0, 0, 0,
  116956. NULL,
  116957. NULL,
  116958. NULL,
  116959. NULL,
  116960. 0
  116961. };
  116962. static long _huff_lengthlist_line_2048x27_class3[] = {
  116963. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  116964. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  116965. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  116966. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  116967. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  116968. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  116969. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  116970. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  116971. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  116972. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  116973. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  116974. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  116975. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  116976. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  116977. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  116978. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  116979. };
  116980. static static_codebook _huff_book_line_2048x27_class3 = {
  116981. 1, 256,
  116982. _huff_lengthlist_line_2048x27_class3,
  116983. 0, 0, 0, 0, 0,
  116984. NULL,
  116985. NULL,
  116986. NULL,
  116987. NULL,
  116988. 0
  116989. };
  116990. static long _huff_lengthlist_line_2048x27_class4[] = {
  116991. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  116992. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  116993. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  116994. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  116995. };
  116996. static static_codebook _huff_book_line_2048x27_class4 = {
  116997. 1, 64,
  116998. _huff_lengthlist_line_2048x27_class4,
  116999. 0, 0, 0, 0, 0,
  117000. NULL,
  117001. NULL,
  117002. NULL,
  117003. NULL,
  117004. 0
  117005. };
  117006. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  117007. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117008. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  117009. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  117010. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  117011. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  117012. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  117013. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  117014. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  117015. };
  117016. static static_codebook _huff_book_line_2048x27_0sub0 = {
  117017. 1, 128,
  117018. _huff_lengthlist_line_2048x27_0sub0,
  117019. 0, 0, 0, 0, 0,
  117020. NULL,
  117021. NULL,
  117022. NULL,
  117023. NULL,
  117024. 0
  117025. };
  117026. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  117027. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  117028. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  117029. };
  117030. static static_codebook _huff_book_line_2048x27_1sub0 = {
  117031. 1, 32,
  117032. _huff_lengthlist_line_2048x27_1sub0,
  117033. 0, 0, 0, 0, 0,
  117034. NULL,
  117035. NULL,
  117036. NULL,
  117037. NULL,
  117038. 0
  117039. };
  117040. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  117041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117043. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  117044. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  117045. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  117046. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  117047. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  117048. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  117049. };
  117050. static static_codebook _huff_book_line_2048x27_1sub1 = {
  117051. 1, 128,
  117052. _huff_lengthlist_line_2048x27_1sub1,
  117053. 0, 0, 0, 0, 0,
  117054. NULL,
  117055. NULL,
  117056. NULL,
  117057. NULL,
  117058. 0
  117059. };
  117060. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  117061. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  117062. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  117063. };
  117064. static static_codebook _huff_book_line_2048x27_2sub0 = {
  117065. 1, 32,
  117066. _huff_lengthlist_line_2048x27_2sub0,
  117067. 0, 0, 0, 0, 0,
  117068. NULL,
  117069. NULL,
  117070. NULL,
  117071. NULL,
  117072. 0
  117073. };
  117074. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  117075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117077. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  117078. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  117079. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  117080. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  117081. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  117082. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117083. };
  117084. static static_codebook _huff_book_line_2048x27_2sub1 = {
  117085. 1, 128,
  117086. _huff_lengthlist_line_2048x27_2sub1,
  117087. 0, 0, 0, 0, 0,
  117088. NULL,
  117089. NULL,
  117090. NULL,
  117091. NULL,
  117092. 0
  117093. };
  117094. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  117095. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  117096. 5, 5,
  117097. };
  117098. static static_codebook _huff_book_line_2048x27_3sub1 = {
  117099. 1, 18,
  117100. _huff_lengthlist_line_2048x27_3sub1,
  117101. 0, 0, 0, 0, 0,
  117102. NULL,
  117103. NULL,
  117104. NULL,
  117105. NULL,
  117106. 0
  117107. };
  117108. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  117109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117110. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  117111. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  117112. 10,12,
  117113. };
  117114. static static_codebook _huff_book_line_2048x27_3sub2 = {
  117115. 1, 50,
  117116. _huff_lengthlist_line_2048x27_3sub2,
  117117. 0, 0, 0, 0, 0,
  117118. NULL,
  117119. NULL,
  117120. NULL,
  117121. NULL,
  117122. 0
  117123. };
  117124. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  117125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117128. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  117129. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117130. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117131. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117132. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117133. };
  117134. static static_codebook _huff_book_line_2048x27_3sub3 = {
  117135. 1, 128,
  117136. _huff_lengthlist_line_2048x27_3sub3,
  117137. 0, 0, 0, 0, 0,
  117138. NULL,
  117139. NULL,
  117140. NULL,
  117141. NULL,
  117142. 0
  117143. };
  117144. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  117145. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  117146. 4, 5,
  117147. };
  117148. static static_codebook _huff_book_line_2048x27_4sub1 = {
  117149. 1, 18,
  117150. _huff_lengthlist_line_2048x27_4sub1,
  117151. 0, 0, 0, 0, 0,
  117152. NULL,
  117153. NULL,
  117154. NULL,
  117155. NULL,
  117156. 0
  117157. };
  117158. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  117159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117160. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  117161. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  117162. 10,10,
  117163. };
  117164. static static_codebook _huff_book_line_2048x27_4sub2 = {
  117165. 1, 50,
  117166. _huff_lengthlist_line_2048x27_4sub2,
  117167. 0, 0, 0, 0, 0,
  117168. NULL,
  117169. NULL,
  117170. NULL,
  117171. NULL,
  117172. 0
  117173. };
  117174. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  117175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117178. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  117179. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  117180. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117181. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117182. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117183. };
  117184. static static_codebook _huff_book_line_2048x27_4sub3 = {
  117185. 1, 128,
  117186. _huff_lengthlist_line_2048x27_4sub3,
  117187. 0, 0, 0, 0, 0,
  117188. NULL,
  117189. NULL,
  117190. NULL,
  117191. NULL,
  117192. 0
  117193. };
  117194. static long _huff_lengthlist_line_256x4low_class0[] = {
  117195. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  117196. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  117197. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  117198. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  117199. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  117200. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  117201. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  117202. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  117203. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  117204. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  117205. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  117206. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  117207. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  117208. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  117209. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  117210. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  117211. };
  117212. static static_codebook _huff_book_line_256x4low_class0 = {
  117213. 1, 256,
  117214. _huff_lengthlist_line_256x4low_class0,
  117215. 0, 0, 0, 0, 0,
  117216. NULL,
  117217. NULL,
  117218. NULL,
  117219. NULL,
  117220. 0
  117221. };
  117222. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  117223. 1, 3, 2, 3,
  117224. };
  117225. static static_codebook _huff_book_line_256x4low_0sub0 = {
  117226. 1, 4,
  117227. _huff_lengthlist_line_256x4low_0sub0,
  117228. 0, 0, 0, 0, 0,
  117229. NULL,
  117230. NULL,
  117231. NULL,
  117232. NULL,
  117233. 0
  117234. };
  117235. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  117236. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  117237. };
  117238. static static_codebook _huff_book_line_256x4low_0sub1 = {
  117239. 1, 10,
  117240. _huff_lengthlist_line_256x4low_0sub1,
  117241. 0, 0, 0, 0, 0,
  117242. NULL,
  117243. NULL,
  117244. NULL,
  117245. NULL,
  117246. 0
  117247. };
  117248. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  117249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  117250. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  117251. };
  117252. static static_codebook _huff_book_line_256x4low_0sub2 = {
  117253. 1, 25,
  117254. _huff_lengthlist_line_256x4low_0sub2,
  117255. 0, 0, 0, 0, 0,
  117256. NULL,
  117257. NULL,
  117258. NULL,
  117259. NULL,
  117260. 0
  117261. };
  117262. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  117263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  117265. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  117266. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  117267. };
  117268. static static_codebook _huff_book_line_256x4low_0sub3 = {
  117269. 1, 64,
  117270. _huff_lengthlist_line_256x4low_0sub3,
  117271. 0, 0, 0, 0, 0,
  117272. NULL,
  117273. NULL,
  117274. NULL,
  117275. NULL,
  117276. 0
  117277. };
  117278. /********* End of inlined file: floor_books.h *********/
  117279. static static_codebook *_floor_128x4_books[]={
  117280. &_huff_book_line_128x4_class0,
  117281. &_huff_book_line_128x4_0sub0,
  117282. &_huff_book_line_128x4_0sub1,
  117283. &_huff_book_line_128x4_0sub2,
  117284. &_huff_book_line_128x4_0sub3,
  117285. };
  117286. static static_codebook *_floor_256x4_books[]={
  117287. &_huff_book_line_256x4_class0,
  117288. &_huff_book_line_256x4_0sub0,
  117289. &_huff_book_line_256x4_0sub1,
  117290. &_huff_book_line_256x4_0sub2,
  117291. &_huff_book_line_256x4_0sub3,
  117292. };
  117293. static static_codebook *_floor_128x7_books[]={
  117294. &_huff_book_line_128x7_class0,
  117295. &_huff_book_line_128x7_class1,
  117296. &_huff_book_line_128x7_0sub1,
  117297. &_huff_book_line_128x7_0sub2,
  117298. &_huff_book_line_128x7_0sub3,
  117299. &_huff_book_line_128x7_1sub1,
  117300. &_huff_book_line_128x7_1sub2,
  117301. &_huff_book_line_128x7_1sub3,
  117302. };
  117303. static static_codebook *_floor_256x7_books[]={
  117304. &_huff_book_line_256x7_class0,
  117305. &_huff_book_line_256x7_class1,
  117306. &_huff_book_line_256x7_0sub1,
  117307. &_huff_book_line_256x7_0sub2,
  117308. &_huff_book_line_256x7_0sub3,
  117309. &_huff_book_line_256x7_1sub1,
  117310. &_huff_book_line_256x7_1sub2,
  117311. &_huff_book_line_256x7_1sub3,
  117312. };
  117313. static static_codebook *_floor_128x11_books[]={
  117314. &_huff_book_line_128x11_class1,
  117315. &_huff_book_line_128x11_class2,
  117316. &_huff_book_line_128x11_class3,
  117317. &_huff_book_line_128x11_0sub0,
  117318. &_huff_book_line_128x11_1sub0,
  117319. &_huff_book_line_128x11_1sub1,
  117320. &_huff_book_line_128x11_2sub1,
  117321. &_huff_book_line_128x11_2sub2,
  117322. &_huff_book_line_128x11_2sub3,
  117323. &_huff_book_line_128x11_3sub1,
  117324. &_huff_book_line_128x11_3sub2,
  117325. &_huff_book_line_128x11_3sub3,
  117326. };
  117327. static static_codebook *_floor_128x17_books[]={
  117328. &_huff_book_line_128x17_class1,
  117329. &_huff_book_line_128x17_class2,
  117330. &_huff_book_line_128x17_class3,
  117331. &_huff_book_line_128x17_0sub0,
  117332. &_huff_book_line_128x17_1sub0,
  117333. &_huff_book_line_128x17_1sub1,
  117334. &_huff_book_line_128x17_2sub1,
  117335. &_huff_book_line_128x17_2sub2,
  117336. &_huff_book_line_128x17_2sub3,
  117337. &_huff_book_line_128x17_3sub1,
  117338. &_huff_book_line_128x17_3sub2,
  117339. &_huff_book_line_128x17_3sub3,
  117340. };
  117341. static static_codebook *_floor_256x4low_books[]={
  117342. &_huff_book_line_256x4low_class0,
  117343. &_huff_book_line_256x4low_0sub0,
  117344. &_huff_book_line_256x4low_0sub1,
  117345. &_huff_book_line_256x4low_0sub2,
  117346. &_huff_book_line_256x4low_0sub3,
  117347. };
  117348. static static_codebook *_floor_1024x27_books[]={
  117349. &_huff_book_line_1024x27_class1,
  117350. &_huff_book_line_1024x27_class2,
  117351. &_huff_book_line_1024x27_class3,
  117352. &_huff_book_line_1024x27_class4,
  117353. &_huff_book_line_1024x27_0sub0,
  117354. &_huff_book_line_1024x27_1sub0,
  117355. &_huff_book_line_1024x27_1sub1,
  117356. &_huff_book_line_1024x27_2sub0,
  117357. &_huff_book_line_1024x27_2sub1,
  117358. &_huff_book_line_1024x27_3sub1,
  117359. &_huff_book_line_1024x27_3sub2,
  117360. &_huff_book_line_1024x27_3sub3,
  117361. &_huff_book_line_1024x27_4sub1,
  117362. &_huff_book_line_1024x27_4sub2,
  117363. &_huff_book_line_1024x27_4sub3,
  117364. };
  117365. static static_codebook *_floor_2048x27_books[]={
  117366. &_huff_book_line_2048x27_class1,
  117367. &_huff_book_line_2048x27_class2,
  117368. &_huff_book_line_2048x27_class3,
  117369. &_huff_book_line_2048x27_class4,
  117370. &_huff_book_line_2048x27_0sub0,
  117371. &_huff_book_line_2048x27_1sub0,
  117372. &_huff_book_line_2048x27_1sub1,
  117373. &_huff_book_line_2048x27_2sub0,
  117374. &_huff_book_line_2048x27_2sub1,
  117375. &_huff_book_line_2048x27_3sub1,
  117376. &_huff_book_line_2048x27_3sub2,
  117377. &_huff_book_line_2048x27_3sub3,
  117378. &_huff_book_line_2048x27_4sub1,
  117379. &_huff_book_line_2048x27_4sub2,
  117380. &_huff_book_line_2048x27_4sub3,
  117381. };
  117382. static static_codebook *_floor_512x17_books[]={
  117383. &_huff_book_line_512x17_class1,
  117384. &_huff_book_line_512x17_class2,
  117385. &_huff_book_line_512x17_class3,
  117386. &_huff_book_line_512x17_0sub0,
  117387. &_huff_book_line_512x17_1sub0,
  117388. &_huff_book_line_512x17_1sub1,
  117389. &_huff_book_line_512x17_2sub1,
  117390. &_huff_book_line_512x17_2sub2,
  117391. &_huff_book_line_512x17_2sub3,
  117392. &_huff_book_line_512x17_3sub1,
  117393. &_huff_book_line_512x17_3sub2,
  117394. &_huff_book_line_512x17_3sub3,
  117395. };
  117396. static static_codebook **_floor_books[10]={
  117397. _floor_128x4_books,
  117398. _floor_256x4_books,
  117399. _floor_128x7_books,
  117400. _floor_256x7_books,
  117401. _floor_128x11_books,
  117402. _floor_128x17_books,
  117403. _floor_256x4low_books,
  117404. _floor_1024x27_books,
  117405. _floor_2048x27_books,
  117406. _floor_512x17_books,
  117407. };
  117408. static vorbis_info_floor1 _floor[10]={
  117409. /* 128 x 4 */
  117410. {
  117411. 1,{0},{4},{2},{0},
  117412. {{1,2,3,4}},
  117413. 4,{0,128, 33,8,16,70},
  117414. 60,30,500, 1.,18., -1
  117415. },
  117416. /* 256 x 4 */
  117417. {
  117418. 1,{0},{4},{2},{0},
  117419. {{1,2,3,4}},
  117420. 4,{0,256, 66,16,32,140},
  117421. 60,30,500, 1.,18., -1
  117422. },
  117423. /* 128 x 7 */
  117424. {
  117425. 2,{0,1},{3,4},{2,2},{0,1},
  117426. {{-1,2,3,4},{-1,5,6,7}},
  117427. 4,{0,128, 14,4,58, 2,8,28,90},
  117428. 60,30,500, 1.,18., -1
  117429. },
  117430. /* 256 x 7 */
  117431. {
  117432. 2,{0,1},{3,4},{2,2},{0,1},
  117433. {{-1,2,3,4},{-1,5,6,7}},
  117434. 4,{0,256, 28,8,116, 4,16,56,180},
  117435. 60,30,500, 1.,18., -1
  117436. },
  117437. /* 128 x 11 */
  117438. {
  117439. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  117440. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  117441. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  117442. 60,30,500, 1,18., -1
  117443. },
  117444. /* 128 x 17 */
  117445. {
  117446. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  117447. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  117448. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  117449. 60,30,500, 1,18., -1
  117450. },
  117451. /* 256 x 4 (low bitrate version) */
  117452. {
  117453. 1,{0},{4},{2},{0},
  117454. {{1,2,3,4}},
  117455. 4,{0,256, 66,16,32,140},
  117456. 60,30,500, 1.,18., -1
  117457. },
  117458. /* 1024 x 27 */
  117459. {
  117460. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  117461. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  117462. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  117463. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  117464. 60,30,500, 3,18., -1 /* lowpass */
  117465. },
  117466. /* 2048 x 27 */
  117467. {
  117468. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  117469. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  117470. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  117471. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  117472. 60,30,500, 3,18., -1 /* lowpass */
  117473. },
  117474. /* 512 x 17 */
  117475. {
  117476. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  117477. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  117478. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  117479. 7,23,39, 55,79,110, 156,232,360},
  117480. 60,30,500, 1,18., -1 /* lowpass! */
  117481. },
  117482. };
  117483. /********* End of inlined file: floor_all.h *********/
  117484. /********* Start of inlined file: residue_44.h *********/
  117485. /********* Start of inlined file: res_books_stereo.h *********/
  117486. static long _vq_quantlist__16c0_s_p1_0[] = {
  117487. 1,
  117488. 0,
  117489. 2,
  117490. };
  117491. static long _vq_lengthlist__16c0_s_p1_0[] = {
  117492. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  117493. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117497. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  117498. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117502. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  117503. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  117538. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  117539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  117543. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  117544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  117548. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  117549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117583. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  117584. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117588. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  117589. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  117590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117593. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  117594. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  117595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117902. 0,
  117903. };
  117904. static float _vq_quantthresh__16c0_s_p1_0[] = {
  117905. -0.5, 0.5,
  117906. };
  117907. static long _vq_quantmap__16c0_s_p1_0[] = {
  117908. 1, 0, 2,
  117909. };
  117910. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  117911. _vq_quantthresh__16c0_s_p1_0,
  117912. _vq_quantmap__16c0_s_p1_0,
  117913. 3,
  117914. 3
  117915. };
  117916. static static_codebook _16c0_s_p1_0 = {
  117917. 8, 6561,
  117918. _vq_lengthlist__16c0_s_p1_0,
  117919. 1, -535822336, 1611661312, 2, 0,
  117920. _vq_quantlist__16c0_s_p1_0,
  117921. NULL,
  117922. &_vq_auxt__16c0_s_p1_0,
  117923. NULL,
  117924. 0
  117925. };
  117926. static long _vq_quantlist__16c0_s_p2_0[] = {
  117927. 2,
  117928. 1,
  117929. 3,
  117930. 0,
  117931. 4,
  117932. };
  117933. static long _vq_lengthlist__16c0_s_p2_0[] = {
  117934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117973. 0,
  117974. };
  117975. static float _vq_quantthresh__16c0_s_p2_0[] = {
  117976. -1.5, -0.5, 0.5, 1.5,
  117977. };
  117978. static long _vq_quantmap__16c0_s_p2_0[] = {
  117979. 3, 1, 0, 2, 4,
  117980. };
  117981. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  117982. _vq_quantthresh__16c0_s_p2_0,
  117983. _vq_quantmap__16c0_s_p2_0,
  117984. 5,
  117985. 5
  117986. };
  117987. static static_codebook _16c0_s_p2_0 = {
  117988. 4, 625,
  117989. _vq_lengthlist__16c0_s_p2_0,
  117990. 1, -533725184, 1611661312, 3, 0,
  117991. _vq_quantlist__16c0_s_p2_0,
  117992. NULL,
  117993. &_vq_auxt__16c0_s_p2_0,
  117994. NULL,
  117995. 0
  117996. };
  117997. static long _vq_quantlist__16c0_s_p3_0[] = {
  117998. 2,
  117999. 1,
  118000. 3,
  118001. 0,
  118002. 4,
  118003. };
  118004. static long _vq_lengthlist__16c0_s_p3_0[] = {
  118005. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  118007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118008. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  118010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118011. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  118012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118044. 0,
  118045. };
  118046. static float _vq_quantthresh__16c0_s_p3_0[] = {
  118047. -1.5, -0.5, 0.5, 1.5,
  118048. };
  118049. static long _vq_quantmap__16c0_s_p3_0[] = {
  118050. 3, 1, 0, 2, 4,
  118051. };
  118052. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  118053. _vq_quantthresh__16c0_s_p3_0,
  118054. _vq_quantmap__16c0_s_p3_0,
  118055. 5,
  118056. 5
  118057. };
  118058. static static_codebook _16c0_s_p3_0 = {
  118059. 4, 625,
  118060. _vq_lengthlist__16c0_s_p3_0,
  118061. 1, -533725184, 1611661312, 3, 0,
  118062. _vq_quantlist__16c0_s_p3_0,
  118063. NULL,
  118064. &_vq_auxt__16c0_s_p3_0,
  118065. NULL,
  118066. 0
  118067. };
  118068. static long _vq_quantlist__16c0_s_p4_0[] = {
  118069. 4,
  118070. 3,
  118071. 5,
  118072. 2,
  118073. 6,
  118074. 1,
  118075. 7,
  118076. 0,
  118077. 8,
  118078. };
  118079. static long _vq_lengthlist__16c0_s_p4_0[] = {
  118080. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  118081. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  118082. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  118083. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  118084. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118085. 0,
  118086. };
  118087. static float _vq_quantthresh__16c0_s_p4_0[] = {
  118088. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118089. };
  118090. static long _vq_quantmap__16c0_s_p4_0[] = {
  118091. 7, 5, 3, 1, 0, 2, 4, 6,
  118092. 8,
  118093. };
  118094. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  118095. _vq_quantthresh__16c0_s_p4_0,
  118096. _vq_quantmap__16c0_s_p4_0,
  118097. 9,
  118098. 9
  118099. };
  118100. static static_codebook _16c0_s_p4_0 = {
  118101. 2, 81,
  118102. _vq_lengthlist__16c0_s_p4_0,
  118103. 1, -531628032, 1611661312, 4, 0,
  118104. _vq_quantlist__16c0_s_p4_0,
  118105. NULL,
  118106. &_vq_auxt__16c0_s_p4_0,
  118107. NULL,
  118108. 0
  118109. };
  118110. static long _vq_quantlist__16c0_s_p5_0[] = {
  118111. 4,
  118112. 3,
  118113. 5,
  118114. 2,
  118115. 6,
  118116. 1,
  118117. 7,
  118118. 0,
  118119. 8,
  118120. };
  118121. static long _vq_lengthlist__16c0_s_p5_0[] = {
  118122. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  118123. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  118124. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  118125. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  118126. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  118127. 10,
  118128. };
  118129. static float _vq_quantthresh__16c0_s_p5_0[] = {
  118130. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118131. };
  118132. static long _vq_quantmap__16c0_s_p5_0[] = {
  118133. 7, 5, 3, 1, 0, 2, 4, 6,
  118134. 8,
  118135. };
  118136. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  118137. _vq_quantthresh__16c0_s_p5_0,
  118138. _vq_quantmap__16c0_s_p5_0,
  118139. 9,
  118140. 9
  118141. };
  118142. static static_codebook _16c0_s_p5_0 = {
  118143. 2, 81,
  118144. _vq_lengthlist__16c0_s_p5_0,
  118145. 1, -531628032, 1611661312, 4, 0,
  118146. _vq_quantlist__16c0_s_p5_0,
  118147. NULL,
  118148. &_vq_auxt__16c0_s_p5_0,
  118149. NULL,
  118150. 0
  118151. };
  118152. static long _vq_quantlist__16c0_s_p6_0[] = {
  118153. 8,
  118154. 7,
  118155. 9,
  118156. 6,
  118157. 10,
  118158. 5,
  118159. 11,
  118160. 4,
  118161. 12,
  118162. 3,
  118163. 13,
  118164. 2,
  118165. 14,
  118166. 1,
  118167. 15,
  118168. 0,
  118169. 16,
  118170. };
  118171. static long _vq_lengthlist__16c0_s_p6_0[] = {
  118172. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  118173. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  118174. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  118175. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  118176. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  118177. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  118178. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  118179. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  118180. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  118181. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  118182. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  118183. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  118184. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  118185. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  118186. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  118187. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  118188. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  118189. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  118190. 14,
  118191. };
  118192. static float _vq_quantthresh__16c0_s_p6_0[] = {
  118193. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  118194. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  118195. };
  118196. static long _vq_quantmap__16c0_s_p6_0[] = {
  118197. 15, 13, 11, 9, 7, 5, 3, 1,
  118198. 0, 2, 4, 6, 8, 10, 12, 14,
  118199. 16,
  118200. };
  118201. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  118202. _vq_quantthresh__16c0_s_p6_0,
  118203. _vq_quantmap__16c0_s_p6_0,
  118204. 17,
  118205. 17
  118206. };
  118207. static static_codebook _16c0_s_p6_0 = {
  118208. 2, 289,
  118209. _vq_lengthlist__16c0_s_p6_0,
  118210. 1, -529530880, 1611661312, 5, 0,
  118211. _vq_quantlist__16c0_s_p6_0,
  118212. NULL,
  118213. &_vq_auxt__16c0_s_p6_0,
  118214. NULL,
  118215. 0
  118216. };
  118217. static long _vq_quantlist__16c0_s_p7_0[] = {
  118218. 1,
  118219. 0,
  118220. 2,
  118221. };
  118222. static long _vq_lengthlist__16c0_s_p7_0[] = {
  118223. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  118224. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  118225. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  118226. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  118227. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  118228. 13,
  118229. };
  118230. static float _vq_quantthresh__16c0_s_p7_0[] = {
  118231. -5.5, 5.5,
  118232. };
  118233. static long _vq_quantmap__16c0_s_p7_0[] = {
  118234. 1, 0, 2,
  118235. };
  118236. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  118237. _vq_quantthresh__16c0_s_p7_0,
  118238. _vq_quantmap__16c0_s_p7_0,
  118239. 3,
  118240. 3
  118241. };
  118242. static static_codebook _16c0_s_p7_0 = {
  118243. 4, 81,
  118244. _vq_lengthlist__16c0_s_p7_0,
  118245. 1, -529137664, 1618345984, 2, 0,
  118246. _vq_quantlist__16c0_s_p7_0,
  118247. NULL,
  118248. &_vq_auxt__16c0_s_p7_0,
  118249. NULL,
  118250. 0
  118251. };
  118252. static long _vq_quantlist__16c0_s_p7_1[] = {
  118253. 5,
  118254. 4,
  118255. 6,
  118256. 3,
  118257. 7,
  118258. 2,
  118259. 8,
  118260. 1,
  118261. 9,
  118262. 0,
  118263. 10,
  118264. };
  118265. static long _vq_lengthlist__16c0_s_p7_1[] = {
  118266. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  118267. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  118268. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  118269. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  118270. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  118271. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  118272. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  118273. 11,11,11, 9, 9, 9, 9,10,10,
  118274. };
  118275. static float _vq_quantthresh__16c0_s_p7_1[] = {
  118276. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  118277. 3.5, 4.5,
  118278. };
  118279. static long _vq_quantmap__16c0_s_p7_1[] = {
  118280. 9, 7, 5, 3, 1, 0, 2, 4,
  118281. 6, 8, 10,
  118282. };
  118283. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  118284. _vq_quantthresh__16c0_s_p7_1,
  118285. _vq_quantmap__16c0_s_p7_1,
  118286. 11,
  118287. 11
  118288. };
  118289. static static_codebook _16c0_s_p7_1 = {
  118290. 2, 121,
  118291. _vq_lengthlist__16c0_s_p7_1,
  118292. 1, -531365888, 1611661312, 4, 0,
  118293. _vq_quantlist__16c0_s_p7_1,
  118294. NULL,
  118295. &_vq_auxt__16c0_s_p7_1,
  118296. NULL,
  118297. 0
  118298. };
  118299. static long _vq_quantlist__16c0_s_p8_0[] = {
  118300. 6,
  118301. 5,
  118302. 7,
  118303. 4,
  118304. 8,
  118305. 3,
  118306. 9,
  118307. 2,
  118308. 10,
  118309. 1,
  118310. 11,
  118311. 0,
  118312. 12,
  118313. };
  118314. static long _vq_lengthlist__16c0_s_p8_0[] = {
  118315. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  118316. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  118317. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  118318. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  118319. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  118320. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  118321. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  118322. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  118323. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  118324. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  118325. 0,12,13,13,12,13,14,14,14,
  118326. };
  118327. static float _vq_quantthresh__16c0_s_p8_0[] = {
  118328. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  118329. 12.5, 17.5, 22.5, 27.5,
  118330. };
  118331. static long _vq_quantmap__16c0_s_p8_0[] = {
  118332. 11, 9, 7, 5, 3, 1, 0, 2,
  118333. 4, 6, 8, 10, 12,
  118334. };
  118335. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  118336. _vq_quantthresh__16c0_s_p8_0,
  118337. _vq_quantmap__16c0_s_p8_0,
  118338. 13,
  118339. 13
  118340. };
  118341. static static_codebook _16c0_s_p8_0 = {
  118342. 2, 169,
  118343. _vq_lengthlist__16c0_s_p8_0,
  118344. 1, -526516224, 1616117760, 4, 0,
  118345. _vq_quantlist__16c0_s_p8_0,
  118346. NULL,
  118347. &_vq_auxt__16c0_s_p8_0,
  118348. NULL,
  118349. 0
  118350. };
  118351. static long _vq_quantlist__16c0_s_p8_1[] = {
  118352. 2,
  118353. 1,
  118354. 3,
  118355. 0,
  118356. 4,
  118357. };
  118358. static long _vq_lengthlist__16c0_s_p8_1[] = {
  118359. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  118360. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  118361. };
  118362. static float _vq_quantthresh__16c0_s_p8_1[] = {
  118363. -1.5, -0.5, 0.5, 1.5,
  118364. };
  118365. static long _vq_quantmap__16c0_s_p8_1[] = {
  118366. 3, 1, 0, 2, 4,
  118367. };
  118368. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  118369. _vq_quantthresh__16c0_s_p8_1,
  118370. _vq_quantmap__16c0_s_p8_1,
  118371. 5,
  118372. 5
  118373. };
  118374. static static_codebook _16c0_s_p8_1 = {
  118375. 2, 25,
  118376. _vq_lengthlist__16c0_s_p8_1,
  118377. 1, -533725184, 1611661312, 3, 0,
  118378. _vq_quantlist__16c0_s_p8_1,
  118379. NULL,
  118380. &_vq_auxt__16c0_s_p8_1,
  118381. NULL,
  118382. 0
  118383. };
  118384. static long _vq_quantlist__16c0_s_p9_0[] = {
  118385. 1,
  118386. 0,
  118387. 2,
  118388. };
  118389. static long _vq_lengthlist__16c0_s_p9_0[] = {
  118390. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118391. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118392. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118393. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118394. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  118395. 7,
  118396. };
  118397. static float _vq_quantthresh__16c0_s_p9_0[] = {
  118398. -157.5, 157.5,
  118399. };
  118400. static long _vq_quantmap__16c0_s_p9_0[] = {
  118401. 1, 0, 2,
  118402. };
  118403. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  118404. _vq_quantthresh__16c0_s_p9_0,
  118405. _vq_quantmap__16c0_s_p9_0,
  118406. 3,
  118407. 3
  118408. };
  118409. static static_codebook _16c0_s_p9_0 = {
  118410. 4, 81,
  118411. _vq_lengthlist__16c0_s_p9_0,
  118412. 1, -518803456, 1628680192, 2, 0,
  118413. _vq_quantlist__16c0_s_p9_0,
  118414. NULL,
  118415. &_vq_auxt__16c0_s_p9_0,
  118416. NULL,
  118417. 0
  118418. };
  118419. static long _vq_quantlist__16c0_s_p9_1[] = {
  118420. 7,
  118421. 6,
  118422. 8,
  118423. 5,
  118424. 9,
  118425. 4,
  118426. 10,
  118427. 3,
  118428. 11,
  118429. 2,
  118430. 12,
  118431. 1,
  118432. 13,
  118433. 0,
  118434. 14,
  118435. };
  118436. static long _vq_lengthlist__16c0_s_p9_1[] = {
  118437. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  118438. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  118439. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  118440. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  118441. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118442. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118443. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118444. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118445. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118446. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118447. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118448. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118449. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118450. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118451. 10,
  118452. };
  118453. static float _vq_quantthresh__16c0_s_p9_1[] = {
  118454. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  118455. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  118456. };
  118457. static long _vq_quantmap__16c0_s_p9_1[] = {
  118458. 13, 11, 9, 7, 5, 3, 1, 0,
  118459. 2, 4, 6, 8, 10, 12, 14,
  118460. };
  118461. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  118462. _vq_quantthresh__16c0_s_p9_1,
  118463. _vq_quantmap__16c0_s_p9_1,
  118464. 15,
  118465. 15
  118466. };
  118467. static static_codebook _16c0_s_p9_1 = {
  118468. 2, 225,
  118469. _vq_lengthlist__16c0_s_p9_1,
  118470. 1, -520986624, 1620377600, 4, 0,
  118471. _vq_quantlist__16c0_s_p9_1,
  118472. NULL,
  118473. &_vq_auxt__16c0_s_p9_1,
  118474. NULL,
  118475. 0
  118476. };
  118477. static long _vq_quantlist__16c0_s_p9_2[] = {
  118478. 10,
  118479. 9,
  118480. 11,
  118481. 8,
  118482. 12,
  118483. 7,
  118484. 13,
  118485. 6,
  118486. 14,
  118487. 5,
  118488. 15,
  118489. 4,
  118490. 16,
  118491. 3,
  118492. 17,
  118493. 2,
  118494. 18,
  118495. 1,
  118496. 19,
  118497. 0,
  118498. 20,
  118499. };
  118500. static long _vq_lengthlist__16c0_s_p9_2[] = {
  118501. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  118502. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  118503. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  118504. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  118505. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  118506. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  118507. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  118508. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  118509. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  118510. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  118511. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  118512. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  118513. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  118514. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  118515. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  118516. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  118517. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  118518. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  118519. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  118520. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  118521. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  118522. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  118523. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  118524. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  118525. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  118526. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  118527. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  118528. 10,11,10,10,11, 9,10,10,10,
  118529. };
  118530. static float _vq_quantthresh__16c0_s_p9_2[] = {
  118531. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  118532. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  118533. 6.5, 7.5, 8.5, 9.5,
  118534. };
  118535. static long _vq_quantmap__16c0_s_p9_2[] = {
  118536. 19, 17, 15, 13, 11, 9, 7, 5,
  118537. 3, 1, 0, 2, 4, 6, 8, 10,
  118538. 12, 14, 16, 18, 20,
  118539. };
  118540. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  118541. _vq_quantthresh__16c0_s_p9_2,
  118542. _vq_quantmap__16c0_s_p9_2,
  118543. 21,
  118544. 21
  118545. };
  118546. static static_codebook _16c0_s_p9_2 = {
  118547. 2, 441,
  118548. _vq_lengthlist__16c0_s_p9_2,
  118549. 1, -529268736, 1611661312, 5, 0,
  118550. _vq_quantlist__16c0_s_p9_2,
  118551. NULL,
  118552. &_vq_auxt__16c0_s_p9_2,
  118553. NULL,
  118554. 0
  118555. };
  118556. static long _huff_lengthlist__16c0_s_single[] = {
  118557. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  118558. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  118559. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  118560. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  118561. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  118562. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  118563. 16,16,18,18,
  118564. };
  118565. static static_codebook _huff_book__16c0_s_single = {
  118566. 2, 100,
  118567. _huff_lengthlist__16c0_s_single,
  118568. 0, 0, 0, 0, 0,
  118569. NULL,
  118570. NULL,
  118571. NULL,
  118572. NULL,
  118573. 0
  118574. };
  118575. static long _huff_lengthlist__16c1_s_long[] = {
  118576. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  118577. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  118578. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  118579. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  118580. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  118581. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  118582. 12,11,11,13,
  118583. };
  118584. static static_codebook _huff_book__16c1_s_long = {
  118585. 2, 100,
  118586. _huff_lengthlist__16c1_s_long,
  118587. 0, 0, 0, 0, 0,
  118588. NULL,
  118589. NULL,
  118590. NULL,
  118591. NULL,
  118592. 0
  118593. };
  118594. static long _vq_quantlist__16c1_s_p1_0[] = {
  118595. 1,
  118596. 0,
  118597. 2,
  118598. };
  118599. static long _vq_lengthlist__16c1_s_p1_0[] = {
  118600. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  118601. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118605. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  118606. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118610. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  118611. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  118646. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  118647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  118651. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  118652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  118656. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  118657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118691. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  118692. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118696. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  118697. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  118698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118701. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  118702. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  118703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119010. 0,
  119011. };
  119012. static float _vq_quantthresh__16c1_s_p1_0[] = {
  119013. -0.5, 0.5,
  119014. };
  119015. static long _vq_quantmap__16c1_s_p1_0[] = {
  119016. 1, 0, 2,
  119017. };
  119018. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  119019. _vq_quantthresh__16c1_s_p1_0,
  119020. _vq_quantmap__16c1_s_p1_0,
  119021. 3,
  119022. 3
  119023. };
  119024. static static_codebook _16c1_s_p1_0 = {
  119025. 8, 6561,
  119026. _vq_lengthlist__16c1_s_p1_0,
  119027. 1, -535822336, 1611661312, 2, 0,
  119028. _vq_quantlist__16c1_s_p1_0,
  119029. NULL,
  119030. &_vq_auxt__16c1_s_p1_0,
  119031. NULL,
  119032. 0
  119033. };
  119034. static long _vq_quantlist__16c1_s_p2_0[] = {
  119035. 2,
  119036. 1,
  119037. 3,
  119038. 0,
  119039. 4,
  119040. };
  119041. static long _vq_lengthlist__16c1_s_p2_0[] = {
  119042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119081. 0,
  119082. };
  119083. static float _vq_quantthresh__16c1_s_p2_0[] = {
  119084. -1.5, -0.5, 0.5, 1.5,
  119085. };
  119086. static long _vq_quantmap__16c1_s_p2_0[] = {
  119087. 3, 1, 0, 2, 4,
  119088. };
  119089. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  119090. _vq_quantthresh__16c1_s_p2_0,
  119091. _vq_quantmap__16c1_s_p2_0,
  119092. 5,
  119093. 5
  119094. };
  119095. static static_codebook _16c1_s_p2_0 = {
  119096. 4, 625,
  119097. _vq_lengthlist__16c1_s_p2_0,
  119098. 1, -533725184, 1611661312, 3, 0,
  119099. _vq_quantlist__16c1_s_p2_0,
  119100. NULL,
  119101. &_vq_auxt__16c1_s_p2_0,
  119102. NULL,
  119103. 0
  119104. };
  119105. static long _vq_quantlist__16c1_s_p3_0[] = {
  119106. 2,
  119107. 1,
  119108. 3,
  119109. 0,
  119110. 4,
  119111. };
  119112. static long _vq_lengthlist__16c1_s_p3_0[] = {
  119113. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  119115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119116. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  119118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119119. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  119120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119152. 0,
  119153. };
  119154. static float _vq_quantthresh__16c1_s_p3_0[] = {
  119155. -1.5, -0.5, 0.5, 1.5,
  119156. };
  119157. static long _vq_quantmap__16c1_s_p3_0[] = {
  119158. 3, 1, 0, 2, 4,
  119159. };
  119160. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  119161. _vq_quantthresh__16c1_s_p3_0,
  119162. _vq_quantmap__16c1_s_p3_0,
  119163. 5,
  119164. 5
  119165. };
  119166. static static_codebook _16c1_s_p3_0 = {
  119167. 4, 625,
  119168. _vq_lengthlist__16c1_s_p3_0,
  119169. 1, -533725184, 1611661312, 3, 0,
  119170. _vq_quantlist__16c1_s_p3_0,
  119171. NULL,
  119172. &_vq_auxt__16c1_s_p3_0,
  119173. NULL,
  119174. 0
  119175. };
  119176. static long _vq_quantlist__16c1_s_p4_0[] = {
  119177. 4,
  119178. 3,
  119179. 5,
  119180. 2,
  119181. 6,
  119182. 1,
  119183. 7,
  119184. 0,
  119185. 8,
  119186. };
  119187. static long _vq_lengthlist__16c1_s_p4_0[] = {
  119188. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  119189. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  119190. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  119191. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  119192. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119193. 0,
  119194. };
  119195. static float _vq_quantthresh__16c1_s_p4_0[] = {
  119196. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119197. };
  119198. static long _vq_quantmap__16c1_s_p4_0[] = {
  119199. 7, 5, 3, 1, 0, 2, 4, 6,
  119200. 8,
  119201. };
  119202. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  119203. _vq_quantthresh__16c1_s_p4_0,
  119204. _vq_quantmap__16c1_s_p4_0,
  119205. 9,
  119206. 9
  119207. };
  119208. static static_codebook _16c1_s_p4_0 = {
  119209. 2, 81,
  119210. _vq_lengthlist__16c1_s_p4_0,
  119211. 1, -531628032, 1611661312, 4, 0,
  119212. _vq_quantlist__16c1_s_p4_0,
  119213. NULL,
  119214. &_vq_auxt__16c1_s_p4_0,
  119215. NULL,
  119216. 0
  119217. };
  119218. static long _vq_quantlist__16c1_s_p5_0[] = {
  119219. 4,
  119220. 3,
  119221. 5,
  119222. 2,
  119223. 6,
  119224. 1,
  119225. 7,
  119226. 0,
  119227. 8,
  119228. };
  119229. static long _vq_lengthlist__16c1_s_p5_0[] = {
  119230. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  119231. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  119232. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  119233. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  119234. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  119235. 10,
  119236. };
  119237. static float _vq_quantthresh__16c1_s_p5_0[] = {
  119238. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119239. };
  119240. static long _vq_quantmap__16c1_s_p5_0[] = {
  119241. 7, 5, 3, 1, 0, 2, 4, 6,
  119242. 8,
  119243. };
  119244. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  119245. _vq_quantthresh__16c1_s_p5_0,
  119246. _vq_quantmap__16c1_s_p5_0,
  119247. 9,
  119248. 9
  119249. };
  119250. static static_codebook _16c1_s_p5_0 = {
  119251. 2, 81,
  119252. _vq_lengthlist__16c1_s_p5_0,
  119253. 1, -531628032, 1611661312, 4, 0,
  119254. _vq_quantlist__16c1_s_p5_0,
  119255. NULL,
  119256. &_vq_auxt__16c1_s_p5_0,
  119257. NULL,
  119258. 0
  119259. };
  119260. static long _vq_quantlist__16c1_s_p6_0[] = {
  119261. 8,
  119262. 7,
  119263. 9,
  119264. 6,
  119265. 10,
  119266. 5,
  119267. 11,
  119268. 4,
  119269. 12,
  119270. 3,
  119271. 13,
  119272. 2,
  119273. 14,
  119274. 1,
  119275. 15,
  119276. 0,
  119277. 16,
  119278. };
  119279. static long _vq_lengthlist__16c1_s_p6_0[] = {
  119280. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  119281. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  119282. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  119283. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  119284. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  119285. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  119286. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  119287. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  119288. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  119289. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  119290. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  119291. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  119292. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  119293. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  119294. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  119295. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  119296. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  119297. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  119298. 14,
  119299. };
  119300. static float _vq_quantthresh__16c1_s_p6_0[] = {
  119301. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  119302. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  119303. };
  119304. static long _vq_quantmap__16c1_s_p6_0[] = {
  119305. 15, 13, 11, 9, 7, 5, 3, 1,
  119306. 0, 2, 4, 6, 8, 10, 12, 14,
  119307. 16,
  119308. };
  119309. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  119310. _vq_quantthresh__16c1_s_p6_0,
  119311. _vq_quantmap__16c1_s_p6_0,
  119312. 17,
  119313. 17
  119314. };
  119315. static static_codebook _16c1_s_p6_0 = {
  119316. 2, 289,
  119317. _vq_lengthlist__16c1_s_p6_0,
  119318. 1, -529530880, 1611661312, 5, 0,
  119319. _vq_quantlist__16c1_s_p6_0,
  119320. NULL,
  119321. &_vq_auxt__16c1_s_p6_0,
  119322. NULL,
  119323. 0
  119324. };
  119325. static long _vq_quantlist__16c1_s_p7_0[] = {
  119326. 1,
  119327. 0,
  119328. 2,
  119329. };
  119330. static long _vq_lengthlist__16c1_s_p7_0[] = {
  119331. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  119332. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  119333. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  119334. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  119335. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  119336. 11,
  119337. };
  119338. static float _vq_quantthresh__16c1_s_p7_0[] = {
  119339. -5.5, 5.5,
  119340. };
  119341. static long _vq_quantmap__16c1_s_p7_0[] = {
  119342. 1, 0, 2,
  119343. };
  119344. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  119345. _vq_quantthresh__16c1_s_p7_0,
  119346. _vq_quantmap__16c1_s_p7_0,
  119347. 3,
  119348. 3
  119349. };
  119350. static static_codebook _16c1_s_p7_0 = {
  119351. 4, 81,
  119352. _vq_lengthlist__16c1_s_p7_0,
  119353. 1, -529137664, 1618345984, 2, 0,
  119354. _vq_quantlist__16c1_s_p7_0,
  119355. NULL,
  119356. &_vq_auxt__16c1_s_p7_0,
  119357. NULL,
  119358. 0
  119359. };
  119360. static long _vq_quantlist__16c1_s_p7_1[] = {
  119361. 5,
  119362. 4,
  119363. 6,
  119364. 3,
  119365. 7,
  119366. 2,
  119367. 8,
  119368. 1,
  119369. 9,
  119370. 0,
  119371. 10,
  119372. };
  119373. static long _vq_lengthlist__16c1_s_p7_1[] = {
  119374. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  119375. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  119376. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  119377. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  119378. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  119379. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  119380. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  119381. 10,10,10, 8, 8, 8, 8, 9, 9,
  119382. };
  119383. static float _vq_quantthresh__16c1_s_p7_1[] = {
  119384. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119385. 3.5, 4.5,
  119386. };
  119387. static long _vq_quantmap__16c1_s_p7_1[] = {
  119388. 9, 7, 5, 3, 1, 0, 2, 4,
  119389. 6, 8, 10,
  119390. };
  119391. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  119392. _vq_quantthresh__16c1_s_p7_1,
  119393. _vq_quantmap__16c1_s_p7_1,
  119394. 11,
  119395. 11
  119396. };
  119397. static static_codebook _16c1_s_p7_1 = {
  119398. 2, 121,
  119399. _vq_lengthlist__16c1_s_p7_1,
  119400. 1, -531365888, 1611661312, 4, 0,
  119401. _vq_quantlist__16c1_s_p7_1,
  119402. NULL,
  119403. &_vq_auxt__16c1_s_p7_1,
  119404. NULL,
  119405. 0
  119406. };
  119407. static long _vq_quantlist__16c1_s_p8_0[] = {
  119408. 6,
  119409. 5,
  119410. 7,
  119411. 4,
  119412. 8,
  119413. 3,
  119414. 9,
  119415. 2,
  119416. 10,
  119417. 1,
  119418. 11,
  119419. 0,
  119420. 12,
  119421. };
  119422. static long _vq_lengthlist__16c1_s_p8_0[] = {
  119423. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  119424. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  119425. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  119426. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  119427. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  119428. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  119429. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  119430. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  119431. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  119432. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  119433. 0,12,12,12,12,13,13,14,15,
  119434. };
  119435. static float _vq_quantthresh__16c1_s_p8_0[] = {
  119436. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  119437. 12.5, 17.5, 22.5, 27.5,
  119438. };
  119439. static long _vq_quantmap__16c1_s_p8_0[] = {
  119440. 11, 9, 7, 5, 3, 1, 0, 2,
  119441. 4, 6, 8, 10, 12,
  119442. };
  119443. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  119444. _vq_quantthresh__16c1_s_p8_0,
  119445. _vq_quantmap__16c1_s_p8_0,
  119446. 13,
  119447. 13
  119448. };
  119449. static static_codebook _16c1_s_p8_0 = {
  119450. 2, 169,
  119451. _vq_lengthlist__16c1_s_p8_0,
  119452. 1, -526516224, 1616117760, 4, 0,
  119453. _vq_quantlist__16c1_s_p8_0,
  119454. NULL,
  119455. &_vq_auxt__16c1_s_p8_0,
  119456. NULL,
  119457. 0
  119458. };
  119459. static long _vq_quantlist__16c1_s_p8_1[] = {
  119460. 2,
  119461. 1,
  119462. 3,
  119463. 0,
  119464. 4,
  119465. };
  119466. static long _vq_lengthlist__16c1_s_p8_1[] = {
  119467. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  119468. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  119469. };
  119470. static float _vq_quantthresh__16c1_s_p8_1[] = {
  119471. -1.5, -0.5, 0.5, 1.5,
  119472. };
  119473. static long _vq_quantmap__16c1_s_p8_1[] = {
  119474. 3, 1, 0, 2, 4,
  119475. };
  119476. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  119477. _vq_quantthresh__16c1_s_p8_1,
  119478. _vq_quantmap__16c1_s_p8_1,
  119479. 5,
  119480. 5
  119481. };
  119482. static static_codebook _16c1_s_p8_1 = {
  119483. 2, 25,
  119484. _vq_lengthlist__16c1_s_p8_1,
  119485. 1, -533725184, 1611661312, 3, 0,
  119486. _vq_quantlist__16c1_s_p8_1,
  119487. NULL,
  119488. &_vq_auxt__16c1_s_p8_1,
  119489. NULL,
  119490. 0
  119491. };
  119492. static long _vq_quantlist__16c1_s_p9_0[] = {
  119493. 6,
  119494. 5,
  119495. 7,
  119496. 4,
  119497. 8,
  119498. 3,
  119499. 9,
  119500. 2,
  119501. 10,
  119502. 1,
  119503. 11,
  119504. 0,
  119505. 12,
  119506. };
  119507. static long _vq_lengthlist__16c1_s_p9_0[] = {
  119508. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119509. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119510. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119511. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119512. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119513. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119514. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119515. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119516. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119517. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119518. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119519. };
  119520. static float _vq_quantthresh__16c1_s_p9_0[] = {
  119521. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  119522. 787.5, 1102.5, 1417.5, 1732.5,
  119523. };
  119524. static long _vq_quantmap__16c1_s_p9_0[] = {
  119525. 11, 9, 7, 5, 3, 1, 0, 2,
  119526. 4, 6, 8, 10, 12,
  119527. };
  119528. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  119529. _vq_quantthresh__16c1_s_p9_0,
  119530. _vq_quantmap__16c1_s_p9_0,
  119531. 13,
  119532. 13
  119533. };
  119534. static static_codebook _16c1_s_p9_0 = {
  119535. 2, 169,
  119536. _vq_lengthlist__16c1_s_p9_0,
  119537. 1, -513964032, 1628680192, 4, 0,
  119538. _vq_quantlist__16c1_s_p9_0,
  119539. NULL,
  119540. &_vq_auxt__16c1_s_p9_0,
  119541. NULL,
  119542. 0
  119543. };
  119544. static long _vq_quantlist__16c1_s_p9_1[] = {
  119545. 7,
  119546. 6,
  119547. 8,
  119548. 5,
  119549. 9,
  119550. 4,
  119551. 10,
  119552. 3,
  119553. 11,
  119554. 2,
  119555. 12,
  119556. 1,
  119557. 13,
  119558. 0,
  119559. 14,
  119560. };
  119561. static long _vq_lengthlist__16c1_s_p9_1[] = {
  119562. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  119563. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  119564. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  119565. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  119566. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  119567. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  119568. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  119569. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  119570. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  119571. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  119572. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  119573. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  119574. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  119575. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  119576. 13,
  119577. };
  119578. static float _vq_quantthresh__16c1_s_p9_1[] = {
  119579. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  119580. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  119581. };
  119582. static long _vq_quantmap__16c1_s_p9_1[] = {
  119583. 13, 11, 9, 7, 5, 3, 1, 0,
  119584. 2, 4, 6, 8, 10, 12, 14,
  119585. };
  119586. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  119587. _vq_quantthresh__16c1_s_p9_1,
  119588. _vq_quantmap__16c1_s_p9_1,
  119589. 15,
  119590. 15
  119591. };
  119592. static static_codebook _16c1_s_p9_1 = {
  119593. 2, 225,
  119594. _vq_lengthlist__16c1_s_p9_1,
  119595. 1, -520986624, 1620377600, 4, 0,
  119596. _vq_quantlist__16c1_s_p9_1,
  119597. NULL,
  119598. &_vq_auxt__16c1_s_p9_1,
  119599. NULL,
  119600. 0
  119601. };
  119602. static long _vq_quantlist__16c1_s_p9_2[] = {
  119603. 10,
  119604. 9,
  119605. 11,
  119606. 8,
  119607. 12,
  119608. 7,
  119609. 13,
  119610. 6,
  119611. 14,
  119612. 5,
  119613. 15,
  119614. 4,
  119615. 16,
  119616. 3,
  119617. 17,
  119618. 2,
  119619. 18,
  119620. 1,
  119621. 19,
  119622. 0,
  119623. 20,
  119624. };
  119625. static long _vq_lengthlist__16c1_s_p9_2[] = {
  119626. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  119627. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  119628. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  119629. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  119630. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  119631. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  119632. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  119633. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  119634. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  119635. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  119636. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  119637. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  119638. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  119639. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  119640. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  119641. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  119642. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  119643. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  119644. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  119645. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  119646. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  119647. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  119648. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  119649. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  119650. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  119651. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  119652. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  119653. 11,11,11,11,12,11,11,12,11,
  119654. };
  119655. static float _vq_quantthresh__16c1_s_p9_2[] = {
  119656. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  119657. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  119658. 6.5, 7.5, 8.5, 9.5,
  119659. };
  119660. static long _vq_quantmap__16c1_s_p9_2[] = {
  119661. 19, 17, 15, 13, 11, 9, 7, 5,
  119662. 3, 1, 0, 2, 4, 6, 8, 10,
  119663. 12, 14, 16, 18, 20,
  119664. };
  119665. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  119666. _vq_quantthresh__16c1_s_p9_2,
  119667. _vq_quantmap__16c1_s_p9_2,
  119668. 21,
  119669. 21
  119670. };
  119671. static static_codebook _16c1_s_p9_2 = {
  119672. 2, 441,
  119673. _vq_lengthlist__16c1_s_p9_2,
  119674. 1, -529268736, 1611661312, 5, 0,
  119675. _vq_quantlist__16c1_s_p9_2,
  119676. NULL,
  119677. &_vq_auxt__16c1_s_p9_2,
  119678. NULL,
  119679. 0
  119680. };
  119681. static long _huff_lengthlist__16c1_s_short[] = {
  119682. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  119683. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  119684. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  119685. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  119686. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  119687. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  119688. 9, 9,10,13,
  119689. };
  119690. static static_codebook _huff_book__16c1_s_short = {
  119691. 2, 100,
  119692. _huff_lengthlist__16c1_s_short,
  119693. 0, 0, 0, 0, 0,
  119694. NULL,
  119695. NULL,
  119696. NULL,
  119697. NULL,
  119698. 0
  119699. };
  119700. static long _huff_lengthlist__16c2_s_long[] = {
  119701. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  119702. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  119703. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  119704. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  119705. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  119706. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  119707. 14,14,16,18,
  119708. };
  119709. static static_codebook _huff_book__16c2_s_long = {
  119710. 2, 100,
  119711. _huff_lengthlist__16c2_s_long,
  119712. 0, 0, 0, 0, 0,
  119713. NULL,
  119714. NULL,
  119715. NULL,
  119716. NULL,
  119717. 0
  119718. };
  119719. static long _vq_quantlist__16c2_s_p1_0[] = {
  119720. 1,
  119721. 0,
  119722. 2,
  119723. };
  119724. static long _vq_lengthlist__16c2_s_p1_0[] = {
  119725. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  119726. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119730. 0,
  119731. };
  119732. static float _vq_quantthresh__16c2_s_p1_0[] = {
  119733. -0.5, 0.5,
  119734. };
  119735. static long _vq_quantmap__16c2_s_p1_0[] = {
  119736. 1, 0, 2,
  119737. };
  119738. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  119739. _vq_quantthresh__16c2_s_p1_0,
  119740. _vq_quantmap__16c2_s_p1_0,
  119741. 3,
  119742. 3
  119743. };
  119744. static static_codebook _16c2_s_p1_0 = {
  119745. 4, 81,
  119746. _vq_lengthlist__16c2_s_p1_0,
  119747. 1, -535822336, 1611661312, 2, 0,
  119748. _vq_quantlist__16c2_s_p1_0,
  119749. NULL,
  119750. &_vq_auxt__16c2_s_p1_0,
  119751. NULL,
  119752. 0
  119753. };
  119754. static long _vq_quantlist__16c2_s_p2_0[] = {
  119755. 2,
  119756. 1,
  119757. 3,
  119758. 0,
  119759. 4,
  119760. };
  119761. static long _vq_lengthlist__16c2_s_p2_0[] = {
  119762. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  119763. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  119764. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  119765. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  119766. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  119767. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  119768. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  119769. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  119770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119774. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  119775. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  119776. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  119777. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  119778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119782. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  119783. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  119784. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  119785. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119790. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  119791. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  119792. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  119793. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  119798. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  119799. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  119800. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  119801. 13,
  119802. };
  119803. static float _vq_quantthresh__16c2_s_p2_0[] = {
  119804. -1.5, -0.5, 0.5, 1.5,
  119805. };
  119806. static long _vq_quantmap__16c2_s_p2_0[] = {
  119807. 3, 1, 0, 2, 4,
  119808. };
  119809. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  119810. _vq_quantthresh__16c2_s_p2_0,
  119811. _vq_quantmap__16c2_s_p2_0,
  119812. 5,
  119813. 5
  119814. };
  119815. static static_codebook _16c2_s_p2_0 = {
  119816. 4, 625,
  119817. _vq_lengthlist__16c2_s_p2_0,
  119818. 1, -533725184, 1611661312, 3, 0,
  119819. _vq_quantlist__16c2_s_p2_0,
  119820. NULL,
  119821. &_vq_auxt__16c2_s_p2_0,
  119822. NULL,
  119823. 0
  119824. };
  119825. static long _vq_quantlist__16c2_s_p3_0[] = {
  119826. 4,
  119827. 3,
  119828. 5,
  119829. 2,
  119830. 6,
  119831. 1,
  119832. 7,
  119833. 0,
  119834. 8,
  119835. };
  119836. static long _vq_lengthlist__16c2_s_p3_0[] = {
  119837. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  119838. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  119839. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  119840. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  119841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119842. 0,
  119843. };
  119844. static float _vq_quantthresh__16c2_s_p3_0[] = {
  119845. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119846. };
  119847. static long _vq_quantmap__16c2_s_p3_0[] = {
  119848. 7, 5, 3, 1, 0, 2, 4, 6,
  119849. 8,
  119850. };
  119851. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  119852. _vq_quantthresh__16c2_s_p3_0,
  119853. _vq_quantmap__16c2_s_p3_0,
  119854. 9,
  119855. 9
  119856. };
  119857. static static_codebook _16c2_s_p3_0 = {
  119858. 2, 81,
  119859. _vq_lengthlist__16c2_s_p3_0,
  119860. 1, -531628032, 1611661312, 4, 0,
  119861. _vq_quantlist__16c2_s_p3_0,
  119862. NULL,
  119863. &_vq_auxt__16c2_s_p3_0,
  119864. NULL,
  119865. 0
  119866. };
  119867. static long _vq_quantlist__16c2_s_p4_0[] = {
  119868. 8,
  119869. 7,
  119870. 9,
  119871. 6,
  119872. 10,
  119873. 5,
  119874. 11,
  119875. 4,
  119876. 12,
  119877. 3,
  119878. 13,
  119879. 2,
  119880. 14,
  119881. 1,
  119882. 15,
  119883. 0,
  119884. 16,
  119885. };
  119886. static long _vq_lengthlist__16c2_s_p4_0[] = {
  119887. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  119888. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  119889. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  119890. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  119891. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  119892. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  119893. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  119894. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  119895. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  119896. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  119897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119905. 0,
  119906. };
  119907. static float _vq_quantthresh__16c2_s_p4_0[] = {
  119908. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  119909. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  119910. };
  119911. static long _vq_quantmap__16c2_s_p4_0[] = {
  119912. 15, 13, 11, 9, 7, 5, 3, 1,
  119913. 0, 2, 4, 6, 8, 10, 12, 14,
  119914. 16,
  119915. };
  119916. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  119917. _vq_quantthresh__16c2_s_p4_0,
  119918. _vq_quantmap__16c2_s_p4_0,
  119919. 17,
  119920. 17
  119921. };
  119922. static static_codebook _16c2_s_p4_0 = {
  119923. 2, 289,
  119924. _vq_lengthlist__16c2_s_p4_0,
  119925. 1, -529530880, 1611661312, 5, 0,
  119926. _vq_quantlist__16c2_s_p4_0,
  119927. NULL,
  119928. &_vq_auxt__16c2_s_p4_0,
  119929. NULL,
  119930. 0
  119931. };
  119932. static long _vq_quantlist__16c2_s_p5_0[] = {
  119933. 1,
  119934. 0,
  119935. 2,
  119936. };
  119937. static long _vq_lengthlist__16c2_s_p5_0[] = {
  119938. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  119939. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  119940. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  119941. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  119942. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  119943. 12,
  119944. };
  119945. static float _vq_quantthresh__16c2_s_p5_0[] = {
  119946. -5.5, 5.5,
  119947. };
  119948. static long _vq_quantmap__16c2_s_p5_0[] = {
  119949. 1, 0, 2,
  119950. };
  119951. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  119952. _vq_quantthresh__16c2_s_p5_0,
  119953. _vq_quantmap__16c2_s_p5_0,
  119954. 3,
  119955. 3
  119956. };
  119957. static static_codebook _16c2_s_p5_0 = {
  119958. 4, 81,
  119959. _vq_lengthlist__16c2_s_p5_0,
  119960. 1, -529137664, 1618345984, 2, 0,
  119961. _vq_quantlist__16c2_s_p5_0,
  119962. NULL,
  119963. &_vq_auxt__16c2_s_p5_0,
  119964. NULL,
  119965. 0
  119966. };
  119967. static long _vq_quantlist__16c2_s_p5_1[] = {
  119968. 5,
  119969. 4,
  119970. 6,
  119971. 3,
  119972. 7,
  119973. 2,
  119974. 8,
  119975. 1,
  119976. 9,
  119977. 0,
  119978. 10,
  119979. };
  119980. static long _vq_lengthlist__16c2_s_p5_1[] = {
  119981. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  119982. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  119983. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  119984. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  119985. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  119986. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  119987. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  119988. 11,11,11, 7, 7, 8, 8, 8, 8,
  119989. };
  119990. static float _vq_quantthresh__16c2_s_p5_1[] = {
  119991. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119992. 3.5, 4.5,
  119993. };
  119994. static long _vq_quantmap__16c2_s_p5_1[] = {
  119995. 9, 7, 5, 3, 1, 0, 2, 4,
  119996. 6, 8, 10,
  119997. };
  119998. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  119999. _vq_quantthresh__16c2_s_p5_1,
  120000. _vq_quantmap__16c2_s_p5_1,
  120001. 11,
  120002. 11
  120003. };
  120004. static static_codebook _16c2_s_p5_1 = {
  120005. 2, 121,
  120006. _vq_lengthlist__16c2_s_p5_1,
  120007. 1, -531365888, 1611661312, 4, 0,
  120008. _vq_quantlist__16c2_s_p5_1,
  120009. NULL,
  120010. &_vq_auxt__16c2_s_p5_1,
  120011. NULL,
  120012. 0
  120013. };
  120014. static long _vq_quantlist__16c2_s_p6_0[] = {
  120015. 6,
  120016. 5,
  120017. 7,
  120018. 4,
  120019. 8,
  120020. 3,
  120021. 9,
  120022. 2,
  120023. 10,
  120024. 1,
  120025. 11,
  120026. 0,
  120027. 12,
  120028. };
  120029. static long _vq_lengthlist__16c2_s_p6_0[] = {
  120030. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  120031. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  120032. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  120033. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  120034. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  120035. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  120036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120040. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120041. };
  120042. static float _vq_quantthresh__16c2_s_p6_0[] = {
  120043. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120044. 12.5, 17.5, 22.5, 27.5,
  120045. };
  120046. static long _vq_quantmap__16c2_s_p6_0[] = {
  120047. 11, 9, 7, 5, 3, 1, 0, 2,
  120048. 4, 6, 8, 10, 12,
  120049. };
  120050. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  120051. _vq_quantthresh__16c2_s_p6_0,
  120052. _vq_quantmap__16c2_s_p6_0,
  120053. 13,
  120054. 13
  120055. };
  120056. static static_codebook _16c2_s_p6_0 = {
  120057. 2, 169,
  120058. _vq_lengthlist__16c2_s_p6_0,
  120059. 1, -526516224, 1616117760, 4, 0,
  120060. _vq_quantlist__16c2_s_p6_0,
  120061. NULL,
  120062. &_vq_auxt__16c2_s_p6_0,
  120063. NULL,
  120064. 0
  120065. };
  120066. static long _vq_quantlist__16c2_s_p6_1[] = {
  120067. 2,
  120068. 1,
  120069. 3,
  120070. 0,
  120071. 4,
  120072. };
  120073. static long _vq_lengthlist__16c2_s_p6_1[] = {
  120074. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  120075. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  120076. };
  120077. static float _vq_quantthresh__16c2_s_p6_1[] = {
  120078. -1.5, -0.5, 0.5, 1.5,
  120079. };
  120080. static long _vq_quantmap__16c2_s_p6_1[] = {
  120081. 3, 1, 0, 2, 4,
  120082. };
  120083. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  120084. _vq_quantthresh__16c2_s_p6_1,
  120085. _vq_quantmap__16c2_s_p6_1,
  120086. 5,
  120087. 5
  120088. };
  120089. static static_codebook _16c2_s_p6_1 = {
  120090. 2, 25,
  120091. _vq_lengthlist__16c2_s_p6_1,
  120092. 1, -533725184, 1611661312, 3, 0,
  120093. _vq_quantlist__16c2_s_p6_1,
  120094. NULL,
  120095. &_vq_auxt__16c2_s_p6_1,
  120096. NULL,
  120097. 0
  120098. };
  120099. static long _vq_quantlist__16c2_s_p7_0[] = {
  120100. 6,
  120101. 5,
  120102. 7,
  120103. 4,
  120104. 8,
  120105. 3,
  120106. 9,
  120107. 2,
  120108. 10,
  120109. 1,
  120110. 11,
  120111. 0,
  120112. 12,
  120113. };
  120114. static long _vq_lengthlist__16c2_s_p7_0[] = {
  120115. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  120116. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  120117. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  120118. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  120119. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  120120. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  120121. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  120122. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  120123. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  120124. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  120125. 18,13,14,13,13,14,13,15,14,
  120126. };
  120127. static float _vq_quantthresh__16c2_s_p7_0[] = {
  120128. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  120129. 27.5, 38.5, 49.5, 60.5,
  120130. };
  120131. static long _vq_quantmap__16c2_s_p7_0[] = {
  120132. 11, 9, 7, 5, 3, 1, 0, 2,
  120133. 4, 6, 8, 10, 12,
  120134. };
  120135. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  120136. _vq_quantthresh__16c2_s_p7_0,
  120137. _vq_quantmap__16c2_s_p7_0,
  120138. 13,
  120139. 13
  120140. };
  120141. static static_codebook _16c2_s_p7_0 = {
  120142. 2, 169,
  120143. _vq_lengthlist__16c2_s_p7_0,
  120144. 1, -523206656, 1618345984, 4, 0,
  120145. _vq_quantlist__16c2_s_p7_0,
  120146. NULL,
  120147. &_vq_auxt__16c2_s_p7_0,
  120148. NULL,
  120149. 0
  120150. };
  120151. static long _vq_quantlist__16c2_s_p7_1[] = {
  120152. 5,
  120153. 4,
  120154. 6,
  120155. 3,
  120156. 7,
  120157. 2,
  120158. 8,
  120159. 1,
  120160. 9,
  120161. 0,
  120162. 10,
  120163. };
  120164. static long _vq_lengthlist__16c2_s_p7_1[] = {
  120165. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  120166. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  120167. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  120168. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  120169. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  120170. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  120171. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  120172. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  120173. };
  120174. static float _vq_quantthresh__16c2_s_p7_1[] = {
  120175. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120176. 3.5, 4.5,
  120177. };
  120178. static long _vq_quantmap__16c2_s_p7_1[] = {
  120179. 9, 7, 5, 3, 1, 0, 2, 4,
  120180. 6, 8, 10,
  120181. };
  120182. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  120183. _vq_quantthresh__16c2_s_p7_1,
  120184. _vq_quantmap__16c2_s_p7_1,
  120185. 11,
  120186. 11
  120187. };
  120188. static static_codebook _16c2_s_p7_1 = {
  120189. 2, 121,
  120190. _vq_lengthlist__16c2_s_p7_1,
  120191. 1, -531365888, 1611661312, 4, 0,
  120192. _vq_quantlist__16c2_s_p7_1,
  120193. NULL,
  120194. &_vq_auxt__16c2_s_p7_1,
  120195. NULL,
  120196. 0
  120197. };
  120198. static long _vq_quantlist__16c2_s_p8_0[] = {
  120199. 7,
  120200. 6,
  120201. 8,
  120202. 5,
  120203. 9,
  120204. 4,
  120205. 10,
  120206. 3,
  120207. 11,
  120208. 2,
  120209. 12,
  120210. 1,
  120211. 13,
  120212. 0,
  120213. 14,
  120214. };
  120215. static long _vq_lengthlist__16c2_s_p8_0[] = {
  120216. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  120217. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  120218. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  120219. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  120220. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  120221. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  120222. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  120223. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  120224. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  120225. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  120226. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  120227. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  120228. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  120229. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  120230. 13,
  120231. };
  120232. static float _vq_quantthresh__16c2_s_p8_0[] = {
  120233. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120234. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120235. };
  120236. static long _vq_quantmap__16c2_s_p8_0[] = {
  120237. 13, 11, 9, 7, 5, 3, 1, 0,
  120238. 2, 4, 6, 8, 10, 12, 14,
  120239. };
  120240. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  120241. _vq_quantthresh__16c2_s_p8_0,
  120242. _vq_quantmap__16c2_s_p8_0,
  120243. 15,
  120244. 15
  120245. };
  120246. static static_codebook _16c2_s_p8_0 = {
  120247. 2, 225,
  120248. _vq_lengthlist__16c2_s_p8_0,
  120249. 1, -520986624, 1620377600, 4, 0,
  120250. _vq_quantlist__16c2_s_p8_0,
  120251. NULL,
  120252. &_vq_auxt__16c2_s_p8_0,
  120253. NULL,
  120254. 0
  120255. };
  120256. static long _vq_quantlist__16c2_s_p8_1[] = {
  120257. 10,
  120258. 9,
  120259. 11,
  120260. 8,
  120261. 12,
  120262. 7,
  120263. 13,
  120264. 6,
  120265. 14,
  120266. 5,
  120267. 15,
  120268. 4,
  120269. 16,
  120270. 3,
  120271. 17,
  120272. 2,
  120273. 18,
  120274. 1,
  120275. 19,
  120276. 0,
  120277. 20,
  120278. };
  120279. static long _vq_lengthlist__16c2_s_p8_1[] = {
  120280. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  120281. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  120282. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  120283. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  120284. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  120285. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  120286. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  120287. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  120288. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  120289. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  120290. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  120291. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  120292. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  120293. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  120294. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  120295. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  120296. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  120297. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  120298. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  120299. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  120300. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  120301. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  120302. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  120303. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  120304. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  120305. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  120306. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  120307. 10,11,10,10,10,10,10,10,10,
  120308. };
  120309. static float _vq_quantthresh__16c2_s_p8_1[] = {
  120310. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120311. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120312. 6.5, 7.5, 8.5, 9.5,
  120313. };
  120314. static long _vq_quantmap__16c2_s_p8_1[] = {
  120315. 19, 17, 15, 13, 11, 9, 7, 5,
  120316. 3, 1, 0, 2, 4, 6, 8, 10,
  120317. 12, 14, 16, 18, 20,
  120318. };
  120319. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  120320. _vq_quantthresh__16c2_s_p8_1,
  120321. _vq_quantmap__16c2_s_p8_1,
  120322. 21,
  120323. 21
  120324. };
  120325. static static_codebook _16c2_s_p8_1 = {
  120326. 2, 441,
  120327. _vq_lengthlist__16c2_s_p8_1,
  120328. 1, -529268736, 1611661312, 5, 0,
  120329. _vq_quantlist__16c2_s_p8_1,
  120330. NULL,
  120331. &_vq_auxt__16c2_s_p8_1,
  120332. NULL,
  120333. 0
  120334. };
  120335. static long _vq_quantlist__16c2_s_p9_0[] = {
  120336. 6,
  120337. 5,
  120338. 7,
  120339. 4,
  120340. 8,
  120341. 3,
  120342. 9,
  120343. 2,
  120344. 10,
  120345. 1,
  120346. 11,
  120347. 0,
  120348. 12,
  120349. };
  120350. static long _vq_lengthlist__16c2_s_p9_0[] = {
  120351. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120352. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120353. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120354. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120355. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120356. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120357. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120358. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120359. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120360. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120361. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120362. };
  120363. static float _vq_quantthresh__16c2_s_p9_0[] = {
  120364. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  120365. 2327.5, 3258.5, 4189.5, 5120.5,
  120366. };
  120367. static long _vq_quantmap__16c2_s_p9_0[] = {
  120368. 11, 9, 7, 5, 3, 1, 0, 2,
  120369. 4, 6, 8, 10, 12,
  120370. };
  120371. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  120372. _vq_quantthresh__16c2_s_p9_0,
  120373. _vq_quantmap__16c2_s_p9_0,
  120374. 13,
  120375. 13
  120376. };
  120377. static static_codebook _16c2_s_p9_0 = {
  120378. 2, 169,
  120379. _vq_lengthlist__16c2_s_p9_0,
  120380. 1, -510275072, 1631393792, 4, 0,
  120381. _vq_quantlist__16c2_s_p9_0,
  120382. NULL,
  120383. &_vq_auxt__16c2_s_p9_0,
  120384. NULL,
  120385. 0
  120386. };
  120387. static long _vq_quantlist__16c2_s_p9_1[] = {
  120388. 8,
  120389. 7,
  120390. 9,
  120391. 6,
  120392. 10,
  120393. 5,
  120394. 11,
  120395. 4,
  120396. 12,
  120397. 3,
  120398. 13,
  120399. 2,
  120400. 14,
  120401. 1,
  120402. 15,
  120403. 0,
  120404. 16,
  120405. };
  120406. static long _vq_lengthlist__16c2_s_p9_1[] = {
  120407. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  120408. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  120409. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  120410. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  120411. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  120412. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  120413. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  120414. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  120415. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  120416. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  120417. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120418. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120419. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120420. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120421. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120422. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  120423. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  120424. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120425. 10,
  120426. };
  120427. static float _vq_quantthresh__16c2_s_p9_1[] = {
  120428. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  120429. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  120430. };
  120431. static long _vq_quantmap__16c2_s_p9_1[] = {
  120432. 15, 13, 11, 9, 7, 5, 3, 1,
  120433. 0, 2, 4, 6, 8, 10, 12, 14,
  120434. 16,
  120435. };
  120436. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  120437. _vq_quantthresh__16c2_s_p9_1,
  120438. _vq_quantmap__16c2_s_p9_1,
  120439. 17,
  120440. 17
  120441. };
  120442. static static_codebook _16c2_s_p9_1 = {
  120443. 2, 289,
  120444. _vq_lengthlist__16c2_s_p9_1,
  120445. 1, -518488064, 1622704128, 5, 0,
  120446. _vq_quantlist__16c2_s_p9_1,
  120447. NULL,
  120448. &_vq_auxt__16c2_s_p9_1,
  120449. NULL,
  120450. 0
  120451. };
  120452. static long _vq_quantlist__16c2_s_p9_2[] = {
  120453. 13,
  120454. 12,
  120455. 14,
  120456. 11,
  120457. 15,
  120458. 10,
  120459. 16,
  120460. 9,
  120461. 17,
  120462. 8,
  120463. 18,
  120464. 7,
  120465. 19,
  120466. 6,
  120467. 20,
  120468. 5,
  120469. 21,
  120470. 4,
  120471. 22,
  120472. 3,
  120473. 23,
  120474. 2,
  120475. 24,
  120476. 1,
  120477. 25,
  120478. 0,
  120479. 26,
  120480. };
  120481. static long _vq_lengthlist__16c2_s_p9_2[] = {
  120482. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  120483. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  120484. };
  120485. static float _vq_quantthresh__16c2_s_p9_2[] = {
  120486. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  120487. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120488. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  120489. 11.5, 12.5,
  120490. };
  120491. static long _vq_quantmap__16c2_s_p9_2[] = {
  120492. 25, 23, 21, 19, 17, 15, 13, 11,
  120493. 9, 7, 5, 3, 1, 0, 2, 4,
  120494. 6, 8, 10, 12, 14, 16, 18, 20,
  120495. 22, 24, 26,
  120496. };
  120497. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  120498. _vq_quantthresh__16c2_s_p9_2,
  120499. _vq_quantmap__16c2_s_p9_2,
  120500. 27,
  120501. 27
  120502. };
  120503. static static_codebook _16c2_s_p9_2 = {
  120504. 1, 27,
  120505. _vq_lengthlist__16c2_s_p9_2,
  120506. 1, -528875520, 1611661312, 5, 0,
  120507. _vq_quantlist__16c2_s_p9_2,
  120508. NULL,
  120509. &_vq_auxt__16c2_s_p9_2,
  120510. NULL,
  120511. 0
  120512. };
  120513. static long _huff_lengthlist__16c2_s_short[] = {
  120514. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  120515. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  120516. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  120517. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  120518. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  120519. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  120520. 15,12,14,14,
  120521. };
  120522. static static_codebook _huff_book__16c2_s_short = {
  120523. 2, 100,
  120524. _huff_lengthlist__16c2_s_short,
  120525. 0, 0, 0, 0, 0,
  120526. NULL,
  120527. NULL,
  120528. NULL,
  120529. NULL,
  120530. 0
  120531. };
  120532. static long _vq_quantlist__8c0_s_p1_0[] = {
  120533. 1,
  120534. 0,
  120535. 2,
  120536. };
  120537. static long _vq_lengthlist__8c0_s_p1_0[] = {
  120538. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  120539. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120543. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  120544. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120548. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  120549. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  120584. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  120585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  120589. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  120590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  120594. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  120595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120629. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  120630. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120634. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  120635. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  120636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120639. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  120640. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  120641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0,
  120794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0,
  120878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120948. 0,
  120949. };
  120950. static float _vq_quantthresh__8c0_s_p1_0[] = {
  120951. -0.5, 0.5,
  120952. };
  120953. static long _vq_quantmap__8c0_s_p1_0[] = {
  120954. 1, 0, 2,
  120955. };
  120956. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  120957. _vq_quantthresh__8c0_s_p1_0,
  120958. _vq_quantmap__8c0_s_p1_0,
  120959. 3,
  120960. 3
  120961. };
  120962. static static_codebook _8c0_s_p1_0 = {
  120963. 8, 6561,
  120964. _vq_lengthlist__8c0_s_p1_0,
  120965. 1, -535822336, 1611661312, 2, 0,
  120966. _vq_quantlist__8c0_s_p1_0,
  120967. NULL,
  120968. &_vq_auxt__8c0_s_p1_0,
  120969. NULL,
  120970. 0
  120971. };
  120972. static long _vq_quantlist__8c0_s_p2_0[] = {
  120973. 2,
  120974. 1,
  120975. 3,
  120976. 0,
  120977. 4,
  120978. };
  120979. static long _vq_lengthlist__8c0_s_p2_0[] = {
  120980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121019. 0,
  121020. };
  121021. static float _vq_quantthresh__8c0_s_p2_0[] = {
  121022. -1.5, -0.5, 0.5, 1.5,
  121023. };
  121024. static long _vq_quantmap__8c0_s_p2_0[] = {
  121025. 3, 1, 0, 2, 4,
  121026. };
  121027. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  121028. _vq_quantthresh__8c0_s_p2_0,
  121029. _vq_quantmap__8c0_s_p2_0,
  121030. 5,
  121031. 5
  121032. };
  121033. static static_codebook _8c0_s_p2_0 = {
  121034. 4, 625,
  121035. _vq_lengthlist__8c0_s_p2_0,
  121036. 1, -533725184, 1611661312, 3, 0,
  121037. _vq_quantlist__8c0_s_p2_0,
  121038. NULL,
  121039. &_vq_auxt__8c0_s_p2_0,
  121040. NULL,
  121041. 0
  121042. };
  121043. static long _vq_quantlist__8c0_s_p3_0[] = {
  121044. 2,
  121045. 1,
  121046. 3,
  121047. 0,
  121048. 4,
  121049. };
  121050. static long _vq_lengthlist__8c0_s_p3_0[] = {
  121051. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  121053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121054. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  121056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121057. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  121058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121090. 0,
  121091. };
  121092. static float _vq_quantthresh__8c0_s_p3_0[] = {
  121093. -1.5, -0.5, 0.5, 1.5,
  121094. };
  121095. static long _vq_quantmap__8c0_s_p3_0[] = {
  121096. 3, 1, 0, 2, 4,
  121097. };
  121098. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  121099. _vq_quantthresh__8c0_s_p3_0,
  121100. _vq_quantmap__8c0_s_p3_0,
  121101. 5,
  121102. 5
  121103. };
  121104. static static_codebook _8c0_s_p3_0 = {
  121105. 4, 625,
  121106. _vq_lengthlist__8c0_s_p3_0,
  121107. 1, -533725184, 1611661312, 3, 0,
  121108. _vq_quantlist__8c0_s_p3_0,
  121109. NULL,
  121110. &_vq_auxt__8c0_s_p3_0,
  121111. NULL,
  121112. 0
  121113. };
  121114. static long _vq_quantlist__8c0_s_p4_0[] = {
  121115. 4,
  121116. 3,
  121117. 5,
  121118. 2,
  121119. 6,
  121120. 1,
  121121. 7,
  121122. 0,
  121123. 8,
  121124. };
  121125. static long _vq_lengthlist__8c0_s_p4_0[] = {
  121126. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  121127. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  121128. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  121129. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  121130. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121131. 0,
  121132. };
  121133. static float _vq_quantthresh__8c0_s_p4_0[] = {
  121134. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121135. };
  121136. static long _vq_quantmap__8c0_s_p4_0[] = {
  121137. 7, 5, 3, 1, 0, 2, 4, 6,
  121138. 8,
  121139. };
  121140. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  121141. _vq_quantthresh__8c0_s_p4_0,
  121142. _vq_quantmap__8c0_s_p4_0,
  121143. 9,
  121144. 9
  121145. };
  121146. static static_codebook _8c0_s_p4_0 = {
  121147. 2, 81,
  121148. _vq_lengthlist__8c0_s_p4_0,
  121149. 1, -531628032, 1611661312, 4, 0,
  121150. _vq_quantlist__8c0_s_p4_0,
  121151. NULL,
  121152. &_vq_auxt__8c0_s_p4_0,
  121153. NULL,
  121154. 0
  121155. };
  121156. static long _vq_quantlist__8c0_s_p5_0[] = {
  121157. 4,
  121158. 3,
  121159. 5,
  121160. 2,
  121161. 6,
  121162. 1,
  121163. 7,
  121164. 0,
  121165. 8,
  121166. };
  121167. static long _vq_lengthlist__8c0_s_p5_0[] = {
  121168. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  121169. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  121170. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  121171. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  121172. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  121173. 10,
  121174. };
  121175. static float _vq_quantthresh__8c0_s_p5_0[] = {
  121176. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121177. };
  121178. static long _vq_quantmap__8c0_s_p5_0[] = {
  121179. 7, 5, 3, 1, 0, 2, 4, 6,
  121180. 8,
  121181. };
  121182. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  121183. _vq_quantthresh__8c0_s_p5_0,
  121184. _vq_quantmap__8c0_s_p5_0,
  121185. 9,
  121186. 9
  121187. };
  121188. static static_codebook _8c0_s_p5_0 = {
  121189. 2, 81,
  121190. _vq_lengthlist__8c0_s_p5_0,
  121191. 1, -531628032, 1611661312, 4, 0,
  121192. _vq_quantlist__8c0_s_p5_0,
  121193. NULL,
  121194. &_vq_auxt__8c0_s_p5_0,
  121195. NULL,
  121196. 0
  121197. };
  121198. static long _vq_quantlist__8c0_s_p6_0[] = {
  121199. 8,
  121200. 7,
  121201. 9,
  121202. 6,
  121203. 10,
  121204. 5,
  121205. 11,
  121206. 4,
  121207. 12,
  121208. 3,
  121209. 13,
  121210. 2,
  121211. 14,
  121212. 1,
  121213. 15,
  121214. 0,
  121215. 16,
  121216. };
  121217. static long _vq_lengthlist__8c0_s_p6_0[] = {
  121218. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  121219. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  121220. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  121221. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  121222. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  121223. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  121224. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  121225. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  121226. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  121227. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  121228. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  121229. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  121230. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  121231. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  121232. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  121233. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  121234. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  121235. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  121236. 14,
  121237. };
  121238. static float _vq_quantthresh__8c0_s_p6_0[] = {
  121239. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  121240. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  121241. };
  121242. static long _vq_quantmap__8c0_s_p6_0[] = {
  121243. 15, 13, 11, 9, 7, 5, 3, 1,
  121244. 0, 2, 4, 6, 8, 10, 12, 14,
  121245. 16,
  121246. };
  121247. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  121248. _vq_quantthresh__8c0_s_p6_0,
  121249. _vq_quantmap__8c0_s_p6_0,
  121250. 17,
  121251. 17
  121252. };
  121253. static static_codebook _8c0_s_p6_0 = {
  121254. 2, 289,
  121255. _vq_lengthlist__8c0_s_p6_0,
  121256. 1, -529530880, 1611661312, 5, 0,
  121257. _vq_quantlist__8c0_s_p6_0,
  121258. NULL,
  121259. &_vq_auxt__8c0_s_p6_0,
  121260. NULL,
  121261. 0
  121262. };
  121263. static long _vq_quantlist__8c0_s_p7_0[] = {
  121264. 1,
  121265. 0,
  121266. 2,
  121267. };
  121268. static long _vq_lengthlist__8c0_s_p7_0[] = {
  121269. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  121270. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  121271. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  121272. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  121273. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  121274. 10,
  121275. };
  121276. static float _vq_quantthresh__8c0_s_p7_0[] = {
  121277. -5.5, 5.5,
  121278. };
  121279. static long _vq_quantmap__8c0_s_p7_0[] = {
  121280. 1, 0, 2,
  121281. };
  121282. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  121283. _vq_quantthresh__8c0_s_p7_0,
  121284. _vq_quantmap__8c0_s_p7_0,
  121285. 3,
  121286. 3
  121287. };
  121288. static static_codebook _8c0_s_p7_0 = {
  121289. 4, 81,
  121290. _vq_lengthlist__8c0_s_p7_0,
  121291. 1, -529137664, 1618345984, 2, 0,
  121292. _vq_quantlist__8c0_s_p7_0,
  121293. NULL,
  121294. &_vq_auxt__8c0_s_p7_0,
  121295. NULL,
  121296. 0
  121297. };
  121298. static long _vq_quantlist__8c0_s_p7_1[] = {
  121299. 5,
  121300. 4,
  121301. 6,
  121302. 3,
  121303. 7,
  121304. 2,
  121305. 8,
  121306. 1,
  121307. 9,
  121308. 0,
  121309. 10,
  121310. };
  121311. static long _vq_lengthlist__8c0_s_p7_1[] = {
  121312. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  121313. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  121314. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  121315. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  121316. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  121317. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  121318. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  121319. 10,10,10, 9, 9, 9,10,10,10,
  121320. };
  121321. static float _vq_quantthresh__8c0_s_p7_1[] = {
  121322. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121323. 3.5, 4.5,
  121324. };
  121325. static long _vq_quantmap__8c0_s_p7_1[] = {
  121326. 9, 7, 5, 3, 1, 0, 2, 4,
  121327. 6, 8, 10,
  121328. };
  121329. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  121330. _vq_quantthresh__8c0_s_p7_1,
  121331. _vq_quantmap__8c0_s_p7_1,
  121332. 11,
  121333. 11
  121334. };
  121335. static static_codebook _8c0_s_p7_1 = {
  121336. 2, 121,
  121337. _vq_lengthlist__8c0_s_p7_1,
  121338. 1, -531365888, 1611661312, 4, 0,
  121339. _vq_quantlist__8c0_s_p7_1,
  121340. NULL,
  121341. &_vq_auxt__8c0_s_p7_1,
  121342. NULL,
  121343. 0
  121344. };
  121345. static long _vq_quantlist__8c0_s_p8_0[] = {
  121346. 6,
  121347. 5,
  121348. 7,
  121349. 4,
  121350. 8,
  121351. 3,
  121352. 9,
  121353. 2,
  121354. 10,
  121355. 1,
  121356. 11,
  121357. 0,
  121358. 12,
  121359. };
  121360. static long _vq_lengthlist__8c0_s_p8_0[] = {
  121361. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  121362. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  121363. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  121364. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  121365. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  121366. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  121367. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  121368. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  121369. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  121370. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  121371. 0, 0,13,13,11,13,13,11,12,
  121372. };
  121373. static float _vq_quantthresh__8c0_s_p8_0[] = {
  121374. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  121375. 12.5, 17.5, 22.5, 27.5,
  121376. };
  121377. static long _vq_quantmap__8c0_s_p8_0[] = {
  121378. 11, 9, 7, 5, 3, 1, 0, 2,
  121379. 4, 6, 8, 10, 12,
  121380. };
  121381. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  121382. _vq_quantthresh__8c0_s_p8_0,
  121383. _vq_quantmap__8c0_s_p8_0,
  121384. 13,
  121385. 13
  121386. };
  121387. static static_codebook _8c0_s_p8_0 = {
  121388. 2, 169,
  121389. _vq_lengthlist__8c0_s_p8_0,
  121390. 1, -526516224, 1616117760, 4, 0,
  121391. _vq_quantlist__8c0_s_p8_0,
  121392. NULL,
  121393. &_vq_auxt__8c0_s_p8_0,
  121394. NULL,
  121395. 0
  121396. };
  121397. static long _vq_quantlist__8c0_s_p8_1[] = {
  121398. 2,
  121399. 1,
  121400. 3,
  121401. 0,
  121402. 4,
  121403. };
  121404. static long _vq_lengthlist__8c0_s_p8_1[] = {
  121405. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  121406. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  121407. };
  121408. static float _vq_quantthresh__8c0_s_p8_1[] = {
  121409. -1.5, -0.5, 0.5, 1.5,
  121410. };
  121411. static long _vq_quantmap__8c0_s_p8_1[] = {
  121412. 3, 1, 0, 2, 4,
  121413. };
  121414. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  121415. _vq_quantthresh__8c0_s_p8_1,
  121416. _vq_quantmap__8c0_s_p8_1,
  121417. 5,
  121418. 5
  121419. };
  121420. static static_codebook _8c0_s_p8_1 = {
  121421. 2, 25,
  121422. _vq_lengthlist__8c0_s_p8_1,
  121423. 1, -533725184, 1611661312, 3, 0,
  121424. _vq_quantlist__8c0_s_p8_1,
  121425. NULL,
  121426. &_vq_auxt__8c0_s_p8_1,
  121427. NULL,
  121428. 0
  121429. };
  121430. static long _vq_quantlist__8c0_s_p9_0[] = {
  121431. 1,
  121432. 0,
  121433. 2,
  121434. };
  121435. static long _vq_lengthlist__8c0_s_p9_0[] = {
  121436. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121437. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121438. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121439. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121440. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121441. 7,
  121442. };
  121443. static float _vq_quantthresh__8c0_s_p9_0[] = {
  121444. -157.5, 157.5,
  121445. };
  121446. static long _vq_quantmap__8c0_s_p9_0[] = {
  121447. 1, 0, 2,
  121448. };
  121449. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  121450. _vq_quantthresh__8c0_s_p9_0,
  121451. _vq_quantmap__8c0_s_p9_0,
  121452. 3,
  121453. 3
  121454. };
  121455. static static_codebook _8c0_s_p9_0 = {
  121456. 4, 81,
  121457. _vq_lengthlist__8c0_s_p9_0,
  121458. 1, -518803456, 1628680192, 2, 0,
  121459. _vq_quantlist__8c0_s_p9_0,
  121460. NULL,
  121461. &_vq_auxt__8c0_s_p9_0,
  121462. NULL,
  121463. 0
  121464. };
  121465. static long _vq_quantlist__8c0_s_p9_1[] = {
  121466. 7,
  121467. 6,
  121468. 8,
  121469. 5,
  121470. 9,
  121471. 4,
  121472. 10,
  121473. 3,
  121474. 11,
  121475. 2,
  121476. 12,
  121477. 1,
  121478. 13,
  121479. 0,
  121480. 14,
  121481. };
  121482. static long _vq_lengthlist__8c0_s_p9_1[] = {
  121483. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  121484. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  121485. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  121486. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  121487. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  121488. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  121489. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121490. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121492. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121494. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121495. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121497. 11,
  121498. };
  121499. static float _vq_quantthresh__8c0_s_p9_1[] = {
  121500. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121501. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121502. };
  121503. static long _vq_quantmap__8c0_s_p9_1[] = {
  121504. 13, 11, 9, 7, 5, 3, 1, 0,
  121505. 2, 4, 6, 8, 10, 12, 14,
  121506. };
  121507. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  121508. _vq_quantthresh__8c0_s_p9_1,
  121509. _vq_quantmap__8c0_s_p9_1,
  121510. 15,
  121511. 15
  121512. };
  121513. static static_codebook _8c0_s_p9_1 = {
  121514. 2, 225,
  121515. _vq_lengthlist__8c0_s_p9_1,
  121516. 1, -520986624, 1620377600, 4, 0,
  121517. _vq_quantlist__8c0_s_p9_1,
  121518. NULL,
  121519. &_vq_auxt__8c0_s_p9_1,
  121520. NULL,
  121521. 0
  121522. };
  121523. static long _vq_quantlist__8c0_s_p9_2[] = {
  121524. 10,
  121525. 9,
  121526. 11,
  121527. 8,
  121528. 12,
  121529. 7,
  121530. 13,
  121531. 6,
  121532. 14,
  121533. 5,
  121534. 15,
  121535. 4,
  121536. 16,
  121537. 3,
  121538. 17,
  121539. 2,
  121540. 18,
  121541. 1,
  121542. 19,
  121543. 0,
  121544. 20,
  121545. };
  121546. static long _vq_lengthlist__8c0_s_p9_2[] = {
  121547. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  121548. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  121549. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  121550. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  121551. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  121552. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  121553. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  121554. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  121555. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  121556. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  121557. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  121558. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  121559. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  121560. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  121561. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  121562. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  121563. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  121564. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  121565. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  121566. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  121567. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  121568. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  121569. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  121570. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  121571. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  121572. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  121573. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  121574. 10,11, 9,11,10, 9,10, 9,10,
  121575. };
  121576. static float _vq_quantthresh__8c0_s_p9_2[] = {
  121577. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121578. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121579. 6.5, 7.5, 8.5, 9.5,
  121580. };
  121581. static long _vq_quantmap__8c0_s_p9_2[] = {
  121582. 19, 17, 15, 13, 11, 9, 7, 5,
  121583. 3, 1, 0, 2, 4, 6, 8, 10,
  121584. 12, 14, 16, 18, 20,
  121585. };
  121586. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  121587. _vq_quantthresh__8c0_s_p9_2,
  121588. _vq_quantmap__8c0_s_p9_2,
  121589. 21,
  121590. 21
  121591. };
  121592. static static_codebook _8c0_s_p9_2 = {
  121593. 2, 441,
  121594. _vq_lengthlist__8c0_s_p9_2,
  121595. 1, -529268736, 1611661312, 5, 0,
  121596. _vq_quantlist__8c0_s_p9_2,
  121597. NULL,
  121598. &_vq_auxt__8c0_s_p9_2,
  121599. NULL,
  121600. 0
  121601. };
  121602. static long _huff_lengthlist__8c0_s_single[] = {
  121603. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  121604. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  121605. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  121606. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  121607. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  121608. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  121609. 17,16,17,17,
  121610. };
  121611. static static_codebook _huff_book__8c0_s_single = {
  121612. 2, 100,
  121613. _huff_lengthlist__8c0_s_single,
  121614. 0, 0, 0, 0, 0,
  121615. NULL,
  121616. NULL,
  121617. NULL,
  121618. NULL,
  121619. 0
  121620. };
  121621. static long _vq_quantlist__8c1_s_p1_0[] = {
  121622. 1,
  121623. 0,
  121624. 2,
  121625. };
  121626. static long _vq_lengthlist__8c1_s_p1_0[] = {
  121627. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  121628. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121632. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  121633. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121637. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  121638. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  121673. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  121674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  121678. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  121679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  121683. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  121684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121718. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  121719. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121723. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  121724. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  121725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121728. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  121729. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  121730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0,
  122006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122037. 0,
  122038. };
  122039. static float _vq_quantthresh__8c1_s_p1_0[] = {
  122040. -0.5, 0.5,
  122041. };
  122042. static long _vq_quantmap__8c1_s_p1_0[] = {
  122043. 1, 0, 2,
  122044. };
  122045. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  122046. _vq_quantthresh__8c1_s_p1_0,
  122047. _vq_quantmap__8c1_s_p1_0,
  122048. 3,
  122049. 3
  122050. };
  122051. static static_codebook _8c1_s_p1_0 = {
  122052. 8, 6561,
  122053. _vq_lengthlist__8c1_s_p1_0,
  122054. 1, -535822336, 1611661312, 2, 0,
  122055. _vq_quantlist__8c1_s_p1_0,
  122056. NULL,
  122057. &_vq_auxt__8c1_s_p1_0,
  122058. NULL,
  122059. 0
  122060. };
  122061. static long _vq_quantlist__8c1_s_p2_0[] = {
  122062. 2,
  122063. 1,
  122064. 3,
  122065. 0,
  122066. 4,
  122067. };
  122068. static long _vq_lengthlist__8c1_s_p2_0[] = {
  122069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122108. 0,
  122109. };
  122110. static float _vq_quantthresh__8c1_s_p2_0[] = {
  122111. -1.5, -0.5, 0.5, 1.5,
  122112. };
  122113. static long _vq_quantmap__8c1_s_p2_0[] = {
  122114. 3, 1, 0, 2, 4,
  122115. };
  122116. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  122117. _vq_quantthresh__8c1_s_p2_0,
  122118. _vq_quantmap__8c1_s_p2_0,
  122119. 5,
  122120. 5
  122121. };
  122122. static static_codebook _8c1_s_p2_0 = {
  122123. 4, 625,
  122124. _vq_lengthlist__8c1_s_p2_0,
  122125. 1, -533725184, 1611661312, 3, 0,
  122126. _vq_quantlist__8c1_s_p2_0,
  122127. NULL,
  122128. &_vq_auxt__8c1_s_p2_0,
  122129. NULL,
  122130. 0
  122131. };
  122132. static long _vq_quantlist__8c1_s_p3_0[] = {
  122133. 2,
  122134. 1,
  122135. 3,
  122136. 0,
  122137. 4,
  122138. };
  122139. static long _vq_lengthlist__8c1_s_p3_0[] = {
  122140. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  122142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122143. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  122145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122146. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122179. 0,
  122180. };
  122181. static float _vq_quantthresh__8c1_s_p3_0[] = {
  122182. -1.5, -0.5, 0.5, 1.5,
  122183. };
  122184. static long _vq_quantmap__8c1_s_p3_0[] = {
  122185. 3, 1, 0, 2, 4,
  122186. };
  122187. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  122188. _vq_quantthresh__8c1_s_p3_0,
  122189. _vq_quantmap__8c1_s_p3_0,
  122190. 5,
  122191. 5
  122192. };
  122193. static static_codebook _8c1_s_p3_0 = {
  122194. 4, 625,
  122195. _vq_lengthlist__8c1_s_p3_0,
  122196. 1, -533725184, 1611661312, 3, 0,
  122197. _vq_quantlist__8c1_s_p3_0,
  122198. NULL,
  122199. &_vq_auxt__8c1_s_p3_0,
  122200. NULL,
  122201. 0
  122202. };
  122203. static long _vq_quantlist__8c1_s_p4_0[] = {
  122204. 4,
  122205. 3,
  122206. 5,
  122207. 2,
  122208. 6,
  122209. 1,
  122210. 7,
  122211. 0,
  122212. 8,
  122213. };
  122214. static long _vq_lengthlist__8c1_s_p4_0[] = {
  122215. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122216. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122217. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122218. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  122219. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122220. 0,
  122221. };
  122222. static float _vq_quantthresh__8c1_s_p4_0[] = {
  122223. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122224. };
  122225. static long _vq_quantmap__8c1_s_p4_0[] = {
  122226. 7, 5, 3, 1, 0, 2, 4, 6,
  122227. 8,
  122228. };
  122229. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  122230. _vq_quantthresh__8c1_s_p4_0,
  122231. _vq_quantmap__8c1_s_p4_0,
  122232. 9,
  122233. 9
  122234. };
  122235. static static_codebook _8c1_s_p4_0 = {
  122236. 2, 81,
  122237. _vq_lengthlist__8c1_s_p4_0,
  122238. 1, -531628032, 1611661312, 4, 0,
  122239. _vq_quantlist__8c1_s_p4_0,
  122240. NULL,
  122241. &_vq_auxt__8c1_s_p4_0,
  122242. NULL,
  122243. 0
  122244. };
  122245. static long _vq_quantlist__8c1_s_p5_0[] = {
  122246. 4,
  122247. 3,
  122248. 5,
  122249. 2,
  122250. 6,
  122251. 1,
  122252. 7,
  122253. 0,
  122254. 8,
  122255. };
  122256. static long _vq_lengthlist__8c1_s_p5_0[] = {
  122257. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  122258. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  122259. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  122260. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  122261. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122262. 10,
  122263. };
  122264. static float _vq_quantthresh__8c1_s_p5_0[] = {
  122265. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122266. };
  122267. static long _vq_quantmap__8c1_s_p5_0[] = {
  122268. 7, 5, 3, 1, 0, 2, 4, 6,
  122269. 8,
  122270. };
  122271. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  122272. _vq_quantthresh__8c1_s_p5_0,
  122273. _vq_quantmap__8c1_s_p5_0,
  122274. 9,
  122275. 9
  122276. };
  122277. static static_codebook _8c1_s_p5_0 = {
  122278. 2, 81,
  122279. _vq_lengthlist__8c1_s_p5_0,
  122280. 1, -531628032, 1611661312, 4, 0,
  122281. _vq_quantlist__8c1_s_p5_0,
  122282. NULL,
  122283. &_vq_auxt__8c1_s_p5_0,
  122284. NULL,
  122285. 0
  122286. };
  122287. static long _vq_quantlist__8c1_s_p6_0[] = {
  122288. 8,
  122289. 7,
  122290. 9,
  122291. 6,
  122292. 10,
  122293. 5,
  122294. 11,
  122295. 4,
  122296. 12,
  122297. 3,
  122298. 13,
  122299. 2,
  122300. 14,
  122301. 1,
  122302. 15,
  122303. 0,
  122304. 16,
  122305. };
  122306. static long _vq_lengthlist__8c1_s_p6_0[] = {
  122307. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  122308. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  122309. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  122310. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  122311. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  122312. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  122313. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  122314. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  122315. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  122316. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122317. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  122318. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  122319. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  122320. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  122321. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  122322. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  122323. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  122324. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  122325. 14,
  122326. };
  122327. static float _vq_quantthresh__8c1_s_p6_0[] = {
  122328. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122329. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122330. };
  122331. static long _vq_quantmap__8c1_s_p6_0[] = {
  122332. 15, 13, 11, 9, 7, 5, 3, 1,
  122333. 0, 2, 4, 6, 8, 10, 12, 14,
  122334. 16,
  122335. };
  122336. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  122337. _vq_quantthresh__8c1_s_p6_0,
  122338. _vq_quantmap__8c1_s_p6_0,
  122339. 17,
  122340. 17
  122341. };
  122342. static static_codebook _8c1_s_p6_0 = {
  122343. 2, 289,
  122344. _vq_lengthlist__8c1_s_p6_0,
  122345. 1, -529530880, 1611661312, 5, 0,
  122346. _vq_quantlist__8c1_s_p6_0,
  122347. NULL,
  122348. &_vq_auxt__8c1_s_p6_0,
  122349. NULL,
  122350. 0
  122351. };
  122352. static long _vq_quantlist__8c1_s_p7_0[] = {
  122353. 1,
  122354. 0,
  122355. 2,
  122356. };
  122357. static long _vq_lengthlist__8c1_s_p7_0[] = {
  122358. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  122359. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  122360. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  122361. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  122362. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  122363. 9,
  122364. };
  122365. static float _vq_quantthresh__8c1_s_p7_0[] = {
  122366. -5.5, 5.5,
  122367. };
  122368. static long _vq_quantmap__8c1_s_p7_0[] = {
  122369. 1, 0, 2,
  122370. };
  122371. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  122372. _vq_quantthresh__8c1_s_p7_0,
  122373. _vq_quantmap__8c1_s_p7_0,
  122374. 3,
  122375. 3
  122376. };
  122377. static static_codebook _8c1_s_p7_0 = {
  122378. 4, 81,
  122379. _vq_lengthlist__8c1_s_p7_0,
  122380. 1, -529137664, 1618345984, 2, 0,
  122381. _vq_quantlist__8c1_s_p7_0,
  122382. NULL,
  122383. &_vq_auxt__8c1_s_p7_0,
  122384. NULL,
  122385. 0
  122386. };
  122387. static long _vq_quantlist__8c1_s_p7_1[] = {
  122388. 5,
  122389. 4,
  122390. 6,
  122391. 3,
  122392. 7,
  122393. 2,
  122394. 8,
  122395. 1,
  122396. 9,
  122397. 0,
  122398. 10,
  122399. };
  122400. static long _vq_lengthlist__8c1_s_p7_1[] = {
  122401. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  122402. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  122403. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  122404. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  122405. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  122406. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  122407. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  122408. 10,10,10, 8, 8, 8, 8, 8, 8,
  122409. };
  122410. static float _vq_quantthresh__8c1_s_p7_1[] = {
  122411. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122412. 3.5, 4.5,
  122413. };
  122414. static long _vq_quantmap__8c1_s_p7_1[] = {
  122415. 9, 7, 5, 3, 1, 0, 2, 4,
  122416. 6, 8, 10,
  122417. };
  122418. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  122419. _vq_quantthresh__8c1_s_p7_1,
  122420. _vq_quantmap__8c1_s_p7_1,
  122421. 11,
  122422. 11
  122423. };
  122424. static static_codebook _8c1_s_p7_1 = {
  122425. 2, 121,
  122426. _vq_lengthlist__8c1_s_p7_1,
  122427. 1, -531365888, 1611661312, 4, 0,
  122428. _vq_quantlist__8c1_s_p7_1,
  122429. NULL,
  122430. &_vq_auxt__8c1_s_p7_1,
  122431. NULL,
  122432. 0
  122433. };
  122434. static long _vq_quantlist__8c1_s_p8_0[] = {
  122435. 6,
  122436. 5,
  122437. 7,
  122438. 4,
  122439. 8,
  122440. 3,
  122441. 9,
  122442. 2,
  122443. 10,
  122444. 1,
  122445. 11,
  122446. 0,
  122447. 12,
  122448. };
  122449. static long _vq_lengthlist__8c1_s_p8_0[] = {
  122450. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  122451. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  122452. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  122453. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  122454. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  122455. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  122456. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  122457. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  122458. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  122459. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  122460. 0,12,12,11,10,12,11,13,12,
  122461. };
  122462. static float _vq_quantthresh__8c1_s_p8_0[] = {
  122463. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122464. 12.5, 17.5, 22.5, 27.5,
  122465. };
  122466. static long _vq_quantmap__8c1_s_p8_0[] = {
  122467. 11, 9, 7, 5, 3, 1, 0, 2,
  122468. 4, 6, 8, 10, 12,
  122469. };
  122470. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  122471. _vq_quantthresh__8c1_s_p8_0,
  122472. _vq_quantmap__8c1_s_p8_0,
  122473. 13,
  122474. 13
  122475. };
  122476. static static_codebook _8c1_s_p8_0 = {
  122477. 2, 169,
  122478. _vq_lengthlist__8c1_s_p8_0,
  122479. 1, -526516224, 1616117760, 4, 0,
  122480. _vq_quantlist__8c1_s_p8_0,
  122481. NULL,
  122482. &_vq_auxt__8c1_s_p8_0,
  122483. NULL,
  122484. 0
  122485. };
  122486. static long _vq_quantlist__8c1_s_p8_1[] = {
  122487. 2,
  122488. 1,
  122489. 3,
  122490. 0,
  122491. 4,
  122492. };
  122493. static long _vq_lengthlist__8c1_s_p8_1[] = {
  122494. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  122495. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  122496. };
  122497. static float _vq_quantthresh__8c1_s_p8_1[] = {
  122498. -1.5, -0.5, 0.5, 1.5,
  122499. };
  122500. static long _vq_quantmap__8c1_s_p8_1[] = {
  122501. 3, 1, 0, 2, 4,
  122502. };
  122503. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  122504. _vq_quantthresh__8c1_s_p8_1,
  122505. _vq_quantmap__8c1_s_p8_1,
  122506. 5,
  122507. 5
  122508. };
  122509. static static_codebook _8c1_s_p8_1 = {
  122510. 2, 25,
  122511. _vq_lengthlist__8c1_s_p8_1,
  122512. 1, -533725184, 1611661312, 3, 0,
  122513. _vq_quantlist__8c1_s_p8_1,
  122514. NULL,
  122515. &_vq_auxt__8c1_s_p8_1,
  122516. NULL,
  122517. 0
  122518. };
  122519. static long _vq_quantlist__8c1_s_p9_0[] = {
  122520. 6,
  122521. 5,
  122522. 7,
  122523. 4,
  122524. 8,
  122525. 3,
  122526. 9,
  122527. 2,
  122528. 10,
  122529. 1,
  122530. 11,
  122531. 0,
  122532. 12,
  122533. };
  122534. static long _vq_lengthlist__8c1_s_p9_0[] = {
  122535. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  122536. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  122537. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122538. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122539. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122540. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122541. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122542. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122543. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122544. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122545. 10,10,10,10,10, 9, 9, 9, 9,
  122546. };
  122547. static float _vq_quantthresh__8c1_s_p9_0[] = {
  122548. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  122549. 787.5, 1102.5, 1417.5, 1732.5,
  122550. };
  122551. static long _vq_quantmap__8c1_s_p9_0[] = {
  122552. 11, 9, 7, 5, 3, 1, 0, 2,
  122553. 4, 6, 8, 10, 12,
  122554. };
  122555. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  122556. _vq_quantthresh__8c1_s_p9_0,
  122557. _vq_quantmap__8c1_s_p9_0,
  122558. 13,
  122559. 13
  122560. };
  122561. static static_codebook _8c1_s_p9_0 = {
  122562. 2, 169,
  122563. _vq_lengthlist__8c1_s_p9_0,
  122564. 1, -513964032, 1628680192, 4, 0,
  122565. _vq_quantlist__8c1_s_p9_0,
  122566. NULL,
  122567. &_vq_auxt__8c1_s_p9_0,
  122568. NULL,
  122569. 0
  122570. };
  122571. static long _vq_quantlist__8c1_s_p9_1[] = {
  122572. 7,
  122573. 6,
  122574. 8,
  122575. 5,
  122576. 9,
  122577. 4,
  122578. 10,
  122579. 3,
  122580. 11,
  122581. 2,
  122582. 12,
  122583. 1,
  122584. 13,
  122585. 0,
  122586. 14,
  122587. };
  122588. static long _vq_lengthlist__8c1_s_p9_1[] = {
  122589. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  122590. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  122591. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  122592. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  122593. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  122594. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  122595. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  122596. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  122597. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  122598. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  122599. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  122600. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  122601. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  122602. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  122603. 15,
  122604. };
  122605. static float _vq_quantthresh__8c1_s_p9_1[] = {
  122606. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  122607. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  122608. };
  122609. static long _vq_quantmap__8c1_s_p9_1[] = {
  122610. 13, 11, 9, 7, 5, 3, 1, 0,
  122611. 2, 4, 6, 8, 10, 12, 14,
  122612. };
  122613. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  122614. _vq_quantthresh__8c1_s_p9_1,
  122615. _vq_quantmap__8c1_s_p9_1,
  122616. 15,
  122617. 15
  122618. };
  122619. static static_codebook _8c1_s_p9_1 = {
  122620. 2, 225,
  122621. _vq_lengthlist__8c1_s_p9_1,
  122622. 1, -520986624, 1620377600, 4, 0,
  122623. _vq_quantlist__8c1_s_p9_1,
  122624. NULL,
  122625. &_vq_auxt__8c1_s_p9_1,
  122626. NULL,
  122627. 0
  122628. };
  122629. static long _vq_quantlist__8c1_s_p9_2[] = {
  122630. 10,
  122631. 9,
  122632. 11,
  122633. 8,
  122634. 12,
  122635. 7,
  122636. 13,
  122637. 6,
  122638. 14,
  122639. 5,
  122640. 15,
  122641. 4,
  122642. 16,
  122643. 3,
  122644. 17,
  122645. 2,
  122646. 18,
  122647. 1,
  122648. 19,
  122649. 0,
  122650. 20,
  122651. };
  122652. static long _vq_lengthlist__8c1_s_p9_2[] = {
  122653. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  122654. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  122655. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  122656. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  122657. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  122658. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  122659. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  122660. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  122661. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  122662. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  122663. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  122664. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  122665. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  122666. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  122667. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  122668. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  122669. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122670. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  122671. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  122672. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  122673. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122674. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  122675. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  122676. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  122677. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  122678. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  122679. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  122680. 10,10,10,10,10,10,10,10,10,
  122681. };
  122682. static float _vq_quantthresh__8c1_s_p9_2[] = {
  122683. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  122684. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  122685. 6.5, 7.5, 8.5, 9.5,
  122686. };
  122687. static long _vq_quantmap__8c1_s_p9_2[] = {
  122688. 19, 17, 15, 13, 11, 9, 7, 5,
  122689. 3, 1, 0, 2, 4, 6, 8, 10,
  122690. 12, 14, 16, 18, 20,
  122691. };
  122692. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  122693. _vq_quantthresh__8c1_s_p9_2,
  122694. _vq_quantmap__8c1_s_p9_2,
  122695. 21,
  122696. 21
  122697. };
  122698. static static_codebook _8c1_s_p9_2 = {
  122699. 2, 441,
  122700. _vq_lengthlist__8c1_s_p9_2,
  122701. 1, -529268736, 1611661312, 5, 0,
  122702. _vq_quantlist__8c1_s_p9_2,
  122703. NULL,
  122704. &_vq_auxt__8c1_s_p9_2,
  122705. NULL,
  122706. 0
  122707. };
  122708. static long _huff_lengthlist__8c1_s_single[] = {
  122709. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  122710. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  122711. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  122712. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  122713. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  122714. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  122715. 9, 7, 7, 8,
  122716. };
  122717. static static_codebook _huff_book__8c1_s_single = {
  122718. 2, 100,
  122719. _huff_lengthlist__8c1_s_single,
  122720. 0, 0, 0, 0, 0,
  122721. NULL,
  122722. NULL,
  122723. NULL,
  122724. NULL,
  122725. 0
  122726. };
  122727. static long _huff_lengthlist__44c2_s_long[] = {
  122728. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  122729. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  122730. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  122731. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  122732. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  122733. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  122734. 10, 8, 8, 9,
  122735. };
  122736. static static_codebook _huff_book__44c2_s_long = {
  122737. 2, 100,
  122738. _huff_lengthlist__44c2_s_long,
  122739. 0, 0, 0, 0, 0,
  122740. NULL,
  122741. NULL,
  122742. NULL,
  122743. NULL,
  122744. 0
  122745. };
  122746. static long _vq_quantlist__44c2_s_p1_0[] = {
  122747. 1,
  122748. 0,
  122749. 2,
  122750. };
  122751. static long _vq_lengthlist__44c2_s_p1_0[] = {
  122752. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  122753. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  122758. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  122763. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122798. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  122803. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  122808. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  122844. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  122849. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  122854. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0,
  123163. };
  123164. static float _vq_quantthresh__44c2_s_p1_0[] = {
  123165. -0.5, 0.5,
  123166. };
  123167. static long _vq_quantmap__44c2_s_p1_0[] = {
  123168. 1, 0, 2,
  123169. };
  123170. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  123171. _vq_quantthresh__44c2_s_p1_0,
  123172. _vq_quantmap__44c2_s_p1_0,
  123173. 3,
  123174. 3
  123175. };
  123176. static static_codebook _44c2_s_p1_0 = {
  123177. 8, 6561,
  123178. _vq_lengthlist__44c2_s_p1_0,
  123179. 1, -535822336, 1611661312, 2, 0,
  123180. _vq_quantlist__44c2_s_p1_0,
  123181. NULL,
  123182. &_vq_auxt__44c2_s_p1_0,
  123183. NULL,
  123184. 0
  123185. };
  123186. static long _vq_quantlist__44c2_s_p2_0[] = {
  123187. 2,
  123188. 1,
  123189. 3,
  123190. 0,
  123191. 4,
  123192. };
  123193. static long _vq_lengthlist__44c2_s_p2_0[] = {
  123194. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  123195. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  123196. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  123197. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  123198. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123203. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  123204. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  123205. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  123206. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123211. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  123212. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  123213. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  123214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  123220. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  123221. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  123222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123233. 0,
  123234. };
  123235. static float _vq_quantthresh__44c2_s_p2_0[] = {
  123236. -1.5, -0.5, 0.5, 1.5,
  123237. };
  123238. static long _vq_quantmap__44c2_s_p2_0[] = {
  123239. 3, 1, 0, 2, 4,
  123240. };
  123241. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  123242. _vq_quantthresh__44c2_s_p2_0,
  123243. _vq_quantmap__44c2_s_p2_0,
  123244. 5,
  123245. 5
  123246. };
  123247. static static_codebook _44c2_s_p2_0 = {
  123248. 4, 625,
  123249. _vq_lengthlist__44c2_s_p2_0,
  123250. 1, -533725184, 1611661312, 3, 0,
  123251. _vq_quantlist__44c2_s_p2_0,
  123252. NULL,
  123253. &_vq_auxt__44c2_s_p2_0,
  123254. NULL,
  123255. 0
  123256. };
  123257. static long _vq_quantlist__44c2_s_p3_0[] = {
  123258. 2,
  123259. 1,
  123260. 3,
  123261. 0,
  123262. 4,
  123263. };
  123264. static long _vq_lengthlist__44c2_s_p3_0[] = {
  123265. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  123267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123268. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123271. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0,
  123305. };
  123306. static float _vq_quantthresh__44c2_s_p3_0[] = {
  123307. -1.5, -0.5, 0.5, 1.5,
  123308. };
  123309. static long _vq_quantmap__44c2_s_p3_0[] = {
  123310. 3, 1, 0, 2, 4,
  123311. };
  123312. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  123313. _vq_quantthresh__44c2_s_p3_0,
  123314. _vq_quantmap__44c2_s_p3_0,
  123315. 5,
  123316. 5
  123317. };
  123318. static static_codebook _44c2_s_p3_0 = {
  123319. 4, 625,
  123320. _vq_lengthlist__44c2_s_p3_0,
  123321. 1, -533725184, 1611661312, 3, 0,
  123322. _vq_quantlist__44c2_s_p3_0,
  123323. NULL,
  123324. &_vq_auxt__44c2_s_p3_0,
  123325. NULL,
  123326. 0
  123327. };
  123328. static long _vq_quantlist__44c2_s_p4_0[] = {
  123329. 4,
  123330. 3,
  123331. 5,
  123332. 2,
  123333. 6,
  123334. 1,
  123335. 7,
  123336. 0,
  123337. 8,
  123338. };
  123339. static long _vq_lengthlist__44c2_s_p4_0[] = {
  123340. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  123341. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  123342. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  123343. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123344. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123345. 0,
  123346. };
  123347. static float _vq_quantthresh__44c2_s_p4_0[] = {
  123348. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123349. };
  123350. static long _vq_quantmap__44c2_s_p4_0[] = {
  123351. 7, 5, 3, 1, 0, 2, 4, 6,
  123352. 8,
  123353. };
  123354. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  123355. _vq_quantthresh__44c2_s_p4_0,
  123356. _vq_quantmap__44c2_s_p4_0,
  123357. 9,
  123358. 9
  123359. };
  123360. static static_codebook _44c2_s_p4_0 = {
  123361. 2, 81,
  123362. _vq_lengthlist__44c2_s_p4_0,
  123363. 1, -531628032, 1611661312, 4, 0,
  123364. _vq_quantlist__44c2_s_p4_0,
  123365. NULL,
  123366. &_vq_auxt__44c2_s_p4_0,
  123367. NULL,
  123368. 0
  123369. };
  123370. static long _vq_quantlist__44c2_s_p5_0[] = {
  123371. 4,
  123372. 3,
  123373. 5,
  123374. 2,
  123375. 6,
  123376. 1,
  123377. 7,
  123378. 0,
  123379. 8,
  123380. };
  123381. static long _vq_lengthlist__44c2_s_p5_0[] = {
  123382. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  123383. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  123384. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  123385. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  123386. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  123387. 11,
  123388. };
  123389. static float _vq_quantthresh__44c2_s_p5_0[] = {
  123390. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123391. };
  123392. static long _vq_quantmap__44c2_s_p5_0[] = {
  123393. 7, 5, 3, 1, 0, 2, 4, 6,
  123394. 8,
  123395. };
  123396. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  123397. _vq_quantthresh__44c2_s_p5_0,
  123398. _vq_quantmap__44c2_s_p5_0,
  123399. 9,
  123400. 9
  123401. };
  123402. static static_codebook _44c2_s_p5_0 = {
  123403. 2, 81,
  123404. _vq_lengthlist__44c2_s_p5_0,
  123405. 1, -531628032, 1611661312, 4, 0,
  123406. _vq_quantlist__44c2_s_p5_0,
  123407. NULL,
  123408. &_vq_auxt__44c2_s_p5_0,
  123409. NULL,
  123410. 0
  123411. };
  123412. static long _vq_quantlist__44c2_s_p6_0[] = {
  123413. 8,
  123414. 7,
  123415. 9,
  123416. 6,
  123417. 10,
  123418. 5,
  123419. 11,
  123420. 4,
  123421. 12,
  123422. 3,
  123423. 13,
  123424. 2,
  123425. 14,
  123426. 1,
  123427. 15,
  123428. 0,
  123429. 16,
  123430. };
  123431. static long _vq_lengthlist__44c2_s_p6_0[] = {
  123432. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  123433. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123434. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  123435. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  123436. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  123437. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123438. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123439. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  123440. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  123441. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123442. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123443. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  123444. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  123445. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123446. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  123447. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  123448. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123449. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123450. 14,
  123451. };
  123452. static float _vq_quantthresh__44c2_s_p6_0[] = {
  123453. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123454. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123455. };
  123456. static long _vq_quantmap__44c2_s_p6_0[] = {
  123457. 15, 13, 11, 9, 7, 5, 3, 1,
  123458. 0, 2, 4, 6, 8, 10, 12, 14,
  123459. 16,
  123460. };
  123461. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  123462. _vq_quantthresh__44c2_s_p6_0,
  123463. _vq_quantmap__44c2_s_p6_0,
  123464. 17,
  123465. 17
  123466. };
  123467. static static_codebook _44c2_s_p6_0 = {
  123468. 2, 289,
  123469. _vq_lengthlist__44c2_s_p6_0,
  123470. 1, -529530880, 1611661312, 5, 0,
  123471. _vq_quantlist__44c2_s_p6_0,
  123472. NULL,
  123473. &_vq_auxt__44c2_s_p6_0,
  123474. NULL,
  123475. 0
  123476. };
  123477. static long _vq_quantlist__44c2_s_p7_0[] = {
  123478. 1,
  123479. 0,
  123480. 2,
  123481. };
  123482. static long _vq_lengthlist__44c2_s_p7_0[] = {
  123483. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  123484. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  123485. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  123486. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  123487. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  123488. 11,
  123489. };
  123490. static float _vq_quantthresh__44c2_s_p7_0[] = {
  123491. -5.5, 5.5,
  123492. };
  123493. static long _vq_quantmap__44c2_s_p7_0[] = {
  123494. 1, 0, 2,
  123495. };
  123496. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  123497. _vq_quantthresh__44c2_s_p7_0,
  123498. _vq_quantmap__44c2_s_p7_0,
  123499. 3,
  123500. 3
  123501. };
  123502. static static_codebook _44c2_s_p7_0 = {
  123503. 4, 81,
  123504. _vq_lengthlist__44c2_s_p7_0,
  123505. 1, -529137664, 1618345984, 2, 0,
  123506. _vq_quantlist__44c2_s_p7_0,
  123507. NULL,
  123508. &_vq_auxt__44c2_s_p7_0,
  123509. NULL,
  123510. 0
  123511. };
  123512. static long _vq_quantlist__44c2_s_p7_1[] = {
  123513. 5,
  123514. 4,
  123515. 6,
  123516. 3,
  123517. 7,
  123518. 2,
  123519. 8,
  123520. 1,
  123521. 9,
  123522. 0,
  123523. 10,
  123524. };
  123525. static long _vq_lengthlist__44c2_s_p7_1[] = {
  123526. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  123527. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  123528. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123529. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  123530. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  123531. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  123532. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  123533. 10,10,10, 8, 8, 8, 8, 8, 8,
  123534. };
  123535. static float _vq_quantthresh__44c2_s_p7_1[] = {
  123536. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123537. 3.5, 4.5,
  123538. };
  123539. static long _vq_quantmap__44c2_s_p7_1[] = {
  123540. 9, 7, 5, 3, 1, 0, 2, 4,
  123541. 6, 8, 10,
  123542. };
  123543. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  123544. _vq_quantthresh__44c2_s_p7_1,
  123545. _vq_quantmap__44c2_s_p7_1,
  123546. 11,
  123547. 11
  123548. };
  123549. static static_codebook _44c2_s_p7_1 = {
  123550. 2, 121,
  123551. _vq_lengthlist__44c2_s_p7_1,
  123552. 1, -531365888, 1611661312, 4, 0,
  123553. _vq_quantlist__44c2_s_p7_1,
  123554. NULL,
  123555. &_vq_auxt__44c2_s_p7_1,
  123556. NULL,
  123557. 0
  123558. };
  123559. static long _vq_quantlist__44c2_s_p8_0[] = {
  123560. 6,
  123561. 5,
  123562. 7,
  123563. 4,
  123564. 8,
  123565. 3,
  123566. 9,
  123567. 2,
  123568. 10,
  123569. 1,
  123570. 11,
  123571. 0,
  123572. 12,
  123573. };
  123574. static long _vq_lengthlist__44c2_s_p8_0[] = {
  123575. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  123576. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  123577. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123578. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123579. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  123580. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  123581. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  123582. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  123583. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  123584. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  123585. 0,12,12,12,12,13,12,14,14,
  123586. };
  123587. static float _vq_quantthresh__44c2_s_p8_0[] = {
  123588. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123589. 12.5, 17.5, 22.5, 27.5,
  123590. };
  123591. static long _vq_quantmap__44c2_s_p8_0[] = {
  123592. 11, 9, 7, 5, 3, 1, 0, 2,
  123593. 4, 6, 8, 10, 12,
  123594. };
  123595. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  123596. _vq_quantthresh__44c2_s_p8_0,
  123597. _vq_quantmap__44c2_s_p8_0,
  123598. 13,
  123599. 13
  123600. };
  123601. static static_codebook _44c2_s_p8_0 = {
  123602. 2, 169,
  123603. _vq_lengthlist__44c2_s_p8_0,
  123604. 1, -526516224, 1616117760, 4, 0,
  123605. _vq_quantlist__44c2_s_p8_0,
  123606. NULL,
  123607. &_vq_auxt__44c2_s_p8_0,
  123608. NULL,
  123609. 0
  123610. };
  123611. static long _vq_quantlist__44c2_s_p8_1[] = {
  123612. 2,
  123613. 1,
  123614. 3,
  123615. 0,
  123616. 4,
  123617. };
  123618. static long _vq_lengthlist__44c2_s_p8_1[] = {
  123619. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  123620. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  123621. };
  123622. static float _vq_quantthresh__44c2_s_p8_1[] = {
  123623. -1.5, -0.5, 0.5, 1.5,
  123624. };
  123625. static long _vq_quantmap__44c2_s_p8_1[] = {
  123626. 3, 1, 0, 2, 4,
  123627. };
  123628. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  123629. _vq_quantthresh__44c2_s_p8_1,
  123630. _vq_quantmap__44c2_s_p8_1,
  123631. 5,
  123632. 5
  123633. };
  123634. static static_codebook _44c2_s_p8_1 = {
  123635. 2, 25,
  123636. _vq_lengthlist__44c2_s_p8_1,
  123637. 1, -533725184, 1611661312, 3, 0,
  123638. _vq_quantlist__44c2_s_p8_1,
  123639. NULL,
  123640. &_vq_auxt__44c2_s_p8_1,
  123641. NULL,
  123642. 0
  123643. };
  123644. static long _vq_quantlist__44c2_s_p9_0[] = {
  123645. 6,
  123646. 5,
  123647. 7,
  123648. 4,
  123649. 8,
  123650. 3,
  123651. 9,
  123652. 2,
  123653. 10,
  123654. 1,
  123655. 11,
  123656. 0,
  123657. 12,
  123658. };
  123659. static long _vq_lengthlist__44c2_s_p9_0[] = {
  123660. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  123661. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  123662. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123663. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  123664. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123665. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123666. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123667. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123668. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123669. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123670. 11,11,11,11,11,11,11,11,11,
  123671. };
  123672. static float _vq_quantthresh__44c2_s_p9_0[] = {
  123673. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  123674. 552.5, 773.5, 994.5, 1215.5,
  123675. };
  123676. static long _vq_quantmap__44c2_s_p9_0[] = {
  123677. 11, 9, 7, 5, 3, 1, 0, 2,
  123678. 4, 6, 8, 10, 12,
  123679. };
  123680. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  123681. _vq_quantthresh__44c2_s_p9_0,
  123682. _vq_quantmap__44c2_s_p9_0,
  123683. 13,
  123684. 13
  123685. };
  123686. static static_codebook _44c2_s_p9_0 = {
  123687. 2, 169,
  123688. _vq_lengthlist__44c2_s_p9_0,
  123689. 1, -514541568, 1627103232, 4, 0,
  123690. _vq_quantlist__44c2_s_p9_0,
  123691. NULL,
  123692. &_vq_auxt__44c2_s_p9_0,
  123693. NULL,
  123694. 0
  123695. };
  123696. static long _vq_quantlist__44c2_s_p9_1[] = {
  123697. 6,
  123698. 5,
  123699. 7,
  123700. 4,
  123701. 8,
  123702. 3,
  123703. 9,
  123704. 2,
  123705. 10,
  123706. 1,
  123707. 11,
  123708. 0,
  123709. 12,
  123710. };
  123711. static long _vq_lengthlist__44c2_s_p9_1[] = {
  123712. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  123713. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  123714. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  123715. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  123716. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  123717. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  123718. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  123719. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  123720. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  123721. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  123722. 17,13,12,12,10,13,11,14,14,
  123723. };
  123724. static float _vq_quantthresh__44c2_s_p9_1[] = {
  123725. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  123726. 42.5, 59.5, 76.5, 93.5,
  123727. };
  123728. static long _vq_quantmap__44c2_s_p9_1[] = {
  123729. 11, 9, 7, 5, 3, 1, 0, 2,
  123730. 4, 6, 8, 10, 12,
  123731. };
  123732. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  123733. _vq_quantthresh__44c2_s_p9_1,
  123734. _vq_quantmap__44c2_s_p9_1,
  123735. 13,
  123736. 13
  123737. };
  123738. static static_codebook _44c2_s_p9_1 = {
  123739. 2, 169,
  123740. _vq_lengthlist__44c2_s_p9_1,
  123741. 1, -522616832, 1620115456, 4, 0,
  123742. _vq_quantlist__44c2_s_p9_1,
  123743. NULL,
  123744. &_vq_auxt__44c2_s_p9_1,
  123745. NULL,
  123746. 0
  123747. };
  123748. static long _vq_quantlist__44c2_s_p9_2[] = {
  123749. 8,
  123750. 7,
  123751. 9,
  123752. 6,
  123753. 10,
  123754. 5,
  123755. 11,
  123756. 4,
  123757. 12,
  123758. 3,
  123759. 13,
  123760. 2,
  123761. 14,
  123762. 1,
  123763. 15,
  123764. 0,
  123765. 16,
  123766. };
  123767. static long _vq_lengthlist__44c2_s_p9_2[] = {
  123768. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  123769. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  123770. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  123771. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  123772. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  123773. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  123774. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  123775. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  123776. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  123777. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  123778. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  123779. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  123780. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  123781. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  123782. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  123783. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  123784. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  123785. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  123786. 10,
  123787. };
  123788. static float _vq_quantthresh__44c2_s_p9_2[] = {
  123789. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123790. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123791. };
  123792. static long _vq_quantmap__44c2_s_p9_2[] = {
  123793. 15, 13, 11, 9, 7, 5, 3, 1,
  123794. 0, 2, 4, 6, 8, 10, 12, 14,
  123795. 16,
  123796. };
  123797. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  123798. _vq_quantthresh__44c2_s_p9_2,
  123799. _vq_quantmap__44c2_s_p9_2,
  123800. 17,
  123801. 17
  123802. };
  123803. static static_codebook _44c2_s_p9_2 = {
  123804. 2, 289,
  123805. _vq_lengthlist__44c2_s_p9_2,
  123806. 1, -529530880, 1611661312, 5, 0,
  123807. _vq_quantlist__44c2_s_p9_2,
  123808. NULL,
  123809. &_vq_auxt__44c2_s_p9_2,
  123810. NULL,
  123811. 0
  123812. };
  123813. static long _huff_lengthlist__44c2_s_short[] = {
  123814. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  123815. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  123816. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  123817. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  123818. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  123819. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  123820. 6, 8, 9,12,
  123821. };
  123822. static static_codebook _huff_book__44c2_s_short = {
  123823. 2, 100,
  123824. _huff_lengthlist__44c2_s_short,
  123825. 0, 0, 0, 0, 0,
  123826. NULL,
  123827. NULL,
  123828. NULL,
  123829. NULL,
  123830. 0
  123831. };
  123832. static long _huff_lengthlist__44c3_s_long[] = {
  123833. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  123834. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  123835. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  123836. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  123837. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  123838. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  123839. 9, 8, 8, 8,
  123840. };
  123841. static static_codebook _huff_book__44c3_s_long = {
  123842. 2, 100,
  123843. _huff_lengthlist__44c3_s_long,
  123844. 0, 0, 0, 0, 0,
  123845. NULL,
  123846. NULL,
  123847. NULL,
  123848. NULL,
  123849. 0
  123850. };
  123851. static long _vq_quantlist__44c3_s_p1_0[] = {
  123852. 1,
  123853. 0,
  123854. 2,
  123855. };
  123856. static long _vq_lengthlist__44c3_s_p1_0[] = {
  123857. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  123858. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123863. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  123868. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123903. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123908. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  123913. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123949. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123954. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123959. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124267. 0,
  124268. };
  124269. static float _vq_quantthresh__44c3_s_p1_0[] = {
  124270. -0.5, 0.5,
  124271. };
  124272. static long _vq_quantmap__44c3_s_p1_0[] = {
  124273. 1, 0, 2,
  124274. };
  124275. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  124276. _vq_quantthresh__44c3_s_p1_0,
  124277. _vq_quantmap__44c3_s_p1_0,
  124278. 3,
  124279. 3
  124280. };
  124281. static static_codebook _44c3_s_p1_0 = {
  124282. 8, 6561,
  124283. _vq_lengthlist__44c3_s_p1_0,
  124284. 1, -535822336, 1611661312, 2, 0,
  124285. _vq_quantlist__44c3_s_p1_0,
  124286. NULL,
  124287. &_vq_auxt__44c3_s_p1_0,
  124288. NULL,
  124289. 0
  124290. };
  124291. static long _vq_quantlist__44c3_s_p2_0[] = {
  124292. 2,
  124293. 1,
  124294. 3,
  124295. 0,
  124296. 4,
  124297. };
  124298. static long _vq_lengthlist__44c3_s_p2_0[] = {
  124299. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  124300. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  124301. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  124302. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  124303. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124308. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  124309. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  124310. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  124311. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124316. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  124317. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  124318. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  124319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124324. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  124325. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  124326. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  124327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124338. 0,
  124339. };
  124340. static float _vq_quantthresh__44c3_s_p2_0[] = {
  124341. -1.5, -0.5, 0.5, 1.5,
  124342. };
  124343. static long _vq_quantmap__44c3_s_p2_0[] = {
  124344. 3, 1, 0, 2, 4,
  124345. };
  124346. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  124347. _vq_quantthresh__44c3_s_p2_0,
  124348. _vq_quantmap__44c3_s_p2_0,
  124349. 5,
  124350. 5
  124351. };
  124352. static static_codebook _44c3_s_p2_0 = {
  124353. 4, 625,
  124354. _vq_lengthlist__44c3_s_p2_0,
  124355. 1, -533725184, 1611661312, 3, 0,
  124356. _vq_quantlist__44c3_s_p2_0,
  124357. NULL,
  124358. &_vq_auxt__44c3_s_p2_0,
  124359. NULL,
  124360. 0
  124361. };
  124362. static long _vq_quantlist__44c3_s_p3_0[] = {
  124363. 2,
  124364. 1,
  124365. 3,
  124366. 0,
  124367. 4,
  124368. };
  124369. static long _vq_lengthlist__44c3_s_p3_0[] = {
  124370. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  124372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124373. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  124375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124376. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124409. 0,
  124410. };
  124411. static float _vq_quantthresh__44c3_s_p3_0[] = {
  124412. -1.5, -0.5, 0.5, 1.5,
  124413. };
  124414. static long _vq_quantmap__44c3_s_p3_0[] = {
  124415. 3, 1, 0, 2, 4,
  124416. };
  124417. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  124418. _vq_quantthresh__44c3_s_p3_0,
  124419. _vq_quantmap__44c3_s_p3_0,
  124420. 5,
  124421. 5
  124422. };
  124423. static static_codebook _44c3_s_p3_0 = {
  124424. 4, 625,
  124425. _vq_lengthlist__44c3_s_p3_0,
  124426. 1, -533725184, 1611661312, 3, 0,
  124427. _vq_quantlist__44c3_s_p3_0,
  124428. NULL,
  124429. &_vq_auxt__44c3_s_p3_0,
  124430. NULL,
  124431. 0
  124432. };
  124433. static long _vq_quantlist__44c3_s_p4_0[] = {
  124434. 4,
  124435. 3,
  124436. 5,
  124437. 2,
  124438. 6,
  124439. 1,
  124440. 7,
  124441. 0,
  124442. 8,
  124443. };
  124444. static long _vq_lengthlist__44c3_s_p4_0[] = {
  124445. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  124446. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  124447. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  124448. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  124449. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124450. 0,
  124451. };
  124452. static float _vq_quantthresh__44c3_s_p4_0[] = {
  124453. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124454. };
  124455. static long _vq_quantmap__44c3_s_p4_0[] = {
  124456. 7, 5, 3, 1, 0, 2, 4, 6,
  124457. 8,
  124458. };
  124459. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  124460. _vq_quantthresh__44c3_s_p4_0,
  124461. _vq_quantmap__44c3_s_p4_0,
  124462. 9,
  124463. 9
  124464. };
  124465. static static_codebook _44c3_s_p4_0 = {
  124466. 2, 81,
  124467. _vq_lengthlist__44c3_s_p4_0,
  124468. 1, -531628032, 1611661312, 4, 0,
  124469. _vq_quantlist__44c3_s_p4_0,
  124470. NULL,
  124471. &_vq_auxt__44c3_s_p4_0,
  124472. NULL,
  124473. 0
  124474. };
  124475. static long _vq_quantlist__44c3_s_p5_0[] = {
  124476. 4,
  124477. 3,
  124478. 5,
  124479. 2,
  124480. 6,
  124481. 1,
  124482. 7,
  124483. 0,
  124484. 8,
  124485. };
  124486. static long _vq_lengthlist__44c3_s_p5_0[] = {
  124487. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  124488. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  124489. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124490. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  124491. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  124492. 11,
  124493. };
  124494. static float _vq_quantthresh__44c3_s_p5_0[] = {
  124495. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124496. };
  124497. static long _vq_quantmap__44c3_s_p5_0[] = {
  124498. 7, 5, 3, 1, 0, 2, 4, 6,
  124499. 8,
  124500. };
  124501. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  124502. _vq_quantthresh__44c3_s_p5_0,
  124503. _vq_quantmap__44c3_s_p5_0,
  124504. 9,
  124505. 9
  124506. };
  124507. static static_codebook _44c3_s_p5_0 = {
  124508. 2, 81,
  124509. _vq_lengthlist__44c3_s_p5_0,
  124510. 1, -531628032, 1611661312, 4, 0,
  124511. _vq_quantlist__44c3_s_p5_0,
  124512. NULL,
  124513. &_vq_auxt__44c3_s_p5_0,
  124514. NULL,
  124515. 0
  124516. };
  124517. static long _vq_quantlist__44c3_s_p6_0[] = {
  124518. 8,
  124519. 7,
  124520. 9,
  124521. 6,
  124522. 10,
  124523. 5,
  124524. 11,
  124525. 4,
  124526. 12,
  124527. 3,
  124528. 13,
  124529. 2,
  124530. 14,
  124531. 1,
  124532. 15,
  124533. 0,
  124534. 16,
  124535. };
  124536. static long _vq_lengthlist__44c3_s_p6_0[] = {
  124537. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  124538. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  124539. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  124540. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  124541. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  124542. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124543. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  124544. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  124545. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  124546. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  124547. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  124548. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  124549. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  124550. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  124551. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  124552. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  124553. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  124554. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  124555. 13,
  124556. };
  124557. static float _vq_quantthresh__44c3_s_p6_0[] = {
  124558. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124559. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124560. };
  124561. static long _vq_quantmap__44c3_s_p6_0[] = {
  124562. 15, 13, 11, 9, 7, 5, 3, 1,
  124563. 0, 2, 4, 6, 8, 10, 12, 14,
  124564. 16,
  124565. };
  124566. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  124567. _vq_quantthresh__44c3_s_p6_0,
  124568. _vq_quantmap__44c3_s_p6_0,
  124569. 17,
  124570. 17
  124571. };
  124572. static static_codebook _44c3_s_p6_0 = {
  124573. 2, 289,
  124574. _vq_lengthlist__44c3_s_p6_0,
  124575. 1, -529530880, 1611661312, 5, 0,
  124576. _vq_quantlist__44c3_s_p6_0,
  124577. NULL,
  124578. &_vq_auxt__44c3_s_p6_0,
  124579. NULL,
  124580. 0
  124581. };
  124582. static long _vq_quantlist__44c3_s_p7_0[] = {
  124583. 1,
  124584. 0,
  124585. 2,
  124586. };
  124587. static long _vq_lengthlist__44c3_s_p7_0[] = {
  124588. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  124589. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  124590. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  124591. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  124592. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  124593. 10,
  124594. };
  124595. static float _vq_quantthresh__44c3_s_p7_0[] = {
  124596. -5.5, 5.5,
  124597. };
  124598. static long _vq_quantmap__44c3_s_p7_0[] = {
  124599. 1, 0, 2,
  124600. };
  124601. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  124602. _vq_quantthresh__44c3_s_p7_0,
  124603. _vq_quantmap__44c3_s_p7_0,
  124604. 3,
  124605. 3
  124606. };
  124607. static static_codebook _44c3_s_p7_0 = {
  124608. 4, 81,
  124609. _vq_lengthlist__44c3_s_p7_0,
  124610. 1, -529137664, 1618345984, 2, 0,
  124611. _vq_quantlist__44c3_s_p7_0,
  124612. NULL,
  124613. &_vq_auxt__44c3_s_p7_0,
  124614. NULL,
  124615. 0
  124616. };
  124617. static long _vq_quantlist__44c3_s_p7_1[] = {
  124618. 5,
  124619. 4,
  124620. 6,
  124621. 3,
  124622. 7,
  124623. 2,
  124624. 8,
  124625. 1,
  124626. 9,
  124627. 0,
  124628. 10,
  124629. };
  124630. static long _vq_lengthlist__44c3_s_p7_1[] = {
  124631. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  124632. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  124633. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  124634. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  124635. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  124636. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  124637. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  124638. 10,10,10, 8, 8, 8, 8, 8, 8,
  124639. };
  124640. static float _vq_quantthresh__44c3_s_p7_1[] = {
  124641. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124642. 3.5, 4.5,
  124643. };
  124644. static long _vq_quantmap__44c3_s_p7_1[] = {
  124645. 9, 7, 5, 3, 1, 0, 2, 4,
  124646. 6, 8, 10,
  124647. };
  124648. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  124649. _vq_quantthresh__44c3_s_p7_1,
  124650. _vq_quantmap__44c3_s_p7_1,
  124651. 11,
  124652. 11
  124653. };
  124654. static static_codebook _44c3_s_p7_1 = {
  124655. 2, 121,
  124656. _vq_lengthlist__44c3_s_p7_1,
  124657. 1, -531365888, 1611661312, 4, 0,
  124658. _vq_quantlist__44c3_s_p7_1,
  124659. NULL,
  124660. &_vq_auxt__44c3_s_p7_1,
  124661. NULL,
  124662. 0
  124663. };
  124664. static long _vq_quantlist__44c3_s_p8_0[] = {
  124665. 6,
  124666. 5,
  124667. 7,
  124668. 4,
  124669. 8,
  124670. 3,
  124671. 9,
  124672. 2,
  124673. 10,
  124674. 1,
  124675. 11,
  124676. 0,
  124677. 12,
  124678. };
  124679. static long _vq_lengthlist__44c3_s_p8_0[] = {
  124680. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  124681. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  124682. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124683. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124684. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  124685. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124686. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  124687. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  124688. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  124689. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  124690. 0,13,13,12,12,13,12,14,13,
  124691. };
  124692. static float _vq_quantthresh__44c3_s_p8_0[] = {
  124693. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124694. 12.5, 17.5, 22.5, 27.5,
  124695. };
  124696. static long _vq_quantmap__44c3_s_p8_0[] = {
  124697. 11, 9, 7, 5, 3, 1, 0, 2,
  124698. 4, 6, 8, 10, 12,
  124699. };
  124700. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  124701. _vq_quantthresh__44c3_s_p8_0,
  124702. _vq_quantmap__44c3_s_p8_0,
  124703. 13,
  124704. 13
  124705. };
  124706. static static_codebook _44c3_s_p8_0 = {
  124707. 2, 169,
  124708. _vq_lengthlist__44c3_s_p8_0,
  124709. 1, -526516224, 1616117760, 4, 0,
  124710. _vq_quantlist__44c3_s_p8_0,
  124711. NULL,
  124712. &_vq_auxt__44c3_s_p8_0,
  124713. NULL,
  124714. 0
  124715. };
  124716. static long _vq_quantlist__44c3_s_p8_1[] = {
  124717. 2,
  124718. 1,
  124719. 3,
  124720. 0,
  124721. 4,
  124722. };
  124723. static long _vq_lengthlist__44c3_s_p8_1[] = {
  124724. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  124725. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  124726. };
  124727. static float _vq_quantthresh__44c3_s_p8_1[] = {
  124728. -1.5, -0.5, 0.5, 1.5,
  124729. };
  124730. static long _vq_quantmap__44c3_s_p8_1[] = {
  124731. 3, 1, 0, 2, 4,
  124732. };
  124733. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  124734. _vq_quantthresh__44c3_s_p8_1,
  124735. _vq_quantmap__44c3_s_p8_1,
  124736. 5,
  124737. 5
  124738. };
  124739. static static_codebook _44c3_s_p8_1 = {
  124740. 2, 25,
  124741. _vq_lengthlist__44c3_s_p8_1,
  124742. 1, -533725184, 1611661312, 3, 0,
  124743. _vq_quantlist__44c3_s_p8_1,
  124744. NULL,
  124745. &_vq_auxt__44c3_s_p8_1,
  124746. NULL,
  124747. 0
  124748. };
  124749. static long _vq_quantlist__44c3_s_p9_0[] = {
  124750. 6,
  124751. 5,
  124752. 7,
  124753. 4,
  124754. 8,
  124755. 3,
  124756. 9,
  124757. 2,
  124758. 10,
  124759. 1,
  124760. 11,
  124761. 0,
  124762. 12,
  124763. };
  124764. static long _vq_lengthlist__44c3_s_p9_0[] = {
  124765. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  124766. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  124767. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124768. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  124769. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124770. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124771. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124772. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124773. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  124774. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124775. 11,11,11,11,11,11,11,11,11,
  124776. };
  124777. static float _vq_quantthresh__44c3_s_p9_0[] = {
  124778. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  124779. 637.5, 892.5, 1147.5, 1402.5,
  124780. };
  124781. static long _vq_quantmap__44c3_s_p9_0[] = {
  124782. 11, 9, 7, 5, 3, 1, 0, 2,
  124783. 4, 6, 8, 10, 12,
  124784. };
  124785. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  124786. _vq_quantthresh__44c3_s_p9_0,
  124787. _vq_quantmap__44c3_s_p9_0,
  124788. 13,
  124789. 13
  124790. };
  124791. static static_codebook _44c3_s_p9_0 = {
  124792. 2, 169,
  124793. _vq_lengthlist__44c3_s_p9_0,
  124794. 1, -514332672, 1627381760, 4, 0,
  124795. _vq_quantlist__44c3_s_p9_0,
  124796. NULL,
  124797. &_vq_auxt__44c3_s_p9_0,
  124798. NULL,
  124799. 0
  124800. };
  124801. static long _vq_quantlist__44c3_s_p9_1[] = {
  124802. 7,
  124803. 6,
  124804. 8,
  124805. 5,
  124806. 9,
  124807. 4,
  124808. 10,
  124809. 3,
  124810. 11,
  124811. 2,
  124812. 12,
  124813. 1,
  124814. 13,
  124815. 0,
  124816. 14,
  124817. };
  124818. static long _vq_lengthlist__44c3_s_p9_1[] = {
  124819. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  124820. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  124821. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  124822. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  124823. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  124824. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  124825. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  124826. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  124827. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  124828. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  124829. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  124830. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  124831. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  124832. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  124833. 15,
  124834. };
  124835. static float _vq_quantthresh__44c3_s_p9_1[] = {
  124836. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  124837. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  124838. };
  124839. static long _vq_quantmap__44c3_s_p9_1[] = {
  124840. 13, 11, 9, 7, 5, 3, 1, 0,
  124841. 2, 4, 6, 8, 10, 12, 14,
  124842. };
  124843. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  124844. _vq_quantthresh__44c3_s_p9_1,
  124845. _vq_quantmap__44c3_s_p9_1,
  124846. 15,
  124847. 15
  124848. };
  124849. static static_codebook _44c3_s_p9_1 = {
  124850. 2, 225,
  124851. _vq_lengthlist__44c3_s_p9_1,
  124852. 1, -522338304, 1620115456, 4, 0,
  124853. _vq_quantlist__44c3_s_p9_1,
  124854. NULL,
  124855. &_vq_auxt__44c3_s_p9_1,
  124856. NULL,
  124857. 0
  124858. };
  124859. static long _vq_quantlist__44c3_s_p9_2[] = {
  124860. 8,
  124861. 7,
  124862. 9,
  124863. 6,
  124864. 10,
  124865. 5,
  124866. 11,
  124867. 4,
  124868. 12,
  124869. 3,
  124870. 13,
  124871. 2,
  124872. 14,
  124873. 1,
  124874. 15,
  124875. 0,
  124876. 16,
  124877. };
  124878. static long _vq_lengthlist__44c3_s_p9_2[] = {
  124879. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  124880. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  124881. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  124882. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  124883. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  124884. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  124885. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  124886. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  124887. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  124888. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  124889. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  124890. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  124891. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  124892. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  124893. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  124894. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  124895. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  124896. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  124897. 10,
  124898. };
  124899. static float _vq_quantthresh__44c3_s_p9_2[] = {
  124900. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124901. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124902. };
  124903. static long _vq_quantmap__44c3_s_p9_2[] = {
  124904. 15, 13, 11, 9, 7, 5, 3, 1,
  124905. 0, 2, 4, 6, 8, 10, 12, 14,
  124906. 16,
  124907. };
  124908. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  124909. _vq_quantthresh__44c3_s_p9_2,
  124910. _vq_quantmap__44c3_s_p9_2,
  124911. 17,
  124912. 17
  124913. };
  124914. static static_codebook _44c3_s_p9_2 = {
  124915. 2, 289,
  124916. _vq_lengthlist__44c3_s_p9_2,
  124917. 1, -529530880, 1611661312, 5, 0,
  124918. _vq_quantlist__44c3_s_p9_2,
  124919. NULL,
  124920. &_vq_auxt__44c3_s_p9_2,
  124921. NULL,
  124922. 0
  124923. };
  124924. static long _huff_lengthlist__44c3_s_short[] = {
  124925. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  124926. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  124927. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  124928. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  124929. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  124930. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  124931. 6, 8, 9,11,
  124932. };
  124933. static static_codebook _huff_book__44c3_s_short = {
  124934. 2, 100,
  124935. _huff_lengthlist__44c3_s_short,
  124936. 0, 0, 0, 0, 0,
  124937. NULL,
  124938. NULL,
  124939. NULL,
  124940. NULL,
  124941. 0
  124942. };
  124943. static long _huff_lengthlist__44c4_s_long[] = {
  124944. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  124945. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  124946. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  124947. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  124948. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  124949. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  124950. 9, 8, 7, 7,
  124951. };
  124952. static static_codebook _huff_book__44c4_s_long = {
  124953. 2, 100,
  124954. _huff_lengthlist__44c4_s_long,
  124955. 0, 0, 0, 0, 0,
  124956. NULL,
  124957. NULL,
  124958. NULL,
  124959. NULL,
  124960. 0
  124961. };
  124962. static long _vq_quantlist__44c4_s_p1_0[] = {
  124963. 1,
  124964. 0,
  124965. 2,
  124966. };
  124967. static long _vq_lengthlist__44c4_s_p1_0[] = {
  124968. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  124969. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124973. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124974. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124978. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  124979. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125014. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  125015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  125019. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  125020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  125024. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125059. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  125060. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125064. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  125065. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  125066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125069. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125070. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  125071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125280. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125285. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125290. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  125325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  125330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  125335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125378. 0,
  125379. };
  125380. static float _vq_quantthresh__44c4_s_p1_0[] = {
  125381. -0.5, 0.5,
  125382. };
  125383. static long _vq_quantmap__44c4_s_p1_0[] = {
  125384. 1, 0, 2,
  125385. };
  125386. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  125387. _vq_quantthresh__44c4_s_p1_0,
  125388. _vq_quantmap__44c4_s_p1_0,
  125389. 3,
  125390. 3
  125391. };
  125392. static static_codebook _44c4_s_p1_0 = {
  125393. 8, 6561,
  125394. _vq_lengthlist__44c4_s_p1_0,
  125395. 1, -535822336, 1611661312, 2, 0,
  125396. _vq_quantlist__44c4_s_p1_0,
  125397. NULL,
  125398. &_vq_auxt__44c4_s_p1_0,
  125399. NULL,
  125400. 0
  125401. };
  125402. static long _vq_quantlist__44c4_s_p2_0[] = {
  125403. 2,
  125404. 1,
  125405. 3,
  125406. 0,
  125407. 4,
  125408. };
  125409. static long _vq_lengthlist__44c4_s_p2_0[] = {
  125410. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  125411. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  125412. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125413. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  125414. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  125420. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  125421. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  125422. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  125428. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  125429. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  125436. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  125437. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  125450. };
  125451. static float _vq_quantthresh__44c4_s_p2_0[] = {
  125452. -1.5, -0.5, 0.5, 1.5,
  125453. };
  125454. static long _vq_quantmap__44c4_s_p2_0[] = {
  125455. 3, 1, 0, 2, 4,
  125456. };
  125457. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  125458. _vq_quantthresh__44c4_s_p2_0,
  125459. _vq_quantmap__44c4_s_p2_0,
  125460. 5,
  125461. 5
  125462. };
  125463. static static_codebook _44c4_s_p2_0 = {
  125464. 4, 625,
  125465. _vq_lengthlist__44c4_s_p2_0,
  125466. 1, -533725184, 1611661312, 3, 0,
  125467. _vq_quantlist__44c4_s_p2_0,
  125468. NULL,
  125469. &_vq_auxt__44c4_s_p2_0,
  125470. NULL,
  125471. 0
  125472. };
  125473. static long _vq_quantlist__44c4_s_p3_0[] = {
  125474. 2,
  125475. 1,
  125476. 3,
  125477. 0,
  125478. 4,
  125479. };
  125480. static long _vq_lengthlist__44c4_s_p3_0[] = {
  125481. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  125483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125484. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  125486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125487. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  125521. };
  125522. static float _vq_quantthresh__44c4_s_p3_0[] = {
  125523. -1.5, -0.5, 0.5, 1.5,
  125524. };
  125525. static long _vq_quantmap__44c4_s_p3_0[] = {
  125526. 3, 1, 0, 2, 4,
  125527. };
  125528. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  125529. _vq_quantthresh__44c4_s_p3_0,
  125530. _vq_quantmap__44c4_s_p3_0,
  125531. 5,
  125532. 5
  125533. };
  125534. static static_codebook _44c4_s_p3_0 = {
  125535. 4, 625,
  125536. _vq_lengthlist__44c4_s_p3_0,
  125537. 1, -533725184, 1611661312, 3, 0,
  125538. _vq_quantlist__44c4_s_p3_0,
  125539. NULL,
  125540. &_vq_auxt__44c4_s_p3_0,
  125541. NULL,
  125542. 0
  125543. };
  125544. static long _vq_quantlist__44c4_s_p4_0[] = {
  125545. 4,
  125546. 3,
  125547. 5,
  125548. 2,
  125549. 6,
  125550. 1,
  125551. 7,
  125552. 0,
  125553. 8,
  125554. };
  125555. static long _vq_lengthlist__44c4_s_p4_0[] = {
  125556. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  125557. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  125558. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  125559. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  125560. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125561. 0,
  125562. };
  125563. static float _vq_quantthresh__44c4_s_p4_0[] = {
  125564. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125565. };
  125566. static long _vq_quantmap__44c4_s_p4_0[] = {
  125567. 7, 5, 3, 1, 0, 2, 4, 6,
  125568. 8,
  125569. };
  125570. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  125571. _vq_quantthresh__44c4_s_p4_0,
  125572. _vq_quantmap__44c4_s_p4_0,
  125573. 9,
  125574. 9
  125575. };
  125576. static static_codebook _44c4_s_p4_0 = {
  125577. 2, 81,
  125578. _vq_lengthlist__44c4_s_p4_0,
  125579. 1, -531628032, 1611661312, 4, 0,
  125580. _vq_quantlist__44c4_s_p4_0,
  125581. NULL,
  125582. &_vq_auxt__44c4_s_p4_0,
  125583. NULL,
  125584. 0
  125585. };
  125586. static long _vq_quantlist__44c4_s_p5_0[] = {
  125587. 4,
  125588. 3,
  125589. 5,
  125590. 2,
  125591. 6,
  125592. 1,
  125593. 7,
  125594. 0,
  125595. 8,
  125596. };
  125597. static long _vq_lengthlist__44c4_s_p5_0[] = {
  125598. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  125599. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  125600. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  125601. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  125602. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  125603. 10,
  125604. };
  125605. static float _vq_quantthresh__44c4_s_p5_0[] = {
  125606. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125607. };
  125608. static long _vq_quantmap__44c4_s_p5_0[] = {
  125609. 7, 5, 3, 1, 0, 2, 4, 6,
  125610. 8,
  125611. };
  125612. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  125613. _vq_quantthresh__44c4_s_p5_0,
  125614. _vq_quantmap__44c4_s_p5_0,
  125615. 9,
  125616. 9
  125617. };
  125618. static static_codebook _44c4_s_p5_0 = {
  125619. 2, 81,
  125620. _vq_lengthlist__44c4_s_p5_0,
  125621. 1, -531628032, 1611661312, 4, 0,
  125622. _vq_quantlist__44c4_s_p5_0,
  125623. NULL,
  125624. &_vq_auxt__44c4_s_p5_0,
  125625. NULL,
  125626. 0
  125627. };
  125628. static long _vq_quantlist__44c4_s_p6_0[] = {
  125629. 8,
  125630. 7,
  125631. 9,
  125632. 6,
  125633. 10,
  125634. 5,
  125635. 11,
  125636. 4,
  125637. 12,
  125638. 3,
  125639. 13,
  125640. 2,
  125641. 14,
  125642. 1,
  125643. 15,
  125644. 0,
  125645. 16,
  125646. };
  125647. static long _vq_lengthlist__44c4_s_p6_0[] = {
  125648. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  125649. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125650. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  125651. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  125652. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  125653. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125654. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  125655. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  125656. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  125657. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  125658. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  125659. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  125660. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  125661. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  125662. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  125663. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  125664. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  125665. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  125666. 13,
  125667. };
  125668. static float _vq_quantthresh__44c4_s_p6_0[] = {
  125669. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125670. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125671. };
  125672. static long _vq_quantmap__44c4_s_p6_0[] = {
  125673. 15, 13, 11, 9, 7, 5, 3, 1,
  125674. 0, 2, 4, 6, 8, 10, 12, 14,
  125675. 16,
  125676. };
  125677. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  125678. _vq_quantthresh__44c4_s_p6_0,
  125679. _vq_quantmap__44c4_s_p6_0,
  125680. 17,
  125681. 17
  125682. };
  125683. static static_codebook _44c4_s_p6_0 = {
  125684. 2, 289,
  125685. _vq_lengthlist__44c4_s_p6_0,
  125686. 1, -529530880, 1611661312, 5, 0,
  125687. _vq_quantlist__44c4_s_p6_0,
  125688. NULL,
  125689. &_vq_auxt__44c4_s_p6_0,
  125690. NULL,
  125691. 0
  125692. };
  125693. static long _vq_quantlist__44c4_s_p7_0[] = {
  125694. 1,
  125695. 0,
  125696. 2,
  125697. };
  125698. static long _vq_lengthlist__44c4_s_p7_0[] = {
  125699. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  125700. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  125701. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  125702. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  125703. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  125704. 10,
  125705. };
  125706. static float _vq_quantthresh__44c4_s_p7_0[] = {
  125707. -5.5, 5.5,
  125708. };
  125709. static long _vq_quantmap__44c4_s_p7_0[] = {
  125710. 1, 0, 2,
  125711. };
  125712. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  125713. _vq_quantthresh__44c4_s_p7_0,
  125714. _vq_quantmap__44c4_s_p7_0,
  125715. 3,
  125716. 3
  125717. };
  125718. static static_codebook _44c4_s_p7_0 = {
  125719. 4, 81,
  125720. _vq_lengthlist__44c4_s_p7_0,
  125721. 1, -529137664, 1618345984, 2, 0,
  125722. _vq_quantlist__44c4_s_p7_0,
  125723. NULL,
  125724. &_vq_auxt__44c4_s_p7_0,
  125725. NULL,
  125726. 0
  125727. };
  125728. static long _vq_quantlist__44c4_s_p7_1[] = {
  125729. 5,
  125730. 4,
  125731. 6,
  125732. 3,
  125733. 7,
  125734. 2,
  125735. 8,
  125736. 1,
  125737. 9,
  125738. 0,
  125739. 10,
  125740. };
  125741. static long _vq_lengthlist__44c4_s_p7_1[] = {
  125742. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  125743. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  125744. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  125745. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  125746. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  125747. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  125748. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  125749. 10,10,10, 8, 8, 8, 8, 9, 9,
  125750. };
  125751. static float _vq_quantthresh__44c4_s_p7_1[] = {
  125752. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125753. 3.5, 4.5,
  125754. };
  125755. static long _vq_quantmap__44c4_s_p7_1[] = {
  125756. 9, 7, 5, 3, 1, 0, 2, 4,
  125757. 6, 8, 10,
  125758. };
  125759. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  125760. _vq_quantthresh__44c4_s_p7_1,
  125761. _vq_quantmap__44c4_s_p7_1,
  125762. 11,
  125763. 11
  125764. };
  125765. static static_codebook _44c4_s_p7_1 = {
  125766. 2, 121,
  125767. _vq_lengthlist__44c4_s_p7_1,
  125768. 1, -531365888, 1611661312, 4, 0,
  125769. _vq_quantlist__44c4_s_p7_1,
  125770. NULL,
  125771. &_vq_auxt__44c4_s_p7_1,
  125772. NULL,
  125773. 0
  125774. };
  125775. static long _vq_quantlist__44c4_s_p8_0[] = {
  125776. 6,
  125777. 5,
  125778. 7,
  125779. 4,
  125780. 8,
  125781. 3,
  125782. 9,
  125783. 2,
  125784. 10,
  125785. 1,
  125786. 11,
  125787. 0,
  125788. 12,
  125789. };
  125790. static long _vq_lengthlist__44c4_s_p8_0[] = {
  125791. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  125792. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  125793. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125794. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  125795. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  125796. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  125797. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  125798. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  125799. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  125800. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  125801. 0,13,12,12,12,12,12,13,13,
  125802. };
  125803. static float _vq_quantthresh__44c4_s_p8_0[] = {
  125804. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125805. 12.5, 17.5, 22.5, 27.5,
  125806. };
  125807. static long _vq_quantmap__44c4_s_p8_0[] = {
  125808. 11, 9, 7, 5, 3, 1, 0, 2,
  125809. 4, 6, 8, 10, 12,
  125810. };
  125811. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  125812. _vq_quantthresh__44c4_s_p8_0,
  125813. _vq_quantmap__44c4_s_p8_0,
  125814. 13,
  125815. 13
  125816. };
  125817. static static_codebook _44c4_s_p8_0 = {
  125818. 2, 169,
  125819. _vq_lengthlist__44c4_s_p8_0,
  125820. 1, -526516224, 1616117760, 4, 0,
  125821. _vq_quantlist__44c4_s_p8_0,
  125822. NULL,
  125823. &_vq_auxt__44c4_s_p8_0,
  125824. NULL,
  125825. 0
  125826. };
  125827. static long _vq_quantlist__44c4_s_p8_1[] = {
  125828. 2,
  125829. 1,
  125830. 3,
  125831. 0,
  125832. 4,
  125833. };
  125834. static long _vq_lengthlist__44c4_s_p8_1[] = {
  125835. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  125836. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  125837. };
  125838. static float _vq_quantthresh__44c4_s_p8_1[] = {
  125839. -1.5, -0.5, 0.5, 1.5,
  125840. };
  125841. static long _vq_quantmap__44c4_s_p8_1[] = {
  125842. 3, 1, 0, 2, 4,
  125843. };
  125844. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  125845. _vq_quantthresh__44c4_s_p8_1,
  125846. _vq_quantmap__44c4_s_p8_1,
  125847. 5,
  125848. 5
  125849. };
  125850. static static_codebook _44c4_s_p8_1 = {
  125851. 2, 25,
  125852. _vq_lengthlist__44c4_s_p8_1,
  125853. 1, -533725184, 1611661312, 3, 0,
  125854. _vq_quantlist__44c4_s_p8_1,
  125855. NULL,
  125856. &_vq_auxt__44c4_s_p8_1,
  125857. NULL,
  125858. 0
  125859. };
  125860. static long _vq_quantlist__44c4_s_p9_0[] = {
  125861. 6,
  125862. 5,
  125863. 7,
  125864. 4,
  125865. 8,
  125866. 3,
  125867. 9,
  125868. 2,
  125869. 10,
  125870. 1,
  125871. 11,
  125872. 0,
  125873. 12,
  125874. };
  125875. static long _vq_lengthlist__44c4_s_p9_0[] = {
  125876. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  125877. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  125878. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125879. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125880. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125881. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125882. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125883. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125884. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125885. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125886. 12,12,12,12,12,12,12,12,12,
  125887. };
  125888. static float _vq_quantthresh__44c4_s_p9_0[] = {
  125889. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  125890. 787.5, 1102.5, 1417.5, 1732.5,
  125891. };
  125892. static long _vq_quantmap__44c4_s_p9_0[] = {
  125893. 11, 9, 7, 5, 3, 1, 0, 2,
  125894. 4, 6, 8, 10, 12,
  125895. };
  125896. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  125897. _vq_quantthresh__44c4_s_p9_0,
  125898. _vq_quantmap__44c4_s_p9_0,
  125899. 13,
  125900. 13
  125901. };
  125902. static static_codebook _44c4_s_p9_0 = {
  125903. 2, 169,
  125904. _vq_lengthlist__44c4_s_p9_0,
  125905. 1, -513964032, 1628680192, 4, 0,
  125906. _vq_quantlist__44c4_s_p9_0,
  125907. NULL,
  125908. &_vq_auxt__44c4_s_p9_0,
  125909. NULL,
  125910. 0
  125911. };
  125912. static long _vq_quantlist__44c4_s_p9_1[] = {
  125913. 7,
  125914. 6,
  125915. 8,
  125916. 5,
  125917. 9,
  125918. 4,
  125919. 10,
  125920. 3,
  125921. 11,
  125922. 2,
  125923. 12,
  125924. 1,
  125925. 13,
  125926. 0,
  125927. 14,
  125928. };
  125929. static long _vq_lengthlist__44c4_s_p9_1[] = {
  125930. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  125931. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  125932. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  125933. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  125934. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  125935. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  125936. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  125937. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  125938. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  125939. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  125940. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  125941. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  125942. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  125943. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  125944. 15,
  125945. };
  125946. static float _vq_quantthresh__44c4_s_p9_1[] = {
  125947. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125948. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125949. };
  125950. static long _vq_quantmap__44c4_s_p9_1[] = {
  125951. 13, 11, 9, 7, 5, 3, 1, 0,
  125952. 2, 4, 6, 8, 10, 12, 14,
  125953. };
  125954. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  125955. _vq_quantthresh__44c4_s_p9_1,
  125956. _vq_quantmap__44c4_s_p9_1,
  125957. 15,
  125958. 15
  125959. };
  125960. static static_codebook _44c4_s_p9_1 = {
  125961. 2, 225,
  125962. _vq_lengthlist__44c4_s_p9_1,
  125963. 1, -520986624, 1620377600, 4, 0,
  125964. _vq_quantlist__44c4_s_p9_1,
  125965. NULL,
  125966. &_vq_auxt__44c4_s_p9_1,
  125967. NULL,
  125968. 0
  125969. };
  125970. static long _vq_quantlist__44c4_s_p9_2[] = {
  125971. 10,
  125972. 9,
  125973. 11,
  125974. 8,
  125975. 12,
  125976. 7,
  125977. 13,
  125978. 6,
  125979. 14,
  125980. 5,
  125981. 15,
  125982. 4,
  125983. 16,
  125984. 3,
  125985. 17,
  125986. 2,
  125987. 18,
  125988. 1,
  125989. 19,
  125990. 0,
  125991. 20,
  125992. };
  125993. static long _vq_lengthlist__44c4_s_p9_2[] = {
  125994. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  125995. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  125996. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  125997. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  125998. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  125999. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  126000. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  126001. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  126002. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  126003. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  126004. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  126005. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  126006. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  126007. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  126008. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  126009. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  126010. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  126011. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  126012. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  126013. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  126014. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126015. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  126016. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  126017. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  126018. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  126019. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  126020. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  126021. 10,10,10,10,10,10,10,10,10,
  126022. };
  126023. static float _vq_quantthresh__44c4_s_p9_2[] = {
  126024. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126025. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126026. 6.5, 7.5, 8.5, 9.5,
  126027. };
  126028. static long _vq_quantmap__44c4_s_p9_2[] = {
  126029. 19, 17, 15, 13, 11, 9, 7, 5,
  126030. 3, 1, 0, 2, 4, 6, 8, 10,
  126031. 12, 14, 16, 18, 20,
  126032. };
  126033. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  126034. _vq_quantthresh__44c4_s_p9_2,
  126035. _vq_quantmap__44c4_s_p9_2,
  126036. 21,
  126037. 21
  126038. };
  126039. static static_codebook _44c4_s_p9_2 = {
  126040. 2, 441,
  126041. _vq_lengthlist__44c4_s_p9_2,
  126042. 1, -529268736, 1611661312, 5, 0,
  126043. _vq_quantlist__44c4_s_p9_2,
  126044. NULL,
  126045. &_vq_auxt__44c4_s_p9_2,
  126046. NULL,
  126047. 0
  126048. };
  126049. static long _huff_lengthlist__44c4_s_short[] = {
  126050. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  126051. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  126052. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  126053. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  126054. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  126055. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  126056. 7, 9,12,17,
  126057. };
  126058. static static_codebook _huff_book__44c4_s_short = {
  126059. 2, 100,
  126060. _huff_lengthlist__44c4_s_short,
  126061. 0, 0, 0, 0, 0,
  126062. NULL,
  126063. NULL,
  126064. NULL,
  126065. NULL,
  126066. 0
  126067. };
  126068. static long _huff_lengthlist__44c5_s_long[] = {
  126069. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  126070. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  126071. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  126072. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  126073. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  126074. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  126075. 9, 8, 7, 7,
  126076. };
  126077. static static_codebook _huff_book__44c5_s_long = {
  126078. 2, 100,
  126079. _huff_lengthlist__44c5_s_long,
  126080. 0, 0, 0, 0, 0,
  126081. NULL,
  126082. NULL,
  126083. NULL,
  126084. NULL,
  126085. 0
  126086. };
  126087. static long _vq_quantlist__44c5_s_p1_0[] = {
  126088. 1,
  126089. 0,
  126090. 2,
  126091. };
  126092. static long _vq_lengthlist__44c5_s_p1_0[] = {
  126093. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  126094. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126099. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126104. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  126139. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126144. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126149. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126185. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  126190. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126195. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126369. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126374. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126379. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  126414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  126419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  126424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  126504. };
  126505. static float _vq_quantthresh__44c5_s_p1_0[] = {
  126506. -0.5, 0.5,
  126507. };
  126508. static long _vq_quantmap__44c5_s_p1_0[] = {
  126509. 1, 0, 2,
  126510. };
  126511. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  126512. _vq_quantthresh__44c5_s_p1_0,
  126513. _vq_quantmap__44c5_s_p1_0,
  126514. 3,
  126515. 3
  126516. };
  126517. static static_codebook _44c5_s_p1_0 = {
  126518. 8, 6561,
  126519. _vq_lengthlist__44c5_s_p1_0,
  126520. 1, -535822336, 1611661312, 2, 0,
  126521. _vq_quantlist__44c5_s_p1_0,
  126522. NULL,
  126523. &_vq_auxt__44c5_s_p1_0,
  126524. NULL,
  126525. 0
  126526. };
  126527. static long _vq_quantlist__44c5_s_p2_0[] = {
  126528. 2,
  126529. 1,
  126530. 3,
  126531. 0,
  126532. 4,
  126533. };
  126534. static long _vq_lengthlist__44c5_s_p2_0[] = {
  126535. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  126536. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  126537. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  126538. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  126539. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  126545. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  126546. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  126547. 10, 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, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  126553. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  126554. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 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. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  126561. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  126562. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 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,
  126575. };
  126576. static float _vq_quantthresh__44c5_s_p2_0[] = {
  126577. -1.5, -0.5, 0.5, 1.5,
  126578. };
  126579. static long _vq_quantmap__44c5_s_p2_0[] = {
  126580. 3, 1, 0, 2, 4,
  126581. };
  126582. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  126583. _vq_quantthresh__44c5_s_p2_0,
  126584. _vq_quantmap__44c5_s_p2_0,
  126585. 5,
  126586. 5
  126587. };
  126588. static static_codebook _44c5_s_p2_0 = {
  126589. 4, 625,
  126590. _vq_lengthlist__44c5_s_p2_0,
  126591. 1, -533725184, 1611661312, 3, 0,
  126592. _vq_quantlist__44c5_s_p2_0,
  126593. NULL,
  126594. &_vq_auxt__44c5_s_p2_0,
  126595. NULL,
  126596. 0
  126597. };
  126598. static long _vq_quantlist__44c5_s_p3_0[] = {
  126599. 2,
  126600. 1,
  126601. 3,
  126602. 0,
  126603. 4,
  126604. };
  126605. static long _vq_lengthlist__44c5_s_p3_0[] = {
  126606. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  126608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126609. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  126611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126612. 0, 0, 0, 0, 5, 6, 6, 8, 8, 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,
  126646. };
  126647. static float _vq_quantthresh__44c5_s_p3_0[] = {
  126648. -1.5, -0.5, 0.5, 1.5,
  126649. };
  126650. static long _vq_quantmap__44c5_s_p3_0[] = {
  126651. 3, 1, 0, 2, 4,
  126652. };
  126653. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  126654. _vq_quantthresh__44c5_s_p3_0,
  126655. _vq_quantmap__44c5_s_p3_0,
  126656. 5,
  126657. 5
  126658. };
  126659. static static_codebook _44c5_s_p3_0 = {
  126660. 4, 625,
  126661. _vq_lengthlist__44c5_s_p3_0,
  126662. 1, -533725184, 1611661312, 3, 0,
  126663. _vq_quantlist__44c5_s_p3_0,
  126664. NULL,
  126665. &_vq_auxt__44c5_s_p3_0,
  126666. NULL,
  126667. 0
  126668. };
  126669. static long _vq_quantlist__44c5_s_p4_0[] = {
  126670. 4,
  126671. 3,
  126672. 5,
  126673. 2,
  126674. 6,
  126675. 1,
  126676. 7,
  126677. 0,
  126678. 8,
  126679. };
  126680. static long _vq_lengthlist__44c5_s_p4_0[] = {
  126681. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  126682. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  126683. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  126684. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  126685. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126686. 0,
  126687. };
  126688. static float _vq_quantthresh__44c5_s_p4_0[] = {
  126689. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126690. };
  126691. static long _vq_quantmap__44c5_s_p4_0[] = {
  126692. 7, 5, 3, 1, 0, 2, 4, 6,
  126693. 8,
  126694. };
  126695. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  126696. _vq_quantthresh__44c5_s_p4_0,
  126697. _vq_quantmap__44c5_s_p4_0,
  126698. 9,
  126699. 9
  126700. };
  126701. static static_codebook _44c5_s_p4_0 = {
  126702. 2, 81,
  126703. _vq_lengthlist__44c5_s_p4_0,
  126704. 1, -531628032, 1611661312, 4, 0,
  126705. _vq_quantlist__44c5_s_p4_0,
  126706. NULL,
  126707. &_vq_auxt__44c5_s_p4_0,
  126708. NULL,
  126709. 0
  126710. };
  126711. static long _vq_quantlist__44c5_s_p5_0[] = {
  126712. 4,
  126713. 3,
  126714. 5,
  126715. 2,
  126716. 6,
  126717. 1,
  126718. 7,
  126719. 0,
  126720. 8,
  126721. };
  126722. static long _vq_lengthlist__44c5_s_p5_0[] = {
  126723. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  126724. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  126725. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  126726. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  126727. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126728. 10,
  126729. };
  126730. static float _vq_quantthresh__44c5_s_p5_0[] = {
  126731. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126732. };
  126733. static long _vq_quantmap__44c5_s_p5_0[] = {
  126734. 7, 5, 3, 1, 0, 2, 4, 6,
  126735. 8,
  126736. };
  126737. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  126738. _vq_quantthresh__44c5_s_p5_0,
  126739. _vq_quantmap__44c5_s_p5_0,
  126740. 9,
  126741. 9
  126742. };
  126743. static static_codebook _44c5_s_p5_0 = {
  126744. 2, 81,
  126745. _vq_lengthlist__44c5_s_p5_0,
  126746. 1, -531628032, 1611661312, 4, 0,
  126747. _vq_quantlist__44c5_s_p5_0,
  126748. NULL,
  126749. &_vq_auxt__44c5_s_p5_0,
  126750. NULL,
  126751. 0
  126752. };
  126753. static long _vq_quantlist__44c5_s_p6_0[] = {
  126754. 8,
  126755. 7,
  126756. 9,
  126757. 6,
  126758. 10,
  126759. 5,
  126760. 11,
  126761. 4,
  126762. 12,
  126763. 3,
  126764. 13,
  126765. 2,
  126766. 14,
  126767. 1,
  126768. 15,
  126769. 0,
  126770. 16,
  126771. };
  126772. static long _vq_lengthlist__44c5_s_p6_0[] = {
  126773. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  126774. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126775. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  126776. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  126777. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  126778. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  126779. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  126780. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  126781. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  126782. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  126783. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  126784. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  126785. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  126786. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  126787. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  126788. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  126789. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  126790. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  126791. 13,
  126792. };
  126793. static float _vq_quantthresh__44c5_s_p6_0[] = {
  126794. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126795. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126796. };
  126797. static long _vq_quantmap__44c5_s_p6_0[] = {
  126798. 15, 13, 11, 9, 7, 5, 3, 1,
  126799. 0, 2, 4, 6, 8, 10, 12, 14,
  126800. 16,
  126801. };
  126802. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  126803. _vq_quantthresh__44c5_s_p6_0,
  126804. _vq_quantmap__44c5_s_p6_0,
  126805. 17,
  126806. 17
  126807. };
  126808. static static_codebook _44c5_s_p6_0 = {
  126809. 2, 289,
  126810. _vq_lengthlist__44c5_s_p6_0,
  126811. 1, -529530880, 1611661312, 5, 0,
  126812. _vq_quantlist__44c5_s_p6_0,
  126813. NULL,
  126814. &_vq_auxt__44c5_s_p6_0,
  126815. NULL,
  126816. 0
  126817. };
  126818. static long _vq_quantlist__44c5_s_p7_0[] = {
  126819. 1,
  126820. 0,
  126821. 2,
  126822. };
  126823. static long _vq_lengthlist__44c5_s_p7_0[] = {
  126824. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  126825. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  126826. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  126827. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  126828. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  126829. 10,
  126830. };
  126831. static float _vq_quantthresh__44c5_s_p7_0[] = {
  126832. -5.5, 5.5,
  126833. };
  126834. static long _vq_quantmap__44c5_s_p7_0[] = {
  126835. 1, 0, 2,
  126836. };
  126837. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  126838. _vq_quantthresh__44c5_s_p7_0,
  126839. _vq_quantmap__44c5_s_p7_0,
  126840. 3,
  126841. 3
  126842. };
  126843. static static_codebook _44c5_s_p7_0 = {
  126844. 4, 81,
  126845. _vq_lengthlist__44c5_s_p7_0,
  126846. 1, -529137664, 1618345984, 2, 0,
  126847. _vq_quantlist__44c5_s_p7_0,
  126848. NULL,
  126849. &_vq_auxt__44c5_s_p7_0,
  126850. NULL,
  126851. 0
  126852. };
  126853. static long _vq_quantlist__44c5_s_p7_1[] = {
  126854. 5,
  126855. 4,
  126856. 6,
  126857. 3,
  126858. 7,
  126859. 2,
  126860. 8,
  126861. 1,
  126862. 9,
  126863. 0,
  126864. 10,
  126865. };
  126866. static long _vq_lengthlist__44c5_s_p7_1[] = {
  126867. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  126868. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  126869. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  126870. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  126871. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  126872. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  126873. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  126874. 10,10,10, 8, 8, 8, 8, 8, 8,
  126875. };
  126876. static float _vq_quantthresh__44c5_s_p7_1[] = {
  126877. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126878. 3.5, 4.5,
  126879. };
  126880. static long _vq_quantmap__44c5_s_p7_1[] = {
  126881. 9, 7, 5, 3, 1, 0, 2, 4,
  126882. 6, 8, 10,
  126883. };
  126884. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  126885. _vq_quantthresh__44c5_s_p7_1,
  126886. _vq_quantmap__44c5_s_p7_1,
  126887. 11,
  126888. 11
  126889. };
  126890. static static_codebook _44c5_s_p7_1 = {
  126891. 2, 121,
  126892. _vq_lengthlist__44c5_s_p7_1,
  126893. 1, -531365888, 1611661312, 4, 0,
  126894. _vq_quantlist__44c5_s_p7_1,
  126895. NULL,
  126896. &_vq_auxt__44c5_s_p7_1,
  126897. NULL,
  126898. 0
  126899. };
  126900. static long _vq_quantlist__44c5_s_p8_0[] = {
  126901. 6,
  126902. 5,
  126903. 7,
  126904. 4,
  126905. 8,
  126906. 3,
  126907. 9,
  126908. 2,
  126909. 10,
  126910. 1,
  126911. 11,
  126912. 0,
  126913. 12,
  126914. };
  126915. static long _vq_lengthlist__44c5_s_p8_0[] = {
  126916. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  126917. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  126918. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126919. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126920. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  126921. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  126922. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  126923. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  126924. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  126925. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  126926. 0,12,12,12,12,12,12,13,13,
  126927. };
  126928. static float _vq_quantthresh__44c5_s_p8_0[] = {
  126929. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126930. 12.5, 17.5, 22.5, 27.5,
  126931. };
  126932. static long _vq_quantmap__44c5_s_p8_0[] = {
  126933. 11, 9, 7, 5, 3, 1, 0, 2,
  126934. 4, 6, 8, 10, 12,
  126935. };
  126936. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  126937. _vq_quantthresh__44c5_s_p8_0,
  126938. _vq_quantmap__44c5_s_p8_0,
  126939. 13,
  126940. 13
  126941. };
  126942. static static_codebook _44c5_s_p8_0 = {
  126943. 2, 169,
  126944. _vq_lengthlist__44c5_s_p8_0,
  126945. 1, -526516224, 1616117760, 4, 0,
  126946. _vq_quantlist__44c5_s_p8_0,
  126947. NULL,
  126948. &_vq_auxt__44c5_s_p8_0,
  126949. NULL,
  126950. 0
  126951. };
  126952. static long _vq_quantlist__44c5_s_p8_1[] = {
  126953. 2,
  126954. 1,
  126955. 3,
  126956. 0,
  126957. 4,
  126958. };
  126959. static long _vq_lengthlist__44c5_s_p8_1[] = {
  126960. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  126961. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126962. };
  126963. static float _vq_quantthresh__44c5_s_p8_1[] = {
  126964. -1.5, -0.5, 0.5, 1.5,
  126965. };
  126966. static long _vq_quantmap__44c5_s_p8_1[] = {
  126967. 3, 1, 0, 2, 4,
  126968. };
  126969. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  126970. _vq_quantthresh__44c5_s_p8_1,
  126971. _vq_quantmap__44c5_s_p8_1,
  126972. 5,
  126973. 5
  126974. };
  126975. static static_codebook _44c5_s_p8_1 = {
  126976. 2, 25,
  126977. _vq_lengthlist__44c5_s_p8_1,
  126978. 1, -533725184, 1611661312, 3, 0,
  126979. _vq_quantlist__44c5_s_p8_1,
  126980. NULL,
  126981. &_vq_auxt__44c5_s_p8_1,
  126982. NULL,
  126983. 0
  126984. };
  126985. static long _vq_quantlist__44c5_s_p9_0[] = {
  126986. 7,
  126987. 6,
  126988. 8,
  126989. 5,
  126990. 9,
  126991. 4,
  126992. 10,
  126993. 3,
  126994. 11,
  126995. 2,
  126996. 12,
  126997. 1,
  126998. 13,
  126999. 0,
  127000. 14,
  127001. };
  127002. static long _vq_lengthlist__44c5_s_p9_0[] = {
  127003. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  127004. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  127005. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127006. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127007. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127008. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127009. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127010. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127011. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127012. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127013. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127014. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127015. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127016. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  127017. 12,
  127018. };
  127019. static float _vq_quantthresh__44c5_s_p9_0[] = {
  127020. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  127021. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  127022. };
  127023. static long _vq_quantmap__44c5_s_p9_0[] = {
  127024. 13, 11, 9, 7, 5, 3, 1, 0,
  127025. 2, 4, 6, 8, 10, 12, 14,
  127026. };
  127027. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  127028. _vq_quantthresh__44c5_s_p9_0,
  127029. _vq_quantmap__44c5_s_p9_0,
  127030. 15,
  127031. 15
  127032. };
  127033. static static_codebook _44c5_s_p9_0 = {
  127034. 2, 225,
  127035. _vq_lengthlist__44c5_s_p9_0,
  127036. 1, -512522752, 1628852224, 4, 0,
  127037. _vq_quantlist__44c5_s_p9_0,
  127038. NULL,
  127039. &_vq_auxt__44c5_s_p9_0,
  127040. NULL,
  127041. 0
  127042. };
  127043. static long _vq_quantlist__44c5_s_p9_1[] = {
  127044. 8,
  127045. 7,
  127046. 9,
  127047. 6,
  127048. 10,
  127049. 5,
  127050. 11,
  127051. 4,
  127052. 12,
  127053. 3,
  127054. 13,
  127055. 2,
  127056. 14,
  127057. 1,
  127058. 15,
  127059. 0,
  127060. 16,
  127061. };
  127062. static long _vq_lengthlist__44c5_s_p9_1[] = {
  127063. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  127064. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  127065. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  127066. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  127067. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  127068. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  127069. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  127070. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  127071. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  127072. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  127073. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  127074. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  127075. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  127076. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  127077. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  127078. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  127079. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  127080. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  127081. 15,
  127082. };
  127083. static float _vq_quantthresh__44c5_s_p9_1[] = {
  127084. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  127085. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  127086. };
  127087. static long _vq_quantmap__44c5_s_p9_1[] = {
  127088. 15, 13, 11, 9, 7, 5, 3, 1,
  127089. 0, 2, 4, 6, 8, 10, 12, 14,
  127090. 16,
  127091. };
  127092. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  127093. _vq_quantthresh__44c5_s_p9_1,
  127094. _vq_quantmap__44c5_s_p9_1,
  127095. 17,
  127096. 17
  127097. };
  127098. static static_codebook _44c5_s_p9_1 = {
  127099. 2, 289,
  127100. _vq_lengthlist__44c5_s_p9_1,
  127101. 1, -520814592, 1620377600, 5, 0,
  127102. _vq_quantlist__44c5_s_p9_1,
  127103. NULL,
  127104. &_vq_auxt__44c5_s_p9_1,
  127105. NULL,
  127106. 0
  127107. };
  127108. static long _vq_quantlist__44c5_s_p9_2[] = {
  127109. 10,
  127110. 9,
  127111. 11,
  127112. 8,
  127113. 12,
  127114. 7,
  127115. 13,
  127116. 6,
  127117. 14,
  127118. 5,
  127119. 15,
  127120. 4,
  127121. 16,
  127122. 3,
  127123. 17,
  127124. 2,
  127125. 18,
  127126. 1,
  127127. 19,
  127128. 0,
  127129. 20,
  127130. };
  127131. static long _vq_lengthlist__44c5_s_p9_2[] = {
  127132. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  127133. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  127134. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  127135. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  127136. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  127137. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127138. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127139. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  127140. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127141. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127142. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  127143. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  127144. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  127145. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  127146. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  127147. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  127148. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  127149. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  127150. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  127151. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  127152. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127153. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  127154. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  127155. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127156. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  127157. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  127158. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  127159. 10,10,10,10,10,10,10,10,10,
  127160. };
  127161. static float _vq_quantthresh__44c5_s_p9_2[] = {
  127162. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127163. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127164. 6.5, 7.5, 8.5, 9.5,
  127165. };
  127166. static long _vq_quantmap__44c5_s_p9_2[] = {
  127167. 19, 17, 15, 13, 11, 9, 7, 5,
  127168. 3, 1, 0, 2, 4, 6, 8, 10,
  127169. 12, 14, 16, 18, 20,
  127170. };
  127171. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  127172. _vq_quantthresh__44c5_s_p9_2,
  127173. _vq_quantmap__44c5_s_p9_2,
  127174. 21,
  127175. 21
  127176. };
  127177. static static_codebook _44c5_s_p9_2 = {
  127178. 2, 441,
  127179. _vq_lengthlist__44c5_s_p9_2,
  127180. 1, -529268736, 1611661312, 5, 0,
  127181. _vq_quantlist__44c5_s_p9_2,
  127182. NULL,
  127183. &_vq_auxt__44c5_s_p9_2,
  127184. NULL,
  127185. 0
  127186. };
  127187. static long _huff_lengthlist__44c5_s_short[] = {
  127188. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  127189. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  127190. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  127191. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  127192. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  127193. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  127194. 6, 8,11,16,
  127195. };
  127196. static static_codebook _huff_book__44c5_s_short = {
  127197. 2, 100,
  127198. _huff_lengthlist__44c5_s_short,
  127199. 0, 0, 0, 0, 0,
  127200. NULL,
  127201. NULL,
  127202. NULL,
  127203. NULL,
  127204. 0
  127205. };
  127206. static long _huff_lengthlist__44c6_s_long[] = {
  127207. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  127208. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  127209. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  127210. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  127211. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  127212. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  127213. 11,10,10,12,
  127214. };
  127215. static static_codebook _huff_book__44c6_s_long = {
  127216. 2, 100,
  127217. _huff_lengthlist__44c6_s_long,
  127218. 0, 0, 0, 0, 0,
  127219. NULL,
  127220. NULL,
  127221. NULL,
  127222. NULL,
  127223. 0
  127224. };
  127225. static long _vq_quantlist__44c6_s_p1_0[] = {
  127226. 1,
  127227. 0,
  127228. 2,
  127229. };
  127230. static long _vq_lengthlist__44c6_s_p1_0[] = {
  127231. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  127232. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  127234. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  127235. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  127236. 8,
  127237. };
  127238. static float _vq_quantthresh__44c6_s_p1_0[] = {
  127239. -0.5, 0.5,
  127240. };
  127241. static long _vq_quantmap__44c6_s_p1_0[] = {
  127242. 1, 0, 2,
  127243. };
  127244. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  127245. _vq_quantthresh__44c6_s_p1_0,
  127246. _vq_quantmap__44c6_s_p1_0,
  127247. 3,
  127248. 3
  127249. };
  127250. static static_codebook _44c6_s_p1_0 = {
  127251. 4, 81,
  127252. _vq_lengthlist__44c6_s_p1_0,
  127253. 1, -535822336, 1611661312, 2, 0,
  127254. _vq_quantlist__44c6_s_p1_0,
  127255. NULL,
  127256. &_vq_auxt__44c6_s_p1_0,
  127257. NULL,
  127258. 0
  127259. };
  127260. static long _vq_quantlist__44c6_s_p2_0[] = {
  127261. 2,
  127262. 1,
  127263. 3,
  127264. 0,
  127265. 4,
  127266. };
  127267. static long _vq_lengthlist__44c6_s_p2_0[] = {
  127268. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  127269. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  127270. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  127271. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  127272. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  127273. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  127274. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  127275. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  127276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127277. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  127278. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  127279. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  127280. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  127281. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  127282. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  127283. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  127286. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  127287. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  127288. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  127289. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  127290. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  127291. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  127294. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  127295. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  127296. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  127297. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  127298. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  127299. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  127304. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  127305. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  127306. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  127307. 13,
  127308. };
  127309. static float _vq_quantthresh__44c6_s_p2_0[] = {
  127310. -1.5, -0.5, 0.5, 1.5,
  127311. };
  127312. static long _vq_quantmap__44c6_s_p2_0[] = {
  127313. 3, 1, 0, 2, 4,
  127314. };
  127315. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  127316. _vq_quantthresh__44c6_s_p2_0,
  127317. _vq_quantmap__44c6_s_p2_0,
  127318. 5,
  127319. 5
  127320. };
  127321. static static_codebook _44c6_s_p2_0 = {
  127322. 4, 625,
  127323. _vq_lengthlist__44c6_s_p2_0,
  127324. 1, -533725184, 1611661312, 3, 0,
  127325. _vq_quantlist__44c6_s_p2_0,
  127326. NULL,
  127327. &_vq_auxt__44c6_s_p2_0,
  127328. NULL,
  127329. 0
  127330. };
  127331. static long _vq_quantlist__44c6_s_p3_0[] = {
  127332. 4,
  127333. 3,
  127334. 5,
  127335. 2,
  127336. 6,
  127337. 1,
  127338. 7,
  127339. 0,
  127340. 8,
  127341. };
  127342. static long _vq_lengthlist__44c6_s_p3_0[] = {
  127343. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127344. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  127345. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  127346. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  127347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127348. 0,
  127349. };
  127350. static float _vq_quantthresh__44c6_s_p3_0[] = {
  127351. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127352. };
  127353. static long _vq_quantmap__44c6_s_p3_0[] = {
  127354. 7, 5, 3, 1, 0, 2, 4, 6,
  127355. 8,
  127356. };
  127357. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  127358. _vq_quantthresh__44c6_s_p3_0,
  127359. _vq_quantmap__44c6_s_p3_0,
  127360. 9,
  127361. 9
  127362. };
  127363. static static_codebook _44c6_s_p3_0 = {
  127364. 2, 81,
  127365. _vq_lengthlist__44c6_s_p3_0,
  127366. 1, -531628032, 1611661312, 4, 0,
  127367. _vq_quantlist__44c6_s_p3_0,
  127368. NULL,
  127369. &_vq_auxt__44c6_s_p3_0,
  127370. NULL,
  127371. 0
  127372. };
  127373. static long _vq_quantlist__44c6_s_p4_0[] = {
  127374. 8,
  127375. 7,
  127376. 9,
  127377. 6,
  127378. 10,
  127379. 5,
  127380. 11,
  127381. 4,
  127382. 12,
  127383. 3,
  127384. 13,
  127385. 2,
  127386. 14,
  127387. 1,
  127388. 15,
  127389. 0,
  127390. 16,
  127391. };
  127392. static long _vq_lengthlist__44c6_s_p4_0[] = {
  127393. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  127394. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127395. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  127396. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  127397. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  127398. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  127399. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  127400. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  127401. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  127402. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  127403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127411. 0,
  127412. };
  127413. static float _vq_quantthresh__44c6_s_p4_0[] = {
  127414. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127415. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127416. };
  127417. static long _vq_quantmap__44c6_s_p4_0[] = {
  127418. 15, 13, 11, 9, 7, 5, 3, 1,
  127419. 0, 2, 4, 6, 8, 10, 12, 14,
  127420. 16,
  127421. };
  127422. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  127423. _vq_quantthresh__44c6_s_p4_0,
  127424. _vq_quantmap__44c6_s_p4_0,
  127425. 17,
  127426. 17
  127427. };
  127428. static static_codebook _44c6_s_p4_0 = {
  127429. 2, 289,
  127430. _vq_lengthlist__44c6_s_p4_0,
  127431. 1, -529530880, 1611661312, 5, 0,
  127432. _vq_quantlist__44c6_s_p4_0,
  127433. NULL,
  127434. &_vq_auxt__44c6_s_p4_0,
  127435. NULL,
  127436. 0
  127437. };
  127438. static long _vq_quantlist__44c6_s_p5_0[] = {
  127439. 1,
  127440. 0,
  127441. 2,
  127442. };
  127443. static long _vq_lengthlist__44c6_s_p5_0[] = {
  127444. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  127445. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  127446. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  127447. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  127448. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  127449. 12,
  127450. };
  127451. static float _vq_quantthresh__44c6_s_p5_0[] = {
  127452. -5.5, 5.5,
  127453. };
  127454. static long _vq_quantmap__44c6_s_p5_0[] = {
  127455. 1, 0, 2,
  127456. };
  127457. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  127458. _vq_quantthresh__44c6_s_p5_0,
  127459. _vq_quantmap__44c6_s_p5_0,
  127460. 3,
  127461. 3
  127462. };
  127463. static static_codebook _44c6_s_p5_0 = {
  127464. 4, 81,
  127465. _vq_lengthlist__44c6_s_p5_0,
  127466. 1, -529137664, 1618345984, 2, 0,
  127467. _vq_quantlist__44c6_s_p5_0,
  127468. NULL,
  127469. &_vq_auxt__44c6_s_p5_0,
  127470. NULL,
  127471. 0
  127472. };
  127473. static long _vq_quantlist__44c6_s_p5_1[] = {
  127474. 5,
  127475. 4,
  127476. 6,
  127477. 3,
  127478. 7,
  127479. 2,
  127480. 8,
  127481. 1,
  127482. 9,
  127483. 0,
  127484. 10,
  127485. };
  127486. static long _vq_lengthlist__44c6_s_p5_1[] = {
  127487. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  127488. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  127489. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  127490. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  127491. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  127492. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  127493. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  127494. 11,10,10, 7, 7, 8, 8, 8, 8,
  127495. };
  127496. static float _vq_quantthresh__44c6_s_p5_1[] = {
  127497. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127498. 3.5, 4.5,
  127499. };
  127500. static long _vq_quantmap__44c6_s_p5_1[] = {
  127501. 9, 7, 5, 3, 1, 0, 2, 4,
  127502. 6, 8, 10,
  127503. };
  127504. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  127505. _vq_quantthresh__44c6_s_p5_1,
  127506. _vq_quantmap__44c6_s_p5_1,
  127507. 11,
  127508. 11
  127509. };
  127510. static static_codebook _44c6_s_p5_1 = {
  127511. 2, 121,
  127512. _vq_lengthlist__44c6_s_p5_1,
  127513. 1, -531365888, 1611661312, 4, 0,
  127514. _vq_quantlist__44c6_s_p5_1,
  127515. NULL,
  127516. &_vq_auxt__44c6_s_p5_1,
  127517. NULL,
  127518. 0
  127519. };
  127520. static long _vq_quantlist__44c6_s_p6_0[] = {
  127521. 6,
  127522. 5,
  127523. 7,
  127524. 4,
  127525. 8,
  127526. 3,
  127527. 9,
  127528. 2,
  127529. 10,
  127530. 1,
  127531. 11,
  127532. 0,
  127533. 12,
  127534. };
  127535. static long _vq_lengthlist__44c6_s_p6_0[] = {
  127536. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  127537. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  127538. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  127539. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  127540. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  127541. 12, 9, 8,10,10,11,11,12,12,13,13, 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, 0, 0, 0, 0, 0, 0,
  127544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  127547. };
  127548. static float _vq_quantthresh__44c6_s_p6_0[] = {
  127549. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127550. 12.5, 17.5, 22.5, 27.5,
  127551. };
  127552. static long _vq_quantmap__44c6_s_p6_0[] = {
  127553. 11, 9, 7, 5, 3, 1, 0, 2,
  127554. 4, 6, 8, 10, 12,
  127555. };
  127556. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  127557. _vq_quantthresh__44c6_s_p6_0,
  127558. _vq_quantmap__44c6_s_p6_0,
  127559. 13,
  127560. 13
  127561. };
  127562. static static_codebook _44c6_s_p6_0 = {
  127563. 2, 169,
  127564. _vq_lengthlist__44c6_s_p6_0,
  127565. 1, -526516224, 1616117760, 4, 0,
  127566. _vq_quantlist__44c6_s_p6_0,
  127567. NULL,
  127568. &_vq_auxt__44c6_s_p6_0,
  127569. NULL,
  127570. 0
  127571. };
  127572. static long _vq_quantlist__44c6_s_p6_1[] = {
  127573. 2,
  127574. 1,
  127575. 3,
  127576. 0,
  127577. 4,
  127578. };
  127579. static long _vq_lengthlist__44c6_s_p6_1[] = {
  127580. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  127581. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127582. };
  127583. static float _vq_quantthresh__44c6_s_p6_1[] = {
  127584. -1.5, -0.5, 0.5, 1.5,
  127585. };
  127586. static long _vq_quantmap__44c6_s_p6_1[] = {
  127587. 3, 1, 0, 2, 4,
  127588. };
  127589. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  127590. _vq_quantthresh__44c6_s_p6_1,
  127591. _vq_quantmap__44c6_s_p6_1,
  127592. 5,
  127593. 5
  127594. };
  127595. static static_codebook _44c6_s_p6_1 = {
  127596. 2, 25,
  127597. _vq_lengthlist__44c6_s_p6_1,
  127598. 1, -533725184, 1611661312, 3, 0,
  127599. _vq_quantlist__44c6_s_p6_1,
  127600. NULL,
  127601. &_vq_auxt__44c6_s_p6_1,
  127602. NULL,
  127603. 0
  127604. };
  127605. static long _vq_quantlist__44c6_s_p7_0[] = {
  127606. 6,
  127607. 5,
  127608. 7,
  127609. 4,
  127610. 8,
  127611. 3,
  127612. 9,
  127613. 2,
  127614. 10,
  127615. 1,
  127616. 11,
  127617. 0,
  127618. 12,
  127619. };
  127620. static long _vq_lengthlist__44c6_s_p7_0[] = {
  127621. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  127622. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  127623. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  127624. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  127625. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  127626. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  127627. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  127628. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  127629. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  127630. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  127631. 20,13,13,13,13,13,13,14,14,
  127632. };
  127633. static float _vq_quantthresh__44c6_s_p7_0[] = {
  127634. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  127635. 27.5, 38.5, 49.5, 60.5,
  127636. };
  127637. static long _vq_quantmap__44c6_s_p7_0[] = {
  127638. 11, 9, 7, 5, 3, 1, 0, 2,
  127639. 4, 6, 8, 10, 12,
  127640. };
  127641. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  127642. _vq_quantthresh__44c6_s_p7_0,
  127643. _vq_quantmap__44c6_s_p7_0,
  127644. 13,
  127645. 13
  127646. };
  127647. static static_codebook _44c6_s_p7_0 = {
  127648. 2, 169,
  127649. _vq_lengthlist__44c6_s_p7_0,
  127650. 1, -523206656, 1618345984, 4, 0,
  127651. _vq_quantlist__44c6_s_p7_0,
  127652. NULL,
  127653. &_vq_auxt__44c6_s_p7_0,
  127654. NULL,
  127655. 0
  127656. };
  127657. static long _vq_quantlist__44c6_s_p7_1[] = {
  127658. 5,
  127659. 4,
  127660. 6,
  127661. 3,
  127662. 7,
  127663. 2,
  127664. 8,
  127665. 1,
  127666. 9,
  127667. 0,
  127668. 10,
  127669. };
  127670. static long _vq_lengthlist__44c6_s_p7_1[] = {
  127671. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  127672. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  127673. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  127674. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  127675. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  127676. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  127677. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  127678. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  127679. };
  127680. static float _vq_quantthresh__44c6_s_p7_1[] = {
  127681. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127682. 3.5, 4.5,
  127683. };
  127684. static long _vq_quantmap__44c6_s_p7_1[] = {
  127685. 9, 7, 5, 3, 1, 0, 2, 4,
  127686. 6, 8, 10,
  127687. };
  127688. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  127689. _vq_quantthresh__44c6_s_p7_1,
  127690. _vq_quantmap__44c6_s_p7_1,
  127691. 11,
  127692. 11
  127693. };
  127694. static static_codebook _44c6_s_p7_1 = {
  127695. 2, 121,
  127696. _vq_lengthlist__44c6_s_p7_1,
  127697. 1, -531365888, 1611661312, 4, 0,
  127698. _vq_quantlist__44c6_s_p7_1,
  127699. NULL,
  127700. &_vq_auxt__44c6_s_p7_1,
  127701. NULL,
  127702. 0
  127703. };
  127704. static long _vq_quantlist__44c6_s_p8_0[] = {
  127705. 7,
  127706. 6,
  127707. 8,
  127708. 5,
  127709. 9,
  127710. 4,
  127711. 10,
  127712. 3,
  127713. 11,
  127714. 2,
  127715. 12,
  127716. 1,
  127717. 13,
  127718. 0,
  127719. 14,
  127720. };
  127721. static long _vq_lengthlist__44c6_s_p8_0[] = {
  127722. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  127723. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  127724. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  127725. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  127726. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  127727. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  127728. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  127729. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  127730. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  127731. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  127732. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  127733. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  127734. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  127735. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  127736. 14,
  127737. };
  127738. static float _vq_quantthresh__44c6_s_p8_0[] = {
  127739. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127740. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127741. };
  127742. static long _vq_quantmap__44c6_s_p8_0[] = {
  127743. 13, 11, 9, 7, 5, 3, 1, 0,
  127744. 2, 4, 6, 8, 10, 12, 14,
  127745. };
  127746. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  127747. _vq_quantthresh__44c6_s_p8_0,
  127748. _vq_quantmap__44c6_s_p8_0,
  127749. 15,
  127750. 15
  127751. };
  127752. static static_codebook _44c6_s_p8_0 = {
  127753. 2, 225,
  127754. _vq_lengthlist__44c6_s_p8_0,
  127755. 1, -520986624, 1620377600, 4, 0,
  127756. _vq_quantlist__44c6_s_p8_0,
  127757. NULL,
  127758. &_vq_auxt__44c6_s_p8_0,
  127759. NULL,
  127760. 0
  127761. };
  127762. static long _vq_quantlist__44c6_s_p8_1[] = {
  127763. 10,
  127764. 9,
  127765. 11,
  127766. 8,
  127767. 12,
  127768. 7,
  127769. 13,
  127770. 6,
  127771. 14,
  127772. 5,
  127773. 15,
  127774. 4,
  127775. 16,
  127776. 3,
  127777. 17,
  127778. 2,
  127779. 18,
  127780. 1,
  127781. 19,
  127782. 0,
  127783. 20,
  127784. };
  127785. static long _vq_lengthlist__44c6_s_p8_1[] = {
  127786. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  127787. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  127788. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  127789. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  127790. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127791. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  127792. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  127793. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  127794. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127795. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127796. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  127797. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  127798. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  127799. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  127800. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  127801. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  127802. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  127803. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  127804. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  127805. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  127806. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  127807. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  127808. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  127809. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127810. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  127811. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  127812. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  127813. 10,10,10,10,10,10,10,10,10,
  127814. };
  127815. static float _vq_quantthresh__44c6_s_p8_1[] = {
  127816. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127817. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127818. 6.5, 7.5, 8.5, 9.5,
  127819. };
  127820. static long _vq_quantmap__44c6_s_p8_1[] = {
  127821. 19, 17, 15, 13, 11, 9, 7, 5,
  127822. 3, 1, 0, 2, 4, 6, 8, 10,
  127823. 12, 14, 16, 18, 20,
  127824. };
  127825. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  127826. _vq_quantthresh__44c6_s_p8_1,
  127827. _vq_quantmap__44c6_s_p8_1,
  127828. 21,
  127829. 21
  127830. };
  127831. static static_codebook _44c6_s_p8_1 = {
  127832. 2, 441,
  127833. _vq_lengthlist__44c6_s_p8_1,
  127834. 1, -529268736, 1611661312, 5, 0,
  127835. _vq_quantlist__44c6_s_p8_1,
  127836. NULL,
  127837. &_vq_auxt__44c6_s_p8_1,
  127838. NULL,
  127839. 0
  127840. };
  127841. static long _vq_quantlist__44c6_s_p9_0[] = {
  127842. 6,
  127843. 5,
  127844. 7,
  127845. 4,
  127846. 8,
  127847. 3,
  127848. 9,
  127849. 2,
  127850. 10,
  127851. 1,
  127852. 11,
  127853. 0,
  127854. 12,
  127855. };
  127856. static long _vq_lengthlist__44c6_s_p9_0[] = {
  127857. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  127858. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  127859. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127860. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  127861. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127862. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127863. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127864. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127865. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127866. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127867. 10,10,10,10,10,10,10,10,10,
  127868. };
  127869. static float _vq_quantthresh__44c6_s_p9_0[] = {
  127870. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  127871. 1592.5, 2229.5, 2866.5, 3503.5,
  127872. };
  127873. static long _vq_quantmap__44c6_s_p9_0[] = {
  127874. 11, 9, 7, 5, 3, 1, 0, 2,
  127875. 4, 6, 8, 10, 12,
  127876. };
  127877. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  127878. _vq_quantthresh__44c6_s_p9_0,
  127879. _vq_quantmap__44c6_s_p9_0,
  127880. 13,
  127881. 13
  127882. };
  127883. static static_codebook _44c6_s_p9_0 = {
  127884. 2, 169,
  127885. _vq_lengthlist__44c6_s_p9_0,
  127886. 1, -511845376, 1630791680, 4, 0,
  127887. _vq_quantlist__44c6_s_p9_0,
  127888. NULL,
  127889. &_vq_auxt__44c6_s_p9_0,
  127890. NULL,
  127891. 0
  127892. };
  127893. static long _vq_quantlist__44c6_s_p9_1[] = {
  127894. 6,
  127895. 5,
  127896. 7,
  127897. 4,
  127898. 8,
  127899. 3,
  127900. 9,
  127901. 2,
  127902. 10,
  127903. 1,
  127904. 11,
  127905. 0,
  127906. 12,
  127907. };
  127908. static long _vq_lengthlist__44c6_s_p9_1[] = {
  127909. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  127910. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  127911. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  127912. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  127913. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  127914. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  127915. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  127916. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  127917. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  127918. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  127919. 15,12,10,11,11,13,11,12,13,
  127920. };
  127921. static float _vq_quantthresh__44c6_s_p9_1[] = {
  127922. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  127923. 122.5, 171.5, 220.5, 269.5,
  127924. };
  127925. static long _vq_quantmap__44c6_s_p9_1[] = {
  127926. 11, 9, 7, 5, 3, 1, 0, 2,
  127927. 4, 6, 8, 10, 12,
  127928. };
  127929. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  127930. _vq_quantthresh__44c6_s_p9_1,
  127931. _vq_quantmap__44c6_s_p9_1,
  127932. 13,
  127933. 13
  127934. };
  127935. static static_codebook _44c6_s_p9_1 = {
  127936. 2, 169,
  127937. _vq_lengthlist__44c6_s_p9_1,
  127938. 1, -518889472, 1622704128, 4, 0,
  127939. _vq_quantlist__44c6_s_p9_1,
  127940. NULL,
  127941. &_vq_auxt__44c6_s_p9_1,
  127942. NULL,
  127943. 0
  127944. };
  127945. static long _vq_quantlist__44c6_s_p9_2[] = {
  127946. 24,
  127947. 23,
  127948. 25,
  127949. 22,
  127950. 26,
  127951. 21,
  127952. 27,
  127953. 20,
  127954. 28,
  127955. 19,
  127956. 29,
  127957. 18,
  127958. 30,
  127959. 17,
  127960. 31,
  127961. 16,
  127962. 32,
  127963. 15,
  127964. 33,
  127965. 14,
  127966. 34,
  127967. 13,
  127968. 35,
  127969. 12,
  127970. 36,
  127971. 11,
  127972. 37,
  127973. 10,
  127974. 38,
  127975. 9,
  127976. 39,
  127977. 8,
  127978. 40,
  127979. 7,
  127980. 41,
  127981. 6,
  127982. 42,
  127983. 5,
  127984. 43,
  127985. 4,
  127986. 44,
  127987. 3,
  127988. 45,
  127989. 2,
  127990. 46,
  127991. 1,
  127992. 47,
  127993. 0,
  127994. 48,
  127995. };
  127996. static long _vq_lengthlist__44c6_s_p9_2[] = {
  127997. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  127998. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  127999. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128000. 7,
  128001. };
  128002. static float _vq_quantthresh__44c6_s_p9_2[] = {
  128003. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128004. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128005. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128006. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128007. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128008. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128009. };
  128010. static long _vq_quantmap__44c6_s_p9_2[] = {
  128011. 47, 45, 43, 41, 39, 37, 35, 33,
  128012. 31, 29, 27, 25, 23, 21, 19, 17,
  128013. 15, 13, 11, 9, 7, 5, 3, 1,
  128014. 0, 2, 4, 6, 8, 10, 12, 14,
  128015. 16, 18, 20, 22, 24, 26, 28, 30,
  128016. 32, 34, 36, 38, 40, 42, 44, 46,
  128017. 48,
  128018. };
  128019. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  128020. _vq_quantthresh__44c6_s_p9_2,
  128021. _vq_quantmap__44c6_s_p9_2,
  128022. 49,
  128023. 49
  128024. };
  128025. static static_codebook _44c6_s_p9_2 = {
  128026. 1, 49,
  128027. _vq_lengthlist__44c6_s_p9_2,
  128028. 1, -526909440, 1611661312, 6, 0,
  128029. _vq_quantlist__44c6_s_p9_2,
  128030. NULL,
  128031. &_vq_auxt__44c6_s_p9_2,
  128032. NULL,
  128033. 0
  128034. };
  128035. static long _huff_lengthlist__44c6_s_short[] = {
  128036. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  128037. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  128038. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  128039. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  128040. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  128041. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  128042. 9,10,17,18,
  128043. };
  128044. static static_codebook _huff_book__44c6_s_short = {
  128045. 2, 100,
  128046. _huff_lengthlist__44c6_s_short,
  128047. 0, 0, 0, 0, 0,
  128048. NULL,
  128049. NULL,
  128050. NULL,
  128051. NULL,
  128052. 0
  128053. };
  128054. static long _huff_lengthlist__44c7_s_long[] = {
  128055. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  128056. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  128057. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  128058. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  128059. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  128060. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  128061. 11,10,10,12,
  128062. };
  128063. static static_codebook _huff_book__44c7_s_long = {
  128064. 2, 100,
  128065. _huff_lengthlist__44c7_s_long,
  128066. 0, 0, 0, 0, 0,
  128067. NULL,
  128068. NULL,
  128069. NULL,
  128070. NULL,
  128071. 0
  128072. };
  128073. static long _vq_quantlist__44c7_s_p1_0[] = {
  128074. 1,
  128075. 0,
  128076. 2,
  128077. };
  128078. static long _vq_lengthlist__44c7_s_p1_0[] = {
  128079. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  128080. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  128082. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128083. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  128084. 8,
  128085. };
  128086. static float _vq_quantthresh__44c7_s_p1_0[] = {
  128087. -0.5, 0.5,
  128088. };
  128089. static long _vq_quantmap__44c7_s_p1_0[] = {
  128090. 1, 0, 2,
  128091. };
  128092. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  128093. _vq_quantthresh__44c7_s_p1_0,
  128094. _vq_quantmap__44c7_s_p1_0,
  128095. 3,
  128096. 3
  128097. };
  128098. static static_codebook _44c7_s_p1_0 = {
  128099. 4, 81,
  128100. _vq_lengthlist__44c7_s_p1_0,
  128101. 1, -535822336, 1611661312, 2, 0,
  128102. _vq_quantlist__44c7_s_p1_0,
  128103. NULL,
  128104. &_vq_auxt__44c7_s_p1_0,
  128105. NULL,
  128106. 0
  128107. };
  128108. static long _vq_quantlist__44c7_s_p2_0[] = {
  128109. 2,
  128110. 1,
  128111. 3,
  128112. 0,
  128113. 4,
  128114. };
  128115. static long _vq_lengthlist__44c7_s_p2_0[] = {
  128116. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128117. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  128118. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  128119. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  128120. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  128121. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  128122. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  128123. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  128126. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  128127. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  128128. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  128129. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  128130. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  128131. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  128134. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  128135. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  128136. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  128137. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  128138. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  128139. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  128142. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  128143. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  128144. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  128145. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  128146. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  128147. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  128152. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  128153. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  128154. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  128155. 13,
  128156. };
  128157. static float _vq_quantthresh__44c7_s_p2_0[] = {
  128158. -1.5, -0.5, 0.5, 1.5,
  128159. };
  128160. static long _vq_quantmap__44c7_s_p2_0[] = {
  128161. 3, 1, 0, 2, 4,
  128162. };
  128163. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  128164. _vq_quantthresh__44c7_s_p2_0,
  128165. _vq_quantmap__44c7_s_p2_0,
  128166. 5,
  128167. 5
  128168. };
  128169. static static_codebook _44c7_s_p2_0 = {
  128170. 4, 625,
  128171. _vq_lengthlist__44c7_s_p2_0,
  128172. 1, -533725184, 1611661312, 3, 0,
  128173. _vq_quantlist__44c7_s_p2_0,
  128174. NULL,
  128175. &_vq_auxt__44c7_s_p2_0,
  128176. NULL,
  128177. 0
  128178. };
  128179. static long _vq_quantlist__44c7_s_p3_0[] = {
  128180. 4,
  128181. 3,
  128182. 5,
  128183. 2,
  128184. 6,
  128185. 1,
  128186. 7,
  128187. 0,
  128188. 8,
  128189. };
  128190. static long _vq_lengthlist__44c7_s_p3_0[] = {
  128191. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128192. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  128193. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  128194. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0,
  128197. };
  128198. static float _vq_quantthresh__44c7_s_p3_0[] = {
  128199. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128200. };
  128201. static long _vq_quantmap__44c7_s_p3_0[] = {
  128202. 7, 5, 3, 1, 0, 2, 4, 6,
  128203. 8,
  128204. };
  128205. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  128206. _vq_quantthresh__44c7_s_p3_0,
  128207. _vq_quantmap__44c7_s_p3_0,
  128208. 9,
  128209. 9
  128210. };
  128211. static static_codebook _44c7_s_p3_0 = {
  128212. 2, 81,
  128213. _vq_lengthlist__44c7_s_p3_0,
  128214. 1, -531628032, 1611661312, 4, 0,
  128215. _vq_quantlist__44c7_s_p3_0,
  128216. NULL,
  128217. &_vq_auxt__44c7_s_p3_0,
  128218. NULL,
  128219. 0
  128220. };
  128221. static long _vq_quantlist__44c7_s_p4_0[] = {
  128222. 8,
  128223. 7,
  128224. 9,
  128225. 6,
  128226. 10,
  128227. 5,
  128228. 11,
  128229. 4,
  128230. 12,
  128231. 3,
  128232. 13,
  128233. 2,
  128234. 14,
  128235. 1,
  128236. 15,
  128237. 0,
  128238. 16,
  128239. };
  128240. static long _vq_lengthlist__44c7_s_p4_0[] = {
  128241. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  128242. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  128243. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  128244. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  128245. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  128246. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  128247. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  128248. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  128249. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  128250. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0,
  128260. };
  128261. static float _vq_quantthresh__44c7_s_p4_0[] = {
  128262. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128263. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128264. };
  128265. static long _vq_quantmap__44c7_s_p4_0[] = {
  128266. 15, 13, 11, 9, 7, 5, 3, 1,
  128267. 0, 2, 4, 6, 8, 10, 12, 14,
  128268. 16,
  128269. };
  128270. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  128271. _vq_quantthresh__44c7_s_p4_0,
  128272. _vq_quantmap__44c7_s_p4_0,
  128273. 17,
  128274. 17
  128275. };
  128276. static static_codebook _44c7_s_p4_0 = {
  128277. 2, 289,
  128278. _vq_lengthlist__44c7_s_p4_0,
  128279. 1, -529530880, 1611661312, 5, 0,
  128280. _vq_quantlist__44c7_s_p4_0,
  128281. NULL,
  128282. &_vq_auxt__44c7_s_p4_0,
  128283. NULL,
  128284. 0
  128285. };
  128286. static long _vq_quantlist__44c7_s_p5_0[] = {
  128287. 1,
  128288. 0,
  128289. 2,
  128290. };
  128291. static long _vq_lengthlist__44c7_s_p5_0[] = {
  128292. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  128293. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  128294. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  128295. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  128296. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  128297. 12,
  128298. };
  128299. static float _vq_quantthresh__44c7_s_p5_0[] = {
  128300. -5.5, 5.5,
  128301. };
  128302. static long _vq_quantmap__44c7_s_p5_0[] = {
  128303. 1, 0, 2,
  128304. };
  128305. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  128306. _vq_quantthresh__44c7_s_p5_0,
  128307. _vq_quantmap__44c7_s_p5_0,
  128308. 3,
  128309. 3
  128310. };
  128311. static static_codebook _44c7_s_p5_0 = {
  128312. 4, 81,
  128313. _vq_lengthlist__44c7_s_p5_0,
  128314. 1, -529137664, 1618345984, 2, 0,
  128315. _vq_quantlist__44c7_s_p5_0,
  128316. NULL,
  128317. &_vq_auxt__44c7_s_p5_0,
  128318. NULL,
  128319. 0
  128320. };
  128321. static long _vq_quantlist__44c7_s_p5_1[] = {
  128322. 5,
  128323. 4,
  128324. 6,
  128325. 3,
  128326. 7,
  128327. 2,
  128328. 8,
  128329. 1,
  128330. 9,
  128331. 0,
  128332. 10,
  128333. };
  128334. static long _vq_lengthlist__44c7_s_p5_1[] = {
  128335. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  128336. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  128337. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  128338. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  128339. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  128340. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  128341. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  128342. 11,11,11, 7, 7, 8, 8, 8, 8,
  128343. };
  128344. static float _vq_quantthresh__44c7_s_p5_1[] = {
  128345. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128346. 3.5, 4.5,
  128347. };
  128348. static long _vq_quantmap__44c7_s_p5_1[] = {
  128349. 9, 7, 5, 3, 1, 0, 2, 4,
  128350. 6, 8, 10,
  128351. };
  128352. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  128353. _vq_quantthresh__44c7_s_p5_1,
  128354. _vq_quantmap__44c7_s_p5_1,
  128355. 11,
  128356. 11
  128357. };
  128358. static static_codebook _44c7_s_p5_1 = {
  128359. 2, 121,
  128360. _vq_lengthlist__44c7_s_p5_1,
  128361. 1, -531365888, 1611661312, 4, 0,
  128362. _vq_quantlist__44c7_s_p5_1,
  128363. NULL,
  128364. &_vq_auxt__44c7_s_p5_1,
  128365. NULL,
  128366. 0
  128367. };
  128368. static long _vq_quantlist__44c7_s_p6_0[] = {
  128369. 6,
  128370. 5,
  128371. 7,
  128372. 4,
  128373. 8,
  128374. 3,
  128375. 9,
  128376. 2,
  128377. 10,
  128378. 1,
  128379. 11,
  128380. 0,
  128381. 12,
  128382. };
  128383. static long _vq_lengthlist__44c7_s_p6_0[] = {
  128384. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  128385. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  128386. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  128387. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  128388. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  128389. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  128390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128394. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128395. };
  128396. static float _vq_quantthresh__44c7_s_p6_0[] = {
  128397. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128398. 12.5, 17.5, 22.5, 27.5,
  128399. };
  128400. static long _vq_quantmap__44c7_s_p6_0[] = {
  128401. 11, 9, 7, 5, 3, 1, 0, 2,
  128402. 4, 6, 8, 10, 12,
  128403. };
  128404. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  128405. _vq_quantthresh__44c7_s_p6_0,
  128406. _vq_quantmap__44c7_s_p6_0,
  128407. 13,
  128408. 13
  128409. };
  128410. static static_codebook _44c7_s_p6_0 = {
  128411. 2, 169,
  128412. _vq_lengthlist__44c7_s_p6_0,
  128413. 1, -526516224, 1616117760, 4, 0,
  128414. _vq_quantlist__44c7_s_p6_0,
  128415. NULL,
  128416. &_vq_auxt__44c7_s_p6_0,
  128417. NULL,
  128418. 0
  128419. };
  128420. static long _vq_quantlist__44c7_s_p6_1[] = {
  128421. 2,
  128422. 1,
  128423. 3,
  128424. 0,
  128425. 4,
  128426. };
  128427. static long _vq_lengthlist__44c7_s_p6_1[] = {
  128428. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  128429. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128430. };
  128431. static float _vq_quantthresh__44c7_s_p6_1[] = {
  128432. -1.5, -0.5, 0.5, 1.5,
  128433. };
  128434. static long _vq_quantmap__44c7_s_p6_1[] = {
  128435. 3, 1, 0, 2, 4,
  128436. };
  128437. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  128438. _vq_quantthresh__44c7_s_p6_1,
  128439. _vq_quantmap__44c7_s_p6_1,
  128440. 5,
  128441. 5
  128442. };
  128443. static static_codebook _44c7_s_p6_1 = {
  128444. 2, 25,
  128445. _vq_lengthlist__44c7_s_p6_1,
  128446. 1, -533725184, 1611661312, 3, 0,
  128447. _vq_quantlist__44c7_s_p6_1,
  128448. NULL,
  128449. &_vq_auxt__44c7_s_p6_1,
  128450. NULL,
  128451. 0
  128452. };
  128453. static long _vq_quantlist__44c7_s_p7_0[] = {
  128454. 6,
  128455. 5,
  128456. 7,
  128457. 4,
  128458. 8,
  128459. 3,
  128460. 9,
  128461. 2,
  128462. 10,
  128463. 1,
  128464. 11,
  128465. 0,
  128466. 12,
  128467. };
  128468. static long _vq_lengthlist__44c7_s_p7_0[] = {
  128469. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  128470. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  128471. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  128472. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  128473. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  128474. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  128475. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  128476. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  128477. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  128478. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  128479. 19,13,13,13,13,14,14,15,15,
  128480. };
  128481. static float _vq_quantthresh__44c7_s_p7_0[] = {
  128482. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  128483. 27.5, 38.5, 49.5, 60.5,
  128484. };
  128485. static long _vq_quantmap__44c7_s_p7_0[] = {
  128486. 11, 9, 7, 5, 3, 1, 0, 2,
  128487. 4, 6, 8, 10, 12,
  128488. };
  128489. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  128490. _vq_quantthresh__44c7_s_p7_0,
  128491. _vq_quantmap__44c7_s_p7_0,
  128492. 13,
  128493. 13
  128494. };
  128495. static static_codebook _44c7_s_p7_0 = {
  128496. 2, 169,
  128497. _vq_lengthlist__44c7_s_p7_0,
  128498. 1, -523206656, 1618345984, 4, 0,
  128499. _vq_quantlist__44c7_s_p7_0,
  128500. NULL,
  128501. &_vq_auxt__44c7_s_p7_0,
  128502. NULL,
  128503. 0
  128504. };
  128505. static long _vq_quantlist__44c7_s_p7_1[] = {
  128506. 5,
  128507. 4,
  128508. 6,
  128509. 3,
  128510. 7,
  128511. 2,
  128512. 8,
  128513. 1,
  128514. 9,
  128515. 0,
  128516. 10,
  128517. };
  128518. static long _vq_lengthlist__44c7_s_p7_1[] = {
  128519. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  128520. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  128521. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  128522. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  128523. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  128524. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  128525. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  128526. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  128527. };
  128528. static float _vq_quantthresh__44c7_s_p7_1[] = {
  128529. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128530. 3.5, 4.5,
  128531. };
  128532. static long _vq_quantmap__44c7_s_p7_1[] = {
  128533. 9, 7, 5, 3, 1, 0, 2, 4,
  128534. 6, 8, 10,
  128535. };
  128536. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  128537. _vq_quantthresh__44c7_s_p7_1,
  128538. _vq_quantmap__44c7_s_p7_1,
  128539. 11,
  128540. 11
  128541. };
  128542. static static_codebook _44c7_s_p7_1 = {
  128543. 2, 121,
  128544. _vq_lengthlist__44c7_s_p7_1,
  128545. 1, -531365888, 1611661312, 4, 0,
  128546. _vq_quantlist__44c7_s_p7_1,
  128547. NULL,
  128548. &_vq_auxt__44c7_s_p7_1,
  128549. NULL,
  128550. 0
  128551. };
  128552. static long _vq_quantlist__44c7_s_p8_0[] = {
  128553. 7,
  128554. 6,
  128555. 8,
  128556. 5,
  128557. 9,
  128558. 4,
  128559. 10,
  128560. 3,
  128561. 11,
  128562. 2,
  128563. 12,
  128564. 1,
  128565. 13,
  128566. 0,
  128567. 14,
  128568. };
  128569. static long _vq_lengthlist__44c7_s_p8_0[] = {
  128570. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  128571. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  128572. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  128573. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  128574. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  128575. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  128576. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  128577. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  128578. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  128579. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  128580. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  128581. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  128582. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  128583. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  128584. 14,
  128585. };
  128586. static float _vq_quantthresh__44c7_s_p8_0[] = {
  128587. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128588. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128589. };
  128590. static long _vq_quantmap__44c7_s_p8_0[] = {
  128591. 13, 11, 9, 7, 5, 3, 1, 0,
  128592. 2, 4, 6, 8, 10, 12, 14,
  128593. };
  128594. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  128595. _vq_quantthresh__44c7_s_p8_0,
  128596. _vq_quantmap__44c7_s_p8_0,
  128597. 15,
  128598. 15
  128599. };
  128600. static static_codebook _44c7_s_p8_0 = {
  128601. 2, 225,
  128602. _vq_lengthlist__44c7_s_p8_0,
  128603. 1, -520986624, 1620377600, 4, 0,
  128604. _vq_quantlist__44c7_s_p8_0,
  128605. NULL,
  128606. &_vq_auxt__44c7_s_p8_0,
  128607. NULL,
  128608. 0
  128609. };
  128610. static long _vq_quantlist__44c7_s_p8_1[] = {
  128611. 10,
  128612. 9,
  128613. 11,
  128614. 8,
  128615. 12,
  128616. 7,
  128617. 13,
  128618. 6,
  128619. 14,
  128620. 5,
  128621. 15,
  128622. 4,
  128623. 16,
  128624. 3,
  128625. 17,
  128626. 2,
  128627. 18,
  128628. 1,
  128629. 19,
  128630. 0,
  128631. 20,
  128632. };
  128633. static long _vq_lengthlist__44c7_s_p8_1[] = {
  128634. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  128635. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  128636. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  128637. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  128638. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128639. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  128640. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  128641. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  128642. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128643. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128644. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  128645. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  128646. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  128647. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  128648. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  128649. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  128650. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  128651. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  128652. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  128653. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  128654. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  128655. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  128656. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  128657. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  128658. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  128659. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  128660. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  128661. 10,10,10,10,10,10,10,10,10,
  128662. };
  128663. static float _vq_quantthresh__44c7_s_p8_1[] = {
  128664. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128665. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128666. 6.5, 7.5, 8.5, 9.5,
  128667. };
  128668. static long _vq_quantmap__44c7_s_p8_1[] = {
  128669. 19, 17, 15, 13, 11, 9, 7, 5,
  128670. 3, 1, 0, 2, 4, 6, 8, 10,
  128671. 12, 14, 16, 18, 20,
  128672. };
  128673. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  128674. _vq_quantthresh__44c7_s_p8_1,
  128675. _vq_quantmap__44c7_s_p8_1,
  128676. 21,
  128677. 21
  128678. };
  128679. static static_codebook _44c7_s_p8_1 = {
  128680. 2, 441,
  128681. _vq_lengthlist__44c7_s_p8_1,
  128682. 1, -529268736, 1611661312, 5, 0,
  128683. _vq_quantlist__44c7_s_p8_1,
  128684. NULL,
  128685. &_vq_auxt__44c7_s_p8_1,
  128686. NULL,
  128687. 0
  128688. };
  128689. static long _vq_quantlist__44c7_s_p9_0[] = {
  128690. 6,
  128691. 5,
  128692. 7,
  128693. 4,
  128694. 8,
  128695. 3,
  128696. 9,
  128697. 2,
  128698. 10,
  128699. 1,
  128700. 11,
  128701. 0,
  128702. 12,
  128703. };
  128704. static long _vq_lengthlist__44c7_s_p9_0[] = {
  128705. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  128706. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  128707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128708. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128710. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128711. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128712. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128713. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128714. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128715. 11,11,11,11,11,11,11,11,11,
  128716. };
  128717. static float _vq_quantthresh__44c7_s_p9_0[] = {
  128718. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  128719. 1592.5, 2229.5, 2866.5, 3503.5,
  128720. };
  128721. static long _vq_quantmap__44c7_s_p9_0[] = {
  128722. 11, 9, 7, 5, 3, 1, 0, 2,
  128723. 4, 6, 8, 10, 12,
  128724. };
  128725. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  128726. _vq_quantthresh__44c7_s_p9_0,
  128727. _vq_quantmap__44c7_s_p9_0,
  128728. 13,
  128729. 13
  128730. };
  128731. static static_codebook _44c7_s_p9_0 = {
  128732. 2, 169,
  128733. _vq_lengthlist__44c7_s_p9_0,
  128734. 1, -511845376, 1630791680, 4, 0,
  128735. _vq_quantlist__44c7_s_p9_0,
  128736. NULL,
  128737. &_vq_auxt__44c7_s_p9_0,
  128738. NULL,
  128739. 0
  128740. };
  128741. static long _vq_quantlist__44c7_s_p9_1[] = {
  128742. 6,
  128743. 5,
  128744. 7,
  128745. 4,
  128746. 8,
  128747. 3,
  128748. 9,
  128749. 2,
  128750. 10,
  128751. 1,
  128752. 11,
  128753. 0,
  128754. 12,
  128755. };
  128756. static long _vq_lengthlist__44c7_s_p9_1[] = {
  128757. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  128758. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  128759. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  128760. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  128761. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  128762. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  128763. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  128764. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  128765. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  128766. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  128767. 15,11,11,10,10,12,12,12,12,
  128768. };
  128769. static float _vq_quantthresh__44c7_s_p9_1[] = {
  128770. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  128771. 122.5, 171.5, 220.5, 269.5,
  128772. };
  128773. static long _vq_quantmap__44c7_s_p9_1[] = {
  128774. 11, 9, 7, 5, 3, 1, 0, 2,
  128775. 4, 6, 8, 10, 12,
  128776. };
  128777. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  128778. _vq_quantthresh__44c7_s_p9_1,
  128779. _vq_quantmap__44c7_s_p9_1,
  128780. 13,
  128781. 13
  128782. };
  128783. static static_codebook _44c7_s_p9_1 = {
  128784. 2, 169,
  128785. _vq_lengthlist__44c7_s_p9_1,
  128786. 1, -518889472, 1622704128, 4, 0,
  128787. _vq_quantlist__44c7_s_p9_1,
  128788. NULL,
  128789. &_vq_auxt__44c7_s_p9_1,
  128790. NULL,
  128791. 0
  128792. };
  128793. static long _vq_quantlist__44c7_s_p9_2[] = {
  128794. 24,
  128795. 23,
  128796. 25,
  128797. 22,
  128798. 26,
  128799. 21,
  128800. 27,
  128801. 20,
  128802. 28,
  128803. 19,
  128804. 29,
  128805. 18,
  128806. 30,
  128807. 17,
  128808. 31,
  128809. 16,
  128810. 32,
  128811. 15,
  128812. 33,
  128813. 14,
  128814. 34,
  128815. 13,
  128816. 35,
  128817. 12,
  128818. 36,
  128819. 11,
  128820. 37,
  128821. 10,
  128822. 38,
  128823. 9,
  128824. 39,
  128825. 8,
  128826. 40,
  128827. 7,
  128828. 41,
  128829. 6,
  128830. 42,
  128831. 5,
  128832. 43,
  128833. 4,
  128834. 44,
  128835. 3,
  128836. 45,
  128837. 2,
  128838. 46,
  128839. 1,
  128840. 47,
  128841. 0,
  128842. 48,
  128843. };
  128844. static long _vq_lengthlist__44c7_s_p9_2[] = {
  128845. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  128846. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128847. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128848. 7,
  128849. };
  128850. static float _vq_quantthresh__44c7_s_p9_2[] = {
  128851. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128852. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128853. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128854. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128855. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128856. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128857. };
  128858. static long _vq_quantmap__44c7_s_p9_2[] = {
  128859. 47, 45, 43, 41, 39, 37, 35, 33,
  128860. 31, 29, 27, 25, 23, 21, 19, 17,
  128861. 15, 13, 11, 9, 7, 5, 3, 1,
  128862. 0, 2, 4, 6, 8, 10, 12, 14,
  128863. 16, 18, 20, 22, 24, 26, 28, 30,
  128864. 32, 34, 36, 38, 40, 42, 44, 46,
  128865. 48,
  128866. };
  128867. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  128868. _vq_quantthresh__44c7_s_p9_2,
  128869. _vq_quantmap__44c7_s_p9_2,
  128870. 49,
  128871. 49
  128872. };
  128873. static static_codebook _44c7_s_p9_2 = {
  128874. 1, 49,
  128875. _vq_lengthlist__44c7_s_p9_2,
  128876. 1, -526909440, 1611661312, 6, 0,
  128877. _vq_quantlist__44c7_s_p9_2,
  128878. NULL,
  128879. &_vq_auxt__44c7_s_p9_2,
  128880. NULL,
  128881. 0
  128882. };
  128883. static long _huff_lengthlist__44c7_s_short[] = {
  128884. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  128885. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  128886. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  128887. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  128888. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  128889. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  128890. 10, 9,11,14,
  128891. };
  128892. static static_codebook _huff_book__44c7_s_short = {
  128893. 2, 100,
  128894. _huff_lengthlist__44c7_s_short,
  128895. 0, 0, 0, 0, 0,
  128896. NULL,
  128897. NULL,
  128898. NULL,
  128899. NULL,
  128900. 0
  128901. };
  128902. static long _huff_lengthlist__44c8_s_long[] = {
  128903. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  128904. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  128905. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  128906. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  128907. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  128908. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  128909. 11, 9, 9,10,
  128910. };
  128911. static static_codebook _huff_book__44c8_s_long = {
  128912. 2, 100,
  128913. _huff_lengthlist__44c8_s_long,
  128914. 0, 0, 0, 0, 0,
  128915. NULL,
  128916. NULL,
  128917. NULL,
  128918. NULL,
  128919. 0
  128920. };
  128921. static long _vq_quantlist__44c8_s_p1_0[] = {
  128922. 1,
  128923. 0,
  128924. 2,
  128925. };
  128926. static long _vq_lengthlist__44c8_s_p1_0[] = {
  128927. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  128928. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128929. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  128930. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128931. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  128932. 8,
  128933. };
  128934. static float _vq_quantthresh__44c8_s_p1_0[] = {
  128935. -0.5, 0.5,
  128936. };
  128937. static long _vq_quantmap__44c8_s_p1_0[] = {
  128938. 1, 0, 2,
  128939. };
  128940. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  128941. _vq_quantthresh__44c8_s_p1_0,
  128942. _vq_quantmap__44c8_s_p1_0,
  128943. 3,
  128944. 3
  128945. };
  128946. static static_codebook _44c8_s_p1_0 = {
  128947. 4, 81,
  128948. _vq_lengthlist__44c8_s_p1_0,
  128949. 1, -535822336, 1611661312, 2, 0,
  128950. _vq_quantlist__44c8_s_p1_0,
  128951. NULL,
  128952. &_vq_auxt__44c8_s_p1_0,
  128953. NULL,
  128954. 0
  128955. };
  128956. static long _vq_quantlist__44c8_s_p2_0[] = {
  128957. 2,
  128958. 1,
  128959. 3,
  128960. 0,
  128961. 4,
  128962. };
  128963. static long _vq_lengthlist__44c8_s_p2_0[] = {
  128964. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128965. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  128966. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  128967. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  128968. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  128969. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  128970. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  128971. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  128974. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  128975. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  128976. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  128977. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  128978. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  128979. 0,12,12,13,13, 0, 0, 0,12,13, 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, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  128982. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  128983. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  128984. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  128985. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  128986. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  128987. 13,13, 0, 0, 0,12,13, 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. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  128990. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  128991. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  128992. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  128993. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  128994. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  128995. 0, 0,13,13, 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, 9,
  129000. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  129001. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  129002. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  129003. 13,
  129004. };
  129005. static float _vq_quantthresh__44c8_s_p2_0[] = {
  129006. -1.5, -0.5, 0.5, 1.5,
  129007. };
  129008. static long _vq_quantmap__44c8_s_p2_0[] = {
  129009. 3, 1, 0, 2, 4,
  129010. };
  129011. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  129012. _vq_quantthresh__44c8_s_p2_0,
  129013. _vq_quantmap__44c8_s_p2_0,
  129014. 5,
  129015. 5
  129016. };
  129017. static static_codebook _44c8_s_p2_0 = {
  129018. 4, 625,
  129019. _vq_lengthlist__44c8_s_p2_0,
  129020. 1, -533725184, 1611661312, 3, 0,
  129021. _vq_quantlist__44c8_s_p2_0,
  129022. NULL,
  129023. &_vq_auxt__44c8_s_p2_0,
  129024. NULL,
  129025. 0
  129026. };
  129027. static long _vq_quantlist__44c8_s_p3_0[] = {
  129028. 4,
  129029. 3,
  129030. 5,
  129031. 2,
  129032. 6,
  129033. 1,
  129034. 7,
  129035. 0,
  129036. 8,
  129037. };
  129038. static long _vq_lengthlist__44c8_s_p3_0[] = {
  129039. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129040. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  129041. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  129042. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  129043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129044. 0,
  129045. };
  129046. static float _vq_quantthresh__44c8_s_p3_0[] = {
  129047. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129048. };
  129049. static long _vq_quantmap__44c8_s_p3_0[] = {
  129050. 7, 5, 3, 1, 0, 2, 4, 6,
  129051. 8,
  129052. };
  129053. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  129054. _vq_quantthresh__44c8_s_p3_0,
  129055. _vq_quantmap__44c8_s_p3_0,
  129056. 9,
  129057. 9
  129058. };
  129059. static static_codebook _44c8_s_p3_0 = {
  129060. 2, 81,
  129061. _vq_lengthlist__44c8_s_p3_0,
  129062. 1, -531628032, 1611661312, 4, 0,
  129063. _vq_quantlist__44c8_s_p3_0,
  129064. NULL,
  129065. &_vq_auxt__44c8_s_p3_0,
  129066. NULL,
  129067. 0
  129068. };
  129069. static long _vq_quantlist__44c8_s_p4_0[] = {
  129070. 8,
  129071. 7,
  129072. 9,
  129073. 6,
  129074. 10,
  129075. 5,
  129076. 11,
  129077. 4,
  129078. 12,
  129079. 3,
  129080. 13,
  129081. 2,
  129082. 14,
  129083. 1,
  129084. 15,
  129085. 0,
  129086. 16,
  129087. };
  129088. static long _vq_lengthlist__44c8_s_p4_0[] = {
  129089. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129090. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  129091. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  129092. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  129093. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  129094. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  129095. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  129096. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129097. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  129098. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  129099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129107. 0,
  129108. };
  129109. static float _vq_quantthresh__44c8_s_p4_0[] = {
  129110. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129111. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129112. };
  129113. static long _vq_quantmap__44c8_s_p4_0[] = {
  129114. 15, 13, 11, 9, 7, 5, 3, 1,
  129115. 0, 2, 4, 6, 8, 10, 12, 14,
  129116. 16,
  129117. };
  129118. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  129119. _vq_quantthresh__44c8_s_p4_0,
  129120. _vq_quantmap__44c8_s_p4_0,
  129121. 17,
  129122. 17
  129123. };
  129124. static static_codebook _44c8_s_p4_0 = {
  129125. 2, 289,
  129126. _vq_lengthlist__44c8_s_p4_0,
  129127. 1, -529530880, 1611661312, 5, 0,
  129128. _vq_quantlist__44c8_s_p4_0,
  129129. NULL,
  129130. &_vq_auxt__44c8_s_p4_0,
  129131. NULL,
  129132. 0
  129133. };
  129134. static long _vq_quantlist__44c8_s_p5_0[] = {
  129135. 1,
  129136. 0,
  129137. 2,
  129138. };
  129139. static long _vq_lengthlist__44c8_s_p5_0[] = {
  129140. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  129141. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  129142. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  129143. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  129144. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  129145. 12,
  129146. };
  129147. static float _vq_quantthresh__44c8_s_p5_0[] = {
  129148. -5.5, 5.5,
  129149. };
  129150. static long _vq_quantmap__44c8_s_p5_0[] = {
  129151. 1, 0, 2,
  129152. };
  129153. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  129154. _vq_quantthresh__44c8_s_p5_0,
  129155. _vq_quantmap__44c8_s_p5_0,
  129156. 3,
  129157. 3
  129158. };
  129159. static static_codebook _44c8_s_p5_0 = {
  129160. 4, 81,
  129161. _vq_lengthlist__44c8_s_p5_0,
  129162. 1, -529137664, 1618345984, 2, 0,
  129163. _vq_quantlist__44c8_s_p5_0,
  129164. NULL,
  129165. &_vq_auxt__44c8_s_p5_0,
  129166. NULL,
  129167. 0
  129168. };
  129169. static long _vq_quantlist__44c8_s_p5_1[] = {
  129170. 5,
  129171. 4,
  129172. 6,
  129173. 3,
  129174. 7,
  129175. 2,
  129176. 8,
  129177. 1,
  129178. 9,
  129179. 0,
  129180. 10,
  129181. };
  129182. static long _vq_lengthlist__44c8_s_p5_1[] = {
  129183. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  129184. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129185. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  129186. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  129187. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  129188. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  129189. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  129190. 11,11,11, 7, 7, 7, 7, 8, 8,
  129191. };
  129192. static float _vq_quantthresh__44c8_s_p5_1[] = {
  129193. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129194. 3.5, 4.5,
  129195. };
  129196. static long _vq_quantmap__44c8_s_p5_1[] = {
  129197. 9, 7, 5, 3, 1, 0, 2, 4,
  129198. 6, 8, 10,
  129199. };
  129200. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  129201. _vq_quantthresh__44c8_s_p5_1,
  129202. _vq_quantmap__44c8_s_p5_1,
  129203. 11,
  129204. 11
  129205. };
  129206. static static_codebook _44c8_s_p5_1 = {
  129207. 2, 121,
  129208. _vq_lengthlist__44c8_s_p5_1,
  129209. 1, -531365888, 1611661312, 4, 0,
  129210. _vq_quantlist__44c8_s_p5_1,
  129211. NULL,
  129212. &_vq_auxt__44c8_s_p5_1,
  129213. NULL,
  129214. 0
  129215. };
  129216. static long _vq_quantlist__44c8_s_p6_0[] = {
  129217. 6,
  129218. 5,
  129219. 7,
  129220. 4,
  129221. 8,
  129222. 3,
  129223. 9,
  129224. 2,
  129225. 10,
  129226. 1,
  129227. 11,
  129228. 0,
  129229. 12,
  129230. };
  129231. static long _vq_lengthlist__44c8_s_p6_0[] = {
  129232. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129233. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  129234. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  129235. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  129236. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  129237. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. };
  129244. static float _vq_quantthresh__44c8_s_p6_0[] = {
  129245. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129246. 12.5, 17.5, 22.5, 27.5,
  129247. };
  129248. static long _vq_quantmap__44c8_s_p6_0[] = {
  129249. 11, 9, 7, 5, 3, 1, 0, 2,
  129250. 4, 6, 8, 10, 12,
  129251. };
  129252. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  129253. _vq_quantthresh__44c8_s_p6_0,
  129254. _vq_quantmap__44c8_s_p6_0,
  129255. 13,
  129256. 13
  129257. };
  129258. static static_codebook _44c8_s_p6_0 = {
  129259. 2, 169,
  129260. _vq_lengthlist__44c8_s_p6_0,
  129261. 1, -526516224, 1616117760, 4, 0,
  129262. _vq_quantlist__44c8_s_p6_0,
  129263. NULL,
  129264. &_vq_auxt__44c8_s_p6_0,
  129265. NULL,
  129266. 0
  129267. };
  129268. static long _vq_quantlist__44c8_s_p6_1[] = {
  129269. 2,
  129270. 1,
  129271. 3,
  129272. 0,
  129273. 4,
  129274. };
  129275. static long _vq_lengthlist__44c8_s_p6_1[] = {
  129276. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  129277. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129278. };
  129279. static float _vq_quantthresh__44c8_s_p6_1[] = {
  129280. -1.5, -0.5, 0.5, 1.5,
  129281. };
  129282. static long _vq_quantmap__44c8_s_p6_1[] = {
  129283. 3, 1, 0, 2, 4,
  129284. };
  129285. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  129286. _vq_quantthresh__44c8_s_p6_1,
  129287. _vq_quantmap__44c8_s_p6_1,
  129288. 5,
  129289. 5
  129290. };
  129291. static static_codebook _44c8_s_p6_1 = {
  129292. 2, 25,
  129293. _vq_lengthlist__44c8_s_p6_1,
  129294. 1, -533725184, 1611661312, 3, 0,
  129295. _vq_quantlist__44c8_s_p6_1,
  129296. NULL,
  129297. &_vq_auxt__44c8_s_p6_1,
  129298. NULL,
  129299. 0
  129300. };
  129301. static long _vq_quantlist__44c8_s_p7_0[] = {
  129302. 6,
  129303. 5,
  129304. 7,
  129305. 4,
  129306. 8,
  129307. 3,
  129308. 9,
  129309. 2,
  129310. 10,
  129311. 1,
  129312. 11,
  129313. 0,
  129314. 12,
  129315. };
  129316. static long _vq_lengthlist__44c8_s_p7_0[] = {
  129317. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  129318. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  129319. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  129320. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  129321. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  129322. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  129323. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  129324. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  129325. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  129326. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  129327. 20,13,13,13,13,14,13,15,15,
  129328. };
  129329. static float _vq_quantthresh__44c8_s_p7_0[] = {
  129330. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  129331. 27.5, 38.5, 49.5, 60.5,
  129332. };
  129333. static long _vq_quantmap__44c8_s_p7_0[] = {
  129334. 11, 9, 7, 5, 3, 1, 0, 2,
  129335. 4, 6, 8, 10, 12,
  129336. };
  129337. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  129338. _vq_quantthresh__44c8_s_p7_0,
  129339. _vq_quantmap__44c8_s_p7_0,
  129340. 13,
  129341. 13
  129342. };
  129343. static static_codebook _44c8_s_p7_0 = {
  129344. 2, 169,
  129345. _vq_lengthlist__44c8_s_p7_0,
  129346. 1, -523206656, 1618345984, 4, 0,
  129347. _vq_quantlist__44c8_s_p7_0,
  129348. NULL,
  129349. &_vq_auxt__44c8_s_p7_0,
  129350. NULL,
  129351. 0
  129352. };
  129353. static long _vq_quantlist__44c8_s_p7_1[] = {
  129354. 5,
  129355. 4,
  129356. 6,
  129357. 3,
  129358. 7,
  129359. 2,
  129360. 8,
  129361. 1,
  129362. 9,
  129363. 0,
  129364. 10,
  129365. };
  129366. static long _vq_lengthlist__44c8_s_p7_1[] = {
  129367. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  129368. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  129369. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  129370. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129371. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  129372. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  129373. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  129374. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129375. };
  129376. static float _vq_quantthresh__44c8_s_p7_1[] = {
  129377. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129378. 3.5, 4.5,
  129379. };
  129380. static long _vq_quantmap__44c8_s_p7_1[] = {
  129381. 9, 7, 5, 3, 1, 0, 2, 4,
  129382. 6, 8, 10,
  129383. };
  129384. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  129385. _vq_quantthresh__44c8_s_p7_1,
  129386. _vq_quantmap__44c8_s_p7_1,
  129387. 11,
  129388. 11
  129389. };
  129390. static static_codebook _44c8_s_p7_1 = {
  129391. 2, 121,
  129392. _vq_lengthlist__44c8_s_p7_1,
  129393. 1, -531365888, 1611661312, 4, 0,
  129394. _vq_quantlist__44c8_s_p7_1,
  129395. NULL,
  129396. &_vq_auxt__44c8_s_p7_1,
  129397. NULL,
  129398. 0
  129399. };
  129400. static long _vq_quantlist__44c8_s_p8_0[] = {
  129401. 7,
  129402. 6,
  129403. 8,
  129404. 5,
  129405. 9,
  129406. 4,
  129407. 10,
  129408. 3,
  129409. 11,
  129410. 2,
  129411. 12,
  129412. 1,
  129413. 13,
  129414. 0,
  129415. 14,
  129416. };
  129417. static long _vq_lengthlist__44c8_s_p8_0[] = {
  129418. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  129419. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  129420. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  129421. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  129422. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  129423. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  129424. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  129425. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  129426. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  129427. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  129428. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  129429. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  129430. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  129431. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  129432. 15,
  129433. };
  129434. static float _vq_quantthresh__44c8_s_p8_0[] = {
  129435. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  129436. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  129437. };
  129438. static long _vq_quantmap__44c8_s_p8_0[] = {
  129439. 13, 11, 9, 7, 5, 3, 1, 0,
  129440. 2, 4, 6, 8, 10, 12, 14,
  129441. };
  129442. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  129443. _vq_quantthresh__44c8_s_p8_0,
  129444. _vq_quantmap__44c8_s_p8_0,
  129445. 15,
  129446. 15
  129447. };
  129448. static static_codebook _44c8_s_p8_0 = {
  129449. 2, 225,
  129450. _vq_lengthlist__44c8_s_p8_0,
  129451. 1, -520986624, 1620377600, 4, 0,
  129452. _vq_quantlist__44c8_s_p8_0,
  129453. NULL,
  129454. &_vq_auxt__44c8_s_p8_0,
  129455. NULL,
  129456. 0
  129457. };
  129458. static long _vq_quantlist__44c8_s_p8_1[] = {
  129459. 10,
  129460. 9,
  129461. 11,
  129462. 8,
  129463. 12,
  129464. 7,
  129465. 13,
  129466. 6,
  129467. 14,
  129468. 5,
  129469. 15,
  129470. 4,
  129471. 16,
  129472. 3,
  129473. 17,
  129474. 2,
  129475. 18,
  129476. 1,
  129477. 19,
  129478. 0,
  129479. 20,
  129480. };
  129481. static long _vq_lengthlist__44c8_s_p8_1[] = {
  129482. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  129483. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  129484. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  129485. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  129486. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129487. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  129488. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  129489. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  129490. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129491. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129492. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  129493. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  129494. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  129495. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129496. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  129497. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  129498. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  129499. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  129500. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  129501. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  129502. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  129503. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  129504. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  129505. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  129506. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  129507. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  129508. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  129509. 10, 9, 9,10,10, 9,10, 9, 9,
  129510. };
  129511. static float _vq_quantthresh__44c8_s_p8_1[] = {
  129512. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129513. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129514. 6.5, 7.5, 8.5, 9.5,
  129515. };
  129516. static long _vq_quantmap__44c8_s_p8_1[] = {
  129517. 19, 17, 15, 13, 11, 9, 7, 5,
  129518. 3, 1, 0, 2, 4, 6, 8, 10,
  129519. 12, 14, 16, 18, 20,
  129520. };
  129521. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  129522. _vq_quantthresh__44c8_s_p8_1,
  129523. _vq_quantmap__44c8_s_p8_1,
  129524. 21,
  129525. 21
  129526. };
  129527. static static_codebook _44c8_s_p8_1 = {
  129528. 2, 441,
  129529. _vq_lengthlist__44c8_s_p8_1,
  129530. 1, -529268736, 1611661312, 5, 0,
  129531. _vq_quantlist__44c8_s_p8_1,
  129532. NULL,
  129533. &_vq_auxt__44c8_s_p8_1,
  129534. NULL,
  129535. 0
  129536. };
  129537. static long _vq_quantlist__44c8_s_p9_0[] = {
  129538. 8,
  129539. 7,
  129540. 9,
  129541. 6,
  129542. 10,
  129543. 5,
  129544. 11,
  129545. 4,
  129546. 12,
  129547. 3,
  129548. 13,
  129549. 2,
  129550. 14,
  129551. 1,
  129552. 15,
  129553. 0,
  129554. 16,
  129555. };
  129556. static long _vq_lengthlist__44c8_s_p9_0[] = {
  129557. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129558. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  129559. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  129560. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129561. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129562. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129563. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129564. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129565. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129566. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129567. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129568. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129569. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129570. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129571. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129572. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129573. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129574. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129575. 10,
  129576. };
  129577. static float _vq_quantthresh__44c8_s_p9_0[] = {
  129578. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  129579. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  129580. };
  129581. static long _vq_quantmap__44c8_s_p9_0[] = {
  129582. 15, 13, 11, 9, 7, 5, 3, 1,
  129583. 0, 2, 4, 6, 8, 10, 12, 14,
  129584. 16,
  129585. };
  129586. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  129587. _vq_quantthresh__44c8_s_p9_0,
  129588. _vq_quantmap__44c8_s_p9_0,
  129589. 17,
  129590. 17
  129591. };
  129592. static static_codebook _44c8_s_p9_0 = {
  129593. 2, 289,
  129594. _vq_lengthlist__44c8_s_p9_0,
  129595. 1, -509798400, 1631393792, 5, 0,
  129596. _vq_quantlist__44c8_s_p9_0,
  129597. NULL,
  129598. &_vq_auxt__44c8_s_p9_0,
  129599. NULL,
  129600. 0
  129601. };
  129602. static long _vq_quantlist__44c8_s_p9_1[] = {
  129603. 9,
  129604. 8,
  129605. 10,
  129606. 7,
  129607. 11,
  129608. 6,
  129609. 12,
  129610. 5,
  129611. 13,
  129612. 4,
  129613. 14,
  129614. 3,
  129615. 15,
  129616. 2,
  129617. 16,
  129618. 1,
  129619. 17,
  129620. 0,
  129621. 18,
  129622. };
  129623. static long _vq_lengthlist__44c8_s_p9_1[] = {
  129624. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  129625. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  129626. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  129627. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  129628. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  129629. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  129630. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  129631. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  129632. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  129633. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  129634. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  129635. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  129636. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  129637. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  129638. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  129639. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  129640. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  129641. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  129642. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  129643. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  129644. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  129645. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  129646. 14,13,13,14,14,15,14,15,14,
  129647. };
  129648. static float _vq_quantthresh__44c8_s_p9_1[] = {
  129649. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  129650. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  129651. 367.5, 416.5,
  129652. };
  129653. static long _vq_quantmap__44c8_s_p9_1[] = {
  129654. 17, 15, 13, 11, 9, 7, 5, 3,
  129655. 1, 0, 2, 4, 6, 8, 10, 12,
  129656. 14, 16, 18,
  129657. };
  129658. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  129659. _vq_quantthresh__44c8_s_p9_1,
  129660. _vq_quantmap__44c8_s_p9_1,
  129661. 19,
  129662. 19
  129663. };
  129664. static static_codebook _44c8_s_p9_1 = {
  129665. 2, 361,
  129666. _vq_lengthlist__44c8_s_p9_1,
  129667. 1, -518287360, 1622704128, 5, 0,
  129668. _vq_quantlist__44c8_s_p9_1,
  129669. NULL,
  129670. &_vq_auxt__44c8_s_p9_1,
  129671. NULL,
  129672. 0
  129673. };
  129674. static long _vq_quantlist__44c8_s_p9_2[] = {
  129675. 24,
  129676. 23,
  129677. 25,
  129678. 22,
  129679. 26,
  129680. 21,
  129681. 27,
  129682. 20,
  129683. 28,
  129684. 19,
  129685. 29,
  129686. 18,
  129687. 30,
  129688. 17,
  129689. 31,
  129690. 16,
  129691. 32,
  129692. 15,
  129693. 33,
  129694. 14,
  129695. 34,
  129696. 13,
  129697. 35,
  129698. 12,
  129699. 36,
  129700. 11,
  129701. 37,
  129702. 10,
  129703. 38,
  129704. 9,
  129705. 39,
  129706. 8,
  129707. 40,
  129708. 7,
  129709. 41,
  129710. 6,
  129711. 42,
  129712. 5,
  129713. 43,
  129714. 4,
  129715. 44,
  129716. 3,
  129717. 45,
  129718. 2,
  129719. 46,
  129720. 1,
  129721. 47,
  129722. 0,
  129723. 48,
  129724. };
  129725. static long _vq_lengthlist__44c8_s_p9_2[] = {
  129726. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  129727. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129728. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129729. 7,
  129730. };
  129731. static float _vq_quantthresh__44c8_s_p9_2[] = {
  129732. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  129733. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  129734. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129735. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129736. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  129737. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  129738. };
  129739. static long _vq_quantmap__44c8_s_p9_2[] = {
  129740. 47, 45, 43, 41, 39, 37, 35, 33,
  129741. 31, 29, 27, 25, 23, 21, 19, 17,
  129742. 15, 13, 11, 9, 7, 5, 3, 1,
  129743. 0, 2, 4, 6, 8, 10, 12, 14,
  129744. 16, 18, 20, 22, 24, 26, 28, 30,
  129745. 32, 34, 36, 38, 40, 42, 44, 46,
  129746. 48,
  129747. };
  129748. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  129749. _vq_quantthresh__44c8_s_p9_2,
  129750. _vq_quantmap__44c8_s_p9_2,
  129751. 49,
  129752. 49
  129753. };
  129754. static static_codebook _44c8_s_p9_2 = {
  129755. 1, 49,
  129756. _vq_lengthlist__44c8_s_p9_2,
  129757. 1, -526909440, 1611661312, 6, 0,
  129758. _vq_quantlist__44c8_s_p9_2,
  129759. NULL,
  129760. &_vq_auxt__44c8_s_p9_2,
  129761. NULL,
  129762. 0
  129763. };
  129764. static long _huff_lengthlist__44c8_s_short[] = {
  129765. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  129766. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  129767. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  129768. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  129769. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  129770. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  129771. 10, 9,11,14,
  129772. };
  129773. static static_codebook _huff_book__44c8_s_short = {
  129774. 2, 100,
  129775. _huff_lengthlist__44c8_s_short,
  129776. 0, 0, 0, 0, 0,
  129777. NULL,
  129778. NULL,
  129779. NULL,
  129780. NULL,
  129781. 0
  129782. };
  129783. static long _huff_lengthlist__44c9_s_long[] = {
  129784. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  129785. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  129786. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  129787. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  129788. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  129789. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  129790. 10, 9, 8, 9,
  129791. };
  129792. static static_codebook _huff_book__44c9_s_long = {
  129793. 2, 100,
  129794. _huff_lengthlist__44c9_s_long,
  129795. 0, 0, 0, 0, 0,
  129796. NULL,
  129797. NULL,
  129798. NULL,
  129799. NULL,
  129800. 0
  129801. };
  129802. static long _vq_quantlist__44c9_s_p1_0[] = {
  129803. 1,
  129804. 0,
  129805. 2,
  129806. };
  129807. static long _vq_lengthlist__44c9_s_p1_0[] = {
  129808. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  129809. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  129810. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  129811. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  129812. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  129813. 7,
  129814. };
  129815. static float _vq_quantthresh__44c9_s_p1_0[] = {
  129816. -0.5, 0.5,
  129817. };
  129818. static long _vq_quantmap__44c9_s_p1_0[] = {
  129819. 1, 0, 2,
  129820. };
  129821. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  129822. _vq_quantthresh__44c9_s_p1_0,
  129823. _vq_quantmap__44c9_s_p1_0,
  129824. 3,
  129825. 3
  129826. };
  129827. static static_codebook _44c9_s_p1_0 = {
  129828. 4, 81,
  129829. _vq_lengthlist__44c9_s_p1_0,
  129830. 1, -535822336, 1611661312, 2, 0,
  129831. _vq_quantlist__44c9_s_p1_0,
  129832. NULL,
  129833. &_vq_auxt__44c9_s_p1_0,
  129834. NULL,
  129835. 0
  129836. };
  129837. static long _vq_quantlist__44c9_s_p2_0[] = {
  129838. 2,
  129839. 1,
  129840. 3,
  129841. 0,
  129842. 4,
  129843. };
  129844. static long _vq_lengthlist__44c9_s_p2_0[] = {
  129845. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  129846. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  129847. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  129848. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  129849. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  129850. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  129851. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  129852. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 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, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  129855. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  129856. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  129857. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  129858. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  129859. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  129860. 0,12,12,12,12, 0, 0, 0,12,12, 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, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  129863. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  129864. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  129865. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  129866. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  129867. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  129868. 12,12, 0, 0, 0,12,12, 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. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  129871. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  129872. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  129873. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  129874. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  129875. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  129876. 0, 0,12,13, 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, 9,
  129881. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  129882. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  129883. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  129884. 12,
  129885. };
  129886. static float _vq_quantthresh__44c9_s_p2_0[] = {
  129887. -1.5, -0.5, 0.5, 1.5,
  129888. };
  129889. static long _vq_quantmap__44c9_s_p2_0[] = {
  129890. 3, 1, 0, 2, 4,
  129891. };
  129892. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  129893. _vq_quantthresh__44c9_s_p2_0,
  129894. _vq_quantmap__44c9_s_p2_0,
  129895. 5,
  129896. 5
  129897. };
  129898. static static_codebook _44c9_s_p2_0 = {
  129899. 4, 625,
  129900. _vq_lengthlist__44c9_s_p2_0,
  129901. 1, -533725184, 1611661312, 3, 0,
  129902. _vq_quantlist__44c9_s_p2_0,
  129903. NULL,
  129904. &_vq_auxt__44c9_s_p2_0,
  129905. NULL,
  129906. 0
  129907. };
  129908. static long _vq_quantlist__44c9_s_p3_0[] = {
  129909. 4,
  129910. 3,
  129911. 5,
  129912. 2,
  129913. 6,
  129914. 1,
  129915. 7,
  129916. 0,
  129917. 8,
  129918. };
  129919. static long _vq_lengthlist__44c9_s_p3_0[] = {
  129920. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  129921. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  129922. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  129923. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  129924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129925. 0,
  129926. };
  129927. static float _vq_quantthresh__44c9_s_p3_0[] = {
  129928. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129929. };
  129930. static long _vq_quantmap__44c9_s_p3_0[] = {
  129931. 7, 5, 3, 1, 0, 2, 4, 6,
  129932. 8,
  129933. };
  129934. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  129935. _vq_quantthresh__44c9_s_p3_0,
  129936. _vq_quantmap__44c9_s_p3_0,
  129937. 9,
  129938. 9
  129939. };
  129940. static static_codebook _44c9_s_p3_0 = {
  129941. 2, 81,
  129942. _vq_lengthlist__44c9_s_p3_0,
  129943. 1, -531628032, 1611661312, 4, 0,
  129944. _vq_quantlist__44c9_s_p3_0,
  129945. NULL,
  129946. &_vq_auxt__44c9_s_p3_0,
  129947. NULL,
  129948. 0
  129949. };
  129950. static long _vq_quantlist__44c9_s_p4_0[] = {
  129951. 8,
  129952. 7,
  129953. 9,
  129954. 6,
  129955. 10,
  129956. 5,
  129957. 11,
  129958. 4,
  129959. 12,
  129960. 3,
  129961. 13,
  129962. 2,
  129963. 14,
  129964. 1,
  129965. 15,
  129966. 0,
  129967. 16,
  129968. };
  129969. static long _vq_lengthlist__44c9_s_p4_0[] = {
  129970. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  129971. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  129972. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  129973. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  129974. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  129975. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  129976. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  129977. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129978. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  129979. 9,10,10,11,11,12,12,12,12, 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,
  129989. };
  129990. static float _vq_quantthresh__44c9_s_p4_0[] = {
  129991. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129992. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129993. };
  129994. static long _vq_quantmap__44c9_s_p4_0[] = {
  129995. 15, 13, 11, 9, 7, 5, 3, 1,
  129996. 0, 2, 4, 6, 8, 10, 12, 14,
  129997. 16,
  129998. };
  129999. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  130000. _vq_quantthresh__44c9_s_p4_0,
  130001. _vq_quantmap__44c9_s_p4_0,
  130002. 17,
  130003. 17
  130004. };
  130005. static static_codebook _44c9_s_p4_0 = {
  130006. 2, 289,
  130007. _vq_lengthlist__44c9_s_p4_0,
  130008. 1, -529530880, 1611661312, 5, 0,
  130009. _vq_quantlist__44c9_s_p4_0,
  130010. NULL,
  130011. &_vq_auxt__44c9_s_p4_0,
  130012. NULL,
  130013. 0
  130014. };
  130015. static long _vq_quantlist__44c9_s_p5_0[] = {
  130016. 1,
  130017. 0,
  130018. 2,
  130019. };
  130020. static long _vq_lengthlist__44c9_s_p5_0[] = {
  130021. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  130022. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  130023. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  130024. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  130025. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  130026. 12,
  130027. };
  130028. static float _vq_quantthresh__44c9_s_p5_0[] = {
  130029. -5.5, 5.5,
  130030. };
  130031. static long _vq_quantmap__44c9_s_p5_0[] = {
  130032. 1, 0, 2,
  130033. };
  130034. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  130035. _vq_quantthresh__44c9_s_p5_0,
  130036. _vq_quantmap__44c9_s_p5_0,
  130037. 3,
  130038. 3
  130039. };
  130040. static static_codebook _44c9_s_p5_0 = {
  130041. 4, 81,
  130042. _vq_lengthlist__44c9_s_p5_0,
  130043. 1, -529137664, 1618345984, 2, 0,
  130044. _vq_quantlist__44c9_s_p5_0,
  130045. NULL,
  130046. &_vq_auxt__44c9_s_p5_0,
  130047. NULL,
  130048. 0
  130049. };
  130050. static long _vq_quantlist__44c9_s_p5_1[] = {
  130051. 5,
  130052. 4,
  130053. 6,
  130054. 3,
  130055. 7,
  130056. 2,
  130057. 8,
  130058. 1,
  130059. 9,
  130060. 0,
  130061. 10,
  130062. };
  130063. static long _vq_lengthlist__44c9_s_p5_1[] = {
  130064. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  130065. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  130066. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  130067. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  130068. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  130069. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  130070. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  130071. 11,11,11, 7, 7, 7, 7, 7, 7,
  130072. };
  130073. static float _vq_quantthresh__44c9_s_p5_1[] = {
  130074. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130075. 3.5, 4.5,
  130076. };
  130077. static long _vq_quantmap__44c9_s_p5_1[] = {
  130078. 9, 7, 5, 3, 1, 0, 2, 4,
  130079. 6, 8, 10,
  130080. };
  130081. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  130082. _vq_quantthresh__44c9_s_p5_1,
  130083. _vq_quantmap__44c9_s_p5_1,
  130084. 11,
  130085. 11
  130086. };
  130087. static static_codebook _44c9_s_p5_1 = {
  130088. 2, 121,
  130089. _vq_lengthlist__44c9_s_p5_1,
  130090. 1, -531365888, 1611661312, 4, 0,
  130091. _vq_quantlist__44c9_s_p5_1,
  130092. NULL,
  130093. &_vq_auxt__44c9_s_p5_1,
  130094. NULL,
  130095. 0
  130096. };
  130097. static long _vq_quantlist__44c9_s_p6_0[] = {
  130098. 6,
  130099. 5,
  130100. 7,
  130101. 4,
  130102. 8,
  130103. 3,
  130104. 9,
  130105. 2,
  130106. 10,
  130107. 1,
  130108. 11,
  130109. 0,
  130110. 12,
  130111. };
  130112. static long _vq_lengthlist__44c9_s_p6_0[] = {
  130113. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  130114. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  130115. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  130116. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  130117. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  130118. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  130119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130123. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130124. };
  130125. static float _vq_quantthresh__44c9_s_p6_0[] = {
  130126. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130127. 12.5, 17.5, 22.5, 27.5,
  130128. };
  130129. static long _vq_quantmap__44c9_s_p6_0[] = {
  130130. 11, 9, 7, 5, 3, 1, 0, 2,
  130131. 4, 6, 8, 10, 12,
  130132. };
  130133. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  130134. _vq_quantthresh__44c9_s_p6_0,
  130135. _vq_quantmap__44c9_s_p6_0,
  130136. 13,
  130137. 13
  130138. };
  130139. static static_codebook _44c9_s_p6_0 = {
  130140. 2, 169,
  130141. _vq_lengthlist__44c9_s_p6_0,
  130142. 1, -526516224, 1616117760, 4, 0,
  130143. _vq_quantlist__44c9_s_p6_0,
  130144. NULL,
  130145. &_vq_auxt__44c9_s_p6_0,
  130146. NULL,
  130147. 0
  130148. };
  130149. static long _vq_quantlist__44c9_s_p6_1[] = {
  130150. 2,
  130151. 1,
  130152. 3,
  130153. 0,
  130154. 4,
  130155. };
  130156. static long _vq_lengthlist__44c9_s_p6_1[] = {
  130157. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  130158. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  130159. };
  130160. static float _vq_quantthresh__44c9_s_p6_1[] = {
  130161. -1.5, -0.5, 0.5, 1.5,
  130162. };
  130163. static long _vq_quantmap__44c9_s_p6_1[] = {
  130164. 3, 1, 0, 2, 4,
  130165. };
  130166. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  130167. _vq_quantthresh__44c9_s_p6_1,
  130168. _vq_quantmap__44c9_s_p6_1,
  130169. 5,
  130170. 5
  130171. };
  130172. static static_codebook _44c9_s_p6_1 = {
  130173. 2, 25,
  130174. _vq_lengthlist__44c9_s_p6_1,
  130175. 1, -533725184, 1611661312, 3, 0,
  130176. _vq_quantlist__44c9_s_p6_1,
  130177. NULL,
  130178. &_vq_auxt__44c9_s_p6_1,
  130179. NULL,
  130180. 0
  130181. };
  130182. static long _vq_quantlist__44c9_s_p7_0[] = {
  130183. 6,
  130184. 5,
  130185. 7,
  130186. 4,
  130187. 8,
  130188. 3,
  130189. 9,
  130190. 2,
  130191. 10,
  130192. 1,
  130193. 11,
  130194. 0,
  130195. 12,
  130196. };
  130197. static long _vq_lengthlist__44c9_s_p7_0[] = {
  130198. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  130199. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  130200. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  130201. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  130202. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  130203. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  130204. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  130205. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  130206. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  130207. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  130208. 19,12,12,12,12,13,13,14,14,
  130209. };
  130210. static float _vq_quantthresh__44c9_s_p7_0[] = {
  130211. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  130212. 27.5, 38.5, 49.5, 60.5,
  130213. };
  130214. static long _vq_quantmap__44c9_s_p7_0[] = {
  130215. 11, 9, 7, 5, 3, 1, 0, 2,
  130216. 4, 6, 8, 10, 12,
  130217. };
  130218. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  130219. _vq_quantthresh__44c9_s_p7_0,
  130220. _vq_quantmap__44c9_s_p7_0,
  130221. 13,
  130222. 13
  130223. };
  130224. static static_codebook _44c9_s_p7_0 = {
  130225. 2, 169,
  130226. _vq_lengthlist__44c9_s_p7_0,
  130227. 1, -523206656, 1618345984, 4, 0,
  130228. _vq_quantlist__44c9_s_p7_0,
  130229. NULL,
  130230. &_vq_auxt__44c9_s_p7_0,
  130231. NULL,
  130232. 0
  130233. };
  130234. static long _vq_quantlist__44c9_s_p7_1[] = {
  130235. 5,
  130236. 4,
  130237. 6,
  130238. 3,
  130239. 7,
  130240. 2,
  130241. 8,
  130242. 1,
  130243. 9,
  130244. 0,
  130245. 10,
  130246. };
  130247. static long _vq_lengthlist__44c9_s_p7_1[] = {
  130248. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  130249. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  130250. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  130251. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130252. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  130253. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  130254. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  130255. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130256. };
  130257. static float _vq_quantthresh__44c9_s_p7_1[] = {
  130258. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130259. 3.5, 4.5,
  130260. };
  130261. static long _vq_quantmap__44c9_s_p7_1[] = {
  130262. 9, 7, 5, 3, 1, 0, 2, 4,
  130263. 6, 8, 10,
  130264. };
  130265. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  130266. _vq_quantthresh__44c9_s_p7_1,
  130267. _vq_quantmap__44c9_s_p7_1,
  130268. 11,
  130269. 11
  130270. };
  130271. static static_codebook _44c9_s_p7_1 = {
  130272. 2, 121,
  130273. _vq_lengthlist__44c9_s_p7_1,
  130274. 1, -531365888, 1611661312, 4, 0,
  130275. _vq_quantlist__44c9_s_p7_1,
  130276. NULL,
  130277. &_vq_auxt__44c9_s_p7_1,
  130278. NULL,
  130279. 0
  130280. };
  130281. static long _vq_quantlist__44c9_s_p8_0[] = {
  130282. 7,
  130283. 6,
  130284. 8,
  130285. 5,
  130286. 9,
  130287. 4,
  130288. 10,
  130289. 3,
  130290. 11,
  130291. 2,
  130292. 12,
  130293. 1,
  130294. 13,
  130295. 0,
  130296. 14,
  130297. };
  130298. static long _vq_lengthlist__44c9_s_p8_0[] = {
  130299. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  130300. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  130301. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  130302. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  130303. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  130304. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  130305. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  130306. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  130307. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  130308. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  130309. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  130310. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  130311. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  130312. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  130313. 14,
  130314. };
  130315. static float _vq_quantthresh__44c9_s_p8_0[] = {
  130316. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130317. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130318. };
  130319. static long _vq_quantmap__44c9_s_p8_0[] = {
  130320. 13, 11, 9, 7, 5, 3, 1, 0,
  130321. 2, 4, 6, 8, 10, 12, 14,
  130322. };
  130323. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  130324. _vq_quantthresh__44c9_s_p8_0,
  130325. _vq_quantmap__44c9_s_p8_0,
  130326. 15,
  130327. 15
  130328. };
  130329. static static_codebook _44c9_s_p8_0 = {
  130330. 2, 225,
  130331. _vq_lengthlist__44c9_s_p8_0,
  130332. 1, -520986624, 1620377600, 4, 0,
  130333. _vq_quantlist__44c9_s_p8_0,
  130334. NULL,
  130335. &_vq_auxt__44c9_s_p8_0,
  130336. NULL,
  130337. 0
  130338. };
  130339. static long _vq_quantlist__44c9_s_p8_1[] = {
  130340. 10,
  130341. 9,
  130342. 11,
  130343. 8,
  130344. 12,
  130345. 7,
  130346. 13,
  130347. 6,
  130348. 14,
  130349. 5,
  130350. 15,
  130351. 4,
  130352. 16,
  130353. 3,
  130354. 17,
  130355. 2,
  130356. 18,
  130357. 1,
  130358. 19,
  130359. 0,
  130360. 20,
  130361. };
  130362. static long _vq_lengthlist__44c9_s_p8_1[] = {
  130363. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  130364. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130365. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  130366. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  130367. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130368. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  130369. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  130370. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  130371. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130372. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130373. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  130374. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130375. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130376. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130377. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  130378. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  130379. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  130380. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  130381. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  130382. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  130383. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  130384. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  130385. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  130386. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  130387. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  130388. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  130389. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  130390. 9, 9, 9,10, 9, 9, 9, 9, 9,
  130391. };
  130392. static float _vq_quantthresh__44c9_s_p8_1[] = {
  130393. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130394. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130395. 6.5, 7.5, 8.5, 9.5,
  130396. };
  130397. static long _vq_quantmap__44c9_s_p8_1[] = {
  130398. 19, 17, 15, 13, 11, 9, 7, 5,
  130399. 3, 1, 0, 2, 4, 6, 8, 10,
  130400. 12, 14, 16, 18, 20,
  130401. };
  130402. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  130403. _vq_quantthresh__44c9_s_p8_1,
  130404. _vq_quantmap__44c9_s_p8_1,
  130405. 21,
  130406. 21
  130407. };
  130408. static static_codebook _44c9_s_p8_1 = {
  130409. 2, 441,
  130410. _vq_lengthlist__44c9_s_p8_1,
  130411. 1, -529268736, 1611661312, 5, 0,
  130412. _vq_quantlist__44c9_s_p8_1,
  130413. NULL,
  130414. &_vq_auxt__44c9_s_p8_1,
  130415. NULL,
  130416. 0
  130417. };
  130418. static long _vq_quantlist__44c9_s_p9_0[] = {
  130419. 9,
  130420. 8,
  130421. 10,
  130422. 7,
  130423. 11,
  130424. 6,
  130425. 12,
  130426. 5,
  130427. 13,
  130428. 4,
  130429. 14,
  130430. 3,
  130431. 15,
  130432. 2,
  130433. 16,
  130434. 1,
  130435. 17,
  130436. 0,
  130437. 18,
  130438. };
  130439. static long _vq_lengthlist__44c9_s_p9_0[] = {
  130440. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130441. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  130442. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  130443. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  130444. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130445. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130446. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130447. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130448. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130449. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130450. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130451. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130452. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130453. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130454. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130455. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130456. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  130457. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130458. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130459. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130460. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130461. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130462. 11,11,11,11,11,11,11,11,11,
  130463. };
  130464. static float _vq_quantthresh__44c9_s_p9_0[] = {
  130465. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  130466. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  130467. 6982.5, 7913.5,
  130468. };
  130469. static long _vq_quantmap__44c9_s_p9_0[] = {
  130470. 17, 15, 13, 11, 9, 7, 5, 3,
  130471. 1, 0, 2, 4, 6, 8, 10, 12,
  130472. 14, 16, 18,
  130473. };
  130474. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  130475. _vq_quantthresh__44c9_s_p9_0,
  130476. _vq_quantmap__44c9_s_p9_0,
  130477. 19,
  130478. 19
  130479. };
  130480. static static_codebook _44c9_s_p9_0 = {
  130481. 2, 361,
  130482. _vq_lengthlist__44c9_s_p9_0,
  130483. 1, -508535424, 1631393792, 5, 0,
  130484. _vq_quantlist__44c9_s_p9_0,
  130485. NULL,
  130486. &_vq_auxt__44c9_s_p9_0,
  130487. NULL,
  130488. 0
  130489. };
  130490. static long _vq_quantlist__44c9_s_p9_1[] = {
  130491. 9,
  130492. 8,
  130493. 10,
  130494. 7,
  130495. 11,
  130496. 6,
  130497. 12,
  130498. 5,
  130499. 13,
  130500. 4,
  130501. 14,
  130502. 3,
  130503. 15,
  130504. 2,
  130505. 16,
  130506. 1,
  130507. 17,
  130508. 0,
  130509. 18,
  130510. };
  130511. static long _vq_lengthlist__44c9_s_p9_1[] = {
  130512. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  130513. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  130514. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  130515. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  130516. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  130517. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  130518. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  130519. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  130520. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  130521. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  130522. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  130523. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  130524. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  130525. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  130526. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  130527. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  130528. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  130529. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  130530. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  130531. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  130532. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  130533. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  130534. 13,13,13,14,13,14,15,15,15,
  130535. };
  130536. static float _vq_quantthresh__44c9_s_p9_1[] = {
  130537. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  130538. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  130539. 367.5, 416.5,
  130540. };
  130541. static long _vq_quantmap__44c9_s_p9_1[] = {
  130542. 17, 15, 13, 11, 9, 7, 5, 3,
  130543. 1, 0, 2, 4, 6, 8, 10, 12,
  130544. 14, 16, 18,
  130545. };
  130546. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  130547. _vq_quantthresh__44c9_s_p9_1,
  130548. _vq_quantmap__44c9_s_p9_1,
  130549. 19,
  130550. 19
  130551. };
  130552. static static_codebook _44c9_s_p9_1 = {
  130553. 2, 361,
  130554. _vq_lengthlist__44c9_s_p9_1,
  130555. 1, -518287360, 1622704128, 5, 0,
  130556. _vq_quantlist__44c9_s_p9_1,
  130557. NULL,
  130558. &_vq_auxt__44c9_s_p9_1,
  130559. NULL,
  130560. 0
  130561. };
  130562. static long _vq_quantlist__44c9_s_p9_2[] = {
  130563. 24,
  130564. 23,
  130565. 25,
  130566. 22,
  130567. 26,
  130568. 21,
  130569. 27,
  130570. 20,
  130571. 28,
  130572. 19,
  130573. 29,
  130574. 18,
  130575. 30,
  130576. 17,
  130577. 31,
  130578. 16,
  130579. 32,
  130580. 15,
  130581. 33,
  130582. 14,
  130583. 34,
  130584. 13,
  130585. 35,
  130586. 12,
  130587. 36,
  130588. 11,
  130589. 37,
  130590. 10,
  130591. 38,
  130592. 9,
  130593. 39,
  130594. 8,
  130595. 40,
  130596. 7,
  130597. 41,
  130598. 6,
  130599. 42,
  130600. 5,
  130601. 43,
  130602. 4,
  130603. 44,
  130604. 3,
  130605. 45,
  130606. 2,
  130607. 46,
  130608. 1,
  130609. 47,
  130610. 0,
  130611. 48,
  130612. };
  130613. static long _vq_lengthlist__44c9_s_p9_2[] = {
  130614. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  130615. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  130616. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130617. 7,
  130618. };
  130619. static float _vq_quantthresh__44c9_s_p9_2[] = {
  130620. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  130621. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  130622. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130623. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130624. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  130625. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  130626. };
  130627. static long _vq_quantmap__44c9_s_p9_2[] = {
  130628. 47, 45, 43, 41, 39, 37, 35, 33,
  130629. 31, 29, 27, 25, 23, 21, 19, 17,
  130630. 15, 13, 11, 9, 7, 5, 3, 1,
  130631. 0, 2, 4, 6, 8, 10, 12, 14,
  130632. 16, 18, 20, 22, 24, 26, 28, 30,
  130633. 32, 34, 36, 38, 40, 42, 44, 46,
  130634. 48,
  130635. };
  130636. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  130637. _vq_quantthresh__44c9_s_p9_2,
  130638. _vq_quantmap__44c9_s_p9_2,
  130639. 49,
  130640. 49
  130641. };
  130642. static static_codebook _44c9_s_p9_2 = {
  130643. 1, 49,
  130644. _vq_lengthlist__44c9_s_p9_2,
  130645. 1, -526909440, 1611661312, 6, 0,
  130646. _vq_quantlist__44c9_s_p9_2,
  130647. NULL,
  130648. &_vq_auxt__44c9_s_p9_2,
  130649. NULL,
  130650. 0
  130651. };
  130652. static long _huff_lengthlist__44c9_s_short[] = {
  130653. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  130654. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  130655. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  130656. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  130657. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  130658. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  130659. 9, 8,10,13,
  130660. };
  130661. static static_codebook _huff_book__44c9_s_short = {
  130662. 2, 100,
  130663. _huff_lengthlist__44c9_s_short,
  130664. 0, 0, 0, 0, 0,
  130665. NULL,
  130666. NULL,
  130667. NULL,
  130668. NULL,
  130669. 0
  130670. };
  130671. static long _huff_lengthlist__44c0_s_long[] = {
  130672. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  130673. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  130674. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  130675. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  130676. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  130677. 12,
  130678. };
  130679. static static_codebook _huff_book__44c0_s_long = {
  130680. 2, 81,
  130681. _huff_lengthlist__44c0_s_long,
  130682. 0, 0, 0, 0, 0,
  130683. NULL,
  130684. NULL,
  130685. NULL,
  130686. NULL,
  130687. 0
  130688. };
  130689. static long _vq_quantlist__44c0_s_p1_0[] = {
  130690. 1,
  130691. 0,
  130692. 2,
  130693. };
  130694. static long _vq_lengthlist__44c0_s_p1_0[] = {
  130695. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130696. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130700. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130701. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130705. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130706. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130741. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130746. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130751. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  130752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130786. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130787. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130791. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130792. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  130793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130796. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  130797. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  130798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130842. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130845. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  130880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  130885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  130890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  131106. };
  131107. static float _vq_quantthresh__44c0_s_p1_0[] = {
  131108. -0.5, 0.5,
  131109. };
  131110. static long _vq_quantmap__44c0_s_p1_0[] = {
  131111. 1, 0, 2,
  131112. };
  131113. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  131114. _vq_quantthresh__44c0_s_p1_0,
  131115. _vq_quantmap__44c0_s_p1_0,
  131116. 3,
  131117. 3
  131118. };
  131119. static static_codebook _44c0_s_p1_0 = {
  131120. 8, 6561,
  131121. _vq_lengthlist__44c0_s_p1_0,
  131122. 1, -535822336, 1611661312, 2, 0,
  131123. _vq_quantlist__44c0_s_p1_0,
  131124. NULL,
  131125. &_vq_auxt__44c0_s_p1_0,
  131126. NULL,
  131127. 0
  131128. };
  131129. static long _vq_quantlist__44c0_s_p2_0[] = {
  131130. 2,
  131131. 1,
  131132. 3,
  131133. 0,
  131134. 4,
  131135. };
  131136. static long _vq_lengthlist__44c0_s_p2_0[] = {
  131137. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  131139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131140. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  131142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131143. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  131177. };
  131178. static float _vq_quantthresh__44c0_s_p2_0[] = {
  131179. -1.5, -0.5, 0.5, 1.5,
  131180. };
  131181. static long _vq_quantmap__44c0_s_p2_0[] = {
  131182. 3, 1, 0, 2, 4,
  131183. };
  131184. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  131185. _vq_quantthresh__44c0_s_p2_0,
  131186. _vq_quantmap__44c0_s_p2_0,
  131187. 5,
  131188. 5
  131189. };
  131190. static static_codebook _44c0_s_p2_0 = {
  131191. 4, 625,
  131192. _vq_lengthlist__44c0_s_p2_0,
  131193. 1, -533725184, 1611661312, 3, 0,
  131194. _vq_quantlist__44c0_s_p2_0,
  131195. NULL,
  131196. &_vq_auxt__44c0_s_p2_0,
  131197. NULL,
  131198. 0
  131199. };
  131200. static long _vq_quantlist__44c0_s_p3_0[] = {
  131201. 4,
  131202. 3,
  131203. 5,
  131204. 2,
  131205. 6,
  131206. 1,
  131207. 7,
  131208. 0,
  131209. 8,
  131210. };
  131211. static long _vq_lengthlist__44c0_s_p3_0[] = {
  131212. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  131213. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  131214. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  131215. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  131216. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131217. 0,
  131218. };
  131219. static float _vq_quantthresh__44c0_s_p3_0[] = {
  131220. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131221. };
  131222. static long _vq_quantmap__44c0_s_p3_0[] = {
  131223. 7, 5, 3, 1, 0, 2, 4, 6,
  131224. 8,
  131225. };
  131226. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  131227. _vq_quantthresh__44c0_s_p3_0,
  131228. _vq_quantmap__44c0_s_p3_0,
  131229. 9,
  131230. 9
  131231. };
  131232. static static_codebook _44c0_s_p3_0 = {
  131233. 2, 81,
  131234. _vq_lengthlist__44c0_s_p3_0,
  131235. 1, -531628032, 1611661312, 4, 0,
  131236. _vq_quantlist__44c0_s_p3_0,
  131237. NULL,
  131238. &_vq_auxt__44c0_s_p3_0,
  131239. NULL,
  131240. 0
  131241. };
  131242. static long _vq_quantlist__44c0_s_p4_0[] = {
  131243. 4,
  131244. 3,
  131245. 5,
  131246. 2,
  131247. 6,
  131248. 1,
  131249. 7,
  131250. 0,
  131251. 8,
  131252. };
  131253. static long _vq_lengthlist__44c0_s_p4_0[] = {
  131254. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  131255. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  131256. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  131257. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  131258. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131259. 10,
  131260. };
  131261. static float _vq_quantthresh__44c0_s_p4_0[] = {
  131262. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131263. };
  131264. static long _vq_quantmap__44c0_s_p4_0[] = {
  131265. 7, 5, 3, 1, 0, 2, 4, 6,
  131266. 8,
  131267. };
  131268. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  131269. _vq_quantthresh__44c0_s_p4_0,
  131270. _vq_quantmap__44c0_s_p4_0,
  131271. 9,
  131272. 9
  131273. };
  131274. static static_codebook _44c0_s_p4_0 = {
  131275. 2, 81,
  131276. _vq_lengthlist__44c0_s_p4_0,
  131277. 1, -531628032, 1611661312, 4, 0,
  131278. _vq_quantlist__44c0_s_p4_0,
  131279. NULL,
  131280. &_vq_auxt__44c0_s_p4_0,
  131281. NULL,
  131282. 0
  131283. };
  131284. static long _vq_quantlist__44c0_s_p5_0[] = {
  131285. 8,
  131286. 7,
  131287. 9,
  131288. 6,
  131289. 10,
  131290. 5,
  131291. 11,
  131292. 4,
  131293. 12,
  131294. 3,
  131295. 13,
  131296. 2,
  131297. 14,
  131298. 1,
  131299. 15,
  131300. 0,
  131301. 16,
  131302. };
  131303. static long _vq_lengthlist__44c0_s_p5_0[] = {
  131304. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  131305. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  131306. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  131307. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131308. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131309. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  131310. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  131311. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  131312. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131313. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  131314. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  131315. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  131316. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131317. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131318. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  131319. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  131320. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  131322. 14,
  131323. };
  131324. static float _vq_quantthresh__44c0_s_p5_0[] = {
  131325. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131326. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131327. };
  131328. static long _vq_quantmap__44c0_s_p5_0[] = {
  131329. 15, 13, 11, 9, 7, 5, 3, 1,
  131330. 0, 2, 4, 6, 8, 10, 12, 14,
  131331. 16,
  131332. };
  131333. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  131334. _vq_quantthresh__44c0_s_p5_0,
  131335. _vq_quantmap__44c0_s_p5_0,
  131336. 17,
  131337. 17
  131338. };
  131339. static static_codebook _44c0_s_p5_0 = {
  131340. 2, 289,
  131341. _vq_lengthlist__44c0_s_p5_0,
  131342. 1, -529530880, 1611661312, 5, 0,
  131343. _vq_quantlist__44c0_s_p5_0,
  131344. NULL,
  131345. &_vq_auxt__44c0_s_p5_0,
  131346. NULL,
  131347. 0
  131348. };
  131349. static long _vq_quantlist__44c0_s_p6_0[] = {
  131350. 1,
  131351. 0,
  131352. 2,
  131353. };
  131354. static long _vq_lengthlist__44c0_s_p6_0[] = {
  131355. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  131356. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131357. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  131358. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  131359. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  131360. 10,
  131361. };
  131362. static float _vq_quantthresh__44c0_s_p6_0[] = {
  131363. -5.5, 5.5,
  131364. };
  131365. static long _vq_quantmap__44c0_s_p6_0[] = {
  131366. 1, 0, 2,
  131367. };
  131368. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  131369. _vq_quantthresh__44c0_s_p6_0,
  131370. _vq_quantmap__44c0_s_p6_0,
  131371. 3,
  131372. 3
  131373. };
  131374. static static_codebook _44c0_s_p6_0 = {
  131375. 4, 81,
  131376. _vq_lengthlist__44c0_s_p6_0,
  131377. 1, -529137664, 1618345984, 2, 0,
  131378. _vq_quantlist__44c0_s_p6_0,
  131379. NULL,
  131380. &_vq_auxt__44c0_s_p6_0,
  131381. NULL,
  131382. 0
  131383. };
  131384. static long _vq_quantlist__44c0_s_p6_1[] = {
  131385. 5,
  131386. 4,
  131387. 6,
  131388. 3,
  131389. 7,
  131390. 2,
  131391. 8,
  131392. 1,
  131393. 9,
  131394. 0,
  131395. 10,
  131396. };
  131397. static long _vq_lengthlist__44c0_s_p6_1[] = {
  131398. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  131399. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  131400. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  131401. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  131402. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131403. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131404. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131405. 10,10,10, 8, 8, 8, 8, 8, 8,
  131406. };
  131407. static float _vq_quantthresh__44c0_s_p6_1[] = {
  131408. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131409. 3.5, 4.5,
  131410. };
  131411. static long _vq_quantmap__44c0_s_p6_1[] = {
  131412. 9, 7, 5, 3, 1, 0, 2, 4,
  131413. 6, 8, 10,
  131414. };
  131415. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  131416. _vq_quantthresh__44c0_s_p6_1,
  131417. _vq_quantmap__44c0_s_p6_1,
  131418. 11,
  131419. 11
  131420. };
  131421. static static_codebook _44c0_s_p6_1 = {
  131422. 2, 121,
  131423. _vq_lengthlist__44c0_s_p6_1,
  131424. 1, -531365888, 1611661312, 4, 0,
  131425. _vq_quantlist__44c0_s_p6_1,
  131426. NULL,
  131427. &_vq_auxt__44c0_s_p6_1,
  131428. NULL,
  131429. 0
  131430. };
  131431. static long _vq_quantlist__44c0_s_p7_0[] = {
  131432. 6,
  131433. 5,
  131434. 7,
  131435. 4,
  131436. 8,
  131437. 3,
  131438. 9,
  131439. 2,
  131440. 10,
  131441. 1,
  131442. 11,
  131443. 0,
  131444. 12,
  131445. };
  131446. static long _vq_lengthlist__44c0_s_p7_0[] = {
  131447. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  131448. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  131449. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131450. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131451. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  131452. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  131453. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  131454. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  131455. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  131456. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  131457. 0,12,12,11,11,12,12,13,13,
  131458. };
  131459. static float _vq_quantthresh__44c0_s_p7_0[] = {
  131460. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131461. 12.5, 17.5, 22.5, 27.5,
  131462. };
  131463. static long _vq_quantmap__44c0_s_p7_0[] = {
  131464. 11, 9, 7, 5, 3, 1, 0, 2,
  131465. 4, 6, 8, 10, 12,
  131466. };
  131467. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  131468. _vq_quantthresh__44c0_s_p7_0,
  131469. _vq_quantmap__44c0_s_p7_0,
  131470. 13,
  131471. 13
  131472. };
  131473. static static_codebook _44c0_s_p7_0 = {
  131474. 2, 169,
  131475. _vq_lengthlist__44c0_s_p7_0,
  131476. 1, -526516224, 1616117760, 4, 0,
  131477. _vq_quantlist__44c0_s_p7_0,
  131478. NULL,
  131479. &_vq_auxt__44c0_s_p7_0,
  131480. NULL,
  131481. 0
  131482. };
  131483. static long _vq_quantlist__44c0_s_p7_1[] = {
  131484. 2,
  131485. 1,
  131486. 3,
  131487. 0,
  131488. 4,
  131489. };
  131490. static long _vq_lengthlist__44c0_s_p7_1[] = {
  131491. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  131492. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  131493. };
  131494. static float _vq_quantthresh__44c0_s_p7_1[] = {
  131495. -1.5, -0.5, 0.5, 1.5,
  131496. };
  131497. static long _vq_quantmap__44c0_s_p7_1[] = {
  131498. 3, 1, 0, 2, 4,
  131499. };
  131500. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  131501. _vq_quantthresh__44c0_s_p7_1,
  131502. _vq_quantmap__44c0_s_p7_1,
  131503. 5,
  131504. 5
  131505. };
  131506. static static_codebook _44c0_s_p7_1 = {
  131507. 2, 25,
  131508. _vq_lengthlist__44c0_s_p7_1,
  131509. 1, -533725184, 1611661312, 3, 0,
  131510. _vq_quantlist__44c0_s_p7_1,
  131511. NULL,
  131512. &_vq_auxt__44c0_s_p7_1,
  131513. NULL,
  131514. 0
  131515. };
  131516. static long _vq_quantlist__44c0_s_p8_0[] = {
  131517. 2,
  131518. 1,
  131519. 3,
  131520. 0,
  131521. 4,
  131522. };
  131523. static long _vq_lengthlist__44c0_s_p8_0[] = {
  131524. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  131525. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131526. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131527. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131528. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131529. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131530. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131531. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  131532. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131533. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131534. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131535. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131536. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  131537. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131538. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131539. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  131540. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131541. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131542. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131543. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131544. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131545. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131546. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131547. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131548. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131549. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131550. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131551. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131552. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131553. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131554. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131555. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131556. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131557. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131558. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131559. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131560. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131561. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131562. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131563. 11,
  131564. };
  131565. static float _vq_quantthresh__44c0_s_p8_0[] = {
  131566. -331.5, -110.5, 110.5, 331.5,
  131567. };
  131568. static long _vq_quantmap__44c0_s_p8_0[] = {
  131569. 3, 1, 0, 2, 4,
  131570. };
  131571. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  131572. _vq_quantthresh__44c0_s_p8_0,
  131573. _vq_quantmap__44c0_s_p8_0,
  131574. 5,
  131575. 5
  131576. };
  131577. static static_codebook _44c0_s_p8_0 = {
  131578. 4, 625,
  131579. _vq_lengthlist__44c0_s_p8_0,
  131580. 1, -518283264, 1627103232, 3, 0,
  131581. _vq_quantlist__44c0_s_p8_0,
  131582. NULL,
  131583. &_vq_auxt__44c0_s_p8_0,
  131584. NULL,
  131585. 0
  131586. };
  131587. static long _vq_quantlist__44c0_s_p8_1[] = {
  131588. 6,
  131589. 5,
  131590. 7,
  131591. 4,
  131592. 8,
  131593. 3,
  131594. 9,
  131595. 2,
  131596. 10,
  131597. 1,
  131598. 11,
  131599. 0,
  131600. 12,
  131601. };
  131602. static long _vq_lengthlist__44c0_s_p8_1[] = {
  131603. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  131604. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  131605. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  131606. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  131607. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  131608. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  131609. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  131610. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  131611. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  131612. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  131613. 16,13,13,12,12,14,14,15,13,
  131614. };
  131615. static float _vq_quantthresh__44c0_s_p8_1[] = {
  131616. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  131617. 42.5, 59.5, 76.5, 93.5,
  131618. };
  131619. static long _vq_quantmap__44c0_s_p8_1[] = {
  131620. 11, 9, 7, 5, 3, 1, 0, 2,
  131621. 4, 6, 8, 10, 12,
  131622. };
  131623. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  131624. _vq_quantthresh__44c0_s_p8_1,
  131625. _vq_quantmap__44c0_s_p8_1,
  131626. 13,
  131627. 13
  131628. };
  131629. static static_codebook _44c0_s_p8_1 = {
  131630. 2, 169,
  131631. _vq_lengthlist__44c0_s_p8_1,
  131632. 1, -522616832, 1620115456, 4, 0,
  131633. _vq_quantlist__44c0_s_p8_1,
  131634. NULL,
  131635. &_vq_auxt__44c0_s_p8_1,
  131636. NULL,
  131637. 0
  131638. };
  131639. static long _vq_quantlist__44c0_s_p8_2[] = {
  131640. 8,
  131641. 7,
  131642. 9,
  131643. 6,
  131644. 10,
  131645. 5,
  131646. 11,
  131647. 4,
  131648. 12,
  131649. 3,
  131650. 13,
  131651. 2,
  131652. 14,
  131653. 1,
  131654. 15,
  131655. 0,
  131656. 16,
  131657. };
  131658. static long _vq_lengthlist__44c0_s_p8_2[] = {
  131659. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131660. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  131661. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131662. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  131663. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  131664. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  131665. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  131666. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  131667. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  131668. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  131669. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  131670. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  131671. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  131672. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131673. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  131674. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  131675. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  131676. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  131677. 10,
  131678. };
  131679. static float _vq_quantthresh__44c0_s_p8_2[] = {
  131680. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131681. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131682. };
  131683. static long _vq_quantmap__44c0_s_p8_2[] = {
  131684. 15, 13, 11, 9, 7, 5, 3, 1,
  131685. 0, 2, 4, 6, 8, 10, 12, 14,
  131686. 16,
  131687. };
  131688. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  131689. _vq_quantthresh__44c0_s_p8_2,
  131690. _vq_quantmap__44c0_s_p8_2,
  131691. 17,
  131692. 17
  131693. };
  131694. static static_codebook _44c0_s_p8_2 = {
  131695. 2, 289,
  131696. _vq_lengthlist__44c0_s_p8_2,
  131697. 1, -529530880, 1611661312, 5, 0,
  131698. _vq_quantlist__44c0_s_p8_2,
  131699. NULL,
  131700. &_vq_auxt__44c0_s_p8_2,
  131701. NULL,
  131702. 0
  131703. };
  131704. static long _huff_lengthlist__44c0_s_short[] = {
  131705. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  131706. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  131707. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  131708. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  131709. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  131710. 12,
  131711. };
  131712. static static_codebook _huff_book__44c0_s_short = {
  131713. 2, 81,
  131714. _huff_lengthlist__44c0_s_short,
  131715. 0, 0, 0, 0, 0,
  131716. NULL,
  131717. NULL,
  131718. NULL,
  131719. NULL,
  131720. 0
  131721. };
  131722. static long _huff_lengthlist__44c0_sm_long[] = {
  131723. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  131724. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  131725. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  131726. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  131727. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  131728. 13,
  131729. };
  131730. static static_codebook _huff_book__44c0_sm_long = {
  131731. 2, 81,
  131732. _huff_lengthlist__44c0_sm_long,
  131733. 0, 0, 0, 0, 0,
  131734. NULL,
  131735. NULL,
  131736. NULL,
  131737. NULL,
  131738. 0
  131739. };
  131740. static long _vq_quantlist__44c0_sm_p1_0[] = {
  131741. 1,
  131742. 0,
  131743. 2,
  131744. };
  131745. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  131746. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  131747. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131751. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131752. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131756. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131757. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  131792. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  131793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131797. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131802. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131837. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131838. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131842. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131843. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131847. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131848. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  131849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132032. 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132040. 0, 0, 0, 0, 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, 0,
  132045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132156. 0,
  132157. };
  132158. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  132159. -0.5, 0.5,
  132160. };
  132161. static long _vq_quantmap__44c0_sm_p1_0[] = {
  132162. 1, 0, 2,
  132163. };
  132164. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  132165. _vq_quantthresh__44c0_sm_p1_0,
  132166. _vq_quantmap__44c0_sm_p1_0,
  132167. 3,
  132168. 3
  132169. };
  132170. static static_codebook _44c0_sm_p1_0 = {
  132171. 8, 6561,
  132172. _vq_lengthlist__44c0_sm_p1_0,
  132173. 1, -535822336, 1611661312, 2, 0,
  132174. _vq_quantlist__44c0_sm_p1_0,
  132175. NULL,
  132176. &_vq_auxt__44c0_sm_p1_0,
  132177. NULL,
  132178. 0
  132179. };
  132180. static long _vq_quantlist__44c0_sm_p2_0[] = {
  132181. 2,
  132182. 1,
  132183. 3,
  132184. 0,
  132185. 4,
  132186. };
  132187. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  132188. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  132190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132191. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  132193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132194. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  132195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132227. 0,
  132228. };
  132229. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  132230. -1.5, -0.5, 0.5, 1.5,
  132231. };
  132232. static long _vq_quantmap__44c0_sm_p2_0[] = {
  132233. 3, 1, 0, 2, 4,
  132234. };
  132235. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  132236. _vq_quantthresh__44c0_sm_p2_0,
  132237. _vq_quantmap__44c0_sm_p2_0,
  132238. 5,
  132239. 5
  132240. };
  132241. static static_codebook _44c0_sm_p2_0 = {
  132242. 4, 625,
  132243. _vq_lengthlist__44c0_sm_p2_0,
  132244. 1, -533725184, 1611661312, 3, 0,
  132245. _vq_quantlist__44c0_sm_p2_0,
  132246. NULL,
  132247. &_vq_auxt__44c0_sm_p2_0,
  132248. NULL,
  132249. 0
  132250. };
  132251. static long _vq_quantlist__44c0_sm_p3_0[] = {
  132252. 4,
  132253. 3,
  132254. 5,
  132255. 2,
  132256. 6,
  132257. 1,
  132258. 7,
  132259. 0,
  132260. 8,
  132261. };
  132262. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  132263. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  132264. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  132265. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  132266. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  132267. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132268. 0,
  132269. };
  132270. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  132271. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132272. };
  132273. static long _vq_quantmap__44c0_sm_p3_0[] = {
  132274. 7, 5, 3, 1, 0, 2, 4, 6,
  132275. 8,
  132276. };
  132277. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  132278. _vq_quantthresh__44c0_sm_p3_0,
  132279. _vq_quantmap__44c0_sm_p3_0,
  132280. 9,
  132281. 9
  132282. };
  132283. static static_codebook _44c0_sm_p3_0 = {
  132284. 2, 81,
  132285. _vq_lengthlist__44c0_sm_p3_0,
  132286. 1, -531628032, 1611661312, 4, 0,
  132287. _vq_quantlist__44c0_sm_p3_0,
  132288. NULL,
  132289. &_vq_auxt__44c0_sm_p3_0,
  132290. NULL,
  132291. 0
  132292. };
  132293. static long _vq_quantlist__44c0_sm_p4_0[] = {
  132294. 4,
  132295. 3,
  132296. 5,
  132297. 2,
  132298. 6,
  132299. 1,
  132300. 7,
  132301. 0,
  132302. 8,
  132303. };
  132304. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  132305. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  132306. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  132307. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  132308. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  132309. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  132310. 11,
  132311. };
  132312. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  132313. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132314. };
  132315. static long _vq_quantmap__44c0_sm_p4_0[] = {
  132316. 7, 5, 3, 1, 0, 2, 4, 6,
  132317. 8,
  132318. };
  132319. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  132320. _vq_quantthresh__44c0_sm_p4_0,
  132321. _vq_quantmap__44c0_sm_p4_0,
  132322. 9,
  132323. 9
  132324. };
  132325. static static_codebook _44c0_sm_p4_0 = {
  132326. 2, 81,
  132327. _vq_lengthlist__44c0_sm_p4_0,
  132328. 1, -531628032, 1611661312, 4, 0,
  132329. _vq_quantlist__44c0_sm_p4_0,
  132330. NULL,
  132331. &_vq_auxt__44c0_sm_p4_0,
  132332. NULL,
  132333. 0
  132334. };
  132335. static long _vq_quantlist__44c0_sm_p5_0[] = {
  132336. 8,
  132337. 7,
  132338. 9,
  132339. 6,
  132340. 10,
  132341. 5,
  132342. 11,
  132343. 4,
  132344. 12,
  132345. 3,
  132346. 13,
  132347. 2,
  132348. 14,
  132349. 1,
  132350. 15,
  132351. 0,
  132352. 16,
  132353. };
  132354. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  132355. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  132356. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  132357. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  132358. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  132359. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  132360. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  132361. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  132362. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  132363. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  132364. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  132365. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  132366. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132367. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  132368. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  132369. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  132370. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  132371. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  132372. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  132373. 14,
  132374. };
  132375. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  132376. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132377. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132378. };
  132379. static long _vq_quantmap__44c0_sm_p5_0[] = {
  132380. 15, 13, 11, 9, 7, 5, 3, 1,
  132381. 0, 2, 4, 6, 8, 10, 12, 14,
  132382. 16,
  132383. };
  132384. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  132385. _vq_quantthresh__44c0_sm_p5_0,
  132386. _vq_quantmap__44c0_sm_p5_0,
  132387. 17,
  132388. 17
  132389. };
  132390. static static_codebook _44c0_sm_p5_0 = {
  132391. 2, 289,
  132392. _vq_lengthlist__44c0_sm_p5_0,
  132393. 1, -529530880, 1611661312, 5, 0,
  132394. _vq_quantlist__44c0_sm_p5_0,
  132395. NULL,
  132396. &_vq_auxt__44c0_sm_p5_0,
  132397. NULL,
  132398. 0
  132399. };
  132400. static long _vq_quantlist__44c0_sm_p6_0[] = {
  132401. 1,
  132402. 0,
  132403. 2,
  132404. };
  132405. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  132406. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132407. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  132408. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  132409. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  132410. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  132411. 11,
  132412. };
  132413. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  132414. -5.5, 5.5,
  132415. };
  132416. static long _vq_quantmap__44c0_sm_p6_0[] = {
  132417. 1, 0, 2,
  132418. };
  132419. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  132420. _vq_quantthresh__44c0_sm_p6_0,
  132421. _vq_quantmap__44c0_sm_p6_0,
  132422. 3,
  132423. 3
  132424. };
  132425. static static_codebook _44c0_sm_p6_0 = {
  132426. 4, 81,
  132427. _vq_lengthlist__44c0_sm_p6_0,
  132428. 1, -529137664, 1618345984, 2, 0,
  132429. _vq_quantlist__44c0_sm_p6_0,
  132430. NULL,
  132431. &_vq_auxt__44c0_sm_p6_0,
  132432. NULL,
  132433. 0
  132434. };
  132435. static long _vq_quantlist__44c0_sm_p6_1[] = {
  132436. 5,
  132437. 4,
  132438. 6,
  132439. 3,
  132440. 7,
  132441. 2,
  132442. 8,
  132443. 1,
  132444. 9,
  132445. 0,
  132446. 10,
  132447. };
  132448. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  132449. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  132450. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132451. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  132452. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  132453. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  132454. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  132455. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132456. 10,10,10, 8, 8, 8, 8, 8, 8,
  132457. };
  132458. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  132459. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132460. 3.5, 4.5,
  132461. };
  132462. static long _vq_quantmap__44c0_sm_p6_1[] = {
  132463. 9, 7, 5, 3, 1, 0, 2, 4,
  132464. 6, 8, 10,
  132465. };
  132466. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  132467. _vq_quantthresh__44c0_sm_p6_1,
  132468. _vq_quantmap__44c0_sm_p6_1,
  132469. 11,
  132470. 11
  132471. };
  132472. static static_codebook _44c0_sm_p6_1 = {
  132473. 2, 121,
  132474. _vq_lengthlist__44c0_sm_p6_1,
  132475. 1, -531365888, 1611661312, 4, 0,
  132476. _vq_quantlist__44c0_sm_p6_1,
  132477. NULL,
  132478. &_vq_auxt__44c0_sm_p6_1,
  132479. NULL,
  132480. 0
  132481. };
  132482. static long _vq_quantlist__44c0_sm_p7_0[] = {
  132483. 6,
  132484. 5,
  132485. 7,
  132486. 4,
  132487. 8,
  132488. 3,
  132489. 9,
  132490. 2,
  132491. 10,
  132492. 1,
  132493. 11,
  132494. 0,
  132495. 12,
  132496. };
  132497. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  132498. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  132499. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  132500. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132501. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132502. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  132503. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  132504. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  132505. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  132506. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  132507. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  132508. 0,12,12,11,11,13,12,14,14,
  132509. };
  132510. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  132511. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132512. 12.5, 17.5, 22.5, 27.5,
  132513. };
  132514. static long _vq_quantmap__44c0_sm_p7_0[] = {
  132515. 11, 9, 7, 5, 3, 1, 0, 2,
  132516. 4, 6, 8, 10, 12,
  132517. };
  132518. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  132519. _vq_quantthresh__44c0_sm_p7_0,
  132520. _vq_quantmap__44c0_sm_p7_0,
  132521. 13,
  132522. 13
  132523. };
  132524. static static_codebook _44c0_sm_p7_0 = {
  132525. 2, 169,
  132526. _vq_lengthlist__44c0_sm_p7_0,
  132527. 1, -526516224, 1616117760, 4, 0,
  132528. _vq_quantlist__44c0_sm_p7_0,
  132529. NULL,
  132530. &_vq_auxt__44c0_sm_p7_0,
  132531. NULL,
  132532. 0
  132533. };
  132534. static long _vq_quantlist__44c0_sm_p7_1[] = {
  132535. 2,
  132536. 1,
  132537. 3,
  132538. 0,
  132539. 4,
  132540. };
  132541. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  132542. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  132543. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  132544. };
  132545. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  132546. -1.5, -0.5, 0.5, 1.5,
  132547. };
  132548. static long _vq_quantmap__44c0_sm_p7_1[] = {
  132549. 3, 1, 0, 2, 4,
  132550. };
  132551. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  132552. _vq_quantthresh__44c0_sm_p7_1,
  132553. _vq_quantmap__44c0_sm_p7_1,
  132554. 5,
  132555. 5
  132556. };
  132557. static static_codebook _44c0_sm_p7_1 = {
  132558. 2, 25,
  132559. _vq_lengthlist__44c0_sm_p7_1,
  132560. 1, -533725184, 1611661312, 3, 0,
  132561. _vq_quantlist__44c0_sm_p7_1,
  132562. NULL,
  132563. &_vq_auxt__44c0_sm_p7_1,
  132564. NULL,
  132565. 0
  132566. };
  132567. static long _vq_quantlist__44c0_sm_p8_0[] = {
  132568. 4,
  132569. 3,
  132570. 5,
  132571. 2,
  132572. 6,
  132573. 1,
  132574. 7,
  132575. 0,
  132576. 8,
  132577. };
  132578. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  132579. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  132580. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  132581. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132582. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132583. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  132584. 12,
  132585. };
  132586. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  132587. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  132588. };
  132589. static long _vq_quantmap__44c0_sm_p8_0[] = {
  132590. 7, 5, 3, 1, 0, 2, 4, 6,
  132591. 8,
  132592. };
  132593. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  132594. _vq_quantthresh__44c0_sm_p8_0,
  132595. _vq_quantmap__44c0_sm_p8_0,
  132596. 9,
  132597. 9
  132598. };
  132599. static static_codebook _44c0_sm_p8_0 = {
  132600. 2, 81,
  132601. _vq_lengthlist__44c0_sm_p8_0,
  132602. 1, -516186112, 1627103232, 4, 0,
  132603. _vq_quantlist__44c0_sm_p8_0,
  132604. NULL,
  132605. &_vq_auxt__44c0_sm_p8_0,
  132606. NULL,
  132607. 0
  132608. };
  132609. static long _vq_quantlist__44c0_sm_p8_1[] = {
  132610. 6,
  132611. 5,
  132612. 7,
  132613. 4,
  132614. 8,
  132615. 3,
  132616. 9,
  132617. 2,
  132618. 10,
  132619. 1,
  132620. 11,
  132621. 0,
  132622. 12,
  132623. };
  132624. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  132625. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  132626. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  132627. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  132628. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  132629. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  132630. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  132631. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  132632. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  132633. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  132634. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  132635. 20,13,13,12,12,16,13,15,13,
  132636. };
  132637. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  132638. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  132639. 42.5, 59.5, 76.5, 93.5,
  132640. };
  132641. static long _vq_quantmap__44c0_sm_p8_1[] = {
  132642. 11, 9, 7, 5, 3, 1, 0, 2,
  132643. 4, 6, 8, 10, 12,
  132644. };
  132645. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  132646. _vq_quantthresh__44c0_sm_p8_1,
  132647. _vq_quantmap__44c0_sm_p8_1,
  132648. 13,
  132649. 13
  132650. };
  132651. static static_codebook _44c0_sm_p8_1 = {
  132652. 2, 169,
  132653. _vq_lengthlist__44c0_sm_p8_1,
  132654. 1, -522616832, 1620115456, 4, 0,
  132655. _vq_quantlist__44c0_sm_p8_1,
  132656. NULL,
  132657. &_vq_auxt__44c0_sm_p8_1,
  132658. NULL,
  132659. 0
  132660. };
  132661. static long _vq_quantlist__44c0_sm_p8_2[] = {
  132662. 8,
  132663. 7,
  132664. 9,
  132665. 6,
  132666. 10,
  132667. 5,
  132668. 11,
  132669. 4,
  132670. 12,
  132671. 3,
  132672. 13,
  132673. 2,
  132674. 14,
  132675. 1,
  132676. 15,
  132677. 0,
  132678. 16,
  132679. };
  132680. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  132681. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132682. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  132683. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  132684. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  132685. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  132686. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  132687. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  132688. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  132689. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  132690. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  132691. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  132692. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  132693. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  132694. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  132695. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  132696. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132697. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  132698. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  132699. 9,
  132700. };
  132701. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  132702. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132703. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132704. };
  132705. static long _vq_quantmap__44c0_sm_p8_2[] = {
  132706. 15, 13, 11, 9, 7, 5, 3, 1,
  132707. 0, 2, 4, 6, 8, 10, 12, 14,
  132708. 16,
  132709. };
  132710. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  132711. _vq_quantthresh__44c0_sm_p8_2,
  132712. _vq_quantmap__44c0_sm_p8_2,
  132713. 17,
  132714. 17
  132715. };
  132716. static static_codebook _44c0_sm_p8_2 = {
  132717. 2, 289,
  132718. _vq_lengthlist__44c0_sm_p8_2,
  132719. 1, -529530880, 1611661312, 5, 0,
  132720. _vq_quantlist__44c0_sm_p8_2,
  132721. NULL,
  132722. &_vq_auxt__44c0_sm_p8_2,
  132723. NULL,
  132724. 0
  132725. };
  132726. static long _huff_lengthlist__44c0_sm_short[] = {
  132727. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  132728. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  132729. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  132730. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  132731. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  132732. 12,
  132733. };
  132734. static static_codebook _huff_book__44c0_sm_short = {
  132735. 2, 81,
  132736. _huff_lengthlist__44c0_sm_short,
  132737. 0, 0, 0, 0, 0,
  132738. NULL,
  132739. NULL,
  132740. NULL,
  132741. NULL,
  132742. 0
  132743. };
  132744. static long _huff_lengthlist__44c1_s_long[] = {
  132745. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  132746. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  132747. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  132748. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  132749. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  132750. 11,
  132751. };
  132752. static static_codebook _huff_book__44c1_s_long = {
  132753. 2, 81,
  132754. _huff_lengthlist__44c1_s_long,
  132755. 0, 0, 0, 0, 0,
  132756. NULL,
  132757. NULL,
  132758. NULL,
  132759. NULL,
  132760. 0
  132761. };
  132762. static long _vq_quantlist__44c1_s_p1_0[] = {
  132763. 1,
  132764. 0,
  132765. 2,
  132766. };
  132767. static long _vq_lengthlist__44c1_s_p1_0[] = {
  132768. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  132769. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132773. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  132774. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132778. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  132779. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  132814. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  132815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  132819. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  132820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  132824. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  132825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132859. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  132860. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132864. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  132865. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  132866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132869. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  132870. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  132871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132880. 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132888. 0, 0, 0, 0, 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, 0,
  132893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  133136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133178. 0,
  133179. };
  133180. static float _vq_quantthresh__44c1_s_p1_0[] = {
  133181. -0.5, 0.5,
  133182. };
  133183. static long _vq_quantmap__44c1_s_p1_0[] = {
  133184. 1, 0, 2,
  133185. };
  133186. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  133187. _vq_quantthresh__44c1_s_p1_0,
  133188. _vq_quantmap__44c1_s_p1_0,
  133189. 3,
  133190. 3
  133191. };
  133192. static static_codebook _44c1_s_p1_0 = {
  133193. 8, 6561,
  133194. _vq_lengthlist__44c1_s_p1_0,
  133195. 1, -535822336, 1611661312, 2, 0,
  133196. _vq_quantlist__44c1_s_p1_0,
  133197. NULL,
  133198. &_vq_auxt__44c1_s_p1_0,
  133199. NULL,
  133200. 0
  133201. };
  133202. static long _vq_quantlist__44c1_s_p2_0[] = {
  133203. 2,
  133204. 1,
  133205. 3,
  133206. 0,
  133207. 4,
  133208. };
  133209. static long _vq_lengthlist__44c1_s_p2_0[] = {
  133210. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  133212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133213. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  133215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133216. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  133217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133249. 0,
  133250. };
  133251. static float _vq_quantthresh__44c1_s_p2_0[] = {
  133252. -1.5, -0.5, 0.5, 1.5,
  133253. };
  133254. static long _vq_quantmap__44c1_s_p2_0[] = {
  133255. 3, 1, 0, 2, 4,
  133256. };
  133257. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  133258. _vq_quantthresh__44c1_s_p2_0,
  133259. _vq_quantmap__44c1_s_p2_0,
  133260. 5,
  133261. 5
  133262. };
  133263. static static_codebook _44c1_s_p2_0 = {
  133264. 4, 625,
  133265. _vq_lengthlist__44c1_s_p2_0,
  133266. 1, -533725184, 1611661312, 3, 0,
  133267. _vq_quantlist__44c1_s_p2_0,
  133268. NULL,
  133269. &_vq_auxt__44c1_s_p2_0,
  133270. NULL,
  133271. 0
  133272. };
  133273. static long _vq_quantlist__44c1_s_p3_0[] = {
  133274. 4,
  133275. 3,
  133276. 5,
  133277. 2,
  133278. 6,
  133279. 1,
  133280. 7,
  133281. 0,
  133282. 8,
  133283. };
  133284. static long _vq_lengthlist__44c1_s_p3_0[] = {
  133285. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  133286. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  133287. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  133288. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  133289. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133290. 0,
  133291. };
  133292. static float _vq_quantthresh__44c1_s_p3_0[] = {
  133293. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133294. };
  133295. static long _vq_quantmap__44c1_s_p3_0[] = {
  133296. 7, 5, 3, 1, 0, 2, 4, 6,
  133297. 8,
  133298. };
  133299. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  133300. _vq_quantthresh__44c1_s_p3_0,
  133301. _vq_quantmap__44c1_s_p3_0,
  133302. 9,
  133303. 9
  133304. };
  133305. static static_codebook _44c1_s_p3_0 = {
  133306. 2, 81,
  133307. _vq_lengthlist__44c1_s_p3_0,
  133308. 1, -531628032, 1611661312, 4, 0,
  133309. _vq_quantlist__44c1_s_p3_0,
  133310. NULL,
  133311. &_vq_auxt__44c1_s_p3_0,
  133312. NULL,
  133313. 0
  133314. };
  133315. static long _vq_quantlist__44c1_s_p4_0[] = {
  133316. 4,
  133317. 3,
  133318. 5,
  133319. 2,
  133320. 6,
  133321. 1,
  133322. 7,
  133323. 0,
  133324. 8,
  133325. };
  133326. static long _vq_lengthlist__44c1_s_p4_0[] = {
  133327. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  133328. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  133329. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  133330. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  133331. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  133332. 11,
  133333. };
  133334. static float _vq_quantthresh__44c1_s_p4_0[] = {
  133335. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133336. };
  133337. static long _vq_quantmap__44c1_s_p4_0[] = {
  133338. 7, 5, 3, 1, 0, 2, 4, 6,
  133339. 8,
  133340. };
  133341. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  133342. _vq_quantthresh__44c1_s_p4_0,
  133343. _vq_quantmap__44c1_s_p4_0,
  133344. 9,
  133345. 9
  133346. };
  133347. static static_codebook _44c1_s_p4_0 = {
  133348. 2, 81,
  133349. _vq_lengthlist__44c1_s_p4_0,
  133350. 1, -531628032, 1611661312, 4, 0,
  133351. _vq_quantlist__44c1_s_p4_0,
  133352. NULL,
  133353. &_vq_auxt__44c1_s_p4_0,
  133354. NULL,
  133355. 0
  133356. };
  133357. static long _vq_quantlist__44c1_s_p5_0[] = {
  133358. 8,
  133359. 7,
  133360. 9,
  133361. 6,
  133362. 10,
  133363. 5,
  133364. 11,
  133365. 4,
  133366. 12,
  133367. 3,
  133368. 13,
  133369. 2,
  133370. 14,
  133371. 1,
  133372. 15,
  133373. 0,
  133374. 16,
  133375. };
  133376. static long _vq_lengthlist__44c1_s_p5_0[] = {
  133377. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133378. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  133379. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  133380. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  133381. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  133382. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  133383. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  133384. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  133385. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  133386. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  133387. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133388. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133389. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  133390. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  133391. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  133392. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  133393. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  133394. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  133395. 14,
  133396. };
  133397. static float _vq_quantthresh__44c1_s_p5_0[] = {
  133398. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133399. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133400. };
  133401. static long _vq_quantmap__44c1_s_p5_0[] = {
  133402. 15, 13, 11, 9, 7, 5, 3, 1,
  133403. 0, 2, 4, 6, 8, 10, 12, 14,
  133404. 16,
  133405. };
  133406. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  133407. _vq_quantthresh__44c1_s_p5_0,
  133408. _vq_quantmap__44c1_s_p5_0,
  133409. 17,
  133410. 17
  133411. };
  133412. static static_codebook _44c1_s_p5_0 = {
  133413. 2, 289,
  133414. _vq_lengthlist__44c1_s_p5_0,
  133415. 1, -529530880, 1611661312, 5, 0,
  133416. _vq_quantlist__44c1_s_p5_0,
  133417. NULL,
  133418. &_vq_auxt__44c1_s_p5_0,
  133419. NULL,
  133420. 0
  133421. };
  133422. static long _vq_quantlist__44c1_s_p6_0[] = {
  133423. 1,
  133424. 0,
  133425. 2,
  133426. };
  133427. static long _vq_lengthlist__44c1_s_p6_0[] = {
  133428. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  133429. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  133430. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  133431. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  133432. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  133433. 11,
  133434. };
  133435. static float _vq_quantthresh__44c1_s_p6_0[] = {
  133436. -5.5, 5.5,
  133437. };
  133438. static long _vq_quantmap__44c1_s_p6_0[] = {
  133439. 1, 0, 2,
  133440. };
  133441. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  133442. _vq_quantthresh__44c1_s_p6_0,
  133443. _vq_quantmap__44c1_s_p6_0,
  133444. 3,
  133445. 3
  133446. };
  133447. static static_codebook _44c1_s_p6_0 = {
  133448. 4, 81,
  133449. _vq_lengthlist__44c1_s_p6_0,
  133450. 1, -529137664, 1618345984, 2, 0,
  133451. _vq_quantlist__44c1_s_p6_0,
  133452. NULL,
  133453. &_vq_auxt__44c1_s_p6_0,
  133454. NULL,
  133455. 0
  133456. };
  133457. static long _vq_quantlist__44c1_s_p6_1[] = {
  133458. 5,
  133459. 4,
  133460. 6,
  133461. 3,
  133462. 7,
  133463. 2,
  133464. 8,
  133465. 1,
  133466. 9,
  133467. 0,
  133468. 10,
  133469. };
  133470. static long _vq_lengthlist__44c1_s_p6_1[] = {
  133471. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  133472. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  133473. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  133474. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  133475. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  133476. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  133477. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  133478. 10,10,10, 8, 8, 8, 8, 8, 8,
  133479. };
  133480. static float _vq_quantthresh__44c1_s_p6_1[] = {
  133481. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133482. 3.5, 4.5,
  133483. };
  133484. static long _vq_quantmap__44c1_s_p6_1[] = {
  133485. 9, 7, 5, 3, 1, 0, 2, 4,
  133486. 6, 8, 10,
  133487. };
  133488. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  133489. _vq_quantthresh__44c1_s_p6_1,
  133490. _vq_quantmap__44c1_s_p6_1,
  133491. 11,
  133492. 11
  133493. };
  133494. static static_codebook _44c1_s_p6_1 = {
  133495. 2, 121,
  133496. _vq_lengthlist__44c1_s_p6_1,
  133497. 1, -531365888, 1611661312, 4, 0,
  133498. _vq_quantlist__44c1_s_p6_1,
  133499. NULL,
  133500. &_vq_auxt__44c1_s_p6_1,
  133501. NULL,
  133502. 0
  133503. };
  133504. static long _vq_quantlist__44c1_s_p7_0[] = {
  133505. 6,
  133506. 5,
  133507. 7,
  133508. 4,
  133509. 8,
  133510. 3,
  133511. 9,
  133512. 2,
  133513. 10,
  133514. 1,
  133515. 11,
  133516. 0,
  133517. 12,
  133518. };
  133519. static long _vq_lengthlist__44c1_s_p7_0[] = {
  133520. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  133521. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  133522. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133523. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133524. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  133525. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  133526. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  133527. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133528. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133529. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  133530. 0,12,11,11,11,13,10,14,13,
  133531. };
  133532. static float _vq_quantthresh__44c1_s_p7_0[] = {
  133533. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133534. 12.5, 17.5, 22.5, 27.5,
  133535. };
  133536. static long _vq_quantmap__44c1_s_p7_0[] = {
  133537. 11, 9, 7, 5, 3, 1, 0, 2,
  133538. 4, 6, 8, 10, 12,
  133539. };
  133540. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  133541. _vq_quantthresh__44c1_s_p7_0,
  133542. _vq_quantmap__44c1_s_p7_0,
  133543. 13,
  133544. 13
  133545. };
  133546. static static_codebook _44c1_s_p7_0 = {
  133547. 2, 169,
  133548. _vq_lengthlist__44c1_s_p7_0,
  133549. 1, -526516224, 1616117760, 4, 0,
  133550. _vq_quantlist__44c1_s_p7_0,
  133551. NULL,
  133552. &_vq_auxt__44c1_s_p7_0,
  133553. NULL,
  133554. 0
  133555. };
  133556. static long _vq_quantlist__44c1_s_p7_1[] = {
  133557. 2,
  133558. 1,
  133559. 3,
  133560. 0,
  133561. 4,
  133562. };
  133563. static long _vq_lengthlist__44c1_s_p7_1[] = {
  133564. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  133565. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  133566. };
  133567. static float _vq_quantthresh__44c1_s_p7_1[] = {
  133568. -1.5, -0.5, 0.5, 1.5,
  133569. };
  133570. static long _vq_quantmap__44c1_s_p7_1[] = {
  133571. 3, 1, 0, 2, 4,
  133572. };
  133573. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  133574. _vq_quantthresh__44c1_s_p7_1,
  133575. _vq_quantmap__44c1_s_p7_1,
  133576. 5,
  133577. 5
  133578. };
  133579. static static_codebook _44c1_s_p7_1 = {
  133580. 2, 25,
  133581. _vq_lengthlist__44c1_s_p7_1,
  133582. 1, -533725184, 1611661312, 3, 0,
  133583. _vq_quantlist__44c1_s_p7_1,
  133584. NULL,
  133585. &_vq_auxt__44c1_s_p7_1,
  133586. NULL,
  133587. 0
  133588. };
  133589. static long _vq_quantlist__44c1_s_p8_0[] = {
  133590. 6,
  133591. 5,
  133592. 7,
  133593. 4,
  133594. 8,
  133595. 3,
  133596. 9,
  133597. 2,
  133598. 10,
  133599. 1,
  133600. 11,
  133601. 0,
  133602. 12,
  133603. };
  133604. static long _vq_lengthlist__44c1_s_p8_0[] = {
  133605. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  133606. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  133607. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133608. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133609. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133610. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133611. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133612. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133613. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133614. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133615. 10,10,10,10,10,10,10,10,10,
  133616. };
  133617. static float _vq_quantthresh__44c1_s_p8_0[] = {
  133618. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  133619. 552.5, 773.5, 994.5, 1215.5,
  133620. };
  133621. static long _vq_quantmap__44c1_s_p8_0[] = {
  133622. 11, 9, 7, 5, 3, 1, 0, 2,
  133623. 4, 6, 8, 10, 12,
  133624. };
  133625. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  133626. _vq_quantthresh__44c1_s_p8_0,
  133627. _vq_quantmap__44c1_s_p8_0,
  133628. 13,
  133629. 13
  133630. };
  133631. static static_codebook _44c1_s_p8_0 = {
  133632. 2, 169,
  133633. _vq_lengthlist__44c1_s_p8_0,
  133634. 1, -514541568, 1627103232, 4, 0,
  133635. _vq_quantlist__44c1_s_p8_0,
  133636. NULL,
  133637. &_vq_auxt__44c1_s_p8_0,
  133638. NULL,
  133639. 0
  133640. };
  133641. static long _vq_quantlist__44c1_s_p8_1[] = {
  133642. 6,
  133643. 5,
  133644. 7,
  133645. 4,
  133646. 8,
  133647. 3,
  133648. 9,
  133649. 2,
  133650. 10,
  133651. 1,
  133652. 11,
  133653. 0,
  133654. 12,
  133655. };
  133656. static long _vq_lengthlist__44c1_s_p8_1[] = {
  133657. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  133658. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  133659. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  133660. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  133661. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  133662. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  133663. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  133664. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  133665. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  133666. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  133667. 16,13,12,12,11,14,12,15,13,
  133668. };
  133669. static float _vq_quantthresh__44c1_s_p8_1[] = {
  133670. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133671. 42.5, 59.5, 76.5, 93.5,
  133672. };
  133673. static long _vq_quantmap__44c1_s_p8_1[] = {
  133674. 11, 9, 7, 5, 3, 1, 0, 2,
  133675. 4, 6, 8, 10, 12,
  133676. };
  133677. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  133678. _vq_quantthresh__44c1_s_p8_1,
  133679. _vq_quantmap__44c1_s_p8_1,
  133680. 13,
  133681. 13
  133682. };
  133683. static static_codebook _44c1_s_p8_1 = {
  133684. 2, 169,
  133685. _vq_lengthlist__44c1_s_p8_1,
  133686. 1, -522616832, 1620115456, 4, 0,
  133687. _vq_quantlist__44c1_s_p8_1,
  133688. NULL,
  133689. &_vq_auxt__44c1_s_p8_1,
  133690. NULL,
  133691. 0
  133692. };
  133693. static long _vq_quantlist__44c1_s_p8_2[] = {
  133694. 8,
  133695. 7,
  133696. 9,
  133697. 6,
  133698. 10,
  133699. 5,
  133700. 11,
  133701. 4,
  133702. 12,
  133703. 3,
  133704. 13,
  133705. 2,
  133706. 14,
  133707. 1,
  133708. 15,
  133709. 0,
  133710. 16,
  133711. };
  133712. static long _vq_lengthlist__44c1_s_p8_2[] = {
  133713. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133714. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  133715. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  133716. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  133717. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  133718. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  133719. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  133720. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  133721. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  133722. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  133723. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  133724. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  133725. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  133726. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  133727. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  133728. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  133729. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  133730. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  133731. 9,
  133732. };
  133733. static float _vq_quantthresh__44c1_s_p8_2[] = {
  133734. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133735. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133736. };
  133737. static long _vq_quantmap__44c1_s_p8_2[] = {
  133738. 15, 13, 11, 9, 7, 5, 3, 1,
  133739. 0, 2, 4, 6, 8, 10, 12, 14,
  133740. 16,
  133741. };
  133742. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  133743. _vq_quantthresh__44c1_s_p8_2,
  133744. _vq_quantmap__44c1_s_p8_2,
  133745. 17,
  133746. 17
  133747. };
  133748. static static_codebook _44c1_s_p8_2 = {
  133749. 2, 289,
  133750. _vq_lengthlist__44c1_s_p8_2,
  133751. 1, -529530880, 1611661312, 5, 0,
  133752. _vq_quantlist__44c1_s_p8_2,
  133753. NULL,
  133754. &_vq_auxt__44c1_s_p8_2,
  133755. NULL,
  133756. 0
  133757. };
  133758. static long _huff_lengthlist__44c1_s_short[] = {
  133759. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  133760. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  133761. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  133762. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  133763. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  133764. 11,
  133765. };
  133766. static static_codebook _huff_book__44c1_s_short = {
  133767. 2, 81,
  133768. _huff_lengthlist__44c1_s_short,
  133769. 0, 0, 0, 0, 0,
  133770. NULL,
  133771. NULL,
  133772. NULL,
  133773. NULL,
  133774. 0
  133775. };
  133776. static long _huff_lengthlist__44c1_sm_long[] = {
  133777. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  133778. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  133779. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  133780. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  133781. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  133782. 11,
  133783. };
  133784. static static_codebook _huff_book__44c1_sm_long = {
  133785. 2, 81,
  133786. _huff_lengthlist__44c1_sm_long,
  133787. 0, 0, 0, 0, 0,
  133788. NULL,
  133789. NULL,
  133790. NULL,
  133791. NULL,
  133792. 0
  133793. };
  133794. static long _vq_quantlist__44c1_sm_p1_0[] = {
  133795. 1,
  133796. 0,
  133797. 2,
  133798. };
  133799. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  133800. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  133801. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133805. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  133806. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133810. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  133811. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0,
  133846. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  133847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  133851. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  133852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  133856. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  133857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133891. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  133892. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133896. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  133897. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  133898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133901. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  133902. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  133903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  133984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134210. 0,
  134211. };
  134212. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  134213. -0.5, 0.5,
  134214. };
  134215. static long _vq_quantmap__44c1_sm_p1_0[] = {
  134216. 1, 0, 2,
  134217. };
  134218. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  134219. _vq_quantthresh__44c1_sm_p1_0,
  134220. _vq_quantmap__44c1_sm_p1_0,
  134221. 3,
  134222. 3
  134223. };
  134224. static static_codebook _44c1_sm_p1_0 = {
  134225. 8, 6561,
  134226. _vq_lengthlist__44c1_sm_p1_0,
  134227. 1, -535822336, 1611661312, 2, 0,
  134228. _vq_quantlist__44c1_sm_p1_0,
  134229. NULL,
  134230. &_vq_auxt__44c1_sm_p1_0,
  134231. NULL,
  134232. 0
  134233. };
  134234. static long _vq_quantlist__44c1_sm_p2_0[] = {
  134235. 2,
  134236. 1,
  134237. 3,
  134238. 0,
  134239. 4,
  134240. };
  134241. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  134242. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  134244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134245. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  134247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134248. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  134249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134281. 0,
  134282. };
  134283. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  134284. -1.5, -0.5, 0.5, 1.5,
  134285. };
  134286. static long _vq_quantmap__44c1_sm_p2_0[] = {
  134287. 3, 1, 0, 2, 4,
  134288. };
  134289. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  134290. _vq_quantthresh__44c1_sm_p2_0,
  134291. _vq_quantmap__44c1_sm_p2_0,
  134292. 5,
  134293. 5
  134294. };
  134295. static static_codebook _44c1_sm_p2_0 = {
  134296. 4, 625,
  134297. _vq_lengthlist__44c1_sm_p2_0,
  134298. 1, -533725184, 1611661312, 3, 0,
  134299. _vq_quantlist__44c1_sm_p2_0,
  134300. NULL,
  134301. &_vq_auxt__44c1_sm_p2_0,
  134302. NULL,
  134303. 0
  134304. };
  134305. static long _vq_quantlist__44c1_sm_p3_0[] = {
  134306. 4,
  134307. 3,
  134308. 5,
  134309. 2,
  134310. 6,
  134311. 1,
  134312. 7,
  134313. 0,
  134314. 8,
  134315. };
  134316. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  134317. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  134318. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  134319. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  134320. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  134321. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134322. 0,
  134323. };
  134324. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  134325. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134326. };
  134327. static long _vq_quantmap__44c1_sm_p3_0[] = {
  134328. 7, 5, 3, 1, 0, 2, 4, 6,
  134329. 8,
  134330. };
  134331. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  134332. _vq_quantthresh__44c1_sm_p3_0,
  134333. _vq_quantmap__44c1_sm_p3_0,
  134334. 9,
  134335. 9
  134336. };
  134337. static static_codebook _44c1_sm_p3_0 = {
  134338. 2, 81,
  134339. _vq_lengthlist__44c1_sm_p3_0,
  134340. 1, -531628032, 1611661312, 4, 0,
  134341. _vq_quantlist__44c1_sm_p3_0,
  134342. NULL,
  134343. &_vq_auxt__44c1_sm_p3_0,
  134344. NULL,
  134345. 0
  134346. };
  134347. static long _vq_quantlist__44c1_sm_p4_0[] = {
  134348. 4,
  134349. 3,
  134350. 5,
  134351. 2,
  134352. 6,
  134353. 1,
  134354. 7,
  134355. 0,
  134356. 8,
  134357. };
  134358. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  134359. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  134360. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  134361. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  134362. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  134363. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  134364. 11,
  134365. };
  134366. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  134367. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134368. };
  134369. static long _vq_quantmap__44c1_sm_p4_0[] = {
  134370. 7, 5, 3, 1, 0, 2, 4, 6,
  134371. 8,
  134372. };
  134373. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  134374. _vq_quantthresh__44c1_sm_p4_0,
  134375. _vq_quantmap__44c1_sm_p4_0,
  134376. 9,
  134377. 9
  134378. };
  134379. static static_codebook _44c1_sm_p4_0 = {
  134380. 2, 81,
  134381. _vq_lengthlist__44c1_sm_p4_0,
  134382. 1, -531628032, 1611661312, 4, 0,
  134383. _vq_quantlist__44c1_sm_p4_0,
  134384. NULL,
  134385. &_vq_auxt__44c1_sm_p4_0,
  134386. NULL,
  134387. 0
  134388. };
  134389. static long _vq_quantlist__44c1_sm_p5_0[] = {
  134390. 8,
  134391. 7,
  134392. 9,
  134393. 6,
  134394. 10,
  134395. 5,
  134396. 11,
  134397. 4,
  134398. 12,
  134399. 3,
  134400. 13,
  134401. 2,
  134402. 14,
  134403. 1,
  134404. 15,
  134405. 0,
  134406. 16,
  134407. };
  134408. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  134409. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134410. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  134411. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  134412. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  134413. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  134414. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  134415. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  134416. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  134417. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  134418. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  134419. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  134420. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  134421. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  134422. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  134423. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  134424. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  134425. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  134426. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  134427. 14,
  134428. };
  134429. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  134430. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134431. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134432. };
  134433. static long _vq_quantmap__44c1_sm_p5_0[] = {
  134434. 15, 13, 11, 9, 7, 5, 3, 1,
  134435. 0, 2, 4, 6, 8, 10, 12, 14,
  134436. 16,
  134437. };
  134438. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  134439. _vq_quantthresh__44c1_sm_p5_0,
  134440. _vq_quantmap__44c1_sm_p5_0,
  134441. 17,
  134442. 17
  134443. };
  134444. static static_codebook _44c1_sm_p5_0 = {
  134445. 2, 289,
  134446. _vq_lengthlist__44c1_sm_p5_0,
  134447. 1, -529530880, 1611661312, 5, 0,
  134448. _vq_quantlist__44c1_sm_p5_0,
  134449. NULL,
  134450. &_vq_auxt__44c1_sm_p5_0,
  134451. NULL,
  134452. 0
  134453. };
  134454. static long _vq_quantlist__44c1_sm_p6_0[] = {
  134455. 1,
  134456. 0,
  134457. 2,
  134458. };
  134459. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  134460. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  134461. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  134462. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  134463. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  134464. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  134465. 11,
  134466. };
  134467. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  134468. -5.5, 5.5,
  134469. };
  134470. static long _vq_quantmap__44c1_sm_p6_0[] = {
  134471. 1, 0, 2,
  134472. };
  134473. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  134474. _vq_quantthresh__44c1_sm_p6_0,
  134475. _vq_quantmap__44c1_sm_p6_0,
  134476. 3,
  134477. 3
  134478. };
  134479. static static_codebook _44c1_sm_p6_0 = {
  134480. 4, 81,
  134481. _vq_lengthlist__44c1_sm_p6_0,
  134482. 1, -529137664, 1618345984, 2, 0,
  134483. _vq_quantlist__44c1_sm_p6_0,
  134484. NULL,
  134485. &_vq_auxt__44c1_sm_p6_0,
  134486. NULL,
  134487. 0
  134488. };
  134489. static long _vq_quantlist__44c1_sm_p6_1[] = {
  134490. 5,
  134491. 4,
  134492. 6,
  134493. 3,
  134494. 7,
  134495. 2,
  134496. 8,
  134497. 1,
  134498. 9,
  134499. 0,
  134500. 10,
  134501. };
  134502. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  134503. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  134504. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134505. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  134506. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  134507. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  134508. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  134509. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  134510. 10,10,10, 8, 8, 8, 8, 8, 8,
  134511. };
  134512. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  134513. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134514. 3.5, 4.5,
  134515. };
  134516. static long _vq_quantmap__44c1_sm_p6_1[] = {
  134517. 9, 7, 5, 3, 1, 0, 2, 4,
  134518. 6, 8, 10,
  134519. };
  134520. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  134521. _vq_quantthresh__44c1_sm_p6_1,
  134522. _vq_quantmap__44c1_sm_p6_1,
  134523. 11,
  134524. 11
  134525. };
  134526. static static_codebook _44c1_sm_p6_1 = {
  134527. 2, 121,
  134528. _vq_lengthlist__44c1_sm_p6_1,
  134529. 1, -531365888, 1611661312, 4, 0,
  134530. _vq_quantlist__44c1_sm_p6_1,
  134531. NULL,
  134532. &_vq_auxt__44c1_sm_p6_1,
  134533. NULL,
  134534. 0
  134535. };
  134536. static long _vq_quantlist__44c1_sm_p7_0[] = {
  134537. 6,
  134538. 5,
  134539. 7,
  134540. 4,
  134541. 8,
  134542. 3,
  134543. 9,
  134544. 2,
  134545. 10,
  134546. 1,
  134547. 11,
  134548. 0,
  134549. 12,
  134550. };
  134551. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  134552. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  134553. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  134554. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134555. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134556. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  134557. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  134558. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  134559. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  134560. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  134561. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  134562. 0,12,12,11,11,13,12,14,13,
  134563. };
  134564. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  134565. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134566. 12.5, 17.5, 22.5, 27.5,
  134567. };
  134568. static long _vq_quantmap__44c1_sm_p7_0[] = {
  134569. 11, 9, 7, 5, 3, 1, 0, 2,
  134570. 4, 6, 8, 10, 12,
  134571. };
  134572. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  134573. _vq_quantthresh__44c1_sm_p7_0,
  134574. _vq_quantmap__44c1_sm_p7_0,
  134575. 13,
  134576. 13
  134577. };
  134578. static static_codebook _44c1_sm_p7_0 = {
  134579. 2, 169,
  134580. _vq_lengthlist__44c1_sm_p7_0,
  134581. 1, -526516224, 1616117760, 4, 0,
  134582. _vq_quantlist__44c1_sm_p7_0,
  134583. NULL,
  134584. &_vq_auxt__44c1_sm_p7_0,
  134585. NULL,
  134586. 0
  134587. };
  134588. static long _vq_quantlist__44c1_sm_p7_1[] = {
  134589. 2,
  134590. 1,
  134591. 3,
  134592. 0,
  134593. 4,
  134594. };
  134595. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  134596. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  134597. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134598. };
  134599. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  134600. -1.5, -0.5, 0.5, 1.5,
  134601. };
  134602. static long _vq_quantmap__44c1_sm_p7_1[] = {
  134603. 3, 1, 0, 2, 4,
  134604. };
  134605. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  134606. _vq_quantthresh__44c1_sm_p7_1,
  134607. _vq_quantmap__44c1_sm_p7_1,
  134608. 5,
  134609. 5
  134610. };
  134611. static static_codebook _44c1_sm_p7_1 = {
  134612. 2, 25,
  134613. _vq_lengthlist__44c1_sm_p7_1,
  134614. 1, -533725184, 1611661312, 3, 0,
  134615. _vq_quantlist__44c1_sm_p7_1,
  134616. NULL,
  134617. &_vq_auxt__44c1_sm_p7_1,
  134618. NULL,
  134619. 0
  134620. };
  134621. static long _vq_quantlist__44c1_sm_p8_0[] = {
  134622. 6,
  134623. 5,
  134624. 7,
  134625. 4,
  134626. 8,
  134627. 3,
  134628. 9,
  134629. 2,
  134630. 10,
  134631. 1,
  134632. 11,
  134633. 0,
  134634. 12,
  134635. };
  134636. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  134637. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  134638. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  134639. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134640. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134641. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134642. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134643. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134644. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134645. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134646. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  134647. 13,13,13,13,13,13,13,13,13,
  134648. };
  134649. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  134650. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  134651. 552.5, 773.5, 994.5, 1215.5,
  134652. };
  134653. static long _vq_quantmap__44c1_sm_p8_0[] = {
  134654. 11, 9, 7, 5, 3, 1, 0, 2,
  134655. 4, 6, 8, 10, 12,
  134656. };
  134657. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  134658. _vq_quantthresh__44c1_sm_p8_0,
  134659. _vq_quantmap__44c1_sm_p8_0,
  134660. 13,
  134661. 13
  134662. };
  134663. static static_codebook _44c1_sm_p8_0 = {
  134664. 2, 169,
  134665. _vq_lengthlist__44c1_sm_p8_0,
  134666. 1, -514541568, 1627103232, 4, 0,
  134667. _vq_quantlist__44c1_sm_p8_0,
  134668. NULL,
  134669. &_vq_auxt__44c1_sm_p8_0,
  134670. NULL,
  134671. 0
  134672. };
  134673. static long _vq_quantlist__44c1_sm_p8_1[] = {
  134674. 6,
  134675. 5,
  134676. 7,
  134677. 4,
  134678. 8,
  134679. 3,
  134680. 9,
  134681. 2,
  134682. 10,
  134683. 1,
  134684. 11,
  134685. 0,
  134686. 12,
  134687. };
  134688. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  134689. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  134690. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  134691. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  134692. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  134693. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  134694. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  134695. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  134696. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  134697. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  134698. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  134699. 20,13,12,12,12,14,12,14,13,
  134700. };
  134701. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  134702. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  134703. 42.5, 59.5, 76.5, 93.5,
  134704. };
  134705. static long _vq_quantmap__44c1_sm_p8_1[] = {
  134706. 11, 9, 7, 5, 3, 1, 0, 2,
  134707. 4, 6, 8, 10, 12,
  134708. };
  134709. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  134710. _vq_quantthresh__44c1_sm_p8_1,
  134711. _vq_quantmap__44c1_sm_p8_1,
  134712. 13,
  134713. 13
  134714. };
  134715. static static_codebook _44c1_sm_p8_1 = {
  134716. 2, 169,
  134717. _vq_lengthlist__44c1_sm_p8_1,
  134718. 1, -522616832, 1620115456, 4, 0,
  134719. _vq_quantlist__44c1_sm_p8_1,
  134720. NULL,
  134721. &_vq_auxt__44c1_sm_p8_1,
  134722. NULL,
  134723. 0
  134724. };
  134725. static long _vq_quantlist__44c1_sm_p8_2[] = {
  134726. 8,
  134727. 7,
  134728. 9,
  134729. 6,
  134730. 10,
  134731. 5,
  134732. 11,
  134733. 4,
  134734. 12,
  134735. 3,
  134736. 13,
  134737. 2,
  134738. 14,
  134739. 1,
  134740. 15,
  134741. 0,
  134742. 16,
  134743. };
  134744. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  134745. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  134746. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  134747. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134748. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  134749. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  134750. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  134751. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  134752. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  134753. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  134754. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  134755. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  134756. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  134757. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  134758. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  134759. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  134760. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  134761. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  134762. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  134763. 9,
  134764. };
  134765. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  134766. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134767. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134768. };
  134769. static long _vq_quantmap__44c1_sm_p8_2[] = {
  134770. 15, 13, 11, 9, 7, 5, 3, 1,
  134771. 0, 2, 4, 6, 8, 10, 12, 14,
  134772. 16,
  134773. };
  134774. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  134775. _vq_quantthresh__44c1_sm_p8_2,
  134776. _vq_quantmap__44c1_sm_p8_2,
  134777. 17,
  134778. 17
  134779. };
  134780. static static_codebook _44c1_sm_p8_2 = {
  134781. 2, 289,
  134782. _vq_lengthlist__44c1_sm_p8_2,
  134783. 1, -529530880, 1611661312, 5, 0,
  134784. _vq_quantlist__44c1_sm_p8_2,
  134785. NULL,
  134786. &_vq_auxt__44c1_sm_p8_2,
  134787. NULL,
  134788. 0
  134789. };
  134790. static long _huff_lengthlist__44c1_sm_short[] = {
  134791. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  134792. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  134793. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  134794. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  134795. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  134796. 11,
  134797. };
  134798. static static_codebook _huff_book__44c1_sm_short = {
  134799. 2, 81,
  134800. _huff_lengthlist__44c1_sm_short,
  134801. 0, 0, 0, 0, 0,
  134802. NULL,
  134803. NULL,
  134804. NULL,
  134805. NULL,
  134806. 0
  134807. };
  134808. static long _huff_lengthlist__44cn1_s_long[] = {
  134809. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  134810. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  134811. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  134812. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  134813. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  134814. 20,
  134815. };
  134816. static static_codebook _huff_book__44cn1_s_long = {
  134817. 2, 81,
  134818. _huff_lengthlist__44cn1_s_long,
  134819. 0, 0, 0, 0, 0,
  134820. NULL,
  134821. NULL,
  134822. NULL,
  134823. NULL,
  134824. 0
  134825. };
  134826. static long _vq_quantlist__44cn1_s_p1_0[] = {
  134827. 1,
  134828. 0,
  134829. 2,
  134830. };
  134831. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  134832. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134833. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134837. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  134838. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134842. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  134843. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  134865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  134878. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  134879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  134883. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  134884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  134888. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  134889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134923. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  134924. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134928. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  134929. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  134930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134933. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  134934. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  134935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135242. 0,
  135243. };
  135244. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  135245. -0.5, 0.5,
  135246. };
  135247. static long _vq_quantmap__44cn1_s_p1_0[] = {
  135248. 1, 0, 2,
  135249. };
  135250. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  135251. _vq_quantthresh__44cn1_s_p1_0,
  135252. _vq_quantmap__44cn1_s_p1_0,
  135253. 3,
  135254. 3
  135255. };
  135256. static static_codebook _44cn1_s_p1_0 = {
  135257. 8, 6561,
  135258. _vq_lengthlist__44cn1_s_p1_0,
  135259. 1, -535822336, 1611661312, 2, 0,
  135260. _vq_quantlist__44cn1_s_p1_0,
  135261. NULL,
  135262. &_vq_auxt__44cn1_s_p1_0,
  135263. NULL,
  135264. 0
  135265. };
  135266. static long _vq_quantlist__44cn1_s_p2_0[] = {
  135267. 2,
  135268. 1,
  135269. 3,
  135270. 0,
  135271. 4,
  135272. };
  135273. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  135274. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  135276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135277. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135280. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135313. 0,
  135314. };
  135315. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  135316. -1.5, -0.5, 0.5, 1.5,
  135317. };
  135318. static long _vq_quantmap__44cn1_s_p2_0[] = {
  135319. 3, 1, 0, 2, 4,
  135320. };
  135321. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  135322. _vq_quantthresh__44cn1_s_p2_0,
  135323. _vq_quantmap__44cn1_s_p2_0,
  135324. 5,
  135325. 5
  135326. };
  135327. static static_codebook _44cn1_s_p2_0 = {
  135328. 4, 625,
  135329. _vq_lengthlist__44cn1_s_p2_0,
  135330. 1, -533725184, 1611661312, 3, 0,
  135331. _vq_quantlist__44cn1_s_p2_0,
  135332. NULL,
  135333. &_vq_auxt__44cn1_s_p2_0,
  135334. NULL,
  135335. 0
  135336. };
  135337. static long _vq_quantlist__44cn1_s_p3_0[] = {
  135338. 4,
  135339. 3,
  135340. 5,
  135341. 2,
  135342. 6,
  135343. 1,
  135344. 7,
  135345. 0,
  135346. 8,
  135347. };
  135348. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  135349. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  135350. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  135351. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135352. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135353. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135354. 0,
  135355. };
  135356. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  135357. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135358. };
  135359. static long _vq_quantmap__44cn1_s_p3_0[] = {
  135360. 7, 5, 3, 1, 0, 2, 4, 6,
  135361. 8,
  135362. };
  135363. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  135364. _vq_quantthresh__44cn1_s_p3_0,
  135365. _vq_quantmap__44cn1_s_p3_0,
  135366. 9,
  135367. 9
  135368. };
  135369. static static_codebook _44cn1_s_p3_0 = {
  135370. 2, 81,
  135371. _vq_lengthlist__44cn1_s_p3_0,
  135372. 1, -531628032, 1611661312, 4, 0,
  135373. _vq_quantlist__44cn1_s_p3_0,
  135374. NULL,
  135375. &_vq_auxt__44cn1_s_p3_0,
  135376. NULL,
  135377. 0
  135378. };
  135379. static long _vq_quantlist__44cn1_s_p4_0[] = {
  135380. 4,
  135381. 3,
  135382. 5,
  135383. 2,
  135384. 6,
  135385. 1,
  135386. 7,
  135387. 0,
  135388. 8,
  135389. };
  135390. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  135391. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  135392. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  135393. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  135394. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  135395. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  135396. 11,
  135397. };
  135398. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  135399. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135400. };
  135401. static long _vq_quantmap__44cn1_s_p4_0[] = {
  135402. 7, 5, 3, 1, 0, 2, 4, 6,
  135403. 8,
  135404. };
  135405. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  135406. _vq_quantthresh__44cn1_s_p4_0,
  135407. _vq_quantmap__44cn1_s_p4_0,
  135408. 9,
  135409. 9
  135410. };
  135411. static static_codebook _44cn1_s_p4_0 = {
  135412. 2, 81,
  135413. _vq_lengthlist__44cn1_s_p4_0,
  135414. 1, -531628032, 1611661312, 4, 0,
  135415. _vq_quantlist__44cn1_s_p4_0,
  135416. NULL,
  135417. &_vq_auxt__44cn1_s_p4_0,
  135418. NULL,
  135419. 0
  135420. };
  135421. static long _vq_quantlist__44cn1_s_p5_0[] = {
  135422. 8,
  135423. 7,
  135424. 9,
  135425. 6,
  135426. 10,
  135427. 5,
  135428. 11,
  135429. 4,
  135430. 12,
  135431. 3,
  135432. 13,
  135433. 2,
  135434. 14,
  135435. 1,
  135436. 15,
  135437. 0,
  135438. 16,
  135439. };
  135440. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  135441. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  135442. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  135443. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  135444. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135445. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135446. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  135447. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  135448. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  135449. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135450. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  135451. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135452. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135453. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  135454. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  135455. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  135456. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  135457. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  135458. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  135459. 14,
  135460. };
  135461. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  135462. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135463. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135464. };
  135465. static long _vq_quantmap__44cn1_s_p5_0[] = {
  135466. 15, 13, 11, 9, 7, 5, 3, 1,
  135467. 0, 2, 4, 6, 8, 10, 12, 14,
  135468. 16,
  135469. };
  135470. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  135471. _vq_quantthresh__44cn1_s_p5_0,
  135472. _vq_quantmap__44cn1_s_p5_0,
  135473. 17,
  135474. 17
  135475. };
  135476. static static_codebook _44cn1_s_p5_0 = {
  135477. 2, 289,
  135478. _vq_lengthlist__44cn1_s_p5_0,
  135479. 1, -529530880, 1611661312, 5, 0,
  135480. _vq_quantlist__44cn1_s_p5_0,
  135481. NULL,
  135482. &_vq_auxt__44cn1_s_p5_0,
  135483. NULL,
  135484. 0
  135485. };
  135486. static long _vq_quantlist__44cn1_s_p6_0[] = {
  135487. 1,
  135488. 0,
  135489. 2,
  135490. };
  135491. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  135492. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  135493. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  135494. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  135495. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  135496. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  135497. 10,
  135498. };
  135499. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  135500. -5.5, 5.5,
  135501. };
  135502. static long _vq_quantmap__44cn1_s_p6_0[] = {
  135503. 1, 0, 2,
  135504. };
  135505. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  135506. _vq_quantthresh__44cn1_s_p6_0,
  135507. _vq_quantmap__44cn1_s_p6_0,
  135508. 3,
  135509. 3
  135510. };
  135511. static static_codebook _44cn1_s_p6_0 = {
  135512. 4, 81,
  135513. _vq_lengthlist__44cn1_s_p6_0,
  135514. 1, -529137664, 1618345984, 2, 0,
  135515. _vq_quantlist__44cn1_s_p6_0,
  135516. NULL,
  135517. &_vq_auxt__44cn1_s_p6_0,
  135518. NULL,
  135519. 0
  135520. };
  135521. static long _vq_quantlist__44cn1_s_p6_1[] = {
  135522. 5,
  135523. 4,
  135524. 6,
  135525. 3,
  135526. 7,
  135527. 2,
  135528. 8,
  135529. 1,
  135530. 9,
  135531. 0,
  135532. 10,
  135533. };
  135534. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  135535. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  135536. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  135537. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  135538. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  135539. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  135540. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135541. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  135542. 10,10,10, 9, 9, 9, 9, 9, 9,
  135543. };
  135544. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  135545. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135546. 3.5, 4.5,
  135547. };
  135548. static long _vq_quantmap__44cn1_s_p6_1[] = {
  135549. 9, 7, 5, 3, 1, 0, 2, 4,
  135550. 6, 8, 10,
  135551. };
  135552. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  135553. _vq_quantthresh__44cn1_s_p6_1,
  135554. _vq_quantmap__44cn1_s_p6_1,
  135555. 11,
  135556. 11
  135557. };
  135558. static static_codebook _44cn1_s_p6_1 = {
  135559. 2, 121,
  135560. _vq_lengthlist__44cn1_s_p6_1,
  135561. 1, -531365888, 1611661312, 4, 0,
  135562. _vq_quantlist__44cn1_s_p6_1,
  135563. NULL,
  135564. &_vq_auxt__44cn1_s_p6_1,
  135565. NULL,
  135566. 0
  135567. };
  135568. static long _vq_quantlist__44cn1_s_p7_0[] = {
  135569. 6,
  135570. 5,
  135571. 7,
  135572. 4,
  135573. 8,
  135574. 3,
  135575. 9,
  135576. 2,
  135577. 10,
  135578. 1,
  135579. 11,
  135580. 0,
  135581. 12,
  135582. };
  135583. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  135584. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  135585. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  135586. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135587. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135588. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  135589. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  135590. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  135591. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  135592. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  135593. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  135594. 0,13,13,12,12,13,13,13,14,
  135595. };
  135596. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  135597. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135598. 12.5, 17.5, 22.5, 27.5,
  135599. };
  135600. static long _vq_quantmap__44cn1_s_p7_0[] = {
  135601. 11, 9, 7, 5, 3, 1, 0, 2,
  135602. 4, 6, 8, 10, 12,
  135603. };
  135604. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  135605. _vq_quantthresh__44cn1_s_p7_0,
  135606. _vq_quantmap__44cn1_s_p7_0,
  135607. 13,
  135608. 13
  135609. };
  135610. static static_codebook _44cn1_s_p7_0 = {
  135611. 2, 169,
  135612. _vq_lengthlist__44cn1_s_p7_0,
  135613. 1, -526516224, 1616117760, 4, 0,
  135614. _vq_quantlist__44cn1_s_p7_0,
  135615. NULL,
  135616. &_vq_auxt__44cn1_s_p7_0,
  135617. NULL,
  135618. 0
  135619. };
  135620. static long _vq_quantlist__44cn1_s_p7_1[] = {
  135621. 2,
  135622. 1,
  135623. 3,
  135624. 0,
  135625. 4,
  135626. };
  135627. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  135628. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  135629. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  135630. };
  135631. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  135632. -1.5, -0.5, 0.5, 1.5,
  135633. };
  135634. static long _vq_quantmap__44cn1_s_p7_1[] = {
  135635. 3, 1, 0, 2, 4,
  135636. };
  135637. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  135638. _vq_quantthresh__44cn1_s_p7_1,
  135639. _vq_quantmap__44cn1_s_p7_1,
  135640. 5,
  135641. 5
  135642. };
  135643. static static_codebook _44cn1_s_p7_1 = {
  135644. 2, 25,
  135645. _vq_lengthlist__44cn1_s_p7_1,
  135646. 1, -533725184, 1611661312, 3, 0,
  135647. _vq_quantlist__44cn1_s_p7_1,
  135648. NULL,
  135649. &_vq_auxt__44cn1_s_p7_1,
  135650. NULL,
  135651. 0
  135652. };
  135653. static long _vq_quantlist__44cn1_s_p8_0[] = {
  135654. 2,
  135655. 1,
  135656. 3,
  135657. 0,
  135658. 4,
  135659. };
  135660. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  135661. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  135662. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  135663. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135664. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  135665. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135666. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135667. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135668. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  135669. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135670. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  135671. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  135672. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135673. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135674. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135675. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135676. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  135677. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135678. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135679. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135680. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135681. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135682. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135683. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135684. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135685. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135686. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135687. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135688. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135689. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135690. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135691. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135692. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135693. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135694. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  135695. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135696. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135697. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135698. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135699. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135700. 12,
  135701. };
  135702. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  135703. -331.5, -110.5, 110.5, 331.5,
  135704. };
  135705. static long _vq_quantmap__44cn1_s_p8_0[] = {
  135706. 3, 1, 0, 2, 4,
  135707. };
  135708. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  135709. _vq_quantthresh__44cn1_s_p8_0,
  135710. _vq_quantmap__44cn1_s_p8_0,
  135711. 5,
  135712. 5
  135713. };
  135714. static static_codebook _44cn1_s_p8_0 = {
  135715. 4, 625,
  135716. _vq_lengthlist__44cn1_s_p8_0,
  135717. 1, -518283264, 1627103232, 3, 0,
  135718. _vq_quantlist__44cn1_s_p8_0,
  135719. NULL,
  135720. &_vq_auxt__44cn1_s_p8_0,
  135721. NULL,
  135722. 0
  135723. };
  135724. static long _vq_quantlist__44cn1_s_p8_1[] = {
  135725. 6,
  135726. 5,
  135727. 7,
  135728. 4,
  135729. 8,
  135730. 3,
  135731. 9,
  135732. 2,
  135733. 10,
  135734. 1,
  135735. 11,
  135736. 0,
  135737. 12,
  135738. };
  135739. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  135740. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  135741. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  135742. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  135743. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  135744. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  135745. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  135746. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  135747. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  135748. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  135749. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  135750. 15,12,12,11,11,14,12,13,14,
  135751. };
  135752. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  135753. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135754. 42.5, 59.5, 76.5, 93.5,
  135755. };
  135756. static long _vq_quantmap__44cn1_s_p8_1[] = {
  135757. 11, 9, 7, 5, 3, 1, 0, 2,
  135758. 4, 6, 8, 10, 12,
  135759. };
  135760. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  135761. _vq_quantthresh__44cn1_s_p8_1,
  135762. _vq_quantmap__44cn1_s_p8_1,
  135763. 13,
  135764. 13
  135765. };
  135766. static static_codebook _44cn1_s_p8_1 = {
  135767. 2, 169,
  135768. _vq_lengthlist__44cn1_s_p8_1,
  135769. 1, -522616832, 1620115456, 4, 0,
  135770. _vq_quantlist__44cn1_s_p8_1,
  135771. NULL,
  135772. &_vq_auxt__44cn1_s_p8_1,
  135773. NULL,
  135774. 0
  135775. };
  135776. static long _vq_quantlist__44cn1_s_p8_2[] = {
  135777. 8,
  135778. 7,
  135779. 9,
  135780. 6,
  135781. 10,
  135782. 5,
  135783. 11,
  135784. 4,
  135785. 12,
  135786. 3,
  135787. 13,
  135788. 2,
  135789. 14,
  135790. 1,
  135791. 15,
  135792. 0,
  135793. 16,
  135794. };
  135795. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  135796. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  135797. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  135798. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  135799. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  135800. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  135801. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  135802. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  135803. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  135804. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  135805. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  135806. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  135807. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  135808. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  135809. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  135810. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  135811. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  135812. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135813. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  135814. 9,
  135815. };
  135816. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  135817. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135818. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135819. };
  135820. static long _vq_quantmap__44cn1_s_p8_2[] = {
  135821. 15, 13, 11, 9, 7, 5, 3, 1,
  135822. 0, 2, 4, 6, 8, 10, 12, 14,
  135823. 16,
  135824. };
  135825. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  135826. _vq_quantthresh__44cn1_s_p8_2,
  135827. _vq_quantmap__44cn1_s_p8_2,
  135828. 17,
  135829. 17
  135830. };
  135831. static static_codebook _44cn1_s_p8_2 = {
  135832. 2, 289,
  135833. _vq_lengthlist__44cn1_s_p8_2,
  135834. 1, -529530880, 1611661312, 5, 0,
  135835. _vq_quantlist__44cn1_s_p8_2,
  135836. NULL,
  135837. &_vq_auxt__44cn1_s_p8_2,
  135838. NULL,
  135839. 0
  135840. };
  135841. static long _huff_lengthlist__44cn1_s_short[] = {
  135842. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  135843. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  135844. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  135845. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  135846. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  135847. 10,
  135848. };
  135849. static static_codebook _huff_book__44cn1_s_short = {
  135850. 2, 81,
  135851. _huff_lengthlist__44cn1_s_short,
  135852. 0, 0, 0, 0, 0,
  135853. NULL,
  135854. NULL,
  135855. NULL,
  135856. NULL,
  135857. 0
  135858. };
  135859. static long _huff_lengthlist__44cn1_sm_long[] = {
  135860. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  135861. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  135862. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  135863. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  135864. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  135865. 17,
  135866. };
  135867. static static_codebook _huff_book__44cn1_sm_long = {
  135868. 2, 81,
  135869. _huff_lengthlist__44cn1_sm_long,
  135870. 0, 0, 0, 0, 0,
  135871. NULL,
  135872. NULL,
  135873. NULL,
  135874. NULL,
  135875. 0
  135876. };
  135877. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  135878. 1,
  135879. 0,
  135880. 2,
  135881. };
  135882. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  135883. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135884. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  135889. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  135894. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  135929. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  135930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  135934. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135939. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  135975. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  135980. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  135985. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0,
  136294. };
  136295. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  136296. -0.5, 0.5,
  136297. };
  136298. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  136299. 1, 0, 2,
  136300. };
  136301. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  136302. _vq_quantthresh__44cn1_sm_p1_0,
  136303. _vq_quantmap__44cn1_sm_p1_0,
  136304. 3,
  136305. 3
  136306. };
  136307. static static_codebook _44cn1_sm_p1_0 = {
  136308. 8, 6561,
  136309. _vq_lengthlist__44cn1_sm_p1_0,
  136310. 1, -535822336, 1611661312, 2, 0,
  136311. _vq_quantlist__44cn1_sm_p1_0,
  136312. NULL,
  136313. &_vq_auxt__44cn1_sm_p1_0,
  136314. NULL,
  136315. 0
  136316. };
  136317. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  136318. 2,
  136319. 1,
  136320. 3,
  136321. 0,
  136322. 4,
  136323. };
  136324. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  136325. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136328. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136331. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136364. 0,
  136365. };
  136366. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  136367. -1.5, -0.5, 0.5, 1.5,
  136368. };
  136369. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  136370. 3, 1, 0, 2, 4,
  136371. };
  136372. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  136373. _vq_quantthresh__44cn1_sm_p2_0,
  136374. _vq_quantmap__44cn1_sm_p2_0,
  136375. 5,
  136376. 5
  136377. };
  136378. static static_codebook _44cn1_sm_p2_0 = {
  136379. 4, 625,
  136380. _vq_lengthlist__44cn1_sm_p2_0,
  136381. 1, -533725184, 1611661312, 3, 0,
  136382. _vq_quantlist__44cn1_sm_p2_0,
  136383. NULL,
  136384. &_vq_auxt__44cn1_sm_p2_0,
  136385. NULL,
  136386. 0
  136387. };
  136388. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  136389. 4,
  136390. 3,
  136391. 5,
  136392. 2,
  136393. 6,
  136394. 1,
  136395. 7,
  136396. 0,
  136397. 8,
  136398. };
  136399. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  136400. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  136401. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  136402. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  136403. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  136404. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136405. 0,
  136406. };
  136407. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  136408. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136409. };
  136410. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  136411. 7, 5, 3, 1, 0, 2, 4, 6,
  136412. 8,
  136413. };
  136414. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  136415. _vq_quantthresh__44cn1_sm_p3_0,
  136416. _vq_quantmap__44cn1_sm_p3_0,
  136417. 9,
  136418. 9
  136419. };
  136420. static static_codebook _44cn1_sm_p3_0 = {
  136421. 2, 81,
  136422. _vq_lengthlist__44cn1_sm_p3_0,
  136423. 1, -531628032, 1611661312, 4, 0,
  136424. _vq_quantlist__44cn1_sm_p3_0,
  136425. NULL,
  136426. &_vq_auxt__44cn1_sm_p3_0,
  136427. NULL,
  136428. 0
  136429. };
  136430. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  136431. 4,
  136432. 3,
  136433. 5,
  136434. 2,
  136435. 6,
  136436. 1,
  136437. 7,
  136438. 0,
  136439. 8,
  136440. };
  136441. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  136442. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  136443. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  136444. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  136445. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  136446. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  136447. 11,
  136448. };
  136449. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  136450. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136451. };
  136452. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  136453. 7, 5, 3, 1, 0, 2, 4, 6,
  136454. 8,
  136455. };
  136456. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  136457. _vq_quantthresh__44cn1_sm_p4_0,
  136458. _vq_quantmap__44cn1_sm_p4_0,
  136459. 9,
  136460. 9
  136461. };
  136462. static static_codebook _44cn1_sm_p4_0 = {
  136463. 2, 81,
  136464. _vq_lengthlist__44cn1_sm_p4_0,
  136465. 1, -531628032, 1611661312, 4, 0,
  136466. _vq_quantlist__44cn1_sm_p4_0,
  136467. NULL,
  136468. &_vq_auxt__44cn1_sm_p4_0,
  136469. NULL,
  136470. 0
  136471. };
  136472. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  136473. 8,
  136474. 7,
  136475. 9,
  136476. 6,
  136477. 10,
  136478. 5,
  136479. 11,
  136480. 4,
  136481. 12,
  136482. 3,
  136483. 13,
  136484. 2,
  136485. 14,
  136486. 1,
  136487. 15,
  136488. 0,
  136489. 16,
  136490. };
  136491. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  136492. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  136493. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  136494. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  136495. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136496. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  136497. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  136498. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  136499. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136500. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  136501. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  136502. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  136503. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  136504. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  136505. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  136506. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  136507. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  136508. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  136509. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  136510. 14,
  136511. };
  136512. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  136513. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136514. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136515. };
  136516. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  136517. 15, 13, 11, 9, 7, 5, 3, 1,
  136518. 0, 2, 4, 6, 8, 10, 12, 14,
  136519. 16,
  136520. };
  136521. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  136522. _vq_quantthresh__44cn1_sm_p5_0,
  136523. _vq_quantmap__44cn1_sm_p5_0,
  136524. 17,
  136525. 17
  136526. };
  136527. static static_codebook _44cn1_sm_p5_0 = {
  136528. 2, 289,
  136529. _vq_lengthlist__44cn1_sm_p5_0,
  136530. 1, -529530880, 1611661312, 5, 0,
  136531. _vq_quantlist__44cn1_sm_p5_0,
  136532. NULL,
  136533. &_vq_auxt__44cn1_sm_p5_0,
  136534. NULL,
  136535. 0
  136536. };
  136537. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  136538. 1,
  136539. 0,
  136540. 2,
  136541. };
  136542. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  136543. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  136544. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  136545. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  136546. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  136547. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  136548. 10,
  136549. };
  136550. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  136551. -5.5, 5.5,
  136552. };
  136553. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  136554. 1, 0, 2,
  136555. };
  136556. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  136557. _vq_quantthresh__44cn1_sm_p6_0,
  136558. _vq_quantmap__44cn1_sm_p6_0,
  136559. 3,
  136560. 3
  136561. };
  136562. static static_codebook _44cn1_sm_p6_0 = {
  136563. 4, 81,
  136564. _vq_lengthlist__44cn1_sm_p6_0,
  136565. 1, -529137664, 1618345984, 2, 0,
  136566. _vq_quantlist__44cn1_sm_p6_0,
  136567. NULL,
  136568. &_vq_auxt__44cn1_sm_p6_0,
  136569. NULL,
  136570. 0
  136571. };
  136572. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  136573. 5,
  136574. 4,
  136575. 6,
  136576. 3,
  136577. 7,
  136578. 2,
  136579. 8,
  136580. 1,
  136581. 9,
  136582. 0,
  136583. 10,
  136584. };
  136585. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  136586. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  136587. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  136588. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  136589. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  136590. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  136591. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  136592. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  136593. 10,10,10, 8, 9, 8, 8, 9, 8,
  136594. };
  136595. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  136596. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136597. 3.5, 4.5,
  136598. };
  136599. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  136600. 9, 7, 5, 3, 1, 0, 2, 4,
  136601. 6, 8, 10,
  136602. };
  136603. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  136604. _vq_quantthresh__44cn1_sm_p6_1,
  136605. _vq_quantmap__44cn1_sm_p6_1,
  136606. 11,
  136607. 11
  136608. };
  136609. static static_codebook _44cn1_sm_p6_1 = {
  136610. 2, 121,
  136611. _vq_lengthlist__44cn1_sm_p6_1,
  136612. 1, -531365888, 1611661312, 4, 0,
  136613. _vq_quantlist__44cn1_sm_p6_1,
  136614. NULL,
  136615. &_vq_auxt__44cn1_sm_p6_1,
  136616. NULL,
  136617. 0
  136618. };
  136619. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  136620. 6,
  136621. 5,
  136622. 7,
  136623. 4,
  136624. 8,
  136625. 3,
  136626. 9,
  136627. 2,
  136628. 10,
  136629. 1,
  136630. 11,
  136631. 0,
  136632. 12,
  136633. };
  136634. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  136635. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  136636. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  136637. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136638. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136639. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  136640. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  136641. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  136642. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  136643. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  136644. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  136645. 0,13,12,12,12,13,13,13,14,
  136646. };
  136647. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  136648. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136649. 12.5, 17.5, 22.5, 27.5,
  136650. };
  136651. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  136652. 11, 9, 7, 5, 3, 1, 0, 2,
  136653. 4, 6, 8, 10, 12,
  136654. };
  136655. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  136656. _vq_quantthresh__44cn1_sm_p7_0,
  136657. _vq_quantmap__44cn1_sm_p7_0,
  136658. 13,
  136659. 13
  136660. };
  136661. static static_codebook _44cn1_sm_p7_0 = {
  136662. 2, 169,
  136663. _vq_lengthlist__44cn1_sm_p7_0,
  136664. 1, -526516224, 1616117760, 4, 0,
  136665. _vq_quantlist__44cn1_sm_p7_0,
  136666. NULL,
  136667. &_vq_auxt__44cn1_sm_p7_0,
  136668. NULL,
  136669. 0
  136670. };
  136671. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  136672. 2,
  136673. 1,
  136674. 3,
  136675. 0,
  136676. 4,
  136677. };
  136678. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  136679. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  136680. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  136681. };
  136682. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  136683. -1.5, -0.5, 0.5, 1.5,
  136684. };
  136685. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  136686. 3, 1, 0, 2, 4,
  136687. };
  136688. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  136689. _vq_quantthresh__44cn1_sm_p7_1,
  136690. _vq_quantmap__44cn1_sm_p7_1,
  136691. 5,
  136692. 5
  136693. };
  136694. static static_codebook _44cn1_sm_p7_1 = {
  136695. 2, 25,
  136696. _vq_lengthlist__44cn1_sm_p7_1,
  136697. 1, -533725184, 1611661312, 3, 0,
  136698. _vq_quantlist__44cn1_sm_p7_1,
  136699. NULL,
  136700. &_vq_auxt__44cn1_sm_p7_1,
  136701. NULL,
  136702. 0
  136703. };
  136704. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  136705. 4,
  136706. 3,
  136707. 5,
  136708. 2,
  136709. 6,
  136710. 1,
  136711. 7,
  136712. 0,
  136713. 8,
  136714. };
  136715. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  136716. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  136717. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  136718. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  136719. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  136720. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  136721. 14,
  136722. };
  136723. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  136724. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  136725. };
  136726. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  136727. 7, 5, 3, 1, 0, 2, 4, 6,
  136728. 8,
  136729. };
  136730. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  136731. _vq_quantthresh__44cn1_sm_p8_0,
  136732. _vq_quantmap__44cn1_sm_p8_0,
  136733. 9,
  136734. 9
  136735. };
  136736. static static_codebook _44cn1_sm_p8_0 = {
  136737. 2, 81,
  136738. _vq_lengthlist__44cn1_sm_p8_0,
  136739. 1, -516186112, 1627103232, 4, 0,
  136740. _vq_quantlist__44cn1_sm_p8_0,
  136741. NULL,
  136742. &_vq_auxt__44cn1_sm_p8_0,
  136743. NULL,
  136744. 0
  136745. };
  136746. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  136747. 6,
  136748. 5,
  136749. 7,
  136750. 4,
  136751. 8,
  136752. 3,
  136753. 9,
  136754. 2,
  136755. 10,
  136756. 1,
  136757. 11,
  136758. 0,
  136759. 12,
  136760. };
  136761. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  136762. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  136763. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  136764. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  136765. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  136766. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  136767. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  136768. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  136769. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  136770. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  136771. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  136772. 17,12,12,11,10,13,11,13,13,
  136773. };
  136774. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  136775. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136776. 42.5, 59.5, 76.5, 93.5,
  136777. };
  136778. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  136779. 11, 9, 7, 5, 3, 1, 0, 2,
  136780. 4, 6, 8, 10, 12,
  136781. };
  136782. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  136783. _vq_quantthresh__44cn1_sm_p8_1,
  136784. _vq_quantmap__44cn1_sm_p8_1,
  136785. 13,
  136786. 13
  136787. };
  136788. static static_codebook _44cn1_sm_p8_1 = {
  136789. 2, 169,
  136790. _vq_lengthlist__44cn1_sm_p8_1,
  136791. 1, -522616832, 1620115456, 4, 0,
  136792. _vq_quantlist__44cn1_sm_p8_1,
  136793. NULL,
  136794. &_vq_auxt__44cn1_sm_p8_1,
  136795. NULL,
  136796. 0
  136797. };
  136798. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  136799. 8,
  136800. 7,
  136801. 9,
  136802. 6,
  136803. 10,
  136804. 5,
  136805. 11,
  136806. 4,
  136807. 12,
  136808. 3,
  136809. 13,
  136810. 2,
  136811. 14,
  136812. 1,
  136813. 15,
  136814. 0,
  136815. 16,
  136816. };
  136817. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  136818. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  136819. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  136820. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  136821. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136822. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  136823. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  136824. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  136825. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  136826. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  136827. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  136828. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  136829. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  136830. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  136831. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  136832. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  136833. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  136834. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  136835. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  136836. 9,
  136837. };
  136838. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  136839. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136840. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136841. };
  136842. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  136843. 15, 13, 11, 9, 7, 5, 3, 1,
  136844. 0, 2, 4, 6, 8, 10, 12, 14,
  136845. 16,
  136846. };
  136847. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  136848. _vq_quantthresh__44cn1_sm_p8_2,
  136849. _vq_quantmap__44cn1_sm_p8_2,
  136850. 17,
  136851. 17
  136852. };
  136853. static static_codebook _44cn1_sm_p8_2 = {
  136854. 2, 289,
  136855. _vq_lengthlist__44cn1_sm_p8_2,
  136856. 1, -529530880, 1611661312, 5, 0,
  136857. _vq_quantlist__44cn1_sm_p8_2,
  136858. NULL,
  136859. &_vq_auxt__44cn1_sm_p8_2,
  136860. NULL,
  136861. 0
  136862. };
  136863. static long _huff_lengthlist__44cn1_sm_short[] = {
  136864. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  136865. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  136866. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  136867. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  136868. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  136869. 9,
  136870. };
  136871. static static_codebook _huff_book__44cn1_sm_short = {
  136872. 2, 81,
  136873. _huff_lengthlist__44cn1_sm_short,
  136874. 0, 0, 0, 0, 0,
  136875. NULL,
  136876. NULL,
  136877. NULL,
  136878. NULL,
  136879. 0
  136880. };
  136881. /********* End of inlined file: res_books_stereo.h *********/
  136882. /***** residue backends *********************************************/
  136883. static vorbis_info_residue0 _residue_44_low={
  136884. 0,-1, -1, 9,-1,
  136885. /* 0 1 2 3 4 5 6 7 */
  136886. {0},
  136887. {-1},
  136888. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  136889. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  136890. };
  136891. static vorbis_info_residue0 _residue_44_mid={
  136892. 0,-1, -1, 10,-1,
  136893. /* 0 1 2 3 4 5 6 7 8 */
  136894. {0},
  136895. {-1},
  136896. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  136897. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  136898. };
  136899. static vorbis_info_residue0 _residue_44_high={
  136900. 0,-1, -1, 10,-1,
  136901. /* 0 1 2 3 4 5 6 7 8 */
  136902. {0},
  136903. {-1},
  136904. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  136905. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  136906. };
  136907. static static_bookblock _resbook_44s_n1={
  136908. {
  136909. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  136910. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  136911. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  136912. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  136913. }
  136914. };
  136915. static static_bookblock _resbook_44sm_n1={
  136916. {
  136917. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  136918. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  136919. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  136920. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  136921. }
  136922. };
  136923. static static_bookblock _resbook_44s_0={
  136924. {
  136925. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  136926. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  136927. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  136928. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  136929. }
  136930. };
  136931. static static_bookblock _resbook_44sm_0={
  136932. {
  136933. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  136934. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  136935. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  136936. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  136937. }
  136938. };
  136939. static static_bookblock _resbook_44s_1={
  136940. {
  136941. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  136942. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  136943. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  136944. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  136945. }
  136946. };
  136947. static static_bookblock _resbook_44sm_1={
  136948. {
  136949. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  136950. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  136951. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  136952. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  136953. }
  136954. };
  136955. static static_bookblock _resbook_44s_2={
  136956. {
  136957. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  136958. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  136959. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  136960. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  136961. }
  136962. };
  136963. static static_bookblock _resbook_44s_3={
  136964. {
  136965. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  136966. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  136967. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  136968. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  136969. }
  136970. };
  136971. static static_bookblock _resbook_44s_4={
  136972. {
  136973. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  136974. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  136975. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  136976. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  136977. }
  136978. };
  136979. static static_bookblock _resbook_44s_5={
  136980. {
  136981. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  136982. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  136983. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  136984. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  136985. }
  136986. };
  136987. static static_bookblock _resbook_44s_6={
  136988. {
  136989. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  136990. {0,0,&_44c6_s_p4_0},
  136991. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  136992. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  136993. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  136994. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  136995. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  136996. }
  136997. };
  136998. static static_bookblock _resbook_44s_7={
  136999. {
  137000. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  137001. {0,0,&_44c7_s_p4_0},
  137002. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  137003. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  137004. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  137005. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  137006. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  137007. }
  137008. };
  137009. static static_bookblock _resbook_44s_8={
  137010. {
  137011. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  137012. {0,0,&_44c8_s_p4_0},
  137013. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  137014. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  137015. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  137016. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  137017. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  137018. }
  137019. };
  137020. static static_bookblock _resbook_44s_9={
  137021. {
  137022. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  137023. {0,0,&_44c9_s_p4_0},
  137024. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  137025. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  137026. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  137027. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  137028. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  137029. }
  137030. };
  137031. static vorbis_residue_template _res_44s_n1[]={
  137032. {2,0, &_residue_44_low,
  137033. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  137034. &_resbook_44s_n1,&_resbook_44sm_n1},
  137035. {2,0, &_residue_44_low,
  137036. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  137037. &_resbook_44s_n1,&_resbook_44sm_n1}
  137038. };
  137039. static vorbis_residue_template _res_44s_0[]={
  137040. {2,0, &_residue_44_low,
  137041. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  137042. &_resbook_44s_0,&_resbook_44sm_0},
  137043. {2,0, &_residue_44_low,
  137044. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  137045. &_resbook_44s_0,&_resbook_44sm_0}
  137046. };
  137047. static vorbis_residue_template _res_44s_1[]={
  137048. {2,0, &_residue_44_low,
  137049. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  137050. &_resbook_44s_1,&_resbook_44sm_1},
  137051. {2,0, &_residue_44_low,
  137052. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  137053. &_resbook_44s_1,&_resbook_44sm_1}
  137054. };
  137055. static vorbis_residue_template _res_44s_2[]={
  137056. {2,0, &_residue_44_mid,
  137057. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  137058. &_resbook_44s_2,&_resbook_44s_2},
  137059. {2,0, &_residue_44_mid,
  137060. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  137061. &_resbook_44s_2,&_resbook_44s_2}
  137062. };
  137063. static vorbis_residue_template _res_44s_3[]={
  137064. {2,0, &_residue_44_mid,
  137065. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  137066. &_resbook_44s_3,&_resbook_44s_3},
  137067. {2,0, &_residue_44_mid,
  137068. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  137069. &_resbook_44s_3,&_resbook_44s_3}
  137070. };
  137071. static vorbis_residue_template _res_44s_4[]={
  137072. {2,0, &_residue_44_mid,
  137073. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  137074. &_resbook_44s_4,&_resbook_44s_4},
  137075. {2,0, &_residue_44_mid,
  137076. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  137077. &_resbook_44s_4,&_resbook_44s_4}
  137078. };
  137079. static vorbis_residue_template _res_44s_5[]={
  137080. {2,0, &_residue_44_mid,
  137081. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  137082. &_resbook_44s_5,&_resbook_44s_5},
  137083. {2,0, &_residue_44_mid,
  137084. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  137085. &_resbook_44s_5,&_resbook_44s_5}
  137086. };
  137087. static vorbis_residue_template _res_44s_6[]={
  137088. {2,0, &_residue_44_high,
  137089. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  137090. &_resbook_44s_6,&_resbook_44s_6},
  137091. {2,0, &_residue_44_high,
  137092. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  137093. &_resbook_44s_6,&_resbook_44s_6}
  137094. };
  137095. static vorbis_residue_template _res_44s_7[]={
  137096. {2,0, &_residue_44_high,
  137097. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  137098. &_resbook_44s_7,&_resbook_44s_7},
  137099. {2,0, &_residue_44_high,
  137100. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  137101. &_resbook_44s_7,&_resbook_44s_7}
  137102. };
  137103. static vorbis_residue_template _res_44s_8[]={
  137104. {2,0, &_residue_44_high,
  137105. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  137106. &_resbook_44s_8,&_resbook_44s_8},
  137107. {2,0, &_residue_44_high,
  137108. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  137109. &_resbook_44s_8,&_resbook_44s_8}
  137110. };
  137111. static vorbis_residue_template _res_44s_9[]={
  137112. {2,0, &_residue_44_high,
  137113. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  137114. &_resbook_44s_9,&_resbook_44s_9},
  137115. {2,0, &_residue_44_high,
  137116. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  137117. &_resbook_44s_9,&_resbook_44s_9}
  137118. };
  137119. static vorbis_mapping_template _mapres_template_44_stereo[]={
  137120. { _map_nominal, _res_44s_n1 }, /* -1 */
  137121. { _map_nominal, _res_44s_0 }, /* 0 */
  137122. { _map_nominal, _res_44s_1 }, /* 1 */
  137123. { _map_nominal, _res_44s_2 }, /* 2 */
  137124. { _map_nominal, _res_44s_3 }, /* 3 */
  137125. { _map_nominal, _res_44s_4 }, /* 4 */
  137126. { _map_nominal, _res_44s_5 }, /* 5 */
  137127. { _map_nominal, _res_44s_6 }, /* 6 */
  137128. { _map_nominal, _res_44s_7 }, /* 7 */
  137129. { _map_nominal, _res_44s_8 }, /* 8 */
  137130. { _map_nominal, _res_44s_9 }, /* 9 */
  137131. };
  137132. /********* End of inlined file: residue_44.h *********/
  137133. /********* Start of inlined file: psych_44.h *********/
  137134. /* preecho trigger settings *****************************************/
  137135. static vorbis_info_psy_global _psy_global_44[5]={
  137136. {8, /* lines per eighth octave */
  137137. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  137138. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  137139. -6.f,
  137140. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137141. },
  137142. {8, /* lines per eighth octave */
  137143. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  137144. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  137145. -6.f,
  137146. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137147. },
  137148. {8, /* lines per eighth octave */
  137149. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  137150. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  137151. -6.f,
  137152. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137153. },
  137154. {8, /* lines per eighth octave */
  137155. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  137156. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  137157. -6.f,
  137158. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137159. },
  137160. {8, /* lines per eighth octave */
  137161. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  137162. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  137163. -6.f,
  137164. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137165. },
  137166. };
  137167. /* noise compander lookups * low, mid, high quality ****************/
  137168. static compandblock _psy_compand_44[6]={
  137169. /* sub-mode Z short */
  137170. {{
  137171. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137172. 8, 9,10,11,12,13,14, 15, /* 15dB */
  137173. 16,17,18,19,20,21,22, 23, /* 23dB */
  137174. 24,25,26,27,28,29,30, 31, /* 31dB */
  137175. 32,33,34,35,36,37,38, 39, /* 39dB */
  137176. }},
  137177. /* mode_Z nominal short */
  137178. {{
  137179. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  137180. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  137181. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  137182. 15,16,17,17,17,18,18, 19, /* 31dB */
  137183. 19,19,20,21,22,23,24, 25, /* 39dB */
  137184. }},
  137185. /* mode A short */
  137186. {{
  137187. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  137188. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  137189. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  137190. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  137191. 11,12,13,14,15,16,17, 18, /* 39dB */
  137192. }},
  137193. /* sub-mode Z long */
  137194. {{
  137195. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137196. 8, 9,10,11,12,13,14, 15, /* 15dB */
  137197. 16,17,18,19,20,21,22, 23, /* 23dB */
  137198. 24,25,26,27,28,29,30, 31, /* 31dB */
  137199. 32,33,34,35,36,37,38, 39, /* 39dB */
  137200. }},
  137201. /* mode_Z nominal long */
  137202. {{
  137203. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137204. 8, 9,10,11,12,12,13, 13, /* 15dB */
  137205. 13,14,14,14,15,15,15, 15, /* 23dB */
  137206. 16,16,17,17,17,18,18, 19, /* 31dB */
  137207. 19,19,20,21,22,23,24, 25, /* 39dB */
  137208. }},
  137209. /* mode A long */
  137210. {{
  137211. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137212. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  137213. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  137214. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  137215. 11,12,13,14,15,16,17, 18, /* 39dB */
  137216. }}
  137217. };
  137218. /* tonal masking curve level adjustments *************************/
  137219. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  137220. /* 63 125 250 500 1 2 4 8 16 */
  137221. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  137222. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  137223. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  137224. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  137225. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  137226. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  137227. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  137228. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  137229. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  137230. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  137231. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  137232. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  137233. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  137234. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  137235. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  137236. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  137237. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  137238. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  137239. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  137240. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  137241. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  137242. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  137243. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  137244. };
  137245. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  137246. /* 63 125 250 500 1 2 4 8 16 */
  137247. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  137248. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  137249. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  137250. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  137251. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  137252. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  137253. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  137254. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  137255. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  137256. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  137257. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  137258. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  137259. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  137260. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  137261. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  137262. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  137263. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  137264. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  137265. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  137266. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  137267. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  137268. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  137269. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  137270. };
  137271. /* noise bias (transition block) */
  137272. static noise3 _psy_noisebias_trans[12]={
  137273. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  137274. /* -1 */
  137275. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  137276. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  137277. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  137278. /* 0
  137279. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137280. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  137281. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  137282. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137283. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  137284. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  137285. /* 1
  137286. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137287. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  137288. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  137289. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137290. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  137291. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  137292. /* 2
  137293. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  137294. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  137295. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  137296. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  137297. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  137298. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  137299. /* 3
  137300. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  137301. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  137302. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  137303. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  137304. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  137305. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  137306. /* 4
  137307. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137308. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  137309. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  137310. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137311. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  137312. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  137313. /* 5
  137314. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137315. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  137316. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  137317. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137318. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  137319. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  137320. /* 6
  137321. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137322. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  137323. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  137324. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137325. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  137326. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  137327. /* 7
  137328. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137329. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  137330. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  137331. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137332. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  137333. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  137334. /* 8
  137335. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  137336. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  137337. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  137338. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  137339. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  137340. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  137341. /* 9
  137342. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  137343. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  137344. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  137345. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  137346. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  137347. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  137348. /* 10 */
  137349. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  137350. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  137351. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  137352. };
  137353. /* noise bias (long block) */
  137354. static noise3 _psy_noisebias_long[12]={
  137355. /*63 125 250 500 1k 2k 4k 8k 16k*/
  137356. /* -1 */
  137357. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  137358. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  137359. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  137360. /* 0 */
  137361. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  137362. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  137363. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  137364. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  137365. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  137366. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  137367. /* 1 */
  137368. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137369. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  137370. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  137371. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137372. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  137373. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  137374. /* 2 */
  137375. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  137376. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  137377. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  137378. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  137379. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  137380. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  137381. /* 3 */
  137382. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  137383. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  137384. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  137385. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  137386. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  137387. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  137388. /* 4 */
  137389. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  137390. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  137391. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  137392. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  137393. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  137394. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  137395. /* 5 */
  137396. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  137397. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  137398. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  137399. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  137400. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  137401. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  137402. /* 6 */
  137403. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  137404. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  137405. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  137406. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  137407. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  137408. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  137409. /* 7 */
  137410. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  137411. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  137412. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  137413. /* 8 */
  137414. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  137415. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  137416. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  137417. /* 9 */
  137418. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  137419. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  137420. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  137421. /* 10 */
  137422. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  137423. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  137424. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  137425. };
  137426. /* noise bias (impulse block) */
  137427. static noise3 _psy_noisebias_impulse[12]={
  137428. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  137429. /* -1 */
  137430. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  137431. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  137432. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  137433. /* 0 */
  137434. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  137435. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  137436. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  137437. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  137438. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  137439. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  137440. /* 1 */
  137441. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  137442. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  137443. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  137444. /* 2 */
  137445. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  137446. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  137447. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  137448. /* 3 */
  137449. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  137450. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  137451. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  137452. /* 4 */
  137453. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  137454. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  137455. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  137456. /* 5 */
  137457. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  137458. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  137459. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  137460. /* 6
  137461. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  137462. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  137463. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  137464. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  137465. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  137466. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  137467. /* 7 */
  137468. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  137469. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  137470. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  137471. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  137472. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  137473. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  137474. /* 8 */
  137475. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  137476. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  137477. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  137478. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  137479. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  137480. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  137481. /* 9 */
  137482. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  137483. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  137484. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  137485. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  137486. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  137487. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  137488. /* 10 */
  137489. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  137490. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  137491. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  137492. };
  137493. /* noise bias (padding block) */
  137494. static noise3 _psy_noisebias_padding[12]={
  137495. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  137496. /* -1 */
  137497. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  137498. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  137499. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  137500. /* 0 */
  137501. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  137502. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  137503. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  137504. /* 1 */
  137505. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  137506. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  137507. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  137508. /* 2 */
  137509. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  137510. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  137511. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  137512. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  137513. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  137514. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  137515. /* 3 */
  137516. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  137517. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  137518. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  137519. /* 4 */
  137520. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  137521. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  137522. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  137523. /* 5 */
  137524. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  137525. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  137526. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  137527. /* 6 */
  137528. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  137529. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  137530. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  137531. /* 7 */
  137532. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  137533. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  137534. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  137535. /* 8 */
  137536. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  137537. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  137538. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  137539. /* 9 */
  137540. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  137541. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  137542. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  137543. /* 10 */
  137544. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  137545. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  137546. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  137547. };
  137548. static noiseguard _psy_noiseguards_44[4]={
  137549. {3,3,15},
  137550. {3,3,15},
  137551. {10,10,100},
  137552. {10,10,100},
  137553. };
  137554. static int _psy_tone_suppress[12]={
  137555. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  137556. };
  137557. static int _psy_tone_0dB[12]={
  137558. 90,90,95,95,95,95,105,105,105,105,105,105,
  137559. };
  137560. static int _psy_noise_suppress[12]={
  137561. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  137562. };
  137563. static vorbis_info_psy _psy_info_template={
  137564. /* blockflag */
  137565. -1,
  137566. /* ath_adjatt, ath_maxatt */
  137567. -140.,-140.,
  137568. /* tonemask att boost/decay,suppr,curves */
  137569. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  137570. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  137571. 1, -0.f, .5f, .5f, 0,0,0,
  137572. /* noiseoffset*3, noisecompand, max_curve_dB */
  137573. {{-1},{-1},{-1}},{-1},105.f,
  137574. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  137575. 0,0,-1,-1,0.,
  137576. };
  137577. /* ath ****************/
  137578. static int _psy_ath_floater[12]={
  137579. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  137580. };
  137581. static int _psy_ath_abs[12]={
  137582. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  137583. };
  137584. /* stereo setup. These don't map directly to quality level, there's
  137585. an additional indirection as several of the below may be used in a
  137586. single bitmanaged stream
  137587. ****************/
  137588. /* various stereo possibilities */
  137589. /* stereo mode by base quality level */
  137590. static adj_stereo _psy_stereo_modes_44[12]={
  137591. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  137592. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  137593. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  137594. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  137595. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  137596. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  137597. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  137598. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  137599. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  137600. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  137601. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  137602. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  137603. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  137604. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  137605. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  137606. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  137607. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  137608. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  137609. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137610. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  137611. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  137612. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  137613. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  137614. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  137615. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  137616. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  137617. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  137618. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137619. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  137620. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  137621. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  137622. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  137623. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137624. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  137625. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137626. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  137627. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  137628. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137629. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  137630. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137631. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  137632. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  137633. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  137634. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137635. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  137636. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  137637. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137638. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  137639. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137640. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137641. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  137642. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  137643. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137644. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137645. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  137646. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137647. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  137648. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137649. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137650. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  137651. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  137652. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137653. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137654. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  137655. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137656. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  137657. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137658. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137659. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  137660. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  137661. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137662. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  137663. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  137664. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137665. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  137666. {{ 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},
  137668. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  137669. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137670. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  137671. {{ 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},
  137673. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  137674. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  137675. };
  137676. /* tone master attenuation by base quality mode and bitrate tweak */
  137677. static att3 _psy_tone_masteratt_44[12]={
  137678. {{ 35, 21, 9}, 0, 0}, /* -1 */
  137679. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  137680. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  137681. {{ 25, 12, 2}, 0, 0}, /* 1 */
  137682. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  137683. {{ 20, 9, -3}, 0, 0}, /* 2 */
  137684. {{ 20, 9, -4}, 0, 0}, /* 3 */
  137685. {{ 20, 9, -4}, 0, 0}, /* 4 */
  137686. {{ 20, 6, -6}, 0, 0}, /* 5 */
  137687. {{ 20, 3, -10}, 0, 0}, /* 6 */
  137688. {{ 18, 1, -14}, 0, 0}, /* 7 */
  137689. {{ 18, 0, -16}, 0, 0}, /* 8 */
  137690. {{ 18, -2, -16}, 0, 0}, /* 9 */
  137691. {{ 12, -2, -20}, 0, 0}, /* 10 */
  137692. };
  137693. /* lowpass by mode **************/
  137694. static double _psy_lowpass_44[12]={
  137695. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  137696. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  137697. };
  137698. /* noise normalization **********/
  137699. static int _noise_start_short_44[11]={
  137700. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  137701. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  137702. };
  137703. static int _noise_start_long_44[11]={
  137704. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  137705. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  137706. };
  137707. static int _noise_part_short_44[11]={
  137708. 8,8,8,8,8,8,8,8,8,8,8
  137709. };
  137710. static int _noise_part_long_44[11]={
  137711. 32,32,32,32,32,32,32,32,32,32,32
  137712. };
  137713. static double _noise_thresh_44[11]={
  137714. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  137715. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  137716. };
  137717. static double _noise_thresh_5only[2]={
  137718. .5,.5,
  137719. };
  137720. /********* End of inlined file: psych_44.h *********/
  137721. static double rate_mapping_44_stereo[12]={
  137722. 22500.,32000.,40000.,48000.,56000.,64000.,
  137723. 80000.,96000.,112000.,128000.,160000.,250001.
  137724. };
  137725. static double quality_mapping_44[12]={
  137726. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  137727. };
  137728. static int blocksize_short_44[11]={
  137729. 512,256,256,256,256,256,256,256,256,256,256
  137730. };
  137731. static int blocksize_long_44[11]={
  137732. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  137733. };
  137734. static double _psy_compand_short_mapping[12]={
  137735. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  137736. };
  137737. static double _psy_compand_long_mapping[12]={
  137738. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  137739. };
  137740. static double _global_mapping_44[12]={
  137741. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  137742. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  137743. };
  137744. static int _floor_short_mapping_44[11]={
  137745. 1,0,0,2,2,4,5,5,5,5,5
  137746. };
  137747. static int _floor_long_mapping_44[11]={
  137748. 8,7,7,7,7,7,7,7,7,7,7
  137749. };
  137750. ve_setup_data_template ve_setup_44_stereo={
  137751. 11,
  137752. rate_mapping_44_stereo,
  137753. quality_mapping_44,
  137754. 2,
  137755. 40000,
  137756. 50000,
  137757. blocksize_short_44,
  137758. blocksize_long_44,
  137759. _psy_tone_masteratt_44,
  137760. _psy_tone_0dB,
  137761. _psy_tone_suppress,
  137762. _vp_tonemask_adj_otherblock,
  137763. _vp_tonemask_adj_longblock,
  137764. _vp_tonemask_adj_otherblock,
  137765. _psy_noiseguards_44,
  137766. _psy_noisebias_impulse,
  137767. _psy_noisebias_padding,
  137768. _psy_noisebias_trans,
  137769. _psy_noisebias_long,
  137770. _psy_noise_suppress,
  137771. _psy_compand_44,
  137772. _psy_compand_short_mapping,
  137773. _psy_compand_long_mapping,
  137774. {_noise_start_short_44,_noise_start_long_44},
  137775. {_noise_part_short_44,_noise_part_long_44},
  137776. _noise_thresh_44,
  137777. _psy_ath_floater,
  137778. _psy_ath_abs,
  137779. _psy_lowpass_44,
  137780. _psy_global_44,
  137781. _global_mapping_44,
  137782. _psy_stereo_modes_44,
  137783. _floor_books,
  137784. _floor,
  137785. _floor_short_mapping_44,
  137786. _floor_long_mapping_44,
  137787. _mapres_template_44_stereo
  137788. };
  137789. /********* End of inlined file: setup_44.h *********/
  137790. /********* Start of inlined file: setup_44u.h *********/
  137791. /********* Start of inlined file: residue_44u.h *********/
  137792. /********* Start of inlined file: res_books_uncoupled.h *********/
  137793. static long _vq_quantlist__16u0__p1_0[] = {
  137794. 1,
  137795. 0,
  137796. 2,
  137797. };
  137798. static long _vq_lengthlist__16u0__p1_0[] = {
  137799. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  137800. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  137801. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  137802. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  137803. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  137804. 12,
  137805. };
  137806. static float _vq_quantthresh__16u0__p1_0[] = {
  137807. -0.5, 0.5,
  137808. };
  137809. static long _vq_quantmap__16u0__p1_0[] = {
  137810. 1, 0, 2,
  137811. };
  137812. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  137813. _vq_quantthresh__16u0__p1_0,
  137814. _vq_quantmap__16u0__p1_0,
  137815. 3,
  137816. 3
  137817. };
  137818. static static_codebook _16u0__p1_0 = {
  137819. 4, 81,
  137820. _vq_lengthlist__16u0__p1_0,
  137821. 1, -535822336, 1611661312, 2, 0,
  137822. _vq_quantlist__16u0__p1_0,
  137823. NULL,
  137824. &_vq_auxt__16u0__p1_0,
  137825. NULL,
  137826. 0
  137827. };
  137828. static long _vq_quantlist__16u0__p2_0[] = {
  137829. 1,
  137830. 0,
  137831. 2,
  137832. };
  137833. static long _vq_lengthlist__16u0__p2_0[] = {
  137834. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  137835. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  137836. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  137837. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  137838. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  137839. 8,
  137840. };
  137841. static float _vq_quantthresh__16u0__p2_0[] = {
  137842. -0.5, 0.5,
  137843. };
  137844. static long _vq_quantmap__16u0__p2_0[] = {
  137845. 1, 0, 2,
  137846. };
  137847. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  137848. _vq_quantthresh__16u0__p2_0,
  137849. _vq_quantmap__16u0__p2_0,
  137850. 3,
  137851. 3
  137852. };
  137853. static static_codebook _16u0__p2_0 = {
  137854. 4, 81,
  137855. _vq_lengthlist__16u0__p2_0,
  137856. 1, -535822336, 1611661312, 2, 0,
  137857. _vq_quantlist__16u0__p2_0,
  137858. NULL,
  137859. &_vq_auxt__16u0__p2_0,
  137860. NULL,
  137861. 0
  137862. };
  137863. static long _vq_quantlist__16u0__p3_0[] = {
  137864. 2,
  137865. 1,
  137866. 3,
  137867. 0,
  137868. 4,
  137869. };
  137870. static long _vq_lengthlist__16u0__p3_0[] = {
  137871. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  137872. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  137873. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  137874. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  137875. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  137876. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  137877. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  137878. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  137879. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  137880. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  137881. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  137882. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  137883. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  137884. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  137885. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  137886. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  137887. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  137888. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  137889. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  137890. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  137891. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  137892. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  137893. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  137894. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  137895. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  137896. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  137897. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  137898. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  137899. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  137900. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  137901. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  137902. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  137903. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  137904. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  137905. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  137906. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  137907. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  137908. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  137909. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  137910. 18,
  137911. };
  137912. static float _vq_quantthresh__16u0__p3_0[] = {
  137913. -1.5, -0.5, 0.5, 1.5,
  137914. };
  137915. static long _vq_quantmap__16u0__p3_0[] = {
  137916. 3, 1, 0, 2, 4,
  137917. };
  137918. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  137919. _vq_quantthresh__16u0__p3_0,
  137920. _vq_quantmap__16u0__p3_0,
  137921. 5,
  137922. 5
  137923. };
  137924. static static_codebook _16u0__p3_0 = {
  137925. 4, 625,
  137926. _vq_lengthlist__16u0__p3_0,
  137927. 1, -533725184, 1611661312, 3, 0,
  137928. _vq_quantlist__16u0__p3_0,
  137929. NULL,
  137930. &_vq_auxt__16u0__p3_0,
  137931. NULL,
  137932. 0
  137933. };
  137934. static long _vq_quantlist__16u0__p4_0[] = {
  137935. 2,
  137936. 1,
  137937. 3,
  137938. 0,
  137939. 4,
  137940. };
  137941. static long _vq_lengthlist__16u0__p4_0[] = {
  137942. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  137943. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  137944. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  137945. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  137946. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  137947. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  137948. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  137949. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  137950. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  137951. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  137952. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  137953. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  137954. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  137955. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  137956. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  137957. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  137958. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  137959. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  137960. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  137961. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  137962. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  137963. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  137964. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  137965. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  137966. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  137967. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  137968. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  137969. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  137970. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  137971. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  137972. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  137973. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  137974. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  137975. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  137976. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  137977. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  137978. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  137979. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  137980. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  137981. 11,
  137982. };
  137983. static float _vq_quantthresh__16u0__p4_0[] = {
  137984. -1.5, -0.5, 0.5, 1.5,
  137985. };
  137986. static long _vq_quantmap__16u0__p4_0[] = {
  137987. 3, 1, 0, 2, 4,
  137988. };
  137989. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  137990. _vq_quantthresh__16u0__p4_0,
  137991. _vq_quantmap__16u0__p4_0,
  137992. 5,
  137993. 5
  137994. };
  137995. static static_codebook _16u0__p4_0 = {
  137996. 4, 625,
  137997. _vq_lengthlist__16u0__p4_0,
  137998. 1, -533725184, 1611661312, 3, 0,
  137999. _vq_quantlist__16u0__p4_0,
  138000. NULL,
  138001. &_vq_auxt__16u0__p4_0,
  138002. NULL,
  138003. 0
  138004. };
  138005. static long _vq_quantlist__16u0__p5_0[] = {
  138006. 4,
  138007. 3,
  138008. 5,
  138009. 2,
  138010. 6,
  138011. 1,
  138012. 7,
  138013. 0,
  138014. 8,
  138015. };
  138016. static long _vq_lengthlist__16u0__p5_0[] = {
  138017. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  138018. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  138019. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  138020. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  138021. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  138022. 12,
  138023. };
  138024. static float _vq_quantthresh__16u0__p5_0[] = {
  138025. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138026. };
  138027. static long _vq_quantmap__16u0__p5_0[] = {
  138028. 7, 5, 3, 1, 0, 2, 4, 6,
  138029. 8,
  138030. };
  138031. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  138032. _vq_quantthresh__16u0__p5_0,
  138033. _vq_quantmap__16u0__p5_0,
  138034. 9,
  138035. 9
  138036. };
  138037. static static_codebook _16u0__p5_0 = {
  138038. 2, 81,
  138039. _vq_lengthlist__16u0__p5_0,
  138040. 1, -531628032, 1611661312, 4, 0,
  138041. _vq_quantlist__16u0__p5_0,
  138042. NULL,
  138043. &_vq_auxt__16u0__p5_0,
  138044. NULL,
  138045. 0
  138046. };
  138047. static long _vq_quantlist__16u0__p6_0[] = {
  138048. 6,
  138049. 5,
  138050. 7,
  138051. 4,
  138052. 8,
  138053. 3,
  138054. 9,
  138055. 2,
  138056. 10,
  138057. 1,
  138058. 11,
  138059. 0,
  138060. 12,
  138061. };
  138062. static long _vq_lengthlist__16u0__p6_0[] = {
  138063. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  138064. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  138065. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  138066. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  138067. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  138068. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  138069. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  138070. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  138071. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  138072. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  138073. 18, 0,19, 0, 0, 0, 0, 0, 0,
  138074. };
  138075. static float _vq_quantthresh__16u0__p6_0[] = {
  138076. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138077. 12.5, 17.5, 22.5, 27.5,
  138078. };
  138079. static long _vq_quantmap__16u0__p6_0[] = {
  138080. 11, 9, 7, 5, 3, 1, 0, 2,
  138081. 4, 6, 8, 10, 12,
  138082. };
  138083. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  138084. _vq_quantthresh__16u0__p6_0,
  138085. _vq_quantmap__16u0__p6_0,
  138086. 13,
  138087. 13
  138088. };
  138089. static static_codebook _16u0__p6_0 = {
  138090. 2, 169,
  138091. _vq_lengthlist__16u0__p6_0,
  138092. 1, -526516224, 1616117760, 4, 0,
  138093. _vq_quantlist__16u0__p6_0,
  138094. NULL,
  138095. &_vq_auxt__16u0__p6_0,
  138096. NULL,
  138097. 0
  138098. };
  138099. static long _vq_quantlist__16u0__p6_1[] = {
  138100. 2,
  138101. 1,
  138102. 3,
  138103. 0,
  138104. 4,
  138105. };
  138106. static long _vq_lengthlist__16u0__p6_1[] = {
  138107. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  138108. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  138109. };
  138110. static float _vq_quantthresh__16u0__p6_1[] = {
  138111. -1.5, -0.5, 0.5, 1.5,
  138112. };
  138113. static long _vq_quantmap__16u0__p6_1[] = {
  138114. 3, 1, 0, 2, 4,
  138115. };
  138116. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  138117. _vq_quantthresh__16u0__p6_1,
  138118. _vq_quantmap__16u0__p6_1,
  138119. 5,
  138120. 5
  138121. };
  138122. static static_codebook _16u0__p6_1 = {
  138123. 2, 25,
  138124. _vq_lengthlist__16u0__p6_1,
  138125. 1, -533725184, 1611661312, 3, 0,
  138126. _vq_quantlist__16u0__p6_1,
  138127. NULL,
  138128. &_vq_auxt__16u0__p6_1,
  138129. NULL,
  138130. 0
  138131. };
  138132. static long _vq_quantlist__16u0__p7_0[] = {
  138133. 1,
  138134. 0,
  138135. 2,
  138136. };
  138137. static long _vq_lengthlist__16u0__p7_0[] = {
  138138. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138139. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138140. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138141. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138142. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138143. 7,
  138144. };
  138145. static float _vq_quantthresh__16u0__p7_0[] = {
  138146. -157.5, 157.5,
  138147. };
  138148. static long _vq_quantmap__16u0__p7_0[] = {
  138149. 1, 0, 2,
  138150. };
  138151. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  138152. _vq_quantthresh__16u0__p7_0,
  138153. _vq_quantmap__16u0__p7_0,
  138154. 3,
  138155. 3
  138156. };
  138157. static static_codebook _16u0__p7_0 = {
  138158. 4, 81,
  138159. _vq_lengthlist__16u0__p7_0,
  138160. 1, -518803456, 1628680192, 2, 0,
  138161. _vq_quantlist__16u0__p7_0,
  138162. NULL,
  138163. &_vq_auxt__16u0__p7_0,
  138164. NULL,
  138165. 0
  138166. };
  138167. static long _vq_quantlist__16u0__p7_1[] = {
  138168. 7,
  138169. 6,
  138170. 8,
  138171. 5,
  138172. 9,
  138173. 4,
  138174. 10,
  138175. 3,
  138176. 11,
  138177. 2,
  138178. 12,
  138179. 1,
  138180. 13,
  138181. 0,
  138182. 14,
  138183. };
  138184. static long _vq_lengthlist__16u0__p7_1[] = {
  138185. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  138186. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  138187. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  138188. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  138189. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  138190. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  138191. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138192. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138193. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138194. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138195. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138196. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138197. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138198. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138199. 10,
  138200. };
  138201. static float _vq_quantthresh__16u0__p7_1[] = {
  138202. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  138203. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  138204. };
  138205. static long _vq_quantmap__16u0__p7_1[] = {
  138206. 13, 11, 9, 7, 5, 3, 1, 0,
  138207. 2, 4, 6, 8, 10, 12, 14,
  138208. };
  138209. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  138210. _vq_quantthresh__16u0__p7_1,
  138211. _vq_quantmap__16u0__p7_1,
  138212. 15,
  138213. 15
  138214. };
  138215. static static_codebook _16u0__p7_1 = {
  138216. 2, 225,
  138217. _vq_lengthlist__16u0__p7_1,
  138218. 1, -520986624, 1620377600, 4, 0,
  138219. _vq_quantlist__16u0__p7_1,
  138220. NULL,
  138221. &_vq_auxt__16u0__p7_1,
  138222. NULL,
  138223. 0
  138224. };
  138225. static long _vq_quantlist__16u0__p7_2[] = {
  138226. 10,
  138227. 9,
  138228. 11,
  138229. 8,
  138230. 12,
  138231. 7,
  138232. 13,
  138233. 6,
  138234. 14,
  138235. 5,
  138236. 15,
  138237. 4,
  138238. 16,
  138239. 3,
  138240. 17,
  138241. 2,
  138242. 18,
  138243. 1,
  138244. 19,
  138245. 0,
  138246. 20,
  138247. };
  138248. static long _vq_lengthlist__16u0__p7_2[] = {
  138249. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  138250. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  138251. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  138252. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  138253. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  138254. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  138255. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  138256. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  138257. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  138258. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  138259. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  138260. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  138261. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  138262. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  138263. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  138264. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  138265. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  138266. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  138267. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  138268. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  138269. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  138270. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  138271. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  138272. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  138273. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  138274. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  138275. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  138276. 10,10,12,11,10,11,11,11,10,
  138277. };
  138278. static float _vq_quantthresh__16u0__p7_2[] = {
  138279. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  138280. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  138281. 6.5, 7.5, 8.5, 9.5,
  138282. };
  138283. static long _vq_quantmap__16u0__p7_2[] = {
  138284. 19, 17, 15, 13, 11, 9, 7, 5,
  138285. 3, 1, 0, 2, 4, 6, 8, 10,
  138286. 12, 14, 16, 18, 20,
  138287. };
  138288. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  138289. _vq_quantthresh__16u0__p7_2,
  138290. _vq_quantmap__16u0__p7_2,
  138291. 21,
  138292. 21
  138293. };
  138294. static static_codebook _16u0__p7_2 = {
  138295. 2, 441,
  138296. _vq_lengthlist__16u0__p7_2,
  138297. 1, -529268736, 1611661312, 5, 0,
  138298. _vq_quantlist__16u0__p7_2,
  138299. NULL,
  138300. &_vq_auxt__16u0__p7_2,
  138301. NULL,
  138302. 0
  138303. };
  138304. static long _huff_lengthlist__16u0__single[] = {
  138305. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  138306. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  138307. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  138308. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  138309. };
  138310. static static_codebook _huff_book__16u0__single = {
  138311. 2, 64,
  138312. _huff_lengthlist__16u0__single,
  138313. 0, 0, 0, 0, 0,
  138314. NULL,
  138315. NULL,
  138316. NULL,
  138317. NULL,
  138318. 0
  138319. };
  138320. static long _huff_lengthlist__16u1__long[] = {
  138321. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  138322. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  138323. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  138324. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  138325. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  138326. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  138327. 16,13,16,18,
  138328. };
  138329. static static_codebook _huff_book__16u1__long = {
  138330. 2, 100,
  138331. _huff_lengthlist__16u1__long,
  138332. 0, 0, 0, 0, 0,
  138333. NULL,
  138334. NULL,
  138335. NULL,
  138336. NULL,
  138337. 0
  138338. };
  138339. static long _vq_quantlist__16u1__p1_0[] = {
  138340. 1,
  138341. 0,
  138342. 2,
  138343. };
  138344. static long _vq_lengthlist__16u1__p1_0[] = {
  138345. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  138346. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  138347. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  138348. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  138349. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  138350. 11,
  138351. };
  138352. static float _vq_quantthresh__16u1__p1_0[] = {
  138353. -0.5, 0.5,
  138354. };
  138355. static long _vq_quantmap__16u1__p1_0[] = {
  138356. 1, 0, 2,
  138357. };
  138358. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  138359. _vq_quantthresh__16u1__p1_0,
  138360. _vq_quantmap__16u1__p1_0,
  138361. 3,
  138362. 3
  138363. };
  138364. static static_codebook _16u1__p1_0 = {
  138365. 4, 81,
  138366. _vq_lengthlist__16u1__p1_0,
  138367. 1, -535822336, 1611661312, 2, 0,
  138368. _vq_quantlist__16u1__p1_0,
  138369. NULL,
  138370. &_vq_auxt__16u1__p1_0,
  138371. NULL,
  138372. 0
  138373. };
  138374. static long _vq_quantlist__16u1__p2_0[] = {
  138375. 1,
  138376. 0,
  138377. 2,
  138378. };
  138379. static long _vq_lengthlist__16u1__p2_0[] = {
  138380. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  138381. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  138382. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  138383. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  138384. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  138385. 8,
  138386. };
  138387. static float _vq_quantthresh__16u1__p2_0[] = {
  138388. -0.5, 0.5,
  138389. };
  138390. static long _vq_quantmap__16u1__p2_0[] = {
  138391. 1, 0, 2,
  138392. };
  138393. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  138394. _vq_quantthresh__16u1__p2_0,
  138395. _vq_quantmap__16u1__p2_0,
  138396. 3,
  138397. 3
  138398. };
  138399. static static_codebook _16u1__p2_0 = {
  138400. 4, 81,
  138401. _vq_lengthlist__16u1__p2_0,
  138402. 1, -535822336, 1611661312, 2, 0,
  138403. _vq_quantlist__16u1__p2_0,
  138404. NULL,
  138405. &_vq_auxt__16u1__p2_0,
  138406. NULL,
  138407. 0
  138408. };
  138409. static long _vq_quantlist__16u1__p3_0[] = {
  138410. 2,
  138411. 1,
  138412. 3,
  138413. 0,
  138414. 4,
  138415. };
  138416. static long _vq_lengthlist__16u1__p3_0[] = {
  138417. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  138418. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  138419. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  138420. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  138421. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  138422. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  138423. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  138424. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  138425. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  138426. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  138427. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  138428. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  138429. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  138430. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  138431. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  138432. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  138433. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  138434. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  138435. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  138436. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  138437. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  138438. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  138439. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  138440. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  138441. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  138442. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  138443. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  138444. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  138445. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  138446. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  138447. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  138448. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  138449. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  138450. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  138451. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  138452. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  138453. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  138454. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  138455. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  138456. 16,
  138457. };
  138458. static float _vq_quantthresh__16u1__p3_0[] = {
  138459. -1.5, -0.5, 0.5, 1.5,
  138460. };
  138461. static long _vq_quantmap__16u1__p3_0[] = {
  138462. 3, 1, 0, 2, 4,
  138463. };
  138464. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  138465. _vq_quantthresh__16u1__p3_0,
  138466. _vq_quantmap__16u1__p3_0,
  138467. 5,
  138468. 5
  138469. };
  138470. static static_codebook _16u1__p3_0 = {
  138471. 4, 625,
  138472. _vq_lengthlist__16u1__p3_0,
  138473. 1, -533725184, 1611661312, 3, 0,
  138474. _vq_quantlist__16u1__p3_0,
  138475. NULL,
  138476. &_vq_auxt__16u1__p3_0,
  138477. NULL,
  138478. 0
  138479. };
  138480. static long _vq_quantlist__16u1__p4_0[] = {
  138481. 2,
  138482. 1,
  138483. 3,
  138484. 0,
  138485. 4,
  138486. };
  138487. static long _vq_lengthlist__16u1__p4_0[] = {
  138488. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  138489. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  138490. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  138491. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  138492. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  138493. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  138494. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  138495. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  138496. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  138497. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  138498. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  138499. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  138500. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  138501. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  138502. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  138503. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  138504. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  138505. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  138506. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  138507. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  138508. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  138509. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  138510. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  138511. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  138512. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  138513. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  138514. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  138515. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  138516. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  138517. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  138518. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  138519. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  138520. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  138521. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  138522. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  138523. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  138524. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  138525. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  138526. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  138527. 11,
  138528. };
  138529. static float _vq_quantthresh__16u1__p4_0[] = {
  138530. -1.5, -0.5, 0.5, 1.5,
  138531. };
  138532. static long _vq_quantmap__16u1__p4_0[] = {
  138533. 3, 1, 0, 2, 4,
  138534. };
  138535. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  138536. _vq_quantthresh__16u1__p4_0,
  138537. _vq_quantmap__16u1__p4_0,
  138538. 5,
  138539. 5
  138540. };
  138541. static static_codebook _16u1__p4_0 = {
  138542. 4, 625,
  138543. _vq_lengthlist__16u1__p4_0,
  138544. 1, -533725184, 1611661312, 3, 0,
  138545. _vq_quantlist__16u1__p4_0,
  138546. NULL,
  138547. &_vq_auxt__16u1__p4_0,
  138548. NULL,
  138549. 0
  138550. };
  138551. static long _vq_quantlist__16u1__p5_0[] = {
  138552. 4,
  138553. 3,
  138554. 5,
  138555. 2,
  138556. 6,
  138557. 1,
  138558. 7,
  138559. 0,
  138560. 8,
  138561. };
  138562. static long _vq_lengthlist__16u1__p5_0[] = {
  138563. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  138564. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  138565. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  138566. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  138567. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  138568. 13,
  138569. };
  138570. static float _vq_quantthresh__16u1__p5_0[] = {
  138571. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138572. };
  138573. static long _vq_quantmap__16u1__p5_0[] = {
  138574. 7, 5, 3, 1, 0, 2, 4, 6,
  138575. 8,
  138576. };
  138577. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  138578. _vq_quantthresh__16u1__p5_0,
  138579. _vq_quantmap__16u1__p5_0,
  138580. 9,
  138581. 9
  138582. };
  138583. static static_codebook _16u1__p5_0 = {
  138584. 2, 81,
  138585. _vq_lengthlist__16u1__p5_0,
  138586. 1, -531628032, 1611661312, 4, 0,
  138587. _vq_quantlist__16u1__p5_0,
  138588. NULL,
  138589. &_vq_auxt__16u1__p5_0,
  138590. NULL,
  138591. 0
  138592. };
  138593. static long _vq_quantlist__16u1__p6_0[] = {
  138594. 4,
  138595. 3,
  138596. 5,
  138597. 2,
  138598. 6,
  138599. 1,
  138600. 7,
  138601. 0,
  138602. 8,
  138603. };
  138604. static long _vq_lengthlist__16u1__p6_0[] = {
  138605. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  138606. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  138607. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  138608. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  138609. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  138610. 11,
  138611. };
  138612. static float _vq_quantthresh__16u1__p6_0[] = {
  138613. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138614. };
  138615. static long _vq_quantmap__16u1__p6_0[] = {
  138616. 7, 5, 3, 1, 0, 2, 4, 6,
  138617. 8,
  138618. };
  138619. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  138620. _vq_quantthresh__16u1__p6_0,
  138621. _vq_quantmap__16u1__p6_0,
  138622. 9,
  138623. 9
  138624. };
  138625. static static_codebook _16u1__p6_0 = {
  138626. 2, 81,
  138627. _vq_lengthlist__16u1__p6_0,
  138628. 1, -531628032, 1611661312, 4, 0,
  138629. _vq_quantlist__16u1__p6_0,
  138630. NULL,
  138631. &_vq_auxt__16u1__p6_0,
  138632. NULL,
  138633. 0
  138634. };
  138635. static long _vq_quantlist__16u1__p7_0[] = {
  138636. 1,
  138637. 0,
  138638. 2,
  138639. };
  138640. static long _vq_lengthlist__16u1__p7_0[] = {
  138641. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  138642. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  138643. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  138644. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  138645. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  138646. 13,
  138647. };
  138648. static float _vq_quantthresh__16u1__p7_0[] = {
  138649. -5.5, 5.5,
  138650. };
  138651. static long _vq_quantmap__16u1__p7_0[] = {
  138652. 1, 0, 2,
  138653. };
  138654. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  138655. _vq_quantthresh__16u1__p7_0,
  138656. _vq_quantmap__16u1__p7_0,
  138657. 3,
  138658. 3
  138659. };
  138660. static static_codebook _16u1__p7_0 = {
  138661. 4, 81,
  138662. _vq_lengthlist__16u1__p7_0,
  138663. 1, -529137664, 1618345984, 2, 0,
  138664. _vq_quantlist__16u1__p7_0,
  138665. NULL,
  138666. &_vq_auxt__16u1__p7_0,
  138667. NULL,
  138668. 0
  138669. };
  138670. static long _vq_quantlist__16u1__p7_1[] = {
  138671. 5,
  138672. 4,
  138673. 6,
  138674. 3,
  138675. 7,
  138676. 2,
  138677. 8,
  138678. 1,
  138679. 9,
  138680. 0,
  138681. 10,
  138682. };
  138683. static long _vq_lengthlist__16u1__p7_1[] = {
  138684. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  138685. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  138686. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  138687. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  138688. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  138689. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  138690. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  138691. 8, 9, 9,10,10,10,10,10,10,
  138692. };
  138693. static float _vq_quantthresh__16u1__p7_1[] = {
  138694. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138695. 3.5, 4.5,
  138696. };
  138697. static long _vq_quantmap__16u1__p7_1[] = {
  138698. 9, 7, 5, 3, 1, 0, 2, 4,
  138699. 6, 8, 10,
  138700. };
  138701. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  138702. _vq_quantthresh__16u1__p7_1,
  138703. _vq_quantmap__16u1__p7_1,
  138704. 11,
  138705. 11
  138706. };
  138707. static static_codebook _16u1__p7_1 = {
  138708. 2, 121,
  138709. _vq_lengthlist__16u1__p7_1,
  138710. 1, -531365888, 1611661312, 4, 0,
  138711. _vq_quantlist__16u1__p7_1,
  138712. NULL,
  138713. &_vq_auxt__16u1__p7_1,
  138714. NULL,
  138715. 0
  138716. };
  138717. static long _vq_quantlist__16u1__p8_0[] = {
  138718. 5,
  138719. 4,
  138720. 6,
  138721. 3,
  138722. 7,
  138723. 2,
  138724. 8,
  138725. 1,
  138726. 9,
  138727. 0,
  138728. 10,
  138729. };
  138730. static long _vq_lengthlist__16u1__p8_0[] = {
  138731. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  138732. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  138733. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  138734. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  138735. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  138736. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  138737. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  138738. 13,14,14,15,15,16,16,15,16,
  138739. };
  138740. static float _vq_quantthresh__16u1__p8_0[] = {
  138741. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  138742. 38.5, 49.5,
  138743. };
  138744. static long _vq_quantmap__16u1__p8_0[] = {
  138745. 9, 7, 5, 3, 1, 0, 2, 4,
  138746. 6, 8, 10,
  138747. };
  138748. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  138749. _vq_quantthresh__16u1__p8_0,
  138750. _vq_quantmap__16u1__p8_0,
  138751. 11,
  138752. 11
  138753. };
  138754. static static_codebook _16u1__p8_0 = {
  138755. 2, 121,
  138756. _vq_lengthlist__16u1__p8_0,
  138757. 1, -524582912, 1618345984, 4, 0,
  138758. _vq_quantlist__16u1__p8_0,
  138759. NULL,
  138760. &_vq_auxt__16u1__p8_0,
  138761. NULL,
  138762. 0
  138763. };
  138764. static long _vq_quantlist__16u1__p8_1[] = {
  138765. 5,
  138766. 4,
  138767. 6,
  138768. 3,
  138769. 7,
  138770. 2,
  138771. 8,
  138772. 1,
  138773. 9,
  138774. 0,
  138775. 10,
  138776. };
  138777. static long _vq_lengthlist__16u1__p8_1[] = {
  138778. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  138779. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  138780. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  138781. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  138782. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  138783. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  138784. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  138785. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  138786. };
  138787. static float _vq_quantthresh__16u1__p8_1[] = {
  138788. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138789. 3.5, 4.5,
  138790. };
  138791. static long _vq_quantmap__16u1__p8_1[] = {
  138792. 9, 7, 5, 3, 1, 0, 2, 4,
  138793. 6, 8, 10,
  138794. };
  138795. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  138796. _vq_quantthresh__16u1__p8_1,
  138797. _vq_quantmap__16u1__p8_1,
  138798. 11,
  138799. 11
  138800. };
  138801. static static_codebook _16u1__p8_1 = {
  138802. 2, 121,
  138803. _vq_lengthlist__16u1__p8_1,
  138804. 1, -531365888, 1611661312, 4, 0,
  138805. _vq_quantlist__16u1__p8_1,
  138806. NULL,
  138807. &_vq_auxt__16u1__p8_1,
  138808. NULL,
  138809. 0
  138810. };
  138811. static long _vq_quantlist__16u1__p9_0[] = {
  138812. 7,
  138813. 6,
  138814. 8,
  138815. 5,
  138816. 9,
  138817. 4,
  138818. 10,
  138819. 3,
  138820. 11,
  138821. 2,
  138822. 12,
  138823. 1,
  138824. 13,
  138825. 0,
  138826. 14,
  138827. };
  138828. static long _vq_lengthlist__16u1__p9_0[] = {
  138829. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138830. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138831. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138832. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138833. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138834. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138835. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138836. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138837. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138838. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138839. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138840. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138841. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138842. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138843. 8,
  138844. };
  138845. static float _vq_quantthresh__16u1__p9_0[] = {
  138846. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  138847. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  138848. };
  138849. static long _vq_quantmap__16u1__p9_0[] = {
  138850. 13, 11, 9, 7, 5, 3, 1, 0,
  138851. 2, 4, 6, 8, 10, 12, 14,
  138852. };
  138853. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  138854. _vq_quantthresh__16u1__p9_0,
  138855. _vq_quantmap__16u1__p9_0,
  138856. 15,
  138857. 15
  138858. };
  138859. static static_codebook _16u1__p9_0 = {
  138860. 2, 225,
  138861. _vq_lengthlist__16u1__p9_0,
  138862. 1, -514071552, 1627381760, 4, 0,
  138863. _vq_quantlist__16u1__p9_0,
  138864. NULL,
  138865. &_vq_auxt__16u1__p9_0,
  138866. NULL,
  138867. 0
  138868. };
  138869. static long _vq_quantlist__16u1__p9_1[] = {
  138870. 7,
  138871. 6,
  138872. 8,
  138873. 5,
  138874. 9,
  138875. 4,
  138876. 10,
  138877. 3,
  138878. 11,
  138879. 2,
  138880. 12,
  138881. 1,
  138882. 13,
  138883. 0,
  138884. 14,
  138885. };
  138886. static long _vq_lengthlist__16u1__p9_1[] = {
  138887. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  138888. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  138889. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  138890. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  138891. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  138892. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  138893. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  138894. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  138895. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  138896. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138897. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138898. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138899. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138900. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138901. 9,
  138902. };
  138903. static float _vq_quantthresh__16u1__p9_1[] = {
  138904. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  138905. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  138906. };
  138907. static long _vq_quantmap__16u1__p9_1[] = {
  138908. 13, 11, 9, 7, 5, 3, 1, 0,
  138909. 2, 4, 6, 8, 10, 12, 14,
  138910. };
  138911. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  138912. _vq_quantthresh__16u1__p9_1,
  138913. _vq_quantmap__16u1__p9_1,
  138914. 15,
  138915. 15
  138916. };
  138917. static static_codebook _16u1__p9_1 = {
  138918. 2, 225,
  138919. _vq_lengthlist__16u1__p9_1,
  138920. 1, -522338304, 1620115456, 4, 0,
  138921. _vq_quantlist__16u1__p9_1,
  138922. NULL,
  138923. &_vq_auxt__16u1__p9_1,
  138924. NULL,
  138925. 0
  138926. };
  138927. static long _vq_quantlist__16u1__p9_2[] = {
  138928. 8,
  138929. 7,
  138930. 9,
  138931. 6,
  138932. 10,
  138933. 5,
  138934. 11,
  138935. 4,
  138936. 12,
  138937. 3,
  138938. 13,
  138939. 2,
  138940. 14,
  138941. 1,
  138942. 15,
  138943. 0,
  138944. 16,
  138945. };
  138946. static long _vq_lengthlist__16u1__p9_2[] = {
  138947. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  138948. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  138949. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  138950. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  138951. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  138952. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  138953. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  138954. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  138955. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  138956. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  138957. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  138958. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  138959. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  138960. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  138961. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  138962. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  138963. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  138964. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  138965. 10,
  138966. };
  138967. static float _vq_quantthresh__16u1__p9_2[] = {
  138968. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138969. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138970. };
  138971. static long _vq_quantmap__16u1__p9_2[] = {
  138972. 15, 13, 11, 9, 7, 5, 3, 1,
  138973. 0, 2, 4, 6, 8, 10, 12, 14,
  138974. 16,
  138975. };
  138976. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  138977. _vq_quantthresh__16u1__p9_2,
  138978. _vq_quantmap__16u1__p9_2,
  138979. 17,
  138980. 17
  138981. };
  138982. static static_codebook _16u1__p9_2 = {
  138983. 2, 289,
  138984. _vq_lengthlist__16u1__p9_2,
  138985. 1, -529530880, 1611661312, 5, 0,
  138986. _vq_quantlist__16u1__p9_2,
  138987. NULL,
  138988. &_vq_auxt__16u1__p9_2,
  138989. NULL,
  138990. 0
  138991. };
  138992. static long _huff_lengthlist__16u1__short[] = {
  138993. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  138994. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  138995. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  138996. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  138997. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  138998. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  138999. 16,16,16,16,
  139000. };
  139001. static static_codebook _huff_book__16u1__short = {
  139002. 2, 100,
  139003. _huff_lengthlist__16u1__short,
  139004. 0, 0, 0, 0, 0,
  139005. NULL,
  139006. NULL,
  139007. NULL,
  139008. NULL,
  139009. 0
  139010. };
  139011. static long _huff_lengthlist__16u2__long[] = {
  139012. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  139013. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  139014. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  139015. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  139016. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  139017. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  139018. 13,14,18,18,
  139019. };
  139020. static static_codebook _huff_book__16u2__long = {
  139021. 2, 100,
  139022. _huff_lengthlist__16u2__long,
  139023. 0, 0, 0, 0, 0,
  139024. NULL,
  139025. NULL,
  139026. NULL,
  139027. NULL,
  139028. 0
  139029. };
  139030. static long _huff_lengthlist__16u2__short[] = {
  139031. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  139032. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  139033. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  139034. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  139035. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  139036. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  139037. 16,16,16,16,
  139038. };
  139039. static static_codebook _huff_book__16u2__short = {
  139040. 2, 100,
  139041. _huff_lengthlist__16u2__short,
  139042. 0, 0, 0, 0, 0,
  139043. NULL,
  139044. NULL,
  139045. NULL,
  139046. NULL,
  139047. 0
  139048. };
  139049. static long _vq_quantlist__16u2_p1_0[] = {
  139050. 1,
  139051. 0,
  139052. 2,
  139053. };
  139054. static long _vq_lengthlist__16u2_p1_0[] = {
  139055. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  139056. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  139057. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  139058. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  139059. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  139060. 10,
  139061. };
  139062. static float _vq_quantthresh__16u2_p1_0[] = {
  139063. -0.5, 0.5,
  139064. };
  139065. static long _vq_quantmap__16u2_p1_0[] = {
  139066. 1, 0, 2,
  139067. };
  139068. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  139069. _vq_quantthresh__16u2_p1_0,
  139070. _vq_quantmap__16u2_p1_0,
  139071. 3,
  139072. 3
  139073. };
  139074. static static_codebook _16u2_p1_0 = {
  139075. 4, 81,
  139076. _vq_lengthlist__16u2_p1_0,
  139077. 1, -535822336, 1611661312, 2, 0,
  139078. _vq_quantlist__16u2_p1_0,
  139079. NULL,
  139080. &_vq_auxt__16u2_p1_0,
  139081. NULL,
  139082. 0
  139083. };
  139084. static long _vq_quantlist__16u2_p2_0[] = {
  139085. 2,
  139086. 1,
  139087. 3,
  139088. 0,
  139089. 4,
  139090. };
  139091. static long _vq_lengthlist__16u2_p2_0[] = {
  139092. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  139093. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  139094. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  139095. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  139096. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  139097. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  139098. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  139099. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  139100. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  139101. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  139102. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  139103. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  139104. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  139105. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  139106. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  139107. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  139108. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  139109. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  139110. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  139111. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  139112. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  139113. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  139114. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  139115. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  139116. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  139117. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  139118. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  139119. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  139120. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  139121. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  139122. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  139123. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  139124. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  139125. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  139126. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  139127. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  139128. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  139129. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  139130. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  139131. 13,
  139132. };
  139133. static float _vq_quantthresh__16u2_p2_0[] = {
  139134. -1.5, -0.5, 0.5, 1.5,
  139135. };
  139136. static long _vq_quantmap__16u2_p2_0[] = {
  139137. 3, 1, 0, 2, 4,
  139138. };
  139139. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  139140. _vq_quantthresh__16u2_p2_0,
  139141. _vq_quantmap__16u2_p2_0,
  139142. 5,
  139143. 5
  139144. };
  139145. static static_codebook _16u2_p2_0 = {
  139146. 4, 625,
  139147. _vq_lengthlist__16u2_p2_0,
  139148. 1, -533725184, 1611661312, 3, 0,
  139149. _vq_quantlist__16u2_p2_0,
  139150. NULL,
  139151. &_vq_auxt__16u2_p2_0,
  139152. NULL,
  139153. 0
  139154. };
  139155. static long _vq_quantlist__16u2_p3_0[] = {
  139156. 4,
  139157. 3,
  139158. 5,
  139159. 2,
  139160. 6,
  139161. 1,
  139162. 7,
  139163. 0,
  139164. 8,
  139165. };
  139166. static long _vq_lengthlist__16u2_p3_0[] = {
  139167. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  139168. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  139169. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  139170. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  139171. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  139172. 11,
  139173. };
  139174. static float _vq_quantthresh__16u2_p3_0[] = {
  139175. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139176. };
  139177. static long _vq_quantmap__16u2_p3_0[] = {
  139178. 7, 5, 3, 1, 0, 2, 4, 6,
  139179. 8,
  139180. };
  139181. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  139182. _vq_quantthresh__16u2_p3_0,
  139183. _vq_quantmap__16u2_p3_0,
  139184. 9,
  139185. 9
  139186. };
  139187. static static_codebook _16u2_p3_0 = {
  139188. 2, 81,
  139189. _vq_lengthlist__16u2_p3_0,
  139190. 1, -531628032, 1611661312, 4, 0,
  139191. _vq_quantlist__16u2_p3_0,
  139192. NULL,
  139193. &_vq_auxt__16u2_p3_0,
  139194. NULL,
  139195. 0
  139196. };
  139197. static long _vq_quantlist__16u2_p4_0[] = {
  139198. 8,
  139199. 7,
  139200. 9,
  139201. 6,
  139202. 10,
  139203. 5,
  139204. 11,
  139205. 4,
  139206. 12,
  139207. 3,
  139208. 13,
  139209. 2,
  139210. 14,
  139211. 1,
  139212. 15,
  139213. 0,
  139214. 16,
  139215. };
  139216. static long _vq_lengthlist__16u2_p4_0[] = {
  139217. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  139218. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  139219. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  139220. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139221. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139222. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  139223. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  139224. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  139225. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  139226. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  139227. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  139228. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  139229. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  139230. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  139231. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  139232. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  139233. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  139234. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  139235. 14,
  139236. };
  139237. static float _vq_quantthresh__16u2_p4_0[] = {
  139238. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139239. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139240. };
  139241. static long _vq_quantmap__16u2_p4_0[] = {
  139242. 15, 13, 11, 9, 7, 5, 3, 1,
  139243. 0, 2, 4, 6, 8, 10, 12, 14,
  139244. 16,
  139245. };
  139246. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  139247. _vq_quantthresh__16u2_p4_0,
  139248. _vq_quantmap__16u2_p4_0,
  139249. 17,
  139250. 17
  139251. };
  139252. static static_codebook _16u2_p4_0 = {
  139253. 2, 289,
  139254. _vq_lengthlist__16u2_p4_0,
  139255. 1, -529530880, 1611661312, 5, 0,
  139256. _vq_quantlist__16u2_p4_0,
  139257. NULL,
  139258. &_vq_auxt__16u2_p4_0,
  139259. NULL,
  139260. 0
  139261. };
  139262. static long _vq_quantlist__16u2_p5_0[] = {
  139263. 1,
  139264. 0,
  139265. 2,
  139266. };
  139267. static long _vq_lengthlist__16u2_p5_0[] = {
  139268. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  139269. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  139270. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  139271. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  139272. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  139273. 10,
  139274. };
  139275. static float _vq_quantthresh__16u2_p5_0[] = {
  139276. -5.5, 5.5,
  139277. };
  139278. static long _vq_quantmap__16u2_p5_0[] = {
  139279. 1, 0, 2,
  139280. };
  139281. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  139282. _vq_quantthresh__16u2_p5_0,
  139283. _vq_quantmap__16u2_p5_0,
  139284. 3,
  139285. 3
  139286. };
  139287. static static_codebook _16u2_p5_0 = {
  139288. 4, 81,
  139289. _vq_lengthlist__16u2_p5_0,
  139290. 1, -529137664, 1618345984, 2, 0,
  139291. _vq_quantlist__16u2_p5_0,
  139292. NULL,
  139293. &_vq_auxt__16u2_p5_0,
  139294. NULL,
  139295. 0
  139296. };
  139297. static long _vq_quantlist__16u2_p5_1[] = {
  139298. 5,
  139299. 4,
  139300. 6,
  139301. 3,
  139302. 7,
  139303. 2,
  139304. 8,
  139305. 1,
  139306. 9,
  139307. 0,
  139308. 10,
  139309. };
  139310. static long _vq_lengthlist__16u2_p5_1[] = {
  139311. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  139312. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  139313. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  139314. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  139315. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  139316. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  139317. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  139318. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  139319. };
  139320. static float _vq_quantthresh__16u2_p5_1[] = {
  139321. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139322. 3.5, 4.5,
  139323. };
  139324. static long _vq_quantmap__16u2_p5_1[] = {
  139325. 9, 7, 5, 3, 1, 0, 2, 4,
  139326. 6, 8, 10,
  139327. };
  139328. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  139329. _vq_quantthresh__16u2_p5_1,
  139330. _vq_quantmap__16u2_p5_1,
  139331. 11,
  139332. 11
  139333. };
  139334. static static_codebook _16u2_p5_1 = {
  139335. 2, 121,
  139336. _vq_lengthlist__16u2_p5_1,
  139337. 1, -531365888, 1611661312, 4, 0,
  139338. _vq_quantlist__16u2_p5_1,
  139339. NULL,
  139340. &_vq_auxt__16u2_p5_1,
  139341. NULL,
  139342. 0
  139343. };
  139344. static long _vq_quantlist__16u2_p6_0[] = {
  139345. 6,
  139346. 5,
  139347. 7,
  139348. 4,
  139349. 8,
  139350. 3,
  139351. 9,
  139352. 2,
  139353. 10,
  139354. 1,
  139355. 11,
  139356. 0,
  139357. 12,
  139358. };
  139359. static long _vq_lengthlist__16u2_p6_0[] = {
  139360. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  139361. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  139362. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  139363. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  139364. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  139365. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  139366. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  139367. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  139368. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  139369. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  139370. 12,13,13,14,14,14,14,15,15,
  139371. };
  139372. static float _vq_quantthresh__16u2_p6_0[] = {
  139373. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139374. 12.5, 17.5, 22.5, 27.5,
  139375. };
  139376. static long _vq_quantmap__16u2_p6_0[] = {
  139377. 11, 9, 7, 5, 3, 1, 0, 2,
  139378. 4, 6, 8, 10, 12,
  139379. };
  139380. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  139381. _vq_quantthresh__16u2_p6_0,
  139382. _vq_quantmap__16u2_p6_0,
  139383. 13,
  139384. 13
  139385. };
  139386. static static_codebook _16u2_p6_0 = {
  139387. 2, 169,
  139388. _vq_lengthlist__16u2_p6_0,
  139389. 1, -526516224, 1616117760, 4, 0,
  139390. _vq_quantlist__16u2_p6_0,
  139391. NULL,
  139392. &_vq_auxt__16u2_p6_0,
  139393. NULL,
  139394. 0
  139395. };
  139396. static long _vq_quantlist__16u2_p6_1[] = {
  139397. 2,
  139398. 1,
  139399. 3,
  139400. 0,
  139401. 4,
  139402. };
  139403. static long _vq_lengthlist__16u2_p6_1[] = {
  139404. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  139405. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  139406. };
  139407. static float _vq_quantthresh__16u2_p6_1[] = {
  139408. -1.5, -0.5, 0.5, 1.5,
  139409. };
  139410. static long _vq_quantmap__16u2_p6_1[] = {
  139411. 3, 1, 0, 2, 4,
  139412. };
  139413. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  139414. _vq_quantthresh__16u2_p6_1,
  139415. _vq_quantmap__16u2_p6_1,
  139416. 5,
  139417. 5
  139418. };
  139419. static static_codebook _16u2_p6_1 = {
  139420. 2, 25,
  139421. _vq_lengthlist__16u2_p6_1,
  139422. 1, -533725184, 1611661312, 3, 0,
  139423. _vq_quantlist__16u2_p6_1,
  139424. NULL,
  139425. &_vq_auxt__16u2_p6_1,
  139426. NULL,
  139427. 0
  139428. };
  139429. static long _vq_quantlist__16u2_p7_0[] = {
  139430. 6,
  139431. 5,
  139432. 7,
  139433. 4,
  139434. 8,
  139435. 3,
  139436. 9,
  139437. 2,
  139438. 10,
  139439. 1,
  139440. 11,
  139441. 0,
  139442. 12,
  139443. };
  139444. static long _vq_lengthlist__16u2_p7_0[] = {
  139445. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  139446. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  139447. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  139448. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  139449. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  139450. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  139451. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  139452. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  139453. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  139454. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  139455. 12,13,13,13,14,14,14,15,14,
  139456. };
  139457. static float _vq_quantthresh__16u2_p7_0[] = {
  139458. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  139459. 27.5, 38.5, 49.5, 60.5,
  139460. };
  139461. static long _vq_quantmap__16u2_p7_0[] = {
  139462. 11, 9, 7, 5, 3, 1, 0, 2,
  139463. 4, 6, 8, 10, 12,
  139464. };
  139465. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  139466. _vq_quantthresh__16u2_p7_0,
  139467. _vq_quantmap__16u2_p7_0,
  139468. 13,
  139469. 13
  139470. };
  139471. static static_codebook _16u2_p7_0 = {
  139472. 2, 169,
  139473. _vq_lengthlist__16u2_p7_0,
  139474. 1, -523206656, 1618345984, 4, 0,
  139475. _vq_quantlist__16u2_p7_0,
  139476. NULL,
  139477. &_vq_auxt__16u2_p7_0,
  139478. NULL,
  139479. 0
  139480. };
  139481. static long _vq_quantlist__16u2_p7_1[] = {
  139482. 5,
  139483. 4,
  139484. 6,
  139485. 3,
  139486. 7,
  139487. 2,
  139488. 8,
  139489. 1,
  139490. 9,
  139491. 0,
  139492. 10,
  139493. };
  139494. static long _vq_lengthlist__16u2_p7_1[] = {
  139495. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  139496. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  139497. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  139498. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  139499. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  139500. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  139501. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  139502. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139503. };
  139504. static float _vq_quantthresh__16u2_p7_1[] = {
  139505. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139506. 3.5, 4.5,
  139507. };
  139508. static long _vq_quantmap__16u2_p7_1[] = {
  139509. 9, 7, 5, 3, 1, 0, 2, 4,
  139510. 6, 8, 10,
  139511. };
  139512. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  139513. _vq_quantthresh__16u2_p7_1,
  139514. _vq_quantmap__16u2_p7_1,
  139515. 11,
  139516. 11
  139517. };
  139518. static static_codebook _16u2_p7_1 = {
  139519. 2, 121,
  139520. _vq_lengthlist__16u2_p7_1,
  139521. 1, -531365888, 1611661312, 4, 0,
  139522. _vq_quantlist__16u2_p7_1,
  139523. NULL,
  139524. &_vq_auxt__16u2_p7_1,
  139525. NULL,
  139526. 0
  139527. };
  139528. static long _vq_quantlist__16u2_p8_0[] = {
  139529. 7,
  139530. 6,
  139531. 8,
  139532. 5,
  139533. 9,
  139534. 4,
  139535. 10,
  139536. 3,
  139537. 11,
  139538. 2,
  139539. 12,
  139540. 1,
  139541. 13,
  139542. 0,
  139543. 14,
  139544. };
  139545. static long _vq_lengthlist__16u2_p8_0[] = {
  139546. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  139547. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  139548. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  139549. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  139550. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  139551. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  139552. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  139553. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  139554. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  139555. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  139556. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  139557. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  139558. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  139559. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  139560. 14,
  139561. };
  139562. static float _vq_quantthresh__16u2_p8_0[] = {
  139563. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  139564. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  139565. };
  139566. static long _vq_quantmap__16u2_p8_0[] = {
  139567. 13, 11, 9, 7, 5, 3, 1, 0,
  139568. 2, 4, 6, 8, 10, 12, 14,
  139569. };
  139570. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  139571. _vq_quantthresh__16u2_p8_0,
  139572. _vq_quantmap__16u2_p8_0,
  139573. 15,
  139574. 15
  139575. };
  139576. static static_codebook _16u2_p8_0 = {
  139577. 2, 225,
  139578. _vq_lengthlist__16u2_p8_0,
  139579. 1, -520986624, 1620377600, 4, 0,
  139580. _vq_quantlist__16u2_p8_0,
  139581. NULL,
  139582. &_vq_auxt__16u2_p8_0,
  139583. NULL,
  139584. 0
  139585. };
  139586. static long _vq_quantlist__16u2_p8_1[] = {
  139587. 10,
  139588. 9,
  139589. 11,
  139590. 8,
  139591. 12,
  139592. 7,
  139593. 13,
  139594. 6,
  139595. 14,
  139596. 5,
  139597. 15,
  139598. 4,
  139599. 16,
  139600. 3,
  139601. 17,
  139602. 2,
  139603. 18,
  139604. 1,
  139605. 19,
  139606. 0,
  139607. 20,
  139608. };
  139609. static long _vq_lengthlist__16u2_p8_1[] = {
  139610. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  139611. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  139612. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  139613. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  139614. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  139615. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  139616. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  139617. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  139618. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  139619. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  139620. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  139621. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  139622. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  139623. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  139624. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  139625. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  139626. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  139627. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  139628. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  139629. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  139630. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  139631. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  139632. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  139633. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  139634. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  139635. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  139636. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  139637. 11,11,10,11,11,11,10,11,11,
  139638. };
  139639. static float _vq_quantthresh__16u2_p8_1[] = {
  139640. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  139641. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  139642. 6.5, 7.5, 8.5, 9.5,
  139643. };
  139644. static long _vq_quantmap__16u2_p8_1[] = {
  139645. 19, 17, 15, 13, 11, 9, 7, 5,
  139646. 3, 1, 0, 2, 4, 6, 8, 10,
  139647. 12, 14, 16, 18, 20,
  139648. };
  139649. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  139650. _vq_quantthresh__16u2_p8_1,
  139651. _vq_quantmap__16u2_p8_1,
  139652. 21,
  139653. 21
  139654. };
  139655. static static_codebook _16u2_p8_1 = {
  139656. 2, 441,
  139657. _vq_lengthlist__16u2_p8_1,
  139658. 1, -529268736, 1611661312, 5, 0,
  139659. _vq_quantlist__16u2_p8_1,
  139660. NULL,
  139661. &_vq_auxt__16u2_p8_1,
  139662. NULL,
  139663. 0
  139664. };
  139665. static long _vq_quantlist__16u2_p9_0[] = {
  139666. 5586,
  139667. 4655,
  139668. 6517,
  139669. 3724,
  139670. 7448,
  139671. 2793,
  139672. 8379,
  139673. 1862,
  139674. 9310,
  139675. 931,
  139676. 10241,
  139677. 0,
  139678. 11172,
  139679. 5521,
  139680. 5651,
  139681. };
  139682. static long _vq_lengthlist__16u2_p9_0[] = {
  139683. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  139684. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139685. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139686. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139687. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139688. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139689. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139690. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139691. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139692. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139693. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139694. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139695. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  139696. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  139697. 5,
  139698. };
  139699. static float _vq_quantthresh__16u2_p9_0[] = {
  139700. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  139701. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  139702. };
  139703. static long _vq_quantmap__16u2_p9_0[] = {
  139704. 11, 9, 7, 5, 3, 1, 13, 0,
  139705. 14, 2, 4, 6, 8, 10, 12,
  139706. };
  139707. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  139708. _vq_quantthresh__16u2_p9_0,
  139709. _vq_quantmap__16u2_p9_0,
  139710. 15,
  139711. 15
  139712. };
  139713. static static_codebook _16u2_p9_0 = {
  139714. 2, 225,
  139715. _vq_lengthlist__16u2_p9_0,
  139716. 1, -510275072, 1611661312, 14, 0,
  139717. _vq_quantlist__16u2_p9_0,
  139718. NULL,
  139719. &_vq_auxt__16u2_p9_0,
  139720. NULL,
  139721. 0
  139722. };
  139723. static long _vq_quantlist__16u2_p9_1[] = {
  139724. 392,
  139725. 343,
  139726. 441,
  139727. 294,
  139728. 490,
  139729. 245,
  139730. 539,
  139731. 196,
  139732. 588,
  139733. 147,
  139734. 637,
  139735. 98,
  139736. 686,
  139737. 49,
  139738. 735,
  139739. 0,
  139740. 784,
  139741. 388,
  139742. 396,
  139743. };
  139744. static long _vq_lengthlist__16u2_p9_1[] = {
  139745. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  139746. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  139747. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  139748. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  139749. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  139750. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  139751. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139752. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  139753. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  139754. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139755. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139756. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139757. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139758. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139759. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  139760. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139761. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139762. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139763. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139764. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139765. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  139766. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  139767. 11,11,11,11,11,11,11, 5, 4,
  139768. };
  139769. static float _vq_quantthresh__16u2_p9_1[] = {
  139770. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  139771. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  139772. 318.5, 367.5,
  139773. };
  139774. static long _vq_quantmap__16u2_p9_1[] = {
  139775. 15, 13, 11, 9, 7, 5, 3, 1,
  139776. 17, 0, 18, 2, 4, 6, 8, 10,
  139777. 12, 14, 16,
  139778. };
  139779. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  139780. _vq_quantthresh__16u2_p9_1,
  139781. _vq_quantmap__16u2_p9_1,
  139782. 19,
  139783. 19
  139784. };
  139785. static static_codebook _16u2_p9_1 = {
  139786. 2, 361,
  139787. _vq_lengthlist__16u2_p9_1,
  139788. 1, -518488064, 1611661312, 10, 0,
  139789. _vq_quantlist__16u2_p9_1,
  139790. NULL,
  139791. &_vq_auxt__16u2_p9_1,
  139792. NULL,
  139793. 0
  139794. };
  139795. static long _vq_quantlist__16u2_p9_2[] = {
  139796. 24,
  139797. 23,
  139798. 25,
  139799. 22,
  139800. 26,
  139801. 21,
  139802. 27,
  139803. 20,
  139804. 28,
  139805. 19,
  139806. 29,
  139807. 18,
  139808. 30,
  139809. 17,
  139810. 31,
  139811. 16,
  139812. 32,
  139813. 15,
  139814. 33,
  139815. 14,
  139816. 34,
  139817. 13,
  139818. 35,
  139819. 12,
  139820. 36,
  139821. 11,
  139822. 37,
  139823. 10,
  139824. 38,
  139825. 9,
  139826. 39,
  139827. 8,
  139828. 40,
  139829. 7,
  139830. 41,
  139831. 6,
  139832. 42,
  139833. 5,
  139834. 43,
  139835. 4,
  139836. 44,
  139837. 3,
  139838. 45,
  139839. 2,
  139840. 46,
  139841. 1,
  139842. 47,
  139843. 0,
  139844. 48,
  139845. };
  139846. static long _vq_lengthlist__16u2_p9_2[] = {
  139847. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  139848. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  139849. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  139850. 11,
  139851. };
  139852. static float _vq_quantthresh__16u2_p9_2[] = {
  139853. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  139854. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  139855. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139856. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139857. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  139858. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  139859. };
  139860. static long _vq_quantmap__16u2_p9_2[] = {
  139861. 47, 45, 43, 41, 39, 37, 35, 33,
  139862. 31, 29, 27, 25, 23, 21, 19, 17,
  139863. 15, 13, 11, 9, 7, 5, 3, 1,
  139864. 0, 2, 4, 6, 8, 10, 12, 14,
  139865. 16, 18, 20, 22, 24, 26, 28, 30,
  139866. 32, 34, 36, 38, 40, 42, 44, 46,
  139867. 48,
  139868. };
  139869. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  139870. _vq_quantthresh__16u2_p9_2,
  139871. _vq_quantmap__16u2_p9_2,
  139872. 49,
  139873. 49
  139874. };
  139875. static static_codebook _16u2_p9_2 = {
  139876. 1, 49,
  139877. _vq_lengthlist__16u2_p9_2,
  139878. 1, -526909440, 1611661312, 6, 0,
  139879. _vq_quantlist__16u2_p9_2,
  139880. NULL,
  139881. &_vq_auxt__16u2_p9_2,
  139882. NULL,
  139883. 0
  139884. };
  139885. static long _vq_quantlist__8u0__p1_0[] = {
  139886. 1,
  139887. 0,
  139888. 2,
  139889. };
  139890. static long _vq_lengthlist__8u0__p1_0[] = {
  139891. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  139892. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  139893. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  139894. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  139895. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  139896. 11,
  139897. };
  139898. static float _vq_quantthresh__8u0__p1_0[] = {
  139899. -0.5, 0.5,
  139900. };
  139901. static long _vq_quantmap__8u0__p1_0[] = {
  139902. 1, 0, 2,
  139903. };
  139904. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  139905. _vq_quantthresh__8u0__p1_0,
  139906. _vq_quantmap__8u0__p1_0,
  139907. 3,
  139908. 3
  139909. };
  139910. static static_codebook _8u0__p1_0 = {
  139911. 4, 81,
  139912. _vq_lengthlist__8u0__p1_0,
  139913. 1, -535822336, 1611661312, 2, 0,
  139914. _vq_quantlist__8u0__p1_0,
  139915. NULL,
  139916. &_vq_auxt__8u0__p1_0,
  139917. NULL,
  139918. 0
  139919. };
  139920. static long _vq_quantlist__8u0__p2_0[] = {
  139921. 1,
  139922. 0,
  139923. 2,
  139924. };
  139925. static long _vq_lengthlist__8u0__p2_0[] = {
  139926. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  139927. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  139928. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  139929. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  139930. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  139931. 8,
  139932. };
  139933. static float _vq_quantthresh__8u0__p2_0[] = {
  139934. -0.5, 0.5,
  139935. };
  139936. static long _vq_quantmap__8u0__p2_0[] = {
  139937. 1, 0, 2,
  139938. };
  139939. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  139940. _vq_quantthresh__8u0__p2_0,
  139941. _vq_quantmap__8u0__p2_0,
  139942. 3,
  139943. 3
  139944. };
  139945. static static_codebook _8u0__p2_0 = {
  139946. 4, 81,
  139947. _vq_lengthlist__8u0__p2_0,
  139948. 1, -535822336, 1611661312, 2, 0,
  139949. _vq_quantlist__8u0__p2_0,
  139950. NULL,
  139951. &_vq_auxt__8u0__p2_0,
  139952. NULL,
  139953. 0
  139954. };
  139955. static long _vq_quantlist__8u0__p3_0[] = {
  139956. 2,
  139957. 1,
  139958. 3,
  139959. 0,
  139960. 4,
  139961. };
  139962. static long _vq_lengthlist__8u0__p3_0[] = {
  139963. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  139964. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  139965. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  139966. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  139967. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  139968. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  139969. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  139970. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  139971. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  139972. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  139973. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  139974. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  139975. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  139976. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  139977. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  139978. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  139979. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  139980. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  139981. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  139982. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  139983. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  139984. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  139985. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  139986. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  139987. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  139988. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  139989. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  139990. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  139991. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  139992. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  139993. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  139994. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  139995. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  139996. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  139997. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  139998. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  139999. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  140000. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  140001. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  140002. 16,
  140003. };
  140004. static float _vq_quantthresh__8u0__p3_0[] = {
  140005. -1.5, -0.5, 0.5, 1.5,
  140006. };
  140007. static long _vq_quantmap__8u0__p3_0[] = {
  140008. 3, 1, 0, 2, 4,
  140009. };
  140010. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  140011. _vq_quantthresh__8u0__p3_0,
  140012. _vq_quantmap__8u0__p3_0,
  140013. 5,
  140014. 5
  140015. };
  140016. static static_codebook _8u0__p3_0 = {
  140017. 4, 625,
  140018. _vq_lengthlist__8u0__p3_0,
  140019. 1, -533725184, 1611661312, 3, 0,
  140020. _vq_quantlist__8u0__p3_0,
  140021. NULL,
  140022. &_vq_auxt__8u0__p3_0,
  140023. NULL,
  140024. 0
  140025. };
  140026. static long _vq_quantlist__8u0__p4_0[] = {
  140027. 2,
  140028. 1,
  140029. 3,
  140030. 0,
  140031. 4,
  140032. };
  140033. static long _vq_lengthlist__8u0__p4_0[] = {
  140034. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  140035. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  140036. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  140037. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  140038. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  140039. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  140040. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  140041. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  140042. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  140043. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  140044. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  140045. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  140046. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  140047. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  140048. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  140049. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  140050. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  140051. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  140052. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  140053. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  140054. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  140055. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  140056. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  140057. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  140058. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  140059. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  140060. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  140061. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  140062. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  140063. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  140064. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  140065. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  140066. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  140067. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  140068. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  140069. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  140070. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  140071. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  140072. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  140073. 12,
  140074. };
  140075. static float _vq_quantthresh__8u0__p4_0[] = {
  140076. -1.5, -0.5, 0.5, 1.5,
  140077. };
  140078. static long _vq_quantmap__8u0__p4_0[] = {
  140079. 3, 1, 0, 2, 4,
  140080. };
  140081. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  140082. _vq_quantthresh__8u0__p4_0,
  140083. _vq_quantmap__8u0__p4_0,
  140084. 5,
  140085. 5
  140086. };
  140087. static static_codebook _8u0__p4_0 = {
  140088. 4, 625,
  140089. _vq_lengthlist__8u0__p4_0,
  140090. 1, -533725184, 1611661312, 3, 0,
  140091. _vq_quantlist__8u0__p4_0,
  140092. NULL,
  140093. &_vq_auxt__8u0__p4_0,
  140094. NULL,
  140095. 0
  140096. };
  140097. static long _vq_quantlist__8u0__p5_0[] = {
  140098. 4,
  140099. 3,
  140100. 5,
  140101. 2,
  140102. 6,
  140103. 1,
  140104. 7,
  140105. 0,
  140106. 8,
  140107. };
  140108. static long _vq_lengthlist__8u0__p5_0[] = {
  140109. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  140110. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  140111. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  140112. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  140113. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  140114. 12,
  140115. };
  140116. static float _vq_quantthresh__8u0__p5_0[] = {
  140117. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140118. };
  140119. static long _vq_quantmap__8u0__p5_0[] = {
  140120. 7, 5, 3, 1, 0, 2, 4, 6,
  140121. 8,
  140122. };
  140123. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  140124. _vq_quantthresh__8u0__p5_0,
  140125. _vq_quantmap__8u0__p5_0,
  140126. 9,
  140127. 9
  140128. };
  140129. static static_codebook _8u0__p5_0 = {
  140130. 2, 81,
  140131. _vq_lengthlist__8u0__p5_0,
  140132. 1, -531628032, 1611661312, 4, 0,
  140133. _vq_quantlist__8u0__p5_0,
  140134. NULL,
  140135. &_vq_auxt__8u0__p5_0,
  140136. NULL,
  140137. 0
  140138. };
  140139. static long _vq_quantlist__8u0__p6_0[] = {
  140140. 6,
  140141. 5,
  140142. 7,
  140143. 4,
  140144. 8,
  140145. 3,
  140146. 9,
  140147. 2,
  140148. 10,
  140149. 1,
  140150. 11,
  140151. 0,
  140152. 12,
  140153. };
  140154. static long _vq_lengthlist__8u0__p6_0[] = {
  140155. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  140156. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  140157. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  140158. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  140159. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  140160. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  140161. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  140162. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  140163. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  140164. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  140165. 16, 0,15, 0,17, 0, 0, 0, 0,
  140166. };
  140167. static float _vq_quantthresh__8u0__p6_0[] = {
  140168. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140169. 12.5, 17.5, 22.5, 27.5,
  140170. };
  140171. static long _vq_quantmap__8u0__p6_0[] = {
  140172. 11, 9, 7, 5, 3, 1, 0, 2,
  140173. 4, 6, 8, 10, 12,
  140174. };
  140175. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  140176. _vq_quantthresh__8u0__p6_0,
  140177. _vq_quantmap__8u0__p6_0,
  140178. 13,
  140179. 13
  140180. };
  140181. static static_codebook _8u0__p6_0 = {
  140182. 2, 169,
  140183. _vq_lengthlist__8u0__p6_0,
  140184. 1, -526516224, 1616117760, 4, 0,
  140185. _vq_quantlist__8u0__p6_0,
  140186. NULL,
  140187. &_vq_auxt__8u0__p6_0,
  140188. NULL,
  140189. 0
  140190. };
  140191. static long _vq_quantlist__8u0__p6_1[] = {
  140192. 2,
  140193. 1,
  140194. 3,
  140195. 0,
  140196. 4,
  140197. };
  140198. static long _vq_lengthlist__8u0__p6_1[] = {
  140199. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  140200. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  140201. };
  140202. static float _vq_quantthresh__8u0__p6_1[] = {
  140203. -1.5, -0.5, 0.5, 1.5,
  140204. };
  140205. static long _vq_quantmap__8u0__p6_1[] = {
  140206. 3, 1, 0, 2, 4,
  140207. };
  140208. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  140209. _vq_quantthresh__8u0__p6_1,
  140210. _vq_quantmap__8u0__p6_1,
  140211. 5,
  140212. 5
  140213. };
  140214. static static_codebook _8u0__p6_1 = {
  140215. 2, 25,
  140216. _vq_lengthlist__8u0__p6_1,
  140217. 1, -533725184, 1611661312, 3, 0,
  140218. _vq_quantlist__8u0__p6_1,
  140219. NULL,
  140220. &_vq_auxt__8u0__p6_1,
  140221. NULL,
  140222. 0
  140223. };
  140224. static long _vq_quantlist__8u0__p7_0[] = {
  140225. 1,
  140226. 0,
  140227. 2,
  140228. };
  140229. static long _vq_lengthlist__8u0__p7_0[] = {
  140230. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140231. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140232. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140233. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140234. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140235. 7,
  140236. };
  140237. static float _vq_quantthresh__8u0__p7_0[] = {
  140238. -157.5, 157.5,
  140239. };
  140240. static long _vq_quantmap__8u0__p7_0[] = {
  140241. 1, 0, 2,
  140242. };
  140243. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  140244. _vq_quantthresh__8u0__p7_0,
  140245. _vq_quantmap__8u0__p7_0,
  140246. 3,
  140247. 3
  140248. };
  140249. static static_codebook _8u0__p7_0 = {
  140250. 4, 81,
  140251. _vq_lengthlist__8u0__p7_0,
  140252. 1, -518803456, 1628680192, 2, 0,
  140253. _vq_quantlist__8u0__p7_0,
  140254. NULL,
  140255. &_vq_auxt__8u0__p7_0,
  140256. NULL,
  140257. 0
  140258. };
  140259. static long _vq_quantlist__8u0__p7_1[] = {
  140260. 7,
  140261. 6,
  140262. 8,
  140263. 5,
  140264. 9,
  140265. 4,
  140266. 10,
  140267. 3,
  140268. 11,
  140269. 2,
  140270. 12,
  140271. 1,
  140272. 13,
  140273. 0,
  140274. 14,
  140275. };
  140276. static long _vq_lengthlist__8u0__p7_1[] = {
  140277. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  140278. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  140279. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  140280. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  140281. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  140282. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  140283. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140284. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140285. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140286. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140287. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140288. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140289. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  140290. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140291. 10,
  140292. };
  140293. static float _vq_quantthresh__8u0__p7_1[] = {
  140294. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  140295. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  140296. };
  140297. static long _vq_quantmap__8u0__p7_1[] = {
  140298. 13, 11, 9, 7, 5, 3, 1, 0,
  140299. 2, 4, 6, 8, 10, 12, 14,
  140300. };
  140301. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  140302. _vq_quantthresh__8u0__p7_1,
  140303. _vq_quantmap__8u0__p7_1,
  140304. 15,
  140305. 15
  140306. };
  140307. static static_codebook _8u0__p7_1 = {
  140308. 2, 225,
  140309. _vq_lengthlist__8u0__p7_1,
  140310. 1, -520986624, 1620377600, 4, 0,
  140311. _vq_quantlist__8u0__p7_1,
  140312. NULL,
  140313. &_vq_auxt__8u0__p7_1,
  140314. NULL,
  140315. 0
  140316. };
  140317. static long _vq_quantlist__8u0__p7_2[] = {
  140318. 10,
  140319. 9,
  140320. 11,
  140321. 8,
  140322. 12,
  140323. 7,
  140324. 13,
  140325. 6,
  140326. 14,
  140327. 5,
  140328. 15,
  140329. 4,
  140330. 16,
  140331. 3,
  140332. 17,
  140333. 2,
  140334. 18,
  140335. 1,
  140336. 19,
  140337. 0,
  140338. 20,
  140339. };
  140340. static long _vq_lengthlist__8u0__p7_2[] = {
  140341. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  140342. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  140343. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  140344. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  140345. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  140346. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  140347. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  140348. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  140349. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  140350. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  140351. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  140352. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  140353. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  140354. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  140355. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  140356. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  140357. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  140358. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  140359. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  140360. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  140361. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  140362. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  140363. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  140364. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  140365. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  140366. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  140367. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  140368. 11,12,11,11,11,10,10,11,11,
  140369. };
  140370. static float _vq_quantthresh__8u0__p7_2[] = {
  140371. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  140372. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  140373. 6.5, 7.5, 8.5, 9.5,
  140374. };
  140375. static long _vq_quantmap__8u0__p7_2[] = {
  140376. 19, 17, 15, 13, 11, 9, 7, 5,
  140377. 3, 1, 0, 2, 4, 6, 8, 10,
  140378. 12, 14, 16, 18, 20,
  140379. };
  140380. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  140381. _vq_quantthresh__8u0__p7_2,
  140382. _vq_quantmap__8u0__p7_2,
  140383. 21,
  140384. 21
  140385. };
  140386. static static_codebook _8u0__p7_2 = {
  140387. 2, 441,
  140388. _vq_lengthlist__8u0__p7_2,
  140389. 1, -529268736, 1611661312, 5, 0,
  140390. _vq_quantlist__8u0__p7_2,
  140391. NULL,
  140392. &_vq_auxt__8u0__p7_2,
  140393. NULL,
  140394. 0
  140395. };
  140396. static long _huff_lengthlist__8u0__single[] = {
  140397. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  140398. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  140399. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  140400. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  140401. };
  140402. static static_codebook _huff_book__8u0__single = {
  140403. 2, 64,
  140404. _huff_lengthlist__8u0__single,
  140405. 0, 0, 0, 0, 0,
  140406. NULL,
  140407. NULL,
  140408. NULL,
  140409. NULL,
  140410. 0
  140411. };
  140412. static long _vq_quantlist__8u1__p1_0[] = {
  140413. 1,
  140414. 0,
  140415. 2,
  140416. };
  140417. static long _vq_lengthlist__8u1__p1_0[] = {
  140418. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  140419. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  140420. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  140421. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  140422. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  140423. 10,
  140424. };
  140425. static float _vq_quantthresh__8u1__p1_0[] = {
  140426. -0.5, 0.5,
  140427. };
  140428. static long _vq_quantmap__8u1__p1_0[] = {
  140429. 1, 0, 2,
  140430. };
  140431. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  140432. _vq_quantthresh__8u1__p1_0,
  140433. _vq_quantmap__8u1__p1_0,
  140434. 3,
  140435. 3
  140436. };
  140437. static static_codebook _8u1__p1_0 = {
  140438. 4, 81,
  140439. _vq_lengthlist__8u1__p1_0,
  140440. 1, -535822336, 1611661312, 2, 0,
  140441. _vq_quantlist__8u1__p1_0,
  140442. NULL,
  140443. &_vq_auxt__8u1__p1_0,
  140444. NULL,
  140445. 0
  140446. };
  140447. static long _vq_quantlist__8u1__p2_0[] = {
  140448. 1,
  140449. 0,
  140450. 2,
  140451. };
  140452. static long _vq_lengthlist__8u1__p2_0[] = {
  140453. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  140454. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  140455. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  140456. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  140457. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  140458. 7,
  140459. };
  140460. static float _vq_quantthresh__8u1__p2_0[] = {
  140461. -0.5, 0.5,
  140462. };
  140463. static long _vq_quantmap__8u1__p2_0[] = {
  140464. 1, 0, 2,
  140465. };
  140466. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  140467. _vq_quantthresh__8u1__p2_0,
  140468. _vq_quantmap__8u1__p2_0,
  140469. 3,
  140470. 3
  140471. };
  140472. static static_codebook _8u1__p2_0 = {
  140473. 4, 81,
  140474. _vq_lengthlist__8u1__p2_0,
  140475. 1, -535822336, 1611661312, 2, 0,
  140476. _vq_quantlist__8u1__p2_0,
  140477. NULL,
  140478. &_vq_auxt__8u1__p2_0,
  140479. NULL,
  140480. 0
  140481. };
  140482. static long _vq_quantlist__8u1__p3_0[] = {
  140483. 2,
  140484. 1,
  140485. 3,
  140486. 0,
  140487. 4,
  140488. };
  140489. static long _vq_lengthlist__8u1__p3_0[] = {
  140490. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  140491. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  140492. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  140493. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  140494. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  140495. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  140496. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  140497. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  140498. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  140499. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  140500. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  140501. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  140502. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  140503. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  140504. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  140505. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  140506. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  140507. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  140508. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  140509. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  140510. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  140511. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  140512. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  140513. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  140514. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  140515. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  140516. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  140517. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  140518. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  140519. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  140520. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  140521. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  140522. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  140523. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  140524. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  140525. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  140526. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  140527. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  140528. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  140529. 16,
  140530. };
  140531. static float _vq_quantthresh__8u1__p3_0[] = {
  140532. -1.5, -0.5, 0.5, 1.5,
  140533. };
  140534. static long _vq_quantmap__8u1__p3_0[] = {
  140535. 3, 1, 0, 2, 4,
  140536. };
  140537. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  140538. _vq_quantthresh__8u1__p3_0,
  140539. _vq_quantmap__8u1__p3_0,
  140540. 5,
  140541. 5
  140542. };
  140543. static static_codebook _8u1__p3_0 = {
  140544. 4, 625,
  140545. _vq_lengthlist__8u1__p3_0,
  140546. 1, -533725184, 1611661312, 3, 0,
  140547. _vq_quantlist__8u1__p3_0,
  140548. NULL,
  140549. &_vq_auxt__8u1__p3_0,
  140550. NULL,
  140551. 0
  140552. };
  140553. static long _vq_quantlist__8u1__p4_0[] = {
  140554. 2,
  140555. 1,
  140556. 3,
  140557. 0,
  140558. 4,
  140559. };
  140560. static long _vq_lengthlist__8u1__p4_0[] = {
  140561. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  140562. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  140563. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  140564. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  140565. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  140566. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  140567. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  140568. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  140569. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  140570. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  140571. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  140572. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  140573. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  140574. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  140575. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  140576. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  140577. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  140578. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  140579. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  140580. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  140581. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  140582. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  140583. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  140584. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  140585. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  140586. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  140587. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  140588. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  140589. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  140590. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  140591. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  140592. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  140593. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  140594. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  140595. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  140596. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  140597. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  140598. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  140599. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  140600. 10,
  140601. };
  140602. static float _vq_quantthresh__8u1__p4_0[] = {
  140603. -1.5, -0.5, 0.5, 1.5,
  140604. };
  140605. static long _vq_quantmap__8u1__p4_0[] = {
  140606. 3, 1, 0, 2, 4,
  140607. };
  140608. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  140609. _vq_quantthresh__8u1__p4_0,
  140610. _vq_quantmap__8u1__p4_0,
  140611. 5,
  140612. 5
  140613. };
  140614. static static_codebook _8u1__p4_0 = {
  140615. 4, 625,
  140616. _vq_lengthlist__8u1__p4_0,
  140617. 1, -533725184, 1611661312, 3, 0,
  140618. _vq_quantlist__8u1__p4_0,
  140619. NULL,
  140620. &_vq_auxt__8u1__p4_0,
  140621. NULL,
  140622. 0
  140623. };
  140624. static long _vq_quantlist__8u1__p5_0[] = {
  140625. 4,
  140626. 3,
  140627. 5,
  140628. 2,
  140629. 6,
  140630. 1,
  140631. 7,
  140632. 0,
  140633. 8,
  140634. };
  140635. static long _vq_lengthlist__8u1__p5_0[] = {
  140636. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  140637. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  140638. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  140639. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  140640. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  140641. 13,
  140642. };
  140643. static float _vq_quantthresh__8u1__p5_0[] = {
  140644. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140645. };
  140646. static long _vq_quantmap__8u1__p5_0[] = {
  140647. 7, 5, 3, 1, 0, 2, 4, 6,
  140648. 8,
  140649. };
  140650. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  140651. _vq_quantthresh__8u1__p5_0,
  140652. _vq_quantmap__8u1__p5_0,
  140653. 9,
  140654. 9
  140655. };
  140656. static static_codebook _8u1__p5_0 = {
  140657. 2, 81,
  140658. _vq_lengthlist__8u1__p5_0,
  140659. 1, -531628032, 1611661312, 4, 0,
  140660. _vq_quantlist__8u1__p5_0,
  140661. NULL,
  140662. &_vq_auxt__8u1__p5_0,
  140663. NULL,
  140664. 0
  140665. };
  140666. static long _vq_quantlist__8u1__p6_0[] = {
  140667. 4,
  140668. 3,
  140669. 5,
  140670. 2,
  140671. 6,
  140672. 1,
  140673. 7,
  140674. 0,
  140675. 8,
  140676. };
  140677. static long _vq_lengthlist__8u1__p6_0[] = {
  140678. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  140679. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  140680. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  140681. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  140682. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  140683. 10,
  140684. };
  140685. static float _vq_quantthresh__8u1__p6_0[] = {
  140686. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140687. };
  140688. static long _vq_quantmap__8u1__p6_0[] = {
  140689. 7, 5, 3, 1, 0, 2, 4, 6,
  140690. 8,
  140691. };
  140692. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  140693. _vq_quantthresh__8u1__p6_0,
  140694. _vq_quantmap__8u1__p6_0,
  140695. 9,
  140696. 9
  140697. };
  140698. static static_codebook _8u1__p6_0 = {
  140699. 2, 81,
  140700. _vq_lengthlist__8u1__p6_0,
  140701. 1, -531628032, 1611661312, 4, 0,
  140702. _vq_quantlist__8u1__p6_0,
  140703. NULL,
  140704. &_vq_auxt__8u1__p6_0,
  140705. NULL,
  140706. 0
  140707. };
  140708. static long _vq_quantlist__8u1__p7_0[] = {
  140709. 1,
  140710. 0,
  140711. 2,
  140712. };
  140713. static long _vq_lengthlist__8u1__p7_0[] = {
  140714. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  140715. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  140716. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  140717. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  140718. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  140719. 11,
  140720. };
  140721. static float _vq_quantthresh__8u1__p7_0[] = {
  140722. -5.5, 5.5,
  140723. };
  140724. static long _vq_quantmap__8u1__p7_0[] = {
  140725. 1, 0, 2,
  140726. };
  140727. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  140728. _vq_quantthresh__8u1__p7_0,
  140729. _vq_quantmap__8u1__p7_0,
  140730. 3,
  140731. 3
  140732. };
  140733. static static_codebook _8u1__p7_0 = {
  140734. 4, 81,
  140735. _vq_lengthlist__8u1__p7_0,
  140736. 1, -529137664, 1618345984, 2, 0,
  140737. _vq_quantlist__8u1__p7_0,
  140738. NULL,
  140739. &_vq_auxt__8u1__p7_0,
  140740. NULL,
  140741. 0
  140742. };
  140743. static long _vq_quantlist__8u1__p7_1[] = {
  140744. 5,
  140745. 4,
  140746. 6,
  140747. 3,
  140748. 7,
  140749. 2,
  140750. 8,
  140751. 1,
  140752. 9,
  140753. 0,
  140754. 10,
  140755. };
  140756. static long _vq_lengthlist__8u1__p7_1[] = {
  140757. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  140758. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  140759. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  140760. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  140761. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  140762. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  140763. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  140764. 9, 9, 9, 9, 9,10,10,10,10,
  140765. };
  140766. static float _vq_quantthresh__8u1__p7_1[] = {
  140767. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140768. 3.5, 4.5,
  140769. };
  140770. static long _vq_quantmap__8u1__p7_1[] = {
  140771. 9, 7, 5, 3, 1, 0, 2, 4,
  140772. 6, 8, 10,
  140773. };
  140774. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  140775. _vq_quantthresh__8u1__p7_1,
  140776. _vq_quantmap__8u1__p7_1,
  140777. 11,
  140778. 11
  140779. };
  140780. static static_codebook _8u1__p7_1 = {
  140781. 2, 121,
  140782. _vq_lengthlist__8u1__p7_1,
  140783. 1, -531365888, 1611661312, 4, 0,
  140784. _vq_quantlist__8u1__p7_1,
  140785. NULL,
  140786. &_vq_auxt__8u1__p7_1,
  140787. NULL,
  140788. 0
  140789. };
  140790. static long _vq_quantlist__8u1__p8_0[] = {
  140791. 5,
  140792. 4,
  140793. 6,
  140794. 3,
  140795. 7,
  140796. 2,
  140797. 8,
  140798. 1,
  140799. 9,
  140800. 0,
  140801. 10,
  140802. };
  140803. static long _vq_lengthlist__8u1__p8_0[] = {
  140804. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  140805. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  140806. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  140807. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  140808. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  140809. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  140810. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  140811. 12,13,13,14,14,15,15,15,15,
  140812. };
  140813. static float _vq_quantthresh__8u1__p8_0[] = {
  140814. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  140815. 38.5, 49.5,
  140816. };
  140817. static long _vq_quantmap__8u1__p8_0[] = {
  140818. 9, 7, 5, 3, 1, 0, 2, 4,
  140819. 6, 8, 10,
  140820. };
  140821. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  140822. _vq_quantthresh__8u1__p8_0,
  140823. _vq_quantmap__8u1__p8_0,
  140824. 11,
  140825. 11
  140826. };
  140827. static static_codebook _8u1__p8_0 = {
  140828. 2, 121,
  140829. _vq_lengthlist__8u1__p8_0,
  140830. 1, -524582912, 1618345984, 4, 0,
  140831. _vq_quantlist__8u1__p8_0,
  140832. NULL,
  140833. &_vq_auxt__8u1__p8_0,
  140834. NULL,
  140835. 0
  140836. };
  140837. static long _vq_quantlist__8u1__p8_1[] = {
  140838. 5,
  140839. 4,
  140840. 6,
  140841. 3,
  140842. 7,
  140843. 2,
  140844. 8,
  140845. 1,
  140846. 9,
  140847. 0,
  140848. 10,
  140849. };
  140850. static long _vq_lengthlist__8u1__p8_1[] = {
  140851. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  140852. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  140853. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  140854. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  140855. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140856. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  140857. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  140858. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  140859. };
  140860. static float _vq_quantthresh__8u1__p8_1[] = {
  140861. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140862. 3.5, 4.5,
  140863. };
  140864. static long _vq_quantmap__8u1__p8_1[] = {
  140865. 9, 7, 5, 3, 1, 0, 2, 4,
  140866. 6, 8, 10,
  140867. };
  140868. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  140869. _vq_quantthresh__8u1__p8_1,
  140870. _vq_quantmap__8u1__p8_1,
  140871. 11,
  140872. 11
  140873. };
  140874. static static_codebook _8u1__p8_1 = {
  140875. 2, 121,
  140876. _vq_lengthlist__8u1__p8_1,
  140877. 1, -531365888, 1611661312, 4, 0,
  140878. _vq_quantlist__8u1__p8_1,
  140879. NULL,
  140880. &_vq_auxt__8u1__p8_1,
  140881. NULL,
  140882. 0
  140883. };
  140884. static long _vq_quantlist__8u1__p9_0[] = {
  140885. 7,
  140886. 6,
  140887. 8,
  140888. 5,
  140889. 9,
  140890. 4,
  140891. 10,
  140892. 3,
  140893. 11,
  140894. 2,
  140895. 12,
  140896. 1,
  140897. 13,
  140898. 0,
  140899. 14,
  140900. };
  140901. static long _vq_lengthlist__8u1__p9_0[] = {
  140902. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  140903. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  140904. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140905. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140906. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140907. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140908. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140909. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140910. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140911. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140913. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140914. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  140915. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140916. 10,
  140917. };
  140918. static float _vq_quantthresh__8u1__p9_0[] = {
  140919. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  140920. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  140921. };
  140922. static long _vq_quantmap__8u1__p9_0[] = {
  140923. 13, 11, 9, 7, 5, 3, 1, 0,
  140924. 2, 4, 6, 8, 10, 12, 14,
  140925. };
  140926. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  140927. _vq_quantthresh__8u1__p9_0,
  140928. _vq_quantmap__8u1__p9_0,
  140929. 15,
  140930. 15
  140931. };
  140932. static static_codebook _8u1__p9_0 = {
  140933. 2, 225,
  140934. _vq_lengthlist__8u1__p9_0,
  140935. 1, -514071552, 1627381760, 4, 0,
  140936. _vq_quantlist__8u1__p9_0,
  140937. NULL,
  140938. &_vq_auxt__8u1__p9_0,
  140939. NULL,
  140940. 0
  140941. };
  140942. static long _vq_quantlist__8u1__p9_1[] = {
  140943. 7,
  140944. 6,
  140945. 8,
  140946. 5,
  140947. 9,
  140948. 4,
  140949. 10,
  140950. 3,
  140951. 11,
  140952. 2,
  140953. 12,
  140954. 1,
  140955. 13,
  140956. 0,
  140957. 14,
  140958. };
  140959. static long _vq_lengthlist__8u1__p9_1[] = {
  140960. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  140961. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  140962. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  140963. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  140964. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  140965. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  140966. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  140967. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  140968. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  140969. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  140970. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  140971. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  140972. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  140973. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  140974. 13,
  140975. };
  140976. static float _vq_quantthresh__8u1__p9_1[] = {
  140977. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  140978. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  140979. };
  140980. static long _vq_quantmap__8u1__p9_1[] = {
  140981. 13, 11, 9, 7, 5, 3, 1, 0,
  140982. 2, 4, 6, 8, 10, 12, 14,
  140983. };
  140984. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  140985. _vq_quantthresh__8u1__p9_1,
  140986. _vq_quantmap__8u1__p9_1,
  140987. 15,
  140988. 15
  140989. };
  140990. static static_codebook _8u1__p9_1 = {
  140991. 2, 225,
  140992. _vq_lengthlist__8u1__p9_1,
  140993. 1, -522338304, 1620115456, 4, 0,
  140994. _vq_quantlist__8u1__p9_1,
  140995. NULL,
  140996. &_vq_auxt__8u1__p9_1,
  140997. NULL,
  140998. 0
  140999. };
  141000. static long _vq_quantlist__8u1__p9_2[] = {
  141001. 8,
  141002. 7,
  141003. 9,
  141004. 6,
  141005. 10,
  141006. 5,
  141007. 11,
  141008. 4,
  141009. 12,
  141010. 3,
  141011. 13,
  141012. 2,
  141013. 14,
  141014. 1,
  141015. 15,
  141016. 0,
  141017. 16,
  141018. };
  141019. static long _vq_lengthlist__8u1__p9_2[] = {
  141020. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141021. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  141022. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141023. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  141024. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141025. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  141026. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141027. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  141028. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  141029. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  141030. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  141031. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  141032. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  141033. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  141034. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  141035. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  141036. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141037. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141038. 10,
  141039. };
  141040. static float _vq_quantthresh__8u1__p9_2[] = {
  141041. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141042. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141043. };
  141044. static long _vq_quantmap__8u1__p9_2[] = {
  141045. 15, 13, 11, 9, 7, 5, 3, 1,
  141046. 0, 2, 4, 6, 8, 10, 12, 14,
  141047. 16,
  141048. };
  141049. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  141050. _vq_quantthresh__8u1__p9_2,
  141051. _vq_quantmap__8u1__p9_2,
  141052. 17,
  141053. 17
  141054. };
  141055. static static_codebook _8u1__p9_2 = {
  141056. 2, 289,
  141057. _vq_lengthlist__8u1__p9_2,
  141058. 1, -529530880, 1611661312, 5, 0,
  141059. _vq_quantlist__8u1__p9_2,
  141060. NULL,
  141061. &_vq_auxt__8u1__p9_2,
  141062. NULL,
  141063. 0
  141064. };
  141065. static long _huff_lengthlist__8u1__single[] = {
  141066. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  141067. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  141068. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  141069. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  141070. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  141071. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  141072. 13, 8, 8,15,
  141073. };
  141074. static static_codebook _huff_book__8u1__single = {
  141075. 2, 100,
  141076. _huff_lengthlist__8u1__single,
  141077. 0, 0, 0, 0, 0,
  141078. NULL,
  141079. NULL,
  141080. NULL,
  141081. NULL,
  141082. 0
  141083. };
  141084. static long _huff_lengthlist__44u0__long[] = {
  141085. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  141086. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  141087. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  141088. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  141089. };
  141090. static static_codebook _huff_book__44u0__long = {
  141091. 2, 64,
  141092. _huff_lengthlist__44u0__long,
  141093. 0, 0, 0, 0, 0,
  141094. NULL,
  141095. NULL,
  141096. NULL,
  141097. NULL,
  141098. 0
  141099. };
  141100. static long _vq_quantlist__44u0__p1_0[] = {
  141101. 1,
  141102. 0,
  141103. 2,
  141104. };
  141105. static long _vq_lengthlist__44u0__p1_0[] = {
  141106. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  141107. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141108. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  141109. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  141110. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  141111. 13,
  141112. };
  141113. static float _vq_quantthresh__44u0__p1_0[] = {
  141114. -0.5, 0.5,
  141115. };
  141116. static long _vq_quantmap__44u0__p1_0[] = {
  141117. 1, 0, 2,
  141118. };
  141119. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  141120. _vq_quantthresh__44u0__p1_0,
  141121. _vq_quantmap__44u0__p1_0,
  141122. 3,
  141123. 3
  141124. };
  141125. static static_codebook _44u0__p1_0 = {
  141126. 4, 81,
  141127. _vq_lengthlist__44u0__p1_0,
  141128. 1, -535822336, 1611661312, 2, 0,
  141129. _vq_quantlist__44u0__p1_0,
  141130. NULL,
  141131. &_vq_auxt__44u0__p1_0,
  141132. NULL,
  141133. 0
  141134. };
  141135. static long _vq_quantlist__44u0__p2_0[] = {
  141136. 1,
  141137. 0,
  141138. 2,
  141139. };
  141140. static long _vq_lengthlist__44u0__p2_0[] = {
  141141. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  141142. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  141143. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141144. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  141145. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  141146. 9,
  141147. };
  141148. static float _vq_quantthresh__44u0__p2_0[] = {
  141149. -0.5, 0.5,
  141150. };
  141151. static long _vq_quantmap__44u0__p2_0[] = {
  141152. 1, 0, 2,
  141153. };
  141154. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  141155. _vq_quantthresh__44u0__p2_0,
  141156. _vq_quantmap__44u0__p2_0,
  141157. 3,
  141158. 3
  141159. };
  141160. static static_codebook _44u0__p2_0 = {
  141161. 4, 81,
  141162. _vq_lengthlist__44u0__p2_0,
  141163. 1, -535822336, 1611661312, 2, 0,
  141164. _vq_quantlist__44u0__p2_0,
  141165. NULL,
  141166. &_vq_auxt__44u0__p2_0,
  141167. NULL,
  141168. 0
  141169. };
  141170. static long _vq_quantlist__44u0__p3_0[] = {
  141171. 2,
  141172. 1,
  141173. 3,
  141174. 0,
  141175. 4,
  141176. };
  141177. static long _vq_lengthlist__44u0__p3_0[] = {
  141178. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  141179. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  141180. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  141181. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  141182. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  141183. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  141184. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  141185. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  141186. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  141187. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  141188. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  141189. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  141190. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  141191. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  141192. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  141193. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  141194. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  141195. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  141196. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  141197. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  141198. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  141199. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  141200. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  141201. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  141202. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  141203. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  141204. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  141205. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  141206. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  141207. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  141208. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  141209. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  141210. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  141211. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  141212. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  141213. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  141214. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  141215. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  141216. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  141217. 19,
  141218. };
  141219. static float _vq_quantthresh__44u0__p3_0[] = {
  141220. -1.5, -0.5, 0.5, 1.5,
  141221. };
  141222. static long _vq_quantmap__44u0__p3_0[] = {
  141223. 3, 1, 0, 2, 4,
  141224. };
  141225. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  141226. _vq_quantthresh__44u0__p3_0,
  141227. _vq_quantmap__44u0__p3_0,
  141228. 5,
  141229. 5
  141230. };
  141231. static static_codebook _44u0__p3_0 = {
  141232. 4, 625,
  141233. _vq_lengthlist__44u0__p3_0,
  141234. 1, -533725184, 1611661312, 3, 0,
  141235. _vq_quantlist__44u0__p3_0,
  141236. NULL,
  141237. &_vq_auxt__44u0__p3_0,
  141238. NULL,
  141239. 0
  141240. };
  141241. static long _vq_quantlist__44u0__p4_0[] = {
  141242. 2,
  141243. 1,
  141244. 3,
  141245. 0,
  141246. 4,
  141247. };
  141248. static long _vq_lengthlist__44u0__p4_0[] = {
  141249. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  141250. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  141251. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  141252. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  141253. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  141254. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  141255. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  141256. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  141257. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  141258. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  141259. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  141260. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141261. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  141262. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  141263. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  141264. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  141265. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  141266. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  141267. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  141268. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  141269. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  141270. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  141271. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  141272. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  141273. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  141274. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  141275. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  141276. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  141277. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  141278. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  141279. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  141280. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  141281. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  141282. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  141283. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  141284. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  141285. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  141286. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  141287. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  141288. 12,
  141289. };
  141290. static float _vq_quantthresh__44u0__p4_0[] = {
  141291. -1.5, -0.5, 0.5, 1.5,
  141292. };
  141293. static long _vq_quantmap__44u0__p4_0[] = {
  141294. 3, 1, 0, 2, 4,
  141295. };
  141296. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  141297. _vq_quantthresh__44u0__p4_0,
  141298. _vq_quantmap__44u0__p4_0,
  141299. 5,
  141300. 5
  141301. };
  141302. static static_codebook _44u0__p4_0 = {
  141303. 4, 625,
  141304. _vq_lengthlist__44u0__p4_0,
  141305. 1, -533725184, 1611661312, 3, 0,
  141306. _vq_quantlist__44u0__p4_0,
  141307. NULL,
  141308. &_vq_auxt__44u0__p4_0,
  141309. NULL,
  141310. 0
  141311. };
  141312. static long _vq_quantlist__44u0__p5_0[] = {
  141313. 4,
  141314. 3,
  141315. 5,
  141316. 2,
  141317. 6,
  141318. 1,
  141319. 7,
  141320. 0,
  141321. 8,
  141322. };
  141323. static long _vq_lengthlist__44u0__p5_0[] = {
  141324. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  141325. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  141326. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  141327. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  141328. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  141329. 12,
  141330. };
  141331. static float _vq_quantthresh__44u0__p5_0[] = {
  141332. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141333. };
  141334. static long _vq_quantmap__44u0__p5_0[] = {
  141335. 7, 5, 3, 1, 0, 2, 4, 6,
  141336. 8,
  141337. };
  141338. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  141339. _vq_quantthresh__44u0__p5_0,
  141340. _vq_quantmap__44u0__p5_0,
  141341. 9,
  141342. 9
  141343. };
  141344. static static_codebook _44u0__p5_0 = {
  141345. 2, 81,
  141346. _vq_lengthlist__44u0__p5_0,
  141347. 1, -531628032, 1611661312, 4, 0,
  141348. _vq_quantlist__44u0__p5_0,
  141349. NULL,
  141350. &_vq_auxt__44u0__p5_0,
  141351. NULL,
  141352. 0
  141353. };
  141354. static long _vq_quantlist__44u0__p6_0[] = {
  141355. 6,
  141356. 5,
  141357. 7,
  141358. 4,
  141359. 8,
  141360. 3,
  141361. 9,
  141362. 2,
  141363. 10,
  141364. 1,
  141365. 11,
  141366. 0,
  141367. 12,
  141368. };
  141369. static long _vq_lengthlist__44u0__p6_0[] = {
  141370. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  141371. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  141372. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  141373. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  141374. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  141375. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  141376. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  141377. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  141378. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  141379. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  141380. 15,17,16,17,18,17,17,18, 0,
  141381. };
  141382. static float _vq_quantthresh__44u0__p6_0[] = {
  141383. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141384. 12.5, 17.5, 22.5, 27.5,
  141385. };
  141386. static long _vq_quantmap__44u0__p6_0[] = {
  141387. 11, 9, 7, 5, 3, 1, 0, 2,
  141388. 4, 6, 8, 10, 12,
  141389. };
  141390. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  141391. _vq_quantthresh__44u0__p6_0,
  141392. _vq_quantmap__44u0__p6_0,
  141393. 13,
  141394. 13
  141395. };
  141396. static static_codebook _44u0__p6_0 = {
  141397. 2, 169,
  141398. _vq_lengthlist__44u0__p6_0,
  141399. 1, -526516224, 1616117760, 4, 0,
  141400. _vq_quantlist__44u0__p6_0,
  141401. NULL,
  141402. &_vq_auxt__44u0__p6_0,
  141403. NULL,
  141404. 0
  141405. };
  141406. static long _vq_quantlist__44u0__p6_1[] = {
  141407. 2,
  141408. 1,
  141409. 3,
  141410. 0,
  141411. 4,
  141412. };
  141413. static long _vq_lengthlist__44u0__p6_1[] = {
  141414. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  141415. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  141416. };
  141417. static float _vq_quantthresh__44u0__p6_1[] = {
  141418. -1.5, -0.5, 0.5, 1.5,
  141419. };
  141420. static long _vq_quantmap__44u0__p6_1[] = {
  141421. 3, 1, 0, 2, 4,
  141422. };
  141423. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  141424. _vq_quantthresh__44u0__p6_1,
  141425. _vq_quantmap__44u0__p6_1,
  141426. 5,
  141427. 5
  141428. };
  141429. static static_codebook _44u0__p6_1 = {
  141430. 2, 25,
  141431. _vq_lengthlist__44u0__p6_1,
  141432. 1, -533725184, 1611661312, 3, 0,
  141433. _vq_quantlist__44u0__p6_1,
  141434. NULL,
  141435. &_vq_auxt__44u0__p6_1,
  141436. NULL,
  141437. 0
  141438. };
  141439. static long _vq_quantlist__44u0__p7_0[] = {
  141440. 2,
  141441. 1,
  141442. 3,
  141443. 0,
  141444. 4,
  141445. };
  141446. static long _vq_lengthlist__44u0__p7_0[] = {
  141447. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  141448. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141449. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141450. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141451. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141452. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141453. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141454. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  141455. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141456. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141457. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141458. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141459. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141460. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141461. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141462. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141463. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141464. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141465. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141466. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141467. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141468. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141469. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141470. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141471. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141472. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141473. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141474. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141475. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141476. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141477. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  141478. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141479. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141480. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141481. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141482. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141483. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141484. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141485. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141486. 10,
  141487. };
  141488. static float _vq_quantthresh__44u0__p7_0[] = {
  141489. -253.5, -84.5, 84.5, 253.5,
  141490. };
  141491. static long _vq_quantmap__44u0__p7_0[] = {
  141492. 3, 1, 0, 2, 4,
  141493. };
  141494. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  141495. _vq_quantthresh__44u0__p7_0,
  141496. _vq_quantmap__44u0__p7_0,
  141497. 5,
  141498. 5
  141499. };
  141500. static static_codebook _44u0__p7_0 = {
  141501. 4, 625,
  141502. _vq_lengthlist__44u0__p7_0,
  141503. 1, -518709248, 1626677248, 3, 0,
  141504. _vq_quantlist__44u0__p7_0,
  141505. NULL,
  141506. &_vq_auxt__44u0__p7_0,
  141507. NULL,
  141508. 0
  141509. };
  141510. static long _vq_quantlist__44u0__p7_1[] = {
  141511. 6,
  141512. 5,
  141513. 7,
  141514. 4,
  141515. 8,
  141516. 3,
  141517. 9,
  141518. 2,
  141519. 10,
  141520. 1,
  141521. 11,
  141522. 0,
  141523. 12,
  141524. };
  141525. static long _vq_lengthlist__44u0__p7_1[] = {
  141526. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  141527. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  141528. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  141529. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  141530. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  141531. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  141532. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  141533. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  141534. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  141535. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  141536. 15,15,15,15,15,15,15,15,15,
  141537. };
  141538. static float _vq_quantthresh__44u0__p7_1[] = {
  141539. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  141540. 32.5, 45.5, 58.5, 71.5,
  141541. };
  141542. static long _vq_quantmap__44u0__p7_1[] = {
  141543. 11, 9, 7, 5, 3, 1, 0, 2,
  141544. 4, 6, 8, 10, 12,
  141545. };
  141546. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  141547. _vq_quantthresh__44u0__p7_1,
  141548. _vq_quantmap__44u0__p7_1,
  141549. 13,
  141550. 13
  141551. };
  141552. static static_codebook _44u0__p7_1 = {
  141553. 2, 169,
  141554. _vq_lengthlist__44u0__p7_1,
  141555. 1, -523010048, 1618608128, 4, 0,
  141556. _vq_quantlist__44u0__p7_1,
  141557. NULL,
  141558. &_vq_auxt__44u0__p7_1,
  141559. NULL,
  141560. 0
  141561. };
  141562. static long _vq_quantlist__44u0__p7_2[] = {
  141563. 6,
  141564. 5,
  141565. 7,
  141566. 4,
  141567. 8,
  141568. 3,
  141569. 9,
  141570. 2,
  141571. 10,
  141572. 1,
  141573. 11,
  141574. 0,
  141575. 12,
  141576. };
  141577. static long _vq_lengthlist__44u0__p7_2[] = {
  141578. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  141579. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  141580. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  141581. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  141582. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  141583. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  141584. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  141585. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141586. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141587. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  141588. 9, 9, 9,10, 9, 9,10,10, 9,
  141589. };
  141590. static float _vq_quantthresh__44u0__p7_2[] = {
  141591. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  141592. 2.5, 3.5, 4.5, 5.5,
  141593. };
  141594. static long _vq_quantmap__44u0__p7_2[] = {
  141595. 11, 9, 7, 5, 3, 1, 0, 2,
  141596. 4, 6, 8, 10, 12,
  141597. };
  141598. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  141599. _vq_quantthresh__44u0__p7_2,
  141600. _vq_quantmap__44u0__p7_2,
  141601. 13,
  141602. 13
  141603. };
  141604. static static_codebook _44u0__p7_2 = {
  141605. 2, 169,
  141606. _vq_lengthlist__44u0__p7_2,
  141607. 1, -531103744, 1611661312, 4, 0,
  141608. _vq_quantlist__44u0__p7_2,
  141609. NULL,
  141610. &_vq_auxt__44u0__p7_2,
  141611. NULL,
  141612. 0
  141613. };
  141614. static long _huff_lengthlist__44u0__short[] = {
  141615. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  141616. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  141617. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  141618. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  141619. };
  141620. static static_codebook _huff_book__44u0__short = {
  141621. 2, 64,
  141622. _huff_lengthlist__44u0__short,
  141623. 0, 0, 0, 0, 0,
  141624. NULL,
  141625. NULL,
  141626. NULL,
  141627. NULL,
  141628. 0
  141629. };
  141630. static long _huff_lengthlist__44u1__long[] = {
  141631. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  141632. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  141633. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  141634. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  141635. };
  141636. static static_codebook _huff_book__44u1__long = {
  141637. 2, 64,
  141638. _huff_lengthlist__44u1__long,
  141639. 0, 0, 0, 0, 0,
  141640. NULL,
  141641. NULL,
  141642. NULL,
  141643. NULL,
  141644. 0
  141645. };
  141646. static long _vq_quantlist__44u1__p1_0[] = {
  141647. 1,
  141648. 0,
  141649. 2,
  141650. };
  141651. static long _vq_lengthlist__44u1__p1_0[] = {
  141652. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  141653. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141654. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  141655. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  141656. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  141657. 13,
  141658. };
  141659. static float _vq_quantthresh__44u1__p1_0[] = {
  141660. -0.5, 0.5,
  141661. };
  141662. static long _vq_quantmap__44u1__p1_0[] = {
  141663. 1, 0, 2,
  141664. };
  141665. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  141666. _vq_quantthresh__44u1__p1_0,
  141667. _vq_quantmap__44u1__p1_0,
  141668. 3,
  141669. 3
  141670. };
  141671. static static_codebook _44u1__p1_0 = {
  141672. 4, 81,
  141673. _vq_lengthlist__44u1__p1_0,
  141674. 1, -535822336, 1611661312, 2, 0,
  141675. _vq_quantlist__44u1__p1_0,
  141676. NULL,
  141677. &_vq_auxt__44u1__p1_0,
  141678. NULL,
  141679. 0
  141680. };
  141681. static long _vq_quantlist__44u1__p2_0[] = {
  141682. 1,
  141683. 0,
  141684. 2,
  141685. };
  141686. static long _vq_lengthlist__44u1__p2_0[] = {
  141687. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  141688. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  141689. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141690. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  141691. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  141692. 9,
  141693. };
  141694. static float _vq_quantthresh__44u1__p2_0[] = {
  141695. -0.5, 0.5,
  141696. };
  141697. static long _vq_quantmap__44u1__p2_0[] = {
  141698. 1, 0, 2,
  141699. };
  141700. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  141701. _vq_quantthresh__44u1__p2_0,
  141702. _vq_quantmap__44u1__p2_0,
  141703. 3,
  141704. 3
  141705. };
  141706. static static_codebook _44u1__p2_0 = {
  141707. 4, 81,
  141708. _vq_lengthlist__44u1__p2_0,
  141709. 1, -535822336, 1611661312, 2, 0,
  141710. _vq_quantlist__44u1__p2_0,
  141711. NULL,
  141712. &_vq_auxt__44u1__p2_0,
  141713. NULL,
  141714. 0
  141715. };
  141716. static long _vq_quantlist__44u1__p3_0[] = {
  141717. 2,
  141718. 1,
  141719. 3,
  141720. 0,
  141721. 4,
  141722. };
  141723. static long _vq_lengthlist__44u1__p3_0[] = {
  141724. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  141725. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  141726. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  141727. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  141728. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  141729. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  141730. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  141731. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  141732. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  141733. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  141734. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  141735. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  141736. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  141737. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  141738. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  141739. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  141740. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  141741. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  141742. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  141743. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  141744. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  141745. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  141746. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  141747. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  141748. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  141749. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  141750. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  141751. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  141752. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  141753. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  141754. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  141755. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  141756. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  141757. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  141758. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  141759. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  141760. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  141761. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  141762. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  141763. 19,
  141764. };
  141765. static float _vq_quantthresh__44u1__p3_0[] = {
  141766. -1.5, -0.5, 0.5, 1.5,
  141767. };
  141768. static long _vq_quantmap__44u1__p3_0[] = {
  141769. 3, 1, 0, 2, 4,
  141770. };
  141771. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  141772. _vq_quantthresh__44u1__p3_0,
  141773. _vq_quantmap__44u1__p3_0,
  141774. 5,
  141775. 5
  141776. };
  141777. static static_codebook _44u1__p3_0 = {
  141778. 4, 625,
  141779. _vq_lengthlist__44u1__p3_0,
  141780. 1, -533725184, 1611661312, 3, 0,
  141781. _vq_quantlist__44u1__p3_0,
  141782. NULL,
  141783. &_vq_auxt__44u1__p3_0,
  141784. NULL,
  141785. 0
  141786. };
  141787. static long _vq_quantlist__44u1__p4_0[] = {
  141788. 2,
  141789. 1,
  141790. 3,
  141791. 0,
  141792. 4,
  141793. };
  141794. static long _vq_lengthlist__44u1__p4_0[] = {
  141795. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  141796. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  141797. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  141798. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  141799. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  141800. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  141801. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  141802. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  141803. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  141804. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  141805. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  141806. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141807. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  141808. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  141809. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  141810. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  141811. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  141812. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  141813. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  141814. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  141815. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  141816. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  141817. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  141818. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  141819. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  141820. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  141821. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  141822. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  141823. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  141824. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  141825. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  141826. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  141827. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  141828. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  141829. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  141830. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  141831. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  141832. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  141833. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  141834. 12,
  141835. };
  141836. static float _vq_quantthresh__44u1__p4_0[] = {
  141837. -1.5, -0.5, 0.5, 1.5,
  141838. };
  141839. static long _vq_quantmap__44u1__p4_0[] = {
  141840. 3, 1, 0, 2, 4,
  141841. };
  141842. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  141843. _vq_quantthresh__44u1__p4_0,
  141844. _vq_quantmap__44u1__p4_0,
  141845. 5,
  141846. 5
  141847. };
  141848. static static_codebook _44u1__p4_0 = {
  141849. 4, 625,
  141850. _vq_lengthlist__44u1__p4_0,
  141851. 1, -533725184, 1611661312, 3, 0,
  141852. _vq_quantlist__44u1__p4_0,
  141853. NULL,
  141854. &_vq_auxt__44u1__p4_0,
  141855. NULL,
  141856. 0
  141857. };
  141858. static long _vq_quantlist__44u1__p5_0[] = {
  141859. 4,
  141860. 3,
  141861. 5,
  141862. 2,
  141863. 6,
  141864. 1,
  141865. 7,
  141866. 0,
  141867. 8,
  141868. };
  141869. static long _vq_lengthlist__44u1__p5_0[] = {
  141870. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  141871. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  141872. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  141873. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  141874. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  141875. 12,
  141876. };
  141877. static float _vq_quantthresh__44u1__p5_0[] = {
  141878. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141879. };
  141880. static long _vq_quantmap__44u1__p5_0[] = {
  141881. 7, 5, 3, 1, 0, 2, 4, 6,
  141882. 8,
  141883. };
  141884. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  141885. _vq_quantthresh__44u1__p5_0,
  141886. _vq_quantmap__44u1__p5_0,
  141887. 9,
  141888. 9
  141889. };
  141890. static static_codebook _44u1__p5_0 = {
  141891. 2, 81,
  141892. _vq_lengthlist__44u1__p5_0,
  141893. 1, -531628032, 1611661312, 4, 0,
  141894. _vq_quantlist__44u1__p5_0,
  141895. NULL,
  141896. &_vq_auxt__44u1__p5_0,
  141897. NULL,
  141898. 0
  141899. };
  141900. static long _vq_quantlist__44u1__p6_0[] = {
  141901. 6,
  141902. 5,
  141903. 7,
  141904. 4,
  141905. 8,
  141906. 3,
  141907. 9,
  141908. 2,
  141909. 10,
  141910. 1,
  141911. 11,
  141912. 0,
  141913. 12,
  141914. };
  141915. static long _vq_lengthlist__44u1__p6_0[] = {
  141916. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  141917. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  141918. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  141919. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  141920. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  141921. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  141922. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  141923. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  141924. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  141925. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  141926. 15,17,16,17,18,17,17,18, 0,
  141927. };
  141928. static float _vq_quantthresh__44u1__p6_0[] = {
  141929. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141930. 12.5, 17.5, 22.5, 27.5,
  141931. };
  141932. static long _vq_quantmap__44u1__p6_0[] = {
  141933. 11, 9, 7, 5, 3, 1, 0, 2,
  141934. 4, 6, 8, 10, 12,
  141935. };
  141936. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  141937. _vq_quantthresh__44u1__p6_0,
  141938. _vq_quantmap__44u1__p6_0,
  141939. 13,
  141940. 13
  141941. };
  141942. static static_codebook _44u1__p6_0 = {
  141943. 2, 169,
  141944. _vq_lengthlist__44u1__p6_0,
  141945. 1, -526516224, 1616117760, 4, 0,
  141946. _vq_quantlist__44u1__p6_0,
  141947. NULL,
  141948. &_vq_auxt__44u1__p6_0,
  141949. NULL,
  141950. 0
  141951. };
  141952. static long _vq_quantlist__44u1__p6_1[] = {
  141953. 2,
  141954. 1,
  141955. 3,
  141956. 0,
  141957. 4,
  141958. };
  141959. static long _vq_lengthlist__44u1__p6_1[] = {
  141960. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  141961. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  141962. };
  141963. static float _vq_quantthresh__44u1__p6_1[] = {
  141964. -1.5, -0.5, 0.5, 1.5,
  141965. };
  141966. static long _vq_quantmap__44u1__p6_1[] = {
  141967. 3, 1, 0, 2, 4,
  141968. };
  141969. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  141970. _vq_quantthresh__44u1__p6_1,
  141971. _vq_quantmap__44u1__p6_1,
  141972. 5,
  141973. 5
  141974. };
  141975. static static_codebook _44u1__p6_1 = {
  141976. 2, 25,
  141977. _vq_lengthlist__44u1__p6_1,
  141978. 1, -533725184, 1611661312, 3, 0,
  141979. _vq_quantlist__44u1__p6_1,
  141980. NULL,
  141981. &_vq_auxt__44u1__p6_1,
  141982. NULL,
  141983. 0
  141984. };
  141985. static long _vq_quantlist__44u1__p7_0[] = {
  141986. 3,
  141987. 2,
  141988. 4,
  141989. 1,
  141990. 5,
  141991. 0,
  141992. 6,
  141993. };
  141994. static long _vq_lengthlist__44u1__p7_0[] = {
  141995. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141996. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141997. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141998. 8,
  141999. };
  142000. static float _vq_quantthresh__44u1__p7_0[] = {
  142001. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  142002. };
  142003. static long _vq_quantmap__44u1__p7_0[] = {
  142004. 5, 3, 1, 0, 2, 4, 6,
  142005. };
  142006. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  142007. _vq_quantthresh__44u1__p7_0,
  142008. _vq_quantmap__44u1__p7_0,
  142009. 7,
  142010. 7
  142011. };
  142012. static static_codebook _44u1__p7_0 = {
  142013. 2, 49,
  142014. _vq_lengthlist__44u1__p7_0,
  142015. 1, -518017024, 1626677248, 3, 0,
  142016. _vq_quantlist__44u1__p7_0,
  142017. NULL,
  142018. &_vq_auxt__44u1__p7_0,
  142019. NULL,
  142020. 0
  142021. };
  142022. static long _vq_quantlist__44u1__p7_1[] = {
  142023. 6,
  142024. 5,
  142025. 7,
  142026. 4,
  142027. 8,
  142028. 3,
  142029. 9,
  142030. 2,
  142031. 10,
  142032. 1,
  142033. 11,
  142034. 0,
  142035. 12,
  142036. };
  142037. static long _vq_lengthlist__44u1__p7_1[] = {
  142038. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  142039. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  142040. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  142041. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  142042. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  142043. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  142044. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  142045. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  142046. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  142047. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  142048. 15,15,15,15,15,15,15,15,15,
  142049. };
  142050. static float _vq_quantthresh__44u1__p7_1[] = {
  142051. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  142052. 32.5, 45.5, 58.5, 71.5,
  142053. };
  142054. static long _vq_quantmap__44u1__p7_1[] = {
  142055. 11, 9, 7, 5, 3, 1, 0, 2,
  142056. 4, 6, 8, 10, 12,
  142057. };
  142058. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  142059. _vq_quantthresh__44u1__p7_1,
  142060. _vq_quantmap__44u1__p7_1,
  142061. 13,
  142062. 13
  142063. };
  142064. static static_codebook _44u1__p7_1 = {
  142065. 2, 169,
  142066. _vq_lengthlist__44u1__p7_1,
  142067. 1, -523010048, 1618608128, 4, 0,
  142068. _vq_quantlist__44u1__p7_1,
  142069. NULL,
  142070. &_vq_auxt__44u1__p7_1,
  142071. NULL,
  142072. 0
  142073. };
  142074. static long _vq_quantlist__44u1__p7_2[] = {
  142075. 6,
  142076. 5,
  142077. 7,
  142078. 4,
  142079. 8,
  142080. 3,
  142081. 9,
  142082. 2,
  142083. 10,
  142084. 1,
  142085. 11,
  142086. 0,
  142087. 12,
  142088. };
  142089. static long _vq_lengthlist__44u1__p7_2[] = {
  142090. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  142091. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  142092. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  142093. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  142094. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  142095. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  142096. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  142097. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142098. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142099. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  142100. 9, 9, 9,10, 9, 9,10,10, 9,
  142101. };
  142102. static float _vq_quantthresh__44u1__p7_2[] = {
  142103. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  142104. 2.5, 3.5, 4.5, 5.5,
  142105. };
  142106. static long _vq_quantmap__44u1__p7_2[] = {
  142107. 11, 9, 7, 5, 3, 1, 0, 2,
  142108. 4, 6, 8, 10, 12,
  142109. };
  142110. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  142111. _vq_quantthresh__44u1__p7_2,
  142112. _vq_quantmap__44u1__p7_2,
  142113. 13,
  142114. 13
  142115. };
  142116. static static_codebook _44u1__p7_2 = {
  142117. 2, 169,
  142118. _vq_lengthlist__44u1__p7_2,
  142119. 1, -531103744, 1611661312, 4, 0,
  142120. _vq_quantlist__44u1__p7_2,
  142121. NULL,
  142122. &_vq_auxt__44u1__p7_2,
  142123. NULL,
  142124. 0
  142125. };
  142126. static long _huff_lengthlist__44u1__short[] = {
  142127. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  142128. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  142129. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  142130. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  142131. };
  142132. static static_codebook _huff_book__44u1__short = {
  142133. 2, 64,
  142134. _huff_lengthlist__44u1__short,
  142135. 0, 0, 0, 0, 0,
  142136. NULL,
  142137. NULL,
  142138. NULL,
  142139. NULL,
  142140. 0
  142141. };
  142142. static long _huff_lengthlist__44u2__long[] = {
  142143. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  142144. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  142145. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  142146. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  142147. };
  142148. static static_codebook _huff_book__44u2__long = {
  142149. 2, 64,
  142150. _huff_lengthlist__44u2__long,
  142151. 0, 0, 0, 0, 0,
  142152. NULL,
  142153. NULL,
  142154. NULL,
  142155. NULL,
  142156. 0
  142157. };
  142158. static long _vq_quantlist__44u2__p1_0[] = {
  142159. 1,
  142160. 0,
  142161. 2,
  142162. };
  142163. static long _vq_lengthlist__44u2__p1_0[] = {
  142164. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  142165. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142166. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  142167. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  142168. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  142169. 13,
  142170. };
  142171. static float _vq_quantthresh__44u2__p1_0[] = {
  142172. -0.5, 0.5,
  142173. };
  142174. static long _vq_quantmap__44u2__p1_0[] = {
  142175. 1, 0, 2,
  142176. };
  142177. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  142178. _vq_quantthresh__44u2__p1_0,
  142179. _vq_quantmap__44u2__p1_0,
  142180. 3,
  142181. 3
  142182. };
  142183. static static_codebook _44u2__p1_0 = {
  142184. 4, 81,
  142185. _vq_lengthlist__44u2__p1_0,
  142186. 1, -535822336, 1611661312, 2, 0,
  142187. _vq_quantlist__44u2__p1_0,
  142188. NULL,
  142189. &_vq_auxt__44u2__p1_0,
  142190. NULL,
  142191. 0
  142192. };
  142193. static long _vq_quantlist__44u2__p2_0[] = {
  142194. 1,
  142195. 0,
  142196. 2,
  142197. };
  142198. static long _vq_lengthlist__44u2__p2_0[] = {
  142199. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  142200. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  142201. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142202. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  142203. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  142204. 9,
  142205. };
  142206. static float _vq_quantthresh__44u2__p2_0[] = {
  142207. -0.5, 0.5,
  142208. };
  142209. static long _vq_quantmap__44u2__p2_0[] = {
  142210. 1, 0, 2,
  142211. };
  142212. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  142213. _vq_quantthresh__44u2__p2_0,
  142214. _vq_quantmap__44u2__p2_0,
  142215. 3,
  142216. 3
  142217. };
  142218. static static_codebook _44u2__p2_0 = {
  142219. 4, 81,
  142220. _vq_lengthlist__44u2__p2_0,
  142221. 1, -535822336, 1611661312, 2, 0,
  142222. _vq_quantlist__44u2__p2_0,
  142223. NULL,
  142224. &_vq_auxt__44u2__p2_0,
  142225. NULL,
  142226. 0
  142227. };
  142228. static long _vq_quantlist__44u2__p3_0[] = {
  142229. 2,
  142230. 1,
  142231. 3,
  142232. 0,
  142233. 4,
  142234. };
  142235. static long _vq_lengthlist__44u2__p3_0[] = {
  142236. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  142237. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  142238. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  142239. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  142240. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  142241. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  142242. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  142243. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  142244. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  142245. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  142246. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  142247. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  142248. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  142249. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  142250. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  142251. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  142252. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  142253. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  142254. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  142255. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  142256. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  142257. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  142258. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  142259. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  142260. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  142261. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  142262. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  142263. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  142264. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  142265. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  142266. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  142267. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  142268. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  142269. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  142270. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  142271. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  142272. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  142273. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  142274. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  142275. 0,
  142276. };
  142277. static float _vq_quantthresh__44u2__p3_0[] = {
  142278. -1.5, -0.5, 0.5, 1.5,
  142279. };
  142280. static long _vq_quantmap__44u2__p3_0[] = {
  142281. 3, 1, 0, 2, 4,
  142282. };
  142283. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  142284. _vq_quantthresh__44u2__p3_0,
  142285. _vq_quantmap__44u2__p3_0,
  142286. 5,
  142287. 5
  142288. };
  142289. static static_codebook _44u2__p3_0 = {
  142290. 4, 625,
  142291. _vq_lengthlist__44u2__p3_0,
  142292. 1, -533725184, 1611661312, 3, 0,
  142293. _vq_quantlist__44u2__p3_0,
  142294. NULL,
  142295. &_vq_auxt__44u2__p3_0,
  142296. NULL,
  142297. 0
  142298. };
  142299. static long _vq_quantlist__44u2__p4_0[] = {
  142300. 2,
  142301. 1,
  142302. 3,
  142303. 0,
  142304. 4,
  142305. };
  142306. static long _vq_lengthlist__44u2__p4_0[] = {
  142307. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  142308. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  142309. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142310. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  142311. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  142312. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  142313. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  142314. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  142315. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  142316. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  142317. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  142318. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142319. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  142320. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  142321. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  142322. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  142323. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  142324. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  142325. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  142326. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  142327. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  142328. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  142329. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  142330. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  142331. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  142332. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  142333. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  142334. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  142335. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  142336. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  142337. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  142338. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  142339. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  142340. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  142341. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  142342. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  142343. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  142344. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  142345. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  142346. 13,
  142347. };
  142348. static float _vq_quantthresh__44u2__p4_0[] = {
  142349. -1.5, -0.5, 0.5, 1.5,
  142350. };
  142351. static long _vq_quantmap__44u2__p4_0[] = {
  142352. 3, 1, 0, 2, 4,
  142353. };
  142354. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  142355. _vq_quantthresh__44u2__p4_0,
  142356. _vq_quantmap__44u2__p4_0,
  142357. 5,
  142358. 5
  142359. };
  142360. static static_codebook _44u2__p4_0 = {
  142361. 4, 625,
  142362. _vq_lengthlist__44u2__p4_0,
  142363. 1, -533725184, 1611661312, 3, 0,
  142364. _vq_quantlist__44u2__p4_0,
  142365. NULL,
  142366. &_vq_auxt__44u2__p4_0,
  142367. NULL,
  142368. 0
  142369. };
  142370. static long _vq_quantlist__44u2__p5_0[] = {
  142371. 4,
  142372. 3,
  142373. 5,
  142374. 2,
  142375. 6,
  142376. 1,
  142377. 7,
  142378. 0,
  142379. 8,
  142380. };
  142381. static long _vq_lengthlist__44u2__p5_0[] = {
  142382. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  142383. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  142384. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  142385. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  142386. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  142387. 13,
  142388. };
  142389. static float _vq_quantthresh__44u2__p5_0[] = {
  142390. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142391. };
  142392. static long _vq_quantmap__44u2__p5_0[] = {
  142393. 7, 5, 3, 1, 0, 2, 4, 6,
  142394. 8,
  142395. };
  142396. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  142397. _vq_quantthresh__44u2__p5_0,
  142398. _vq_quantmap__44u2__p5_0,
  142399. 9,
  142400. 9
  142401. };
  142402. static static_codebook _44u2__p5_0 = {
  142403. 2, 81,
  142404. _vq_lengthlist__44u2__p5_0,
  142405. 1, -531628032, 1611661312, 4, 0,
  142406. _vq_quantlist__44u2__p5_0,
  142407. NULL,
  142408. &_vq_auxt__44u2__p5_0,
  142409. NULL,
  142410. 0
  142411. };
  142412. static long _vq_quantlist__44u2__p6_0[] = {
  142413. 6,
  142414. 5,
  142415. 7,
  142416. 4,
  142417. 8,
  142418. 3,
  142419. 9,
  142420. 2,
  142421. 10,
  142422. 1,
  142423. 11,
  142424. 0,
  142425. 12,
  142426. };
  142427. static long _vq_lengthlist__44u2__p6_0[] = {
  142428. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  142429. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  142430. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  142431. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  142432. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  142433. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  142434. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  142435. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  142436. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  142437. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  142438. 15,17,17,16,18,17,18, 0, 0,
  142439. };
  142440. static float _vq_quantthresh__44u2__p6_0[] = {
  142441. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142442. 12.5, 17.5, 22.5, 27.5,
  142443. };
  142444. static long _vq_quantmap__44u2__p6_0[] = {
  142445. 11, 9, 7, 5, 3, 1, 0, 2,
  142446. 4, 6, 8, 10, 12,
  142447. };
  142448. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  142449. _vq_quantthresh__44u2__p6_0,
  142450. _vq_quantmap__44u2__p6_0,
  142451. 13,
  142452. 13
  142453. };
  142454. static static_codebook _44u2__p6_0 = {
  142455. 2, 169,
  142456. _vq_lengthlist__44u2__p6_0,
  142457. 1, -526516224, 1616117760, 4, 0,
  142458. _vq_quantlist__44u2__p6_0,
  142459. NULL,
  142460. &_vq_auxt__44u2__p6_0,
  142461. NULL,
  142462. 0
  142463. };
  142464. static long _vq_quantlist__44u2__p6_1[] = {
  142465. 2,
  142466. 1,
  142467. 3,
  142468. 0,
  142469. 4,
  142470. };
  142471. static long _vq_lengthlist__44u2__p6_1[] = {
  142472. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  142473. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  142474. };
  142475. static float _vq_quantthresh__44u2__p6_1[] = {
  142476. -1.5, -0.5, 0.5, 1.5,
  142477. };
  142478. static long _vq_quantmap__44u2__p6_1[] = {
  142479. 3, 1, 0, 2, 4,
  142480. };
  142481. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  142482. _vq_quantthresh__44u2__p6_1,
  142483. _vq_quantmap__44u2__p6_1,
  142484. 5,
  142485. 5
  142486. };
  142487. static static_codebook _44u2__p6_1 = {
  142488. 2, 25,
  142489. _vq_lengthlist__44u2__p6_1,
  142490. 1, -533725184, 1611661312, 3, 0,
  142491. _vq_quantlist__44u2__p6_1,
  142492. NULL,
  142493. &_vq_auxt__44u2__p6_1,
  142494. NULL,
  142495. 0
  142496. };
  142497. static long _vq_quantlist__44u2__p7_0[] = {
  142498. 4,
  142499. 3,
  142500. 5,
  142501. 2,
  142502. 6,
  142503. 1,
  142504. 7,
  142505. 0,
  142506. 8,
  142507. };
  142508. static long _vq_lengthlist__44u2__p7_0[] = {
  142509. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  142510. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  142511. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142512. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142513. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142514. 11,
  142515. };
  142516. static float _vq_quantthresh__44u2__p7_0[] = {
  142517. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  142518. };
  142519. static long _vq_quantmap__44u2__p7_0[] = {
  142520. 7, 5, 3, 1, 0, 2, 4, 6,
  142521. 8,
  142522. };
  142523. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  142524. _vq_quantthresh__44u2__p7_0,
  142525. _vq_quantmap__44u2__p7_0,
  142526. 9,
  142527. 9
  142528. };
  142529. static static_codebook _44u2__p7_0 = {
  142530. 2, 81,
  142531. _vq_lengthlist__44u2__p7_0,
  142532. 1, -516612096, 1626677248, 4, 0,
  142533. _vq_quantlist__44u2__p7_0,
  142534. NULL,
  142535. &_vq_auxt__44u2__p7_0,
  142536. NULL,
  142537. 0
  142538. };
  142539. static long _vq_quantlist__44u2__p7_1[] = {
  142540. 6,
  142541. 5,
  142542. 7,
  142543. 4,
  142544. 8,
  142545. 3,
  142546. 9,
  142547. 2,
  142548. 10,
  142549. 1,
  142550. 11,
  142551. 0,
  142552. 12,
  142553. };
  142554. static long _vq_lengthlist__44u2__p7_1[] = {
  142555. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  142556. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  142557. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  142558. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  142559. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  142560. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  142561. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  142562. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  142563. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  142564. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  142565. 14,14,14,17,15,17,17,17,17,
  142566. };
  142567. static float _vq_quantthresh__44u2__p7_1[] = {
  142568. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  142569. 32.5, 45.5, 58.5, 71.5,
  142570. };
  142571. static long _vq_quantmap__44u2__p7_1[] = {
  142572. 11, 9, 7, 5, 3, 1, 0, 2,
  142573. 4, 6, 8, 10, 12,
  142574. };
  142575. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  142576. _vq_quantthresh__44u2__p7_1,
  142577. _vq_quantmap__44u2__p7_1,
  142578. 13,
  142579. 13
  142580. };
  142581. static static_codebook _44u2__p7_1 = {
  142582. 2, 169,
  142583. _vq_lengthlist__44u2__p7_1,
  142584. 1, -523010048, 1618608128, 4, 0,
  142585. _vq_quantlist__44u2__p7_1,
  142586. NULL,
  142587. &_vq_auxt__44u2__p7_1,
  142588. NULL,
  142589. 0
  142590. };
  142591. static long _vq_quantlist__44u2__p7_2[] = {
  142592. 6,
  142593. 5,
  142594. 7,
  142595. 4,
  142596. 8,
  142597. 3,
  142598. 9,
  142599. 2,
  142600. 10,
  142601. 1,
  142602. 11,
  142603. 0,
  142604. 12,
  142605. };
  142606. static long _vq_lengthlist__44u2__p7_2[] = {
  142607. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  142608. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  142609. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  142610. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  142611. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  142612. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  142613. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  142614. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142615. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  142616. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  142617. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142618. };
  142619. static float _vq_quantthresh__44u2__p7_2[] = {
  142620. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  142621. 2.5, 3.5, 4.5, 5.5,
  142622. };
  142623. static long _vq_quantmap__44u2__p7_2[] = {
  142624. 11, 9, 7, 5, 3, 1, 0, 2,
  142625. 4, 6, 8, 10, 12,
  142626. };
  142627. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  142628. _vq_quantthresh__44u2__p7_2,
  142629. _vq_quantmap__44u2__p7_2,
  142630. 13,
  142631. 13
  142632. };
  142633. static static_codebook _44u2__p7_2 = {
  142634. 2, 169,
  142635. _vq_lengthlist__44u2__p7_2,
  142636. 1, -531103744, 1611661312, 4, 0,
  142637. _vq_quantlist__44u2__p7_2,
  142638. NULL,
  142639. &_vq_auxt__44u2__p7_2,
  142640. NULL,
  142641. 0
  142642. };
  142643. static long _huff_lengthlist__44u2__short[] = {
  142644. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  142645. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  142646. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  142647. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  142648. };
  142649. static static_codebook _huff_book__44u2__short = {
  142650. 2, 64,
  142651. _huff_lengthlist__44u2__short,
  142652. 0, 0, 0, 0, 0,
  142653. NULL,
  142654. NULL,
  142655. NULL,
  142656. NULL,
  142657. 0
  142658. };
  142659. static long _huff_lengthlist__44u3__long[] = {
  142660. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  142661. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  142662. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  142663. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  142664. };
  142665. static static_codebook _huff_book__44u3__long = {
  142666. 2, 64,
  142667. _huff_lengthlist__44u3__long,
  142668. 0, 0, 0, 0, 0,
  142669. NULL,
  142670. NULL,
  142671. NULL,
  142672. NULL,
  142673. 0
  142674. };
  142675. static long _vq_quantlist__44u3__p1_0[] = {
  142676. 1,
  142677. 0,
  142678. 2,
  142679. };
  142680. static long _vq_lengthlist__44u3__p1_0[] = {
  142681. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  142682. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142683. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  142684. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  142685. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  142686. 13,
  142687. };
  142688. static float _vq_quantthresh__44u3__p1_0[] = {
  142689. -0.5, 0.5,
  142690. };
  142691. static long _vq_quantmap__44u3__p1_0[] = {
  142692. 1, 0, 2,
  142693. };
  142694. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  142695. _vq_quantthresh__44u3__p1_0,
  142696. _vq_quantmap__44u3__p1_0,
  142697. 3,
  142698. 3
  142699. };
  142700. static static_codebook _44u3__p1_0 = {
  142701. 4, 81,
  142702. _vq_lengthlist__44u3__p1_0,
  142703. 1, -535822336, 1611661312, 2, 0,
  142704. _vq_quantlist__44u3__p1_0,
  142705. NULL,
  142706. &_vq_auxt__44u3__p1_0,
  142707. NULL,
  142708. 0
  142709. };
  142710. static long _vq_quantlist__44u3__p2_0[] = {
  142711. 1,
  142712. 0,
  142713. 2,
  142714. };
  142715. static long _vq_lengthlist__44u3__p2_0[] = {
  142716. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  142717. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  142718. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142719. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  142720. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  142721. 9,
  142722. };
  142723. static float _vq_quantthresh__44u3__p2_0[] = {
  142724. -0.5, 0.5,
  142725. };
  142726. static long _vq_quantmap__44u3__p2_0[] = {
  142727. 1, 0, 2,
  142728. };
  142729. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  142730. _vq_quantthresh__44u3__p2_0,
  142731. _vq_quantmap__44u3__p2_0,
  142732. 3,
  142733. 3
  142734. };
  142735. static static_codebook _44u3__p2_0 = {
  142736. 4, 81,
  142737. _vq_lengthlist__44u3__p2_0,
  142738. 1, -535822336, 1611661312, 2, 0,
  142739. _vq_quantlist__44u3__p2_0,
  142740. NULL,
  142741. &_vq_auxt__44u3__p2_0,
  142742. NULL,
  142743. 0
  142744. };
  142745. static long _vq_quantlist__44u3__p3_0[] = {
  142746. 2,
  142747. 1,
  142748. 3,
  142749. 0,
  142750. 4,
  142751. };
  142752. static long _vq_lengthlist__44u3__p3_0[] = {
  142753. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  142754. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  142755. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  142756. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  142757. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  142758. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  142759. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  142760. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  142761. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  142762. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  142763. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  142764. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  142765. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  142766. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  142767. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  142768. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  142769. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  142770. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  142771. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  142772. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  142773. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  142774. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  142775. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  142776. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  142777. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  142778. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  142779. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  142780. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  142781. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  142782. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  142783. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  142784. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  142785. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  142786. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  142787. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  142788. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  142789. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  142790. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  142791. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  142792. 0,
  142793. };
  142794. static float _vq_quantthresh__44u3__p3_0[] = {
  142795. -1.5, -0.5, 0.5, 1.5,
  142796. };
  142797. static long _vq_quantmap__44u3__p3_0[] = {
  142798. 3, 1, 0, 2, 4,
  142799. };
  142800. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  142801. _vq_quantthresh__44u3__p3_0,
  142802. _vq_quantmap__44u3__p3_0,
  142803. 5,
  142804. 5
  142805. };
  142806. static static_codebook _44u3__p3_0 = {
  142807. 4, 625,
  142808. _vq_lengthlist__44u3__p3_0,
  142809. 1, -533725184, 1611661312, 3, 0,
  142810. _vq_quantlist__44u3__p3_0,
  142811. NULL,
  142812. &_vq_auxt__44u3__p3_0,
  142813. NULL,
  142814. 0
  142815. };
  142816. static long _vq_quantlist__44u3__p4_0[] = {
  142817. 2,
  142818. 1,
  142819. 3,
  142820. 0,
  142821. 4,
  142822. };
  142823. static long _vq_lengthlist__44u3__p4_0[] = {
  142824. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  142825. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  142826. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  142827. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  142828. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  142829. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  142830. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  142831. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  142832. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  142833. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  142834. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  142835. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142836. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  142837. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  142838. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  142839. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  142840. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  142841. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  142842. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  142843. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  142844. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  142845. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  142846. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  142847. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  142848. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  142849. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  142850. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  142851. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  142852. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  142853. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  142854. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  142855. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  142856. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  142857. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  142858. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  142859. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  142860. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  142861. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  142862. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  142863. 13,
  142864. };
  142865. static float _vq_quantthresh__44u3__p4_0[] = {
  142866. -1.5, -0.5, 0.5, 1.5,
  142867. };
  142868. static long _vq_quantmap__44u3__p4_0[] = {
  142869. 3, 1, 0, 2, 4,
  142870. };
  142871. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  142872. _vq_quantthresh__44u3__p4_0,
  142873. _vq_quantmap__44u3__p4_0,
  142874. 5,
  142875. 5
  142876. };
  142877. static static_codebook _44u3__p4_0 = {
  142878. 4, 625,
  142879. _vq_lengthlist__44u3__p4_0,
  142880. 1, -533725184, 1611661312, 3, 0,
  142881. _vq_quantlist__44u3__p4_0,
  142882. NULL,
  142883. &_vq_auxt__44u3__p4_0,
  142884. NULL,
  142885. 0
  142886. };
  142887. static long _vq_quantlist__44u3__p5_0[] = {
  142888. 4,
  142889. 3,
  142890. 5,
  142891. 2,
  142892. 6,
  142893. 1,
  142894. 7,
  142895. 0,
  142896. 8,
  142897. };
  142898. static long _vq_lengthlist__44u3__p5_0[] = {
  142899. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  142900. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  142901. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  142902. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142903. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  142904. 12,
  142905. };
  142906. static float _vq_quantthresh__44u3__p5_0[] = {
  142907. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142908. };
  142909. static long _vq_quantmap__44u3__p5_0[] = {
  142910. 7, 5, 3, 1, 0, 2, 4, 6,
  142911. 8,
  142912. };
  142913. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  142914. _vq_quantthresh__44u3__p5_0,
  142915. _vq_quantmap__44u3__p5_0,
  142916. 9,
  142917. 9
  142918. };
  142919. static static_codebook _44u3__p5_0 = {
  142920. 2, 81,
  142921. _vq_lengthlist__44u3__p5_0,
  142922. 1, -531628032, 1611661312, 4, 0,
  142923. _vq_quantlist__44u3__p5_0,
  142924. NULL,
  142925. &_vq_auxt__44u3__p5_0,
  142926. NULL,
  142927. 0
  142928. };
  142929. static long _vq_quantlist__44u3__p6_0[] = {
  142930. 6,
  142931. 5,
  142932. 7,
  142933. 4,
  142934. 8,
  142935. 3,
  142936. 9,
  142937. 2,
  142938. 10,
  142939. 1,
  142940. 11,
  142941. 0,
  142942. 12,
  142943. };
  142944. static long _vq_lengthlist__44u3__p6_0[] = {
  142945. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  142946. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  142947. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142948. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  142949. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  142950. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  142951. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  142952. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  142953. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  142954. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  142955. 15,16,16,16,17,18,16,20,18,
  142956. };
  142957. static float _vq_quantthresh__44u3__p6_0[] = {
  142958. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142959. 12.5, 17.5, 22.5, 27.5,
  142960. };
  142961. static long _vq_quantmap__44u3__p6_0[] = {
  142962. 11, 9, 7, 5, 3, 1, 0, 2,
  142963. 4, 6, 8, 10, 12,
  142964. };
  142965. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  142966. _vq_quantthresh__44u3__p6_0,
  142967. _vq_quantmap__44u3__p6_0,
  142968. 13,
  142969. 13
  142970. };
  142971. static static_codebook _44u3__p6_0 = {
  142972. 2, 169,
  142973. _vq_lengthlist__44u3__p6_0,
  142974. 1, -526516224, 1616117760, 4, 0,
  142975. _vq_quantlist__44u3__p6_0,
  142976. NULL,
  142977. &_vq_auxt__44u3__p6_0,
  142978. NULL,
  142979. 0
  142980. };
  142981. static long _vq_quantlist__44u3__p6_1[] = {
  142982. 2,
  142983. 1,
  142984. 3,
  142985. 0,
  142986. 4,
  142987. };
  142988. static long _vq_lengthlist__44u3__p6_1[] = {
  142989. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  142990. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  142991. };
  142992. static float _vq_quantthresh__44u3__p6_1[] = {
  142993. -1.5, -0.5, 0.5, 1.5,
  142994. };
  142995. static long _vq_quantmap__44u3__p6_1[] = {
  142996. 3, 1, 0, 2, 4,
  142997. };
  142998. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  142999. _vq_quantthresh__44u3__p6_1,
  143000. _vq_quantmap__44u3__p6_1,
  143001. 5,
  143002. 5
  143003. };
  143004. static static_codebook _44u3__p6_1 = {
  143005. 2, 25,
  143006. _vq_lengthlist__44u3__p6_1,
  143007. 1, -533725184, 1611661312, 3, 0,
  143008. _vq_quantlist__44u3__p6_1,
  143009. NULL,
  143010. &_vq_auxt__44u3__p6_1,
  143011. NULL,
  143012. 0
  143013. };
  143014. static long _vq_quantlist__44u3__p7_0[] = {
  143015. 4,
  143016. 3,
  143017. 5,
  143018. 2,
  143019. 6,
  143020. 1,
  143021. 7,
  143022. 0,
  143023. 8,
  143024. };
  143025. static long _vq_lengthlist__44u3__p7_0[] = {
  143026. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  143027. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143028. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143029. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143030. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143031. 9,
  143032. };
  143033. static float _vq_quantthresh__44u3__p7_0[] = {
  143034. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  143035. };
  143036. static long _vq_quantmap__44u3__p7_0[] = {
  143037. 7, 5, 3, 1, 0, 2, 4, 6,
  143038. 8,
  143039. };
  143040. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  143041. _vq_quantthresh__44u3__p7_0,
  143042. _vq_quantmap__44u3__p7_0,
  143043. 9,
  143044. 9
  143045. };
  143046. static static_codebook _44u3__p7_0 = {
  143047. 2, 81,
  143048. _vq_lengthlist__44u3__p7_0,
  143049. 1, -515907584, 1627381760, 4, 0,
  143050. _vq_quantlist__44u3__p7_0,
  143051. NULL,
  143052. &_vq_auxt__44u3__p7_0,
  143053. NULL,
  143054. 0
  143055. };
  143056. static long _vq_quantlist__44u3__p7_1[] = {
  143057. 7,
  143058. 6,
  143059. 8,
  143060. 5,
  143061. 9,
  143062. 4,
  143063. 10,
  143064. 3,
  143065. 11,
  143066. 2,
  143067. 12,
  143068. 1,
  143069. 13,
  143070. 0,
  143071. 14,
  143072. };
  143073. static long _vq_lengthlist__44u3__p7_1[] = {
  143074. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  143075. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  143076. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  143077. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  143078. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  143079. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  143080. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  143081. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  143082. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  143083. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  143084. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  143085. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  143086. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  143087. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  143088. 17,
  143089. };
  143090. static float _vq_quantthresh__44u3__p7_1[] = {
  143091. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143092. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143093. };
  143094. static long _vq_quantmap__44u3__p7_1[] = {
  143095. 13, 11, 9, 7, 5, 3, 1, 0,
  143096. 2, 4, 6, 8, 10, 12, 14,
  143097. };
  143098. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  143099. _vq_quantthresh__44u3__p7_1,
  143100. _vq_quantmap__44u3__p7_1,
  143101. 15,
  143102. 15
  143103. };
  143104. static static_codebook _44u3__p7_1 = {
  143105. 2, 225,
  143106. _vq_lengthlist__44u3__p7_1,
  143107. 1, -522338304, 1620115456, 4, 0,
  143108. _vq_quantlist__44u3__p7_1,
  143109. NULL,
  143110. &_vq_auxt__44u3__p7_1,
  143111. NULL,
  143112. 0
  143113. };
  143114. static long _vq_quantlist__44u3__p7_2[] = {
  143115. 8,
  143116. 7,
  143117. 9,
  143118. 6,
  143119. 10,
  143120. 5,
  143121. 11,
  143122. 4,
  143123. 12,
  143124. 3,
  143125. 13,
  143126. 2,
  143127. 14,
  143128. 1,
  143129. 15,
  143130. 0,
  143131. 16,
  143132. };
  143133. static long _vq_lengthlist__44u3__p7_2[] = {
  143134. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143135. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143136. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  143137. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143138. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143139. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143140. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  143141. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143142. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  143143. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  143144. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  143145. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  143146. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  143147. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143148. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  143149. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  143150. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143151. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  143152. 11,
  143153. };
  143154. static float _vq_quantthresh__44u3__p7_2[] = {
  143155. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143156. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143157. };
  143158. static long _vq_quantmap__44u3__p7_2[] = {
  143159. 15, 13, 11, 9, 7, 5, 3, 1,
  143160. 0, 2, 4, 6, 8, 10, 12, 14,
  143161. 16,
  143162. };
  143163. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  143164. _vq_quantthresh__44u3__p7_2,
  143165. _vq_quantmap__44u3__p7_2,
  143166. 17,
  143167. 17
  143168. };
  143169. static static_codebook _44u3__p7_2 = {
  143170. 2, 289,
  143171. _vq_lengthlist__44u3__p7_2,
  143172. 1, -529530880, 1611661312, 5, 0,
  143173. _vq_quantlist__44u3__p7_2,
  143174. NULL,
  143175. &_vq_auxt__44u3__p7_2,
  143176. NULL,
  143177. 0
  143178. };
  143179. static long _huff_lengthlist__44u3__short[] = {
  143180. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  143181. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  143182. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  143183. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  143184. };
  143185. static static_codebook _huff_book__44u3__short = {
  143186. 2, 64,
  143187. _huff_lengthlist__44u3__short,
  143188. 0, 0, 0, 0, 0,
  143189. NULL,
  143190. NULL,
  143191. NULL,
  143192. NULL,
  143193. 0
  143194. };
  143195. static long _huff_lengthlist__44u4__long[] = {
  143196. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  143197. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  143198. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  143199. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  143200. };
  143201. static static_codebook _huff_book__44u4__long = {
  143202. 2, 64,
  143203. _huff_lengthlist__44u4__long,
  143204. 0, 0, 0, 0, 0,
  143205. NULL,
  143206. NULL,
  143207. NULL,
  143208. NULL,
  143209. 0
  143210. };
  143211. static long _vq_quantlist__44u4__p1_0[] = {
  143212. 1,
  143213. 0,
  143214. 2,
  143215. };
  143216. static long _vq_lengthlist__44u4__p1_0[] = {
  143217. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  143218. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143219. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  143220. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  143221. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  143222. 13,
  143223. };
  143224. static float _vq_quantthresh__44u4__p1_0[] = {
  143225. -0.5, 0.5,
  143226. };
  143227. static long _vq_quantmap__44u4__p1_0[] = {
  143228. 1, 0, 2,
  143229. };
  143230. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  143231. _vq_quantthresh__44u4__p1_0,
  143232. _vq_quantmap__44u4__p1_0,
  143233. 3,
  143234. 3
  143235. };
  143236. static static_codebook _44u4__p1_0 = {
  143237. 4, 81,
  143238. _vq_lengthlist__44u4__p1_0,
  143239. 1, -535822336, 1611661312, 2, 0,
  143240. _vq_quantlist__44u4__p1_0,
  143241. NULL,
  143242. &_vq_auxt__44u4__p1_0,
  143243. NULL,
  143244. 0
  143245. };
  143246. static long _vq_quantlist__44u4__p2_0[] = {
  143247. 1,
  143248. 0,
  143249. 2,
  143250. };
  143251. static long _vq_lengthlist__44u4__p2_0[] = {
  143252. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  143253. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  143254. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143255. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  143256. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  143257. 9,
  143258. };
  143259. static float _vq_quantthresh__44u4__p2_0[] = {
  143260. -0.5, 0.5,
  143261. };
  143262. static long _vq_quantmap__44u4__p2_0[] = {
  143263. 1, 0, 2,
  143264. };
  143265. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  143266. _vq_quantthresh__44u4__p2_0,
  143267. _vq_quantmap__44u4__p2_0,
  143268. 3,
  143269. 3
  143270. };
  143271. static static_codebook _44u4__p2_0 = {
  143272. 4, 81,
  143273. _vq_lengthlist__44u4__p2_0,
  143274. 1, -535822336, 1611661312, 2, 0,
  143275. _vq_quantlist__44u4__p2_0,
  143276. NULL,
  143277. &_vq_auxt__44u4__p2_0,
  143278. NULL,
  143279. 0
  143280. };
  143281. static long _vq_quantlist__44u4__p3_0[] = {
  143282. 2,
  143283. 1,
  143284. 3,
  143285. 0,
  143286. 4,
  143287. };
  143288. static long _vq_lengthlist__44u4__p3_0[] = {
  143289. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  143290. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  143291. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  143292. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  143293. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  143294. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  143295. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  143296. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  143297. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  143298. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  143299. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  143300. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  143301. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  143302. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  143303. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  143304. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  143305. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  143306. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  143307. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  143308. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  143309. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  143310. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  143311. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  143312. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  143313. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  143314. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  143315. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  143316. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  143317. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  143318. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  143319. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  143320. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  143321. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  143322. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  143323. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  143324. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  143325. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  143326. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  143327. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  143328. 0,
  143329. };
  143330. static float _vq_quantthresh__44u4__p3_0[] = {
  143331. -1.5, -0.5, 0.5, 1.5,
  143332. };
  143333. static long _vq_quantmap__44u4__p3_0[] = {
  143334. 3, 1, 0, 2, 4,
  143335. };
  143336. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  143337. _vq_quantthresh__44u4__p3_0,
  143338. _vq_quantmap__44u4__p3_0,
  143339. 5,
  143340. 5
  143341. };
  143342. static static_codebook _44u4__p3_0 = {
  143343. 4, 625,
  143344. _vq_lengthlist__44u4__p3_0,
  143345. 1, -533725184, 1611661312, 3, 0,
  143346. _vq_quantlist__44u4__p3_0,
  143347. NULL,
  143348. &_vq_auxt__44u4__p3_0,
  143349. NULL,
  143350. 0
  143351. };
  143352. static long _vq_quantlist__44u4__p4_0[] = {
  143353. 2,
  143354. 1,
  143355. 3,
  143356. 0,
  143357. 4,
  143358. };
  143359. static long _vq_lengthlist__44u4__p4_0[] = {
  143360. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  143361. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143362. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  143363. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  143364. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  143365. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  143366. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  143367. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  143368. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  143369. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  143370. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  143371. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143372. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  143373. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  143374. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  143375. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143376. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  143377. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143378. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  143379. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  143380. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  143381. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  143382. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  143383. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  143384. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  143385. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  143386. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  143387. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  143388. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  143389. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  143390. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  143391. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  143392. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  143393. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  143394. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  143395. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  143396. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  143397. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  143398. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  143399. 13,
  143400. };
  143401. static float _vq_quantthresh__44u4__p4_0[] = {
  143402. -1.5, -0.5, 0.5, 1.5,
  143403. };
  143404. static long _vq_quantmap__44u4__p4_0[] = {
  143405. 3, 1, 0, 2, 4,
  143406. };
  143407. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  143408. _vq_quantthresh__44u4__p4_0,
  143409. _vq_quantmap__44u4__p4_0,
  143410. 5,
  143411. 5
  143412. };
  143413. static static_codebook _44u4__p4_0 = {
  143414. 4, 625,
  143415. _vq_lengthlist__44u4__p4_0,
  143416. 1, -533725184, 1611661312, 3, 0,
  143417. _vq_quantlist__44u4__p4_0,
  143418. NULL,
  143419. &_vq_auxt__44u4__p4_0,
  143420. NULL,
  143421. 0
  143422. };
  143423. static long _vq_quantlist__44u4__p5_0[] = {
  143424. 4,
  143425. 3,
  143426. 5,
  143427. 2,
  143428. 6,
  143429. 1,
  143430. 7,
  143431. 0,
  143432. 8,
  143433. };
  143434. static long _vq_lengthlist__44u4__p5_0[] = {
  143435. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  143436. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  143437. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  143438. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143439. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  143440. 12,
  143441. };
  143442. static float _vq_quantthresh__44u4__p5_0[] = {
  143443. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143444. };
  143445. static long _vq_quantmap__44u4__p5_0[] = {
  143446. 7, 5, 3, 1, 0, 2, 4, 6,
  143447. 8,
  143448. };
  143449. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  143450. _vq_quantthresh__44u4__p5_0,
  143451. _vq_quantmap__44u4__p5_0,
  143452. 9,
  143453. 9
  143454. };
  143455. static static_codebook _44u4__p5_0 = {
  143456. 2, 81,
  143457. _vq_lengthlist__44u4__p5_0,
  143458. 1, -531628032, 1611661312, 4, 0,
  143459. _vq_quantlist__44u4__p5_0,
  143460. NULL,
  143461. &_vq_auxt__44u4__p5_0,
  143462. NULL,
  143463. 0
  143464. };
  143465. static long _vq_quantlist__44u4__p6_0[] = {
  143466. 6,
  143467. 5,
  143468. 7,
  143469. 4,
  143470. 8,
  143471. 3,
  143472. 9,
  143473. 2,
  143474. 10,
  143475. 1,
  143476. 11,
  143477. 0,
  143478. 12,
  143479. };
  143480. static long _vq_lengthlist__44u4__p6_0[] = {
  143481. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  143482. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  143483. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  143484. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  143485. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  143486. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  143487. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  143488. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  143489. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  143490. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  143491. 16,16,16,17,17,18,17,20,21,
  143492. };
  143493. static float _vq_quantthresh__44u4__p6_0[] = {
  143494. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143495. 12.5, 17.5, 22.5, 27.5,
  143496. };
  143497. static long _vq_quantmap__44u4__p6_0[] = {
  143498. 11, 9, 7, 5, 3, 1, 0, 2,
  143499. 4, 6, 8, 10, 12,
  143500. };
  143501. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  143502. _vq_quantthresh__44u4__p6_0,
  143503. _vq_quantmap__44u4__p6_0,
  143504. 13,
  143505. 13
  143506. };
  143507. static static_codebook _44u4__p6_0 = {
  143508. 2, 169,
  143509. _vq_lengthlist__44u4__p6_0,
  143510. 1, -526516224, 1616117760, 4, 0,
  143511. _vq_quantlist__44u4__p6_0,
  143512. NULL,
  143513. &_vq_auxt__44u4__p6_0,
  143514. NULL,
  143515. 0
  143516. };
  143517. static long _vq_quantlist__44u4__p6_1[] = {
  143518. 2,
  143519. 1,
  143520. 3,
  143521. 0,
  143522. 4,
  143523. };
  143524. static long _vq_lengthlist__44u4__p6_1[] = {
  143525. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  143526. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  143527. };
  143528. static float _vq_quantthresh__44u4__p6_1[] = {
  143529. -1.5, -0.5, 0.5, 1.5,
  143530. };
  143531. static long _vq_quantmap__44u4__p6_1[] = {
  143532. 3, 1, 0, 2, 4,
  143533. };
  143534. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  143535. _vq_quantthresh__44u4__p6_1,
  143536. _vq_quantmap__44u4__p6_1,
  143537. 5,
  143538. 5
  143539. };
  143540. static static_codebook _44u4__p6_1 = {
  143541. 2, 25,
  143542. _vq_lengthlist__44u4__p6_1,
  143543. 1, -533725184, 1611661312, 3, 0,
  143544. _vq_quantlist__44u4__p6_1,
  143545. NULL,
  143546. &_vq_auxt__44u4__p6_1,
  143547. NULL,
  143548. 0
  143549. };
  143550. static long _vq_quantlist__44u4__p7_0[] = {
  143551. 6,
  143552. 5,
  143553. 7,
  143554. 4,
  143555. 8,
  143556. 3,
  143557. 9,
  143558. 2,
  143559. 10,
  143560. 1,
  143561. 11,
  143562. 0,
  143563. 12,
  143564. };
  143565. static long _vq_lengthlist__44u4__p7_0[] = {
  143566. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  143567. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  143568. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143569. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143570. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143571. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143572. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143573. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143574. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143575. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143576. 11,11,11,11,11,11,11,11,11,
  143577. };
  143578. static float _vq_quantthresh__44u4__p7_0[] = {
  143579. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  143580. 637.5, 892.5, 1147.5, 1402.5,
  143581. };
  143582. static long _vq_quantmap__44u4__p7_0[] = {
  143583. 11, 9, 7, 5, 3, 1, 0, 2,
  143584. 4, 6, 8, 10, 12,
  143585. };
  143586. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  143587. _vq_quantthresh__44u4__p7_0,
  143588. _vq_quantmap__44u4__p7_0,
  143589. 13,
  143590. 13
  143591. };
  143592. static static_codebook _44u4__p7_0 = {
  143593. 2, 169,
  143594. _vq_lengthlist__44u4__p7_0,
  143595. 1, -514332672, 1627381760, 4, 0,
  143596. _vq_quantlist__44u4__p7_0,
  143597. NULL,
  143598. &_vq_auxt__44u4__p7_0,
  143599. NULL,
  143600. 0
  143601. };
  143602. static long _vq_quantlist__44u4__p7_1[] = {
  143603. 7,
  143604. 6,
  143605. 8,
  143606. 5,
  143607. 9,
  143608. 4,
  143609. 10,
  143610. 3,
  143611. 11,
  143612. 2,
  143613. 12,
  143614. 1,
  143615. 13,
  143616. 0,
  143617. 14,
  143618. };
  143619. static long _vq_lengthlist__44u4__p7_1[] = {
  143620. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  143621. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  143622. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  143623. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  143624. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  143625. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  143626. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  143627. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  143628. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  143629. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  143630. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  143631. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  143632. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  143633. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  143634. 16,
  143635. };
  143636. static float _vq_quantthresh__44u4__p7_1[] = {
  143637. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143638. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143639. };
  143640. static long _vq_quantmap__44u4__p7_1[] = {
  143641. 13, 11, 9, 7, 5, 3, 1, 0,
  143642. 2, 4, 6, 8, 10, 12, 14,
  143643. };
  143644. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  143645. _vq_quantthresh__44u4__p7_1,
  143646. _vq_quantmap__44u4__p7_1,
  143647. 15,
  143648. 15
  143649. };
  143650. static static_codebook _44u4__p7_1 = {
  143651. 2, 225,
  143652. _vq_lengthlist__44u4__p7_1,
  143653. 1, -522338304, 1620115456, 4, 0,
  143654. _vq_quantlist__44u4__p7_1,
  143655. NULL,
  143656. &_vq_auxt__44u4__p7_1,
  143657. NULL,
  143658. 0
  143659. };
  143660. static long _vq_quantlist__44u4__p7_2[] = {
  143661. 8,
  143662. 7,
  143663. 9,
  143664. 6,
  143665. 10,
  143666. 5,
  143667. 11,
  143668. 4,
  143669. 12,
  143670. 3,
  143671. 13,
  143672. 2,
  143673. 14,
  143674. 1,
  143675. 15,
  143676. 0,
  143677. 16,
  143678. };
  143679. static long _vq_lengthlist__44u4__p7_2[] = {
  143680. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143681. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143682. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143683. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143684. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143685. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143686. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143687. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  143688. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  143689. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  143690. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  143691. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  143692. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  143693. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  143694. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  143695. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  143696. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143697. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  143698. 10,
  143699. };
  143700. static float _vq_quantthresh__44u4__p7_2[] = {
  143701. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143702. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143703. };
  143704. static long _vq_quantmap__44u4__p7_2[] = {
  143705. 15, 13, 11, 9, 7, 5, 3, 1,
  143706. 0, 2, 4, 6, 8, 10, 12, 14,
  143707. 16,
  143708. };
  143709. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  143710. _vq_quantthresh__44u4__p7_2,
  143711. _vq_quantmap__44u4__p7_2,
  143712. 17,
  143713. 17
  143714. };
  143715. static static_codebook _44u4__p7_2 = {
  143716. 2, 289,
  143717. _vq_lengthlist__44u4__p7_2,
  143718. 1, -529530880, 1611661312, 5, 0,
  143719. _vq_quantlist__44u4__p7_2,
  143720. NULL,
  143721. &_vq_auxt__44u4__p7_2,
  143722. NULL,
  143723. 0
  143724. };
  143725. static long _huff_lengthlist__44u4__short[] = {
  143726. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  143727. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  143728. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  143729. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  143730. };
  143731. static static_codebook _huff_book__44u4__short = {
  143732. 2, 64,
  143733. _huff_lengthlist__44u4__short,
  143734. 0, 0, 0, 0, 0,
  143735. NULL,
  143736. NULL,
  143737. NULL,
  143738. NULL,
  143739. 0
  143740. };
  143741. static long _huff_lengthlist__44u5__long[] = {
  143742. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  143743. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  143744. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  143745. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  143746. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  143747. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  143748. 14, 8, 7, 8,
  143749. };
  143750. static static_codebook _huff_book__44u5__long = {
  143751. 2, 100,
  143752. _huff_lengthlist__44u5__long,
  143753. 0, 0, 0, 0, 0,
  143754. NULL,
  143755. NULL,
  143756. NULL,
  143757. NULL,
  143758. 0
  143759. };
  143760. static long _vq_quantlist__44u5__p1_0[] = {
  143761. 1,
  143762. 0,
  143763. 2,
  143764. };
  143765. static long _vq_lengthlist__44u5__p1_0[] = {
  143766. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  143767. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  143768. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  143769. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  143770. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  143771. 12,
  143772. };
  143773. static float _vq_quantthresh__44u5__p1_0[] = {
  143774. -0.5, 0.5,
  143775. };
  143776. static long _vq_quantmap__44u5__p1_0[] = {
  143777. 1, 0, 2,
  143778. };
  143779. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  143780. _vq_quantthresh__44u5__p1_0,
  143781. _vq_quantmap__44u5__p1_0,
  143782. 3,
  143783. 3
  143784. };
  143785. static static_codebook _44u5__p1_0 = {
  143786. 4, 81,
  143787. _vq_lengthlist__44u5__p1_0,
  143788. 1, -535822336, 1611661312, 2, 0,
  143789. _vq_quantlist__44u5__p1_0,
  143790. NULL,
  143791. &_vq_auxt__44u5__p1_0,
  143792. NULL,
  143793. 0
  143794. };
  143795. static long _vq_quantlist__44u5__p2_0[] = {
  143796. 1,
  143797. 0,
  143798. 2,
  143799. };
  143800. static long _vq_lengthlist__44u5__p2_0[] = {
  143801. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  143802. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  143803. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  143804. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  143805. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  143806. 9,
  143807. };
  143808. static float _vq_quantthresh__44u5__p2_0[] = {
  143809. -0.5, 0.5,
  143810. };
  143811. static long _vq_quantmap__44u5__p2_0[] = {
  143812. 1, 0, 2,
  143813. };
  143814. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  143815. _vq_quantthresh__44u5__p2_0,
  143816. _vq_quantmap__44u5__p2_0,
  143817. 3,
  143818. 3
  143819. };
  143820. static static_codebook _44u5__p2_0 = {
  143821. 4, 81,
  143822. _vq_lengthlist__44u5__p2_0,
  143823. 1, -535822336, 1611661312, 2, 0,
  143824. _vq_quantlist__44u5__p2_0,
  143825. NULL,
  143826. &_vq_auxt__44u5__p2_0,
  143827. NULL,
  143828. 0
  143829. };
  143830. static long _vq_quantlist__44u5__p3_0[] = {
  143831. 2,
  143832. 1,
  143833. 3,
  143834. 0,
  143835. 4,
  143836. };
  143837. static long _vq_lengthlist__44u5__p3_0[] = {
  143838. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  143839. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  143840. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  143841. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  143842. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  143843. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  143844. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  143845. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  143846. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  143847. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  143848. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  143849. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  143850. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  143851. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  143852. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  143853. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  143854. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  143855. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  143856. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  143857. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  143858. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  143859. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  143860. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  143861. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  143862. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  143863. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  143864. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  143865. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  143866. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  143867. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  143868. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  143869. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  143870. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  143871. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  143872. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  143873. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  143874. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  143875. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  143876. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  143877. 0,
  143878. };
  143879. static float _vq_quantthresh__44u5__p3_0[] = {
  143880. -1.5, -0.5, 0.5, 1.5,
  143881. };
  143882. static long _vq_quantmap__44u5__p3_0[] = {
  143883. 3, 1, 0, 2, 4,
  143884. };
  143885. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  143886. _vq_quantthresh__44u5__p3_0,
  143887. _vq_quantmap__44u5__p3_0,
  143888. 5,
  143889. 5
  143890. };
  143891. static static_codebook _44u5__p3_0 = {
  143892. 4, 625,
  143893. _vq_lengthlist__44u5__p3_0,
  143894. 1, -533725184, 1611661312, 3, 0,
  143895. _vq_quantlist__44u5__p3_0,
  143896. NULL,
  143897. &_vq_auxt__44u5__p3_0,
  143898. NULL,
  143899. 0
  143900. };
  143901. static long _vq_quantlist__44u5__p4_0[] = {
  143902. 2,
  143903. 1,
  143904. 3,
  143905. 0,
  143906. 4,
  143907. };
  143908. static long _vq_lengthlist__44u5__p4_0[] = {
  143909. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  143910. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  143911. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  143912. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  143913. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  143914. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  143915. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  143916. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  143917. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  143918. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  143919. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  143920. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143921. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  143922. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  143923. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  143924. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  143925. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  143926. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143927. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  143928. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  143929. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  143930. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  143931. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  143932. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  143933. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  143934. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  143935. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  143936. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  143937. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  143938. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  143939. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  143940. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  143941. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  143942. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  143943. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  143944. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  143945. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  143946. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  143947. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  143948. 12,
  143949. };
  143950. static float _vq_quantthresh__44u5__p4_0[] = {
  143951. -1.5, -0.5, 0.5, 1.5,
  143952. };
  143953. static long _vq_quantmap__44u5__p4_0[] = {
  143954. 3, 1, 0, 2, 4,
  143955. };
  143956. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  143957. _vq_quantthresh__44u5__p4_0,
  143958. _vq_quantmap__44u5__p4_0,
  143959. 5,
  143960. 5
  143961. };
  143962. static static_codebook _44u5__p4_0 = {
  143963. 4, 625,
  143964. _vq_lengthlist__44u5__p4_0,
  143965. 1, -533725184, 1611661312, 3, 0,
  143966. _vq_quantlist__44u5__p4_0,
  143967. NULL,
  143968. &_vq_auxt__44u5__p4_0,
  143969. NULL,
  143970. 0
  143971. };
  143972. static long _vq_quantlist__44u5__p5_0[] = {
  143973. 4,
  143974. 3,
  143975. 5,
  143976. 2,
  143977. 6,
  143978. 1,
  143979. 7,
  143980. 0,
  143981. 8,
  143982. };
  143983. static long _vq_lengthlist__44u5__p5_0[] = {
  143984. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  143985. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  143986. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  143987. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  143988. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  143989. 14,
  143990. };
  143991. static float _vq_quantthresh__44u5__p5_0[] = {
  143992. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143993. };
  143994. static long _vq_quantmap__44u5__p5_0[] = {
  143995. 7, 5, 3, 1, 0, 2, 4, 6,
  143996. 8,
  143997. };
  143998. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  143999. _vq_quantthresh__44u5__p5_0,
  144000. _vq_quantmap__44u5__p5_0,
  144001. 9,
  144002. 9
  144003. };
  144004. static static_codebook _44u5__p5_0 = {
  144005. 2, 81,
  144006. _vq_lengthlist__44u5__p5_0,
  144007. 1, -531628032, 1611661312, 4, 0,
  144008. _vq_quantlist__44u5__p5_0,
  144009. NULL,
  144010. &_vq_auxt__44u5__p5_0,
  144011. NULL,
  144012. 0
  144013. };
  144014. static long _vq_quantlist__44u5__p6_0[] = {
  144015. 4,
  144016. 3,
  144017. 5,
  144018. 2,
  144019. 6,
  144020. 1,
  144021. 7,
  144022. 0,
  144023. 8,
  144024. };
  144025. static long _vq_lengthlist__44u5__p6_0[] = {
  144026. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  144027. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  144028. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  144029. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  144030. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  144031. 11,
  144032. };
  144033. static float _vq_quantthresh__44u5__p6_0[] = {
  144034. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144035. };
  144036. static long _vq_quantmap__44u5__p6_0[] = {
  144037. 7, 5, 3, 1, 0, 2, 4, 6,
  144038. 8,
  144039. };
  144040. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  144041. _vq_quantthresh__44u5__p6_0,
  144042. _vq_quantmap__44u5__p6_0,
  144043. 9,
  144044. 9
  144045. };
  144046. static static_codebook _44u5__p6_0 = {
  144047. 2, 81,
  144048. _vq_lengthlist__44u5__p6_0,
  144049. 1, -531628032, 1611661312, 4, 0,
  144050. _vq_quantlist__44u5__p6_0,
  144051. NULL,
  144052. &_vq_auxt__44u5__p6_0,
  144053. NULL,
  144054. 0
  144055. };
  144056. static long _vq_quantlist__44u5__p7_0[] = {
  144057. 1,
  144058. 0,
  144059. 2,
  144060. };
  144061. static long _vq_lengthlist__44u5__p7_0[] = {
  144062. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  144063. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  144064. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  144065. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  144066. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  144067. 12,
  144068. };
  144069. static float _vq_quantthresh__44u5__p7_0[] = {
  144070. -5.5, 5.5,
  144071. };
  144072. static long _vq_quantmap__44u5__p7_0[] = {
  144073. 1, 0, 2,
  144074. };
  144075. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  144076. _vq_quantthresh__44u5__p7_0,
  144077. _vq_quantmap__44u5__p7_0,
  144078. 3,
  144079. 3
  144080. };
  144081. static static_codebook _44u5__p7_0 = {
  144082. 4, 81,
  144083. _vq_lengthlist__44u5__p7_0,
  144084. 1, -529137664, 1618345984, 2, 0,
  144085. _vq_quantlist__44u5__p7_0,
  144086. NULL,
  144087. &_vq_auxt__44u5__p7_0,
  144088. NULL,
  144089. 0
  144090. };
  144091. static long _vq_quantlist__44u5__p7_1[] = {
  144092. 5,
  144093. 4,
  144094. 6,
  144095. 3,
  144096. 7,
  144097. 2,
  144098. 8,
  144099. 1,
  144100. 9,
  144101. 0,
  144102. 10,
  144103. };
  144104. static long _vq_lengthlist__44u5__p7_1[] = {
  144105. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  144106. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  144107. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144108. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  144109. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  144110. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  144111. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  144112. 9, 9, 9, 9, 9,10,10,10,10,
  144113. };
  144114. static float _vq_quantthresh__44u5__p7_1[] = {
  144115. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144116. 3.5, 4.5,
  144117. };
  144118. static long _vq_quantmap__44u5__p7_1[] = {
  144119. 9, 7, 5, 3, 1, 0, 2, 4,
  144120. 6, 8, 10,
  144121. };
  144122. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  144123. _vq_quantthresh__44u5__p7_1,
  144124. _vq_quantmap__44u5__p7_1,
  144125. 11,
  144126. 11
  144127. };
  144128. static static_codebook _44u5__p7_1 = {
  144129. 2, 121,
  144130. _vq_lengthlist__44u5__p7_1,
  144131. 1, -531365888, 1611661312, 4, 0,
  144132. _vq_quantlist__44u5__p7_1,
  144133. NULL,
  144134. &_vq_auxt__44u5__p7_1,
  144135. NULL,
  144136. 0
  144137. };
  144138. static long _vq_quantlist__44u5__p8_0[] = {
  144139. 5,
  144140. 4,
  144141. 6,
  144142. 3,
  144143. 7,
  144144. 2,
  144145. 8,
  144146. 1,
  144147. 9,
  144148. 0,
  144149. 10,
  144150. };
  144151. static long _vq_lengthlist__44u5__p8_0[] = {
  144152. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  144153. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  144154. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  144155. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  144156. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  144157. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  144158. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  144159. 12,13,13,14,14,14,14,15,15,
  144160. };
  144161. static float _vq_quantthresh__44u5__p8_0[] = {
  144162. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144163. 38.5, 49.5,
  144164. };
  144165. static long _vq_quantmap__44u5__p8_0[] = {
  144166. 9, 7, 5, 3, 1, 0, 2, 4,
  144167. 6, 8, 10,
  144168. };
  144169. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  144170. _vq_quantthresh__44u5__p8_0,
  144171. _vq_quantmap__44u5__p8_0,
  144172. 11,
  144173. 11
  144174. };
  144175. static static_codebook _44u5__p8_0 = {
  144176. 2, 121,
  144177. _vq_lengthlist__44u5__p8_0,
  144178. 1, -524582912, 1618345984, 4, 0,
  144179. _vq_quantlist__44u5__p8_0,
  144180. NULL,
  144181. &_vq_auxt__44u5__p8_0,
  144182. NULL,
  144183. 0
  144184. };
  144185. static long _vq_quantlist__44u5__p8_1[] = {
  144186. 5,
  144187. 4,
  144188. 6,
  144189. 3,
  144190. 7,
  144191. 2,
  144192. 8,
  144193. 1,
  144194. 9,
  144195. 0,
  144196. 10,
  144197. };
  144198. static long _vq_lengthlist__44u5__p8_1[] = {
  144199. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  144200. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  144201. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  144202. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  144203. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  144204. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  144205. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144206. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144207. };
  144208. static float _vq_quantthresh__44u5__p8_1[] = {
  144209. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144210. 3.5, 4.5,
  144211. };
  144212. static long _vq_quantmap__44u5__p8_1[] = {
  144213. 9, 7, 5, 3, 1, 0, 2, 4,
  144214. 6, 8, 10,
  144215. };
  144216. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  144217. _vq_quantthresh__44u5__p8_1,
  144218. _vq_quantmap__44u5__p8_1,
  144219. 11,
  144220. 11
  144221. };
  144222. static static_codebook _44u5__p8_1 = {
  144223. 2, 121,
  144224. _vq_lengthlist__44u5__p8_1,
  144225. 1, -531365888, 1611661312, 4, 0,
  144226. _vq_quantlist__44u5__p8_1,
  144227. NULL,
  144228. &_vq_auxt__44u5__p8_1,
  144229. NULL,
  144230. 0
  144231. };
  144232. static long _vq_quantlist__44u5__p9_0[] = {
  144233. 6,
  144234. 5,
  144235. 7,
  144236. 4,
  144237. 8,
  144238. 3,
  144239. 9,
  144240. 2,
  144241. 10,
  144242. 1,
  144243. 11,
  144244. 0,
  144245. 12,
  144246. };
  144247. static long _vq_lengthlist__44u5__p9_0[] = {
  144248. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  144249. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  144250. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  144251. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  144252. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144253. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144254. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144255. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144256. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  144257. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144258. 12,12,12,12,12,12,12,12,12,
  144259. };
  144260. static float _vq_quantthresh__44u5__p9_0[] = {
  144261. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  144262. 637.5, 892.5, 1147.5, 1402.5,
  144263. };
  144264. static long _vq_quantmap__44u5__p9_0[] = {
  144265. 11, 9, 7, 5, 3, 1, 0, 2,
  144266. 4, 6, 8, 10, 12,
  144267. };
  144268. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  144269. _vq_quantthresh__44u5__p9_0,
  144270. _vq_quantmap__44u5__p9_0,
  144271. 13,
  144272. 13
  144273. };
  144274. static static_codebook _44u5__p9_0 = {
  144275. 2, 169,
  144276. _vq_lengthlist__44u5__p9_0,
  144277. 1, -514332672, 1627381760, 4, 0,
  144278. _vq_quantlist__44u5__p9_0,
  144279. NULL,
  144280. &_vq_auxt__44u5__p9_0,
  144281. NULL,
  144282. 0
  144283. };
  144284. static long _vq_quantlist__44u5__p9_1[] = {
  144285. 7,
  144286. 6,
  144287. 8,
  144288. 5,
  144289. 9,
  144290. 4,
  144291. 10,
  144292. 3,
  144293. 11,
  144294. 2,
  144295. 12,
  144296. 1,
  144297. 13,
  144298. 0,
  144299. 14,
  144300. };
  144301. static long _vq_lengthlist__44u5__p9_1[] = {
  144302. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  144303. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  144304. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  144305. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  144306. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  144307. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  144308. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  144309. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  144310. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  144311. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  144312. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  144313. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  144314. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  144315. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  144316. 14,
  144317. };
  144318. static float _vq_quantthresh__44u5__p9_1[] = {
  144319. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144320. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144321. };
  144322. static long _vq_quantmap__44u5__p9_1[] = {
  144323. 13, 11, 9, 7, 5, 3, 1, 0,
  144324. 2, 4, 6, 8, 10, 12, 14,
  144325. };
  144326. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  144327. _vq_quantthresh__44u5__p9_1,
  144328. _vq_quantmap__44u5__p9_1,
  144329. 15,
  144330. 15
  144331. };
  144332. static static_codebook _44u5__p9_1 = {
  144333. 2, 225,
  144334. _vq_lengthlist__44u5__p9_1,
  144335. 1, -522338304, 1620115456, 4, 0,
  144336. _vq_quantlist__44u5__p9_1,
  144337. NULL,
  144338. &_vq_auxt__44u5__p9_1,
  144339. NULL,
  144340. 0
  144341. };
  144342. static long _vq_quantlist__44u5__p9_2[] = {
  144343. 8,
  144344. 7,
  144345. 9,
  144346. 6,
  144347. 10,
  144348. 5,
  144349. 11,
  144350. 4,
  144351. 12,
  144352. 3,
  144353. 13,
  144354. 2,
  144355. 14,
  144356. 1,
  144357. 15,
  144358. 0,
  144359. 16,
  144360. };
  144361. static long _vq_lengthlist__44u5__p9_2[] = {
  144362. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144363. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  144364. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  144365. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  144366. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  144367. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  144368. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  144369. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  144370. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  144371. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  144372. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  144373. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  144374. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  144375. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  144376. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  144377. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  144378. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144379. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  144380. 10,
  144381. };
  144382. static float _vq_quantthresh__44u5__p9_2[] = {
  144383. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144384. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144385. };
  144386. static long _vq_quantmap__44u5__p9_2[] = {
  144387. 15, 13, 11, 9, 7, 5, 3, 1,
  144388. 0, 2, 4, 6, 8, 10, 12, 14,
  144389. 16,
  144390. };
  144391. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  144392. _vq_quantthresh__44u5__p9_2,
  144393. _vq_quantmap__44u5__p9_2,
  144394. 17,
  144395. 17
  144396. };
  144397. static static_codebook _44u5__p9_2 = {
  144398. 2, 289,
  144399. _vq_lengthlist__44u5__p9_2,
  144400. 1, -529530880, 1611661312, 5, 0,
  144401. _vq_quantlist__44u5__p9_2,
  144402. NULL,
  144403. &_vq_auxt__44u5__p9_2,
  144404. NULL,
  144405. 0
  144406. };
  144407. static long _huff_lengthlist__44u5__short[] = {
  144408. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  144409. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  144410. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  144411. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  144412. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  144413. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  144414. 6, 8,15,17,
  144415. };
  144416. static static_codebook _huff_book__44u5__short = {
  144417. 2, 100,
  144418. _huff_lengthlist__44u5__short,
  144419. 0, 0, 0, 0, 0,
  144420. NULL,
  144421. NULL,
  144422. NULL,
  144423. NULL,
  144424. 0
  144425. };
  144426. static long _huff_lengthlist__44u6__long[] = {
  144427. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  144428. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  144429. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  144430. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  144431. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  144432. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  144433. 13, 8, 7, 7,
  144434. };
  144435. static static_codebook _huff_book__44u6__long = {
  144436. 2, 100,
  144437. _huff_lengthlist__44u6__long,
  144438. 0, 0, 0, 0, 0,
  144439. NULL,
  144440. NULL,
  144441. NULL,
  144442. NULL,
  144443. 0
  144444. };
  144445. static long _vq_quantlist__44u6__p1_0[] = {
  144446. 1,
  144447. 0,
  144448. 2,
  144449. };
  144450. static long _vq_lengthlist__44u6__p1_0[] = {
  144451. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144452. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  144453. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  144454. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  144455. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  144456. 12,
  144457. };
  144458. static float _vq_quantthresh__44u6__p1_0[] = {
  144459. -0.5, 0.5,
  144460. };
  144461. static long _vq_quantmap__44u6__p1_0[] = {
  144462. 1, 0, 2,
  144463. };
  144464. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  144465. _vq_quantthresh__44u6__p1_0,
  144466. _vq_quantmap__44u6__p1_0,
  144467. 3,
  144468. 3
  144469. };
  144470. static static_codebook _44u6__p1_0 = {
  144471. 4, 81,
  144472. _vq_lengthlist__44u6__p1_0,
  144473. 1, -535822336, 1611661312, 2, 0,
  144474. _vq_quantlist__44u6__p1_0,
  144475. NULL,
  144476. &_vq_auxt__44u6__p1_0,
  144477. NULL,
  144478. 0
  144479. };
  144480. static long _vq_quantlist__44u6__p2_0[] = {
  144481. 1,
  144482. 0,
  144483. 2,
  144484. };
  144485. static long _vq_lengthlist__44u6__p2_0[] = {
  144486. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  144487. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  144488. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  144489. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  144490. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  144491. 9,
  144492. };
  144493. static float _vq_quantthresh__44u6__p2_0[] = {
  144494. -0.5, 0.5,
  144495. };
  144496. static long _vq_quantmap__44u6__p2_0[] = {
  144497. 1, 0, 2,
  144498. };
  144499. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  144500. _vq_quantthresh__44u6__p2_0,
  144501. _vq_quantmap__44u6__p2_0,
  144502. 3,
  144503. 3
  144504. };
  144505. static static_codebook _44u6__p2_0 = {
  144506. 4, 81,
  144507. _vq_lengthlist__44u6__p2_0,
  144508. 1, -535822336, 1611661312, 2, 0,
  144509. _vq_quantlist__44u6__p2_0,
  144510. NULL,
  144511. &_vq_auxt__44u6__p2_0,
  144512. NULL,
  144513. 0
  144514. };
  144515. static long _vq_quantlist__44u6__p3_0[] = {
  144516. 2,
  144517. 1,
  144518. 3,
  144519. 0,
  144520. 4,
  144521. };
  144522. static long _vq_lengthlist__44u6__p3_0[] = {
  144523. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  144524. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  144525. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  144526. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  144527. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  144528. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  144529. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  144530. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  144531. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  144532. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  144533. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  144534. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  144535. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  144536. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  144537. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  144538. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  144539. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  144540. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  144541. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  144542. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  144543. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  144544. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  144545. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  144546. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  144547. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  144548. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  144549. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  144550. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  144551. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  144552. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  144553. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  144554. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  144555. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  144556. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  144557. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  144558. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  144559. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  144560. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  144561. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  144562. 19,
  144563. };
  144564. static float _vq_quantthresh__44u6__p3_0[] = {
  144565. -1.5, -0.5, 0.5, 1.5,
  144566. };
  144567. static long _vq_quantmap__44u6__p3_0[] = {
  144568. 3, 1, 0, 2, 4,
  144569. };
  144570. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  144571. _vq_quantthresh__44u6__p3_0,
  144572. _vq_quantmap__44u6__p3_0,
  144573. 5,
  144574. 5
  144575. };
  144576. static static_codebook _44u6__p3_0 = {
  144577. 4, 625,
  144578. _vq_lengthlist__44u6__p3_0,
  144579. 1, -533725184, 1611661312, 3, 0,
  144580. _vq_quantlist__44u6__p3_0,
  144581. NULL,
  144582. &_vq_auxt__44u6__p3_0,
  144583. NULL,
  144584. 0
  144585. };
  144586. static long _vq_quantlist__44u6__p4_0[] = {
  144587. 2,
  144588. 1,
  144589. 3,
  144590. 0,
  144591. 4,
  144592. };
  144593. static long _vq_lengthlist__44u6__p4_0[] = {
  144594. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  144595. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  144596. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  144597. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  144598. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  144599. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  144600. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  144601. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  144602. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  144603. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  144604. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  144605. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  144606. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  144607. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  144608. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  144609. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  144610. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  144611. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  144612. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  144613. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  144614. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  144615. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  144616. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  144617. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  144618. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  144619. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  144620. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  144621. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  144622. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  144623. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  144624. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  144625. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  144626. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  144627. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  144628. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  144629. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  144630. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  144631. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  144632. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  144633. 13,
  144634. };
  144635. static float _vq_quantthresh__44u6__p4_0[] = {
  144636. -1.5, -0.5, 0.5, 1.5,
  144637. };
  144638. static long _vq_quantmap__44u6__p4_0[] = {
  144639. 3, 1, 0, 2, 4,
  144640. };
  144641. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  144642. _vq_quantthresh__44u6__p4_0,
  144643. _vq_quantmap__44u6__p4_0,
  144644. 5,
  144645. 5
  144646. };
  144647. static static_codebook _44u6__p4_0 = {
  144648. 4, 625,
  144649. _vq_lengthlist__44u6__p4_0,
  144650. 1, -533725184, 1611661312, 3, 0,
  144651. _vq_quantlist__44u6__p4_0,
  144652. NULL,
  144653. &_vq_auxt__44u6__p4_0,
  144654. NULL,
  144655. 0
  144656. };
  144657. static long _vq_quantlist__44u6__p5_0[] = {
  144658. 4,
  144659. 3,
  144660. 5,
  144661. 2,
  144662. 6,
  144663. 1,
  144664. 7,
  144665. 0,
  144666. 8,
  144667. };
  144668. static long _vq_lengthlist__44u6__p5_0[] = {
  144669. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  144670. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  144671. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  144672. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  144673. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  144674. 14,
  144675. };
  144676. static float _vq_quantthresh__44u6__p5_0[] = {
  144677. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144678. };
  144679. static long _vq_quantmap__44u6__p5_0[] = {
  144680. 7, 5, 3, 1, 0, 2, 4, 6,
  144681. 8,
  144682. };
  144683. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  144684. _vq_quantthresh__44u6__p5_0,
  144685. _vq_quantmap__44u6__p5_0,
  144686. 9,
  144687. 9
  144688. };
  144689. static static_codebook _44u6__p5_0 = {
  144690. 2, 81,
  144691. _vq_lengthlist__44u6__p5_0,
  144692. 1, -531628032, 1611661312, 4, 0,
  144693. _vq_quantlist__44u6__p5_0,
  144694. NULL,
  144695. &_vq_auxt__44u6__p5_0,
  144696. NULL,
  144697. 0
  144698. };
  144699. static long _vq_quantlist__44u6__p6_0[] = {
  144700. 4,
  144701. 3,
  144702. 5,
  144703. 2,
  144704. 6,
  144705. 1,
  144706. 7,
  144707. 0,
  144708. 8,
  144709. };
  144710. static long _vq_lengthlist__44u6__p6_0[] = {
  144711. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  144712. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  144713. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  144714. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  144715. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  144716. 12,
  144717. };
  144718. static float _vq_quantthresh__44u6__p6_0[] = {
  144719. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144720. };
  144721. static long _vq_quantmap__44u6__p6_0[] = {
  144722. 7, 5, 3, 1, 0, 2, 4, 6,
  144723. 8,
  144724. };
  144725. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  144726. _vq_quantthresh__44u6__p6_0,
  144727. _vq_quantmap__44u6__p6_0,
  144728. 9,
  144729. 9
  144730. };
  144731. static static_codebook _44u6__p6_0 = {
  144732. 2, 81,
  144733. _vq_lengthlist__44u6__p6_0,
  144734. 1, -531628032, 1611661312, 4, 0,
  144735. _vq_quantlist__44u6__p6_0,
  144736. NULL,
  144737. &_vq_auxt__44u6__p6_0,
  144738. NULL,
  144739. 0
  144740. };
  144741. static long _vq_quantlist__44u6__p7_0[] = {
  144742. 1,
  144743. 0,
  144744. 2,
  144745. };
  144746. static long _vq_lengthlist__44u6__p7_0[] = {
  144747. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  144748. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  144749. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  144750. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  144751. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  144752. 10,
  144753. };
  144754. static float _vq_quantthresh__44u6__p7_0[] = {
  144755. -5.5, 5.5,
  144756. };
  144757. static long _vq_quantmap__44u6__p7_0[] = {
  144758. 1, 0, 2,
  144759. };
  144760. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  144761. _vq_quantthresh__44u6__p7_0,
  144762. _vq_quantmap__44u6__p7_0,
  144763. 3,
  144764. 3
  144765. };
  144766. static static_codebook _44u6__p7_0 = {
  144767. 4, 81,
  144768. _vq_lengthlist__44u6__p7_0,
  144769. 1, -529137664, 1618345984, 2, 0,
  144770. _vq_quantlist__44u6__p7_0,
  144771. NULL,
  144772. &_vq_auxt__44u6__p7_0,
  144773. NULL,
  144774. 0
  144775. };
  144776. static long _vq_quantlist__44u6__p7_1[] = {
  144777. 5,
  144778. 4,
  144779. 6,
  144780. 3,
  144781. 7,
  144782. 2,
  144783. 8,
  144784. 1,
  144785. 9,
  144786. 0,
  144787. 10,
  144788. };
  144789. static long _vq_lengthlist__44u6__p7_1[] = {
  144790. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  144791. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  144792. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144793. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  144794. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144795. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144796. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144797. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144798. };
  144799. static float _vq_quantthresh__44u6__p7_1[] = {
  144800. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144801. 3.5, 4.5,
  144802. };
  144803. static long _vq_quantmap__44u6__p7_1[] = {
  144804. 9, 7, 5, 3, 1, 0, 2, 4,
  144805. 6, 8, 10,
  144806. };
  144807. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  144808. _vq_quantthresh__44u6__p7_1,
  144809. _vq_quantmap__44u6__p7_1,
  144810. 11,
  144811. 11
  144812. };
  144813. static static_codebook _44u6__p7_1 = {
  144814. 2, 121,
  144815. _vq_lengthlist__44u6__p7_1,
  144816. 1, -531365888, 1611661312, 4, 0,
  144817. _vq_quantlist__44u6__p7_1,
  144818. NULL,
  144819. &_vq_auxt__44u6__p7_1,
  144820. NULL,
  144821. 0
  144822. };
  144823. static long _vq_quantlist__44u6__p8_0[] = {
  144824. 5,
  144825. 4,
  144826. 6,
  144827. 3,
  144828. 7,
  144829. 2,
  144830. 8,
  144831. 1,
  144832. 9,
  144833. 0,
  144834. 10,
  144835. };
  144836. static long _vq_lengthlist__44u6__p8_0[] = {
  144837. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  144838. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  144839. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  144840. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  144841. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  144842. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  144843. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  144844. 12,13,13,14,14,14,15,15,15,
  144845. };
  144846. static float _vq_quantthresh__44u6__p8_0[] = {
  144847. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144848. 38.5, 49.5,
  144849. };
  144850. static long _vq_quantmap__44u6__p8_0[] = {
  144851. 9, 7, 5, 3, 1, 0, 2, 4,
  144852. 6, 8, 10,
  144853. };
  144854. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  144855. _vq_quantthresh__44u6__p8_0,
  144856. _vq_quantmap__44u6__p8_0,
  144857. 11,
  144858. 11
  144859. };
  144860. static static_codebook _44u6__p8_0 = {
  144861. 2, 121,
  144862. _vq_lengthlist__44u6__p8_0,
  144863. 1, -524582912, 1618345984, 4, 0,
  144864. _vq_quantlist__44u6__p8_0,
  144865. NULL,
  144866. &_vq_auxt__44u6__p8_0,
  144867. NULL,
  144868. 0
  144869. };
  144870. static long _vq_quantlist__44u6__p8_1[] = {
  144871. 5,
  144872. 4,
  144873. 6,
  144874. 3,
  144875. 7,
  144876. 2,
  144877. 8,
  144878. 1,
  144879. 9,
  144880. 0,
  144881. 10,
  144882. };
  144883. static long _vq_lengthlist__44u6__p8_1[] = {
  144884. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  144885. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  144886. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  144887. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  144888. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144889. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  144890. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144891. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144892. };
  144893. static float _vq_quantthresh__44u6__p8_1[] = {
  144894. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144895. 3.5, 4.5,
  144896. };
  144897. static long _vq_quantmap__44u6__p8_1[] = {
  144898. 9, 7, 5, 3, 1, 0, 2, 4,
  144899. 6, 8, 10,
  144900. };
  144901. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  144902. _vq_quantthresh__44u6__p8_1,
  144903. _vq_quantmap__44u6__p8_1,
  144904. 11,
  144905. 11
  144906. };
  144907. static static_codebook _44u6__p8_1 = {
  144908. 2, 121,
  144909. _vq_lengthlist__44u6__p8_1,
  144910. 1, -531365888, 1611661312, 4, 0,
  144911. _vq_quantlist__44u6__p8_1,
  144912. NULL,
  144913. &_vq_auxt__44u6__p8_1,
  144914. NULL,
  144915. 0
  144916. };
  144917. static long _vq_quantlist__44u6__p9_0[] = {
  144918. 7,
  144919. 6,
  144920. 8,
  144921. 5,
  144922. 9,
  144923. 4,
  144924. 10,
  144925. 3,
  144926. 11,
  144927. 2,
  144928. 12,
  144929. 1,
  144930. 13,
  144931. 0,
  144932. 14,
  144933. };
  144934. static long _vq_lengthlist__44u6__p9_0[] = {
  144935. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  144936. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  144937. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  144938. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  144939. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144940. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144941. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144942. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144943. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144944. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144945. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144946. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144947. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144948. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144949. 14,
  144950. };
  144951. static float _vq_quantthresh__44u6__p9_0[] = {
  144952. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144953. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144954. };
  144955. static long _vq_quantmap__44u6__p9_0[] = {
  144956. 13, 11, 9, 7, 5, 3, 1, 0,
  144957. 2, 4, 6, 8, 10, 12, 14,
  144958. };
  144959. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  144960. _vq_quantthresh__44u6__p9_0,
  144961. _vq_quantmap__44u6__p9_0,
  144962. 15,
  144963. 15
  144964. };
  144965. static static_codebook _44u6__p9_0 = {
  144966. 2, 225,
  144967. _vq_lengthlist__44u6__p9_0,
  144968. 1, -514071552, 1627381760, 4, 0,
  144969. _vq_quantlist__44u6__p9_0,
  144970. NULL,
  144971. &_vq_auxt__44u6__p9_0,
  144972. NULL,
  144973. 0
  144974. };
  144975. static long _vq_quantlist__44u6__p9_1[] = {
  144976. 7,
  144977. 6,
  144978. 8,
  144979. 5,
  144980. 9,
  144981. 4,
  144982. 10,
  144983. 3,
  144984. 11,
  144985. 2,
  144986. 12,
  144987. 1,
  144988. 13,
  144989. 0,
  144990. 14,
  144991. };
  144992. static long _vq_lengthlist__44u6__p9_1[] = {
  144993. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  144994. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  144995. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  144996. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  144997. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  144998. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  144999. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  145000. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  145001. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  145002. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  145003. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  145004. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  145005. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  145006. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  145007. 13,
  145008. };
  145009. static float _vq_quantthresh__44u6__p9_1[] = {
  145010. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145011. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145012. };
  145013. static long _vq_quantmap__44u6__p9_1[] = {
  145014. 13, 11, 9, 7, 5, 3, 1, 0,
  145015. 2, 4, 6, 8, 10, 12, 14,
  145016. };
  145017. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  145018. _vq_quantthresh__44u6__p9_1,
  145019. _vq_quantmap__44u6__p9_1,
  145020. 15,
  145021. 15
  145022. };
  145023. static static_codebook _44u6__p9_1 = {
  145024. 2, 225,
  145025. _vq_lengthlist__44u6__p9_1,
  145026. 1, -522338304, 1620115456, 4, 0,
  145027. _vq_quantlist__44u6__p9_1,
  145028. NULL,
  145029. &_vq_auxt__44u6__p9_1,
  145030. NULL,
  145031. 0
  145032. };
  145033. static long _vq_quantlist__44u6__p9_2[] = {
  145034. 8,
  145035. 7,
  145036. 9,
  145037. 6,
  145038. 10,
  145039. 5,
  145040. 11,
  145041. 4,
  145042. 12,
  145043. 3,
  145044. 13,
  145045. 2,
  145046. 14,
  145047. 1,
  145048. 15,
  145049. 0,
  145050. 16,
  145051. };
  145052. static long _vq_lengthlist__44u6__p9_2[] = {
  145053. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  145054. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145055. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  145056. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145057. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145058. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145059. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145060. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145061. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  145062. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  145063. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  145064. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145065. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  145066. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  145067. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  145068. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  145069. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  145070. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  145071. 10,
  145072. };
  145073. static float _vq_quantthresh__44u6__p9_2[] = {
  145074. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145075. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145076. };
  145077. static long _vq_quantmap__44u6__p9_2[] = {
  145078. 15, 13, 11, 9, 7, 5, 3, 1,
  145079. 0, 2, 4, 6, 8, 10, 12, 14,
  145080. 16,
  145081. };
  145082. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  145083. _vq_quantthresh__44u6__p9_2,
  145084. _vq_quantmap__44u6__p9_2,
  145085. 17,
  145086. 17
  145087. };
  145088. static static_codebook _44u6__p9_2 = {
  145089. 2, 289,
  145090. _vq_lengthlist__44u6__p9_2,
  145091. 1, -529530880, 1611661312, 5, 0,
  145092. _vq_quantlist__44u6__p9_2,
  145093. NULL,
  145094. &_vq_auxt__44u6__p9_2,
  145095. NULL,
  145096. 0
  145097. };
  145098. static long _huff_lengthlist__44u6__short[] = {
  145099. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  145100. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  145101. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  145102. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  145103. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  145104. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  145105. 7, 6, 9,16,
  145106. };
  145107. static static_codebook _huff_book__44u6__short = {
  145108. 2, 100,
  145109. _huff_lengthlist__44u6__short,
  145110. 0, 0, 0, 0, 0,
  145111. NULL,
  145112. NULL,
  145113. NULL,
  145114. NULL,
  145115. 0
  145116. };
  145117. static long _huff_lengthlist__44u7__long[] = {
  145118. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  145119. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  145120. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  145121. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  145122. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  145123. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  145124. 12, 8, 6, 7,
  145125. };
  145126. static static_codebook _huff_book__44u7__long = {
  145127. 2, 100,
  145128. _huff_lengthlist__44u7__long,
  145129. 0, 0, 0, 0, 0,
  145130. NULL,
  145131. NULL,
  145132. NULL,
  145133. NULL,
  145134. 0
  145135. };
  145136. static long _vq_quantlist__44u7__p1_0[] = {
  145137. 1,
  145138. 0,
  145139. 2,
  145140. };
  145141. static long _vq_lengthlist__44u7__p1_0[] = {
  145142. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145143. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  145144. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  145145. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  145146. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  145147. 12,
  145148. };
  145149. static float _vq_quantthresh__44u7__p1_0[] = {
  145150. -0.5, 0.5,
  145151. };
  145152. static long _vq_quantmap__44u7__p1_0[] = {
  145153. 1, 0, 2,
  145154. };
  145155. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  145156. _vq_quantthresh__44u7__p1_0,
  145157. _vq_quantmap__44u7__p1_0,
  145158. 3,
  145159. 3
  145160. };
  145161. static static_codebook _44u7__p1_0 = {
  145162. 4, 81,
  145163. _vq_lengthlist__44u7__p1_0,
  145164. 1, -535822336, 1611661312, 2, 0,
  145165. _vq_quantlist__44u7__p1_0,
  145166. NULL,
  145167. &_vq_auxt__44u7__p1_0,
  145168. NULL,
  145169. 0
  145170. };
  145171. static long _vq_quantlist__44u7__p2_0[] = {
  145172. 1,
  145173. 0,
  145174. 2,
  145175. };
  145176. static long _vq_lengthlist__44u7__p2_0[] = {
  145177. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  145178. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  145179. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  145180. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  145181. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  145182. 9,
  145183. };
  145184. static float _vq_quantthresh__44u7__p2_0[] = {
  145185. -0.5, 0.5,
  145186. };
  145187. static long _vq_quantmap__44u7__p2_0[] = {
  145188. 1, 0, 2,
  145189. };
  145190. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  145191. _vq_quantthresh__44u7__p2_0,
  145192. _vq_quantmap__44u7__p2_0,
  145193. 3,
  145194. 3
  145195. };
  145196. static static_codebook _44u7__p2_0 = {
  145197. 4, 81,
  145198. _vq_lengthlist__44u7__p2_0,
  145199. 1, -535822336, 1611661312, 2, 0,
  145200. _vq_quantlist__44u7__p2_0,
  145201. NULL,
  145202. &_vq_auxt__44u7__p2_0,
  145203. NULL,
  145204. 0
  145205. };
  145206. static long _vq_quantlist__44u7__p3_0[] = {
  145207. 2,
  145208. 1,
  145209. 3,
  145210. 0,
  145211. 4,
  145212. };
  145213. static long _vq_lengthlist__44u7__p3_0[] = {
  145214. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145215. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  145216. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  145217. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  145218. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  145219. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  145220. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  145221. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  145222. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  145223. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  145224. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  145225. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  145226. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  145227. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  145228. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  145229. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  145230. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  145231. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  145232. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  145233. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  145234. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  145235. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  145236. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  145237. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  145238. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  145239. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  145240. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  145241. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  145242. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  145243. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  145244. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  145245. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  145246. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  145247. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  145248. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  145249. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  145250. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  145251. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  145252. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  145253. 0,
  145254. };
  145255. static float _vq_quantthresh__44u7__p3_0[] = {
  145256. -1.5, -0.5, 0.5, 1.5,
  145257. };
  145258. static long _vq_quantmap__44u7__p3_0[] = {
  145259. 3, 1, 0, 2, 4,
  145260. };
  145261. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  145262. _vq_quantthresh__44u7__p3_0,
  145263. _vq_quantmap__44u7__p3_0,
  145264. 5,
  145265. 5
  145266. };
  145267. static static_codebook _44u7__p3_0 = {
  145268. 4, 625,
  145269. _vq_lengthlist__44u7__p3_0,
  145270. 1, -533725184, 1611661312, 3, 0,
  145271. _vq_quantlist__44u7__p3_0,
  145272. NULL,
  145273. &_vq_auxt__44u7__p3_0,
  145274. NULL,
  145275. 0
  145276. };
  145277. static long _vq_quantlist__44u7__p4_0[] = {
  145278. 2,
  145279. 1,
  145280. 3,
  145281. 0,
  145282. 4,
  145283. };
  145284. static long _vq_lengthlist__44u7__p4_0[] = {
  145285. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  145286. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  145287. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  145288. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  145289. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  145290. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  145291. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  145292. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  145293. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  145294. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  145295. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  145296. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  145297. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  145298. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  145299. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  145300. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  145301. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  145302. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145303. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  145304. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  145305. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  145306. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  145307. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  145308. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  145309. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  145310. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  145311. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  145312. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  145313. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  145314. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  145315. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  145316. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145317. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  145318. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  145319. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  145320. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  145321. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  145322. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  145323. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  145324. 14,
  145325. };
  145326. static float _vq_quantthresh__44u7__p4_0[] = {
  145327. -1.5, -0.5, 0.5, 1.5,
  145328. };
  145329. static long _vq_quantmap__44u7__p4_0[] = {
  145330. 3, 1, 0, 2, 4,
  145331. };
  145332. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  145333. _vq_quantthresh__44u7__p4_0,
  145334. _vq_quantmap__44u7__p4_0,
  145335. 5,
  145336. 5
  145337. };
  145338. static static_codebook _44u7__p4_0 = {
  145339. 4, 625,
  145340. _vq_lengthlist__44u7__p4_0,
  145341. 1, -533725184, 1611661312, 3, 0,
  145342. _vq_quantlist__44u7__p4_0,
  145343. NULL,
  145344. &_vq_auxt__44u7__p4_0,
  145345. NULL,
  145346. 0
  145347. };
  145348. static long _vq_quantlist__44u7__p5_0[] = {
  145349. 4,
  145350. 3,
  145351. 5,
  145352. 2,
  145353. 6,
  145354. 1,
  145355. 7,
  145356. 0,
  145357. 8,
  145358. };
  145359. static long _vq_lengthlist__44u7__p5_0[] = {
  145360. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  145361. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  145362. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  145363. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  145364. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  145365. 14,
  145366. };
  145367. static float _vq_quantthresh__44u7__p5_0[] = {
  145368. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145369. };
  145370. static long _vq_quantmap__44u7__p5_0[] = {
  145371. 7, 5, 3, 1, 0, 2, 4, 6,
  145372. 8,
  145373. };
  145374. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  145375. _vq_quantthresh__44u7__p5_0,
  145376. _vq_quantmap__44u7__p5_0,
  145377. 9,
  145378. 9
  145379. };
  145380. static static_codebook _44u7__p5_0 = {
  145381. 2, 81,
  145382. _vq_lengthlist__44u7__p5_0,
  145383. 1, -531628032, 1611661312, 4, 0,
  145384. _vq_quantlist__44u7__p5_0,
  145385. NULL,
  145386. &_vq_auxt__44u7__p5_0,
  145387. NULL,
  145388. 0
  145389. };
  145390. static long _vq_quantlist__44u7__p6_0[] = {
  145391. 4,
  145392. 3,
  145393. 5,
  145394. 2,
  145395. 6,
  145396. 1,
  145397. 7,
  145398. 0,
  145399. 8,
  145400. };
  145401. static long _vq_lengthlist__44u7__p6_0[] = {
  145402. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  145403. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  145404. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  145405. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  145406. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  145407. 12,
  145408. };
  145409. static float _vq_quantthresh__44u7__p6_0[] = {
  145410. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145411. };
  145412. static long _vq_quantmap__44u7__p6_0[] = {
  145413. 7, 5, 3, 1, 0, 2, 4, 6,
  145414. 8,
  145415. };
  145416. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  145417. _vq_quantthresh__44u7__p6_0,
  145418. _vq_quantmap__44u7__p6_0,
  145419. 9,
  145420. 9
  145421. };
  145422. static static_codebook _44u7__p6_0 = {
  145423. 2, 81,
  145424. _vq_lengthlist__44u7__p6_0,
  145425. 1, -531628032, 1611661312, 4, 0,
  145426. _vq_quantlist__44u7__p6_0,
  145427. NULL,
  145428. &_vq_auxt__44u7__p6_0,
  145429. NULL,
  145430. 0
  145431. };
  145432. static long _vq_quantlist__44u7__p7_0[] = {
  145433. 1,
  145434. 0,
  145435. 2,
  145436. };
  145437. static long _vq_lengthlist__44u7__p7_0[] = {
  145438. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  145439. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  145440. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  145441. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  145442. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  145443. 10,
  145444. };
  145445. static float _vq_quantthresh__44u7__p7_0[] = {
  145446. -5.5, 5.5,
  145447. };
  145448. static long _vq_quantmap__44u7__p7_0[] = {
  145449. 1, 0, 2,
  145450. };
  145451. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  145452. _vq_quantthresh__44u7__p7_0,
  145453. _vq_quantmap__44u7__p7_0,
  145454. 3,
  145455. 3
  145456. };
  145457. static static_codebook _44u7__p7_0 = {
  145458. 4, 81,
  145459. _vq_lengthlist__44u7__p7_0,
  145460. 1, -529137664, 1618345984, 2, 0,
  145461. _vq_quantlist__44u7__p7_0,
  145462. NULL,
  145463. &_vq_auxt__44u7__p7_0,
  145464. NULL,
  145465. 0
  145466. };
  145467. static long _vq_quantlist__44u7__p7_1[] = {
  145468. 5,
  145469. 4,
  145470. 6,
  145471. 3,
  145472. 7,
  145473. 2,
  145474. 8,
  145475. 1,
  145476. 9,
  145477. 0,
  145478. 10,
  145479. };
  145480. static long _vq_lengthlist__44u7__p7_1[] = {
  145481. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  145482. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  145483. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  145484. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  145485. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  145486. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  145487. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  145488. 8, 9, 9, 9, 9, 9,10,10,10,
  145489. };
  145490. static float _vq_quantthresh__44u7__p7_1[] = {
  145491. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145492. 3.5, 4.5,
  145493. };
  145494. static long _vq_quantmap__44u7__p7_1[] = {
  145495. 9, 7, 5, 3, 1, 0, 2, 4,
  145496. 6, 8, 10,
  145497. };
  145498. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  145499. _vq_quantthresh__44u7__p7_1,
  145500. _vq_quantmap__44u7__p7_1,
  145501. 11,
  145502. 11
  145503. };
  145504. static static_codebook _44u7__p7_1 = {
  145505. 2, 121,
  145506. _vq_lengthlist__44u7__p7_1,
  145507. 1, -531365888, 1611661312, 4, 0,
  145508. _vq_quantlist__44u7__p7_1,
  145509. NULL,
  145510. &_vq_auxt__44u7__p7_1,
  145511. NULL,
  145512. 0
  145513. };
  145514. static long _vq_quantlist__44u7__p8_0[] = {
  145515. 5,
  145516. 4,
  145517. 6,
  145518. 3,
  145519. 7,
  145520. 2,
  145521. 8,
  145522. 1,
  145523. 9,
  145524. 0,
  145525. 10,
  145526. };
  145527. static long _vq_lengthlist__44u7__p8_0[] = {
  145528. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145529. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  145530. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  145531. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  145532. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  145533. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  145534. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  145535. 12,13,13,14,14,15,15,15,16,
  145536. };
  145537. static float _vq_quantthresh__44u7__p8_0[] = {
  145538. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145539. 38.5, 49.5,
  145540. };
  145541. static long _vq_quantmap__44u7__p8_0[] = {
  145542. 9, 7, 5, 3, 1, 0, 2, 4,
  145543. 6, 8, 10,
  145544. };
  145545. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  145546. _vq_quantthresh__44u7__p8_0,
  145547. _vq_quantmap__44u7__p8_0,
  145548. 11,
  145549. 11
  145550. };
  145551. static static_codebook _44u7__p8_0 = {
  145552. 2, 121,
  145553. _vq_lengthlist__44u7__p8_0,
  145554. 1, -524582912, 1618345984, 4, 0,
  145555. _vq_quantlist__44u7__p8_0,
  145556. NULL,
  145557. &_vq_auxt__44u7__p8_0,
  145558. NULL,
  145559. 0
  145560. };
  145561. static long _vq_quantlist__44u7__p8_1[] = {
  145562. 5,
  145563. 4,
  145564. 6,
  145565. 3,
  145566. 7,
  145567. 2,
  145568. 8,
  145569. 1,
  145570. 9,
  145571. 0,
  145572. 10,
  145573. };
  145574. static long _vq_lengthlist__44u7__p8_1[] = {
  145575. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  145576. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  145577. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  145578. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  145579. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  145580. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  145581. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  145582. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  145583. };
  145584. static float _vq_quantthresh__44u7__p8_1[] = {
  145585. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145586. 3.5, 4.5,
  145587. };
  145588. static long _vq_quantmap__44u7__p8_1[] = {
  145589. 9, 7, 5, 3, 1, 0, 2, 4,
  145590. 6, 8, 10,
  145591. };
  145592. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  145593. _vq_quantthresh__44u7__p8_1,
  145594. _vq_quantmap__44u7__p8_1,
  145595. 11,
  145596. 11
  145597. };
  145598. static static_codebook _44u7__p8_1 = {
  145599. 2, 121,
  145600. _vq_lengthlist__44u7__p8_1,
  145601. 1, -531365888, 1611661312, 4, 0,
  145602. _vq_quantlist__44u7__p8_1,
  145603. NULL,
  145604. &_vq_auxt__44u7__p8_1,
  145605. NULL,
  145606. 0
  145607. };
  145608. static long _vq_quantlist__44u7__p9_0[] = {
  145609. 5,
  145610. 4,
  145611. 6,
  145612. 3,
  145613. 7,
  145614. 2,
  145615. 8,
  145616. 1,
  145617. 9,
  145618. 0,
  145619. 10,
  145620. };
  145621. static long _vq_lengthlist__44u7__p9_0[] = {
  145622. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  145623. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  145624. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145625. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145626. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145627. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145628. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145629. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145630. };
  145631. static float _vq_quantthresh__44u7__p9_0[] = {
  145632. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  145633. 2229.5, 2866.5,
  145634. };
  145635. static long _vq_quantmap__44u7__p9_0[] = {
  145636. 9, 7, 5, 3, 1, 0, 2, 4,
  145637. 6, 8, 10,
  145638. };
  145639. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  145640. _vq_quantthresh__44u7__p9_0,
  145641. _vq_quantmap__44u7__p9_0,
  145642. 11,
  145643. 11
  145644. };
  145645. static static_codebook _44u7__p9_0 = {
  145646. 2, 121,
  145647. _vq_lengthlist__44u7__p9_0,
  145648. 1, -512171520, 1630791680, 4, 0,
  145649. _vq_quantlist__44u7__p9_0,
  145650. NULL,
  145651. &_vq_auxt__44u7__p9_0,
  145652. NULL,
  145653. 0
  145654. };
  145655. static long _vq_quantlist__44u7__p9_1[] = {
  145656. 6,
  145657. 5,
  145658. 7,
  145659. 4,
  145660. 8,
  145661. 3,
  145662. 9,
  145663. 2,
  145664. 10,
  145665. 1,
  145666. 11,
  145667. 0,
  145668. 12,
  145669. };
  145670. static long _vq_lengthlist__44u7__p9_1[] = {
  145671. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  145672. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  145673. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  145674. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  145675. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  145676. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  145677. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  145678. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  145679. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  145680. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  145681. 15,15,15,15,17,17,16,17,16,
  145682. };
  145683. static float _vq_quantthresh__44u7__p9_1[] = {
  145684. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  145685. 122.5, 171.5, 220.5, 269.5,
  145686. };
  145687. static long _vq_quantmap__44u7__p9_1[] = {
  145688. 11, 9, 7, 5, 3, 1, 0, 2,
  145689. 4, 6, 8, 10, 12,
  145690. };
  145691. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  145692. _vq_quantthresh__44u7__p9_1,
  145693. _vq_quantmap__44u7__p9_1,
  145694. 13,
  145695. 13
  145696. };
  145697. static static_codebook _44u7__p9_1 = {
  145698. 2, 169,
  145699. _vq_lengthlist__44u7__p9_1,
  145700. 1, -518889472, 1622704128, 4, 0,
  145701. _vq_quantlist__44u7__p9_1,
  145702. NULL,
  145703. &_vq_auxt__44u7__p9_1,
  145704. NULL,
  145705. 0
  145706. };
  145707. static long _vq_quantlist__44u7__p9_2[] = {
  145708. 24,
  145709. 23,
  145710. 25,
  145711. 22,
  145712. 26,
  145713. 21,
  145714. 27,
  145715. 20,
  145716. 28,
  145717. 19,
  145718. 29,
  145719. 18,
  145720. 30,
  145721. 17,
  145722. 31,
  145723. 16,
  145724. 32,
  145725. 15,
  145726. 33,
  145727. 14,
  145728. 34,
  145729. 13,
  145730. 35,
  145731. 12,
  145732. 36,
  145733. 11,
  145734. 37,
  145735. 10,
  145736. 38,
  145737. 9,
  145738. 39,
  145739. 8,
  145740. 40,
  145741. 7,
  145742. 41,
  145743. 6,
  145744. 42,
  145745. 5,
  145746. 43,
  145747. 4,
  145748. 44,
  145749. 3,
  145750. 45,
  145751. 2,
  145752. 46,
  145753. 1,
  145754. 47,
  145755. 0,
  145756. 48,
  145757. };
  145758. static long _vq_lengthlist__44u7__p9_2[] = {
  145759. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  145760. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145761. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  145762. 8,
  145763. };
  145764. static float _vq_quantthresh__44u7__p9_2[] = {
  145765. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145766. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145767. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145768. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145769. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145770. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145771. };
  145772. static long _vq_quantmap__44u7__p9_2[] = {
  145773. 47, 45, 43, 41, 39, 37, 35, 33,
  145774. 31, 29, 27, 25, 23, 21, 19, 17,
  145775. 15, 13, 11, 9, 7, 5, 3, 1,
  145776. 0, 2, 4, 6, 8, 10, 12, 14,
  145777. 16, 18, 20, 22, 24, 26, 28, 30,
  145778. 32, 34, 36, 38, 40, 42, 44, 46,
  145779. 48,
  145780. };
  145781. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  145782. _vq_quantthresh__44u7__p9_2,
  145783. _vq_quantmap__44u7__p9_2,
  145784. 49,
  145785. 49
  145786. };
  145787. static static_codebook _44u7__p9_2 = {
  145788. 1, 49,
  145789. _vq_lengthlist__44u7__p9_2,
  145790. 1, -526909440, 1611661312, 6, 0,
  145791. _vq_quantlist__44u7__p9_2,
  145792. NULL,
  145793. &_vq_auxt__44u7__p9_2,
  145794. NULL,
  145795. 0
  145796. };
  145797. static long _huff_lengthlist__44u7__short[] = {
  145798. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  145799. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  145800. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  145801. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  145802. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  145803. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  145804. 6, 8, 5, 9,
  145805. };
  145806. static static_codebook _huff_book__44u7__short = {
  145807. 2, 100,
  145808. _huff_lengthlist__44u7__short,
  145809. 0, 0, 0, 0, 0,
  145810. NULL,
  145811. NULL,
  145812. NULL,
  145813. NULL,
  145814. 0
  145815. };
  145816. static long _huff_lengthlist__44u8__long[] = {
  145817. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  145818. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  145819. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  145820. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  145821. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  145822. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  145823. 10, 8, 8, 9,
  145824. };
  145825. static static_codebook _huff_book__44u8__long = {
  145826. 2, 100,
  145827. _huff_lengthlist__44u8__long,
  145828. 0, 0, 0, 0, 0,
  145829. NULL,
  145830. NULL,
  145831. NULL,
  145832. NULL,
  145833. 0
  145834. };
  145835. static long _huff_lengthlist__44u8__short[] = {
  145836. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  145837. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  145838. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  145839. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  145840. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  145841. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  145842. 10,10,15,17,
  145843. };
  145844. static static_codebook _huff_book__44u8__short = {
  145845. 2, 100,
  145846. _huff_lengthlist__44u8__short,
  145847. 0, 0, 0, 0, 0,
  145848. NULL,
  145849. NULL,
  145850. NULL,
  145851. NULL,
  145852. 0
  145853. };
  145854. static long _vq_quantlist__44u8_p1_0[] = {
  145855. 1,
  145856. 0,
  145857. 2,
  145858. };
  145859. static long _vq_lengthlist__44u8_p1_0[] = {
  145860. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  145861. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  145862. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  145863. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  145864. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  145865. 10,
  145866. };
  145867. static float _vq_quantthresh__44u8_p1_0[] = {
  145868. -0.5, 0.5,
  145869. };
  145870. static long _vq_quantmap__44u8_p1_0[] = {
  145871. 1, 0, 2,
  145872. };
  145873. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  145874. _vq_quantthresh__44u8_p1_0,
  145875. _vq_quantmap__44u8_p1_0,
  145876. 3,
  145877. 3
  145878. };
  145879. static static_codebook _44u8_p1_0 = {
  145880. 4, 81,
  145881. _vq_lengthlist__44u8_p1_0,
  145882. 1, -535822336, 1611661312, 2, 0,
  145883. _vq_quantlist__44u8_p1_0,
  145884. NULL,
  145885. &_vq_auxt__44u8_p1_0,
  145886. NULL,
  145887. 0
  145888. };
  145889. static long _vq_quantlist__44u8_p2_0[] = {
  145890. 2,
  145891. 1,
  145892. 3,
  145893. 0,
  145894. 4,
  145895. };
  145896. static long _vq_lengthlist__44u8_p2_0[] = {
  145897. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145898. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  145899. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  145900. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  145901. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  145902. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  145903. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145904. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  145905. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  145906. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  145907. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  145908. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145909. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  145910. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  145911. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  145912. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  145913. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  145914. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  145915. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  145916. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  145917. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  145918. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  145919. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  145920. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  145921. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  145922. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  145923. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  145924. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  145925. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  145926. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  145927. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  145928. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145929. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  145930. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  145931. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  145932. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  145933. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  145934. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  145935. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  145936. 14,
  145937. };
  145938. static float _vq_quantthresh__44u8_p2_0[] = {
  145939. -1.5, -0.5, 0.5, 1.5,
  145940. };
  145941. static long _vq_quantmap__44u8_p2_0[] = {
  145942. 3, 1, 0, 2, 4,
  145943. };
  145944. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  145945. _vq_quantthresh__44u8_p2_0,
  145946. _vq_quantmap__44u8_p2_0,
  145947. 5,
  145948. 5
  145949. };
  145950. static static_codebook _44u8_p2_0 = {
  145951. 4, 625,
  145952. _vq_lengthlist__44u8_p2_0,
  145953. 1, -533725184, 1611661312, 3, 0,
  145954. _vq_quantlist__44u8_p2_0,
  145955. NULL,
  145956. &_vq_auxt__44u8_p2_0,
  145957. NULL,
  145958. 0
  145959. };
  145960. static long _vq_quantlist__44u8_p3_0[] = {
  145961. 4,
  145962. 3,
  145963. 5,
  145964. 2,
  145965. 6,
  145966. 1,
  145967. 7,
  145968. 0,
  145969. 8,
  145970. };
  145971. static long _vq_lengthlist__44u8_p3_0[] = {
  145972. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  145973. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  145974. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  145975. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  145976. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  145977. 12,
  145978. };
  145979. static float _vq_quantthresh__44u8_p3_0[] = {
  145980. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145981. };
  145982. static long _vq_quantmap__44u8_p3_0[] = {
  145983. 7, 5, 3, 1, 0, 2, 4, 6,
  145984. 8,
  145985. };
  145986. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  145987. _vq_quantthresh__44u8_p3_0,
  145988. _vq_quantmap__44u8_p3_0,
  145989. 9,
  145990. 9
  145991. };
  145992. static static_codebook _44u8_p3_0 = {
  145993. 2, 81,
  145994. _vq_lengthlist__44u8_p3_0,
  145995. 1, -531628032, 1611661312, 4, 0,
  145996. _vq_quantlist__44u8_p3_0,
  145997. NULL,
  145998. &_vq_auxt__44u8_p3_0,
  145999. NULL,
  146000. 0
  146001. };
  146002. static long _vq_quantlist__44u8_p4_0[] = {
  146003. 8,
  146004. 7,
  146005. 9,
  146006. 6,
  146007. 10,
  146008. 5,
  146009. 11,
  146010. 4,
  146011. 12,
  146012. 3,
  146013. 13,
  146014. 2,
  146015. 14,
  146016. 1,
  146017. 15,
  146018. 0,
  146019. 16,
  146020. };
  146021. static long _vq_lengthlist__44u8_p4_0[] = {
  146022. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  146023. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  146024. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  146025. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  146026. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  146027. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  146028. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  146029. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  146030. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  146031. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  146032. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  146033. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  146034. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  146035. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  146036. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  146037. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  146038. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  146039. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  146040. 14,
  146041. };
  146042. static float _vq_quantthresh__44u8_p4_0[] = {
  146043. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146044. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146045. };
  146046. static long _vq_quantmap__44u8_p4_0[] = {
  146047. 15, 13, 11, 9, 7, 5, 3, 1,
  146048. 0, 2, 4, 6, 8, 10, 12, 14,
  146049. 16,
  146050. };
  146051. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  146052. _vq_quantthresh__44u8_p4_0,
  146053. _vq_quantmap__44u8_p4_0,
  146054. 17,
  146055. 17
  146056. };
  146057. static static_codebook _44u8_p4_0 = {
  146058. 2, 289,
  146059. _vq_lengthlist__44u8_p4_0,
  146060. 1, -529530880, 1611661312, 5, 0,
  146061. _vq_quantlist__44u8_p4_0,
  146062. NULL,
  146063. &_vq_auxt__44u8_p4_0,
  146064. NULL,
  146065. 0
  146066. };
  146067. static long _vq_quantlist__44u8_p5_0[] = {
  146068. 1,
  146069. 0,
  146070. 2,
  146071. };
  146072. static long _vq_lengthlist__44u8_p5_0[] = {
  146073. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  146074. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  146075. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  146076. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  146077. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  146078. 10,
  146079. };
  146080. static float _vq_quantthresh__44u8_p5_0[] = {
  146081. -5.5, 5.5,
  146082. };
  146083. static long _vq_quantmap__44u8_p5_0[] = {
  146084. 1, 0, 2,
  146085. };
  146086. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  146087. _vq_quantthresh__44u8_p5_0,
  146088. _vq_quantmap__44u8_p5_0,
  146089. 3,
  146090. 3
  146091. };
  146092. static static_codebook _44u8_p5_0 = {
  146093. 4, 81,
  146094. _vq_lengthlist__44u8_p5_0,
  146095. 1, -529137664, 1618345984, 2, 0,
  146096. _vq_quantlist__44u8_p5_0,
  146097. NULL,
  146098. &_vq_auxt__44u8_p5_0,
  146099. NULL,
  146100. 0
  146101. };
  146102. static long _vq_quantlist__44u8_p5_1[] = {
  146103. 5,
  146104. 4,
  146105. 6,
  146106. 3,
  146107. 7,
  146108. 2,
  146109. 8,
  146110. 1,
  146111. 9,
  146112. 0,
  146113. 10,
  146114. };
  146115. static long _vq_lengthlist__44u8_p5_1[] = {
  146116. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  146117. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  146118. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  146119. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  146120. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  146121. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  146122. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  146123. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  146124. };
  146125. static float _vq_quantthresh__44u8_p5_1[] = {
  146126. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146127. 3.5, 4.5,
  146128. };
  146129. static long _vq_quantmap__44u8_p5_1[] = {
  146130. 9, 7, 5, 3, 1, 0, 2, 4,
  146131. 6, 8, 10,
  146132. };
  146133. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  146134. _vq_quantthresh__44u8_p5_1,
  146135. _vq_quantmap__44u8_p5_1,
  146136. 11,
  146137. 11
  146138. };
  146139. static static_codebook _44u8_p5_1 = {
  146140. 2, 121,
  146141. _vq_lengthlist__44u8_p5_1,
  146142. 1, -531365888, 1611661312, 4, 0,
  146143. _vq_quantlist__44u8_p5_1,
  146144. NULL,
  146145. &_vq_auxt__44u8_p5_1,
  146146. NULL,
  146147. 0
  146148. };
  146149. static long _vq_quantlist__44u8_p6_0[] = {
  146150. 6,
  146151. 5,
  146152. 7,
  146153. 4,
  146154. 8,
  146155. 3,
  146156. 9,
  146157. 2,
  146158. 10,
  146159. 1,
  146160. 11,
  146161. 0,
  146162. 12,
  146163. };
  146164. static long _vq_lengthlist__44u8_p6_0[] = {
  146165. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  146166. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  146167. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  146168. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  146169. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  146170. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  146171. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  146172. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  146173. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  146174. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  146175. 11,11,11,11,11,12,11,12,12,
  146176. };
  146177. static float _vq_quantthresh__44u8_p6_0[] = {
  146178. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146179. 12.5, 17.5, 22.5, 27.5,
  146180. };
  146181. static long _vq_quantmap__44u8_p6_0[] = {
  146182. 11, 9, 7, 5, 3, 1, 0, 2,
  146183. 4, 6, 8, 10, 12,
  146184. };
  146185. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  146186. _vq_quantthresh__44u8_p6_0,
  146187. _vq_quantmap__44u8_p6_0,
  146188. 13,
  146189. 13
  146190. };
  146191. static static_codebook _44u8_p6_0 = {
  146192. 2, 169,
  146193. _vq_lengthlist__44u8_p6_0,
  146194. 1, -526516224, 1616117760, 4, 0,
  146195. _vq_quantlist__44u8_p6_0,
  146196. NULL,
  146197. &_vq_auxt__44u8_p6_0,
  146198. NULL,
  146199. 0
  146200. };
  146201. static long _vq_quantlist__44u8_p6_1[] = {
  146202. 2,
  146203. 1,
  146204. 3,
  146205. 0,
  146206. 4,
  146207. };
  146208. static long _vq_lengthlist__44u8_p6_1[] = {
  146209. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146210. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  146211. };
  146212. static float _vq_quantthresh__44u8_p6_1[] = {
  146213. -1.5, -0.5, 0.5, 1.5,
  146214. };
  146215. static long _vq_quantmap__44u8_p6_1[] = {
  146216. 3, 1, 0, 2, 4,
  146217. };
  146218. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  146219. _vq_quantthresh__44u8_p6_1,
  146220. _vq_quantmap__44u8_p6_1,
  146221. 5,
  146222. 5
  146223. };
  146224. static static_codebook _44u8_p6_1 = {
  146225. 2, 25,
  146226. _vq_lengthlist__44u8_p6_1,
  146227. 1, -533725184, 1611661312, 3, 0,
  146228. _vq_quantlist__44u8_p6_1,
  146229. NULL,
  146230. &_vq_auxt__44u8_p6_1,
  146231. NULL,
  146232. 0
  146233. };
  146234. static long _vq_quantlist__44u8_p7_0[] = {
  146235. 6,
  146236. 5,
  146237. 7,
  146238. 4,
  146239. 8,
  146240. 3,
  146241. 9,
  146242. 2,
  146243. 10,
  146244. 1,
  146245. 11,
  146246. 0,
  146247. 12,
  146248. };
  146249. static long _vq_lengthlist__44u8_p7_0[] = {
  146250. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  146251. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  146252. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  146253. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  146254. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  146255. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  146256. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  146257. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  146258. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  146259. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  146260. 13,13,14,14,14,15,15,15,16,
  146261. };
  146262. static float _vq_quantthresh__44u8_p7_0[] = {
  146263. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  146264. 27.5, 38.5, 49.5, 60.5,
  146265. };
  146266. static long _vq_quantmap__44u8_p7_0[] = {
  146267. 11, 9, 7, 5, 3, 1, 0, 2,
  146268. 4, 6, 8, 10, 12,
  146269. };
  146270. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  146271. _vq_quantthresh__44u8_p7_0,
  146272. _vq_quantmap__44u8_p7_0,
  146273. 13,
  146274. 13
  146275. };
  146276. static static_codebook _44u8_p7_0 = {
  146277. 2, 169,
  146278. _vq_lengthlist__44u8_p7_0,
  146279. 1, -523206656, 1618345984, 4, 0,
  146280. _vq_quantlist__44u8_p7_0,
  146281. NULL,
  146282. &_vq_auxt__44u8_p7_0,
  146283. NULL,
  146284. 0
  146285. };
  146286. static long _vq_quantlist__44u8_p7_1[] = {
  146287. 5,
  146288. 4,
  146289. 6,
  146290. 3,
  146291. 7,
  146292. 2,
  146293. 8,
  146294. 1,
  146295. 9,
  146296. 0,
  146297. 10,
  146298. };
  146299. static long _vq_lengthlist__44u8_p7_1[] = {
  146300. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  146301. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  146302. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  146303. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  146304. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  146305. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  146306. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  146307. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  146308. };
  146309. static float _vq_quantthresh__44u8_p7_1[] = {
  146310. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146311. 3.5, 4.5,
  146312. };
  146313. static long _vq_quantmap__44u8_p7_1[] = {
  146314. 9, 7, 5, 3, 1, 0, 2, 4,
  146315. 6, 8, 10,
  146316. };
  146317. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  146318. _vq_quantthresh__44u8_p7_1,
  146319. _vq_quantmap__44u8_p7_1,
  146320. 11,
  146321. 11
  146322. };
  146323. static static_codebook _44u8_p7_1 = {
  146324. 2, 121,
  146325. _vq_lengthlist__44u8_p7_1,
  146326. 1, -531365888, 1611661312, 4, 0,
  146327. _vq_quantlist__44u8_p7_1,
  146328. NULL,
  146329. &_vq_auxt__44u8_p7_1,
  146330. NULL,
  146331. 0
  146332. };
  146333. static long _vq_quantlist__44u8_p8_0[] = {
  146334. 7,
  146335. 6,
  146336. 8,
  146337. 5,
  146338. 9,
  146339. 4,
  146340. 10,
  146341. 3,
  146342. 11,
  146343. 2,
  146344. 12,
  146345. 1,
  146346. 13,
  146347. 0,
  146348. 14,
  146349. };
  146350. static long _vq_lengthlist__44u8_p8_0[] = {
  146351. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  146352. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  146353. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  146354. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  146355. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  146356. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  146357. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  146358. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  146359. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  146360. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  146361. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  146362. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  146363. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  146364. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  146365. 17,
  146366. };
  146367. static float _vq_quantthresh__44u8_p8_0[] = {
  146368. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  146369. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  146370. };
  146371. static long _vq_quantmap__44u8_p8_0[] = {
  146372. 13, 11, 9, 7, 5, 3, 1, 0,
  146373. 2, 4, 6, 8, 10, 12, 14,
  146374. };
  146375. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  146376. _vq_quantthresh__44u8_p8_0,
  146377. _vq_quantmap__44u8_p8_0,
  146378. 15,
  146379. 15
  146380. };
  146381. static static_codebook _44u8_p8_0 = {
  146382. 2, 225,
  146383. _vq_lengthlist__44u8_p8_0,
  146384. 1, -520986624, 1620377600, 4, 0,
  146385. _vq_quantlist__44u8_p8_0,
  146386. NULL,
  146387. &_vq_auxt__44u8_p8_0,
  146388. NULL,
  146389. 0
  146390. };
  146391. static long _vq_quantlist__44u8_p8_1[] = {
  146392. 10,
  146393. 9,
  146394. 11,
  146395. 8,
  146396. 12,
  146397. 7,
  146398. 13,
  146399. 6,
  146400. 14,
  146401. 5,
  146402. 15,
  146403. 4,
  146404. 16,
  146405. 3,
  146406. 17,
  146407. 2,
  146408. 18,
  146409. 1,
  146410. 19,
  146411. 0,
  146412. 20,
  146413. };
  146414. static long _vq_lengthlist__44u8_p8_1[] = {
  146415. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146416. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  146417. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  146418. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  146419. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146420. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  146421. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  146422. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  146423. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  146424. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  146425. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  146426. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  146427. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  146428. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  146429. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  146430. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146431. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  146432. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  146433. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  146434. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  146435. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146436. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  146437. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  146438. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146439. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146440. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  146441. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  146442. 10,10,10,10,10,10,10,10,10,
  146443. };
  146444. static float _vq_quantthresh__44u8_p8_1[] = {
  146445. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  146446. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  146447. 6.5, 7.5, 8.5, 9.5,
  146448. };
  146449. static long _vq_quantmap__44u8_p8_1[] = {
  146450. 19, 17, 15, 13, 11, 9, 7, 5,
  146451. 3, 1, 0, 2, 4, 6, 8, 10,
  146452. 12, 14, 16, 18, 20,
  146453. };
  146454. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  146455. _vq_quantthresh__44u8_p8_1,
  146456. _vq_quantmap__44u8_p8_1,
  146457. 21,
  146458. 21
  146459. };
  146460. static static_codebook _44u8_p8_1 = {
  146461. 2, 441,
  146462. _vq_lengthlist__44u8_p8_1,
  146463. 1, -529268736, 1611661312, 5, 0,
  146464. _vq_quantlist__44u8_p8_1,
  146465. NULL,
  146466. &_vq_auxt__44u8_p8_1,
  146467. NULL,
  146468. 0
  146469. };
  146470. static long _vq_quantlist__44u8_p9_0[] = {
  146471. 4,
  146472. 3,
  146473. 5,
  146474. 2,
  146475. 6,
  146476. 1,
  146477. 7,
  146478. 0,
  146479. 8,
  146480. };
  146481. static long _vq_lengthlist__44u8_p9_0[] = {
  146482. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  146483. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146484. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146485. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146486. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  146487. 8,
  146488. };
  146489. static float _vq_quantthresh__44u8_p9_0[] = {
  146490. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  146491. };
  146492. static long _vq_quantmap__44u8_p9_0[] = {
  146493. 7, 5, 3, 1, 0, 2, 4, 6,
  146494. 8,
  146495. };
  146496. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  146497. _vq_quantthresh__44u8_p9_0,
  146498. _vq_quantmap__44u8_p9_0,
  146499. 9,
  146500. 9
  146501. };
  146502. static static_codebook _44u8_p9_0 = {
  146503. 2, 81,
  146504. _vq_lengthlist__44u8_p9_0,
  146505. 1, -511895552, 1631393792, 4, 0,
  146506. _vq_quantlist__44u8_p9_0,
  146507. NULL,
  146508. &_vq_auxt__44u8_p9_0,
  146509. NULL,
  146510. 0
  146511. };
  146512. static long _vq_quantlist__44u8_p9_1[] = {
  146513. 9,
  146514. 8,
  146515. 10,
  146516. 7,
  146517. 11,
  146518. 6,
  146519. 12,
  146520. 5,
  146521. 13,
  146522. 4,
  146523. 14,
  146524. 3,
  146525. 15,
  146526. 2,
  146527. 16,
  146528. 1,
  146529. 17,
  146530. 0,
  146531. 18,
  146532. };
  146533. static long _vq_lengthlist__44u8_p9_1[] = {
  146534. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  146535. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  146536. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  146537. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  146538. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  146539. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  146540. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  146541. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  146542. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  146543. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  146544. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  146545. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  146546. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  146547. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  146548. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  146549. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  146550. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  146551. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  146552. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  146553. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  146554. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  146555. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  146556. 16,15,16,16,16,16,16,16,16,
  146557. };
  146558. static float _vq_quantthresh__44u8_p9_1[] = {
  146559. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  146560. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  146561. 367.5, 416.5,
  146562. };
  146563. static long _vq_quantmap__44u8_p9_1[] = {
  146564. 17, 15, 13, 11, 9, 7, 5, 3,
  146565. 1, 0, 2, 4, 6, 8, 10, 12,
  146566. 14, 16, 18,
  146567. };
  146568. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  146569. _vq_quantthresh__44u8_p9_1,
  146570. _vq_quantmap__44u8_p9_1,
  146571. 19,
  146572. 19
  146573. };
  146574. static static_codebook _44u8_p9_1 = {
  146575. 2, 361,
  146576. _vq_lengthlist__44u8_p9_1,
  146577. 1, -518287360, 1622704128, 5, 0,
  146578. _vq_quantlist__44u8_p9_1,
  146579. NULL,
  146580. &_vq_auxt__44u8_p9_1,
  146581. NULL,
  146582. 0
  146583. };
  146584. static long _vq_quantlist__44u8_p9_2[] = {
  146585. 24,
  146586. 23,
  146587. 25,
  146588. 22,
  146589. 26,
  146590. 21,
  146591. 27,
  146592. 20,
  146593. 28,
  146594. 19,
  146595. 29,
  146596. 18,
  146597. 30,
  146598. 17,
  146599. 31,
  146600. 16,
  146601. 32,
  146602. 15,
  146603. 33,
  146604. 14,
  146605. 34,
  146606. 13,
  146607. 35,
  146608. 12,
  146609. 36,
  146610. 11,
  146611. 37,
  146612. 10,
  146613. 38,
  146614. 9,
  146615. 39,
  146616. 8,
  146617. 40,
  146618. 7,
  146619. 41,
  146620. 6,
  146621. 42,
  146622. 5,
  146623. 43,
  146624. 4,
  146625. 44,
  146626. 3,
  146627. 45,
  146628. 2,
  146629. 46,
  146630. 1,
  146631. 47,
  146632. 0,
  146633. 48,
  146634. };
  146635. static long _vq_lengthlist__44u8_p9_2[] = {
  146636. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  146637. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146638. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146639. 7,
  146640. };
  146641. static float _vq_quantthresh__44u8_p9_2[] = {
  146642. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  146643. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  146644. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146645. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146646. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  146647. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  146648. };
  146649. static long _vq_quantmap__44u8_p9_2[] = {
  146650. 47, 45, 43, 41, 39, 37, 35, 33,
  146651. 31, 29, 27, 25, 23, 21, 19, 17,
  146652. 15, 13, 11, 9, 7, 5, 3, 1,
  146653. 0, 2, 4, 6, 8, 10, 12, 14,
  146654. 16, 18, 20, 22, 24, 26, 28, 30,
  146655. 32, 34, 36, 38, 40, 42, 44, 46,
  146656. 48,
  146657. };
  146658. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  146659. _vq_quantthresh__44u8_p9_2,
  146660. _vq_quantmap__44u8_p9_2,
  146661. 49,
  146662. 49
  146663. };
  146664. static static_codebook _44u8_p9_2 = {
  146665. 1, 49,
  146666. _vq_lengthlist__44u8_p9_2,
  146667. 1, -526909440, 1611661312, 6, 0,
  146668. _vq_quantlist__44u8_p9_2,
  146669. NULL,
  146670. &_vq_auxt__44u8_p9_2,
  146671. NULL,
  146672. 0
  146673. };
  146674. static long _huff_lengthlist__44u9__long[] = {
  146675. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  146676. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  146677. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  146678. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  146679. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  146680. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  146681. 10, 8, 8, 9,
  146682. };
  146683. static static_codebook _huff_book__44u9__long = {
  146684. 2, 100,
  146685. _huff_lengthlist__44u9__long,
  146686. 0, 0, 0, 0, 0,
  146687. NULL,
  146688. NULL,
  146689. NULL,
  146690. NULL,
  146691. 0
  146692. };
  146693. static long _huff_lengthlist__44u9__short[] = {
  146694. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  146695. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  146696. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  146697. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  146698. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  146699. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  146700. 9, 9,12,15,
  146701. };
  146702. static static_codebook _huff_book__44u9__short = {
  146703. 2, 100,
  146704. _huff_lengthlist__44u9__short,
  146705. 0, 0, 0, 0, 0,
  146706. NULL,
  146707. NULL,
  146708. NULL,
  146709. NULL,
  146710. 0
  146711. };
  146712. static long _vq_quantlist__44u9_p1_0[] = {
  146713. 1,
  146714. 0,
  146715. 2,
  146716. };
  146717. static long _vq_lengthlist__44u9_p1_0[] = {
  146718. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  146719. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  146720. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  146721. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  146722. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  146723. 10,
  146724. };
  146725. static float _vq_quantthresh__44u9_p1_0[] = {
  146726. -0.5, 0.5,
  146727. };
  146728. static long _vq_quantmap__44u9_p1_0[] = {
  146729. 1, 0, 2,
  146730. };
  146731. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  146732. _vq_quantthresh__44u9_p1_0,
  146733. _vq_quantmap__44u9_p1_0,
  146734. 3,
  146735. 3
  146736. };
  146737. static static_codebook _44u9_p1_0 = {
  146738. 4, 81,
  146739. _vq_lengthlist__44u9_p1_0,
  146740. 1, -535822336, 1611661312, 2, 0,
  146741. _vq_quantlist__44u9_p1_0,
  146742. NULL,
  146743. &_vq_auxt__44u9_p1_0,
  146744. NULL,
  146745. 0
  146746. };
  146747. static long _vq_quantlist__44u9_p2_0[] = {
  146748. 2,
  146749. 1,
  146750. 3,
  146751. 0,
  146752. 4,
  146753. };
  146754. static long _vq_lengthlist__44u9_p2_0[] = {
  146755. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  146756. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  146757. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  146758. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  146759. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  146760. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  146761. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  146762. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  146763. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  146764. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  146765. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  146766. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  146767. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  146768. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  146769. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  146770. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  146771. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  146772. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  146773. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  146774. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  146775. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  146776. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  146777. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  146778. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  146779. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  146780. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  146781. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  146782. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  146783. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  146784. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  146785. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  146786. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  146787. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  146788. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  146789. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  146790. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  146791. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  146792. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  146793. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  146794. 14,
  146795. };
  146796. static float _vq_quantthresh__44u9_p2_0[] = {
  146797. -1.5, -0.5, 0.5, 1.5,
  146798. };
  146799. static long _vq_quantmap__44u9_p2_0[] = {
  146800. 3, 1, 0, 2, 4,
  146801. };
  146802. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  146803. _vq_quantthresh__44u9_p2_0,
  146804. _vq_quantmap__44u9_p2_0,
  146805. 5,
  146806. 5
  146807. };
  146808. static static_codebook _44u9_p2_0 = {
  146809. 4, 625,
  146810. _vq_lengthlist__44u9_p2_0,
  146811. 1, -533725184, 1611661312, 3, 0,
  146812. _vq_quantlist__44u9_p2_0,
  146813. NULL,
  146814. &_vq_auxt__44u9_p2_0,
  146815. NULL,
  146816. 0
  146817. };
  146818. static long _vq_quantlist__44u9_p3_0[] = {
  146819. 4,
  146820. 3,
  146821. 5,
  146822. 2,
  146823. 6,
  146824. 1,
  146825. 7,
  146826. 0,
  146827. 8,
  146828. };
  146829. static long _vq_lengthlist__44u9_p3_0[] = {
  146830. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  146831. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146832. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  146833. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  146834. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  146835. 11,
  146836. };
  146837. static float _vq_quantthresh__44u9_p3_0[] = {
  146838. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146839. };
  146840. static long _vq_quantmap__44u9_p3_0[] = {
  146841. 7, 5, 3, 1, 0, 2, 4, 6,
  146842. 8,
  146843. };
  146844. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  146845. _vq_quantthresh__44u9_p3_0,
  146846. _vq_quantmap__44u9_p3_0,
  146847. 9,
  146848. 9
  146849. };
  146850. static static_codebook _44u9_p3_0 = {
  146851. 2, 81,
  146852. _vq_lengthlist__44u9_p3_0,
  146853. 1, -531628032, 1611661312, 4, 0,
  146854. _vq_quantlist__44u9_p3_0,
  146855. NULL,
  146856. &_vq_auxt__44u9_p3_0,
  146857. NULL,
  146858. 0
  146859. };
  146860. static long _vq_quantlist__44u9_p4_0[] = {
  146861. 8,
  146862. 7,
  146863. 9,
  146864. 6,
  146865. 10,
  146866. 5,
  146867. 11,
  146868. 4,
  146869. 12,
  146870. 3,
  146871. 13,
  146872. 2,
  146873. 14,
  146874. 1,
  146875. 15,
  146876. 0,
  146877. 16,
  146878. };
  146879. static long _vq_lengthlist__44u9_p4_0[] = {
  146880. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  146881. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  146882. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  146883. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  146884. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  146885. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  146886. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  146887. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  146888. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  146889. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  146890. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  146891. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  146892. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  146893. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  146894. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  146895. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  146896. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  146897. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  146898. 14,
  146899. };
  146900. static float _vq_quantthresh__44u9_p4_0[] = {
  146901. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146902. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146903. };
  146904. static long _vq_quantmap__44u9_p4_0[] = {
  146905. 15, 13, 11, 9, 7, 5, 3, 1,
  146906. 0, 2, 4, 6, 8, 10, 12, 14,
  146907. 16,
  146908. };
  146909. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  146910. _vq_quantthresh__44u9_p4_0,
  146911. _vq_quantmap__44u9_p4_0,
  146912. 17,
  146913. 17
  146914. };
  146915. static static_codebook _44u9_p4_0 = {
  146916. 2, 289,
  146917. _vq_lengthlist__44u9_p4_0,
  146918. 1, -529530880, 1611661312, 5, 0,
  146919. _vq_quantlist__44u9_p4_0,
  146920. NULL,
  146921. &_vq_auxt__44u9_p4_0,
  146922. NULL,
  146923. 0
  146924. };
  146925. static long _vq_quantlist__44u9_p5_0[] = {
  146926. 1,
  146927. 0,
  146928. 2,
  146929. };
  146930. static long _vq_lengthlist__44u9_p5_0[] = {
  146931. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  146932. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  146933. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  146934. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  146935. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  146936. 10,
  146937. };
  146938. static float _vq_quantthresh__44u9_p5_0[] = {
  146939. -5.5, 5.5,
  146940. };
  146941. static long _vq_quantmap__44u9_p5_0[] = {
  146942. 1, 0, 2,
  146943. };
  146944. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  146945. _vq_quantthresh__44u9_p5_0,
  146946. _vq_quantmap__44u9_p5_0,
  146947. 3,
  146948. 3
  146949. };
  146950. static static_codebook _44u9_p5_0 = {
  146951. 4, 81,
  146952. _vq_lengthlist__44u9_p5_0,
  146953. 1, -529137664, 1618345984, 2, 0,
  146954. _vq_quantlist__44u9_p5_0,
  146955. NULL,
  146956. &_vq_auxt__44u9_p5_0,
  146957. NULL,
  146958. 0
  146959. };
  146960. static long _vq_quantlist__44u9_p5_1[] = {
  146961. 5,
  146962. 4,
  146963. 6,
  146964. 3,
  146965. 7,
  146966. 2,
  146967. 8,
  146968. 1,
  146969. 9,
  146970. 0,
  146971. 10,
  146972. };
  146973. static long _vq_lengthlist__44u9_p5_1[] = {
  146974. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  146975. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  146976. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  146977. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  146978. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  146979. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  146980. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  146981. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146982. };
  146983. static float _vq_quantthresh__44u9_p5_1[] = {
  146984. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146985. 3.5, 4.5,
  146986. };
  146987. static long _vq_quantmap__44u9_p5_1[] = {
  146988. 9, 7, 5, 3, 1, 0, 2, 4,
  146989. 6, 8, 10,
  146990. };
  146991. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  146992. _vq_quantthresh__44u9_p5_1,
  146993. _vq_quantmap__44u9_p5_1,
  146994. 11,
  146995. 11
  146996. };
  146997. static static_codebook _44u9_p5_1 = {
  146998. 2, 121,
  146999. _vq_lengthlist__44u9_p5_1,
  147000. 1, -531365888, 1611661312, 4, 0,
  147001. _vq_quantlist__44u9_p5_1,
  147002. NULL,
  147003. &_vq_auxt__44u9_p5_1,
  147004. NULL,
  147005. 0
  147006. };
  147007. static long _vq_quantlist__44u9_p6_0[] = {
  147008. 6,
  147009. 5,
  147010. 7,
  147011. 4,
  147012. 8,
  147013. 3,
  147014. 9,
  147015. 2,
  147016. 10,
  147017. 1,
  147018. 11,
  147019. 0,
  147020. 12,
  147021. };
  147022. static long _vq_lengthlist__44u9_p6_0[] = {
  147023. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  147024. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  147025. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  147026. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  147027. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  147028. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  147029. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  147030. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  147031. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  147032. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  147033. 10,11,11,11,11,12,11,12,12,
  147034. };
  147035. static float _vq_quantthresh__44u9_p6_0[] = {
  147036. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147037. 12.5, 17.5, 22.5, 27.5,
  147038. };
  147039. static long _vq_quantmap__44u9_p6_0[] = {
  147040. 11, 9, 7, 5, 3, 1, 0, 2,
  147041. 4, 6, 8, 10, 12,
  147042. };
  147043. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  147044. _vq_quantthresh__44u9_p6_0,
  147045. _vq_quantmap__44u9_p6_0,
  147046. 13,
  147047. 13
  147048. };
  147049. static static_codebook _44u9_p6_0 = {
  147050. 2, 169,
  147051. _vq_lengthlist__44u9_p6_0,
  147052. 1, -526516224, 1616117760, 4, 0,
  147053. _vq_quantlist__44u9_p6_0,
  147054. NULL,
  147055. &_vq_auxt__44u9_p6_0,
  147056. NULL,
  147057. 0
  147058. };
  147059. static long _vq_quantlist__44u9_p6_1[] = {
  147060. 2,
  147061. 1,
  147062. 3,
  147063. 0,
  147064. 4,
  147065. };
  147066. static long _vq_lengthlist__44u9_p6_1[] = {
  147067. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  147068. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  147069. };
  147070. static float _vq_quantthresh__44u9_p6_1[] = {
  147071. -1.5, -0.5, 0.5, 1.5,
  147072. };
  147073. static long _vq_quantmap__44u9_p6_1[] = {
  147074. 3, 1, 0, 2, 4,
  147075. };
  147076. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  147077. _vq_quantthresh__44u9_p6_1,
  147078. _vq_quantmap__44u9_p6_1,
  147079. 5,
  147080. 5
  147081. };
  147082. static static_codebook _44u9_p6_1 = {
  147083. 2, 25,
  147084. _vq_lengthlist__44u9_p6_1,
  147085. 1, -533725184, 1611661312, 3, 0,
  147086. _vq_quantlist__44u9_p6_1,
  147087. NULL,
  147088. &_vq_auxt__44u9_p6_1,
  147089. NULL,
  147090. 0
  147091. };
  147092. static long _vq_quantlist__44u9_p7_0[] = {
  147093. 6,
  147094. 5,
  147095. 7,
  147096. 4,
  147097. 8,
  147098. 3,
  147099. 9,
  147100. 2,
  147101. 10,
  147102. 1,
  147103. 11,
  147104. 0,
  147105. 12,
  147106. };
  147107. static long _vq_lengthlist__44u9_p7_0[] = {
  147108. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  147109. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  147110. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  147111. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  147112. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  147113. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  147114. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  147115. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  147116. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  147117. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  147118. 12,13,13,14,14,14,15,15,15,
  147119. };
  147120. static float _vq_quantthresh__44u9_p7_0[] = {
  147121. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  147122. 27.5, 38.5, 49.5, 60.5,
  147123. };
  147124. static long _vq_quantmap__44u9_p7_0[] = {
  147125. 11, 9, 7, 5, 3, 1, 0, 2,
  147126. 4, 6, 8, 10, 12,
  147127. };
  147128. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  147129. _vq_quantthresh__44u9_p7_0,
  147130. _vq_quantmap__44u9_p7_0,
  147131. 13,
  147132. 13
  147133. };
  147134. static static_codebook _44u9_p7_0 = {
  147135. 2, 169,
  147136. _vq_lengthlist__44u9_p7_0,
  147137. 1, -523206656, 1618345984, 4, 0,
  147138. _vq_quantlist__44u9_p7_0,
  147139. NULL,
  147140. &_vq_auxt__44u9_p7_0,
  147141. NULL,
  147142. 0
  147143. };
  147144. static long _vq_quantlist__44u9_p7_1[] = {
  147145. 5,
  147146. 4,
  147147. 6,
  147148. 3,
  147149. 7,
  147150. 2,
  147151. 8,
  147152. 1,
  147153. 9,
  147154. 0,
  147155. 10,
  147156. };
  147157. static long _vq_lengthlist__44u9_p7_1[] = {
  147158. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  147159. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  147160. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  147161. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147162. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147163. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147164. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  147165. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  147166. };
  147167. static float _vq_quantthresh__44u9_p7_1[] = {
  147168. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147169. 3.5, 4.5,
  147170. };
  147171. static long _vq_quantmap__44u9_p7_1[] = {
  147172. 9, 7, 5, 3, 1, 0, 2, 4,
  147173. 6, 8, 10,
  147174. };
  147175. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  147176. _vq_quantthresh__44u9_p7_1,
  147177. _vq_quantmap__44u9_p7_1,
  147178. 11,
  147179. 11
  147180. };
  147181. static static_codebook _44u9_p7_1 = {
  147182. 2, 121,
  147183. _vq_lengthlist__44u9_p7_1,
  147184. 1, -531365888, 1611661312, 4, 0,
  147185. _vq_quantlist__44u9_p7_1,
  147186. NULL,
  147187. &_vq_auxt__44u9_p7_1,
  147188. NULL,
  147189. 0
  147190. };
  147191. static long _vq_quantlist__44u9_p8_0[] = {
  147192. 7,
  147193. 6,
  147194. 8,
  147195. 5,
  147196. 9,
  147197. 4,
  147198. 10,
  147199. 3,
  147200. 11,
  147201. 2,
  147202. 12,
  147203. 1,
  147204. 13,
  147205. 0,
  147206. 14,
  147207. };
  147208. static long _vq_lengthlist__44u9_p8_0[] = {
  147209. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  147210. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  147211. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  147212. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  147213. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  147214. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  147215. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  147216. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  147217. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  147218. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  147219. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  147220. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  147221. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  147222. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  147223. 15,
  147224. };
  147225. static float _vq_quantthresh__44u9_p8_0[] = {
  147226. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  147227. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  147228. };
  147229. static long _vq_quantmap__44u9_p8_0[] = {
  147230. 13, 11, 9, 7, 5, 3, 1, 0,
  147231. 2, 4, 6, 8, 10, 12, 14,
  147232. };
  147233. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  147234. _vq_quantthresh__44u9_p8_0,
  147235. _vq_quantmap__44u9_p8_0,
  147236. 15,
  147237. 15
  147238. };
  147239. static static_codebook _44u9_p8_0 = {
  147240. 2, 225,
  147241. _vq_lengthlist__44u9_p8_0,
  147242. 1, -520986624, 1620377600, 4, 0,
  147243. _vq_quantlist__44u9_p8_0,
  147244. NULL,
  147245. &_vq_auxt__44u9_p8_0,
  147246. NULL,
  147247. 0
  147248. };
  147249. static long _vq_quantlist__44u9_p8_1[] = {
  147250. 10,
  147251. 9,
  147252. 11,
  147253. 8,
  147254. 12,
  147255. 7,
  147256. 13,
  147257. 6,
  147258. 14,
  147259. 5,
  147260. 15,
  147261. 4,
  147262. 16,
  147263. 3,
  147264. 17,
  147265. 2,
  147266. 18,
  147267. 1,
  147268. 19,
  147269. 0,
  147270. 20,
  147271. };
  147272. static long _vq_lengthlist__44u9_p8_1[] = {
  147273. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  147274. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  147275. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  147276. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  147277. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  147278. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147279. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  147280. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  147281. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147282. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147283. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  147284. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  147285. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147286. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  147287. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147288. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  147289. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  147290. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147291. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  147292. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  147293. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147294. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  147295. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  147296. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  147297. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  147298. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  147299. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  147300. 10,10,10,10,10,10,10,10,10,
  147301. };
  147302. static float _vq_quantthresh__44u9_p8_1[] = {
  147303. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  147304. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  147305. 6.5, 7.5, 8.5, 9.5,
  147306. };
  147307. static long _vq_quantmap__44u9_p8_1[] = {
  147308. 19, 17, 15, 13, 11, 9, 7, 5,
  147309. 3, 1, 0, 2, 4, 6, 8, 10,
  147310. 12, 14, 16, 18, 20,
  147311. };
  147312. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  147313. _vq_quantthresh__44u9_p8_1,
  147314. _vq_quantmap__44u9_p8_1,
  147315. 21,
  147316. 21
  147317. };
  147318. static static_codebook _44u9_p8_1 = {
  147319. 2, 441,
  147320. _vq_lengthlist__44u9_p8_1,
  147321. 1, -529268736, 1611661312, 5, 0,
  147322. _vq_quantlist__44u9_p8_1,
  147323. NULL,
  147324. &_vq_auxt__44u9_p8_1,
  147325. NULL,
  147326. 0
  147327. };
  147328. static long _vq_quantlist__44u9_p9_0[] = {
  147329. 7,
  147330. 6,
  147331. 8,
  147332. 5,
  147333. 9,
  147334. 4,
  147335. 10,
  147336. 3,
  147337. 11,
  147338. 2,
  147339. 12,
  147340. 1,
  147341. 13,
  147342. 0,
  147343. 14,
  147344. };
  147345. static long _vq_lengthlist__44u9_p9_0[] = {
  147346. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  147347. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  147348. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147349. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147350. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147351. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147352. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147353. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147354. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147355. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147356. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147357. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147358. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147359. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147360. 10,
  147361. };
  147362. static float _vq_quantthresh__44u9_p9_0[] = {
  147363. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  147364. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  147365. };
  147366. static long _vq_quantmap__44u9_p9_0[] = {
  147367. 13, 11, 9, 7, 5, 3, 1, 0,
  147368. 2, 4, 6, 8, 10, 12, 14,
  147369. };
  147370. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  147371. _vq_quantthresh__44u9_p9_0,
  147372. _vq_quantmap__44u9_p9_0,
  147373. 15,
  147374. 15
  147375. };
  147376. static static_codebook _44u9_p9_0 = {
  147377. 2, 225,
  147378. _vq_lengthlist__44u9_p9_0,
  147379. 1, -510036736, 1631393792, 4, 0,
  147380. _vq_quantlist__44u9_p9_0,
  147381. NULL,
  147382. &_vq_auxt__44u9_p9_0,
  147383. NULL,
  147384. 0
  147385. };
  147386. static long _vq_quantlist__44u9_p9_1[] = {
  147387. 9,
  147388. 8,
  147389. 10,
  147390. 7,
  147391. 11,
  147392. 6,
  147393. 12,
  147394. 5,
  147395. 13,
  147396. 4,
  147397. 14,
  147398. 3,
  147399. 15,
  147400. 2,
  147401. 16,
  147402. 1,
  147403. 17,
  147404. 0,
  147405. 18,
  147406. };
  147407. static long _vq_lengthlist__44u9_p9_1[] = {
  147408. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  147409. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  147410. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  147411. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  147412. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  147413. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  147414. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  147415. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  147416. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  147417. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  147418. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  147419. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  147420. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  147421. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  147422. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  147423. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  147424. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  147425. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  147426. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  147427. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  147428. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  147429. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  147430. 17,17,15,17,15,17,16,16,17,
  147431. };
  147432. static float _vq_quantthresh__44u9_p9_1[] = {
  147433. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  147434. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  147435. 367.5, 416.5,
  147436. };
  147437. static long _vq_quantmap__44u9_p9_1[] = {
  147438. 17, 15, 13, 11, 9, 7, 5, 3,
  147439. 1, 0, 2, 4, 6, 8, 10, 12,
  147440. 14, 16, 18,
  147441. };
  147442. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  147443. _vq_quantthresh__44u9_p9_1,
  147444. _vq_quantmap__44u9_p9_1,
  147445. 19,
  147446. 19
  147447. };
  147448. static static_codebook _44u9_p9_1 = {
  147449. 2, 361,
  147450. _vq_lengthlist__44u9_p9_1,
  147451. 1, -518287360, 1622704128, 5, 0,
  147452. _vq_quantlist__44u9_p9_1,
  147453. NULL,
  147454. &_vq_auxt__44u9_p9_1,
  147455. NULL,
  147456. 0
  147457. };
  147458. static long _vq_quantlist__44u9_p9_2[] = {
  147459. 24,
  147460. 23,
  147461. 25,
  147462. 22,
  147463. 26,
  147464. 21,
  147465. 27,
  147466. 20,
  147467. 28,
  147468. 19,
  147469. 29,
  147470. 18,
  147471. 30,
  147472. 17,
  147473. 31,
  147474. 16,
  147475. 32,
  147476. 15,
  147477. 33,
  147478. 14,
  147479. 34,
  147480. 13,
  147481. 35,
  147482. 12,
  147483. 36,
  147484. 11,
  147485. 37,
  147486. 10,
  147487. 38,
  147488. 9,
  147489. 39,
  147490. 8,
  147491. 40,
  147492. 7,
  147493. 41,
  147494. 6,
  147495. 42,
  147496. 5,
  147497. 43,
  147498. 4,
  147499. 44,
  147500. 3,
  147501. 45,
  147502. 2,
  147503. 46,
  147504. 1,
  147505. 47,
  147506. 0,
  147507. 48,
  147508. };
  147509. static long _vq_lengthlist__44u9_p9_2[] = {
  147510. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  147511. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147512. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147513. 7,
  147514. };
  147515. static float _vq_quantthresh__44u9_p9_2[] = {
  147516. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  147517. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  147518. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147519. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147520. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  147521. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  147522. };
  147523. static long _vq_quantmap__44u9_p9_2[] = {
  147524. 47, 45, 43, 41, 39, 37, 35, 33,
  147525. 31, 29, 27, 25, 23, 21, 19, 17,
  147526. 15, 13, 11, 9, 7, 5, 3, 1,
  147527. 0, 2, 4, 6, 8, 10, 12, 14,
  147528. 16, 18, 20, 22, 24, 26, 28, 30,
  147529. 32, 34, 36, 38, 40, 42, 44, 46,
  147530. 48,
  147531. };
  147532. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  147533. _vq_quantthresh__44u9_p9_2,
  147534. _vq_quantmap__44u9_p9_2,
  147535. 49,
  147536. 49
  147537. };
  147538. static static_codebook _44u9_p9_2 = {
  147539. 1, 49,
  147540. _vq_lengthlist__44u9_p9_2,
  147541. 1, -526909440, 1611661312, 6, 0,
  147542. _vq_quantlist__44u9_p9_2,
  147543. NULL,
  147544. &_vq_auxt__44u9_p9_2,
  147545. NULL,
  147546. 0
  147547. };
  147548. static long _huff_lengthlist__44un1__long[] = {
  147549. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  147550. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  147551. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  147552. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  147553. };
  147554. static static_codebook _huff_book__44un1__long = {
  147555. 2, 64,
  147556. _huff_lengthlist__44un1__long,
  147557. 0, 0, 0, 0, 0,
  147558. NULL,
  147559. NULL,
  147560. NULL,
  147561. NULL,
  147562. 0
  147563. };
  147564. static long _vq_quantlist__44un1__p1_0[] = {
  147565. 1,
  147566. 0,
  147567. 2,
  147568. };
  147569. static long _vq_lengthlist__44un1__p1_0[] = {
  147570. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147571. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  147572. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  147573. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  147574. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  147575. 12,
  147576. };
  147577. static float _vq_quantthresh__44un1__p1_0[] = {
  147578. -0.5, 0.5,
  147579. };
  147580. static long _vq_quantmap__44un1__p1_0[] = {
  147581. 1, 0, 2,
  147582. };
  147583. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  147584. _vq_quantthresh__44un1__p1_0,
  147585. _vq_quantmap__44un1__p1_0,
  147586. 3,
  147587. 3
  147588. };
  147589. static static_codebook _44un1__p1_0 = {
  147590. 4, 81,
  147591. _vq_lengthlist__44un1__p1_0,
  147592. 1, -535822336, 1611661312, 2, 0,
  147593. _vq_quantlist__44un1__p1_0,
  147594. NULL,
  147595. &_vq_auxt__44un1__p1_0,
  147596. NULL,
  147597. 0
  147598. };
  147599. static long _vq_quantlist__44un1__p2_0[] = {
  147600. 1,
  147601. 0,
  147602. 2,
  147603. };
  147604. static long _vq_lengthlist__44un1__p2_0[] = {
  147605. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  147606. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  147607. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  147608. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  147609. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  147610. 8,
  147611. };
  147612. static float _vq_quantthresh__44un1__p2_0[] = {
  147613. -0.5, 0.5,
  147614. };
  147615. static long _vq_quantmap__44un1__p2_0[] = {
  147616. 1, 0, 2,
  147617. };
  147618. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  147619. _vq_quantthresh__44un1__p2_0,
  147620. _vq_quantmap__44un1__p2_0,
  147621. 3,
  147622. 3
  147623. };
  147624. static static_codebook _44un1__p2_0 = {
  147625. 4, 81,
  147626. _vq_lengthlist__44un1__p2_0,
  147627. 1, -535822336, 1611661312, 2, 0,
  147628. _vq_quantlist__44un1__p2_0,
  147629. NULL,
  147630. &_vq_auxt__44un1__p2_0,
  147631. NULL,
  147632. 0
  147633. };
  147634. static long _vq_quantlist__44un1__p3_0[] = {
  147635. 2,
  147636. 1,
  147637. 3,
  147638. 0,
  147639. 4,
  147640. };
  147641. static long _vq_lengthlist__44un1__p3_0[] = {
  147642. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  147643. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  147644. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  147645. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  147646. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  147647. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  147648. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  147649. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  147650. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  147651. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  147652. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  147653. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  147654. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  147655. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  147656. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  147657. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  147658. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  147659. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  147660. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  147661. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  147662. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  147663. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  147664. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  147665. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  147666. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  147667. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  147668. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  147669. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  147670. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  147671. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  147672. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  147673. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  147674. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  147675. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  147676. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  147677. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  147678. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  147679. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  147680. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  147681. 17,
  147682. };
  147683. static float _vq_quantthresh__44un1__p3_0[] = {
  147684. -1.5, -0.5, 0.5, 1.5,
  147685. };
  147686. static long _vq_quantmap__44un1__p3_0[] = {
  147687. 3, 1, 0, 2, 4,
  147688. };
  147689. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  147690. _vq_quantthresh__44un1__p3_0,
  147691. _vq_quantmap__44un1__p3_0,
  147692. 5,
  147693. 5
  147694. };
  147695. static static_codebook _44un1__p3_0 = {
  147696. 4, 625,
  147697. _vq_lengthlist__44un1__p3_0,
  147698. 1, -533725184, 1611661312, 3, 0,
  147699. _vq_quantlist__44un1__p3_0,
  147700. NULL,
  147701. &_vq_auxt__44un1__p3_0,
  147702. NULL,
  147703. 0
  147704. };
  147705. static long _vq_quantlist__44un1__p4_0[] = {
  147706. 2,
  147707. 1,
  147708. 3,
  147709. 0,
  147710. 4,
  147711. };
  147712. static long _vq_lengthlist__44un1__p4_0[] = {
  147713. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  147714. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  147715. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  147716. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  147717. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  147718. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  147719. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  147720. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  147721. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  147722. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  147723. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  147724. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  147725. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  147726. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  147727. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  147728. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  147729. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  147730. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  147731. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  147732. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  147733. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  147734. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  147735. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  147736. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  147737. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  147738. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  147739. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  147740. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  147741. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  147742. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  147743. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  147744. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  147745. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  147746. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  147747. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  147748. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  147749. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  147750. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  147751. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  147752. 12,
  147753. };
  147754. static float _vq_quantthresh__44un1__p4_0[] = {
  147755. -1.5, -0.5, 0.5, 1.5,
  147756. };
  147757. static long _vq_quantmap__44un1__p4_0[] = {
  147758. 3, 1, 0, 2, 4,
  147759. };
  147760. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  147761. _vq_quantthresh__44un1__p4_0,
  147762. _vq_quantmap__44un1__p4_0,
  147763. 5,
  147764. 5
  147765. };
  147766. static static_codebook _44un1__p4_0 = {
  147767. 4, 625,
  147768. _vq_lengthlist__44un1__p4_0,
  147769. 1, -533725184, 1611661312, 3, 0,
  147770. _vq_quantlist__44un1__p4_0,
  147771. NULL,
  147772. &_vq_auxt__44un1__p4_0,
  147773. NULL,
  147774. 0
  147775. };
  147776. static long _vq_quantlist__44un1__p5_0[] = {
  147777. 4,
  147778. 3,
  147779. 5,
  147780. 2,
  147781. 6,
  147782. 1,
  147783. 7,
  147784. 0,
  147785. 8,
  147786. };
  147787. static long _vq_lengthlist__44un1__p5_0[] = {
  147788. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  147789. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  147790. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  147791. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  147792. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  147793. 12,
  147794. };
  147795. static float _vq_quantthresh__44un1__p5_0[] = {
  147796. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147797. };
  147798. static long _vq_quantmap__44un1__p5_0[] = {
  147799. 7, 5, 3, 1, 0, 2, 4, 6,
  147800. 8,
  147801. };
  147802. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  147803. _vq_quantthresh__44un1__p5_0,
  147804. _vq_quantmap__44un1__p5_0,
  147805. 9,
  147806. 9
  147807. };
  147808. static static_codebook _44un1__p5_0 = {
  147809. 2, 81,
  147810. _vq_lengthlist__44un1__p5_0,
  147811. 1, -531628032, 1611661312, 4, 0,
  147812. _vq_quantlist__44un1__p5_0,
  147813. NULL,
  147814. &_vq_auxt__44un1__p5_0,
  147815. NULL,
  147816. 0
  147817. };
  147818. static long _vq_quantlist__44un1__p6_0[] = {
  147819. 6,
  147820. 5,
  147821. 7,
  147822. 4,
  147823. 8,
  147824. 3,
  147825. 9,
  147826. 2,
  147827. 10,
  147828. 1,
  147829. 11,
  147830. 0,
  147831. 12,
  147832. };
  147833. static long _vq_lengthlist__44un1__p6_0[] = {
  147834. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  147835. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  147836. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  147837. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  147838. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  147839. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  147840. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  147841. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  147842. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  147843. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  147844. 16, 0,15,18,18, 0,16, 0, 0,
  147845. };
  147846. static float _vq_quantthresh__44un1__p6_0[] = {
  147847. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147848. 12.5, 17.5, 22.5, 27.5,
  147849. };
  147850. static long _vq_quantmap__44un1__p6_0[] = {
  147851. 11, 9, 7, 5, 3, 1, 0, 2,
  147852. 4, 6, 8, 10, 12,
  147853. };
  147854. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  147855. _vq_quantthresh__44un1__p6_0,
  147856. _vq_quantmap__44un1__p6_0,
  147857. 13,
  147858. 13
  147859. };
  147860. static static_codebook _44un1__p6_0 = {
  147861. 2, 169,
  147862. _vq_lengthlist__44un1__p6_0,
  147863. 1, -526516224, 1616117760, 4, 0,
  147864. _vq_quantlist__44un1__p6_0,
  147865. NULL,
  147866. &_vq_auxt__44un1__p6_0,
  147867. NULL,
  147868. 0
  147869. };
  147870. static long _vq_quantlist__44un1__p6_1[] = {
  147871. 2,
  147872. 1,
  147873. 3,
  147874. 0,
  147875. 4,
  147876. };
  147877. static long _vq_lengthlist__44un1__p6_1[] = {
  147878. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  147879. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  147880. };
  147881. static float _vq_quantthresh__44un1__p6_1[] = {
  147882. -1.5, -0.5, 0.5, 1.5,
  147883. };
  147884. static long _vq_quantmap__44un1__p6_1[] = {
  147885. 3, 1, 0, 2, 4,
  147886. };
  147887. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  147888. _vq_quantthresh__44un1__p6_1,
  147889. _vq_quantmap__44un1__p6_1,
  147890. 5,
  147891. 5
  147892. };
  147893. static static_codebook _44un1__p6_1 = {
  147894. 2, 25,
  147895. _vq_lengthlist__44un1__p6_1,
  147896. 1, -533725184, 1611661312, 3, 0,
  147897. _vq_quantlist__44un1__p6_1,
  147898. NULL,
  147899. &_vq_auxt__44un1__p6_1,
  147900. NULL,
  147901. 0
  147902. };
  147903. static long _vq_quantlist__44un1__p7_0[] = {
  147904. 2,
  147905. 1,
  147906. 3,
  147907. 0,
  147908. 4,
  147909. };
  147910. static long _vq_lengthlist__44un1__p7_0[] = {
  147911. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  147912. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  147913. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147914. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147915. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147916. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147917. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147918. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  147919. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147920. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147921. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  147922. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147923. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147924. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147925. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147926. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  147927. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147928. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  147929. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147930. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147931. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147932. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147933. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147934. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147935. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147936. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147937. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147938. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147939. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147940. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147941. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147942. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147943. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147944. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147945. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147946. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147947. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147948. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147949. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147950. 10,
  147951. };
  147952. static float _vq_quantthresh__44un1__p7_0[] = {
  147953. -253.5, -84.5, 84.5, 253.5,
  147954. };
  147955. static long _vq_quantmap__44un1__p7_0[] = {
  147956. 3, 1, 0, 2, 4,
  147957. };
  147958. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  147959. _vq_quantthresh__44un1__p7_0,
  147960. _vq_quantmap__44un1__p7_0,
  147961. 5,
  147962. 5
  147963. };
  147964. static static_codebook _44un1__p7_0 = {
  147965. 4, 625,
  147966. _vq_lengthlist__44un1__p7_0,
  147967. 1, -518709248, 1626677248, 3, 0,
  147968. _vq_quantlist__44un1__p7_0,
  147969. NULL,
  147970. &_vq_auxt__44un1__p7_0,
  147971. NULL,
  147972. 0
  147973. };
  147974. static long _vq_quantlist__44un1__p7_1[] = {
  147975. 6,
  147976. 5,
  147977. 7,
  147978. 4,
  147979. 8,
  147980. 3,
  147981. 9,
  147982. 2,
  147983. 10,
  147984. 1,
  147985. 11,
  147986. 0,
  147987. 12,
  147988. };
  147989. static long _vq_lengthlist__44un1__p7_1[] = {
  147990. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  147991. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  147992. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  147993. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  147994. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  147995. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  147996. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  147997. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  147998. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  147999. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  148000. 12,13,13,12,13,13,14,14,14,
  148001. };
  148002. static float _vq_quantthresh__44un1__p7_1[] = {
  148003. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  148004. 32.5, 45.5, 58.5, 71.5,
  148005. };
  148006. static long _vq_quantmap__44un1__p7_1[] = {
  148007. 11, 9, 7, 5, 3, 1, 0, 2,
  148008. 4, 6, 8, 10, 12,
  148009. };
  148010. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  148011. _vq_quantthresh__44un1__p7_1,
  148012. _vq_quantmap__44un1__p7_1,
  148013. 13,
  148014. 13
  148015. };
  148016. static static_codebook _44un1__p7_1 = {
  148017. 2, 169,
  148018. _vq_lengthlist__44un1__p7_1,
  148019. 1, -523010048, 1618608128, 4, 0,
  148020. _vq_quantlist__44un1__p7_1,
  148021. NULL,
  148022. &_vq_auxt__44un1__p7_1,
  148023. NULL,
  148024. 0
  148025. };
  148026. static long _vq_quantlist__44un1__p7_2[] = {
  148027. 6,
  148028. 5,
  148029. 7,
  148030. 4,
  148031. 8,
  148032. 3,
  148033. 9,
  148034. 2,
  148035. 10,
  148036. 1,
  148037. 11,
  148038. 0,
  148039. 12,
  148040. };
  148041. static long _vq_lengthlist__44un1__p7_2[] = {
  148042. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  148043. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  148044. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  148045. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  148046. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  148047. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  148048. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  148049. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  148050. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  148051. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  148052. 9, 9, 9,10,10,10,10,10,10,
  148053. };
  148054. static float _vq_quantthresh__44un1__p7_2[] = {
  148055. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  148056. 2.5, 3.5, 4.5, 5.5,
  148057. };
  148058. static long _vq_quantmap__44un1__p7_2[] = {
  148059. 11, 9, 7, 5, 3, 1, 0, 2,
  148060. 4, 6, 8, 10, 12,
  148061. };
  148062. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  148063. _vq_quantthresh__44un1__p7_2,
  148064. _vq_quantmap__44un1__p7_2,
  148065. 13,
  148066. 13
  148067. };
  148068. static static_codebook _44un1__p7_2 = {
  148069. 2, 169,
  148070. _vq_lengthlist__44un1__p7_2,
  148071. 1, -531103744, 1611661312, 4, 0,
  148072. _vq_quantlist__44un1__p7_2,
  148073. NULL,
  148074. &_vq_auxt__44un1__p7_2,
  148075. NULL,
  148076. 0
  148077. };
  148078. static long _huff_lengthlist__44un1__short[] = {
  148079. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  148080. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  148081. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  148082. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  148083. };
  148084. static static_codebook _huff_book__44un1__short = {
  148085. 2, 64,
  148086. _huff_lengthlist__44un1__short,
  148087. 0, 0, 0, 0, 0,
  148088. NULL,
  148089. NULL,
  148090. NULL,
  148091. NULL,
  148092. 0
  148093. };
  148094. /********* End of inlined file: res_books_uncoupled.h *********/
  148095. /***** residue backends *********************************************/
  148096. static vorbis_info_residue0 _residue_44_low_un={
  148097. 0,-1, -1, 8,-1,
  148098. {0},
  148099. {-1},
  148100. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  148101. { -1, 25, -1, 45, -1, -1, -1}
  148102. };
  148103. static vorbis_info_residue0 _residue_44_mid_un={
  148104. 0,-1, -1, 10,-1,
  148105. /* 0 1 2 3 4 5 6 7 8 9 */
  148106. {0},
  148107. {-1},
  148108. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  148109. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  148110. };
  148111. static vorbis_info_residue0 _residue_44_hi_un={
  148112. 0,-1, -1, 10,-1,
  148113. /* 0 1 2 3 4 5 6 7 8 9 */
  148114. {0},
  148115. {-1},
  148116. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  148117. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  148118. };
  148119. /* mapping conventions:
  148120. only one submap (this would change for efficient 5.1 support for example)*/
  148121. /* Four psychoacoustic profiles are used, one for each blocktype */
  148122. static vorbis_info_mapping0 _map_nominal_u[2]={
  148123. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  148124. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  148125. };
  148126. static static_bookblock _resbook_44u_n1={
  148127. {
  148128. {0},
  148129. {0,0,&_44un1__p1_0},
  148130. {0,0,&_44un1__p2_0},
  148131. {0,0,&_44un1__p3_0},
  148132. {0,0,&_44un1__p4_0},
  148133. {0,0,&_44un1__p5_0},
  148134. {&_44un1__p6_0,&_44un1__p6_1},
  148135. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  148136. }
  148137. };
  148138. static static_bookblock _resbook_44u_0={
  148139. {
  148140. {0},
  148141. {0,0,&_44u0__p1_0},
  148142. {0,0,&_44u0__p2_0},
  148143. {0,0,&_44u0__p3_0},
  148144. {0,0,&_44u0__p4_0},
  148145. {0,0,&_44u0__p5_0},
  148146. {&_44u0__p6_0,&_44u0__p6_1},
  148147. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  148148. }
  148149. };
  148150. static static_bookblock _resbook_44u_1={
  148151. {
  148152. {0},
  148153. {0,0,&_44u1__p1_0},
  148154. {0,0,&_44u1__p2_0},
  148155. {0,0,&_44u1__p3_0},
  148156. {0,0,&_44u1__p4_0},
  148157. {0,0,&_44u1__p5_0},
  148158. {&_44u1__p6_0,&_44u1__p6_1},
  148159. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  148160. }
  148161. };
  148162. static static_bookblock _resbook_44u_2={
  148163. {
  148164. {0},
  148165. {0,0,&_44u2__p1_0},
  148166. {0,0,&_44u2__p2_0},
  148167. {0,0,&_44u2__p3_0},
  148168. {0,0,&_44u2__p4_0},
  148169. {0,0,&_44u2__p5_0},
  148170. {&_44u2__p6_0,&_44u2__p6_1},
  148171. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  148172. }
  148173. };
  148174. static static_bookblock _resbook_44u_3={
  148175. {
  148176. {0},
  148177. {0,0,&_44u3__p1_0},
  148178. {0,0,&_44u3__p2_0},
  148179. {0,0,&_44u3__p3_0},
  148180. {0,0,&_44u3__p4_0},
  148181. {0,0,&_44u3__p5_0},
  148182. {&_44u3__p6_0,&_44u3__p6_1},
  148183. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  148184. }
  148185. };
  148186. static static_bookblock _resbook_44u_4={
  148187. {
  148188. {0},
  148189. {0,0,&_44u4__p1_0},
  148190. {0,0,&_44u4__p2_0},
  148191. {0,0,&_44u4__p3_0},
  148192. {0,0,&_44u4__p4_0},
  148193. {0,0,&_44u4__p5_0},
  148194. {&_44u4__p6_0,&_44u4__p6_1},
  148195. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  148196. }
  148197. };
  148198. static static_bookblock _resbook_44u_5={
  148199. {
  148200. {0},
  148201. {0,0,&_44u5__p1_0},
  148202. {0,0,&_44u5__p2_0},
  148203. {0,0,&_44u5__p3_0},
  148204. {0,0,&_44u5__p4_0},
  148205. {0,0,&_44u5__p5_0},
  148206. {0,0,&_44u5__p6_0},
  148207. {&_44u5__p7_0,&_44u5__p7_1},
  148208. {&_44u5__p8_0,&_44u5__p8_1},
  148209. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  148210. }
  148211. };
  148212. static static_bookblock _resbook_44u_6={
  148213. {
  148214. {0},
  148215. {0,0,&_44u6__p1_0},
  148216. {0,0,&_44u6__p2_0},
  148217. {0,0,&_44u6__p3_0},
  148218. {0,0,&_44u6__p4_0},
  148219. {0,0,&_44u6__p5_0},
  148220. {0,0,&_44u6__p6_0},
  148221. {&_44u6__p7_0,&_44u6__p7_1},
  148222. {&_44u6__p8_0,&_44u6__p8_1},
  148223. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  148224. }
  148225. };
  148226. static static_bookblock _resbook_44u_7={
  148227. {
  148228. {0},
  148229. {0,0,&_44u7__p1_0},
  148230. {0,0,&_44u7__p2_0},
  148231. {0,0,&_44u7__p3_0},
  148232. {0,0,&_44u7__p4_0},
  148233. {0,0,&_44u7__p5_0},
  148234. {0,0,&_44u7__p6_0},
  148235. {&_44u7__p7_0,&_44u7__p7_1},
  148236. {&_44u7__p8_0,&_44u7__p8_1},
  148237. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  148238. }
  148239. };
  148240. static static_bookblock _resbook_44u_8={
  148241. {
  148242. {0},
  148243. {0,0,&_44u8_p1_0},
  148244. {0,0,&_44u8_p2_0},
  148245. {0,0,&_44u8_p3_0},
  148246. {0,0,&_44u8_p4_0},
  148247. {&_44u8_p5_0,&_44u8_p5_1},
  148248. {&_44u8_p6_0,&_44u8_p6_1},
  148249. {&_44u8_p7_0,&_44u8_p7_1},
  148250. {&_44u8_p8_0,&_44u8_p8_1},
  148251. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  148252. }
  148253. };
  148254. static static_bookblock _resbook_44u_9={
  148255. {
  148256. {0},
  148257. {0,0,&_44u9_p1_0},
  148258. {0,0,&_44u9_p2_0},
  148259. {0,0,&_44u9_p3_0},
  148260. {0,0,&_44u9_p4_0},
  148261. {&_44u9_p5_0,&_44u9_p5_1},
  148262. {&_44u9_p6_0,&_44u9_p6_1},
  148263. {&_44u9_p7_0,&_44u9_p7_1},
  148264. {&_44u9_p8_0,&_44u9_p8_1},
  148265. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  148266. }
  148267. };
  148268. static vorbis_residue_template _res_44u_n1[]={
  148269. {1,0, &_residue_44_low_un,
  148270. &_huff_book__44un1__short,&_huff_book__44un1__short,
  148271. &_resbook_44u_n1,&_resbook_44u_n1},
  148272. {1,0, &_residue_44_low_un,
  148273. &_huff_book__44un1__long,&_huff_book__44un1__long,
  148274. &_resbook_44u_n1,&_resbook_44u_n1}
  148275. };
  148276. static vorbis_residue_template _res_44u_0[]={
  148277. {1,0, &_residue_44_low_un,
  148278. &_huff_book__44u0__short,&_huff_book__44u0__short,
  148279. &_resbook_44u_0,&_resbook_44u_0},
  148280. {1,0, &_residue_44_low_un,
  148281. &_huff_book__44u0__long,&_huff_book__44u0__long,
  148282. &_resbook_44u_0,&_resbook_44u_0}
  148283. };
  148284. static vorbis_residue_template _res_44u_1[]={
  148285. {1,0, &_residue_44_low_un,
  148286. &_huff_book__44u1__short,&_huff_book__44u1__short,
  148287. &_resbook_44u_1,&_resbook_44u_1},
  148288. {1,0, &_residue_44_low_un,
  148289. &_huff_book__44u1__long,&_huff_book__44u1__long,
  148290. &_resbook_44u_1,&_resbook_44u_1}
  148291. };
  148292. static vorbis_residue_template _res_44u_2[]={
  148293. {1,0, &_residue_44_low_un,
  148294. &_huff_book__44u2__short,&_huff_book__44u2__short,
  148295. &_resbook_44u_2,&_resbook_44u_2},
  148296. {1,0, &_residue_44_low_un,
  148297. &_huff_book__44u2__long,&_huff_book__44u2__long,
  148298. &_resbook_44u_2,&_resbook_44u_2}
  148299. };
  148300. static vorbis_residue_template _res_44u_3[]={
  148301. {1,0, &_residue_44_low_un,
  148302. &_huff_book__44u3__short,&_huff_book__44u3__short,
  148303. &_resbook_44u_3,&_resbook_44u_3},
  148304. {1,0, &_residue_44_low_un,
  148305. &_huff_book__44u3__long,&_huff_book__44u3__long,
  148306. &_resbook_44u_3,&_resbook_44u_3}
  148307. };
  148308. static vorbis_residue_template _res_44u_4[]={
  148309. {1,0, &_residue_44_low_un,
  148310. &_huff_book__44u4__short,&_huff_book__44u4__short,
  148311. &_resbook_44u_4,&_resbook_44u_4},
  148312. {1,0, &_residue_44_low_un,
  148313. &_huff_book__44u4__long,&_huff_book__44u4__long,
  148314. &_resbook_44u_4,&_resbook_44u_4}
  148315. };
  148316. static vorbis_residue_template _res_44u_5[]={
  148317. {1,0, &_residue_44_mid_un,
  148318. &_huff_book__44u5__short,&_huff_book__44u5__short,
  148319. &_resbook_44u_5,&_resbook_44u_5},
  148320. {1,0, &_residue_44_mid_un,
  148321. &_huff_book__44u5__long,&_huff_book__44u5__long,
  148322. &_resbook_44u_5,&_resbook_44u_5}
  148323. };
  148324. static vorbis_residue_template _res_44u_6[]={
  148325. {1,0, &_residue_44_mid_un,
  148326. &_huff_book__44u6__short,&_huff_book__44u6__short,
  148327. &_resbook_44u_6,&_resbook_44u_6},
  148328. {1,0, &_residue_44_mid_un,
  148329. &_huff_book__44u6__long,&_huff_book__44u6__long,
  148330. &_resbook_44u_6,&_resbook_44u_6}
  148331. };
  148332. static vorbis_residue_template _res_44u_7[]={
  148333. {1,0, &_residue_44_mid_un,
  148334. &_huff_book__44u7__short,&_huff_book__44u7__short,
  148335. &_resbook_44u_7,&_resbook_44u_7},
  148336. {1,0, &_residue_44_mid_un,
  148337. &_huff_book__44u7__long,&_huff_book__44u7__long,
  148338. &_resbook_44u_7,&_resbook_44u_7}
  148339. };
  148340. static vorbis_residue_template _res_44u_8[]={
  148341. {1,0, &_residue_44_hi_un,
  148342. &_huff_book__44u8__short,&_huff_book__44u8__short,
  148343. &_resbook_44u_8,&_resbook_44u_8},
  148344. {1,0, &_residue_44_hi_un,
  148345. &_huff_book__44u8__long,&_huff_book__44u8__long,
  148346. &_resbook_44u_8,&_resbook_44u_8}
  148347. };
  148348. static vorbis_residue_template _res_44u_9[]={
  148349. {1,0, &_residue_44_hi_un,
  148350. &_huff_book__44u9__short,&_huff_book__44u9__short,
  148351. &_resbook_44u_9,&_resbook_44u_9},
  148352. {1,0, &_residue_44_hi_un,
  148353. &_huff_book__44u9__long,&_huff_book__44u9__long,
  148354. &_resbook_44u_9,&_resbook_44u_9}
  148355. };
  148356. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  148357. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  148358. { _map_nominal_u, _res_44u_0 }, /* 0 */
  148359. { _map_nominal_u, _res_44u_1 }, /* 1 */
  148360. { _map_nominal_u, _res_44u_2 }, /* 2 */
  148361. { _map_nominal_u, _res_44u_3 }, /* 3 */
  148362. { _map_nominal_u, _res_44u_4 }, /* 4 */
  148363. { _map_nominal_u, _res_44u_5 }, /* 5 */
  148364. { _map_nominal_u, _res_44u_6 }, /* 6 */
  148365. { _map_nominal_u, _res_44u_7 }, /* 7 */
  148366. { _map_nominal_u, _res_44u_8 }, /* 8 */
  148367. { _map_nominal_u, _res_44u_9 }, /* 9 */
  148368. };
  148369. /********* End of inlined file: residue_44u.h *********/
  148370. static double rate_mapping_44_un[12]={
  148371. 32000.,48000.,60000.,70000.,80000.,86000.,
  148372. 96000.,110000.,120000.,140000.,160000.,240001.
  148373. };
  148374. ve_setup_data_template ve_setup_44_uncoupled={
  148375. 11,
  148376. rate_mapping_44_un,
  148377. quality_mapping_44,
  148378. -1,
  148379. 40000,
  148380. 50000,
  148381. blocksize_short_44,
  148382. blocksize_long_44,
  148383. _psy_tone_masteratt_44,
  148384. _psy_tone_0dB,
  148385. _psy_tone_suppress,
  148386. _vp_tonemask_adj_otherblock,
  148387. _vp_tonemask_adj_longblock,
  148388. _vp_tonemask_adj_otherblock,
  148389. _psy_noiseguards_44,
  148390. _psy_noisebias_impulse,
  148391. _psy_noisebias_padding,
  148392. _psy_noisebias_trans,
  148393. _psy_noisebias_long,
  148394. _psy_noise_suppress,
  148395. _psy_compand_44,
  148396. _psy_compand_short_mapping,
  148397. _psy_compand_long_mapping,
  148398. {_noise_start_short_44,_noise_start_long_44},
  148399. {_noise_part_short_44,_noise_part_long_44},
  148400. _noise_thresh_44,
  148401. _psy_ath_floater,
  148402. _psy_ath_abs,
  148403. _psy_lowpass_44,
  148404. _psy_global_44,
  148405. _global_mapping_44,
  148406. NULL,
  148407. _floor_books,
  148408. _floor,
  148409. _floor_short_mapping_44,
  148410. _floor_long_mapping_44,
  148411. _mapres_template_44_uncoupled
  148412. };
  148413. /********* End of inlined file: setup_44u.h *********/
  148414. /********* Start of inlined file: setup_32.h *********/
  148415. static double rate_mapping_32[12]={
  148416. 18000.,28000.,35000.,45000.,56000.,60000.,
  148417. 75000.,90000.,100000.,115000.,150000.,190000.,
  148418. };
  148419. static double rate_mapping_32_un[12]={
  148420. 30000.,42000.,52000.,64000.,72000.,78000.,
  148421. 86000.,92000.,110000.,120000.,140000.,190000.,
  148422. };
  148423. static double _psy_lowpass_32[12]={
  148424. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  148425. };
  148426. ve_setup_data_template ve_setup_32_stereo={
  148427. 11,
  148428. rate_mapping_32,
  148429. quality_mapping_44,
  148430. 2,
  148431. 26000,
  148432. 40000,
  148433. blocksize_short_44,
  148434. blocksize_long_44,
  148435. _psy_tone_masteratt_44,
  148436. _psy_tone_0dB,
  148437. _psy_tone_suppress,
  148438. _vp_tonemask_adj_otherblock,
  148439. _vp_tonemask_adj_longblock,
  148440. _vp_tonemask_adj_otherblock,
  148441. _psy_noiseguards_44,
  148442. _psy_noisebias_impulse,
  148443. _psy_noisebias_padding,
  148444. _psy_noisebias_trans,
  148445. _psy_noisebias_long,
  148446. _psy_noise_suppress,
  148447. _psy_compand_44,
  148448. _psy_compand_short_mapping,
  148449. _psy_compand_long_mapping,
  148450. {_noise_start_short_44,_noise_start_long_44},
  148451. {_noise_part_short_44,_noise_part_long_44},
  148452. _noise_thresh_44,
  148453. _psy_ath_floater,
  148454. _psy_ath_abs,
  148455. _psy_lowpass_32,
  148456. _psy_global_44,
  148457. _global_mapping_44,
  148458. _psy_stereo_modes_44,
  148459. _floor_books,
  148460. _floor,
  148461. _floor_short_mapping_44,
  148462. _floor_long_mapping_44,
  148463. _mapres_template_44_stereo
  148464. };
  148465. ve_setup_data_template ve_setup_32_uncoupled={
  148466. 11,
  148467. rate_mapping_32_un,
  148468. quality_mapping_44,
  148469. -1,
  148470. 26000,
  148471. 40000,
  148472. blocksize_short_44,
  148473. blocksize_long_44,
  148474. _psy_tone_masteratt_44,
  148475. _psy_tone_0dB,
  148476. _psy_tone_suppress,
  148477. _vp_tonemask_adj_otherblock,
  148478. _vp_tonemask_adj_longblock,
  148479. _vp_tonemask_adj_otherblock,
  148480. _psy_noiseguards_44,
  148481. _psy_noisebias_impulse,
  148482. _psy_noisebias_padding,
  148483. _psy_noisebias_trans,
  148484. _psy_noisebias_long,
  148485. _psy_noise_suppress,
  148486. _psy_compand_44,
  148487. _psy_compand_short_mapping,
  148488. _psy_compand_long_mapping,
  148489. {_noise_start_short_44,_noise_start_long_44},
  148490. {_noise_part_short_44,_noise_part_long_44},
  148491. _noise_thresh_44,
  148492. _psy_ath_floater,
  148493. _psy_ath_abs,
  148494. _psy_lowpass_32,
  148495. _psy_global_44,
  148496. _global_mapping_44,
  148497. NULL,
  148498. _floor_books,
  148499. _floor,
  148500. _floor_short_mapping_44,
  148501. _floor_long_mapping_44,
  148502. _mapres_template_44_uncoupled
  148503. };
  148504. /********* End of inlined file: setup_32.h *********/
  148505. /********* Start of inlined file: setup_8.h *********/
  148506. /********* Start of inlined file: psych_8.h *********/
  148507. static att3 _psy_tone_masteratt_8[3]={
  148508. {{ 32, 25, 12}, 0, 0}, /* 0 */
  148509. {{ 30, 25, 12}, 0, 0}, /* 0 */
  148510. {{ 20, 0, -14}, 0, 0}, /* 0 */
  148511. };
  148512. static vp_adjblock _vp_tonemask_adj_8[3]={
  148513. /* adjust for mode zero */
  148514. /* 63 125 250 500 1 2 4 8 16 */
  148515. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  148516. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  148517. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  148518. };
  148519. static noise3 _psy_noisebias_8[3]={
  148520. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148521. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  148522. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  148523. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  148524. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  148525. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  148526. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  148527. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  148528. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  148529. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  148530. };
  148531. /* stereo mode by base quality level */
  148532. static adj_stereo _psy_stereo_modes_8[3]={
  148533. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  148534. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148535. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148536. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  148537. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148538. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148539. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148540. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  148541. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148542. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148543. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148544. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  148545. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148546. };
  148547. static noiseguard _psy_noiseguards_8[2]={
  148548. {10,10,-1},
  148549. {10,10,-1},
  148550. };
  148551. static compandblock _psy_compand_8[2]={
  148552. {{
  148553. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  148554. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  148555. 12,12,13,13,14,14,15, 15, /* 23dB */
  148556. 16,16,17,17,17,18,18, 19, /* 31dB */
  148557. 19,19,20,21,22,23,24, 25, /* 39dB */
  148558. }},
  148559. {{
  148560. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  148561. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  148562. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  148563. 9,10,11,12,13,14,15, 16, /* 31dB */
  148564. 17,18,19,20,21,22,23, 24, /* 39dB */
  148565. }},
  148566. };
  148567. static double _psy_lowpass_8[3]={3.,4.,4.};
  148568. static int _noise_start_8[2]={
  148569. 64,64,
  148570. };
  148571. static int _noise_part_8[2]={
  148572. 8,8,
  148573. };
  148574. static int _psy_ath_floater_8[3]={
  148575. -100,-100,-105,
  148576. };
  148577. static int _psy_ath_abs_8[3]={
  148578. -130,-130,-140,
  148579. };
  148580. /********* End of inlined file: psych_8.h *********/
  148581. /********* Start of inlined file: residue_8.h *********/
  148582. /***** residue backends *********************************************/
  148583. static static_bookblock _resbook_8s_0={
  148584. {
  148585. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  148586. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  148587. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  148588. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  148589. }
  148590. };
  148591. static static_bookblock _resbook_8s_1={
  148592. {
  148593. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  148594. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  148595. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  148596. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  148597. }
  148598. };
  148599. static vorbis_residue_template _res_8s_0[]={
  148600. {2,0, &_residue_44_mid,
  148601. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  148602. &_resbook_8s_0,&_resbook_8s_0},
  148603. };
  148604. static vorbis_residue_template _res_8s_1[]={
  148605. {2,0, &_residue_44_mid,
  148606. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  148607. &_resbook_8s_1,&_resbook_8s_1},
  148608. };
  148609. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  148610. { _map_nominal, _res_8s_0 }, /* 0 */
  148611. { _map_nominal, _res_8s_1 }, /* 1 */
  148612. };
  148613. static static_bookblock _resbook_8u_0={
  148614. {
  148615. {0},
  148616. {0,0,&_8u0__p1_0},
  148617. {0,0,&_8u0__p2_0},
  148618. {0,0,&_8u0__p3_0},
  148619. {0,0,&_8u0__p4_0},
  148620. {0,0,&_8u0__p5_0},
  148621. {&_8u0__p6_0,&_8u0__p6_1},
  148622. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  148623. }
  148624. };
  148625. static static_bookblock _resbook_8u_1={
  148626. {
  148627. {0},
  148628. {0,0,&_8u1__p1_0},
  148629. {0,0,&_8u1__p2_0},
  148630. {0,0,&_8u1__p3_0},
  148631. {0,0,&_8u1__p4_0},
  148632. {0,0,&_8u1__p5_0},
  148633. {0,0,&_8u1__p6_0},
  148634. {&_8u1__p7_0,&_8u1__p7_1},
  148635. {&_8u1__p8_0,&_8u1__p8_1},
  148636. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  148637. }
  148638. };
  148639. static vorbis_residue_template _res_8u_0[]={
  148640. {1,0, &_residue_44_low_un,
  148641. &_huff_book__8u0__single,&_huff_book__8u0__single,
  148642. &_resbook_8u_0,&_resbook_8u_0},
  148643. };
  148644. static vorbis_residue_template _res_8u_1[]={
  148645. {1,0, &_residue_44_mid_un,
  148646. &_huff_book__8u1__single,&_huff_book__8u1__single,
  148647. &_resbook_8u_1,&_resbook_8u_1},
  148648. };
  148649. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  148650. { _map_nominal_u, _res_8u_0 }, /* 0 */
  148651. { _map_nominal_u, _res_8u_1 }, /* 1 */
  148652. };
  148653. /********* End of inlined file: residue_8.h *********/
  148654. static int blocksize_8[2]={
  148655. 512,512
  148656. };
  148657. static int _floor_mapping_8[2]={
  148658. 6,6,
  148659. };
  148660. static double rate_mapping_8[3]={
  148661. 6000.,9000.,32000.,
  148662. };
  148663. static double rate_mapping_8_uncoupled[3]={
  148664. 8000.,14000.,42000.,
  148665. };
  148666. static double quality_mapping_8[3]={
  148667. -.1,.0,1.
  148668. };
  148669. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  148670. static double _global_mapping_8[3]={ 1., 2., 3. };
  148671. ve_setup_data_template ve_setup_8_stereo={
  148672. 2,
  148673. rate_mapping_8,
  148674. quality_mapping_8,
  148675. 2,
  148676. 8000,
  148677. 9000,
  148678. blocksize_8,
  148679. blocksize_8,
  148680. _psy_tone_masteratt_8,
  148681. _psy_tone_0dB,
  148682. _psy_tone_suppress,
  148683. _vp_tonemask_adj_8,
  148684. NULL,
  148685. _vp_tonemask_adj_8,
  148686. _psy_noiseguards_8,
  148687. _psy_noisebias_8,
  148688. _psy_noisebias_8,
  148689. NULL,
  148690. NULL,
  148691. _psy_noise_suppress,
  148692. _psy_compand_8,
  148693. _psy_compand_8_mapping,
  148694. NULL,
  148695. {_noise_start_8,_noise_start_8},
  148696. {_noise_part_8,_noise_part_8},
  148697. _noise_thresh_5only,
  148698. _psy_ath_floater_8,
  148699. _psy_ath_abs_8,
  148700. _psy_lowpass_8,
  148701. _psy_global_44,
  148702. _global_mapping_8,
  148703. _psy_stereo_modes_8,
  148704. _floor_books,
  148705. _floor,
  148706. _floor_mapping_8,
  148707. NULL,
  148708. _mapres_template_8_stereo
  148709. };
  148710. ve_setup_data_template ve_setup_8_uncoupled={
  148711. 2,
  148712. rate_mapping_8_uncoupled,
  148713. quality_mapping_8,
  148714. -1,
  148715. 8000,
  148716. 9000,
  148717. blocksize_8,
  148718. blocksize_8,
  148719. _psy_tone_masteratt_8,
  148720. _psy_tone_0dB,
  148721. _psy_tone_suppress,
  148722. _vp_tonemask_adj_8,
  148723. NULL,
  148724. _vp_tonemask_adj_8,
  148725. _psy_noiseguards_8,
  148726. _psy_noisebias_8,
  148727. _psy_noisebias_8,
  148728. NULL,
  148729. NULL,
  148730. _psy_noise_suppress,
  148731. _psy_compand_8,
  148732. _psy_compand_8_mapping,
  148733. NULL,
  148734. {_noise_start_8,_noise_start_8},
  148735. {_noise_part_8,_noise_part_8},
  148736. _noise_thresh_5only,
  148737. _psy_ath_floater_8,
  148738. _psy_ath_abs_8,
  148739. _psy_lowpass_8,
  148740. _psy_global_44,
  148741. _global_mapping_8,
  148742. _psy_stereo_modes_8,
  148743. _floor_books,
  148744. _floor,
  148745. _floor_mapping_8,
  148746. NULL,
  148747. _mapres_template_8_uncoupled
  148748. };
  148749. /********* End of inlined file: setup_8.h *********/
  148750. /********* Start of inlined file: setup_11.h *********/
  148751. /********* Start of inlined file: psych_11.h *********/
  148752. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  148753. static att3 _psy_tone_masteratt_11[3]={
  148754. {{ 30, 25, 12}, 0, 0}, /* 0 */
  148755. {{ 30, 25, 12}, 0, 0}, /* 0 */
  148756. {{ 20, 0, -14}, 0, 0}, /* 0 */
  148757. };
  148758. static vp_adjblock _vp_tonemask_adj_11[3]={
  148759. /* adjust for mode zero */
  148760. /* 63 125 250 500 1 2 4 8 16 */
  148761. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  148762. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  148763. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  148764. };
  148765. static noise3 _psy_noisebias_11[3]={
  148766. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148767. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  148768. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  148769. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  148770. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  148771. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  148772. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  148773. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  148774. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  148775. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  148776. };
  148777. static double _noise_thresh_11[3]={ .3,.5,.5 };
  148778. /********* End of inlined file: psych_11.h *********/
  148779. static int blocksize_11[2]={
  148780. 512,512
  148781. };
  148782. static int _floor_mapping_11[2]={
  148783. 6,6,
  148784. };
  148785. static double rate_mapping_11[3]={
  148786. 8000.,13000.,44000.,
  148787. };
  148788. static double rate_mapping_11_uncoupled[3]={
  148789. 12000.,20000.,50000.,
  148790. };
  148791. static double quality_mapping_11[3]={
  148792. -.1,.0,1.
  148793. };
  148794. ve_setup_data_template ve_setup_11_stereo={
  148795. 2,
  148796. rate_mapping_11,
  148797. quality_mapping_11,
  148798. 2,
  148799. 9000,
  148800. 15000,
  148801. blocksize_11,
  148802. blocksize_11,
  148803. _psy_tone_masteratt_11,
  148804. _psy_tone_0dB,
  148805. _psy_tone_suppress,
  148806. _vp_tonemask_adj_11,
  148807. NULL,
  148808. _vp_tonemask_adj_11,
  148809. _psy_noiseguards_8,
  148810. _psy_noisebias_11,
  148811. _psy_noisebias_11,
  148812. NULL,
  148813. NULL,
  148814. _psy_noise_suppress,
  148815. _psy_compand_8,
  148816. _psy_compand_8_mapping,
  148817. NULL,
  148818. {_noise_start_8,_noise_start_8},
  148819. {_noise_part_8,_noise_part_8},
  148820. _noise_thresh_11,
  148821. _psy_ath_floater_8,
  148822. _psy_ath_abs_8,
  148823. _psy_lowpass_11,
  148824. _psy_global_44,
  148825. _global_mapping_8,
  148826. _psy_stereo_modes_8,
  148827. _floor_books,
  148828. _floor,
  148829. _floor_mapping_11,
  148830. NULL,
  148831. _mapres_template_8_stereo
  148832. };
  148833. ve_setup_data_template ve_setup_11_uncoupled={
  148834. 2,
  148835. rate_mapping_11_uncoupled,
  148836. quality_mapping_11,
  148837. -1,
  148838. 9000,
  148839. 15000,
  148840. blocksize_11,
  148841. blocksize_11,
  148842. _psy_tone_masteratt_11,
  148843. _psy_tone_0dB,
  148844. _psy_tone_suppress,
  148845. _vp_tonemask_adj_11,
  148846. NULL,
  148847. _vp_tonemask_adj_11,
  148848. _psy_noiseguards_8,
  148849. _psy_noisebias_11,
  148850. _psy_noisebias_11,
  148851. NULL,
  148852. NULL,
  148853. _psy_noise_suppress,
  148854. _psy_compand_8,
  148855. _psy_compand_8_mapping,
  148856. NULL,
  148857. {_noise_start_8,_noise_start_8},
  148858. {_noise_part_8,_noise_part_8},
  148859. _noise_thresh_11,
  148860. _psy_ath_floater_8,
  148861. _psy_ath_abs_8,
  148862. _psy_lowpass_11,
  148863. _psy_global_44,
  148864. _global_mapping_8,
  148865. _psy_stereo_modes_8,
  148866. _floor_books,
  148867. _floor,
  148868. _floor_mapping_11,
  148869. NULL,
  148870. _mapres_template_8_uncoupled
  148871. };
  148872. /********* End of inlined file: setup_11.h *********/
  148873. /********* Start of inlined file: setup_16.h *********/
  148874. /********* Start of inlined file: psych_16.h *********/
  148875. /* stereo mode by base quality level */
  148876. static adj_stereo _psy_stereo_modes_16[4]={
  148877. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  148878. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148879. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148880. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  148881. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148882. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148883. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148884. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  148885. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148886. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148887. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148888. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148889. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148890. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  148891. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  148892. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  148893. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148894. };
  148895. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  148896. static att3 _psy_tone_masteratt_16[4]={
  148897. {{ 30, 25, 12}, 0, 0}, /* 0 */
  148898. {{ 25, 22, 12}, 0, 0}, /* 0 */
  148899. {{ 20, 12, 0}, 0, 0}, /* 0 */
  148900. {{ 15, 0, -14}, 0, 0}, /* 0 */
  148901. };
  148902. static vp_adjblock _vp_tonemask_adj_16[4]={
  148903. /* adjust for mode zero */
  148904. /* 63 125 250 500 1 2 4 8 16 */
  148905. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  148906. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  148907. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  148908. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  148909. };
  148910. static noise3 _psy_noisebias_16_short[4]={
  148911. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148912. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  148913. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  148914. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148915. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  148916. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  148917. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  148918. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  148919. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  148920. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148921. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  148922. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  148923. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148924. };
  148925. static noise3 _psy_noisebias_16_impulse[4]={
  148926. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148927. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  148928. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  148929. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148930. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  148931. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  148932. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  148933. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  148934. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  148935. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148936. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  148937. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  148938. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148939. };
  148940. static noise3 _psy_noisebias_16[4]={
  148941. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148942. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  148943. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  148944. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148945. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  148946. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  148947. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148948. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  148949. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  148950. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148951. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  148952. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  148953. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148954. };
  148955. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  148956. static int _noise_start_16[3]={ 256,256,9999 };
  148957. static int _noise_part_16[4]={ 8,8,8,8 };
  148958. static int _psy_ath_floater_16[4]={
  148959. -100,-100,-100,-105,
  148960. };
  148961. static int _psy_ath_abs_16[4]={
  148962. -130,-130,-130,-140,
  148963. };
  148964. /********* End of inlined file: psych_16.h *********/
  148965. /********* Start of inlined file: residue_16.h *********/
  148966. /***** residue backends *********************************************/
  148967. static static_bookblock _resbook_16s_0={
  148968. {
  148969. {0},
  148970. {0,0,&_16c0_s_p1_0},
  148971. {0,0,&_16c0_s_p2_0},
  148972. {0,0,&_16c0_s_p3_0},
  148973. {0,0,&_16c0_s_p4_0},
  148974. {0,0,&_16c0_s_p5_0},
  148975. {0,0,&_16c0_s_p6_0},
  148976. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  148977. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  148978. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  148979. }
  148980. };
  148981. static static_bookblock _resbook_16s_1={
  148982. {
  148983. {0},
  148984. {0,0,&_16c1_s_p1_0},
  148985. {0,0,&_16c1_s_p2_0},
  148986. {0,0,&_16c1_s_p3_0},
  148987. {0,0,&_16c1_s_p4_0},
  148988. {0,0,&_16c1_s_p5_0},
  148989. {0,0,&_16c1_s_p6_0},
  148990. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  148991. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  148992. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  148993. }
  148994. };
  148995. static static_bookblock _resbook_16s_2={
  148996. {
  148997. {0},
  148998. {0,0,&_16c2_s_p1_0},
  148999. {0,0,&_16c2_s_p2_0},
  149000. {0,0,&_16c2_s_p3_0},
  149001. {0,0,&_16c2_s_p4_0},
  149002. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  149003. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  149004. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  149005. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  149006. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  149007. }
  149008. };
  149009. static vorbis_residue_template _res_16s_0[]={
  149010. {2,0, &_residue_44_mid,
  149011. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  149012. &_resbook_16s_0,&_resbook_16s_0},
  149013. };
  149014. static vorbis_residue_template _res_16s_1[]={
  149015. {2,0, &_residue_44_mid,
  149016. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  149017. &_resbook_16s_1,&_resbook_16s_1},
  149018. {2,0, &_residue_44_mid,
  149019. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  149020. &_resbook_16s_1,&_resbook_16s_1}
  149021. };
  149022. static vorbis_residue_template _res_16s_2[]={
  149023. {2,0, &_residue_44_high,
  149024. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  149025. &_resbook_16s_2,&_resbook_16s_2},
  149026. {2,0, &_residue_44_high,
  149027. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  149028. &_resbook_16s_2,&_resbook_16s_2}
  149029. };
  149030. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  149031. { _map_nominal, _res_16s_0 }, /* 0 */
  149032. { _map_nominal, _res_16s_1 }, /* 1 */
  149033. { _map_nominal, _res_16s_2 }, /* 2 */
  149034. };
  149035. static static_bookblock _resbook_16u_0={
  149036. {
  149037. {0},
  149038. {0,0,&_16u0__p1_0},
  149039. {0,0,&_16u0__p2_0},
  149040. {0,0,&_16u0__p3_0},
  149041. {0,0,&_16u0__p4_0},
  149042. {0,0,&_16u0__p5_0},
  149043. {&_16u0__p6_0,&_16u0__p6_1},
  149044. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  149045. }
  149046. };
  149047. static static_bookblock _resbook_16u_1={
  149048. {
  149049. {0},
  149050. {0,0,&_16u1__p1_0},
  149051. {0,0,&_16u1__p2_0},
  149052. {0,0,&_16u1__p3_0},
  149053. {0,0,&_16u1__p4_0},
  149054. {0,0,&_16u1__p5_0},
  149055. {0,0,&_16u1__p6_0},
  149056. {&_16u1__p7_0,&_16u1__p7_1},
  149057. {&_16u1__p8_0,&_16u1__p8_1},
  149058. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  149059. }
  149060. };
  149061. static static_bookblock _resbook_16u_2={
  149062. {
  149063. {0},
  149064. {0,0,&_16u2_p1_0},
  149065. {0,0,&_16u2_p2_0},
  149066. {0,0,&_16u2_p3_0},
  149067. {0,0,&_16u2_p4_0},
  149068. {&_16u2_p5_0,&_16u2_p5_1},
  149069. {&_16u2_p6_0,&_16u2_p6_1},
  149070. {&_16u2_p7_0,&_16u2_p7_1},
  149071. {&_16u2_p8_0,&_16u2_p8_1},
  149072. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  149073. }
  149074. };
  149075. static vorbis_residue_template _res_16u_0[]={
  149076. {1,0, &_residue_44_low_un,
  149077. &_huff_book__16u0__single,&_huff_book__16u0__single,
  149078. &_resbook_16u_0,&_resbook_16u_0},
  149079. };
  149080. static vorbis_residue_template _res_16u_1[]={
  149081. {1,0, &_residue_44_mid_un,
  149082. &_huff_book__16u1__short,&_huff_book__16u1__short,
  149083. &_resbook_16u_1,&_resbook_16u_1},
  149084. {1,0, &_residue_44_mid_un,
  149085. &_huff_book__16u1__long,&_huff_book__16u1__long,
  149086. &_resbook_16u_1,&_resbook_16u_1}
  149087. };
  149088. static vorbis_residue_template _res_16u_2[]={
  149089. {1,0, &_residue_44_hi_un,
  149090. &_huff_book__16u2__short,&_huff_book__16u2__short,
  149091. &_resbook_16u_2,&_resbook_16u_2},
  149092. {1,0, &_residue_44_hi_un,
  149093. &_huff_book__16u2__long,&_huff_book__16u2__long,
  149094. &_resbook_16u_2,&_resbook_16u_2}
  149095. };
  149096. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  149097. { _map_nominal_u, _res_16u_0 }, /* 0 */
  149098. { _map_nominal_u, _res_16u_1 }, /* 1 */
  149099. { _map_nominal_u, _res_16u_2 }, /* 2 */
  149100. };
  149101. /********* End of inlined file: residue_16.h *********/
  149102. static int blocksize_16_short[3]={
  149103. 1024,512,512
  149104. };
  149105. static int blocksize_16_long[3]={
  149106. 1024,1024,1024
  149107. };
  149108. static int _floor_mapping_16_short[3]={
  149109. 9,3,3
  149110. };
  149111. static int _floor_mapping_16[3]={
  149112. 9,9,9
  149113. };
  149114. static double rate_mapping_16[4]={
  149115. 12000.,20000.,44000.,86000.
  149116. };
  149117. static double rate_mapping_16_uncoupled[4]={
  149118. 16000.,28000.,64000.,100000.
  149119. };
  149120. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  149121. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  149122. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  149123. ve_setup_data_template ve_setup_16_stereo={
  149124. 3,
  149125. rate_mapping_16,
  149126. quality_mapping_16,
  149127. 2,
  149128. 15000,
  149129. 19000,
  149130. blocksize_16_short,
  149131. blocksize_16_long,
  149132. _psy_tone_masteratt_16,
  149133. _psy_tone_0dB,
  149134. _psy_tone_suppress,
  149135. _vp_tonemask_adj_16,
  149136. _vp_tonemask_adj_16,
  149137. _vp_tonemask_adj_16,
  149138. _psy_noiseguards_8,
  149139. _psy_noisebias_16_impulse,
  149140. _psy_noisebias_16_short,
  149141. _psy_noisebias_16_short,
  149142. _psy_noisebias_16,
  149143. _psy_noise_suppress,
  149144. _psy_compand_8,
  149145. _psy_compand_16_mapping,
  149146. _psy_compand_16_mapping,
  149147. {_noise_start_16,_noise_start_16},
  149148. { _noise_part_16, _noise_part_16},
  149149. _noise_thresh_16,
  149150. _psy_ath_floater_16,
  149151. _psy_ath_abs_16,
  149152. _psy_lowpass_16,
  149153. _psy_global_44,
  149154. _global_mapping_16,
  149155. _psy_stereo_modes_16,
  149156. _floor_books,
  149157. _floor,
  149158. _floor_mapping_16_short,
  149159. _floor_mapping_16,
  149160. _mapres_template_16_stereo
  149161. };
  149162. ve_setup_data_template ve_setup_16_uncoupled={
  149163. 3,
  149164. rate_mapping_16_uncoupled,
  149165. quality_mapping_16,
  149166. -1,
  149167. 15000,
  149168. 19000,
  149169. blocksize_16_short,
  149170. blocksize_16_long,
  149171. _psy_tone_masteratt_16,
  149172. _psy_tone_0dB,
  149173. _psy_tone_suppress,
  149174. _vp_tonemask_adj_16,
  149175. _vp_tonemask_adj_16,
  149176. _vp_tonemask_adj_16,
  149177. _psy_noiseguards_8,
  149178. _psy_noisebias_16_impulse,
  149179. _psy_noisebias_16_short,
  149180. _psy_noisebias_16_short,
  149181. _psy_noisebias_16,
  149182. _psy_noise_suppress,
  149183. _psy_compand_8,
  149184. _psy_compand_16_mapping,
  149185. _psy_compand_16_mapping,
  149186. {_noise_start_16,_noise_start_16},
  149187. { _noise_part_16, _noise_part_16},
  149188. _noise_thresh_16,
  149189. _psy_ath_floater_16,
  149190. _psy_ath_abs_16,
  149191. _psy_lowpass_16,
  149192. _psy_global_44,
  149193. _global_mapping_16,
  149194. _psy_stereo_modes_16,
  149195. _floor_books,
  149196. _floor,
  149197. _floor_mapping_16_short,
  149198. _floor_mapping_16,
  149199. _mapres_template_16_uncoupled
  149200. };
  149201. /********* End of inlined file: setup_16.h *********/
  149202. /********* Start of inlined file: setup_22.h *********/
  149203. static double rate_mapping_22[4]={
  149204. 15000.,20000.,44000.,86000.
  149205. };
  149206. static double rate_mapping_22_uncoupled[4]={
  149207. 16000.,28000.,50000.,90000.
  149208. };
  149209. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  149210. ve_setup_data_template ve_setup_22_stereo={
  149211. 3,
  149212. rate_mapping_22,
  149213. quality_mapping_16,
  149214. 2,
  149215. 19000,
  149216. 26000,
  149217. blocksize_16_short,
  149218. blocksize_16_long,
  149219. _psy_tone_masteratt_16,
  149220. _psy_tone_0dB,
  149221. _psy_tone_suppress,
  149222. _vp_tonemask_adj_16,
  149223. _vp_tonemask_adj_16,
  149224. _vp_tonemask_adj_16,
  149225. _psy_noiseguards_8,
  149226. _psy_noisebias_16_impulse,
  149227. _psy_noisebias_16_short,
  149228. _psy_noisebias_16_short,
  149229. _psy_noisebias_16,
  149230. _psy_noise_suppress,
  149231. _psy_compand_8,
  149232. _psy_compand_8_mapping,
  149233. _psy_compand_8_mapping,
  149234. {_noise_start_16,_noise_start_16},
  149235. { _noise_part_16, _noise_part_16},
  149236. _noise_thresh_16,
  149237. _psy_ath_floater_16,
  149238. _psy_ath_abs_16,
  149239. _psy_lowpass_22,
  149240. _psy_global_44,
  149241. _global_mapping_16,
  149242. _psy_stereo_modes_16,
  149243. _floor_books,
  149244. _floor,
  149245. _floor_mapping_16_short,
  149246. _floor_mapping_16,
  149247. _mapres_template_16_stereo
  149248. };
  149249. ve_setup_data_template ve_setup_22_uncoupled={
  149250. 3,
  149251. rate_mapping_22_uncoupled,
  149252. quality_mapping_16,
  149253. -1,
  149254. 19000,
  149255. 26000,
  149256. blocksize_16_short,
  149257. blocksize_16_long,
  149258. _psy_tone_masteratt_16,
  149259. _psy_tone_0dB,
  149260. _psy_tone_suppress,
  149261. _vp_tonemask_adj_16,
  149262. _vp_tonemask_adj_16,
  149263. _vp_tonemask_adj_16,
  149264. _psy_noiseguards_8,
  149265. _psy_noisebias_16_impulse,
  149266. _psy_noisebias_16_short,
  149267. _psy_noisebias_16_short,
  149268. _psy_noisebias_16,
  149269. _psy_noise_suppress,
  149270. _psy_compand_8,
  149271. _psy_compand_8_mapping,
  149272. _psy_compand_8_mapping,
  149273. {_noise_start_16,_noise_start_16},
  149274. { _noise_part_16, _noise_part_16},
  149275. _noise_thresh_16,
  149276. _psy_ath_floater_16,
  149277. _psy_ath_abs_16,
  149278. _psy_lowpass_22,
  149279. _psy_global_44,
  149280. _global_mapping_16,
  149281. _psy_stereo_modes_16,
  149282. _floor_books,
  149283. _floor,
  149284. _floor_mapping_16_short,
  149285. _floor_mapping_16,
  149286. _mapres_template_16_uncoupled
  149287. };
  149288. /********* End of inlined file: setup_22.h *********/
  149289. /********* Start of inlined file: setup_X.h *********/
  149290. static double rate_mapping_X[12]={
  149291. -1.,-1.,-1.,-1.,-1.,-1.,
  149292. -1.,-1.,-1.,-1.,-1.,-1.
  149293. };
  149294. ve_setup_data_template ve_setup_X_stereo={
  149295. 11,
  149296. rate_mapping_X,
  149297. quality_mapping_44,
  149298. 2,
  149299. 50000,
  149300. 200000,
  149301. blocksize_short_44,
  149302. blocksize_long_44,
  149303. _psy_tone_masteratt_44,
  149304. _psy_tone_0dB,
  149305. _psy_tone_suppress,
  149306. _vp_tonemask_adj_otherblock,
  149307. _vp_tonemask_adj_longblock,
  149308. _vp_tonemask_adj_otherblock,
  149309. _psy_noiseguards_44,
  149310. _psy_noisebias_impulse,
  149311. _psy_noisebias_padding,
  149312. _psy_noisebias_trans,
  149313. _psy_noisebias_long,
  149314. _psy_noise_suppress,
  149315. _psy_compand_44,
  149316. _psy_compand_short_mapping,
  149317. _psy_compand_long_mapping,
  149318. {_noise_start_short_44,_noise_start_long_44},
  149319. {_noise_part_short_44,_noise_part_long_44},
  149320. _noise_thresh_44,
  149321. _psy_ath_floater,
  149322. _psy_ath_abs,
  149323. _psy_lowpass_44,
  149324. _psy_global_44,
  149325. _global_mapping_44,
  149326. _psy_stereo_modes_44,
  149327. _floor_books,
  149328. _floor,
  149329. _floor_short_mapping_44,
  149330. _floor_long_mapping_44,
  149331. _mapres_template_44_stereo
  149332. };
  149333. ve_setup_data_template ve_setup_X_uncoupled={
  149334. 11,
  149335. rate_mapping_X,
  149336. quality_mapping_44,
  149337. -1,
  149338. 50000,
  149339. 200000,
  149340. blocksize_short_44,
  149341. blocksize_long_44,
  149342. _psy_tone_masteratt_44,
  149343. _psy_tone_0dB,
  149344. _psy_tone_suppress,
  149345. _vp_tonemask_adj_otherblock,
  149346. _vp_tonemask_adj_longblock,
  149347. _vp_tonemask_adj_otherblock,
  149348. _psy_noiseguards_44,
  149349. _psy_noisebias_impulse,
  149350. _psy_noisebias_padding,
  149351. _psy_noisebias_trans,
  149352. _psy_noisebias_long,
  149353. _psy_noise_suppress,
  149354. _psy_compand_44,
  149355. _psy_compand_short_mapping,
  149356. _psy_compand_long_mapping,
  149357. {_noise_start_short_44,_noise_start_long_44},
  149358. {_noise_part_short_44,_noise_part_long_44},
  149359. _noise_thresh_44,
  149360. _psy_ath_floater,
  149361. _psy_ath_abs,
  149362. _psy_lowpass_44,
  149363. _psy_global_44,
  149364. _global_mapping_44,
  149365. NULL,
  149366. _floor_books,
  149367. _floor,
  149368. _floor_short_mapping_44,
  149369. _floor_long_mapping_44,
  149370. _mapres_template_44_uncoupled
  149371. };
  149372. ve_setup_data_template ve_setup_XX_stereo={
  149373. 2,
  149374. rate_mapping_X,
  149375. quality_mapping_8,
  149376. 2,
  149377. 0,
  149378. 8000,
  149379. blocksize_8,
  149380. blocksize_8,
  149381. _psy_tone_masteratt_8,
  149382. _psy_tone_0dB,
  149383. _psy_tone_suppress,
  149384. _vp_tonemask_adj_8,
  149385. NULL,
  149386. _vp_tonemask_adj_8,
  149387. _psy_noiseguards_8,
  149388. _psy_noisebias_8,
  149389. _psy_noisebias_8,
  149390. NULL,
  149391. NULL,
  149392. _psy_noise_suppress,
  149393. _psy_compand_8,
  149394. _psy_compand_8_mapping,
  149395. NULL,
  149396. {_noise_start_8,_noise_start_8},
  149397. {_noise_part_8,_noise_part_8},
  149398. _noise_thresh_5only,
  149399. _psy_ath_floater_8,
  149400. _psy_ath_abs_8,
  149401. _psy_lowpass_8,
  149402. _psy_global_44,
  149403. _global_mapping_8,
  149404. _psy_stereo_modes_8,
  149405. _floor_books,
  149406. _floor,
  149407. _floor_mapping_8,
  149408. NULL,
  149409. _mapres_template_8_stereo
  149410. };
  149411. ve_setup_data_template ve_setup_XX_uncoupled={
  149412. 2,
  149413. rate_mapping_X,
  149414. quality_mapping_8,
  149415. -1,
  149416. 0,
  149417. 8000,
  149418. blocksize_8,
  149419. blocksize_8,
  149420. _psy_tone_masteratt_8,
  149421. _psy_tone_0dB,
  149422. _psy_tone_suppress,
  149423. _vp_tonemask_adj_8,
  149424. NULL,
  149425. _vp_tonemask_adj_8,
  149426. _psy_noiseguards_8,
  149427. _psy_noisebias_8,
  149428. _psy_noisebias_8,
  149429. NULL,
  149430. NULL,
  149431. _psy_noise_suppress,
  149432. _psy_compand_8,
  149433. _psy_compand_8_mapping,
  149434. NULL,
  149435. {_noise_start_8,_noise_start_8},
  149436. {_noise_part_8,_noise_part_8},
  149437. _noise_thresh_5only,
  149438. _psy_ath_floater_8,
  149439. _psy_ath_abs_8,
  149440. _psy_lowpass_8,
  149441. _psy_global_44,
  149442. _global_mapping_8,
  149443. _psy_stereo_modes_8,
  149444. _floor_books,
  149445. _floor,
  149446. _floor_mapping_8,
  149447. NULL,
  149448. _mapres_template_8_uncoupled
  149449. };
  149450. /********* End of inlined file: setup_X.h *********/
  149451. static ve_setup_data_template *setup_list[]={
  149452. &ve_setup_44_stereo,
  149453. &ve_setup_44_uncoupled,
  149454. &ve_setup_32_stereo,
  149455. &ve_setup_32_uncoupled,
  149456. &ve_setup_22_stereo,
  149457. &ve_setup_22_uncoupled,
  149458. &ve_setup_16_stereo,
  149459. &ve_setup_16_uncoupled,
  149460. &ve_setup_11_stereo,
  149461. &ve_setup_11_uncoupled,
  149462. &ve_setup_8_stereo,
  149463. &ve_setup_8_uncoupled,
  149464. &ve_setup_X_stereo,
  149465. &ve_setup_X_uncoupled,
  149466. &ve_setup_XX_stereo,
  149467. &ve_setup_XX_uncoupled,
  149468. 0
  149469. };
  149470. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  149471. if(vi && vi->codec_setup){
  149472. vi->version=0;
  149473. vi->channels=ch;
  149474. vi->rate=rate;
  149475. return(0);
  149476. }
  149477. return(OV_EINVAL);
  149478. }
  149479. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  149480. static_codebook ***books,
  149481. vorbis_info_floor1 *in,
  149482. int *x){
  149483. int i,k,is=s;
  149484. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  149485. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149486. memcpy(f,in+x[is],sizeof(*f));
  149487. /* fill in the lowpass field, even if it's temporary */
  149488. f->n=ci->blocksizes[block]>>1;
  149489. /* books */
  149490. {
  149491. int partitions=f->partitions;
  149492. int maxclass=-1;
  149493. int maxbook=-1;
  149494. for(i=0;i<partitions;i++)
  149495. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  149496. for(i=0;i<=maxclass;i++){
  149497. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  149498. f->class_book[i]+=ci->books;
  149499. for(k=0;k<(1<<f->class_subs[i]);k++){
  149500. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  149501. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  149502. }
  149503. }
  149504. for(i=0;i<=maxbook;i++)
  149505. ci->book_param[ci->books++]=books[x[is]][i];
  149506. }
  149507. /* for now, we're only using floor 1 */
  149508. ci->floor_type[ci->floors]=1;
  149509. ci->floor_param[ci->floors]=f;
  149510. ci->floors++;
  149511. return;
  149512. }
  149513. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  149514. vorbis_info_psy_global *in,
  149515. double *x){
  149516. int i,is=s;
  149517. double ds=s-is;
  149518. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149519. vorbis_info_psy_global *g=&ci->psy_g_param;
  149520. memcpy(g,in+(int)x[is],sizeof(*g));
  149521. ds=x[is]*(1.-ds)+x[is+1]*ds;
  149522. is=(int)ds;
  149523. ds-=is;
  149524. if(ds==0 && is>0){
  149525. is--;
  149526. ds=1.;
  149527. }
  149528. /* interpolate the trigger threshholds */
  149529. for(i=0;i<4;i++){
  149530. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  149531. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  149532. }
  149533. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  149534. return;
  149535. }
  149536. static void vorbis_encode_global_stereo(vorbis_info *vi,
  149537. highlevel_encode_setup *hi,
  149538. adj_stereo *p){
  149539. float s=hi->stereo_point_setting;
  149540. int i,is=s;
  149541. double ds=s-is;
  149542. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149543. vorbis_info_psy_global *g=&ci->psy_g_param;
  149544. if(p){
  149545. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  149546. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  149547. if(hi->managed){
  149548. /* interpolate the kHz threshholds */
  149549. for(i=0;i<PACKETBLOBS;i++){
  149550. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  149551. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  149552. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  149553. g->coupling_pkHz[i]=kHz;
  149554. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  149555. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  149556. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  149557. }
  149558. }else{
  149559. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  149560. for(i=0;i<PACKETBLOBS;i++){
  149561. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  149562. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  149563. g->coupling_pkHz[i]=kHz;
  149564. }
  149565. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  149566. for(i=0;i<PACKETBLOBS;i++){
  149567. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  149568. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  149569. }
  149570. }
  149571. }else{
  149572. for(i=0;i<PACKETBLOBS;i++){
  149573. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  149574. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  149575. }
  149576. }
  149577. return;
  149578. }
  149579. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  149580. int *nn_start,
  149581. int *nn_partition,
  149582. double *nn_thresh,
  149583. int block){
  149584. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  149585. vorbis_info_psy *p=ci->psy_param[block];
  149586. highlevel_encode_setup *hi=&ci->hi;
  149587. int is=s;
  149588. if(block>=ci->psys)
  149589. ci->psys=block+1;
  149590. if(!p){
  149591. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  149592. ci->psy_param[block]=p;
  149593. }
  149594. memcpy(p,&_psy_info_template,sizeof(*p));
  149595. p->blockflag=block>>1;
  149596. if(hi->noise_normalize_p){
  149597. p->normal_channel_p=1;
  149598. p->normal_point_p=1;
  149599. p->normal_start=nn_start[is];
  149600. p->normal_partition=nn_partition[is];
  149601. p->normal_thresh=nn_thresh[is];
  149602. }
  149603. return;
  149604. }
  149605. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  149606. att3 *att,
  149607. int *max,
  149608. vp_adjblock *in){
  149609. int i,is=s;
  149610. double ds=s-is;
  149611. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  149612. vorbis_info_psy *p=ci->psy_param[block];
  149613. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  149614. filling the values in here */
  149615. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  149616. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  149617. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  149618. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  149619. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  149620. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  149621. for(i=0;i<P_BANDS;i++)
  149622. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  149623. return;
  149624. }
  149625. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  149626. compandblock *in, double *x){
  149627. int i,is=s;
  149628. double ds=s-is;
  149629. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149630. vorbis_info_psy *p=ci->psy_param[block];
  149631. ds=x[is]*(1.-ds)+x[is+1]*ds;
  149632. is=(int)ds;
  149633. ds-=is;
  149634. if(ds==0 && is>0){
  149635. is--;
  149636. ds=1.;
  149637. }
  149638. /* interpolate the compander settings */
  149639. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  149640. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  149641. return;
  149642. }
  149643. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  149644. int *suppress){
  149645. int is=s;
  149646. double ds=s-is;
  149647. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149648. vorbis_info_psy *p=ci->psy_param[block];
  149649. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  149650. return;
  149651. }
  149652. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  149653. int *suppress,
  149654. noise3 *in,
  149655. noiseguard *guard,
  149656. double userbias){
  149657. int i,is=s,j;
  149658. double ds=s-is;
  149659. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149660. vorbis_info_psy *p=ci->psy_param[block];
  149661. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  149662. p->noisewindowlomin=guard[block].lo;
  149663. p->noisewindowhimin=guard[block].hi;
  149664. p->noisewindowfixed=guard[block].fixed;
  149665. for(j=0;j<P_NOISECURVES;j++)
  149666. for(i=0;i<P_BANDS;i++)
  149667. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  149668. /* impulse blocks may take a user specified bias to boost the
  149669. nominal/high noise encoding depth */
  149670. for(j=0;j<P_NOISECURVES;j++){
  149671. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  149672. for(i=0;i<P_BANDS;i++){
  149673. p->noiseoff[j][i]+=userbias;
  149674. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  149675. }
  149676. }
  149677. return;
  149678. }
  149679. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  149680. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149681. vorbis_info_psy *p=ci->psy_param[block];
  149682. p->ath_adjatt=ci->hi.ath_floating_dB;
  149683. p->ath_maxatt=ci->hi.ath_absolute_dB;
  149684. return;
  149685. }
  149686. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  149687. int i;
  149688. for(i=0;i<ci->books;i++)
  149689. if(ci->book_param[i]==book)return(i);
  149690. return(ci->books++);
  149691. }
  149692. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  149693. int *shortb,int *longb){
  149694. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149695. int is=s;
  149696. int blockshort=shortb[is];
  149697. int blocklong=longb[is];
  149698. ci->blocksizes[0]=blockshort;
  149699. ci->blocksizes[1]=blocklong;
  149700. }
  149701. static void vorbis_encode_residue_setup(vorbis_info *vi,
  149702. int number, int block,
  149703. vorbis_residue_template *res){
  149704. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149705. int i,n;
  149706. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  149707. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  149708. memcpy(r,res->res,sizeof(*r));
  149709. if(ci->residues<=number)ci->residues=number+1;
  149710. switch(ci->blocksizes[block]){
  149711. case 64:case 128:case 256:
  149712. r->grouping=16;
  149713. break;
  149714. default:
  149715. r->grouping=32;
  149716. break;
  149717. }
  149718. ci->residue_type[number]=res->res_type;
  149719. /* to be adjusted by lowpass/pointlimit later */
  149720. n=r->end=ci->blocksizes[block]>>1;
  149721. if(res->res_type==2)
  149722. n=r->end*=vi->channels;
  149723. /* fill in all the books */
  149724. {
  149725. int booklist=0,k;
  149726. if(ci->hi.managed){
  149727. for(i=0;i<r->partitions;i++)
  149728. for(k=0;k<3;k++)
  149729. if(res->books_base_managed->books[i][k])
  149730. r->secondstages[i]|=(1<<k);
  149731. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  149732. ci->book_param[r->groupbook]=res->book_aux_managed;
  149733. for(i=0;i<r->partitions;i++){
  149734. for(k=0;k<3;k++){
  149735. if(res->books_base_managed->books[i][k]){
  149736. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  149737. r->booklist[booklist++]=bookid;
  149738. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  149739. }
  149740. }
  149741. }
  149742. }else{
  149743. for(i=0;i<r->partitions;i++)
  149744. for(k=0;k<3;k++)
  149745. if(res->books_base->books[i][k])
  149746. r->secondstages[i]|=(1<<k);
  149747. r->groupbook=book_dup_or_new(ci,res->book_aux);
  149748. ci->book_param[r->groupbook]=res->book_aux;
  149749. for(i=0;i<r->partitions;i++){
  149750. for(k=0;k<3;k++){
  149751. if(res->books_base->books[i][k]){
  149752. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  149753. r->booklist[booklist++]=bookid;
  149754. ci->book_param[bookid]=res->books_base->books[i][k];
  149755. }
  149756. }
  149757. }
  149758. }
  149759. }
  149760. /* lowpass setup/pointlimit */
  149761. {
  149762. double freq=ci->hi.lowpass_kHz*1000.;
  149763. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  149764. double nyq=vi->rate/2.;
  149765. long blocksize=ci->blocksizes[block]>>1;
  149766. /* lowpass needs to be set in the floor and the residue. */
  149767. if(freq>nyq)freq=nyq;
  149768. /* in the floor, the granularity can be very fine; it doesn't alter
  149769. the encoding structure, only the samples used to fit the floor
  149770. approximation */
  149771. f->n=freq/nyq*blocksize;
  149772. /* this res may by limited by the maximum pointlimit of the mode,
  149773. not the lowpass. the floor is always lowpass limited. */
  149774. if(res->limit_type){
  149775. if(ci->hi.managed)
  149776. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  149777. else
  149778. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  149779. if(freq>nyq)freq=nyq;
  149780. }
  149781. /* in the residue, we're constrained, physically, by partition
  149782. boundaries. We still lowpass 'wherever', but we have to round up
  149783. here to next boundary, or the vorbis spec will round it *down* to
  149784. previous boundary in encode/decode */
  149785. if(ci->residue_type[block]==2)
  149786. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  149787. r->grouping;
  149788. else
  149789. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  149790. r->grouping;
  149791. }
  149792. }
  149793. /* we assume two maps in this encoder */
  149794. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  149795. vorbis_mapping_template *maps){
  149796. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149797. int i,j,is=s,modes=2;
  149798. vorbis_info_mapping0 *map=maps[is].map;
  149799. vorbis_info_mode *mode=_mode_template;
  149800. vorbis_residue_template *res=maps[is].res;
  149801. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  149802. for(i=0;i<modes;i++){
  149803. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  149804. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  149805. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  149806. if(i>=ci->modes)ci->modes=i+1;
  149807. ci->map_type[i]=0;
  149808. memcpy(ci->map_param[i],map+i,sizeof(*map));
  149809. if(i>=ci->maps)ci->maps=i+1;
  149810. for(j=0;j<map[i].submaps;j++)
  149811. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  149812. ,res+map[i].residuesubmap[j]);
  149813. }
  149814. }
  149815. static double setting_to_approx_bitrate(vorbis_info *vi){
  149816. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149817. highlevel_encode_setup *hi=&ci->hi;
  149818. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  149819. int is=hi->base_setting;
  149820. double ds=hi->base_setting-is;
  149821. int ch=vi->channels;
  149822. double *r=setup->rate_mapping;
  149823. if(r==NULL)
  149824. return(-1);
  149825. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  149826. }
  149827. static void get_setup_template(vorbis_info *vi,
  149828. long ch,long srate,
  149829. double req,int q_or_bitrate){
  149830. int i=0,j;
  149831. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  149832. highlevel_encode_setup *hi=&ci->hi;
  149833. if(q_or_bitrate)req/=ch;
  149834. while(setup_list[i]){
  149835. if(setup_list[i]->coupling_restriction==-1 ||
  149836. setup_list[i]->coupling_restriction==ch){
  149837. if(srate>=setup_list[i]->samplerate_min_restriction &&
  149838. srate<=setup_list[i]->samplerate_max_restriction){
  149839. int mappings=setup_list[i]->mappings;
  149840. double *map=(q_or_bitrate?
  149841. setup_list[i]->rate_mapping:
  149842. setup_list[i]->quality_mapping);
  149843. /* the template matches. Does the requested quality mode
  149844. fall within this template's modes? */
  149845. if(req<map[0]){++i;continue;}
  149846. if(req>map[setup_list[i]->mappings]){++i;continue;}
  149847. for(j=0;j<mappings;j++)
  149848. if(req>=map[j] && req<map[j+1])break;
  149849. /* an all-points match */
  149850. hi->setup=setup_list[i];
  149851. if(j==mappings)
  149852. hi->base_setting=j-.001;
  149853. else{
  149854. float low=map[j];
  149855. float high=map[j+1];
  149856. float del=(req-low)/(high-low);
  149857. hi->base_setting=j+del;
  149858. }
  149859. return;
  149860. }
  149861. }
  149862. i++;
  149863. }
  149864. hi->setup=NULL;
  149865. }
  149866. /* encoders will need to use vorbis_info_init beforehand and call
  149867. vorbis_info clear when all done */
  149868. /* two interfaces; this, more detailed one, and later a convenience
  149869. layer on top */
  149870. /* the final setup call */
  149871. int vorbis_encode_setup_init(vorbis_info *vi){
  149872. int i0=0,singleblock=0;
  149873. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  149874. ve_setup_data_template *setup=NULL;
  149875. highlevel_encode_setup *hi=&ci->hi;
  149876. if(ci==NULL)return(OV_EINVAL);
  149877. if(!hi->impulse_block_p)i0=1;
  149878. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  149879. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  149880. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  149881. /* again, bound this to avoid the app shooting itself int he foot
  149882. too badly */
  149883. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  149884. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  149885. /* get the appropriate setup template; matches the fetch in previous
  149886. stages */
  149887. setup=(ve_setup_data_template *)hi->setup;
  149888. if(setup==NULL)return(OV_EINVAL);
  149889. hi->set_in_stone=1;
  149890. /* choose block sizes from configured sizes as well as paying
  149891. attention to long_block_p and short_block_p. If the configured
  149892. short and long blocks are the same length, we set long_block_p
  149893. and unset short_block_p */
  149894. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  149895. setup->blocksize_short,
  149896. setup->blocksize_long);
  149897. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  149898. /* floor setup; choose proper floor params. Allocated on the floor
  149899. stack in order; if we alloc only long floor, it's 0 */
  149900. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  149901. setup->floor_books,
  149902. setup->floor_params,
  149903. setup->floor_short_mapping);
  149904. if(!singleblock)
  149905. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  149906. setup->floor_books,
  149907. setup->floor_params,
  149908. setup->floor_long_mapping);
  149909. /* setup of [mostly] short block detection and stereo*/
  149910. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  149911. setup->global_params,
  149912. setup->global_mapping);
  149913. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  149914. /* basic psych setup and noise normalization */
  149915. vorbis_encode_psyset_setup(vi,hi->short_setting,
  149916. setup->psy_noise_normal_start[0],
  149917. setup->psy_noise_normal_partition[0],
  149918. setup->psy_noise_normal_thresh,
  149919. 0);
  149920. vorbis_encode_psyset_setup(vi,hi->short_setting,
  149921. setup->psy_noise_normal_start[0],
  149922. setup->psy_noise_normal_partition[0],
  149923. setup->psy_noise_normal_thresh,
  149924. 1);
  149925. if(!singleblock){
  149926. vorbis_encode_psyset_setup(vi,hi->long_setting,
  149927. setup->psy_noise_normal_start[1],
  149928. setup->psy_noise_normal_partition[1],
  149929. setup->psy_noise_normal_thresh,
  149930. 2);
  149931. vorbis_encode_psyset_setup(vi,hi->long_setting,
  149932. setup->psy_noise_normal_start[1],
  149933. setup->psy_noise_normal_partition[1],
  149934. setup->psy_noise_normal_thresh,
  149935. 3);
  149936. }
  149937. /* tone masking setup */
  149938. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  149939. setup->psy_tone_masteratt,
  149940. setup->psy_tone_0dB,
  149941. setup->psy_tone_adj_impulse);
  149942. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  149943. setup->psy_tone_masteratt,
  149944. setup->psy_tone_0dB,
  149945. setup->psy_tone_adj_other);
  149946. if(!singleblock){
  149947. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  149948. setup->psy_tone_masteratt,
  149949. setup->psy_tone_0dB,
  149950. setup->psy_tone_adj_other);
  149951. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  149952. setup->psy_tone_masteratt,
  149953. setup->psy_tone_0dB,
  149954. setup->psy_tone_adj_long);
  149955. }
  149956. /* noise companding setup */
  149957. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  149958. setup->psy_noise_compand,
  149959. setup->psy_noise_compand_short_mapping);
  149960. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  149961. setup->psy_noise_compand,
  149962. setup->psy_noise_compand_short_mapping);
  149963. if(!singleblock){
  149964. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  149965. setup->psy_noise_compand,
  149966. setup->psy_noise_compand_long_mapping);
  149967. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  149968. setup->psy_noise_compand,
  149969. setup->psy_noise_compand_long_mapping);
  149970. }
  149971. /* peak guarding setup */
  149972. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  149973. setup->psy_tone_dBsuppress);
  149974. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  149975. setup->psy_tone_dBsuppress);
  149976. if(!singleblock){
  149977. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  149978. setup->psy_tone_dBsuppress);
  149979. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  149980. setup->psy_tone_dBsuppress);
  149981. }
  149982. /* noise bias setup */
  149983. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  149984. setup->psy_noise_dBsuppress,
  149985. setup->psy_noise_bias_impulse,
  149986. setup->psy_noiseguards,
  149987. (i0==0?hi->impulse_noisetune:0.));
  149988. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  149989. setup->psy_noise_dBsuppress,
  149990. setup->psy_noise_bias_padding,
  149991. setup->psy_noiseguards,0.);
  149992. if(!singleblock){
  149993. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  149994. setup->psy_noise_dBsuppress,
  149995. setup->psy_noise_bias_trans,
  149996. setup->psy_noiseguards,0.);
  149997. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  149998. setup->psy_noise_dBsuppress,
  149999. setup->psy_noise_bias_long,
  150000. setup->psy_noiseguards,0.);
  150001. }
  150002. vorbis_encode_ath_setup(vi,0);
  150003. vorbis_encode_ath_setup(vi,1);
  150004. if(!singleblock){
  150005. vorbis_encode_ath_setup(vi,2);
  150006. vorbis_encode_ath_setup(vi,3);
  150007. }
  150008. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  150009. /* set bitrate readonlies and management */
  150010. if(hi->bitrate_av>0)
  150011. vi->bitrate_nominal=hi->bitrate_av;
  150012. else{
  150013. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  150014. }
  150015. vi->bitrate_lower=hi->bitrate_min;
  150016. vi->bitrate_upper=hi->bitrate_max;
  150017. if(hi->bitrate_av)
  150018. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  150019. else
  150020. vi->bitrate_window=0.;
  150021. if(hi->managed){
  150022. ci->bi.avg_rate=hi->bitrate_av;
  150023. ci->bi.min_rate=hi->bitrate_min;
  150024. ci->bi.max_rate=hi->bitrate_max;
  150025. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  150026. ci->bi.reservoir_bias=
  150027. hi->bitrate_reservoir_bias;
  150028. ci->bi.slew_damp=hi->bitrate_av_damp;
  150029. }
  150030. return(0);
  150031. }
  150032. static int vorbis_encode_setup_setting(vorbis_info *vi,
  150033. long channels,
  150034. long rate){
  150035. int ret=0,i,is;
  150036. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150037. highlevel_encode_setup *hi=&ci->hi;
  150038. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  150039. double ds;
  150040. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  150041. if(ret)return(ret);
  150042. is=hi->base_setting;
  150043. ds=hi->base_setting-is;
  150044. hi->short_setting=hi->base_setting;
  150045. hi->long_setting=hi->base_setting;
  150046. hi->managed=0;
  150047. hi->impulse_block_p=1;
  150048. hi->noise_normalize_p=1;
  150049. hi->stereo_point_setting=hi->base_setting;
  150050. hi->lowpass_kHz=
  150051. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  150052. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  150053. setup->psy_ath_float[is+1]*ds;
  150054. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  150055. setup->psy_ath_abs[is+1]*ds;
  150056. hi->amplitude_track_dBpersec=-6.;
  150057. hi->trigger_setting=hi->base_setting;
  150058. for(i=0;i<4;i++){
  150059. hi->block[i].tone_mask_setting=hi->base_setting;
  150060. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  150061. hi->block[i].noise_bias_setting=hi->base_setting;
  150062. hi->block[i].noise_compand_setting=hi->base_setting;
  150063. }
  150064. return(ret);
  150065. }
  150066. int vorbis_encode_setup_vbr(vorbis_info *vi,
  150067. long channels,
  150068. long rate,
  150069. float quality){
  150070. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150071. highlevel_encode_setup *hi=&ci->hi;
  150072. quality+=.0000001;
  150073. if(quality>=1.)quality=.9999;
  150074. get_setup_template(vi,channels,rate,quality,0);
  150075. if(!hi->setup)return OV_EIMPL;
  150076. return vorbis_encode_setup_setting(vi,channels,rate);
  150077. }
  150078. int vorbis_encode_init_vbr(vorbis_info *vi,
  150079. long channels,
  150080. long rate,
  150081. float base_quality /* 0. to 1. */
  150082. ){
  150083. int ret=0;
  150084. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  150085. if(ret){
  150086. vorbis_info_clear(vi);
  150087. return ret;
  150088. }
  150089. ret=vorbis_encode_setup_init(vi);
  150090. if(ret)
  150091. vorbis_info_clear(vi);
  150092. return(ret);
  150093. }
  150094. int vorbis_encode_setup_managed(vorbis_info *vi,
  150095. long channels,
  150096. long rate,
  150097. long max_bitrate,
  150098. long nominal_bitrate,
  150099. long min_bitrate){
  150100. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150101. highlevel_encode_setup *hi=&ci->hi;
  150102. double tnominal=nominal_bitrate;
  150103. int ret=0;
  150104. if(nominal_bitrate<=0.){
  150105. if(max_bitrate>0.){
  150106. if(min_bitrate>0.)
  150107. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  150108. else
  150109. nominal_bitrate=max_bitrate*.875;
  150110. }else{
  150111. if(min_bitrate>0.){
  150112. nominal_bitrate=min_bitrate;
  150113. }else{
  150114. return(OV_EINVAL);
  150115. }
  150116. }
  150117. }
  150118. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  150119. if(!hi->setup)return OV_EIMPL;
  150120. ret=vorbis_encode_setup_setting(vi,channels,rate);
  150121. if(ret){
  150122. vorbis_info_clear(vi);
  150123. return ret;
  150124. }
  150125. /* initialize management with sane defaults */
  150126. hi->managed=1;
  150127. hi->bitrate_min=min_bitrate;
  150128. hi->bitrate_max=max_bitrate;
  150129. hi->bitrate_av=tnominal;
  150130. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  150131. hi->bitrate_reservoir=nominal_bitrate*2;
  150132. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  150133. return(ret);
  150134. }
  150135. int vorbis_encode_init(vorbis_info *vi,
  150136. long channels,
  150137. long rate,
  150138. long max_bitrate,
  150139. long nominal_bitrate,
  150140. long min_bitrate){
  150141. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  150142. max_bitrate,
  150143. nominal_bitrate,
  150144. min_bitrate);
  150145. if(ret){
  150146. vorbis_info_clear(vi);
  150147. return(ret);
  150148. }
  150149. ret=vorbis_encode_setup_init(vi);
  150150. if(ret)
  150151. vorbis_info_clear(vi);
  150152. return(ret);
  150153. }
  150154. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  150155. if(vi){
  150156. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150157. highlevel_encode_setup *hi=&ci->hi;
  150158. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  150159. if(setp && hi->set_in_stone)return(OV_EINVAL);
  150160. switch(number){
  150161. /* now deprecated *****************/
  150162. case OV_ECTL_RATEMANAGE_GET:
  150163. {
  150164. struct ovectl_ratemanage_arg *ai=
  150165. (struct ovectl_ratemanage_arg *)arg;
  150166. ai->management_active=hi->managed;
  150167. ai->bitrate_hard_window=ai->bitrate_av_window=
  150168. (double)hi->bitrate_reservoir/vi->rate;
  150169. ai->bitrate_av_window_center=1.;
  150170. ai->bitrate_hard_min=hi->bitrate_min;
  150171. ai->bitrate_hard_max=hi->bitrate_max;
  150172. ai->bitrate_av_lo=hi->bitrate_av;
  150173. ai->bitrate_av_hi=hi->bitrate_av;
  150174. }
  150175. return(0);
  150176. /* now deprecated *****************/
  150177. case OV_ECTL_RATEMANAGE_SET:
  150178. {
  150179. struct ovectl_ratemanage_arg *ai=
  150180. (struct ovectl_ratemanage_arg *)arg;
  150181. if(ai==NULL){
  150182. hi->managed=0;
  150183. }else{
  150184. hi->managed=ai->management_active;
  150185. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  150186. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  150187. }
  150188. }
  150189. return 0;
  150190. /* now deprecated *****************/
  150191. case OV_ECTL_RATEMANAGE_AVG:
  150192. {
  150193. struct ovectl_ratemanage_arg *ai=
  150194. (struct ovectl_ratemanage_arg *)arg;
  150195. if(ai==NULL){
  150196. hi->bitrate_av=0;
  150197. }else{
  150198. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  150199. }
  150200. }
  150201. return(0);
  150202. /* now deprecated *****************/
  150203. case OV_ECTL_RATEMANAGE_HARD:
  150204. {
  150205. struct ovectl_ratemanage_arg *ai=
  150206. (struct ovectl_ratemanage_arg *)arg;
  150207. if(ai==NULL){
  150208. hi->bitrate_min=0;
  150209. hi->bitrate_max=0;
  150210. }else{
  150211. hi->bitrate_min=ai->bitrate_hard_min;
  150212. hi->bitrate_max=ai->bitrate_hard_max;
  150213. hi->bitrate_reservoir=ai->bitrate_hard_window*
  150214. (hi->bitrate_max+hi->bitrate_min)*.5;
  150215. }
  150216. if(hi->bitrate_reservoir<128.)
  150217. hi->bitrate_reservoir=128.;
  150218. }
  150219. return(0);
  150220. /* replacement ratemanage interface */
  150221. case OV_ECTL_RATEMANAGE2_GET:
  150222. {
  150223. struct ovectl_ratemanage2_arg *ai=
  150224. (struct ovectl_ratemanage2_arg *)arg;
  150225. if(ai==NULL)return OV_EINVAL;
  150226. ai->management_active=hi->managed;
  150227. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  150228. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  150229. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  150230. ai->bitrate_average_damping=hi->bitrate_av_damp;
  150231. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  150232. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  150233. }
  150234. return (0);
  150235. case OV_ECTL_RATEMANAGE2_SET:
  150236. {
  150237. struct ovectl_ratemanage2_arg *ai=
  150238. (struct ovectl_ratemanage2_arg *)arg;
  150239. if(ai==NULL){
  150240. hi->managed=0;
  150241. }else{
  150242. /* sanity check; only catch invariant violations */
  150243. if(ai->bitrate_limit_min_kbps>0 &&
  150244. ai->bitrate_average_kbps>0 &&
  150245. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  150246. return OV_EINVAL;
  150247. if(ai->bitrate_limit_max_kbps>0 &&
  150248. ai->bitrate_average_kbps>0 &&
  150249. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  150250. return OV_EINVAL;
  150251. if(ai->bitrate_limit_min_kbps>0 &&
  150252. ai->bitrate_limit_max_kbps>0 &&
  150253. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  150254. return OV_EINVAL;
  150255. if(ai->bitrate_average_damping <= 0.)
  150256. return OV_EINVAL;
  150257. if(ai->bitrate_limit_reservoir_bits < 0)
  150258. return OV_EINVAL;
  150259. if(ai->bitrate_limit_reservoir_bias < 0.)
  150260. return OV_EINVAL;
  150261. if(ai->bitrate_limit_reservoir_bias > 1.)
  150262. return OV_EINVAL;
  150263. hi->managed=ai->management_active;
  150264. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  150265. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  150266. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  150267. hi->bitrate_av_damp=ai->bitrate_average_damping;
  150268. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  150269. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  150270. }
  150271. }
  150272. return 0;
  150273. case OV_ECTL_LOWPASS_GET:
  150274. {
  150275. double *farg=(double *)arg;
  150276. *farg=hi->lowpass_kHz;
  150277. }
  150278. return(0);
  150279. case OV_ECTL_LOWPASS_SET:
  150280. {
  150281. double *farg=(double *)arg;
  150282. hi->lowpass_kHz=*farg;
  150283. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  150284. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  150285. }
  150286. return(0);
  150287. case OV_ECTL_IBLOCK_GET:
  150288. {
  150289. double *farg=(double *)arg;
  150290. *farg=hi->impulse_noisetune;
  150291. }
  150292. return(0);
  150293. case OV_ECTL_IBLOCK_SET:
  150294. {
  150295. double *farg=(double *)arg;
  150296. hi->impulse_noisetune=*farg;
  150297. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  150298. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  150299. }
  150300. return(0);
  150301. }
  150302. return(OV_EIMPL);
  150303. }
  150304. return(OV_EINVAL);
  150305. }
  150306. #endif
  150307. /********* End of inlined file: vorbisenc.c *********/
  150308. /********* Start of inlined file: vorbisfile.c *********/
  150309. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  150310. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  150311. // tasks..
  150312. #ifdef _MSC_VER
  150313. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  150314. #endif
  150315. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  150316. #if JUCE_USE_OGGVORBIS
  150317. #include <stdlib.h>
  150318. #include <stdio.h>
  150319. #include <errno.h>
  150320. #include <string.h>
  150321. #include <math.h>
  150322. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  150323. one logical bitstream arranged end to end (the only form of Ogg
  150324. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  150325. multiplexing] is not allowed in Vorbis) */
  150326. /* A Vorbis file can be played beginning to end (streamed) without
  150327. worrying ahead of time about chaining (see decoder_example.c). If
  150328. we have the whole file, however, and want random access
  150329. (seeking/scrubbing) or desire to know the total length/time of a
  150330. file, we need to account for the possibility of chaining. */
  150331. /* We can handle things a number of ways; we can determine the entire
  150332. bitstream structure right off the bat, or find pieces on demand.
  150333. This example determines and caches structure for the entire
  150334. bitstream, but builds a virtual decoder on the fly when moving
  150335. between links in the chain. */
  150336. /* There are also different ways to implement seeking. Enough
  150337. information exists in an Ogg bitstream to seek to
  150338. sample-granularity positions in the output. Or, one can seek by
  150339. picking some portion of the stream roughly in the desired area if
  150340. we only want coarse navigation through the stream. */
  150341. /*************************************************************************
  150342. * Many, many internal helpers. The intention is not to be confusing;
  150343. * rampant duplication and monolithic function implementation would be
  150344. * harder to understand anyway. The high level functions are last. Begin
  150345. * grokking near the end of the file */
  150346. /* read a little more data from the file/pipe into the ogg_sync framer
  150347. */
  150348. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  150349. over 8k gets what they deserve */
  150350. static long _get_data(OggVorbis_File *vf){
  150351. errno=0;
  150352. if(vf->datasource){
  150353. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  150354. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  150355. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  150356. if(bytes==0 && errno)return(-1);
  150357. return(bytes);
  150358. }else
  150359. return(0);
  150360. }
  150361. /* save a tiny smidge of verbosity to make the code more readable */
  150362. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  150363. if(vf->datasource){
  150364. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  150365. vf->offset=offset;
  150366. ogg_sync_reset(&vf->oy);
  150367. }else{
  150368. /* shouldn't happen unless someone writes a broken callback */
  150369. return;
  150370. }
  150371. }
  150372. /* The read/seek functions track absolute position within the stream */
  150373. /* from the head of the stream, get the next page. boundary specifies
  150374. if the function is allowed to fetch more data from the stream (and
  150375. how much) or only use internally buffered data.
  150376. boundary: -1) unbounded search
  150377. 0) read no additional data; use cached only
  150378. n) search for a new page beginning for n bytes
  150379. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  150380. n) found a page at absolute offset n */
  150381. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  150382. ogg_int64_t boundary){
  150383. if(boundary>0)boundary+=vf->offset;
  150384. while(1){
  150385. long more;
  150386. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  150387. more=ogg_sync_pageseek(&vf->oy,og);
  150388. if(more<0){
  150389. /* skipped n bytes */
  150390. vf->offset-=more;
  150391. }else{
  150392. if(more==0){
  150393. /* send more paramedics */
  150394. if(!boundary)return(OV_FALSE);
  150395. {
  150396. long ret=_get_data(vf);
  150397. if(ret==0)return(OV_EOF);
  150398. if(ret<0)return(OV_EREAD);
  150399. }
  150400. }else{
  150401. /* got a page. Return the offset at the page beginning,
  150402. advance the internal offset past the page end */
  150403. ogg_int64_t ret=vf->offset;
  150404. vf->offset+=more;
  150405. return(ret);
  150406. }
  150407. }
  150408. }
  150409. }
  150410. /* find the latest page beginning before the current stream cursor
  150411. position. Much dirtier than the above as Ogg doesn't have any
  150412. backward search linkage. no 'readp' as it will certainly have to
  150413. read. */
  150414. /* returns offset or OV_EREAD, OV_FAULT */
  150415. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  150416. ogg_int64_t begin=vf->offset;
  150417. ogg_int64_t end=begin;
  150418. ogg_int64_t ret;
  150419. ogg_int64_t offset=-1;
  150420. while(offset==-1){
  150421. begin-=CHUNKSIZE;
  150422. if(begin<0)
  150423. begin=0;
  150424. _seek_helper(vf,begin);
  150425. while(vf->offset<end){
  150426. ret=_get_next_page(vf,og,end-vf->offset);
  150427. if(ret==OV_EREAD)return(OV_EREAD);
  150428. if(ret<0){
  150429. break;
  150430. }else{
  150431. offset=ret;
  150432. }
  150433. }
  150434. }
  150435. /* we have the offset. Actually snork and hold the page now */
  150436. _seek_helper(vf,offset);
  150437. ret=_get_next_page(vf,og,CHUNKSIZE);
  150438. if(ret<0)
  150439. /* this shouldn't be possible */
  150440. return(OV_EFAULT);
  150441. return(offset);
  150442. }
  150443. /* finds each bitstream link one at a time using a bisection search
  150444. (has to begin by knowing the offset of the lb's initial page).
  150445. Recurses for each link so it can alloc the link storage after
  150446. finding them all, then unroll and fill the cache at the same time */
  150447. static int _bisect_forward_serialno(OggVorbis_File *vf,
  150448. ogg_int64_t begin,
  150449. ogg_int64_t searched,
  150450. ogg_int64_t end,
  150451. long currentno,
  150452. long m){
  150453. ogg_int64_t endsearched=end;
  150454. ogg_int64_t next=end;
  150455. ogg_page og;
  150456. ogg_int64_t ret;
  150457. /* the below guards against garbage seperating the last and
  150458. first pages of two links. */
  150459. while(searched<endsearched){
  150460. ogg_int64_t bisect;
  150461. if(endsearched-searched<CHUNKSIZE){
  150462. bisect=searched;
  150463. }else{
  150464. bisect=(searched+endsearched)/2;
  150465. }
  150466. _seek_helper(vf,bisect);
  150467. ret=_get_next_page(vf,&og,-1);
  150468. if(ret==OV_EREAD)return(OV_EREAD);
  150469. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  150470. endsearched=bisect;
  150471. if(ret>=0)next=ret;
  150472. }else{
  150473. searched=ret+og.header_len+og.body_len;
  150474. }
  150475. }
  150476. _seek_helper(vf,next);
  150477. ret=_get_next_page(vf,&og,-1);
  150478. if(ret==OV_EREAD)return(OV_EREAD);
  150479. if(searched>=end || ret<0){
  150480. vf->links=m+1;
  150481. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  150482. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  150483. vf->offsets[m+1]=searched;
  150484. }else{
  150485. ret=_bisect_forward_serialno(vf,next,vf->offset,
  150486. end,ogg_page_serialno(&og),m+1);
  150487. if(ret==OV_EREAD)return(OV_EREAD);
  150488. }
  150489. vf->offsets[m]=begin;
  150490. vf->serialnos[m]=currentno;
  150491. return(0);
  150492. }
  150493. /* uses the local ogg_stream storage in vf; this is important for
  150494. non-streaming input sources */
  150495. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  150496. long *serialno,ogg_page *og_ptr){
  150497. ogg_page og;
  150498. ogg_packet op;
  150499. int i,ret;
  150500. if(!og_ptr){
  150501. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  150502. if(llret==OV_EREAD)return(OV_EREAD);
  150503. if(llret<0)return OV_ENOTVORBIS;
  150504. og_ptr=&og;
  150505. }
  150506. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  150507. if(serialno)*serialno=vf->os.serialno;
  150508. vf->ready_state=STREAMSET;
  150509. /* extract the initial header from the first page and verify that the
  150510. Ogg bitstream is in fact Vorbis data */
  150511. vorbis_info_init(vi);
  150512. vorbis_comment_init(vc);
  150513. i=0;
  150514. while(i<3){
  150515. ogg_stream_pagein(&vf->os,og_ptr);
  150516. while(i<3){
  150517. int result=ogg_stream_packetout(&vf->os,&op);
  150518. if(result==0)break;
  150519. if(result==-1){
  150520. ret=OV_EBADHEADER;
  150521. goto bail_header;
  150522. }
  150523. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  150524. goto bail_header;
  150525. }
  150526. i++;
  150527. }
  150528. if(i<3)
  150529. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  150530. ret=OV_EBADHEADER;
  150531. goto bail_header;
  150532. }
  150533. }
  150534. return 0;
  150535. bail_header:
  150536. vorbis_info_clear(vi);
  150537. vorbis_comment_clear(vc);
  150538. vf->ready_state=OPENED;
  150539. return ret;
  150540. }
  150541. /* last step of the OggVorbis_File initialization; get all the
  150542. vorbis_info structs and PCM positions. Only called by the seekable
  150543. initialization (local stream storage is hacked slightly; pay
  150544. attention to how that's done) */
  150545. /* this is void and does not propogate errors up because we want to be
  150546. able to open and use damaged bitstreams as well as we can. Just
  150547. watch out for missing information for links in the OggVorbis_File
  150548. struct */
  150549. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  150550. ogg_page og;
  150551. int i;
  150552. ogg_int64_t ret;
  150553. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  150554. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  150555. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  150556. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  150557. for(i=0;i<vf->links;i++){
  150558. if(i==0){
  150559. /* we already grabbed the initial header earlier. Just set the offset */
  150560. vf->dataoffsets[i]=dataoffset;
  150561. _seek_helper(vf,dataoffset);
  150562. }else{
  150563. /* seek to the location of the initial header */
  150564. _seek_helper(vf,vf->offsets[i]);
  150565. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  150566. vf->dataoffsets[i]=-1;
  150567. }else{
  150568. vf->dataoffsets[i]=vf->offset;
  150569. }
  150570. }
  150571. /* fetch beginning PCM offset */
  150572. if(vf->dataoffsets[i]!=-1){
  150573. ogg_int64_t accumulated=0;
  150574. long lastblock=-1;
  150575. int result;
  150576. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  150577. while(1){
  150578. ogg_packet op;
  150579. ret=_get_next_page(vf,&og,-1);
  150580. if(ret<0)
  150581. /* this should not be possible unless the file is
  150582. truncated/mangled */
  150583. break;
  150584. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  150585. break;
  150586. /* count blocksizes of all frames in the page */
  150587. ogg_stream_pagein(&vf->os,&og);
  150588. while((result=ogg_stream_packetout(&vf->os,&op))){
  150589. if(result>0){ /* ignore holes */
  150590. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  150591. if(lastblock!=-1)
  150592. accumulated+=(lastblock+thisblock)>>2;
  150593. lastblock=thisblock;
  150594. }
  150595. }
  150596. if(ogg_page_granulepos(&og)!=-1){
  150597. /* pcm offset of last packet on the first audio page */
  150598. accumulated= ogg_page_granulepos(&og)-accumulated;
  150599. break;
  150600. }
  150601. }
  150602. /* less than zero? This is a stream with samples trimmed off
  150603. the beginning, a normal occurrence; set the offset to zero */
  150604. if(accumulated<0)accumulated=0;
  150605. vf->pcmlengths[i*2]=accumulated;
  150606. }
  150607. /* get the PCM length of this link. To do this,
  150608. get the last page of the stream */
  150609. {
  150610. ogg_int64_t end=vf->offsets[i+1];
  150611. _seek_helper(vf,end);
  150612. while(1){
  150613. ret=_get_prev_page(vf,&og);
  150614. if(ret<0){
  150615. /* this should not be possible */
  150616. vorbis_info_clear(vf->vi+i);
  150617. vorbis_comment_clear(vf->vc+i);
  150618. break;
  150619. }
  150620. if(ogg_page_granulepos(&og)!=-1){
  150621. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  150622. break;
  150623. }
  150624. vf->offset=ret;
  150625. }
  150626. }
  150627. }
  150628. }
  150629. static int _make_decode_ready(OggVorbis_File *vf){
  150630. if(vf->ready_state>STREAMSET)return 0;
  150631. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  150632. if(vf->seekable){
  150633. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  150634. return OV_EBADLINK;
  150635. }else{
  150636. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  150637. return OV_EBADLINK;
  150638. }
  150639. vorbis_block_init(&vf->vd,&vf->vb);
  150640. vf->ready_state=INITSET;
  150641. vf->bittrack=0.f;
  150642. vf->samptrack=0.f;
  150643. return 0;
  150644. }
  150645. static int _open_seekable2(OggVorbis_File *vf){
  150646. long serialno=vf->current_serialno;
  150647. ogg_int64_t dataoffset=vf->offset, end;
  150648. ogg_page og;
  150649. /* we're partially open and have a first link header state in
  150650. storage in vf */
  150651. /* we can seek, so set out learning all about this file */
  150652. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  150653. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  150654. /* We get the offset for the last page of the physical bitstream.
  150655. Most OggVorbis files will contain a single logical bitstream */
  150656. end=_get_prev_page(vf,&og);
  150657. if(end<0)return(end);
  150658. /* more than one logical bitstream? */
  150659. if(ogg_page_serialno(&og)!=serialno){
  150660. /* Chained bitstream. Bisect-search each logical bitstream
  150661. section. Do so based on serial number only */
  150662. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  150663. }else{
  150664. /* Only one logical bitstream */
  150665. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  150666. }
  150667. /* the initial header memory is referenced by vf after; don't free it */
  150668. _prefetch_all_headers(vf,dataoffset);
  150669. return(ov_raw_seek(vf,0));
  150670. }
  150671. /* clear out the current logical bitstream decoder */
  150672. static void _decode_clear(OggVorbis_File *vf){
  150673. vorbis_dsp_clear(&vf->vd);
  150674. vorbis_block_clear(&vf->vb);
  150675. vf->ready_state=OPENED;
  150676. }
  150677. /* fetch and process a packet. Handles the case where we're at a
  150678. bitstream boundary and dumps the decoding machine. If the decoding
  150679. machine is unloaded, it loads it. It also keeps pcm_offset up to
  150680. date (seek and read both use this. seek uses a special hack with
  150681. readp).
  150682. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  150683. 0) need more data (only if readp==0)
  150684. 1) got a packet
  150685. */
  150686. static int _fetch_and_process_packet(OggVorbis_File *vf,
  150687. ogg_packet *op_in,
  150688. int readp,
  150689. int spanp){
  150690. ogg_page og;
  150691. /* handle one packet. Try to fetch it from current stream state */
  150692. /* extract packets from page */
  150693. while(1){
  150694. /* process a packet if we can. If the machine isn't loaded,
  150695. neither is a page */
  150696. if(vf->ready_state==INITSET){
  150697. while(1) {
  150698. ogg_packet op;
  150699. ogg_packet *op_ptr=(op_in?op_in:&op);
  150700. int result=ogg_stream_packetout(&vf->os,op_ptr);
  150701. ogg_int64_t granulepos;
  150702. op_in=NULL;
  150703. if(result==-1)return(OV_HOLE); /* hole in the data. */
  150704. if(result>0){
  150705. /* got a packet. process it */
  150706. granulepos=op_ptr->granulepos;
  150707. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  150708. header handling. The
  150709. header packets aren't
  150710. audio, so if/when we
  150711. submit them,
  150712. vorbis_synthesis will
  150713. reject them */
  150714. /* suck in the synthesis data and track bitrate */
  150715. {
  150716. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  150717. /* for proper use of libvorbis within libvorbisfile,
  150718. oldsamples will always be zero. */
  150719. if(oldsamples)return(OV_EFAULT);
  150720. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  150721. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  150722. vf->bittrack+=op_ptr->bytes*8;
  150723. }
  150724. /* update the pcm offset. */
  150725. if(granulepos!=-1 && !op_ptr->e_o_s){
  150726. int link=(vf->seekable?vf->current_link:0);
  150727. int i,samples;
  150728. /* this packet has a pcm_offset on it (the last packet
  150729. completed on a page carries the offset) After processing
  150730. (above), we know the pcm position of the *last* sample
  150731. ready to be returned. Find the offset of the *first*
  150732. As an aside, this trick is inaccurate if we begin
  150733. reading anew right at the last page; the end-of-stream
  150734. granulepos declares the last frame in the stream, and the
  150735. last packet of the last page may be a partial frame.
  150736. So, we need a previous granulepos from an in-sequence page
  150737. to have a reference point. Thus the !op_ptr->e_o_s clause
  150738. above */
  150739. if(vf->seekable && link>0)
  150740. granulepos-=vf->pcmlengths[link*2];
  150741. if(granulepos<0)granulepos=0; /* actually, this
  150742. shouldn't be possible
  150743. here unless the stream
  150744. is very broken */
  150745. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  150746. granulepos-=samples;
  150747. for(i=0;i<link;i++)
  150748. granulepos+=vf->pcmlengths[i*2+1];
  150749. vf->pcm_offset=granulepos;
  150750. }
  150751. return(1);
  150752. }
  150753. }
  150754. else
  150755. break;
  150756. }
  150757. }
  150758. if(vf->ready_state>=OPENED){
  150759. ogg_int64_t ret;
  150760. if(!readp)return(0);
  150761. if((ret=_get_next_page(vf,&og,-1))<0){
  150762. return(OV_EOF); /* eof.
  150763. leave unitialized */
  150764. }
  150765. /* bitrate tracking; add the header's bytes here, the body bytes
  150766. are done by packet above */
  150767. vf->bittrack+=og.header_len*8;
  150768. /* has our decoding just traversed a bitstream boundary? */
  150769. if(vf->ready_state==INITSET){
  150770. if(vf->current_serialno!=ogg_page_serialno(&og)){
  150771. if(!spanp)
  150772. return(OV_EOF);
  150773. _decode_clear(vf);
  150774. if(!vf->seekable){
  150775. vorbis_info_clear(vf->vi);
  150776. vorbis_comment_clear(vf->vc);
  150777. }
  150778. }
  150779. }
  150780. }
  150781. /* Do we need to load a new machine before submitting the page? */
  150782. /* This is different in the seekable and non-seekable cases.
  150783. In the seekable case, we already have all the header
  150784. information loaded and cached; we just initialize the machine
  150785. with it and continue on our merry way.
  150786. In the non-seekable (streaming) case, we'll only be at a
  150787. boundary if we just left the previous logical bitstream and
  150788. we're now nominally at the header of the next bitstream
  150789. */
  150790. if(vf->ready_state!=INITSET){
  150791. int link;
  150792. if(vf->ready_state<STREAMSET){
  150793. if(vf->seekable){
  150794. vf->current_serialno=ogg_page_serialno(&og);
  150795. /* match the serialno to bitstream section. We use this rather than
  150796. offset positions to avoid problems near logical bitstream
  150797. boundaries */
  150798. for(link=0;link<vf->links;link++)
  150799. if(vf->serialnos[link]==vf->current_serialno)break;
  150800. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  150801. stream. error out,
  150802. leave machine
  150803. uninitialized */
  150804. vf->current_link=link;
  150805. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  150806. vf->ready_state=STREAMSET;
  150807. }else{
  150808. /* we're streaming */
  150809. /* fetch the three header packets, build the info struct */
  150810. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  150811. if(ret)return(ret);
  150812. vf->current_link++;
  150813. link=0;
  150814. }
  150815. }
  150816. {
  150817. int ret=_make_decode_ready(vf);
  150818. if(ret<0)return ret;
  150819. }
  150820. }
  150821. ogg_stream_pagein(&vf->os,&og);
  150822. }
  150823. }
  150824. /* if, eg, 64 bit stdio is configured by default, this will build with
  150825. fseek64 */
  150826. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  150827. if(f==NULL)return(-1);
  150828. return fseek(f,off,whence);
  150829. }
  150830. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  150831. long ibytes, ov_callbacks callbacks){
  150832. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  150833. int ret;
  150834. memset(vf,0,sizeof(*vf));
  150835. vf->datasource=f;
  150836. vf->callbacks = callbacks;
  150837. /* init the framing state */
  150838. ogg_sync_init(&vf->oy);
  150839. /* perhaps some data was previously read into a buffer for testing
  150840. against other stream types. Allow initialization from this
  150841. previously read data (as we may be reading from a non-seekable
  150842. stream) */
  150843. if(initial){
  150844. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  150845. memcpy(buffer,initial,ibytes);
  150846. ogg_sync_wrote(&vf->oy,ibytes);
  150847. }
  150848. /* can we seek? Stevens suggests the seek test was portable */
  150849. if(offsettest!=-1)vf->seekable=1;
  150850. /* No seeking yet; Set up a 'single' (current) logical bitstream
  150851. entry for partial open */
  150852. vf->links=1;
  150853. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  150854. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  150855. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  150856. /* Try to fetch the headers, maintaining all the storage */
  150857. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  150858. vf->datasource=NULL;
  150859. ov_clear(vf);
  150860. }else
  150861. vf->ready_state=PARTOPEN;
  150862. return(ret);
  150863. }
  150864. static int _ov_open2(OggVorbis_File *vf){
  150865. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  150866. vf->ready_state=OPENED;
  150867. if(vf->seekable){
  150868. int ret=_open_seekable2(vf);
  150869. if(ret){
  150870. vf->datasource=NULL;
  150871. ov_clear(vf);
  150872. }
  150873. return(ret);
  150874. }else
  150875. vf->ready_state=STREAMSET;
  150876. return 0;
  150877. }
  150878. /* clear out the OggVorbis_File struct */
  150879. int ov_clear(OggVorbis_File *vf){
  150880. if(vf){
  150881. vorbis_block_clear(&vf->vb);
  150882. vorbis_dsp_clear(&vf->vd);
  150883. ogg_stream_clear(&vf->os);
  150884. if(vf->vi && vf->links){
  150885. int i;
  150886. for(i=0;i<vf->links;i++){
  150887. vorbis_info_clear(vf->vi+i);
  150888. vorbis_comment_clear(vf->vc+i);
  150889. }
  150890. _ogg_free(vf->vi);
  150891. _ogg_free(vf->vc);
  150892. }
  150893. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  150894. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  150895. if(vf->serialnos)_ogg_free(vf->serialnos);
  150896. if(vf->offsets)_ogg_free(vf->offsets);
  150897. ogg_sync_clear(&vf->oy);
  150898. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  150899. memset(vf,0,sizeof(*vf));
  150900. }
  150901. #ifdef DEBUG_LEAKS
  150902. _VDBG_dump();
  150903. #endif
  150904. return(0);
  150905. }
  150906. /* inspects the OggVorbis file and finds/documents all the logical
  150907. bitstreams contained in it. Tries to be tolerant of logical
  150908. bitstream sections that are truncated/woogie.
  150909. return: -1) error
  150910. 0) OK
  150911. */
  150912. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  150913. ov_callbacks callbacks){
  150914. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  150915. if(ret)return ret;
  150916. return _ov_open2(vf);
  150917. }
  150918. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  150919. ov_callbacks callbacks = {
  150920. (size_t (*)(void *, size_t, size_t, void *)) fread,
  150921. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  150922. (int (*)(void *)) fclose,
  150923. (long (*)(void *)) ftell
  150924. };
  150925. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  150926. }
  150927. /* cheap hack for game usage where downsampling is desirable; there's
  150928. no need for SRC as we can just do it cheaply in libvorbis. */
  150929. int ov_halfrate(OggVorbis_File *vf,int flag){
  150930. int i;
  150931. if(vf->vi==NULL)return OV_EINVAL;
  150932. if(!vf->seekable)return OV_EINVAL;
  150933. if(vf->ready_state>=STREAMSET)
  150934. _decode_clear(vf); /* clear out stream state; later on libvorbis
  150935. will be able to swap this on the fly, but
  150936. for now dumping the decode machine is needed
  150937. to reinit the MDCT lookups. 1.1 libvorbis
  150938. is planned to be able to switch on the fly */
  150939. for(i=0;i<vf->links;i++){
  150940. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  150941. ov_halfrate(vf,0);
  150942. return OV_EINVAL;
  150943. }
  150944. }
  150945. return 0;
  150946. }
  150947. int ov_halfrate_p(OggVorbis_File *vf){
  150948. if(vf->vi==NULL)return OV_EINVAL;
  150949. return vorbis_synthesis_halfrate_p(vf->vi);
  150950. }
  150951. /* Only partially open the vorbis file; test for Vorbisness, and load
  150952. the headers for the first chain. Do not seek (although test for
  150953. seekability). Use ov_test_open to finish opening the file, else
  150954. ov_clear to close/free it. Same return codes as open. */
  150955. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  150956. ov_callbacks callbacks)
  150957. {
  150958. return _ov_open1(f,vf,initial,ibytes,callbacks);
  150959. }
  150960. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  150961. ov_callbacks callbacks = {
  150962. (size_t (*)(void *, size_t, size_t, void *)) fread,
  150963. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  150964. (int (*)(void *)) fclose,
  150965. (long (*)(void *)) ftell
  150966. };
  150967. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  150968. }
  150969. int ov_test_open(OggVorbis_File *vf){
  150970. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  150971. return _ov_open2(vf);
  150972. }
  150973. /* How many logical bitstreams in this physical bitstream? */
  150974. long ov_streams(OggVorbis_File *vf){
  150975. return vf->links;
  150976. }
  150977. /* Is the FILE * associated with vf seekable? */
  150978. long ov_seekable(OggVorbis_File *vf){
  150979. return vf->seekable;
  150980. }
  150981. /* returns the bitrate for a given logical bitstream or the entire
  150982. physical bitstream. If the file is open for random access, it will
  150983. find the *actual* average bitrate. If the file is streaming, it
  150984. returns the nominal bitrate (if set) else the average of the
  150985. upper/lower bounds (if set) else -1 (unset).
  150986. If you want the actual bitrate field settings, get them from the
  150987. vorbis_info structs */
  150988. long ov_bitrate(OggVorbis_File *vf,int i){
  150989. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150990. if(i>=vf->links)return(OV_EINVAL);
  150991. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  150992. if(i<0){
  150993. ogg_int64_t bits=0;
  150994. int i;
  150995. float br;
  150996. for(i=0;i<vf->links;i++)
  150997. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  150998. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  150999. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  151000. * so this is slightly transformed to make it work.
  151001. */
  151002. br = bits/ov_time_total(vf,-1);
  151003. return(rint(br));
  151004. }else{
  151005. if(vf->seekable){
  151006. /* return the actual bitrate */
  151007. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  151008. }else{
  151009. /* return nominal if set */
  151010. if(vf->vi[i].bitrate_nominal>0){
  151011. return vf->vi[i].bitrate_nominal;
  151012. }else{
  151013. if(vf->vi[i].bitrate_upper>0){
  151014. if(vf->vi[i].bitrate_lower>0){
  151015. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  151016. }else{
  151017. return vf->vi[i].bitrate_upper;
  151018. }
  151019. }
  151020. return(OV_FALSE);
  151021. }
  151022. }
  151023. }
  151024. }
  151025. /* returns the actual bitrate since last call. returns -1 if no
  151026. additional data to offer since last call (or at beginning of stream),
  151027. EINVAL if stream is only partially open
  151028. */
  151029. long ov_bitrate_instant(OggVorbis_File *vf){
  151030. int link=(vf->seekable?vf->current_link:0);
  151031. long ret;
  151032. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151033. if(vf->samptrack==0)return(OV_FALSE);
  151034. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  151035. vf->bittrack=0.f;
  151036. vf->samptrack=0.f;
  151037. return(ret);
  151038. }
  151039. /* Guess */
  151040. long ov_serialnumber(OggVorbis_File *vf,int i){
  151041. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  151042. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  151043. if(i<0){
  151044. return(vf->current_serialno);
  151045. }else{
  151046. return(vf->serialnos[i]);
  151047. }
  151048. }
  151049. /* returns: total raw (compressed) length of content if i==-1
  151050. raw (compressed) length of that logical bitstream for i==0 to n
  151051. OV_EINVAL if the stream is not seekable (we can't know the length)
  151052. or if stream is only partially open
  151053. */
  151054. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  151055. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151056. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151057. if(i<0){
  151058. ogg_int64_t acc=0;
  151059. int i;
  151060. for(i=0;i<vf->links;i++)
  151061. acc+=ov_raw_total(vf,i);
  151062. return(acc);
  151063. }else{
  151064. return(vf->offsets[i+1]-vf->offsets[i]);
  151065. }
  151066. }
  151067. /* returns: total PCM length (samples) of content if i==-1 PCM length
  151068. (samples) of that logical bitstream for i==0 to n
  151069. OV_EINVAL if the stream is not seekable (we can't know the
  151070. length) or only partially open
  151071. */
  151072. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  151073. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151074. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151075. if(i<0){
  151076. ogg_int64_t acc=0;
  151077. int i;
  151078. for(i=0;i<vf->links;i++)
  151079. acc+=ov_pcm_total(vf,i);
  151080. return(acc);
  151081. }else{
  151082. return(vf->pcmlengths[i*2+1]);
  151083. }
  151084. }
  151085. /* returns: total seconds of content if i==-1
  151086. seconds in that logical bitstream for i==0 to n
  151087. OV_EINVAL if the stream is not seekable (we can't know the
  151088. length) or only partially open
  151089. */
  151090. double ov_time_total(OggVorbis_File *vf,int i){
  151091. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151092. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151093. if(i<0){
  151094. double acc=0;
  151095. int i;
  151096. for(i=0;i<vf->links;i++)
  151097. acc+=ov_time_total(vf,i);
  151098. return(acc);
  151099. }else{
  151100. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  151101. }
  151102. }
  151103. /* seek to an offset relative to the *compressed* data. This also
  151104. scans packets to update the PCM cursor. It will cross a logical
  151105. bitstream boundary, but only if it can't get any packets out of the
  151106. tail of the bitstream we seek to (so no surprises).
  151107. returns zero on success, nonzero on failure */
  151108. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  151109. ogg_stream_state work_os;
  151110. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151111. if(!vf->seekable)
  151112. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  151113. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  151114. /* don't yet clear out decoding machine (if it's initialized), in
  151115. the case we're in the same link. Restart the decode lapping, and
  151116. let _fetch_and_process_packet deal with a potential bitstream
  151117. boundary */
  151118. vf->pcm_offset=-1;
  151119. ogg_stream_reset_serialno(&vf->os,
  151120. vf->current_serialno); /* must set serialno */
  151121. vorbis_synthesis_restart(&vf->vd);
  151122. _seek_helper(vf,pos);
  151123. /* we need to make sure the pcm_offset is set, but we don't want to
  151124. advance the raw cursor past good packets just to get to the first
  151125. with a granulepos. That's not equivalent behavior to beginning
  151126. decoding as immediately after the seek position as possible.
  151127. So, a hack. We use two stream states; a local scratch state and
  151128. the shared vf->os stream state. We use the local state to
  151129. scan, and the shared state as a buffer for later decode.
  151130. Unfortuantely, on the last page we still advance to last packet
  151131. because the granulepos on the last page is not necessarily on a
  151132. packet boundary, and we need to make sure the granpos is
  151133. correct.
  151134. */
  151135. {
  151136. ogg_page og;
  151137. ogg_packet op;
  151138. int lastblock=0;
  151139. int accblock=0;
  151140. int thisblock;
  151141. int eosflag;
  151142. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  151143. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  151144. return from not necessarily
  151145. starting from the beginning */
  151146. while(1){
  151147. if(vf->ready_state>=STREAMSET){
  151148. /* snarf/scan a packet if we can */
  151149. int result=ogg_stream_packetout(&work_os,&op);
  151150. if(result>0){
  151151. if(vf->vi[vf->current_link].codec_setup){
  151152. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  151153. if(thisblock<0){
  151154. ogg_stream_packetout(&vf->os,NULL);
  151155. thisblock=0;
  151156. }else{
  151157. if(eosflag)
  151158. ogg_stream_packetout(&vf->os,NULL);
  151159. else
  151160. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  151161. }
  151162. if(op.granulepos!=-1){
  151163. int i,link=vf->current_link;
  151164. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  151165. if(granulepos<0)granulepos=0;
  151166. for(i=0;i<link;i++)
  151167. granulepos+=vf->pcmlengths[i*2+1];
  151168. vf->pcm_offset=granulepos-accblock;
  151169. break;
  151170. }
  151171. lastblock=thisblock;
  151172. continue;
  151173. }else
  151174. ogg_stream_packetout(&vf->os,NULL);
  151175. }
  151176. }
  151177. if(!lastblock){
  151178. if(_get_next_page(vf,&og,-1)<0){
  151179. vf->pcm_offset=ov_pcm_total(vf,-1);
  151180. break;
  151181. }
  151182. }else{
  151183. /* huh? Bogus stream with packets but no granulepos */
  151184. vf->pcm_offset=-1;
  151185. break;
  151186. }
  151187. /* has our decoding just traversed a bitstream boundary? */
  151188. if(vf->ready_state>=STREAMSET)
  151189. if(vf->current_serialno!=ogg_page_serialno(&og)){
  151190. _decode_clear(vf); /* clear out stream state */
  151191. ogg_stream_clear(&work_os);
  151192. }
  151193. if(vf->ready_state<STREAMSET){
  151194. int link;
  151195. vf->current_serialno=ogg_page_serialno(&og);
  151196. for(link=0;link<vf->links;link++)
  151197. if(vf->serialnos[link]==vf->current_serialno)break;
  151198. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  151199. error out, leave
  151200. machine uninitialized */
  151201. vf->current_link=link;
  151202. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  151203. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  151204. vf->ready_state=STREAMSET;
  151205. }
  151206. ogg_stream_pagein(&vf->os,&og);
  151207. ogg_stream_pagein(&work_os,&og);
  151208. eosflag=ogg_page_eos(&og);
  151209. }
  151210. }
  151211. ogg_stream_clear(&work_os);
  151212. vf->bittrack=0.f;
  151213. vf->samptrack=0.f;
  151214. return(0);
  151215. seek_error:
  151216. /* dump the machine so we're in a known state */
  151217. vf->pcm_offset=-1;
  151218. ogg_stream_clear(&work_os);
  151219. _decode_clear(vf);
  151220. return OV_EBADLINK;
  151221. }
  151222. /* Page granularity seek (faster than sample granularity because we
  151223. don't do the last bit of decode to find a specific sample).
  151224. Seek to the last [granule marked] page preceeding the specified pos
  151225. location, such that decoding past the returned point will quickly
  151226. arrive at the requested position. */
  151227. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  151228. int link=-1;
  151229. ogg_int64_t result=0;
  151230. ogg_int64_t total=ov_pcm_total(vf,-1);
  151231. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151232. if(!vf->seekable)return(OV_ENOSEEK);
  151233. if(pos<0 || pos>total)return(OV_EINVAL);
  151234. /* which bitstream section does this pcm offset occur in? */
  151235. for(link=vf->links-1;link>=0;link--){
  151236. total-=vf->pcmlengths[link*2+1];
  151237. if(pos>=total)break;
  151238. }
  151239. /* search within the logical bitstream for the page with the highest
  151240. pcm_pos preceeding (or equal to) pos. There is a danger here;
  151241. missing pages or incorrect frame number information in the
  151242. bitstream could make our task impossible. Account for that (it
  151243. would be an error condition) */
  151244. /* new search algorithm by HB (Nicholas Vinen) */
  151245. {
  151246. ogg_int64_t end=vf->offsets[link+1];
  151247. ogg_int64_t begin=vf->offsets[link];
  151248. ogg_int64_t begintime = vf->pcmlengths[link*2];
  151249. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  151250. ogg_int64_t target=pos-total+begintime;
  151251. ogg_int64_t best=begin;
  151252. ogg_page og;
  151253. while(begin<end){
  151254. ogg_int64_t bisect;
  151255. if(end-begin<CHUNKSIZE){
  151256. bisect=begin;
  151257. }else{
  151258. /* take a (pretty decent) guess. */
  151259. bisect=begin +
  151260. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  151261. if(bisect<=begin)
  151262. bisect=begin+1;
  151263. }
  151264. _seek_helper(vf,bisect);
  151265. while(begin<end){
  151266. result=_get_next_page(vf,&og,end-vf->offset);
  151267. if(result==OV_EREAD) goto seek_error;
  151268. if(result<0){
  151269. if(bisect<=begin+1)
  151270. end=begin; /* found it */
  151271. else{
  151272. if(bisect==0) goto seek_error;
  151273. bisect-=CHUNKSIZE;
  151274. if(bisect<=begin)bisect=begin+1;
  151275. _seek_helper(vf,bisect);
  151276. }
  151277. }else{
  151278. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  151279. if(granulepos==-1)continue;
  151280. if(granulepos<target){
  151281. best=result; /* raw offset of packet with granulepos */
  151282. begin=vf->offset; /* raw offset of next page */
  151283. begintime=granulepos;
  151284. if(target-begintime>44100)break;
  151285. bisect=begin; /* *not* begin + 1 */
  151286. }else{
  151287. if(bisect<=begin+1)
  151288. end=begin; /* found it */
  151289. else{
  151290. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  151291. end=result;
  151292. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  151293. if(bisect<=begin)bisect=begin+1;
  151294. _seek_helper(vf,bisect);
  151295. }else{
  151296. end=result;
  151297. endtime=granulepos;
  151298. break;
  151299. }
  151300. }
  151301. }
  151302. }
  151303. }
  151304. }
  151305. /* found our page. seek to it, update pcm offset. Easier case than
  151306. raw_seek, don't keep packets preceeding granulepos. */
  151307. {
  151308. ogg_page og;
  151309. ogg_packet op;
  151310. /* seek */
  151311. _seek_helper(vf,best);
  151312. vf->pcm_offset=-1;
  151313. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  151314. if(link!=vf->current_link){
  151315. /* Different link; dump entire decode machine */
  151316. _decode_clear(vf);
  151317. vf->current_link=link;
  151318. vf->current_serialno=ogg_page_serialno(&og);
  151319. vf->ready_state=STREAMSET;
  151320. }else{
  151321. vorbis_synthesis_restart(&vf->vd);
  151322. }
  151323. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  151324. ogg_stream_pagein(&vf->os,&og);
  151325. /* pull out all but last packet; the one with granulepos */
  151326. while(1){
  151327. result=ogg_stream_packetpeek(&vf->os,&op);
  151328. if(result==0){
  151329. /* !!! the packet finishing this page originated on a
  151330. preceeding page. Keep fetching previous pages until we
  151331. get one with a granulepos or without the 'continued' flag
  151332. set. Then just use raw_seek for simplicity. */
  151333. _seek_helper(vf,best);
  151334. while(1){
  151335. result=_get_prev_page(vf,&og);
  151336. if(result<0) goto seek_error;
  151337. if(ogg_page_granulepos(&og)>-1 ||
  151338. !ogg_page_continued(&og)){
  151339. return ov_raw_seek(vf,result);
  151340. }
  151341. vf->offset=result;
  151342. }
  151343. }
  151344. if(result<0){
  151345. result = OV_EBADPACKET;
  151346. goto seek_error;
  151347. }
  151348. if(op.granulepos!=-1){
  151349. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  151350. if(vf->pcm_offset<0)vf->pcm_offset=0;
  151351. vf->pcm_offset+=total;
  151352. break;
  151353. }else
  151354. result=ogg_stream_packetout(&vf->os,NULL);
  151355. }
  151356. }
  151357. }
  151358. /* verify result */
  151359. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  151360. result=OV_EFAULT;
  151361. goto seek_error;
  151362. }
  151363. vf->bittrack=0.f;
  151364. vf->samptrack=0.f;
  151365. return(0);
  151366. seek_error:
  151367. /* dump machine so we're in a known state */
  151368. vf->pcm_offset=-1;
  151369. _decode_clear(vf);
  151370. return (int)result;
  151371. }
  151372. /* seek to a sample offset relative to the decompressed pcm stream
  151373. returns zero on success, nonzero on failure */
  151374. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  151375. int thisblock,lastblock=0;
  151376. int ret=ov_pcm_seek_page(vf,pos);
  151377. if(ret<0)return(ret);
  151378. if((ret=_make_decode_ready(vf)))return ret;
  151379. /* discard leading packets we don't need for the lapping of the
  151380. position we want; don't decode them */
  151381. while(1){
  151382. ogg_packet op;
  151383. ogg_page og;
  151384. int ret=ogg_stream_packetpeek(&vf->os,&op);
  151385. if(ret>0){
  151386. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  151387. if(thisblock<0){
  151388. ogg_stream_packetout(&vf->os,NULL);
  151389. continue; /* non audio packet */
  151390. }
  151391. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  151392. if(vf->pcm_offset+((thisblock+
  151393. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  151394. /* remove the packet from packet queue and track its granulepos */
  151395. ogg_stream_packetout(&vf->os,NULL);
  151396. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  151397. only tracking, no
  151398. pcm_decode */
  151399. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  151400. /* end of logical stream case is hard, especially with exact
  151401. length positioning. */
  151402. if(op.granulepos>-1){
  151403. int i;
  151404. /* always believe the stream markers */
  151405. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  151406. if(vf->pcm_offset<0)vf->pcm_offset=0;
  151407. for(i=0;i<vf->current_link;i++)
  151408. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  151409. }
  151410. lastblock=thisblock;
  151411. }else{
  151412. if(ret<0 && ret!=OV_HOLE)break;
  151413. /* suck in a new page */
  151414. if(_get_next_page(vf,&og,-1)<0)break;
  151415. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  151416. if(vf->ready_state<STREAMSET){
  151417. int link;
  151418. vf->current_serialno=ogg_page_serialno(&og);
  151419. for(link=0;link<vf->links;link++)
  151420. if(vf->serialnos[link]==vf->current_serialno)break;
  151421. if(link==vf->links)return(OV_EBADLINK);
  151422. vf->current_link=link;
  151423. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  151424. vf->ready_state=STREAMSET;
  151425. ret=_make_decode_ready(vf);
  151426. if(ret)return ret;
  151427. lastblock=0;
  151428. }
  151429. ogg_stream_pagein(&vf->os,&og);
  151430. }
  151431. }
  151432. vf->bittrack=0.f;
  151433. vf->samptrack=0.f;
  151434. /* discard samples until we reach the desired position. Crossing a
  151435. logical bitstream boundary with abandon is OK. */
  151436. while(vf->pcm_offset<pos){
  151437. ogg_int64_t target=pos-vf->pcm_offset;
  151438. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  151439. if(samples>target)samples=target;
  151440. vorbis_synthesis_read(&vf->vd,samples);
  151441. vf->pcm_offset+=samples;
  151442. if(samples<target)
  151443. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  151444. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  151445. }
  151446. return 0;
  151447. }
  151448. /* seek to a playback time relative to the decompressed pcm stream
  151449. returns zero on success, nonzero on failure */
  151450. int ov_time_seek(OggVorbis_File *vf,double seconds){
  151451. /* translate time to PCM position and call ov_pcm_seek */
  151452. int link=-1;
  151453. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  151454. double time_total=ov_time_total(vf,-1);
  151455. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151456. if(!vf->seekable)return(OV_ENOSEEK);
  151457. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  151458. /* which bitstream section does this time offset occur in? */
  151459. for(link=vf->links-1;link>=0;link--){
  151460. pcm_total-=vf->pcmlengths[link*2+1];
  151461. time_total-=ov_time_total(vf,link);
  151462. if(seconds>=time_total)break;
  151463. }
  151464. /* enough information to convert time offset to pcm offset */
  151465. {
  151466. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  151467. return(ov_pcm_seek(vf,target));
  151468. }
  151469. }
  151470. /* page-granularity version of ov_time_seek
  151471. returns zero on success, nonzero on failure */
  151472. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  151473. /* translate time to PCM position and call ov_pcm_seek */
  151474. int link=-1;
  151475. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  151476. double time_total=ov_time_total(vf,-1);
  151477. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151478. if(!vf->seekable)return(OV_ENOSEEK);
  151479. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  151480. /* which bitstream section does this time offset occur in? */
  151481. for(link=vf->links-1;link>=0;link--){
  151482. pcm_total-=vf->pcmlengths[link*2+1];
  151483. time_total-=ov_time_total(vf,link);
  151484. if(seconds>=time_total)break;
  151485. }
  151486. /* enough information to convert time offset to pcm offset */
  151487. {
  151488. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  151489. return(ov_pcm_seek_page(vf,target));
  151490. }
  151491. }
  151492. /* tell the current stream offset cursor. Note that seek followed by
  151493. tell will likely not give the set offset due to caching */
  151494. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  151495. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151496. return(vf->offset);
  151497. }
  151498. /* return PCM offset (sample) of next PCM sample to be read */
  151499. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  151500. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151501. return(vf->pcm_offset);
  151502. }
  151503. /* return time offset (seconds) of next PCM sample to be read */
  151504. double ov_time_tell(OggVorbis_File *vf){
  151505. int link=0;
  151506. ogg_int64_t pcm_total=0;
  151507. double time_total=0.f;
  151508. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151509. if(vf->seekable){
  151510. pcm_total=ov_pcm_total(vf,-1);
  151511. time_total=ov_time_total(vf,-1);
  151512. /* which bitstream section does this time offset occur in? */
  151513. for(link=vf->links-1;link>=0;link--){
  151514. pcm_total-=vf->pcmlengths[link*2+1];
  151515. time_total-=ov_time_total(vf,link);
  151516. if(vf->pcm_offset>=pcm_total)break;
  151517. }
  151518. }
  151519. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  151520. }
  151521. /* link: -1) return the vorbis_info struct for the bitstream section
  151522. currently being decoded
  151523. 0-n) to request information for a specific bitstream section
  151524. In the case of a non-seekable bitstream, any call returns the
  151525. current bitstream. NULL in the case that the machine is not
  151526. initialized */
  151527. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  151528. if(vf->seekable){
  151529. if(link<0)
  151530. if(vf->ready_state>=STREAMSET)
  151531. return vf->vi+vf->current_link;
  151532. else
  151533. return vf->vi;
  151534. else
  151535. if(link>=vf->links)
  151536. return NULL;
  151537. else
  151538. return vf->vi+link;
  151539. }else{
  151540. return vf->vi;
  151541. }
  151542. }
  151543. /* grr, strong typing, grr, no templates/inheritence, grr */
  151544. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  151545. if(vf->seekable){
  151546. if(link<0)
  151547. if(vf->ready_state>=STREAMSET)
  151548. return vf->vc+vf->current_link;
  151549. else
  151550. return vf->vc;
  151551. else
  151552. if(link>=vf->links)
  151553. return NULL;
  151554. else
  151555. return vf->vc+link;
  151556. }else{
  151557. return vf->vc;
  151558. }
  151559. }
  151560. static int host_is_big_endian() {
  151561. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  151562. unsigned char *bytewise = (unsigned char *)&pattern;
  151563. if (bytewise[0] == 0xfe) return 1;
  151564. return 0;
  151565. }
  151566. /* up to this point, everything could more or less hide the multiple
  151567. logical bitstream nature of chaining from the toplevel application
  151568. if the toplevel application didn't particularly care. However, at
  151569. the point that we actually read audio back, the multiple-section
  151570. nature must surface: Multiple bitstream sections do not necessarily
  151571. have to have the same number of channels or sampling rate.
  151572. ov_read returns the sequential logical bitstream number currently
  151573. being decoded along with the PCM data in order that the toplevel
  151574. application can take action on channel/sample rate changes. This
  151575. number will be incremented even for streamed (non-seekable) streams
  151576. (for seekable streams, it represents the actual logical bitstream
  151577. index within the physical bitstream. Note that the accessor
  151578. functions above are aware of this dichotomy).
  151579. input values: buffer) a buffer to hold packed PCM data for return
  151580. length) the byte length requested to be placed into buffer
  151581. bigendianp) should the data be packed LSB first (0) or
  151582. MSB first (1)
  151583. word) word size for output. currently 1 (byte) or
  151584. 2 (16 bit short)
  151585. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  151586. 0) EOF
  151587. n) number of bytes of PCM actually returned. The
  151588. below works on a packet-by-packet basis, so the
  151589. return length is not related to the 'length' passed
  151590. in, just guaranteed to fit.
  151591. *section) set to the logical bitstream number */
  151592. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  151593. int bigendianp,int word,int sgned,int *bitstream){
  151594. int i,j;
  151595. int host_endian = host_is_big_endian();
  151596. float **pcm;
  151597. long samples;
  151598. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151599. while(1){
  151600. if(vf->ready_state==INITSET){
  151601. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  151602. if(samples)break;
  151603. }
  151604. /* suck in another packet */
  151605. {
  151606. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  151607. if(ret==OV_EOF)
  151608. return(0);
  151609. if(ret<=0)
  151610. return(ret);
  151611. }
  151612. }
  151613. if(samples>0){
  151614. /* yay! proceed to pack data into the byte buffer */
  151615. long channels=ov_info(vf,-1)->channels;
  151616. long bytespersample=word * channels;
  151617. vorbis_fpu_control fpu;
  151618. (void) fpu; // (to avoid a warning about it being unused)
  151619. if(samples>length/bytespersample)samples=length/bytespersample;
  151620. if(samples <= 0)
  151621. return OV_EINVAL;
  151622. /* a tight loop to pack each size */
  151623. {
  151624. int val;
  151625. if(word==1){
  151626. int off=(sgned?0:128);
  151627. vorbis_fpu_setround(&fpu);
  151628. for(j=0;j<samples;j++)
  151629. for(i=0;i<channels;i++){
  151630. val=vorbis_ftoi(pcm[i][j]*128.f);
  151631. if(val>127)val=127;
  151632. else if(val<-128)val=-128;
  151633. *buffer++=val+off;
  151634. }
  151635. vorbis_fpu_restore(fpu);
  151636. }else{
  151637. int off=(sgned?0:32768);
  151638. if(host_endian==bigendianp){
  151639. if(sgned){
  151640. vorbis_fpu_setround(&fpu);
  151641. for(i=0;i<channels;i++) { /* It's faster in this order */
  151642. float *src=pcm[i];
  151643. short *dest=((short *)buffer)+i;
  151644. for(j=0;j<samples;j++) {
  151645. val=vorbis_ftoi(src[j]*32768.f);
  151646. if(val>32767)val=32767;
  151647. else if(val<-32768)val=-32768;
  151648. *dest=val;
  151649. dest+=channels;
  151650. }
  151651. }
  151652. vorbis_fpu_restore(fpu);
  151653. }else{
  151654. vorbis_fpu_setround(&fpu);
  151655. for(i=0;i<channels;i++) {
  151656. float *src=pcm[i];
  151657. short *dest=((short *)buffer)+i;
  151658. for(j=0;j<samples;j++) {
  151659. val=vorbis_ftoi(src[j]*32768.f);
  151660. if(val>32767)val=32767;
  151661. else if(val<-32768)val=-32768;
  151662. *dest=val+off;
  151663. dest+=channels;
  151664. }
  151665. }
  151666. vorbis_fpu_restore(fpu);
  151667. }
  151668. }else if(bigendianp){
  151669. vorbis_fpu_setround(&fpu);
  151670. for(j=0;j<samples;j++)
  151671. for(i=0;i<channels;i++){
  151672. val=vorbis_ftoi(pcm[i][j]*32768.f);
  151673. if(val>32767)val=32767;
  151674. else if(val<-32768)val=-32768;
  151675. val+=off;
  151676. *buffer++=(val>>8);
  151677. *buffer++=(val&0xff);
  151678. }
  151679. vorbis_fpu_restore(fpu);
  151680. }else{
  151681. int val;
  151682. vorbis_fpu_setround(&fpu);
  151683. for(j=0;j<samples;j++)
  151684. for(i=0;i<channels;i++){
  151685. val=vorbis_ftoi(pcm[i][j]*32768.f);
  151686. if(val>32767)val=32767;
  151687. else if(val<-32768)val=-32768;
  151688. val+=off;
  151689. *buffer++=(val&0xff);
  151690. *buffer++=(val>>8);
  151691. }
  151692. vorbis_fpu_restore(fpu);
  151693. }
  151694. }
  151695. }
  151696. vorbis_synthesis_read(&vf->vd,samples);
  151697. vf->pcm_offset+=samples;
  151698. if(bitstream)*bitstream=vf->current_link;
  151699. return(samples*bytespersample);
  151700. }else{
  151701. return(samples);
  151702. }
  151703. }
  151704. /* input values: pcm_channels) a float vector per channel of output
  151705. length) the sample length being read by the app
  151706. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  151707. 0) EOF
  151708. n) number of samples of PCM actually returned. The
  151709. below works on a packet-by-packet basis, so the
  151710. return length is not related to the 'length' passed
  151711. in, just guaranteed to fit.
  151712. *section) set to the logical bitstream number */
  151713. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  151714. int *bitstream){
  151715. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151716. while(1){
  151717. if(vf->ready_state==INITSET){
  151718. float **pcm;
  151719. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  151720. if(samples){
  151721. if(pcm_channels)*pcm_channels=pcm;
  151722. if(samples>length)samples=length;
  151723. vorbis_synthesis_read(&vf->vd,samples);
  151724. vf->pcm_offset+=samples;
  151725. if(bitstream)*bitstream=vf->current_link;
  151726. return samples;
  151727. }
  151728. }
  151729. /* suck in another packet */
  151730. {
  151731. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  151732. if(ret==OV_EOF)return(0);
  151733. if(ret<=0)return(ret);
  151734. }
  151735. }
  151736. }
  151737. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  151738. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  151739. ogg_int64_t off);
  151740. static void _ov_splice(float **pcm,float **lappcm,
  151741. int n1, int n2,
  151742. int ch1, int ch2,
  151743. float *w1, float *w2){
  151744. int i,j;
  151745. float *w=w1;
  151746. int n=n1;
  151747. if(n1>n2){
  151748. n=n2;
  151749. w=w2;
  151750. }
  151751. /* splice */
  151752. for(j=0;j<ch1 && j<ch2;j++){
  151753. float *s=lappcm[j];
  151754. float *d=pcm[j];
  151755. for(i=0;i<n;i++){
  151756. float wd=w[i]*w[i];
  151757. float ws=1.-wd;
  151758. d[i]=d[i]*wd + s[i]*ws;
  151759. }
  151760. }
  151761. /* window from zero */
  151762. for(;j<ch2;j++){
  151763. float *d=pcm[j];
  151764. for(i=0;i<n;i++){
  151765. float wd=w[i]*w[i];
  151766. d[i]=d[i]*wd;
  151767. }
  151768. }
  151769. }
  151770. /* make sure vf is INITSET */
  151771. static int _ov_initset(OggVorbis_File *vf){
  151772. while(1){
  151773. if(vf->ready_state==INITSET)break;
  151774. /* suck in another packet */
  151775. {
  151776. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  151777. if(ret<0 && ret!=OV_HOLE)return(ret);
  151778. }
  151779. }
  151780. return 0;
  151781. }
  151782. /* make sure vf is INITSET and that we have a primed buffer; if
  151783. we're crosslapping at a stream section boundary, this also makes
  151784. sure we're sanity checking against the right stream information */
  151785. static int _ov_initprime(OggVorbis_File *vf){
  151786. vorbis_dsp_state *vd=&vf->vd;
  151787. while(1){
  151788. if(vf->ready_state==INITSET)
  151789. if(vorbis_synthesis_pcmout(vd,NULL))break;
  151790. /* suck in another packet */
  151791. {
  151792. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  151793. if(ret<0 && ret!=OV_HOLE)return(ret);
  151794. }
  151795. }
  151796. return 0;
  151797. }
  151798. /* grab enough data for lapping from vf; this may be in the form of
  151799. unreturned, already-decoded pcm, remaining PCM we will need to
  151800. decode, or synthetic postextrapolation from last packets. */
  151801. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  151802. float **lappcm,int lapsize){
  151803. int lapcount=0,i;
  151804. float **pcm;
  151805. /* try first to decode the lapping data */
  151806. while(lapcount<lapsize){
  151807. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  151808. if(samples){
  151809. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  151810. for(i=0;i<vi->channels;i++)
  151811. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  151812. lapcount+=samples;
  151813. vorbis_synthesis_read(vd,samples);
  151814. }else{
  151815. /* suck in another packet */
  151816. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  151817. if(ret==OV_EOF)break;
  151818. }
  151819. }
  151820. if(lapcount<lapsize){
  151821. /* failed to get lapping data from normal decode; pry it from the
  151822. postextrapolation buffering, or the second half of the MDCT
  151823. from the last packet */
  151824. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  151825. if(samples==0){
  151826. for(i=0;i<vi->channels;i++)
  151827. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  151828. lapcount=lapsize;
  151829. }else{
  151830. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  151831. for(i=0;i<vi->channels;i++)
  151832. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  151833. lapcount+=samples;
  151834. }
  151835. }
  151836. }
  151837. /* this sets up crosslapping of a sample by using trailing data from
  151838. sample 1 and lapping it into the windowing buffer of sample 2 */
  151839. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  151840. vorbis_info *vi1,*vi2;
  151841. float **lappcm;
  151842. float **pcm;
  151843. float *w1,*w2;
  151844. int n1,n2,i,ret,hs1,hs2;
  151845. if(vf1==vf2)return(0); /* degenerate case */
  151846. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  151847. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  151848. /* the relevant overlap buffers must be pre-checked and pre-primed
  151849. before looking at settings in the event that priming would cross
  151850. a bitstream boundary. So, do it now */
  151851. ret=_ov_initset(vf1);
  151852. if(ret)return(ret);
  151853. ret=_ov_initprime(vf2);
  151854. if(ret)return(ret);
  151855. vi1=ov_info(vf1,-1);
  151856. vi2=ov_info(vf2,-1);
  151857. hs1=ov_halfrate_p(vf1);
  151858. hs2=ov_halfrate_p(vf2);
  151859. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  151860. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  151861. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  151862. w1=vorbis_window(&vf1->vd,0);
  151863. w2=vorbis_window(&vf2->vd,0);
  151864. for(i=0;i<vi1->channels;i++)
  151865. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  151866. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  151867. /* have a lapping buffer from vf1; now to splice it into the lapping
  151868. buffer of vf2 */
  151869. /* consolidate and expose the buffer. */
  151870. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  151871. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  151872. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  151873. /* splice */
  151874. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  151875. /* done */
  151876. return(0);
  151877. }
  151878. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  151879. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  151880. vorbis_info *vi;
  151881. float **lappcm;
  151882. float **pcm;
  151883. float *w1,*w2;
  151884. int n1,n2,ch1,ch2,hs;
  151885. int i,ret;
  151886. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151887. ret=_ov_initset(vf);
  151888. if(ret)return(ret);
  151889. vi=ov_info(vf,-1);
  151890. hs=ov_halfrate_p(vf);
  151891. ch1=vi->channels;
  151892. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  151893. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  151894. persistent; even if the decode state
  151895. from this link gets dumped, this
  151896. window array continues to exist */
  151897. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  151898. for(i=0;i<ch1;i++)
  151899. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  151900. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  151901. /* have lapping data; seek and prime the buffer */
  151902. ret=localseek(vf,pos);
  151903. if(ret)return ret;
  151904. ret=_ov_initprime(vf);
  151905. if(ret)return(ret);
  151906. /* Guard against cross-link changes; they're perfectly legal */
  151907. vi=ov_info(vf,-1);
  151908. ch2=vi->channels;
  151909. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  151910. w2=vorbis_window(&vf->vd,0);
  151911. /* consolidate and expose the buffer. */
  151912. vorbis_synthesis_lapout(&vf->vd,&pcm);
  151913. /* splice */
  151914. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  151915. /* done */
  151916. return(0);
  151917. }
  151918. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  151919. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  151920. }
  151921. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  151922. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  151923. }
  151924. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  151925. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  151926. }
  151927. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  151928. int (*localseek)(OggVorbis_File *,double)){
  151929. vorbis_info *vi;
  151930. float **lappcm;
  151931. float **pcm;
  151932. float *w1,*w2;
  151933. int n1,n2,ch1,ch2,hs;
  151934. int i,ret;
  151935. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151936. ret=_ov_initset(vf);
  151937. if(ret)return(ret);
  151938. vi=ov_info(vf,-1);
  151939. hs=ov_halfrate_p(vf);
  151940. ch1=vi->channels;
  151941. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  151942. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  151943. persistent; even if the decode state
  151944. from this link gets dumped, this
  151945. window array continues to exist */
  151946. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  151947. for(i=0;i<ch1;i++)
  151948. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  151949. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  151950. /* have lapping data; seek and prime the buffer */
  151951. ret=localseek(vf,pos);
  151952. if(ret)return ret;
  151953. ret=_ov_initprime(vf);
  151954. if(ret)return(ret);
  151955. /* Guard against cross-link changes; they're perfectly legal */
  151956. vi=ov_info(vf,-1);
  151957. ch2=vi->channels;
  151958. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  151959. w2=vorbis_window(&vf->vd,0);
  151960. /* consolidate and expose the buffer. */
  151961. vorbis_synthesis_lapout(&vf->vd,&pcm);
  151962. /* splice */
  151963. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  151964. /* done */
  151965. return(0);
  151966. }
  151967. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  151968. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  151969. }
  151970. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  151971. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  151972. }
  151973. #endif
  151974. /********* End of inlined file: vorbisfile.c *********/
  151975. /********* Start of inlined file: window.c *********/
  151976. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  151977. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  151978. // tasks..
  151979. #ifdef _MSC_VER
  151980. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  151981. #endif
  151982. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  151983. #if JUCE_USE_OGGVORBIS
  151984. #include <stdlib.h>
  151985. #include <math.h>
  151986. static float vwin64[32] = {
  151987. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  151988. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  151989. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  151990. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  151991. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  151992. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  151993. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  151994. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  151995. };
  151996. static float vwin128[64] = {
  151997. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  151998. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  151999. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  152000. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  152001. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  152002. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  152003. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  152004. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  152005. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  152006. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  152007. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  152008. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  152009. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  152010. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  152011. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  152012. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  152013. };
  152014. static float vwin256[128] = {
  152015. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  152016. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  152017. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  152018. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  152019. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  152020. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  152021. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  152022. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  152023. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  152024. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  152025. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  152026. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  152027. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  152028. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  152029. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  152030. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  152031. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  152032. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  152033. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  152034. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  152035. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  152036. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  152037. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  152038. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  152039. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  152040. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  152041. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  152042. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  152043. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  152044. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  152045. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  152046. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  152047. };
  152048. static float vwin512[256] = {
  152049. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  152050. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  152051. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  152052. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  152053. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  152054. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  152055. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  152056. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  152057. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  152058. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  152059. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  152060. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  152061. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  152062. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  152063. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  152064. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  152065. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  152066. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  152067. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  152068. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  152069. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  152070. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  152071. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  152072. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  152073. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  152074. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  152075. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  152076. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  152077. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  152078. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  152079. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  152080. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  152081. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  152082. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  152083. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  152084. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  152085. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  152086. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  152087. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  152088. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  152089. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  152090. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  152091. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  152092. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  152093. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  152094. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  152095. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  152096. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  152097. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  152098. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  152099. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  152100. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  152101. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  152102. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  152103. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  152104. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  152105. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  152106. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  152107. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  152108. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  152109. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  152110. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  152111. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  152112. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  152113. };
  152114. static float vwin1024[512] = {
  152115. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  152116. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  152117. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  152118. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  152119. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  152120. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  152121. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  152122. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  152123. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  152124. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  152125. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  152126. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  152127. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  152128. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  152129. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  152130. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  152131. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  152132. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  152133. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  152134. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  152135. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  152136. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  152137. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  152138. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  152139. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  152140. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  152141. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  152142. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  152143. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  152144. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  152145. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  152146. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  152147. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  152148. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  152149. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  152150. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  152151. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  152152. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  152153. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  152154. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  152155. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  152156. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  152157. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  152158. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  152159. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  152160. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  152161. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  152162. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  152163. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  152164. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  152165. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  152166. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  152167. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  152168. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  152169. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  152170. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  152171. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  152172. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  152173. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  152174. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  152175. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  152176. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  152177. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  152178. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  152179. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  152180. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  152181. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  152182. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  152183. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  152184. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  152185. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  152186. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  152187. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  152188. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  152189. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  152190. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  152191. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  152192. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  152193. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  152194. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  152195. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  152196. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  152197. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  152198. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  152199. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  152200. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  152201. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  152202. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  152203. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  152204. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  152205. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  152206. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  152207. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  152208. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  152209. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  152210. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  152211. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  152212. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  152213. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  152214. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  152215. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  152216. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  152217. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  152218. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  152219. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  152220. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  152221. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  152222. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  152223. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  152224. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  152225. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  152226. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  152227. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  152228. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  152229. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  152230. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  152231. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  152232. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  152233. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  152234. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  152235. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  152236. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  152237. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  152238. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  152239. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  152240. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  152241. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  152242. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  152243. };
  152244. static float vwin2048[1024] = {
  152245. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  152246. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  152247. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  152248. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  152249. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  152250. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  152251. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  152252. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  152253. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  152254. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  152255. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  152256. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  152257. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  152258. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  152259. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  152260. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  152261. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  152262. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  152263. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  152264. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  152265. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  152266. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  152267. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  152268. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  152269. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  152270. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  152271. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  152272. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  152273. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  152274. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  152275. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  152276. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  152277. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  152278. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  152279. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  152280. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  152281. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  152282. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  152283. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  152284. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  152285. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  152286. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  152287. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  152288. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  152289. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  152290. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  152291. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  152292. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  152293. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  152294. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  152295. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  152296. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  152297. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  152298. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  152299. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  152300. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  152301. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  152302. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  152303. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  152304. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  152305. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  152306. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  152307. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  152308. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  152309. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  152310. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  152311. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  152312. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  152313. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  152314. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  152315. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  152316. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  152317. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  152318. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  152319. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  152320. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  152321. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  152322. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  152323. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  152324. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  152325. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  152326. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  152327. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  152328. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  152329. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  152330. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  152331. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  152332. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  152333. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  152334. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  152335. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  152336. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  152337. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  152338. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  152339. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  152340. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  152341. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  152342. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  152343. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  152344. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  152345. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  152346. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  152347. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  152348. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  152349. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  152350. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  152351. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  152352. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  152353. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  152354. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  152355. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  152356. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  152357. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  152358. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  152359. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  152360. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  152361. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  152362. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  152363. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  152364. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  152365. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  152366. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  152367. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  152368. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  152369. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  152370. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  152371. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  152372. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  152373. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  152374. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  152375. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  152376. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  152377. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  152378. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  152379. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  152380. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  152381. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  152382. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  152383. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  152384. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  152385. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  152386. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  152387. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  152388. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  152389. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  152390. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  152391. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  152392. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  152393. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  152394. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  152395. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  152396. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  152397. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  152398. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  152399. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  152400. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  152401. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  152402. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  152403. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  152404. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  152405. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  152406. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  152407. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  152408. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  152409. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  152410. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  152411. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  152412. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  152413. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  152414. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  152415. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  152416. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  152417. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  152418. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  152419. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  152420. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  152421. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  152422. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  152423. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  152424. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  152425. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  152426. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  152427. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  152428. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  152429. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  152430. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  152431. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  152432. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  152433. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  152434. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  152435. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  152436. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  152437. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  152438. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  152439. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  152440. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  152441. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  152442. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  152443. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  152444. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  152445. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  152446. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  152447. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  152448. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  152449. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  152450. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  152451. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  152452. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  152453. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  152454. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  152455. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  152456. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  152457. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  152458. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  152459. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  152460. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  152461. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  152462. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  152463. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  152464. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  152465. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  152466. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  152467. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  152468. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  152469. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  152470. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  152471. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  152472. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  152473. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  152474. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  152475. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  152476. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  152477. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  152478. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  152479. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  152480. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  152481. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  152482. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  152483. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  152484. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  152485. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  152486. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  152487. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  152488. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  152489. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  152490. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  152491. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  152492. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  152493. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  152494. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  152495. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  152496. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  152497. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  152498. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  152499. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  152500. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  152501. };
  152502. static float vwin4096[2048] = {
  152503. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  152504. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  152505. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  152506. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  152507. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  152508. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  152509. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  152510. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  152511. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  152512. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  152513. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  152514. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  152515. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  152516. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  152517. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  152518. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  152519. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  152520. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  152521. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  152522. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  152523. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  152524. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  152525. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  152526. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  152527. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  152528. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  152529. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  152530. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  152531. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  152532. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  152533. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  152534. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  152535. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  152536. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  152537. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  152538. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  152539. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  152540. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  152541. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  152542. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  152543. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  152544. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  152545. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  152546. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  152547. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  152548. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  152549. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  152550. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  152551. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  152552. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  152553. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  152554. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  152555. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  152556. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  152557. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  152558. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  152559. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  152560. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  152561. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  152562. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  152563. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  152564. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  152565. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  152566. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  152567. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  152568. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  152569. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  152570. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  152571. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  152572. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  152573. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  152574. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  152575. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  152576. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  152577. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  152578. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  152579. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  152580. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  152581. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  152582. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  152583. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  152584. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  152585. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  152586. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  152587. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  152588. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  152589. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  152590. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  152591. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  152592. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  152593. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  152594. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  152595. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  152596. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  152597. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  152598. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  152599. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  152600. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  152601. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  152602. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  152603. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  152604. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  152605. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  152606. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  152607. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  152608. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  152609. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  152610. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  152611. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  152612. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  152613. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  152614. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  152615. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  152616. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  152617. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  152618. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  152619. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  152620. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  152621. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  152622. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  152623. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  152624. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  152625. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  152626. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  152627. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  152628. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  152629. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  152630. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  152631. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  152632. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  152633. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  152634. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  152635. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  152636. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  152637. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  152638. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  152639. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  152640. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  152641. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  152642. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  152643. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  152644. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  152645. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  152646. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  152647. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  152648. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  152649. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  152650. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  152651. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  152652. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  152653. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  152654. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  152655. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  152656. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  152657. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  152658. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  152659. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  152660. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  152661. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  152662. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  152663. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  152664. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  152665. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  152666. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  152667. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  152668. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  152669. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  152670. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  152671. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  152672. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  152673. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  152674. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  152675. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  152676. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  152677. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  152678. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  152679. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  152680. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  152681. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  152682. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  152683. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  152684. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  152685. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  152686. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  152687. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  152688. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  152689. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  152690. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  152691. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  152692. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  152693. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  152694. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  152695. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  152696. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  152697. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  152698. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  152699. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  152700. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  152701. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  152702. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  152703. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  152704. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  152705. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  152706. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  152707. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  152708. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  152709. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  152710. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  152711. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  152712. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  152713. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  152714. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  152715. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  152716. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  152717. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  152718. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  152719. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  152720. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  152721. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  152722. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  152723. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  152724. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  152725. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  152726. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  152727. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  152728. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  152729. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  152730. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  152731. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  152732. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  152733. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  152734. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  152735. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  152736. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  152737. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  152738. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  152739. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  152740. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  152741. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  152742. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  152743. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  152744. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  152745. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  152746. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  152747. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  152748. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  152749. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  152750. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  152751. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  152752. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  152753. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  152754. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  152755. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  152756. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  152757. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  152758. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  152759. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  152760. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  152761. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  152762. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  152763. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  152764. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  152765. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  152766. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  152767. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  152768. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  152769. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  152770. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  152771. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  152772. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  152773. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  152774. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  152775. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  152776. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  152777. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  152778. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  152779. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  152780. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  152781. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  152782. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  152783. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  152784. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  152785. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  152786. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  152787. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  152788. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  152789. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  152790. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  152791. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  152792. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  152793. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  152794. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  152795. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  152796. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  152797. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  152798. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  152799. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  152800. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  152801. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  152802. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  152803. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  152804. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  152805. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  152806. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  152807. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  152808. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  152809. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  152810. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  152811. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  152812. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  152813. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  152814. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  152815. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  152816. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  152817. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  152818. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  152819. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  152820. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  152821. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  152822. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  152823. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  152824. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  152825. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  152826. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  152827. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  152828. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  152829. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  152830. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  152831. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  152832. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  152833. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  152834. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  152835. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  152836. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  152837. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  152838. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  152839. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  152840. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  152841. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  152842. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  152843. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  152844. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  152845. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  152846. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  152847. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  152848. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  152849. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  152850. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  152851. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  152852. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  152853. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  152854. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  152855. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  152856. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  152857. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  152858. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  152859. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  152860. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  152861. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  152862. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  152863. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  152864. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  152865. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  152866. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  152867. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  152868. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  152869. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  152870. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  152871. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  152872. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  152873. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  152874. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  152875. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  152876. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  152877. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  152878. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  152879. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  152880. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  152881. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  152882. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  152883. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  152884. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  152885. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  152886. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  152887. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  152888. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  152889. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  152890. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  152891. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  152892. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  152893. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  152894. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  152895. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  152896. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  152897. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  152898. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  152899. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  152900. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  152901. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  152902. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  152903. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  152904. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  152905. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  152906. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  152907. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  152908. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  152909. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  152910. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  152911. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  152912. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  152913. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  152914. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  152915. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  152916. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  152917. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  152918. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  152919. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  152920. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  152921. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  152922. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  152923. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  152924. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  152925. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  152926. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  152927. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  152928. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  152929. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  152930. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  152931. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  152932. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  152933. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  152934. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  152935. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  152936. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  152937. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  152938. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  152939. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  152940. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  152941. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  152942. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  152943. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  152944. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  152945. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  152946. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  152947. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  152948. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  152949. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  152950. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  152951. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  152952. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  152953. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  152954. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  152955. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  152956. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  152957. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  152958. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  152959. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  152960. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  152961. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  152962. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  152963. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  152964. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  152965. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  152966. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  152967. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  152968. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  152969. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  152970. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  152971. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  152972. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  152973. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  152974. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  152975. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  152976. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  152977. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  152978. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  152979. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  152980. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  152981. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  152982. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  152983. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  152984. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  152985. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  152986. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  152987. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  152988. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  152989. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  152990. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  152991. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  152992. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  152993. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  152994. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  152995. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  152996. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  152997. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  152998. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  152999. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  153000. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  153001. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  153002. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  153003. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  153004. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  153005. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  153006. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  153007. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  153008. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  153009. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  153010. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  153011. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  153012. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  153013. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  153014. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  153015. };
  153016. static float vwin8192[4096] = {
  153017. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  153018. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  153019. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  153020. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  153021. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  153022. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  153023. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  153024. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  153025. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  153026. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  153027. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  153028. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  153029. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  153030. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  153031. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  153032. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  153033. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  153034. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  153035. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  153036. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  153037. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  153038. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  153039. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  153040. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  153041. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  153042. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  153043. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  153044. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  153045. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  153046. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  153047. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  153048. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  153049. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  153050. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  153051. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  153052. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  153053. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  153054. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  153055. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  153056. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  153057. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  153058. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  153059. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  153060. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  153061. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  153062. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  153063. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  153064. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  153065. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  153066. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  153067. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  153068. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  153069. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  153070. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  153071. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  153072. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  153073. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  153074. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  153075. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  153076. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  153077. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  153078. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  153079. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  153080. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  153081. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  153082. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  153083. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  153084. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  153085. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  153086. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  153087. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  153088. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  153089. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  153090. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  153091. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  153092. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  153093. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  153094. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  153095. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  153096. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  153097. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  153098. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  153099. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  153100. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  153101. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  153102. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  153103. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  153104. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  153105. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  153106. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  153107. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  153108. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  153109. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  153110. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  153111. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  153112. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  153113. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  153114. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  153115. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  153116. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  153117. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  153118. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  153119. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  153120. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  153121. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  153122. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  153123. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  153124. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  153125. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  153126. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  153127. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  153128. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  153129. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  153130. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  153131. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  153132. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  153133. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  153134. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  153135. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  153136. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  153137. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  153138. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  153139. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  153140. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  153141. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  153142. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  153143. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  153144. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  153145. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  153146. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  153147. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  153148. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  153149. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  153150. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  153151. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  153152. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  153153. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  153154. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  153155. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  153156. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  153157. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  153158. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  153159. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  153160. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  153161. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  153162. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  153163. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  153164. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  153165. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  153166. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  153167. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  153168. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  153169. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  153170. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  153171. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  153172. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  153173. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  153174. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  153175. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  153176. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  153177. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  153178. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  153179. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  153180. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  153181. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  153182. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  153183. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  153184. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  153185. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  153186. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  153187. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  153188. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  153189. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  153190. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  153191. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  153192. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  153193. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  153194. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  153195. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  153196. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  153197. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  153198. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  153199. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  153200. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  153201. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  153202. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  153203. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  153204. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  153205. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  153206. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  153207. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  153208. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  153209. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  153210. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  153211. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  153212. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  153213. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  153214. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  153215. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  153216. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  153217. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  153218. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  153219. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  153220. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  153221. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  153222. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  153223. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  153224. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  153225. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  153226. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  153227. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  153228. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  153229. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  153230. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  153231. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  153232. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  153233. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  153234. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  153235. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  153236. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  153237. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  153238. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  153239. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  153240. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  153241. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  153242. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  153243. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  153244. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  153245. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  153246. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  153247. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  153248. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  153249. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  153250. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  153251. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  153252. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  153253. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  153254. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  153255. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  153256. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  153257. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  153258. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  153259. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  153260. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  153261. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  153262. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  153263. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  153264. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  153265. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  153266. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  153267. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  153268. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  153269. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  153270. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  153271. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  153272. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  153273. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  153274. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  153275. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  153276. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  153277. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  153278. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  153279. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  153280. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  153281. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  153282. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  153283. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  153284. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  153285. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  153286. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  153287. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  153288. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  153289. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  153290. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  153291. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  153292. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  153293. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  153294. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  153295. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  153296. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  153297. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  153298. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  153299. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  153300. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  153301. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  153302. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  153303. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  153304. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  153305. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  153306. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  153307. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  153308. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  153309. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  153310. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  153311. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  153312. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  153313. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  153314. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  153315. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  153316. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  153317. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  153318. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  153319. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  153320. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  153321. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  153322. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  153323. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  153324. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  153325. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  153326. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  153327. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  153328. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  153329. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  153330. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  153331. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  153332. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  153333. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  153334. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  153335. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  153336. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  153337. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  153338. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  153339. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  153340. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  153341. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  153342. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  153343. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  153344. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  153345. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  153346. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  153347. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  153348. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  153349. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  153350. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  153351. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  153352. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  153353. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  153354. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  153355. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  153356. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  153357. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  153358. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  153359. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  153360. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  153361. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  153362. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  153363. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  153364. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  153365. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  153366. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  153367. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  153368. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  153369. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  153370. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  153371. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  153372. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  153373. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  153374. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  153375. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  153376. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  153377. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  153378. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  153379. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  153380. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  153381. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  153382. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  153383. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  153384. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  153385. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  153386. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  153387. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  153388. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  153389. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  153390. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  153391. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  153392. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  153393. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  153394. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  153395. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  153396. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  153397. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  153398. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  153399. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  153400. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  153401. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  153402. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  153403. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  153404. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  153405. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  153406. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  153407. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  153408. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  153409. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  153410. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  153411. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  153412. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  153413. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  153414. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  153415. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  153416. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  153417. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  153418. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  153419. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  153420. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  153421. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  153422. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  153423. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  153424. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  153425. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  153426. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  153427. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  153428. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  153429. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  153430. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  153431. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  153432. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  153433. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  153434. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  153435. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  153436. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  153437. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  153438. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  153439. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  153440. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  153441. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  153442. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  153443. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  153444. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  153445. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  153446. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  153447. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  153448. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  153449. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  153450. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  153451. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  153452. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  153453. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  153454. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  153455. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  153456. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  153457. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  153458. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  153459. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  153460. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  153461. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  153462. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  153463. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  153464. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  153465. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  153466. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  153467. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  153468. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  153469. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  153470. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  153471. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  153472. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  153473. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  153474. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  153475. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  153476. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  153477. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  153478. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  153479. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  153480. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  153481. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  153482. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  153483. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  153484. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  153485. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  153486. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  153487. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  153488. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  153489. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  153490. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  153491. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  153492. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  153493. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  153494. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  153495. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  153496. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  153497. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  153498. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  153499. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  153500. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  153501. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  153502. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  153503. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  153504. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  153505. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  153506. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  153507. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  153508. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  153509. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  153510. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  153511. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  153512. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  153513. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  153514. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  153515. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  153516. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  153517. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  153518. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  153519. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  153520. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  153521. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  153522. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  153523. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  153524. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  153525. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  153526. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  153527. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  153528. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  153529. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  153530. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  153531. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  153532. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  153533. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  153534. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  153535. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  153536. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  153537. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  153538. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  153539. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  153540. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  153541. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  153542. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  153543. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  153544. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  153545. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  153546. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  153547. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  153548. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  153549. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  153550. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  153551. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  153552. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  153553. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  153554. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  153555. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  153556. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  153557. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  153558. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  153559. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  153560. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  153561. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  153562. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  153563. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  153564. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  153565. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  153566. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  153567. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  153568. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  153569. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  153570. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  153571. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  153572. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  153573. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  153574. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  153575. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  153576. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  153577. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  153578. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  153579. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  153580. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  153581. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  153582. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  153583. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  153584. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  153585. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  153586. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  153587. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  153588. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  153589. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  153590. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  153591. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  153592. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  153593. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  153594. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  153595. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  153596. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  153597. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  153598. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  153599. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  153600. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  153601. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  153602. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  153603. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  153604. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  153605. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  153606. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  153607. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  153608. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  153609. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  153610. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  153611. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  153612. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  153613. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  153614. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  153615. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  153616. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  153617. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  153618. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  153619. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  153620. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  153621. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  153622. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  153623. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  153624. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  153625. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  153626. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  153627. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  153628. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  153629. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  153630. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  153631. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  153632. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  153633. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  153634. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  153635. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  153636. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  153637. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  153638. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  153639. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  153640. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  153641. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  153642. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  153643. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  153644. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  153645. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  153646. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  153647. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  153648. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  153649. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  153650. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  153651. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  153652. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  153653. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  153654. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  153655. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  153656. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  153657. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  153658. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  153659. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  153660. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  153661. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  153662. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  153663. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  153664. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  153665. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  153666. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  153667. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  153668. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  153669. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  153670. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  153671. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  153672. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  153673. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  153674. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  153675. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  153676. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  153677. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  153678. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  153679. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  153680. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  153681. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  153682. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  153683. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  153684. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  153685. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  153686. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  153687. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  153688. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  153689. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  153690. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  153691. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  153692. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  153693. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  153694. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  153695. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  153696. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  153697. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  153698. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  153699. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  153700. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  153701. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  153702. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  153703. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  153704. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  153705. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  153706. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  153707. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  153708. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  153709. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  153710. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  153711. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  153712. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  153713. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  153714. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  153715. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  153716. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  153717. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  153718. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  153719. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  153720. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  153721. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  153722. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  153723. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  153724. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  153725. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  153726. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  153727. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  153728. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  153729. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  153730. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  153731. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  153732. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  153733. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  153734. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  153735. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  153736. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  153737. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  153738. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  153739. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  153740. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  153741. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  153742. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  153743. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  153744. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  153745. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  153746. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  153747. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  153748. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  153749. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  153750. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  153751. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  153752. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  153753. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  153754. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  153755. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  153756. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  153757. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  153758. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  153759. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  153760. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  153761. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  153762. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  153763. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  153764. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  153765. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  153766. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  153767. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  153768. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  153769. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  153770. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  153771. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  153772. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  153773. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  153774. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  153775. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  153776. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  153777. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  153778. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  153779. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  153780. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  153781. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  153782. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  153783. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  153784. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  153785. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  153786. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  153787. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  153788. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  153789. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  153790. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  153791. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  153792. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  153793. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  153794. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  153795. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  153796. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  153797. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  153798. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  153799. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  153800. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  153801. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  153802. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  153803. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  153804. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  153805. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  153806. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  153807. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  153808. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  153809. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  153810. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  153811. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  153812. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  153813. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  153814. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  153815. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  153816. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  153817. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  153818. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  153819. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  153820. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  153821. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  153822. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  153823. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  153824. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  153825. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  153826. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  153827. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  153828. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  153829. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  153830. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  153831. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  153832. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  153833. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  153834. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  153835. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  153836. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  153837. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  153838. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  153839. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  153840. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  153841. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  153842. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  153843. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  153844. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  153845. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  153846. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  153847. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  153848. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  153849. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  153850. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  153851. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  153852. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  153853. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  153854. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  153855. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  153856. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  153857. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  153858. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  153859. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  153860. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  153861. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  153862. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  153863. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  153864. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  153865. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  153866. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  153867. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  153868. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  153869. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  153870. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  153871. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  153872. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  153873. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  153874. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  153875. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  153876. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  153877. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  153878. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  153879. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  153880. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  153881. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  153882. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  153883. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  153884. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  153885. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  153886. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  153887. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  153888. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  153889. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  153890. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  153891. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  153892. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  153893. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  153894. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  153895. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  153896. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  153897. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  153898. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  153899. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  153900. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  153901. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  153902. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  153903. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  153904. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  153905. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  153906. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  153907. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  153908. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  153909. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  153910. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  153911. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  153912. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  153913. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  153914. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  153915. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  153916. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  153917. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  153918. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  153919. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  153920. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  153921. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  153922. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  153923. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  153924. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  153925. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  153926. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  153927. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  153928. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  153929. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  153930. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  153931. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  153932. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  153933. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  153934. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  153935. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  153936. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  153937. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  153938. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  153939. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  153940. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  153941. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  153942. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  153943. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  153944. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  153945. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  153946. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  153947. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  153948. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  153949. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  153950. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  153951. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  153952. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  153953. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  153954. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  153955. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  153956. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  153957. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  153958. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  153959. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  153960. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  153961. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  153962. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  153963. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  153964. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  153965. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  153966. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  153967. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  153968. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  153969. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  153970. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  153971. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  153972. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  153973. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  153974. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  153975. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  153976. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  153977. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  153978. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  153979. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  153980. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  153981. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  153982. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  153983. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  153984. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  153985. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  153986. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  153987. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  153988. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  153989. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  153990. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  153991. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  153992. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  153993. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  153994. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  153995. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  153996. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  153997. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  153998. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  153999. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  154000. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  154001. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  154002. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  154003. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  154004. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  154005. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  154006. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  154007. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  154008. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  154009. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  154010. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  154011. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  154012. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  154013. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  154014. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  154015. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  154016. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  154017. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  154018. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  154019. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  154020. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  154021. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  154022. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  154023. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  154024. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  154025. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  154026. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  154027. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  154028. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  154029. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  154030. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  154031. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  154032. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  154033. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  154034. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  154035. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  154036. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  154037. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  154038. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  154039. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  154040. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  154041. };
  154042. static float *vwin[8] = {
  154043. vwin64,
  154044. vwin128,
  154045. vwin256,
  154046. vwin512,
  154047. vwin1024,
  154048. vwin2048,
  154049. vwin4096,
  154050. vwin8192,
  154051. };
  154052. float *_vorbis_window_get(int n){
  154053. return vwin[n];
  154054. }
  154055. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  154056. int lW,int W,int nW){
  154057. lW=(W?lW:0);
  154058. nW=(W?nW:0);
  154059. {
  154060. float *windowLW=vwin[winno[lW]];
  154061. float *windowNW=vwin[winno[nW]];
  154062. long n=blocksizes[W];
  154063. long ln=blocksizes[lW];
  154064. long rn=blocksizes[nW];
  154065. long leftbegin=n/4-ln/4;
  154066. long leftend=leftbegin+ln/2;
  154067. long rightbegin=n/2+n/4-rn/4;
  154068. long rightend=rightbegin+rn/2;
  154069. int i,p;
  154070. for(i=0;i<leftbegin;i++)
  154071. d[i]=0.f;
  154072. for(p=0;i<leftend;i++,p++)
  154073. d[i]*=windowLW[p];
  154074. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  154075. d[i]*=windowNW[p];
  154076. for(;i<n;i++)
  154077. d[i]=0.f;
  154078. }
  154079. }
  154080. #endif
  154081. /********* End of inlined file: window.c *********/
  154082. #else
  154083. #include <vorbis/vorbisenc.h>
  154084. #include <vorbis/codec.h>
  154085. #include <vorbis/vorbisfile.h>
  154086. #endif
  154087. }
  154088. BEGIN_JUCE_NAMESPACE
  154089. using namespace OggVorbisNamespace;
  154090. #define oggFormatName TRANS("Ogg-Vorbis file")
  154091. static const tchar* const oggExtensions[] = { T(".ogg"), 0 };
  154092. class OggReader : public AudioFormatReader
  154093. {
  154094. OggVorbis_File ovFile;
  154095. ov_callbacks callbacks;
  154096. AudioSampleBuffer reservoir;
  154097. int reservoirStart, samplesInReservoir;
  154098. public:
  154099. OggReader (InputStream* const inp)
  154100. : AudioFormatReader (inp, oggFormatName),
  154101. reservoir (2, 4096),
  154102. reservoirStart (0),
  154103. samplesInReservoir (0)
  154104. {
  154105. sampleRate = 0;
  154106. usesFloatingPointData = true;
  154107. callbacks.read_func = &oggReadCallback;
  154108. callbacks.seek_func = &oggSeekCallback;
  154109. callbacks.close_func = &oggCloseCallback;
  154110. callbacks.tell_func = &oggTellCallback;
  154111. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  154112. if (err == 0)
  154113. {
  154114. vorbis_info* info = ov_info (&ovFile, -1);
  154115. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  154116. numChannels = info->channels;
  154117. bitsPerSample = 16;
  154118. sampleRate = info->rate;
  154119. reservoir.setSize (numChannels,
  154120. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  154121. }
  154122. }
  154123. ~OggReader()
  154124. {
  154125. ov_clear (&ovFile);
  154126. }
  154127. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  154128. int64 startSampleInFile, int numSamples)
  154129. {
  154130. while (numSamples > 0)
  154131. {
  154132. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  154133. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  154134. {
  154135. // got a few samples overlapping, so use them before seeking..
  154136. const int numToUse = jmin (numSamples, numAvailable);
  154137. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  154138. if (destSamples[i] != 0)
  154139. memcpy (destSamples[i] + startOffsetInDestBuffer,
  154140. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  154141. sizeof (float) * numToUse);
  154142. startSampleInFile += numToUse;
  154143. numSamples -= numToUse;
  154144. startOffsetInDestBuffer += numToUse;
  154145. if (numSamples == 0)
  154146. break;
  154147. }
  154148. if (startSampleInFile < reservoirStart
  154149. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  154150. {
  154151. // buffer miss, so refill the reservoir
  154152. int bitStream = 0;
  154153. reservoirStart = jmax (0, (int) startSampleInFile);
  154154. samplesInReservoir = reservoir.getNumSamples();
  154155. if (reservoirStart != (int) ov_pcm_tell (&ovFile))
  154156. ov_pcm_seek (&ovFile, reservoirStart);
  154157. int offset = 0;
  154158. int numToRead = samplesInReservoir;
  154159. while (numToRead > 0)
  154160. {
  154161. float** dataIn = 0;
  154162. const int samps = ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  154163. if (samps == 0)
  154164. break;
  154165. jassert (samps <= numToRead);
  154166. for (int i = jmin (numChannels, reservoir.getNumChannels()); --i >= 0;)
  154167. {
  154168. memcpy (reservoir.getSampleData (i, offset),
  154169. dataIn[i],
  154170. sizeof (float) * samps);
  154171. }
  154172. numToRead -= samps;
  154173. offset += samps;
  154174. }
  154175. if (numToRead > 0)
  154176. reservoir.clear (offset, numToRead);
  154177. }
  154178. }
  154179. if (numSamples > 0)
  154180. {
  154181. for (int i = numDestChannels; --i >= 0;)
  154182. if (destSamples[i] != 0)
  154183. zeromem (destSamples[i] + startOffsetInDestBuffer,
  154184. sizeof (int) * numSamples);
  154185. }
  154186. return true;
  154187. }
  154188. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  154189. {
  154190. return (size_t) (((InputStream*) datasource)->read (ptr, (int) (size * nmemb)) / size);
  154191. }
  154192. static int oggSeekCallback (void* datasource, ogg_int64_t offset, int whence)
  154193. {
  154194. InputStream* const in = (InputStream*) datasource;
  154195. if (whence == SEEK_CUR)
  154196. offset += in->getPosition();
  154197. else if (whence == SEEK_END)
  154198. offset += in->getTotalLength();
  154199. in->setPosition (offset);
  154200. return 0;
  154201. }
  154202. static int oggCloseCallback (void*)
  154203. {
  154204. return 0;
  154205. }
  154206. static long oggTellCallback (void* datasource)
  154207. {
  154208. return (long) ((InputStream*) datasource)->getPosition();
  154209. }
  154210. juce_UseDebuggingNewOperator
  154211. };
  154212. class OggWriter : public AudioFormatWriter
  154213. {
  154214. ogg_stream_state os;
  154215. ogg_page og;
  154216. ogg_packet op;
  154217. vorbis_info vi;
  154218. vorbis_comment vc;
  154219. vorbis_dsp_state vd;
  154220. vorbis_block vb;
  154221. public:
  154222. bool ok;
  154223. OggWriter (OutputStream* const out,
  154224. const double sampleRate,
  154225. const int numChannels,
  154226. const int bitsPerSample,
  154227. const int qualityIndex)
  154228. : AudioFormatWriter (out, oggFormatName,
  154229. sampleRate,
  154230. numChannels,
  154231. bitsPerSample)
  154232. {
  154233. ok = false;
  154234. vorbis_info_init (&vi);
  154235. if (vorbis_encode_init_vbr (&vi,
  154236. numChannels,
  154237. (int) sampleRate,
  154238. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  154239. {
  154240. vorbis_comment_init (&vc);
  154241. if (JUCEApplication::getInstance() != 0)
  154242. vorbis_comment_add_tag (&vc, "ENCODER",
  154243. (char*) (const char*) JUCEApplication::getInstance()->getApplicationName());
  154244. vorbis_analysis_init (&vd, &vi);
  154245. vorbis_block_init (&vd, &vb);
  154246. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  154247. ogg_packet header;
  154248. ogg_packet header_comm;
  154249. ogg_packet header_code;
  154250. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  154251. ogg_stream_packetin (&os, &header);
  154252. ogg_stream_packetin (&os, &header_comm);
  154253. ogg_stream_packetin (&os, &header_code);
  154254. for (;;)
  154255. {
  154256. if (ogg_stream_flush (&os, &og) == 0)
  154257. break;
  154258. output->write (og.header, og.header_len);
  154259. output->write (og.body, og.body_len);
  154260. }
  154261. ok = true;
  154262. }
  154263. }
  154264. ~OggWriter()
  154265. {
  154266. if (ok)
  154267. {
  154268. // write a zero-length packet to show ogg that we're finished..
  154269. write (0, 0);
  154270. ogg_stream_clear (&os);
  154271. vorbis_block_clear (&vb);
  154272. vorbis_dsp_clear (&vd);
  154273. vorbis_comment_clear (&vc);
  154274. vorbis_info_clear (&vi);
  154275. output->flush();
  154276. }
  154277. else
  154278. {
  154279. vorbis_info_clear (&vi);
  154280. output = 0; // to stop the base class deleting this, as it needs to be returned
  154281. // to the caller of createWriter()
  154282. }
  154283. }
  154284. bool write (const int** samplesToWrite, int numSamples)
  154285. {
  154286. if (! ok)
  154287. return false;
  154288. if (numSamples > 0)
  154289. {
  154290. const double gain = 1.0 / 0x80000000u;
  154291. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  154292. for (int i = numChannels; --i >= 0;)
  154293. {
  154294. float* const dst = vorbisBuffer[i];
  154295. const int* const src = samplesToWrite [i];
  154296. if (src != 0 && dst != 0)
  154297. {
  154298. for (int j = 0; j < numSamples; ++j)
  154299. dst[j] = (float) (src[j] * gain);
  154300. }
  154301. }
  154302. }
  154303. vorbis_analysis_wrote (&vd, numSamples);
  154304. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  154305. {
  154306. vorbis_analysis (&vb, 0);
  154307. vorbis_bitrate_addblock (&vb);
  154308. while (vorbis_bitrate_flushpacket (&vd, &op))
  154309. {
  154310. ogg_stream_packetin (&os, &op);
  154311. for (;;)
  154312. {
  154313. if (ogg_stream_pageout (&os, &og) == 0)
  154314. break;
  154315. output->write (og.header, og.header_len);
  154316. output->write (og.body, og.body_len);
  154317. if (ogg_page_eos (&og))
  154318. break;
  154319. }
  154320. }
  154321. }
  154322. return true;
  154323. }
  154324. juce_UseDebuggingNewOperator
  154325. };
  154326. OggVorbisAudioFormat::OggVorbisAudioFormat()
  154327. : AudioFormat (oggFormatName, (const tchar**) oggExtensions)
  154328. {
  154329. }
  154330. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  154331. {
  154332. }
  154333. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  154334. {
  154335. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  154336. return Array <int> (rates);
  154337. }
  154338. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  154339. {
  154340. Array <int> depths;
  154341. depths.add (32);
  154342. return depths;
  154343. }
  154344. bool OggVorbisAudioFormat::canDoStereo()
  154345. {
  154346. return true;
  154347. }
  154348. bool OggVorbisAudioFormat::canDoMono()
  154349. {
  154350. return true;
  154351. }
  154352. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  154353. const bool deleteStreamIfOpeningFails)
  154354. {
  154355. OggReader* r = new OggReader (in);
  154356. if (r->sampleRate == 0)
  154357. {
  154358. if (! deleteStreamIfOpeningFails)
  154359. r->input = 0;
  154360. deleteAndZero (r);
  154361. }
  154362. return r;
  154363. }
  154364. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  154365. double sampleRate,
  154366. unsigned int numChannels,
  154367. int bitsPerSample,
  154368. const StringPairArray& /*metadataValues*/,
  154369. int qualityOptionIndex)
  154370. {
  154371. OggWriter* w = new OggWriter (out,
  154372. sampleRate,
  154373. numChannels,
  154374. bitsPerSample,
  154375. qualityOptionIndex);
  154376. if (! w->ok)
  154377. deleteAndZero (w);
  154378. return w;
  154379. }
  154380. bool OggVorbisAudioFormat::isCompressed()
  154381. {
  154382. return true;
  154383. }
  154384. const StringArray OggVorbisAudioFormat::getQualityOptions()
  154385. {
  154386. StringArray s;
  154387. s.add ("Low Quality");
  154388. s.add ("Medium Quality");
  154389. s.add ("High Quality");
  154390. return s;
  154391. }
  154392. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  154393. {
  154394. FileInputStream* const in = source.createInputStream();
  154395. if (in != 0)
  154396. {
  154397. AudioFormatReader* const r = createReaderFor (in, true);
  154398. if (r != 0)
  154399. {
  154400. const int64 numSamps = r->lengthInSamples;
  154401. delete r;
  154402. const int64 fileNumSamps = source.getSize() / 4;
  154403. const double ratio = numSamps / (double) fileNumSamps;
  154404. if (ratio > 12.0)
  154405. return 0;
  154406. else if (ratio > 6.0)
  154407. return 1;
  154408. else
  154409. return 2;
  154410. }
  154411. }
  154412. return 1;
  154413. }
  154414. END_JUCE_NAMESPACE
  154415. #endif
  154416. /********* End of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  154417. /********* Start of inlined file: juce_JPEGLoader.cpp *********/
  154418. #if JUCE_MSVC
  154419. #pragma warning (push)
  154420. #endif
  154421. namespace jpeglibNamespace
  154422. {
  154423. #if JUCE_INCLUDE_JPEGLIB_CODE
  154424. extern "C"
  154425. {
  154426. #define JPEG_INTERNALS
  154427. #undef FAR
  154428. /********* Start of inlined file: jpeglib.h *********/
  154429. #ifndef JPEGLIB_H
  154430. #define JPEGLIB_H
  154431. /*
  154432. * First we include the configuration files that record how this
  154433. * installation of the JPEG library is set up. jconfig.h can be
  154434. * generated automatically for many systems. jmorecfg.h contains
  154435. * manual configuration options that most people need not worry about.
  154436. */
  154437. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  154438. /********* Start of inlined file: jconfig.h *********/
  154439. /* see jconfig.doc for explanations */
  154440. // disable all the warnings under MSVC
  154441. #ifdef _MSC_VER
  154442. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  154443. #endif
  154444. #ifdef __BORLANDC__
  154445. #pragma warn -8057
  154446. #pragma warn -8019
  154447. #pragma warn -8004
  154448. #pragma warn -8008
  154449. #endif
  154450. #define HAVE_PROTOTYPES
  154451. #define HAVE_UNSIGNED_CHAR
  154452. #define HAVE_UNSIGNED_SHORT
  154453. /* #define void char */
  154454. /* #define const */
  154455. #undef CHAR_IS_UNSIGNED
  154456. #define HAVE_STDDEF_H
  154457. #define HAVE_STDLIB_H
  154458. #undef NEED_BSD_STRINGS
  154459. #undef NEED_SYS_TYPES_H
  154460. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  154461. #undef NEED_SHORT_EXTERNAL_NAMES
  154462. #undef INCOMPLETE_TYPES_BROKEN
  154463. /* Define "boolean" as unsigned char, not int, per Windows custom */
  154464. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  154465. typedef unsigned char boolean;
  154466. #endif
  154467. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  154468. #ifdef JPEG_INTERNALS
  154469. #undef RIGHT_SHIFT_IS_UNSIGNED
  154470. #endif /* JPEG_INTERNALS */
  154471. #ifdef JPEG_CJPEG_DJPEG
  154472. #define BMP_SUPPORTED /* BMP image file format */
  154473. #define GIF_SUPPORTED /* GIF image file format */
  154474. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  154475. #undef RLE_SUPPORTED /* Utah RLE image file format */
  154476. #define TARGA_SUPPORTED /* Targa image file format */
  154477. #define TWO_FILE_COMMANDLINE /* optional */
  154478. #define USE_SETMODE /* Microsoft has setmode() */
  154479. #undef NEED_SIGNAL_CATCHER
  154480. #undef DONT_USE_B_MODE
  154481. #undef PROGRESS_REPORT /* optional */
  154482. #endif /* JPEG_CJPEG_DJPEG */
  154483. /********* End of inlined file: jconfig.h *********/
  154484. /* widely used configuration options */
  154485. #endif
  154486. /********* Start of inlined file: jmorecfg.h *********/
  154487. /*
  154488. * Define BITS_IN_JSAMPLE as either
  154489. * 8 for 8-bit sample values (the usual setting)
  154490. * 12 for 12-bit sample values
  154491. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  154492. * JPEG standard, and the IJG code does not support anything else!
  154493. * We do not support run-time selection of data precision, sorry.
  154494. */
  154495. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  154496. /*
  154497. * Maximum number of components (color channels) allowed in JPEG image.
  154498. * To meet the letter of the JPEG spec, set this to 255. However, darn
  154499. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  154500. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  154501. * really short on memory. (Each allowed component costs a hundred or so
  154502. * bytes of storage, whether actually used in an image or not.)
  154503. */
  154504. #define MAX_COMPONENTS 10 /* maximum number of image components */
  154505. /*
  154506. * Basic data types.
  154507. * You may need to change these if you have a machine with unusual data
  154508. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  154509. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  154510. * but it had better be at least 16.
  154511. */
  154512. /* Representation of a single sample (pixel element value).
  154513. * We frequently allocate large arrays of these, so it's important to keep
  154514. * them small. But if you have memory to burn and access to char or short
  154515. * arrays is very slow on your hardware, you might want to change these.
  154516. */
  154517. #if BITS_IN_JSAMPLE == 8
  154518. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  154519. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  154520. */
  154521. #ifdef HAVE_UNSIGNED_CHAR
  154522. typedef unsigned char JSAMPLE;
  154523. #define GETJSAMPLE(value) ((int) (value))
  154524. #else /* not HAVE_UNSIGNED_CHAR */
  154525. typedef char JSAMPLE;
  154526. #ifdef CHAR_IS_UNSIGNED
  154527. #define GETJSAMPLE(value) ((int) (value))
  154528. #else
  154529. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  154530. #endif /* CHAR_IS_UNSIGNED */
  154531. #endif /* HAVE_UNSIGNED_CHAR */
  154532. #define MAXJSAMPLE 255
  154533. #define CENTERJSAMPLE 128
  154534. #endif /* BITS_IN_JSAMPLE == 8 */
  154535. #if BITS_IN_JSAMPLE == 12
  154536. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  154537. * On nearly all machines "short" will do nicely.
  154538. */
  154539. typedef short JSAMPLE;
  154540. #define GETJSAMPLE(value) ((int) (value))
  154541. #define MAXJSAMPLE 4095
  154542. #define CENTERJSAMPLE 2048
  154543. #endif /* BITS_IN_JSAMPLE == 12 */
  154544. /* Representation of a DCT frequency coefficient.
  154545. * This should be a signed value of at least 16 bits; "short" is usually OK.
  154546. * Again, we allocate large arrays of these, but you can change to int
  154547. * if you have memory to burn and "short" is really slow.
  154548. */
  154549. typedef short JCOEF;
  154550. /* Compressed datastreams are represented as arrays of JOCTET.
  154551. * These must be EXACTLY 8 bits wide, at least once they are written to
  154552. * external storage. Note that when using the stdio data source/destination
  154553. * managers, this is also the data type passed to fread/fwrite.
  154554. */
  154555. #ifdef HAVE_UNSIGNED_CHAR
  154556. typedef unsigned char JOCTET;
  154557. #define GETJOCTET(value) (value)
  154558. #else /* not HAVE_UNSIGNED_CHAR */
  154559. typedef char JOCTET;
  154560. #ifdef CHAR_IS_UNSIGNED
  154561. #define GETJOCTET(value) (value)
  154562. #else
  154563. #define GETJOCTET(value) ((value) & 0xFF)
  154564. #endif /* CHAR_IS_UNSIGNED */
  154565. #endif /* HAVE_UNSIGNED_CHAR */
  154566. /* These typedefs are used for various table entries and so forth.
  154567. * They must be at least as wide as specified; but making them too big
  154568. * won't cost a huge amount of memory, so we don't provide special
  154569. * extraction code like we did for JSAMPLE. (In other words, these
  154570. * typedefs live at a different point on the speed/space tradeoff curve.)
  154571. */
  154572. /* UINT8 must hold at least the values 0..255. */
  154573. #ifdef HAVE_UNSIGNED_CHAR
  154574. typedef unsigned char UINT8;
  154575. #else /* not HAVE_UNSIGNED_CHAR */
  154576. #ifdef CHAR_IS_UNSIGNED
  154577. typedef char UINT8;
  154578. #else /* not CHAR_IS_UNSIGNED */
  154579. typedef short UINT8;
  154580. #endif /* CHAR_IS_UNSIGNED */
  154581. #endif /* HAVE_UNSIGNED_CHAR */
  154582. /* UINT16 must hold at least the values 0..65535. */
  154583. #ifdef HAVE_UNSIGNED_SHORT
  154584. typedef unsigned short UINT16;
  154585. #else /* not HAVE_UNSIGNED_SHORT */
  154586. typedef unsigned int UINT16;
  154587. #endif /* HAVE_UNSIGNED_SHORT */
  154588. /* INT16 must hold at least the values -32768..32767. */
  154589. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  154590. typedef short INT16;
  154591. #endif
  154592. /* INT32 must hold at least signed 32-bit values. */
  154593. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  154594. typedef long INT32;
  154595. #endif
  154596. /* Datatype used for image dimensions. The JPEG standard only supports
  154597. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  154598. * "unsigned int" is sufficient on all machines. However, if you need to
  154599. * handle larger images and you don't mind deviating from the spec, you
  154600. * can change this datatype.
  154601. */
  154602. typedef unsigned int JDIMENSION;
  154603. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  154604. /* These macros are used in all function definitions and extern declarations.
  154605. * You could modify them if you need to change function linkage conventions;
  154606. * in particular, you'll need to do that to make the library a Windows DLL.
  154607. * Another application is to make all functions global for use with debuggers
  154608. * or code profilers that require it.
  154609. */
  154610. /* a function called through method pointers: */
  154611. #define METHODDEF(type) static type
  154612. /* a function used only in its module: */
  154613. #define LOCAL(type) static type
  154614. /* a function referenced thru EXTERNs: */
  154615. #define GLOBAL(type) type
  154616. /* a reference to a GLOBAL function: */
  154617. #define EXTERN(type) extern type
  154618. /* This macro is used to declare a "method", that is, a function pointer.
  154619. * We want to supply prototype parameters if the compiler can cope.
  154620. * Note that the arglist parameter must be parenthesized!
  154621. * Again, you can customize this if you need special linkage keywords.
  154622. */
  154623. #ifdef HAVE_PROTOTYPES
  154624. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  154625. #else
  154626. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  154627. #endif
  154628. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  154629. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  154630. * by just saying "FAR *" where such a pointer is needed. In a few places
  154631. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  154632. */
  154633. #ifdef NEED_FAR_POINTERS
  154634. #define FAR far
  154635. #else
  154636. #define FAR
  154637. #endif
  154638. /*
  154639. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  154640. * in standard header files. Or you may have conflicts with application-
  154641. * specific header files that you want to include together with these files.
  154642. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  154643. */
  154644. #ifndef HAVE_BOOLEAN
  154645. typedef int boolean;
  154646. #endif
  154647. #ifndef FALSE /* in case these macros already exist */
  154648. #define FALSE 0 /* values of boolean */
  154649. #endif
  154650. #ifndef TRUE
  154651. #define TRUE 1
  154652. #endif
  154653. /*
  154654. * The remaining options affect code selection within the JPEG library,
  154655. * but they don't need to be visible to most applications using the library.
  154656. * To minimize application namespace pollution, the symbols won't be
  154657. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  154658. */
  154659. #ifdef JPEG_INTERNALS
  154660. #define JPEG_INTERNAL_OPTIONS
  154661. #endif
  154662. #ifdef JPEG_INTERNAL_OPTIONS
  154663. /*
  154664. * These defines indicate whether to include various optional functions.
  154665. * Undefining some of these symbols will produce a smaller but less capable
  154666. * library. Note that you can leave certain source files out of the
  154667. * compilation/linking process if you've #undef'd the corresponding symbols.
  154668. * (You may HAVE to do that if your compiler doesn't like null source files.)
  154669. */
  154670. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  154671. /* Capability options common to encoder and decoder: */
  154672. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  154673. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  154674. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  154675. /* Encoder capability options: */
  154676. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  154677. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  154678. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  154679. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  154680. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  154681. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  154682. * precision, so jchuff.c normally uses entropy optimization to compute
  154683. * usable tables for higher precision. If you don't want to do optimization,
  154684. * you'll have to supply different default Huffman tables.
  154685. * The exact same statements apply for progressive JPEG: the default tables
  154686. * don't work for progressive mode. (This may get fixed, however.)
  154687. */
  154688. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  154689. /* Decoder capability options: */
  154690. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  154691. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  154692. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  154693. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  154694. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  154695. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  154696. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  154697. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  154698. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  154699. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  154700. /* more capability options later, no doubt */
  154701. /*
  154702. * Ordering of RGB data in scanlines passed to or from the application.
  154703. * If your application wants to deal with data in the order B,G,R, just
  154704. * change these macros. You can also deal with formats such as R,G,B,X
  154705. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  154706. * the offsets will also change the order in which colormap data is organized.
  154707. * RESTRICTIONS:
  154708. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  154709. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  154710. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  154711. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  154712. * is not 3 (they don't understand about dummy color components!). So you
  154713. * can't use color quantization if you change that value.
  154714. */
  154715. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  154716. #define RGB_GREEN 1 /* Offset of Green */
  154717. #define RGB_BLUE 2 /* Offset of Blue */
  154718. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  154719. /* Definitions for speed-related optimizations. */
  154720. /* If your compiler supports inline functions, define INLINE
  154721. * as the inline keyword; otherwise define it as empty.
  154722. */
  154723. #ifndef INLINE
  154724. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  154725. #define INLINE __inline__
  154726. #endif
  154727. #ifndef INLINE
  154728. #define INLINE /* default is to define it as empty */
  154729. #endif
  154730. #endif
  154731. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  154732. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  154733. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  154734. */
  154735. #ifndef MULTIPLIER
  154736. #define MULTIPLIER int /* type for fastest integer multiply */
  154737. #endif
  154738. /* FAST_FLOAT should be either float or double, whichever is done faster
  154739. * by your compiler. (Note that this type is only used in the floating point
  154740. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  154741. * Typically, float is faster in ANSI C compilers, while double is faster in
  154742. * pre-ANSI compilers (because they insist on converting to double anyway).
  154743. * The code below therefore chooses float if we have ANSI-style prototypes.
  154744. */
  154745. #ifndef FAST_FLOAT
  154746. #ifdef HAVE_PROTOTYPES
  154747. #define FAST_FLOAT float
  154748. #else
  154749. #define FAST_FLOAT double
  154750. #endif
  154751. #endif
  154752. #endif /* JPEG_INTERNAL_OPTIONS */
  154753. /********* End of inlined file: jmorecfg.h *********/
  154754. /* seldom changed options */
  154755. /* Version ID for the JPEG library.
  154756. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  154757. */
  154758. #define JPEG_LIB_VERSION 62 /* Version 6b */
  154759. /* Various constants determining the sizes of things.
  154760. * All of these are specified by the JPEG standard, so don't change them
  154761. * if you want to be compatible.
  154762. */
  154763. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  154764. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  154765. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  154766. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  154767. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  154768. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  154769. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  154770. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  154771. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  154772. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  154773. * to handle it. We even let you do this from the jconfig.h file. However,
  154774. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  154775. * sometimes emits noncompliant files doesn't mean you should too.
  154776. */
  154777. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  154778. #ifndef D_MAX_BLOCKS_IN_MCU
  154779. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  154780. #endif
  154781. /* Data structures for images (arrays of samples and of DCT coefficients).
  154782. * On 80x86 machines, the image arrays are too big for near pointers,
  154783. * but the pointer arrays can fit in near memory.
  154784. */
  154785. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  154786. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  154787. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  154788. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  154789. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  154790. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  154791. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  154792. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  154793. /* Types for JPEG compression parameters and working tables. */
  154794. /* DCT coefficient quantization tables. */
  154795. typedef struct {
  154796. /* This array gives the coefficient quantizers in natural array order
  154797. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  154798. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  154799. */
  154800. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  154801. /* This field is used only during compression. It's initialized FALSE when
  154802. * the table is created, and set TRUE when it's been output to the file.
  154803. * You could suppress output of a table by setting this to TRUE.
  154804. * (See jpeg_suppress_tables for an example.)
  154805. */
  154806. boolean sent_table; /* TRUE when table has been output */
  154807. } JQUANT_TBL;
  154808. /* Huffman coding tables. */
  154809. typedef struct {
  154810. /* These two fields directly represent the contents of a JPEG DHT marker */
  154811. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  154812. /* length k bits; bits[0] is unused */
  154813. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  154814. /* This field is used only during compression. It's initialized FALSE when
  154815. * the table is created, and set TRUE when it's been output to the file.
  154816. * You could suppress output of a table by setting this to TRUE.
  154817. * (See jpeg_suppress_tables for an example.)
  154818. */
  154819. boolean sent_table; /* TRUE when table has been output */
  154820. } JHUFF_TBL;
  154821. /* Basic info about one component (color channel). */
  154822. typedef struct {
  154823. /* These values are fixed over the whole image. */
  154824. /* For compression, they must be supplied by parameter setup; */
  154825. /* for decompression, they are read from the SOF marker. */
  154826. int component_id; /* identifier for this component (0..255) */
  154827. int component_index; /* its index in SOF or cinfo->comp_info[] */
  154828. int h_samp_factor; /* horizontal sampling factor (1..4) */
  154829. int v_samp_factor; /* vertical sampling factor (1..4) */
  154830. int quant_tbl_no; /* quantization table selector (0..3) */
  154831. /* These values may vary between scans. */
  154832. /* For compression, they must be supplied by parameter setup; */
  154833. /* for decompression, they are read from the SOS marker. */
  154834. /* The decompressor output side may not use these variables. */
  154835. int dc_tbl_no; /* DC entropy table selector (0..3) */
  154836. int ac_tbl_no; /* AC entropy table selector (0..3) */
  154837. /* Remaining fields should be treated as private by applications. */
  154838. /* These values are computed during compression or decompression startup: */
  154839. /* Component's size in DCT blocks.
  154840. * Any dummy blocks added to complete an MCU are not counted; therefore
  154841. * these values do not depend on whether a scan is interleaved or not.
  154842. */
  154843. JDIMENSION width_in_blocks;
  154844. JDIMENSION height_in_blocks;
  154845. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  154846. * For decompression this is the size of the output from one DCT block,
  154847. * reflecting any scaling we choose to apply during the IDCT step.
  154848. * Values of 1,2,4,8 are likely to be supported. Note that different
  154849. * components may receive different IDCT scalings.
  154850. */
  154851. int DCT_scaled_size;
  154852. /* The downsampled dimensions are the component's actual, unpadded number
  154853. * of samples at the main buffer (preprocessing/compression interface), thus
  154854. * downsampled_width = ceil(image_width * Hi/Hmax)
  154855. * and similarly for height. For decompression, IDCT scaling is included, so
  154856. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  154857. */
  154858. JDIMENSION downsampled_width; /* actual width in samples */
  154859. JDIMENSION downsampled_height; /* actual height in samples */
  154860. /* This flag is used only for decompression. In cases where some of the
  154861. * components will be ignored (eg grayscale output from YCbCr image),
  154862. * we can skip most computations for the unused components.
  154863. */
  154864. boolean component_needed; /* do we need the value of this component? */
  154865. /* These values are computed before starting a scan of the component. */
  154866. /* The decompressor output side may not use these variables. */
  154867. int MCU_width; /* number of blocks per MCU, horizontally */
  154868. int MCU_height; /* number of blocks per MCU, vertically */
  154869. int MCU_blocks; /* MCU_width * MCU_height */
  154870. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  154871. int last_col_width; /* # of non-dummy blocks across in last MCU */
  154872. int last_row_height; /* # of non-dummy blocks down in last MCU */
  154873. /* Saved quantization table for component; NULL if none yet saved.
  154874. * See jdinput.c comments about the need for this information.
  154875. * This field is currently used only for decompression.
  154876. */
  154877. JQUANT_TBL * quant_table;
  154878. /* Private per-component storage for DCT or IDCT subsystem. */
  154879. void * dct_table;
  154880. } jpeg_component_info;
  154881. /* The script for encoding a multiple-scan file is an array of these: */
  154882. typedef struct {
  154883. int comps_in_scan; /* number of components encoded in this scan */
  154884. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  154885. int Ss, Se; /* progressive JPEG spectral selection parms */
  154886. int Ah, Al; /* progressive JPEG successive approx. parms */
  154887. } jpeg_scan_info;
  154888. /* The decompressor can save APPn and COM markers in a list of these: */
  154889. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  154890. struct jpeg_marker_struct {
  154891. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  154892. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  154893. unsigned int original_length; /* # bytes of data in the file */
  154894. unsigned int data_length; /* # bytes of data saved at data[] */
  154895. JOCTET FAR * data; /* the data contained in the marker */
  154896. /* the marker length word is not counted in data_length or original_length */
  154897. };
  154898. /* Known color spaces. */
  154899. typedef enum {
  154900. JCS_UNKNOWN, /* error/unspecified */
  154901. JCS_GRAYSCALE, /* monochrome */
  154902. JCS_RGB, /* red/green/blue */
  154903. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  154904. JCS_CMYK, /* C/M/Y/K */
  154905. JCS_YCCK /* Y/Cb/Cr/K */
  154906. } J_COLOR_SPACE;
  154907. /* DCT/IDCT algorithm options. */
  154908. typedef enum {
  154909. JDCT_ISLOW, /* slow but accurate integer algorithm */
  154910. JDCT_IFAST, /* faster, less accurate integer method */
  154911. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  154912. } J_DCT_METHOD;
  154913. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  154914. #define JDCT_DEFAULT JDCT_ISLOW
  154915. #endif
  154916. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  154917. #define JDCT_FASTEST JDCT_IFAST
  154918. #endif
  154919. /* Dithering options for decompression. */
  154920. typedef enum {
  154921. JDITHER_NONE, /* no dithering */
  154922. JDITHER_ORDERED, /* simple ordered dither */
  154923. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  154924. } J_DITHER_MODE;
  154925. /* Common fields between JPEG compression and decompression master structs. */
  154926. #define jpeg_common_fields \
  154927. struct jpeg_error_mgr * err; /* Error handler module */\
  154928. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  154929. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  154930. void * client_data; /* Available for use by application */\
  154931. boolean is_decompressor; /* So common code can tell which is which */\
  154932. int global_state /* For checking call sequence validity */
  154933. /* Routines that are to be used by both halves of the library are declared
  154934. * to receive a pointer to this structure. There are no actual instances of
  154935. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  154936. */
  154937. struct jpeg_common_struct {
  154938. jpeg_common_fields; /* Fields common to both master struct types */
  154939. /* Additional fields follow in an actual jpeg_compress_struct or
  154940. * jpeg_decompress_struct. All three structs must agree on these
  154941. * initial fields! (This would be a lot cleaner in C++.)
  154942. */
  154943. };
  154944. typedef struct jpeg_common_struct * j_common_ptr;
  154945. typedef struct jpeg_compress_struct * j_compress_ptr;
  154946. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  154947. /* Master record for a compression instance */
  154948. struct jpeg_compress_struct {
  154949. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  154950. /* Destination for compressed data */
  154951. struct jpeg_destination_mgr * dest;
  154952. /* Description of source image --- these fields must be filled in by
  154953. * outer application before starting compression. in_color_space must
  154954. * be correct before you can even call jpeg_set_defaults().
  154955. */
  154956. JDIMENSION image_width; /* input image width */
  154957. JDIMENSION image_height; /* input image height */
  154958. int input_components; /* # of color components in input image */
  154959. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  154960. double input_gamma; /* image gamma of input image */
  154961. /* Compression parameters --- these fields must be set before calling
  154962. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  154963. * initialize everything to reasonable defaults, then changing anything
  154964. * the application specifically wants to change. That way you won't get
  154965. * burnt when new parameters are added. Also note that there are several
  154966. * helper routines to simplify changing parameters.
  154967. */
  154968. int data_precision; /* bits of precision in image data */
  154969. int num_components; /* # of color components in JPEG image */
  154970. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  154971. jpeg_component_info * comp_info;
  154972. /* comp_info[i] describes component that appears i'th in SOF */
  154973. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  154974. /* ptrs to coefficient quantization tables, or NULL if not defined */
  154975. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  154976. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  154977. /* ptrs to Huffman coding tables, or NULL if not defined */
  154978. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  154979. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  154980. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  154981. int num_scans; /* # of entries in scan_info array */
  154982. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  154983. /* The default value of scan_info is NULL, which causes a single-scan
  154984. * sequential JPEG file to be emitted. To create a multi-scan file,
  154985. * set num_scans and scan_info to point to an array of scan definitions.
  154986. */
  154987. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  154988. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  154989. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  154990. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  154991. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  154992. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  154993. /* The restart interval can be specified in absolute MCUs by setting
  154994. * restart_interval, or in MCU rows by setting restart_in_rows
  154995. * (in which case the correct restart_interval will be figured
  154996. * for each scan).
  154997. */
  154998. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  154999. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  155000. /* Parameters controlling emission of special markers. */
  155001. boolean write_JFIF_header; /* should a JFIF marker be written? */
  155002. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  155003. UINT8 JFIF_minor_version;
  155004. /* These three values are not used by the JPEG code, merely copied */
  155005. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  155006. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  155007. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  155008. UINT8 density_unit; /* JFIF code for pixel size units */
  155009. UINT16 X_density; /* Horizontal pixel density */
  155010. UINT16 Y_density; /* Vertical pixel density */
  155011. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  155012. /* State variable: index of next scanline to be written to
  155013. * jpeg_write_scanlines(). Application may use this to control its
  155014. * processing loop, e.g., "while (next_scanline < image_height)".
  155015. */
  155016. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  155017. /* Remaining fields are known throughout compressor, but generally
  155018. * should not be touched by a surrounding application.
  155019. */
  155020. /*
  155021. * These fields are computed during compression startup
  155022. */
  155023. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  155024. int max_h_samp_factor; /* largest h_samp_factor */
  155025. int max_v_samp_factor; /* largest v_samp_factor */
  155026. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  155027. /* The coefficient controller receives data in units of MCU rows as defined
  155028. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  155029. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  155030. * "iMCU" (interleaved MCU) row.
  155031. */
  155032. /*
  155033. * These fields are valid during any one scan.
  155034. * They describe the components and MCUs actually appearing in the scan.
  155035. */
  155036. int comps_in_scan; /* # of JPEG components in this scan */
  155037. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  155038. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  155039. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  155040. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  155041. int blocks_in_MCU; /* # of DCT blocks per MCU */
  155042. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  155043. /* MCU_membership[i] is index in cur_comp_info of component owning */
  155044. /* i'th block in an MCU */
  155045. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  155046. /*
  155047. * Links to compression subobjects (methods and private variables of modules)
  155048. */
  155049. struct jpeg_comp_master * master;
  155050. struct jpeg_c_main_controller * main;
  155051. struct jpeg_c_prep_controller * prep;
  155052. struct jpeg_c_coef_controller * coef;
  155053. struct jpeg_marker_writer * marker;
  155054. struct jpeg_color_converter * cconvert;
  155055. struct jpeg_downsampler * downsample;
  155056. struct jpeg_forward_dct * fdct;
  155057. struct jpeg_entropy_encoder * entropy;
  155058. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  155059. int script_space_size;
  155060. };
  155061. /* Master record for a decompression instance */
  155062. struct jpeg_decompress_struct {
  155063. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  155064. /* Source of compressed data */
  155065. struct jpeg_source_mgr * src;
  155066. /* Basic description of image --- filled in by jpeg_read_header(). */
  155067. /* Application may inspect these values to decide how to process image. */
  155068. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  155069. JDIMENSION image_height; /* nominal image height */
  155070. int num_components; /* # of color components in JPEG image */
  155071. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  155072. /* Decompression processing parameters --- these fields must be set before
  155073. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  155074. * them to default values.
  155075. */
  155076. J_COLOR_SPACE out_color_space; /* colorspace for output */
  155077. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  155078. double output_gamma; /* image gamma wanted in output */
  155079. boolean buffered_image; /* TRUE=multiple output passes */
  155080. boolean raw_data_out; /* TRUE=downsampled data wanted */
  155081. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  155082. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  155083. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  155084. boolean quantize_colors; /* TRUE=colormapped output wanted */
  155085. /* the following are ignored if not quantize_colors: */
  155086. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  155087. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  155088. int desired_number_of_colors; /* max # colors to use in created colormap */
  155089. /* these are significant only in buffered-image mode: */
  155090. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  155091. boolean enable_external_quant;/* enable future use of external colormap */
  155092. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  155093. /* Description of actual output image that will be returned to application.
  155094. * These fields are computed by jpeg_start_decompress().
  155095. * You can also use jpeg_calc_output_dimensions() to determine these values
  155096. * in advance of calling jpeg_start_decompress().
  155097. */
  155098. JDIMENSION output_width; /* scaled image width */
  155099. JDIMENSION output_height; /* scaled image height */
  155100. int out_color_components; /* # of color components in out_color_space */
  155101. int output_components; /* # of color components returned */
  155102. /* output_components is 1 (a colormap index) when quantizing colors;
  155103. * otherwise it equals out_color_components.
  155104. */
  155105. int rec_outbuf_height; /* min recommended height of scanline buffer */
  155106. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  155107. * high, space and time will be wasted due to unnecessary data copying.
  155108. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  155109. */
  155110. /* When quantizing colors, the output colormap is described by these fields.
  155111. * The application can supply a colormap by setting colormap non-NULL before
  155112. * calling jpeg_start_decompress; otherwise a colormap is created during
  155113. * jpeg_start_decompress or jpeg_start_output.
  155114. * The map has out_color_components rows and actual_number_of_colors columns.
  155115. */
  155116. int actual_number_of_colors; /* number of entries in use */
  155117. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  155118. /* State variables: these variables indicate the progress of decompression.
  155119. * The application may examine these but must not modify them.
  155120. */
  155121. /* Row index of next scanline to be read from jpeg_read_scanlines().
  155122. * Application may use this to control its processing loop, e.g.,
  155123. * "while (output_scanline < output_height)".
  155124. */
  155125. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  155126. /* Current input scan number and number of iMCU rows completed in scan.
  155127. * These indicate the progress of the decompressor input side.
  155128. */
  155129. int input_scan_number; /* Number of SOS markers seen so far */
  155130. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  155131. /* The "output scan number" is the notional scan being displayed by the
  155132. * output side. The decompressor will not allow output scan/row number
  155133. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  155134. */
  155135. int output_scan_number; /* Nominal scan number being displayed */
  155136. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  155137. /* Current progression status. coef_bits[c][i] indicates the precision
  155138. * with which component c's DCT coefficient i (in zigzag order) is known.
  155139. * It is -1 when no data has yet been received, otherwise it is the point
  155140. * transform (shift) value for the most recent scan of the coefficient
  155141. * (thus, 0 at completion of the progression).
  155142. * This pointer is NULL when reading a non-progressive file.
  155143. */
  155144. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  155145. /* Internal JPEG parameters --- the application usually need not look at
  155146. * these fields. Note that the decompressor output side may not use
  155147. * any parameters that can change between scans.
  155148. */
  155149. /* Quantization and Huffman tables are carried forward across input
  155150. * datastreams when processing abbreviated JPEG datastreams.
  155151. */
  155152. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  155153. /* ptrs to coefficient quantization tables, or NULL if not defined */
  155154. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155155. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155156. /* ptrs to Huffman coding tables, or NULL if not defined */
  155157. /* These parameters are never carried across datastreams, since they
  155158. * are given in SOF/SOS markers or defined to be reset by SOI.
  155159. */
  155160. int data_precision; /* bits of precision in image data */
  155161. jpeg_component_info * comp_info;
  155162. /* comp_info[i] describes component that appears i'th in SOF */
  155163. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  155164. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  155165. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  155166. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  155167. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  155168. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  155169. /* These fields record data obtained from optional markers recognized by
  155170. * the JPEG library.
  155171. */
  155172. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  155173. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  155174. UINT8 JFIF_major_version; /* JFIF version number */
  155175. UINT8 JFIF_minor_version;
  155176. UINT8 density_unit; /* JFIF code for pixel size units */
  155177. UINT16 X_density; /* Horizontal pixel density */
  155178. UINT16 Y_density; /* Vertical pixel density */
  155179. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  155180. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  155181. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  155182. /* Aside from the specific data retained from APPn markers known to the
  155183. * library, the uninterpreted contents of any or all APPn and COM markers
  155184. * can be saved in a list for examination by the application.
  155185. */
  155186. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  155187. /* Remaining fields are known throughout decompressor, but generally
  155188. * should not be touched by a surrounding application.
  155189. */
  155190. /*
  155191. * These fields are computed during decompression startup
  155192. */
  155193. int max_h_samp_factor; /* largest h_samp_factor */
  155194. int max_v_samp_factor; /* largest v_samp_factor */
  155195. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  155196. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  155197. /* The coefficient controller's input and output progress is measured in
  155198. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  155199. * in fully interleaved JPEG scans, but are used whether the scan is
  155200. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  155201. * rows of each component. Therefore, the IDCT output contains
  155202. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  155203. */
  155204. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  155205. /*
  155206. * These fields are valid during any one scan.
  155207. * They describe the components and MCUs actually appearing in the scan.
  155208. * Note that the decompressor output side must not use these fields.
  155209. */
  155210. int comps_in_scan; /* # of JPEG components in this scan */
  155211. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  155212. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  155213. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  155214. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  155215. int blocks_in_MCU; /* # of DCT blocks per MCU */
  155216. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  155217. /* MCU_membership[i] is index in cur_comp_info of component owning */
  155218. /* i'th block in an MCU */
  155219. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  155220. /* This field is shared between entropy decoder and marker parser.
  155221. * It is either zero or the code of a JPEG marker that has been
  155222. * read from the data source, but has not yet been processed.
  155223. */
  155224. int unread_marker;
  155225. /*
  155226. * Links to decompression subobjects (methods, private variables of modules)
  155227. */
  155228. struct jpeg_decomp_master * master;
  155229. struct jpeg_d_main_controller * main;
  155230. struct jpeg_d_coef_controller * coef;
  155231. struct jpeg_d_post_controller * post;
  155232. struct jpeg_input_controller * inputctl;
  155233. struct jpeg_marker_reader * marker;
  155234. struct jpeg_entropy_decoder * entropy;
  155235. struct jpeg_inverse_dct * idct;
  155236. struct jpeg_upsampler * upsample;
  155237. struct jpeg_color_deconverter * cconvert;
  155238. struct jpeg_color_quantizer * cquantize;
  155239. };
  155240. /* "Object" declarations for JPEG modules that may be supplied or called
  155241. * directly by the surrounding application.
  155242. * As with all objects in the JPEG library, these structs only define the
  155243. * publicly visible methods and state variables of a module. Additional
  155244. * private fields may exist after the public ones.
  155245. */
  155246. /* Error handler object */
  155247. struct jpeg_error_mgr {
  155248. /* Error exit handler: does not return to caller */
  155249. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  155250. /* Conditionally emit a trace or warning message */
  155251. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  155252. /* Routine that actually outputs a trace or error message */
  155253. JMETHOD(void, output_message, (j_common_ptr cinfo));
  155254. /* Format a message string for the most recent JPEG error or message */
  155255. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  155256. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  155257. /* Reset error state variables at start of a new image */
  155258. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  155259. /* The message ID code and any parameters are saved here.
  155260. * A message can have one string parameter or up to 8 int parameters.
  155261. */
  155262. int msg_code;
  155263. #define JMSG_STR_PARM_MAX 80
  155264. union {
  155265. int i[8];
  155266. char s[JMSG_STR_PARM_MAX];
  155267. } msg_parm;
  155268. /* Standard state variables for error facility */
  155269. int trace_level; /* max msg_level that will be displayed */
  155270. /* For recoverable corrupt-data errors, we emit a warning message,
  155271. * but keep going unless emit_message chooses to abort. emit_message
  155272. * should count warnings in num_warnings. The surrounding application
  155273. * can check for bad data by seeing if num_warnings is nonzero at the
  155274. * end of processing.
  155275. */
  155276. long num_warnings; /* number of corrupt-data warnings */
  155277. /* These fields point to the table(s) of error message strings.
  155278. * An application can change the table pointer to switch to a different
  155279. * message list (typically, to change the language in which errors are
  155280. * reported). Some applications may wish to add additional error codes
  155281. * that will be handled by the JPEG library error mechanism; the second
  155282. * table pointer is used for this purpose.
  155283. *
  155284. * First table includes all errors generated by JPEG library itself.
  155285. * Error code 0 is reserved for a "no such error string" message.
  155286. */
  155287. const char * const * jpeg_message_table; /* Library errors */
  155288. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  155289. /* Second table can be added by application (see cjpeg/djpeg for example).
  155290. * It contains strings numbered first_addon_message..last_addon_message.
  155291. */
  155292. const char * const * addon_message_table; /* Non-library errors */
  155293. int first_addon_message; /* code for first string in addon table */
  155294. int last_addon_message; /* code for last string in addon table */
  155295. };
  155296. /* Progress monitor object */
  155297. struct jpeg_progress_mgr {
  155298. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  155299. long pass_counter; /* work units completed in this pass */
  155300. long pass_limit; /* total number of work units in this pass */
  155301. int completed_passes; /* passes completed so far */
  155302. int total_passes; /* total number of passes expected */
  155303. };
  155304. /* Data destination object for compression */
  155305. struct jpeg_destination_mgr {
  155306. JOCTET * next_output_byte; /* => next byte to write in buffer */
  155307. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  155308. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  155309. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  155310. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  155311. };
  155312. /* Data source object for decompression */
  155313. struct jpeg_source_mgr {
  155314. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  155315. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  155316. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  155317. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  155318. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  155319. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  155320. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  155321. };
  155322. /* Memory manager object.
  155323. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  155324. * and "really big" objects (virtual arrays with backing store if needed).
  155325. * The memory manager does not allow individual objects to be freed; rather,
  155326. * each created object is assigned to a pool, and whole pools can be freed
  155327. * at once. This is faster and more convenient than remembering exactly what
  155328. * to free, especially where malloc()/free() are not too speedy.
  155329. * NB: alloc routines never return NULL. They exit to error_exit if not
  155330. * successful.
  155331. */
  155332. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  155333. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  155334. #define JPOOL_NUMPOOLS 2
  155335. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  155336. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  155337. struct jpeg_memory_mgr {
  155338. /* Method pointers */
  155339. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  155340. size_t sizeofobject));
  155341. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  155342. size_t sizeofobject));
  155343. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  155344. JDIMENSION samplesperrow,
  155345. JDIMENSION numrows));
  155346. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  155347. JDIMENSION blocksperrow,
  155348. JDIMENSION numrows));
  155349. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  155350. int pool_id,
  155351. boolean pre_zero,
  155352. JDIMENSION samplesperrow,
  155353. JDIMENSION numrows,
  155354. JDIMENSION maxaccess));
  155355. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  155356. int pool_id,
  155357. boolean pre_zero,
  155358. JDIMENSION blocksperrow,
  155359. JDIMENSION numrows,
  155360. JDIMENSION maxaccess));
  155361. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  155362. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  155363. jvirt_sarray_ptr ptr,
  155364. JDIMENSION start_row,
  155365. JDIMENSION num_rows,
  155366. boolean writable));
  155367. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  155368. jvirt_barray_ptr ptr,
  155369. JDIMENSION start_row,
  155370. JDIMENSION num_rows,
  155371. boolean writable));
  155372. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  155373. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  155374. /* Limit on memory allocation for this JPEG object. (Note that this is
  155375. * merely advisory, not a guaranteed maximum; it only affects the space
  155376. * used for virtual-array buffers.) May be changed by outer application
  155377. * after creating the JPEG object.
  155378. */
  155379. long max_memory_to_use;
  155380. /* Maximum allocation request accepted by alloc_large. */
  155381. long max_alloc_chunk;
  155382. };
  155383. /* Routine signature for application-supplied marker processing methods.
  155384. * Need not pass marker code since it is stored in cinfo->unread_marker.
  155385. */
  155386. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  155387. /* Declarations for routines called by application.
  155388. * The JPP macro hides prototype parameters from compilers that can't cope.
  155389. * Note JPP requires double parentheses.
  155390. */
  155391. #ifdef HAVE_PROTOTYPES
  155392. #define JPP(arglist) arglist
  155393. #else
  155394. #define JPP(arglist) ()
  155395. #endif
  155396. /* Short forms of external names for systems with brain-damaged linkers.
  155397. * We shorten external names to be unique in the first six letters, which
  155398. * is good enough for all known systems.
  155399. * (If your compiler itself needs names to be unique in less than 15
  155400. * characters, you are out of luck. Get a better compiler.)
  155401. */
  155402. #ifdef NEED_SHORT_EXTERNAL_NAMES
  155403. #define jpeg_std_error jStdError
  155404. #define jpeg_CreateCompress jCreaCompress
  155405. #define jpeg_CreateDecompress jCreaDecompress
  155406. #define jpeg_destroy_compress jDestCompress
  155407. #define jpeg_destroy_decompress jDestDecompress
  155408. #define jpeg_stdio_dest jStdDest
  155409. #define jpeg_stdio_src jStdSrc
  155410. #define jpeg_set_defaults jSetDefaults
  155411. #define jpeg_set_colorspace jSetColorspace
  155412. #define jpeg_default_colorspace jDefColorspace
  155413. #define jpeg_set_quality jSetQuality
  155414. #define jpeg_set_linear_quality jSetLQuality
  155415. #define jpeg_add_quant_table jAddQuantTable
  155416. #define jpeg_quality_scaling jQualityScaling
  155417. #define jpeg_simple_progression jSimProgress
  155418. #define jpeg_suppress_tables jSuppressTables
  155419. #define jpeg_alloc_quant_table jAlcQTable
  155420. #define jpeg_alloc_huff_table jAlcHTable
  155421. #define jpeg_start_compress jStrtCompress
  155422. #define jpeg_write_scanlines jWrtScanlines
  155423. #define jpeg_finish_compress jFinCompress
  155424. #define jpeg_write_raw_data jWrtRawData
  155425. #define jpeg_write_marker jWrtMarker
  155426. #define jpeg_write_m_header jWrtMHeader
  155427. #define jpeg_write_m_byte jWrtMByte
  155428. #define jpeg_write_tables jWrtTables
  155429. #define jpeg_read_header jReadHeader
  155430. #define jpeg_start_decompress jStrtDecompress
  155431. #define jpeg_read_scanlines jReadScanlines
  155432. #define jpeg_finish_decompress jFinDecompress
  155433. #define jpeg_read_raw_data jReadRawData
  155434. #define jpeg_has_multiple_scans jHasMultScn
  155435. #define jpeg_start_output jStrtOutput
  155436. #define jpeg_finish_output jFinOutput
  155437. #define jpeg_input_complete jInComplete
  155438. #define jpeg_new_colormap jNewCMap
  155439. #define jpeg_consume_input jConsumeInput
  155440. #define jpeg_calc_output_dimensions jCalcDimensions
  155441. #define jpeg_save_markers jSaveMarkers
  155442. #define jpeg_set_marker_processor jSetMarker
  155443. #define jpeg_read_coefficients jReadCoefs
  155444. #define jpeg_write_coefficients jWrtCoefs
  155445. #define jpeg_copy_critical_parameters jCopyCrit
  155446. #define jpeg_abort_compress jAbrtCompress
  155447. #define jpeg_abort_decompress jAbrtDecompress
  155448. #define jpeg_abort jAbort
  155449. #define jpeg_destroy jDestroy
  155450. #define jpeg_resync_to_restart jResyncRestart
  155451. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  155452. /* Default error-management setup */
  155453. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  155454. JPP((struct jpeg_error_mgr * err));
  155455. /* Initialization of JPEG compression objects.
  155456. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  155457. * names that applications should call. These expand to calls on
  155458. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  155459. * passed for version mismatch checking.
  155460. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  155461. */
  155462. #define jpeg_create_compress(cinfo) \
  155463. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  155464. (size_t) sizeof(struct jpeg_compress_struct))
  155465. #define jpeg_create_decompress(cinfo) \
  155466. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  155467. (size_t) sizeof(struct jpeg_decompress_struct))
  155468. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  155469. int version, size_t structsize));
  155470. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  155471. int version, size_t structsize));
  155472. /* Destruction of JPEG compression objects */
  155473. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  155474. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  155475. /* Standard data source and destination managers: stdio streams. */
  155476. /* Caller is responsible for opening the file before and closing after. */
  155477. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  155478. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  155479. /* Default parameter setup for compression */
  155480. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  155481. /* Compression parameter setup aids */
  155482. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  155483. J_COLOR_SPACE colorspace));
  155484. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  155485. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  155486. boolean force_baseline));
  155487. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  155488. int scale_factor,
  155489. boolean force_baseline));
  155490. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  155491. const unsigned int *basic_table,
  155492. int scale_factor,
  155493. boolean force_baseline));
  155494. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  155495. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  155496. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  155497. boolean suppress));
  155498. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  155499. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  155500. /* Main entry points for compression */
  155501. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  155502. boolean write_all_tables));
  155503. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  155504. JSAMPARRAY scanlines,
  155505. JDIMENSION num_lines));
  155506. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  155507. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  155508. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  155509. JSAMPIMAGE data,
  155510. JDIMENSION num_lines));
  155511. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  155512. EXTERN(void) jpeg_write_marker
  155513. JPP((j_compress_ptr cinfo, int marker,
  155514. const JOCTET * dataptr, unsigned int datalen));
  155515. /* Same, but piecemeal. */
  155516. EXTERN(void) jpeg_write_m_header
  155517. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  155518. EXTERN(void) jpeg_write_m_byte
  155519. JPP((j_compress_ptr cinfo, int val));
  155520. /* Alternate compression function: just write an abbreviated table file */
  155521. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  155522. /* Decompression startup: read start of JPEG datastream to see what's there */
  155523. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  155524. boolean require_image));
  155525. /* Return value is one of: */
  155526. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  155527. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  155528. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  155529. /* If you pass require_image = TRUE (normal case), you need not check for
  155530. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  155531. * JPEG_SUSPENDED is only possible if you use a data source module that can
  155532. * give a suspension return (the stdio source module doesn't).
  155533. */
  155534. /* Main entry points for decompression */
  155535. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  155536. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  155537. JSAMPARRAY scanlines,
  155538. JDIMENSION max_lines));
  155539. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  155540. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  155541. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  155542. JSAMPIMAGE data,
  155543. JDIMENSION max_lines));
  155544. /* Additional entry points for buffered-image mode. */
  155545. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  155546. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  155547. int scan_number));
  155548. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  155549. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  155550. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  155551. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  155552. /* Return value is one of: */
  155553. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  155554. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  155555. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  155556. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  155557. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  155558. /* Precalculate output dimensions for current decompression parameters. */
  155559. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  155560. /* Control saving of COM and APPn markers into marker_list. */
  155561. EXTERN(void) jpeg_save_markers
  155562. JPP((j_decompress_ptr cinfo, int marker_code,
  155563. unsigned int length_limit));
  155564. /* Install a special processing method for COM or APPn markers. */
  155565. EXTERN(void) jpeg_set_marker_processor
  155566. JPP((j_decompress_ptr cinfo, int marker_code,
  155567. jpeg_marker_parser_method routine));
  155568. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  155569. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  155570. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  155571. jvirt_barray_ptr * coef_arrays));
  155572. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  155573. j_compress_ptr dstinfo));
  155574. /* If you choose to abort compression or decompression before completing
  155575. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  155576. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  155577. * if you're done with the JPEG object, but if you want to clean it up and
  155578. * reuse it, call this:
  155579. */
  155580. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  155581. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  155582. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  155583. * flavor of JPEG object. These may be more convenient in some places.
  155584. */
  155585. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  155586. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  155587. /* Default restart-marker-resync procedure for use by data source modules */
  155588. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  155589. int desired));
  155590. /* These marker codes are exported since applications and data source modules
  155591. * are likely to want to use them.
  155592. */
  155593. #define JPEG_RST0 0xD0 /* RST0 marker code */
  155594. #define JPEG_EOI 0xD9 /* EOI marker code */
  155595. #define JPEG_APP0 0xE0 /* APP0 marker code */
  155596. #define JPEG_COM 0xFE /* COM marker code */
  155597. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  155598. * for structure definitions that are never filled in, keep it quiet by
  155599. * supplying dummy definitions for the various substructures.
  155600. */
  155601. #ifdef INCOMPLETE_TYPES_BROKEN
  155602. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  155603. struct jvirt_sarray_control { long dummy; };
  155604. struct jvirt_barray_control { long dummy; };
  155605. struct jpeg_comp_master { long dummy; };
  155606. struct jpeg_c_main_controller { long dummy; };
  155607. struct jpeg_c_prep_controller { long dummy; };
  155608. struct jpeg_c_coef_controller { long dummy; };
  155609. struct jpeg_marker_writer { long dummy; };
  155610. struct jpeg_color_converter { long dummy; };
  155611. struct jpeg_downsampler { long dummy; };
  155612. struct jpeg_forward_dct { long dummy; };
  155613. struct jpeg_entropy_encoder { long dummy; };
  155614. struct jpeg_decomp_master { long dummy; };
  155615. struct jpeg_d_main_controller { long dummy; };
  155616. struct jpeg_d_coef_controller { long dummy; };
  155617. struct jpeg_d_post_controller { long dummy; };
  155618. struct jpeg_input_controller { long dummy; };
  155619. struct jpeg_marker_reader { long dummy; };
  155620. struct jpeg_entropy_decoder { long dummy; };
  155621. struct jpeg_inverse_dct { long dummy; };
  155622. struct jpeg_upsampler { long dummy; };
  155623. struct jpeg_color_deconverter { long dummy; };
  155624. struct jpeg_color_quantizer { long dummy; };
  155625. #endif /* JPEG_INTERNALS */
  155626. #endif /* INCOMPLETE_TYPES_BROKEN */
  155627. /*
  155628. * The JPEG library modules define JPEG_INTERNALS before including this file.
  155629. * The internal structure declarations are read only when that is true.
  155630. * Applications using the library should not include jpegint.h, but may wish
  155631. * to include jerror.h.
  155632. */
  155633. #ifdef JPEG_INTERNALS
  155634. /********* Start of inlined file: jpegint.h *********/
  155635. /* Declarations for both compression & decompression */
  155636. typedef enum { /* Operating modes for buffer controllers */
  155637. JBUF_PASS_THRU, /* Plain stripwise operation */
  155638. /* Remaining modes require a full-image buffer to have been created */
  155639. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  155640. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  155641. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  155642. } J_BUF_MODE;
  155643. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  155644. #define CSTATE_START 100 /* after create_compress */
  155645. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  155646. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  155647. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  155648. #define DSTATE_START 200 /* after create_decompress */
  155649. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  155650. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  155651. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  155652. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  155653. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  155654. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  155655. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  155656. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  155657. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  155658. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  155659. /* Declarations for compression modules */
  155660. /* Master control module */
  155661. struct jpeg_comp_master {
  155662. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  155663. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  155664. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  155665. /* State variables made visible to other modules */
  155666. boolean call_pass_startup; /* True if pass_startup must be called */
  155667. boolean is_last_pass; /* True during last pass */
  155668. };
  155669. /* Main buffer control (downsampled-data buffer) */
  155670. struct jpeg_c_main_controller {
  155671. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  155672. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  155673. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  155674. JDIMENSION in_rows_avail));
  155675. };
  155676. /* Compression preprocessing (downsampling input buffer control) */
  155677. struct jpeg_c_prep_controller {
  155678. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  155679. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  155680. JSAMPARRAY input_buf,
  155681. JDIMENSION *in_row_ctr,
  155682. JDIMENSION in_rows_avail,
  155683. JSAMPIMAGE output_buf,
  155684. JDIMENSION *out_row_group_ctr,
  155685. JDIMENSION out_row_groups_avail));
  155686. };
  155687. /* Coefficient buffer control */
  155688. struct jpeg_c_coef_controller {
  155689. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  155690. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  155691. JSAMPIMAGE input_buf));
  155692. };
  155693. /* Colorspace conversion */
  155694. struct jpeg_color_converter {
  155695. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  155696. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  155697. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  155698. JDIMENSION output_row, int num_rows));
  155699. };
  155700. /* Downsampling */
  155701. struct jpeg_downsampler {
  155702. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  155703. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  155704. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  155705. JSAMPIMAGE output_buf,
  155706. JDIMENSION out_row_group_index));
  155707. boolean need_context_rows; /* TRUE if need rows above & below */
  155708. };
  155709. /* Forward DCT (also controls coefficient quantization) */
  155710. struct jpeg_forward_dct {
  155711. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  155712. /* perhaps this should be an array??? */
  155713. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  155714. jpeg_component_info * compptr,
  155715. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  155716. JDIMENSION start_row, JDIMENSION start_col,
  155717. JDIMENSION num_blocks));
  155718. };
  155719. /* Entropy encoding */
  155720. struct jpeg_entropy_encoder {
  155721. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  155722. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  155723. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  155724. };
  155725. /* Marker writing */
  155726. struct jpeg_marker_writer {
  155727. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  155728. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  155729. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  155730. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  155731. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  155732. /* These routines are exported to allow insertion of extra markers */
  155733. /* Probably only COM and APPn markers should be written this way */
  155734. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  155735. unsigned int datalen));
  155736. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  155737. };
  155738. /* Declarations for decompression modules */
  155739. /* Master control module */
  155740. struct jpeg_decomp_master {
  155741. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  155742. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  155743. /* State variables made visible to other modules */
  155744. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  155745. };
  155746. /* Input control module */
  155747. struct jpeg_input_controller {
  155748. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  155749. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  155750. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  155751. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  155752. /* State variables made visible to other modules */
  155753. boolean has_multiple_scans; /* True if file has multiple scans */
  155754. boolean eoi_reached; /* True when EOI has been consumed */
  155755. };
  155756. /* Main buffer control (downsampled-data buffer) */
  155757. struct jpeg_d_main_controller {
  155758. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  155759. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  155760. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  155761. JDIMENSION out_rows_avail));
  155762. };
  155763. /* Coefficient buffer control */
  155764. struct jpeg_d_coef_controller {
  155765. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  155766. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  155767. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  155768. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  155769. JSAMPIMAGE output_buf));
  155770. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  155771. jvirt_barray_ptr *coef_arrays;
  155772. };
  155773. /* Decompression postprocessing (color quantization buffer control) */
  155774. struct jpeg_d_post_controller {
  155775. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  155776. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  155777. JSAMPIMAGE input_buf,
  155778. JDIMENSION *in_row_group_ctr,
  155779. JDIMENSION in_row_groups_avail,
  155780. JSAMPARRAY output_buf,
  155781. JDIMENSION *out_row_ctr,
  155782. JDIMENSION out_rows_avail));
  155783. };
  155784. /* Marker reading & parsing */
  155785. struct jpeg_marker_reader {
  155786. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  155787. /* Read markers until SOS or EOI.
  155788. * Returns same codes as are defined for jpeg_consume_input:
  155789. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  155790. */
  155791. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  155792. /* Read a restart marker --- exported for use by entropy decoder only */
  155793. jpeg_marker_parser_method read_restart_marker;
  155794. /* State of marker reader --- nominally internal, but applications
  155795. * supplying COM or APPn handlers might like to know the state.
  155796. */
  155797. boolean saw_SOI; /* found SOI? */
  155798. boolean saw_SOF; /* found SOF? */
  155799. int next_restart_num; /* next restart number expected (0-7) */
  155800. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  155801. };
  155802. /* Entropy decoding */
  155803. struct jpeg_entropy_decoder {
  155804. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  155805. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  155806. JBLOCKROW *MCU_data));
  155807. /* This is here to share code between baseline and progressive decoders; */
  155808. /* other modules probably should not use it */
  155809. boolean insufficient_data; /* set TRUE after emitting warning */
  155810. };
  155811. /* Inverse DCT (also performs dequantization) */
  155812. typedef JMETHOD(void, inverse_DCT_method_ptr,
  155813. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  155814. JCOEFPTR coef_block,
  155815. JSAMPARRAY output_buf, JDIMENSION output_col));
  155816. struct jpeg_inverse_dct {
  155817. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  155818. /* It is useful to allow each component to have a separate IDCT method. */
  155819. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  155820. };
  155821. /* Upsampling (note that upsampler must also call color converter) */
  155822. struct jpeg_upsampler {
  155823. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  155824. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  155825. JSAMPIMAGE input_buf,
  155826. JDIMENSION *in_row_group_ctr,
  155827. JDIMENSION in_row_groups_avail,
  155828. JSAMPARRAY output_buf,
  155829. JDIMENSION *out_row_ctr,
  155830. JDIMENSION out_rows_avail));
  155831. boolean need_context_rows; /* TRUE if need rows above & below */
  155832. };
  155833. /* Colorspace conversion */
  155834. struct jpeg_color_deconverter {
  155835. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  155836. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  155837. JSAMPIMAGE input_buf, JDIMENSION input_row,
  155838. JSAMPARRAY output_buf, int num_rows));
  155839. };
  155840. /* Color quantization or color precision reduction */
  155841. struct jpeg_color_quantizer {
  155842. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  155843. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  155844. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  155845. int num_rows));
  155846. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  155847. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  155848. };
  155849. /* Miscellaneous useful macros */
  155850. #undef MAX
  155851. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  155852. #undef MIN
  155853. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  155854. /* We assume that right shift corresponds to signed division by 2 with
  155855. * rounding towards minus infinity. This is correct for typical "arithmetic
  155856. * shift" instructions that shift in copies of the sign bit. But some
  155857. * C compilers implement >> with an unsigned shift. For these machines you
  155858. * must define RIGHT_SHIFT_IS_UNSIGNED.
  155859. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  155860. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  155861. * included in the variables of any routine using RIGHT_SHIFT.
  155862. */
  155863. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  155864. #define SHIFT_TEMPS INT32 shift_temp;
  155865. #define RIGHT_SHIFT(x,shft) \
  155866. ((shift_temp = (x)) < 0 ? \
  155867. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  155868. (shift_temp >> (shft)))
  155869. #else
  155870. #define SHIFT_TEMPS
  155871. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  155872. #endif
  155873. /* Short forms of external names for systems with brain-damaged linkers. */
  155874. #ifdef NEED_SHORT_EXTERNAL_NAMES
  155875. #define jinit_compress_master jICompress
  155876. #define jinit_c_master_control jICMaster
  155877. #define jinit_c_main_controller jICMainC
  155878. #define jinit_c_prep_controller jICPrepC
  155879. #define jinit_c_coef_controller jICCoefC
  155880. #define jinit_color_converter jICColor
  155881. #define jinit_downsampler jIDownsampler
  155882. #define jinit_forward_dct jIFDCT
  155883. #define jinit_huff_encoder jIHEncoder
  155884. #define jinit_phuff_encoder jIPHEncoder
  155885. #define jinit_marker_writer jIMWriter
  155886. #define jinit_master_decompress jIDMaster
  155887. #define jinit_d_main_controller jIDMainC
  155888. #define jinit_d_coef_controller jIDCoefC
  155889. #define jinit_d_post_controller jIDPostC
  155890. #define jinit_input_controller jIInCtlr
  155891. #define jinit_marker_reader jIMReader
  155892. #define jinit_huff_decoder jIHDecoder
  155893. #define jinit_phuff_decoder jIPHDecoder
  155894. #define jinit_inverse_dct jIIDCT
  155895. #define jinit_upsampler jIUpsampler
  155896. #define jinit_color_deconverter jIDColor
  155897. #define jinit_1pass_quantizer jI1Quant
  155898. #define jinit_2pass_quantizer jI2Quant
  155899. #define jinit_merged_upsampler jIMUpsampler
  155900. #define jinit_memory_mgr jIMemMgr
  155901. #define jdiv_round_up jDivRound
  155902. #define jround_up jRound
  155903. #define jcopy_sample_rows jCopySamples
  155904. #define jcopy_block_row jCopyBlocks
  155905. #define jzero_far jZeroFar
  155906. #define jpeg_zigzag_order jZIGTable
  155907. #define jpeg_natural_order jZAGTable
  155908. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  155909. /* Compression module initialization routines */
  155910. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  155911. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  155912. boolean transcode_only));
  155913. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  155914. boolean need_full_buffer));
  155915. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  155916. boolean need_full_buffer));
  155917. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  155918. boolean need_full_buffer));
  155919. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  155920. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  155921. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  155922. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  155923. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  155924. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  155925. /* Decompression module initialization routines */
  155926. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  155927. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  155928. boolean need_full_buffer));
  155929. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  155930. boolean need_full_buffer));
  155931. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  155932. boolean need_full_buffer));
  155933. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  155934. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  155935. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  155936. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  155937. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  155938. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  155939. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  155940. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  155941. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  155942. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  155943. /* Memory manager initialization */
  155944. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  155945. /* Utility routines in jutils.c */
  155946. EXTERN(long) jdiv_round_up JPP((long a, long b));
  155947. EXTERN(long) jround_up JPP((long a, long b));
  155948. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  155949. JSAMPARRAY output_array, int dest_row,
  155950. int num_rows, JDIMENSION num_cols));
  155951. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  155952. JDIMENSION num_blocks));
  155953. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  155954. /* Constant tables in jutils.c */
  155955. #if 0 /* This table is not actually needed in v6a */
  155956. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  155957. #endif
  155958. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  155959. /* Suppress undefined-structure complaints if necessary. */
  155960. #ifdef INCOMPLETE_TYPES_BROKEN
  155961. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  155962. struct jvirt_sarray_control { long dummy; };
  155963. struct jvirt_barray_control { long dummy; };
  155964. #endif
  155965. #endif /* INCOMPLETE_TYPES_BROKEN */
  155966. /********* End of inlined file: jpegint.h *********/
  155967. /* fetch private declarations */
  155968. /********* Start of inlined file: jerror.h *********/
  155969. /*
  155970. * To define the enum list of message codes, include this file without
  155971. * defining macro JMESSAGE. To create a message string table, include it
  155972. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  155973. */
  155974. #ifndef JMESSAGE
  155975. #ifndef JERROR_H
  155976. /* First time through, define the enum list */
  155977. #define JMAKE_ENUM_LIST
  155978. #else
  155979. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  155980. #define JMESSAGE(code,string)
  155981. #endif /* JERROR_H */
  155982. #endif /* JMESSAGE */
  155983. #ifdef JMAKE_ENUM_LIST
  155984. typedef enum {
  155985. #define JMESSAGE(code,string) code ,
  155986. #endif /* JMAKE_ENUM_LIST */
  155987. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  155988. /* For maintenance convenience, list is alphabetical by message code name */
  155989. JMESSAGE(JERR_ARITH_NOTIMPL,
  155990. "Sorry, there are legal restrictions on arithmetic coding")
  155991. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  155992. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  155993. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  155994. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  155995. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  155996. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  155997. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  155998. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  155999. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  156000. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  156001. JMESSAGE(JERR_BAD_LIB_VERSION,
  156002. "Wrong JPEG library version: library is %d, caller expects %d")
  156003. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  156004. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  156005. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  156006. JMESSAGE(JERR_BAD_PROGRESSION,
  156007. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  156008. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  156009. "Invalid progressive parameters at scan script entry %d")
  156010. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  156011. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  156012. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  156013. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  156014. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  156015. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  156016. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  156017. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  156018. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  156019. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  156020. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  156021. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  156022. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  156023. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  156024. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  156025. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  156026. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  156027. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  156028. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  156029. JMESSAGE(JERR_FILE_READ, "Input file read error")
  156030. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  156031. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  156032. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  156033. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  156034. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  156035. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  156036. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  156037. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  156038. "Cannot transcode due to multiple use of quantization table %d")
  156039. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  156040. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  156041. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  156042. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  156043. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  156044. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  156045. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  156046. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  156047. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  156048. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  156049. JMESSAGE(JERR_QUANT_COMPONENTS,
  156050. "Cannot quantize more than %d color components")
  156051. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  156052. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  156053. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  156054. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  156055. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  156056. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  156057. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  156058. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  156059. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  156060. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  156061. JMESSAGE(JERR_TFILE_WRITE,
  156062. "Write failed on temporary file --- out of disk space?")
  156063. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  156064. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  156065. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  156066. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  156067. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  156068. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  156069. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  156070. JMESSAGE(JMSG_VERSION, JVERSION)
  156071. JMESSAGE(JTRC_16BIT_TABLES,
  156072. "Caution: quantization tables are too coarse for baseline JPEG")
  156073. JMESSAGE(JTRC_ADOBE,
  156074. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  156075. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  156076. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  156077. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  156078. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  156079. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  156080. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  156081. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  156082. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  156083. JMESSAGE(JTRC_EOI, "End Of Image")
  156084. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  156085. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  156086. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  156087. "Warning: thumbnail image size does not match data length %u")
  156088. JMESSAGE(JTRC_JFIF_EXTENSION,
  156089. "JFIF extension marker: type 0x%02x, length %u")
  156090. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  156091. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  156092. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  156093. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  156094. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  156095. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  156096. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  156097. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  156098. JMESSAGE(JTRC_RST, "RST%d")
  156099. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  156100. "Smoothing not supported with nonstandard sampling ratios")
  156101. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  156102. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  156103. JMESSAGE(JTRC_SOI, "Start of Image")
  156104. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  156105. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  156106. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  156107. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  156108. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  156109. JMESSAGE(JTRC_THUMB_JPEG,
  156110. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  156111. JMESSAGE(JTRC_THUMB_PALETTE,
  156112. "JFIF extension marker: palette thumbnail image, length %u")
  156113. JMESSAGE(JTRC_THUMB_RGB,
  156114. "JFIF extension marker: RGB thumbnail image, length %u")
  156115. JMESSAGE(JTRC_UNKNOWN_IDS,
  156116. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  156117. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  156118. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  156119. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  156120. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  156121. "Inconsistent progression sequence for component %d coefficient %d")
  156122. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  156123. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  156124. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  156125. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  156126. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  156127. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  156128. JMESSAGE(JWRN_MUST_RESYNC,
  156129. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  156130. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  156131. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  156132. #ifdef JMAKE_ENUM_LIST
  156133. JMSG_LASTMSGCODE
  156134. } J_MESSAGE_CODE;
  156135. #undef JMAKE_ENUM_LIST
  156136. #endif /* JMAKE_ENUM_LIST */
  156137. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  156138. #undef JMESSAGE
  156139. #ifndef JERROR_H
  156140. #define JERROR_H
  156141. /* Macros to simplify using the error and trace message stuff */
  156142. /* The first parameter is either type of cinfo pointer */
  156143. /* Fatal errors (print message and exit) */
  156144. #define ERREXIT(cinfo,code) \
  156145. ((cinfo)->err->msg_code = (code), \
  156146. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156147. #define ERREXIT1(cinfo,code,p1) \
  156148. ((cinfo)->err->msg_code = (code), \
  156149. (cinfo)->err->msg_parm.i[0] = (p1), \
  156150. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156151. #define ERREXIT2(cinfo,code,p1,p2) \
  156152. ((cinfo)->err->msg_code = (code), \
  156153. (cinfo)->err->msg_parm.i[0] = (p1), \
  156154. (cinfo)->err->msg_parm.i[1] = (p2), \
  156155. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156156. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  156157. ((cinfo)->err->msg_code = (code), \
  156158. (cinfo)->err->msg_parm.i[0] = (p1), \
  156159. (cinfo)->err->msg_parm.i[1] = (p2), \
  156160. (cinfo)->err->msg_parm.i[2] = (p3), \
  156161. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156162. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  156163. ((cinfo)->err->msg_code = (code), \
  156164. (cinfo)->err->msg_parm.i[0] = (p1), \
  156165. (cinfo)->err->msg_parm.i[1] = (p2), \
  156166. (cinfo)->err->msg_parm.i[2] = (p3), \
  156167. (cinfo)->err->msg_parm.i[3] = (p4), \
  156168. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156169. #define ERREXITS(cinfo,code,str) \
  156170. ((cinfo)->err->msg_code = (code), \
  156171. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  156172. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156173. #define MAKESTMT(stuff) do { stuff } while (0)
  156174. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  156175. #define WARNMS(cinfo,code) \
  156176. ((cinfo)->err->msg_code = (code), \
  156177. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  156178. #define WARNMS1(cinfo,code,p1) \
  156179. ((cinfo)->err->msg_code = (code), \
  156180. (cinfo)->err->msg_parm.i[0] = (p1), \
  156181. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  156182. #define WARNMS2(cinfo,code,p1,p2) \
  156183. ((cinfo)->err->msg_code = (code), \
  156184. (cinfo)->err->msg_parm.i[0] = (p1), \
  156185. (cinfo)->err->msg_parm.i[1] = (p2), \
  156186. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  156187. /* Informational/debugging messages */
  156188. #define TRACEMS(cinfo,lvl,code) \
  156189. ((cinfo)->err->msg_code = (code), \
  156190. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156191. #define TRACEMS1(cinfo,lvl,code,p1) \
  156192. ((cinfo)->err->msg_code = (code), \
  156193. (cinfo)->err->msg_parm.i[0] = (p1), \
  156194. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156195. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  156196. ((cinfo)->err->msg_code = (code), \
  156197. (cinfo)->err->msg_parm.i[0] = (p1), \
  156198. (cinfo)->err->msg_parm.i[1] = (p2), \
  156199. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156200. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  156201. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156202. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  156203. (cinfo)->err->msg_code = (code); \
  156204. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156205. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  156206. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156207. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  156208. (cinfo)->err->msg_code = (code); \
  156209. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156210. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  156211. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156212. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  156213. _mp[4] = (p5); \
  156214. (cinfo)->err->msg_code = (code); \
  156215. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156216. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  156217. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156218. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  156219. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  156220. (cinfo)->err->msg_code = (code); \
  156221. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156222. #define TRACEMSS(cinfo,lvl,code,str) \
  156223. ((cinfo)->err->msg_code = (code), \
  156224. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  156225. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156226. #endif /* JERROR_H */
  156227. /********* End of inlined file: jerror.h *********/
  156228. /* fetch error codes too */
  156229. #endif
  156230. #endif /* JPEGLIB_H */
  156231. /********* End of inlined file: jpeglib.h *********/
  156232. /********* Start of inlined file: jcapimin.c *********/
  156233. #define JPEG_INTERNALS
  156234. /********* Start of inlined file: jinclude.h *********/
  156235. /* Include auto-config file to find out which system include files we need. */
  156236. #ifndef __jinclude_h__
  156237. #define __jinclude_h__
  156238. /********* Start of inlined file: jconfig.h *********/
  156239. /* see jconfig.doc for explanations */
  156240. // disable all the warnings under MSVC
  156241. #ifdef _MSC_VER
  156242. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  156243. #endif
  156244. #ifdef __BORLANDC__
  156245. #pragma warn -8057
  156246. #pragma warn -8019
  156247. #pragma warn -8004
  156248. #pragma warn -8008
  156249. #endif
  156250. #define HAVE_PROTOTYPES
  156251. #define HAVE_UNSIGNED_CHAR
  156252. #define HAVE_UNSIGNED_SHORT
  156253. /* #define void char */
  156254. /* #define const */
  156255. #undef CHAR_IS_UNSIGNED
  156256. #define HAVE_STDDEF_H
  156257. #define HAVE_STDLIB_H
  156258. #undef NEED_BSD_STRINGS
  156259. #undef NEED_SYS_TYPES_H
  156260. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  156261. #undef NEED_SHORT_EXTERNAL_NAMES
  156262. #undef INCOMPLETE_TYPES_BROKEN
  156263. /* Define "boolean" as unsigned char, not int, per Windows custom */
  156264. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  156265. typedef unsigned char boolean;
  156266. #endif
  156267. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  156268. #ifdef JPEG_INTERNALS
  156269. #undef RIGHT_SHIFT_IS_UNSIGNED
  156270. #endif /* JPEG_INTERNALS */
  156271. #ifdef JPEG_CJPEG_DJPEG
  156272. #define BMP_SUPPORTED /* BMP image file format */
  156273. #define GIF_SUPPORTED /* GIF image file format */
  156274. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  156275. #undef RLE_SUPPORTED /* Utah RLE image file format */
  156276. #define TARGA_SUPPORTED /* Targa image file format */
  156277. #define TWO_FILE_COMMANDLINE /* optional */
  156278. #define USE_SETMODE /* Microsoft has setmode() */
  156279. #undef NEED_SIGNAL_CATCHER
  156280. #undef DONT_USE_B_MODE
  156281. #undef PROGRESS_REPORT /* optional */
  156282. #endif /* JPEG_CJPEG_DJPEG */
  156283. /********* End of inlined file: jconfig.h *********/
  156284. /* auto configuration options */
  156285. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  156286. /*
  156287. * We need the NULL macro and size_t typedef.
  156288. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  156289. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  156290. * pull in <sys/types.h> as well.
  156291. * Note that the core JPEG library does not require <stdio.h>;
  156292. * only the default error handler and data source/destination modules do.
  156293. * But we must pull it in because of the references to FILE in jpeglib.h.
  156294. * You can remove those references if you want to compile without <stdio.h>.
  156295. */
  156296. #ifdef HAVE_STDDEF_H
  156297. #include <stddef.h>
  156298. #endif
  156299. #ifdef HAVE_STDLIB_H
  156300. #include <stdlib.h>
  156301. #endif
  156302. #ifdef NEED_SYS_TYPES_H
  156303. #include <sys/types.h>
  156304. #endif
  156305. #include <stdio.h>
  156306. /*
  156307. * We need memory copying and zeroing functions, plus strncpy().
  156308. * ANSI and System V implementations declare these in <string.h>.
  156309. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  156310. * Some systems may declare memset and memcpy in <memory.h>.
  156311. *
  156312. * NOTE: we assume the size parameters to these functions are of type size_t.
  156313. * Change the casts in these macros if not!
  156314. */
  156315. #ifdef NEED_BSD_STRINGS
  156316. #include <strings.h>
  156317. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  156318. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  156319. #else /* not BSD, assume ANSI/SysV string lib */
  156320. #include <string.h>
  156321. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  156322. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  156323. #endif
  156324. /*
  156325. * In ANSI C, and indeed any rational implementation, size_t is also the
  156326. * type returned by sizeof(). However, it seems there are some irrational
  156327. * implementations out there, in which sizeof() returns an int even though
  156328. * size_t is defined as long or unsigned long. To ensure consistent results
  156329. * we always use this SIZEOF() macro in place of using sizeof() directly.
  156330. */
  156331. #define SIZEOF(object) ((size_t) sizeof(object))
  156332. /*
  156333. * The modules that use fread() and fwrite() always invoke them through
  156334. * these macros. On some systems you may need to twiddle the argument casts.
  156335. * CAUTION: argument order is different from underlying functions!
  156336. */
  156337. #define JFREAD(file,buf,sizeofbuf) \
  156338. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  156339. #define JFWRITE(file,buf,sizeofbuf) \
  156340. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  156341. typedef enum { /* JPEG marker codes */
  156342. M_SOF0 = 0xc0,
  156343. M_SOF1 = 0xc1,
  156344. M_SOF2 = 0xc2,
  156345. M_SOF3 = 0xc3,
  156346. M_SOF5 = 0xc5,
  156347. M_SOF6 = 0xc6,
  156348. M_SOF7 = 0xc7,
  156349. M_JPG = 0xc8,
  156350. M_SOF9 = 0xc9,
  156351. M_SOF10 = 0xca,
  156352. M_SOF11 = 0xcb,
  156353. M_SOF13 = 0xcd,
  156354. M_SOF14 = 0xce,
  156355. M_SOF15 = 0xcf,
  156356. M_DHT = 0xc4,
  156357. M_DAC = 0xcc,
  156358. M_RST0 = 0xd0,
  156359. M_RST1 = 0xd1,
  156360. M_RST2 = 0xd2,
  156361. M_RST3 = 0xd3,
  156362. M_RST4 = 0xd4,
  156363. M_RST5 = 0xd5,
  156364. M_RST6 = 0xd6,
  156365. M_RST7 = 0xd7,
  156366. M_SOI = 0xd8,
  156367. M_EOI = 0xd9,
  156368. M_SOS = 0xda,
  156369. M_DQT = 0xdb,
  156370. M_DNL = 0xdc,
  156371. M_DRI = 0xdd,
  156372. M_DHP = 0xde,
  156373. M_EXP = 0xdf,
  156374. M_APP0 = 0xe0,
  156375. M_APP1 = 0xe1,
  156376. M_APP2 = 0xe2,
  156377. M_APP3 = 0xe3,
  156378. M_APP4 = 0xe4,
  156379. M_APP5 = 0xe5,
  156380. M_APP6 = 0xe6,
  156381. M_APP7 = 0xe7,
  156382. M_APP8 = 0xe8,
  156383. M_APP9 = 0xe9,
  156384. M_APP10 = 0xea,
  156385. M_APP11 = 0xeb,
  156386. M_APP12 = 0xec,
  156387. M_APP13 = 0xed,
  156388. M_APP14 = 0xee,
  156389. M_APP15 = 0xef,
  156390. M_JPG0 = 0xf0,
  156391. M_JPG13 = 0xfd,
  156392. M_COM = 0xfe,
  156393. M_TEM = 0x01,
  156394. M_ERROR = 0x100
  156395. } JPEG_MARKER;
  156396. /*
  156397. * Figure F.12: extend sign bit.
  156398. * On some machines, a shift and add will be faster than a table lookup.
  156399. */
  156400. #ifdef AVOID_TABLES
  156401. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  156402. #else
  156403. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  156404. static const int extend_test[16] = /* entry n is 2**(n-1) */
  156405. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  156406. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  156407. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  156408. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  156409. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  156410. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  156411. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  156412. #endif /* AVOID_TABLES */
  156413. #endif
  156414. /********* End of inlined file: jinclude.h *********/
  156415. /*
  156416. * Initialization of a JPEG compression object.
  156417. * The error manager must already be set up (in case memory manager fails).
  156418. */
  156419. GLOBAL(void)
  156420. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  156421. {
  156422. int i;
  156423. /* Guard against version mismatches between library and caller. */
  156424. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  156425. if (version != JPEG_LIB_VERSION)
  156426. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  156427. if (structsize != SIZEOF(struct jpeg_compress_struct))
  156428. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  156429. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  156430. /* For debugging purposes, we zero the whole master structure.
  156431. * But the application has already set the err pointer, and may have set
  156432. * client_data, so we have to save and restore those fields.
  156433. * Note: if application hasn't set client_data, tools like Purify may
  156434. * complain here.
  156435. */
  156436. {
  156437. struct jpeg_error_mgr * err = cinfo->err;
  156438. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  156439. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  156440. cinfo->err = err;
  156441. cinfo->client_data = client_data;
  156442. }
  156443. cinfo->is_decompressor = FALSE;
  156444. /* Initialize a memory manager instance for this object */
  156445. jinit_memory_mgr((j_common_ptr) cinfo);
  156446. /* Zero out pointers to permanent structures. */
  156447. cinfo->progress = NULL;
  156448. cinfo->dest = NULL;
  156449. cinfo->comp_info = NULL;
  156450. for (i = 0; i < NUM_QUANT_TBLS; i++)
  156451. cinfo->quant_tbl_ptrs[i] = NULL;
  156452. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  156453. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  156454. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  156455. }
  156456. cinfo->script_space = NULL;
  156457. cinfo->input_gamma = 1.0; /* in case application forgets */
  156458. /* OK, I'm ready */
  156459. cinfo->global_state = CSTATE_START;
  156460. }
  156461. /*
  156462. * Destruction of a JPEG compression object
  156463. */
  156464. GLOBAL(void)
  156465. jpeg_destroy_compress (j_compress_ptr cinfo)
  156466. {
  156467. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  156468. }
  156469. /*
  156470. * Abort processing of a JPEG compression operation,
  156471. * but don't destroy the object itself.
  156472. */
  156473. GLOBAL(void)
  156474. jpeg_abort_compress (j_compress_ptr cinfo)
  156475. {
  156476. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  156477. }
  156478. /*
  156479. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  156480. * Marks all currently defined tables as already written (if suppress)
  156481. * or not written (if !suppress). This will control whether they get emitted
  156482. * by a subsequent jpeg_start_compress call.
  156483. *
  156484. * This routine is exported for use by applications that want to produce
  156485. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  156486. * since it is called by jpeg_start_compress, we put it here --- otherwise
  156487. * jcparam.o would be linked whether the application used it or not.
  156488. */
  156489. GLOBAL(void)
  156490. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  156491. {
  156492. int i;
  156493. JQUANT_TBL * qtbl;
  156494. JHUFF_TBL * htbl;
  156495. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  156496. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  156497. qtbl->sent_table = suppress;
  156498. }
  156499. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  156500. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  156501. htbl->sent_table = suppress;
  156502. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  156503. htbl->sent_table = suppress;
  156504. }
  156505. }
  156506. /*
  156507. * Finish JPEG compression.
  156508. *
  156509. * If a multipass operating mode was selected, this may do a great deal of
  156510. * work including most of the actual output.
  156511. */
  156512. GLOBAL(void)
  156513. jpeg_finish_compress (j_compress_ptr cinfo)
  156514. {
  156515. JDIMENSION iMCU_row;
  156516. if (cinfo->global_state == CSTATE_SCANNING ||
  156517. cinfo->global_state == CSTATE_RAW_OK) {
  156518. /* Terminate first pass */
  156519. if (cinfo->next_scanline < cinfo->image_height)
  156520. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  156521. (*cinfo->master->finish_pass) (cinfo);
  156522. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  156523. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  156524. /* Perform any remaining passes */
  156525. while (! cinfo->master->is_last_pass) {
  156526. (*cinfo->master->prepare_for_pass) (cinfo);
  156527. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  156528. if (cinfo->progress != NULL) {
  156529. cinfo->progress->pass_counter = (long) iMCU_row;
  156530. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  156531. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  156532. }
  156533. /* We bypass the main controller and invoke coef controller directly;
  156534. * all work is being done from the coefficient buffer.
  156535. */
  156536. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  156537. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  156538. }
  156539. (*cinfo->master->finish_pass) (cinfo);
  156540. }
  156541. /* Write EOI, do final cleanup */
  156542. (*cinfo->marker->write_file_trailer) (cinfo);
  156543. (*cinfo->dest->term_destination) (cinfo);
  156544. /* We can use jpeg_abort to release memory and reset global_state */
  156545. jpeg_abort((j_common_ptr) cinfo);
  156546. }
  156547. /*
  156548. * Write a special marker.
  156549. * This is only recommended for writing COM or APPn markers.
  156550. * Must be called after jpeg_start_compress() and before
  156551. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  156552. */
  156553. GLOBAL(void)
  156554. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  156555. const JOCTET *dataptr, unsigned int datalen)
  156556. {
  156557. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  156558. if (cinfo->next_scanline != 0 ||
  156559. (cinfo->global_state != CSTATE_SCANNING &&
  156560. cinfo->global_state != CSTATE_RAW_OK &&
  156561. cinfo->global_state != CSTATE_WRCOEFS))
  156562. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  156563. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  156564. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  156565. while (datalen--) {
  156566. (*write_marker_byte) (cinfo, *dataptr);
  156567. dataptr++;
  156568. }
  156569. }
  156570. /* Same, but piecemeal. */
  156571. GLOBAL(void)
  156572. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  156573. {
  156574. if (cinfo->next_scanline != 0 ||
  156575. (cinfo->global_state != CSTATE_SCANNING &&
  156576. cinfo->global_state != CSTATE_RAW_OK &&
  156577. cinfo->global_state != CSTATE_WRCOEFS))
  156578. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  156579. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  156580. }
  156581. GLOBAL(void)
  156582. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  156583. {
  156584. (*cinfo->marker->write_marker_byte) (cinfo, val);
  156585. }
  156586. /*
  156587. * Alternate compression function: just write an abbreviated table file.
  156588. * Before calling this, all parameters and a data destination must be set up.
  156589. *
  156590. * To produce a pair of files containing abbreviated tables and abbreviated
  156591. * image data, one would proceed as follows:
  156592. *
  156593. * initialize JPEG object
  156594. * set JPEG parameters
  156595. * set destination to table file
  156596. * jpeg_write_tables(cinfo);
  156597. * set destination to image file
  156598. * jpeg_start_compress(cinfo, FALSE);
  156599. * write data...
  156600. * jpeg_finish_compress(cinfo);
  156601. *
  156602. * jpeg_write_tables has the side effect of marking all tables written
  156603. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  156604. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  156605. */
  156606. GLOBAL(void)
  156607. jpeg_write_tables (j_compress_ptr cinfo)
  156608. {
  156609. if (cinfo->global_state != CSTATE_START)
  156610. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  156611. /* (Re)initialize error mgr and destination modules */
  156612. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  156613. (*cinfo->dest->init_destination) (cinfo);
  156614. /* Initialize the marker writer ... bit of a crock to do it here. */
  156615. jinit_marker_writer(cinfo);
  156616. /* Write them tables! */
  156617. (*cinfo->marker->write_tables_only) (cinfo);
  156618. /* And clean up. */
  156619. (*cinfo->dest->term_destination) (cinfo);
  156620. /*
  156621. * In library releases up through v6a, we called jpeg_abort() here to free
  156622. * any working memory allocated by the destination manager and marker
  156623. * writer. Some applications had a problem with that: they allocated space
  156624. * of their own from the library memory manager, and didn't want it to go
  156625. * away during write_tables. So now we do nothing. This will cause a
  156626. * memory leak if an app calls write_tables repeatedly without doing a full
  156627. * compression cycle or otherwise resetting the JPEG object. However, that
  156628. * seems less bad than unexpectedly freeing memory in the normal case.
  156629. * An app that prefers the old behavior can call jpeg_abort for itself after
  156630. * each call to jpeg_write_tables().
  156631. */
  156632. }
  156633. /********* End of inlined file: jcapimin.c *********/
  156634. /********* Start of inlined file: jcapistd.c *********/
  156635. #define JPEG_INTERNALS
  156636. /*
  156637. * Compression initialization.
  156638. * Before calling this, all parameters and a data destination must be set up.
  156639. *
  156640. * We require a write_all_tables parameter as a failsafe check when writing
  156641. * multiple datastreams from the same compression object. Since prior runs
  156642. * will have left all the tables marked sent_table=TRUE, a subsequent run
  156643. * would emit an abbreviated stream (no tables) by default. This may be what
  156644. * is wanted, but for safety's sake it should not be the default behavior:
  156645. * programmers should have to make a deliberate choice to emit abbreviated
  156646. * images. Therefore the documentation and examples should encourage people
  156647. * to pass write_all_tables=TRUE; then it will take active thought to do the
  156648. * wrong thing.
  156649. */
  156650. GLOBAL(void)
  156651. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  156652. {
  156653. if (cinfo->global_state != CSTATE_START)
  156654. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  156655. if (write_all_tables)
  156656. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  156657. /* (Re)initialize error mgr and destination modules */
  156658. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  156659. (*cinfo->dest->init_destination) (cinfo);
  156660. /* Perform master selection of active modules */
  156661. jinit_compress_master(cinfo);
  156662. /* Set up for the first pass */
  156663. (*cinfo->master->prepare_for_pass) (cinfo);
  156664. /* Ready for application to drive first pass through jpeg_write_scanlines
  156665. * or jpeg_write_raw_data.
  156666. */
  156667. cinfo->next_scanline = 0;
  156668. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  156669. }
  156670. /*
  156671. * Write some scanlines of data to the JPEG compressor.
  156672. *
  156673. * The return value will be the number of lines actually written.
  156674. * This should be less than the supplied num_lines only in case that
  156675. * the data destination module has requested suspension of the compressor,
  156676. * or if more than image_height scanlines are passed in.
  156677. *
  156678. * Note: we warn about excess calls to jpeg_write_scanlines() since
  156679. * this likely signals an application programmer error. However,
  156680. * excess scanlines passed in the last valid call are *silently* ignored,
  156681. * so that the application need not adjust num_lines for end-of-image
  156682. * when using a multiple-scanline buffer.
  156683. */
  156684. GLOBAL(JDIMENSION)
  156685. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  156686. JDIMENSION num_lines)
  156687. {
  156688. JDIMENSION row_ctr, rows_left;
  156689. if (cinfo->global_state != CSTATE_SCANNING)
  156690. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  156691. if (cinfo->next_scanline >= cinfo->image_height)
  156692. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  156693. /* Call progress monitor hook if present */
  156694. if (cinfo->progress != NULL) {
  156695. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  156696. cinfo->progress->pass_limit = (long) cinfo->image_height;
  156697. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  156698. }
  156699. /* Give master control module another chance if this is first call to
  156700. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  156701. * delayed so that application can write COM, etc, markers between
  156702. * jpeg_start_compress and jpeg_write_scanlines.
  156703. */
  156704. if (cinfo->master->call_pass_startup)
  156705. (*cinfo->master->pass_startup) (cinfo);
  156706. /* Ignore any extra scanlines at bottom of image. */
  156707. rows_left = cinfo->image_height - cinfo->next_scanline;
  156708. if (num_lines > rows_left)
  156709. num_lines = rows_left;
  156710. row_ctr = 0;
  156711. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  156712. cinfo->next_scanline += row_ctr;
  156713. return row_ctr;
  156714. }
  156715. /*
  156716. * Alternate entry point to write raw data.
  156717. * Processes exactly one iMCU row per call, unless suspended.
  156718. */
  156719. GLOBAL(JDIMENSION)
  156720. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  156721. JDIMENSION num_lines)
  156722. {
  156723. JDIMENSION lines_per_iMCU_row;
  156724. if (cinfo->global_state != CSTATE_RAW_OK)
  156725. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  156726. if (cinfo->next_scanline >= cinfo->image_height) {
  156727. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  156728. return 0;
  156729. }
  156730. /* Call progress monitor hook if present */
  156731. if (cinfo->progress != NULL) {
  156732. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  156733. cinfo->progress->pass_limit = (long) cinfo->image_height;
  156734. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  156735. }
  156736. /* Give master control module another chance if this is first call to
  156737. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  156738. * delayed so that application can write COM, etc, markers between
  156739. * jpeg_start_compress and jpeg_write_raw_data.
  156740. */
  156741. if (cinfo->master->call_pass_startup)
  156742. (*cinfo->master->pass_startup) (cinfo);
  156743. /* Verify that at least one iMCU row has been passed. */
  156744. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  156745. if (num_lines < lines_per_iMCU_row)
  156746. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  156747. /* Directly compress the row. */
  156748. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  156749. /* If compressor did not consume the whole row, suspend processing. */
  156750. return 0;
  156751. }
  156752. /* OK, we processed one iMCU row. */
  156753. cinfo->next_scanline += lines_per_iMCU_row;
  156754. return lines_per_iMCU_row;
  156755. }
  156756. /********* End of inlined file: jcapistd.c *********/
  156757. /********* Start of inlined file: jccoefct.c *********/
  156758. #define JPEG_INTERNALS
  156759. /* We use a full-image coefficient buffer when doing Huffman optimization,
  156760. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  156761. * step is run during the first pass, and subsequent passes need only read
  156762. * the buffered coefficients.
  156763. */
  156764. #ifdef ENTROPY_OPT_SUPPORTED
  156765. #define FULL_COEF_BUFFER_SUPPORTED
  156766. #else
  156767. #ifdef C_MULTISCAN_FILES_SUPPORTED
  156768. #define FULL_COEF_BUFFER_SUPPORTED
  156769. #endif
  156770. #endif
  156771. /* Private buffer controller object */
  156772. typedef struct {
  156773. struct jpeg_c_coef_controller pub; /* public fields */
  156774. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  156775. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  156776. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  156777. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  156778. /* For single-pass compression, it's sufficient to buffer just one MCU
  156779. * (although this may prove a bit slow in practice). We allocate a
  156780. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  156781. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  156782. * it's not really very big; this is to keep the module interfaces unchanged
  156783. * when a large coefficient buffer is necessary.)
  156784. * In multi-pass modes, this array points to the current MCU's blocks
  156785. * within the virtual arrays.
  156786. */
  156787. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  156788. /* In multi-pass modes, we need a virtual block array for each component. */
  156789. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  156790. } my_coef_controller;
  156791. typedef my_coef_controller * my_coef_ptr;
  156792. /* Forward declarations */
  156793. METHODDEF(boolean) compress_data
  156794. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  156795. #ifdef FULL_COEF_BUFFER_SUPPORTED
  156796. METHODDEF(boolean) compress_first_pass
  156797. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  156798. METHODDEF(boolean) compress_output
  156799. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  156800. #endif
  156801. LOCAL(void)
  156802. start_iMCU_row (j_compress_ptr cinfo)
  156803. /* Reset within-iMCU-row counters for a new row */
  156804. {
  156805. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156806. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  156807. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  156808. * But at the bottom of the image, process only what's left.
  156809. */
  156810. if (cinfo->comps_in_scan > 1) {
  156811. coef->MCU_rows_per_iMCU_row = 1;
  156812. } else {
  156813. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  156814. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  156815. else
  156816. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  156817. }
  156818. coef->mcu_ctr = 0;
  156819. coef->MCU_vert_offset = 0;
  156820. }
  156821. /*
  156822. * Initialize for a processing pass.
  156823. */
  156824. METHODDEF(void)
  156825. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  156826. {
  156827. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156828. coef->iMCU_row_num = 0;
  156829. start_iMCU_row(cinfo);
  156830. switch (pass_mode) {
  156831. case JBUF_PASS_THRU:
  156832. if (coef->whole_image[0] != NULL)
  156833. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156834. coef->pub.compress_data = compress_data;
  156835. break;
  156836. #ifdef FULL_COEF_BUFFER_SUPPORTED
  156837. case JBUF_SAVE_AND_PASS:
  156838. if (coef->whole_image[0] == NULL)
  156839. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156840. coef->pub.compress_data = compress_first_pass;
  156841. break;
  156842. case JBUF_CRANK_DEST:
  156843. if (coef->whole_image[0] == NULL)
  156844. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156845. coef->pub.compress_data = compress_output;
  156846. break;
  156847. #endif
  156848. default:
  156849. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156850. break;
  156851. }
  156852. }
  156853. /*
  156854. * Process some data in the single-pass case.
  156855. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  156856. * per call, ie, v_samp_factor block rows for each component in the image.
  156857. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  156858. *
  156859. * NB: input_buf contains a plane for each component in image,
  156860. * which we index according to the component's SOF position.
  156861. */
  156862. METHODDEF(boolean)
  156863. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  156864. {
  156865. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156866. JDIMENSION MCU_col_num; /* index of current MCU within row */
  156867. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  156868. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  156869. int blkn, bi, ci, yindex, yoffset, blockcnt;
  156870. JDIMENSION ypos, xpos;
  156871. jpeg_component_info *compptr;
  156872. /* Loop to write as much as one whole iMCU row */
  156873. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  156874. yoffset++) {
  156875. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  156876. MCU_col_num++) {
  156877. /* Determine where data comes from in input_buf and do the DCT thing.
  156878. * Each call on forward_DCT processes a horizontal row of DCT blocks
  156879. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  156880. * sequentially. Dummy blocks at the right or bottom edge are filled in
  156881. * specially. The data in them does not matter for image reconstruction,
  156882. * so we fill them with values that will encode to the smallest amount of
  156883. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  156884. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  156885. */
  156886. blkn = 0;
  156887. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  156888. compptr = cinfo->cur_comp_info[ci];
  156889. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  156890. : compptr->last_col_width;
  156891. xpos = MCU_col_num * compptr->MCU_sample_width;
  156892. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  156893. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  156894. if (coef->iMCU_row_num < last_iMCU_row ||
  156895. yoffset+yindex < compptr->last_row_height) {
  156896. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  156897. input_buf[compptr->component_index],
  156898. coef->MCU_buffer[blkn],
  156899. ypos, xpos, (JDIMENSION) blockcnt);
  156900. if (blockcnt < compptr->MCU_width) {
  156901. /* Create some dummy blocks at the right edge of the image. */
  156902. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  156903. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  156904. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  156905. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  156906. }
  156907. }
  156908. } else {
  156909. /* Create a row of dummy blocks at the bottom of the image. */
  156910. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  156911. compptr->MCU_width * SIZEOF(JBLOCK));
  156912. for (bi = 0; bi < compptr->MCU_width; bi++) {
  156913. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  156914. }
  156915. }
  156916. blkn += compptr->MCU_width;
  156917. ypos += DCTSIZE;
  156918. }
  156919. }
  156920. /* Try to write the MCU. In event of a suspension failure, we will
  156921. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  156922. */
  156923. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  156924. /* Suspension forced; update state counters and exit */
  156925. coef->MCU_vert_offset = yoffset;
  156926. coef->mcu_ctr = MCU_col_num;
  156927. return FALSE;
  156928. }
  156929. }
  156930. /* Completed an MCU row, but perhaps not an iMCU row */
  156931. coef->mcu_ctr = 0;
  156932. }
  156933. /* Completed the iMCU row, advance counters for next one */
  156934. coef->iMCU_row_num++;
  156935. start_iMCU_row(cinfo);
  156936. return TRUE;
  156937. }
  156938. #ifdef FULL_COEF_BUFFER_SUPPORTED
  156939. /*
  156940. * Process some data in the first pass of a multi-pass case.
  156941. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  156942. * per call, ie, v_samp_factor block rows for each component in the image.
  156943. * This amount of data is read from the source buffer, DCT'd and quantized,
  156944. * and saved into the virtual arrays. We also generate suitable dummy blocks
  156945. * as needed at the right and lower edges. (The dummy blocks are constructed
  156946. * in the virtual arrays, which have been padded appropriately.) This makes
  156947. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  156948. *
  156949. * We must also emit the data to the entropy encoder. This is conveniently
  156950. * done by calling compress_output() after we've loaded the current strip
  156951. * of the virtual arrays.
  156952. *
  156953. * NB: input_buf contains a plane for each component in image. All
  156954. * components are DCT'd and loaded into the virtual arrays in this pass.
  156955. * However, it may be that only a subset of the components are emitted to
  156956. * the entropy encoder during this first pass; be careful about looking
  156957. * at the scan-dependent variables (MCU dimensions, etc).
  156958. */
  156959. METHODDEF(boolean)
  156960. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  156961. {
  156962. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156963. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  156964. JDIMENSION blocks_across, MCUs_across, MCUindex;
  156965. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  156966. JCOEF lastDC;
  156967. jpeg_component_info *compptr;
  156968. JBLOCKARRAY buffer;
  156969. JBLOCKROW thisblockrow, lastblockrow;
  156970. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  156971. ci++, compptr++) {
  156972. /* Align the virtual buffer for this component. */
  156973. buffer = (*cinfo->mem->access_virt_barray)
  156974. ((j_common_ptr) cinfo, coef->whole_image[ci],
  156975. coef->iMCU_row_num * compptr->v_samp_factor,
  156976. (JDIMENSION) compptr->v_samp_factor, TRUE);
  156977. /* Count non-dummy DCT block rows in this iMCU row. */
  156978. if (coef->iMCU_row_num < last_iMCU_row)
  156979. block_rows = compptr->v_samp_factor;
  156980. else {
  156981. /* NB: can't use last_row_height here, since may not be set! */
  156982. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  156983. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  156984. }
  156985. blocks_across = compptr->width_in_blocks;
  156986. h_samp_factor = compptr->h_samp_factor;
  156987. /* Count number of dummy blocks to be added at the right margin. */
  156988. ndummy = (int) (blocks_across % h_samp_factor);
  156989. if (ndummy > 0)
  156990. ndummy = h_samp_factor - ndummy;
  156991. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  156992. * on forward_DCT processes a complete horizontal row of DCT blocks.
  156993. */
  156994. for (block_row = 0; block_row < block_rows; block_row++) {
  156995. thisblockrow = buffer[block_row];
  156996. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  156997. input_buf[ci], thisblockrow,
  156998. (JDIMENSION) (block_row * DCTSIZE),
  156999. (JDIMENSION) 0, blocks_across);
  157000. if (ndummy > 0) {
  157001. /* Create dummy blocks at the right edge of the image. */
  157002. thisblockrow += blocks_across; /* => first dummy block */
  157003. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  157004. lastDC = thisblockrow[-1][0];
  157005. for (bi = 0; bi < ndummy; bi++) {
  157006. thisblockrow[bi][0] = lastDC;
  157007. }
  157008. }
  157009. }
  157010. /* If at end of image, create dummy block rows as needed.
  157011. * The tricky part here is that within each MCU, we want the DC values
  157012. * of the dummy blocks to match the last real block's DC value.
  157013. * This squeezes a few more bytes out of the resulting file...
  157014. */
  157015. if (coef->iMCU_row_num == last_iMCU_row) {
  157016. blocks_across += ndummy; /* include lower right corner */
  157017. MCUs_across = blocks_across / h_samp_factor;
  157018. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  157019. block_row++) {
  157020. thisblockrow = buffer[block_row];
  157021. lastblockrow = buffer[block_row-1];
  157022. jzero_far((void FAR *) thisblockrow,
  157023. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  157024. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  157025. lastDC = lastblockrow[h_samp_factor-1][0];
  157026. for (bi = 0; bi < h_samp_factor; bi++) {
  157027. thisblockrow[bi][0] = lastDC;
  157028. }
  157029. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  157030. lastblockrow += h_samp_factor;
  157031. }
  157032. }
  157033. }
  157034. }
  157035. /* NB: compress_output will increment iMCU_row_num if successful.
  157036. * A suspension return will result in redoing all the work above next time.
  157037. */
  157038. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  157039. return compress_output(cinfo, input_buf);
  157040. }
  157041. /*
  157042. * Process some data in subsequent passes of a multi-pass case.
  157043. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157044. * per call, ie, v_samp_factor block rows for each component in the scan.
  157045. * The data is obtained from the virtual arrays and fed to the entropy coder.
  157046. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  157047. *
  157048. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  157049. */
  157050. METHODDEF(boolean)
  157051. compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157052. {
  157053. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157054. JDIMENSION MCU_col_num; /* index of current MCU within row */
  157055. int blkn, ci, xindex, yindex, yoffset;
  157056. JDIMENSION start_col;
  157057. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  157058. JBLOCKROW buffer_ptr;
  157059. jpeg_component_info *compptr;
  157060. /* Align the virtual buffers for the components used in this scan.
  157061. * NB: during first pass, this is safe only because the buffers will
  157062. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  157063. */
  157064. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157065. compptr = cinfo->cur_comp_info[ci];
  157066. buffer[ci] = (*cinfo->mem->access_virt_barray)
  157067. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  157068. coef->iMCU_row_num * compptr->v_samp_factor,
  157069. (JDIMENSION) compptr->v_samp_factor, FALSE);
  157070. }
  157071. /* Loop to process one whole iMCU row */
  157072. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  157073. yoffset++) {
  157074. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  157075. MCU_col_num++) {
  157076. /* Construct list of pointers to DCT blocks belonging to this MCU */
  157077. blkn = 0; /* index of current DCT block within MCU */
  157078. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157079. compptr = cinfo->cur_comp_info[ci];
  157080. start_col = MCU_col_num * compptr->MCU_width;
  157081. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  157082. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  157083. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  157084. coef->MCU_buffer[blkn++] = buffer_ptr++;
  157085. }
  157086. }
  157087. }
  157088. /* Try to write the MCU. */
  157089. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  157090. /* Suspension forced; update state counters and exit */
  157091. coef->MCU_vert_offset = yoffset;
  157092. coef->mcu_ctr = MCU_col_num;
  157093. return FALSE;
  157094. }
  157095. }
  157096. /* Completed an MCU row, but perhaps not an iMCU row */
  157097. coef->mcu_ctr = 0;
  157098. }
  157099. /* Completed the iMCU row, advance counters for next one */
  157100. coef->iMCU_row_num++;
  157101. start_iMCU_row(cinfo);
  157102. return TRUE;
  157103. }
  157104. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  157105. /*
  157106. * Initialize coefficient buffer controller.
  157107. */
  157108. GLOBAL(void)
  157109. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  157110. {
  157111. my_coef_ptr coef;
  157112. coef = (my_coef_ptr)
  157113. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157114. SIZEOF(my_coef_controller));
  157115. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  157116. coef->pub.start_pass = start_pass_coef;
  157117. /* Create the coefficient buffer. */
  157118. if (need_full_buffer) {
  157119. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157120. /* Allocate a full-image virtual array for each component, */
  157121. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  157122. int ci;
  157123. jpeg_component_info *compptr;
  157124. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157125. ci++, compptr++) {
  157126. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  157127. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  157128. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  157129. (long) compptr->h_samp_factor),
  157130. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  157131. (long) compptr->v_samp_factor),
  157132. (JDIMENSION) compptr->v_samp_factor);
  157133. }
  157134. #else
  157135. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157136. #endif
  157137. } else {
  157138. /* We only need a single-MCU buffer. */
  157139. JBLOCKROW buffer;
  157140. int i;
  157141. buffer = (JBLOCKROW)
  157142. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157143. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  157144. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  157145. coef->MCU_buffer[i] = buffer + i;
  157146. }
  157147. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  157148. }
  157149. }
  157150. /********* End of inlined file: jccoefct.c *********/
  157151. /********* Start of inlined file: jccolor.c *********/
  157152. #define JPEG_INTERNALS
  157153. /* Private subobject */
  157154. typedef struct {
  157155. struct jpeg_color_converter pub; /* public fields */
  157156. /* Private state for RGB->YCC conversion */
  157157. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  157158. } my_color_converter;
  157159. typedef my_color_converter * my_cconvert_ptr;
  157160. /**************** RGB -> YCbCr conversion: most common case **************/
  157161. /*
  157162. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  157163. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  157164. * The conversion equations to be implemented are therefore
  157165. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  157166. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  157167. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  157168. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  157169. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  157170. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  157171. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  157172. * were not represented exactly. Now we sacrifice exact representation of
  157173. * maximum red and maximum blue in order to get exact grayscales.
  157174. *
  157175. * To avoid floating-point arithmetic, we represent the fractional constants
  157176. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  157177. * the products by 2^16, with appropriate rounding, to get the correct answer.
  157178. *
  157179. * For even more speed, we avoid doing any multiplications in the inner loop
  157180. * by precalculating the constants times R,G,B for all possible values.
  157181. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  157182. * for 12-bit samples it is still acceptable. It's not very reasonable for
  157183. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  157184. * colorspace anyway.
  157185. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  157186. * in the tables to save adding them separately in the inner loop.
  157187. */
  157188. #define SCALEBITS 16 /* speediest right-shift on some machines */
  157189. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  157190. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  157191. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  157192. /* We allocate one big table and divide it up into eight parts, instead of
  157193. * doing eight alloc_small requests. This lets us use a single table base
  157194. * address, which can be held in a register in the inner loops on many
  157195. * machines (more than can hold all eight addresses, anyway).
  157196. */
  157197. #define R_Y_OFF 0 /* offset to R => Y section */
  157198. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  157199. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  157200. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  157201. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  157202. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  157203. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  157204. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  157205. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  157206. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  157207. /*
  157208. * Initialize for RGB->YCC colorspace conversion.
  157209. */
  157210. METHODDEF(void)
  157211. rgb_ycc_start (j_compress_ptr cinfo)
  157212. {
  157213. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  157214. INT32 * rgb_ycc_tab;
  157215. INT32 i;
  157216. /* Allocate and fill in the conversion tables. */
  157217. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  157218. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157219. (TABLE_SIZE * SIZEOF(INT32)));
  157220. for (i = 0; i <= MAXJSAMPLE; i++) {
  157221. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  157222. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  157223. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  157224. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  157225. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  157226. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  157227. * This ensures that the maximum output will round to MAXJSAMPLE
  157228. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  157229. */
  157230. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  157231. /* B=>Cb and R=>Cr tables are the same
  157232. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  157233. */
  157234. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  157235. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  157236. }
  157237. }
  157238. /*
  157239. * Convert some rows of samples to the JPEG colorspace.
  157240. *
  157241. * Note that we change from the application's interleaved-pixel format
  157242. * to our internal noninterleaved, one-plane-per-component format.
  157243. * The input buffer is therefore three times as wide as the output buffer.
  157244. *
  157245. * A starting row offset is provided only for the output buffer. The caller
  157246. * can easily adjust the passed input_buf value to accommodate any row
  157247. * offset required on that side.
  157248. */
  157249. METHODDEF(void)
  157250. rgb_ycc_convert (j_compress_ptr cinfo,
  157251. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157252. JDIMENSION output_row, int num_rows)
  157253. {
  157254. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  157255. register int r, g, b;
  157256. register INT32 * ctab = cconvert->rgb_ycc_tab;
  157257. register JSAMPROW inptr;
  157258. register JSAMPROW outptr0, outptr1, outptr2;
  157259. register JDIMENSION col;
  157260. JDIMENSION num_cols = cinfo->image_width;
  157261. while (--num_rows >= 0) {
  157262. inptr = *input_buf++;
  157263. outptr0 = output_buf[0][output_row];
  157264. outptr1 = output_buf[1][output_row];
  157265. outptr2 = output_buf[2][output_row];
  157266. output_row++;
  157267. for (col = 0; col < num_cols; col++) {
  157268. r = GETJSAMPLE(inptr[RGB_RED]);
  157269. g = GETJSAMPLE(inptr[RGB_GREEN]);
  157270. b = GETJSAMPLE(inptr[RGB_BLUE]);
  157271. inptr += RGB_PIXELSIZE;
  157272. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  157273. * must be too; we do not need an explicit range-limiting operation.
  157274. * Hence the value being shifted is never negative, and we don't
  157275. * need the general RIGHT_SHIFT macro.
  157276. */
  157277. /* Y */
  157278. outptr0[col] = (JSAMPLE)
  157279. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  157280. >> SCALEBITS);
  157281. /* Cb */
  157282. outptr1[col] = (JSAMPLE)
  157283. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  157284. >> SCALEBITS);
  157285. /* Cr */
  157286. outptr2[col] = (JSAMPLE)
  157287. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  157288. >> SCALEBITS);
  157289. }
  157290. }
  157291. }
  157292. /**************** Cases other than RGB -> YCbCr **************/
  157293. /*
  157294. * Convert some rows of samples to the JPEG colorspace.
  157295. * This version handles RGB->grayscale conversion, which is the same
  157296. * as the RGB->Y portion of RGB->YCbCr.
  157297. * We assume rgb_ycc_start has been called (we only use the Y tables).
  157298. */
  157299. METHODDEF(void)
  157300. rgb_gray_convert (j_compress_ptr cinfo,
  157301. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157302. JDIMENSION output_row, int num_rows)
  157303. {
  157304. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  157305. register int r, g, b;
  157306. register INT32 * ctab = cconvert->rgb_ycc_tab;
  157307. register JSAMPROW inptr;
  157308. register JSAMPROW outptr;
  157309. register JDIMENSION col;
  157310. JDIMENSION num_cols = cinfo->image_width;
  157311. while (--num_rows >= 0) {
  157312. inptr = *input_buf++;
  157313. outptr = output_buf[0][output_row];
  157314. output_row++;
  157315. for (col = 0; col < num_cols; col++) {
  157316. r = GETJSAMPLE(inptr[RGB_RED]);
  157317. g = GETJSAMPLE(inptr[RGB_GREEN]);
  157318. b = GETJSAMPLE(inptr[RGB_BLUE]);
  157319. inptr += RGB_PIXELSIZE;
  157320. /* Y */
  157321. outptr[col] = (JSAMPLE)
  157322. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  157323. >> SCALEBITS);
  157324. }
  157325. }
  157326. }
  157327. /*
  157328. * Convert some rows of samples to the JPEG colorspace.
  157329. * This version handles Adobe-style CMYK->YCCK conversion,
  157330. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  157331. * conversion as above, while passing K (black) unchanged.
  157332. * We assume rgb_ycc_start has been called.
  157333. */
  157334. METHODDEF(void)
  157335. cmyk_ycck_convert (j_compress_ptr cinfo,
  157336. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157337. JDIMENSION output_row, int num_rows)
  157338. {
  157339. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  157340. register int r, g, b;
  157341. register INT32 * ctab = cconvert->rgb_ycc_tab;
  157342. register JSAMPROW inptr;
  157343. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  157344. register JDIMENSION col;
  157345. JDIMENSION num_cols = cinfo->image_width;
  157346. while (--num_rows >= 0) {
  157347. inptr = *input_buf++;
  157348. outptr0 = output_buf[0][output_row];
  157349. outptr1 = output_buf[1][output_row];
  157350. outptr2 = output_buf[2][output_row];
  157351. outptr3 = output_buf[3][output_row];
  157352. output_row++;
  157353. for (col = 0; col < num_cols; col++) {
  157354. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  157355. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  157356. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  157357. /* K passes through as-is */
  157358. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  157359. inptr += 4;
  157360. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  157361. * must be too; we do not need an explicit range-limiting operation.
  157362. * Hence the value being shifted is never negative, and we don't
  157363. * need the general RIGHT_SHIFT macro.
  157364. */
  157365. /* Y */
  157366. outptr0[col] = (JSAMPLE)
  157367. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  157368. >> SCALEBITS);
  157369. /* Cb */
  157370. outptr1[col] = (JSAMPLE)
  157371. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  157372. >> SCALEBITS);
  157373. /* Cr */
  157374. outptr2[col] = (JSAMPLE)
  157375. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  157376. >> SCALEBITS);
  157377. }
  157378. }
  157379. }
  157380. /*
  157381. * Convert some rows of samples to the JPEG colorspace.
  157382. * This version handles grayscale output with no conversion.
  157383. * The source can be either plain grayscale or YCbCr (since Y == gray).
  157384. */
  157385. METHODDEF(void)
  157386. grayscale_convert (j_compress_ptr cinfo,
  157387. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157388. JDIMENSION output_row, int num_rows)
  157389. {
  157390. register JSAMPROW inptr;
  157391. register JSAMPROW outptr;
  157392. register JDIMENSION col;
  157393. JDIMENSION num_cols = cinfo->image_width;
  157394. int instride = cinfo->input_components;
  157395. while (--num_rows >= 0) {
  157396. inptr = *input_buf++;
  157397. outptr = output_buf[0][output_row];
  157398. output_row++;
  157399. for (col = 0; col < num_cols; col++) {
  157400. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  157401. inptr += instride;
  157402. }
  157403. }
  157404. }
  157405. /*
  157406. * Convert some rows of samples to the JPEG colorspace.
  157407. * This version handles multi-component colorspaces without conversion.
  157408. * We assume input_components == num_components.
  157409. */
  157410. METHODDEF(void)
  157411. null_convert (j_compress_ptr cinfo,
  157412. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157413. JDIMENSION output_row, int num_rows)
  157414. {
  157415. register JSAMPROW inptr;
  157416. register JSAMPROW outptr;
  157417. register JDIMENSION col;
  157418. register int ci;
  157419. int nc = cinfo->num_components;
  157420. JDIMENSION num_cols = cinfo->image_width;
  157421. while (--num_rows >= 0) {
  157422. /* It seems fastest to make a separate pass for each component. */
  157423. for (ci = 0; ci < nc; ci++) {
  157424. inptr = *input_buf;
  157425. outptr = output_buf[ci][output_row];
  157426. for (col = 0; col < num_cols; col++) {
  157427. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  157428. inptr += nc;
  157429. }
  157430. }
  157431. input_buf++;
  157432. output_row++;
  157433. }
  157434. }
  157435. /*
  157436. * Empty method for start_pass.
  157437. */
  157438. METHODDEF(void)
  157439. null_method (j_compress_ptr cinfo)
  157440. {
  157441. /* no work needed */
  157442. }
  157443. /*
  157444. * Module initialization routine for input colorspace conversion.
  157445. */
  157446. GLOBAL(void)
  157447. jinit_color_converter (j_compress_ptr cinfo)
  157448. {
  157449. my_cconvert_ptr cconvert;
  157450. cconvert = (my_cconvert_ptr)
  157451. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157452. SIZEOF(my_color_converter));
  157453. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  157454. /* set start_pass to null method until we find out differently */
  157455. cconvert->pub.start_pass = null_method;
  157456. /* Make sure input_components agrees with in_color_space */
  157457. switch (cinfo->in_color_space) {
  157458. case JCS_GRAYSCALE:
  157459. if (cinfo->input_components != 1)
  157460. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  157461. break;
  157462. case JCS_RGB:
  157463. #if RGB_PIXELSIZE != 3
  157464. if (cinfo->input_components != RGB_PIXELSIZE)
  157465. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  157466. break;
  157467. #endif /* else share code with YCbCr */
  157468. case JCS_YCbCr:
  157469. if (cinfo->input_components != 3)
  157470. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  157471. break;
  157472. case JCS_CMYK:
  157473. case JCS_YCCK:
  157474. if (cinfo->input_components != 4)
  157475. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  157476. break;
  157477. default: /* JCS_UNKNOWN can be anything */
  157478. if (cinfo->input_components < 1)
  157479. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  157480. break;
  157481. }
  157482. /* Check num_components, set conversion method based on requested space */
  157483. switch (cinfo->jpeg_color_space) {
  157484. case JCS_GRAYSCALE:
  157485. if (cinfo->num_components != 1)
  157486. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  157487. if (cinfo->in_color_space == JCS_GRAYSCALE)
  157488. cconvert->pub.color_convert = grayscale_convert;
  157489. else if (cinfo->in_color_space == JCS_RGB) {
  157490. cconvert->pub.start_pass = rgb_ycc_start;
  157491. cconvert->pub.color_convert = rgb_gray_convert;
  157492. } else if (cinfo->in_color_space == JCS_YCbCr)
  157493. cconvert->pub.color_convert = grayscale_convert;
  157494. else
  157495. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  157496. break;
  157497. case JCS_RGB:
  157498. if (cinfo->num_components != 3)
  157499. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  157500. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  157501. cconvert->pub.color_convert = null_convert;
  157502. else
  157503. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  157504. break;
  157505. case JCS_YCbCr:
  157506. if (cinfo->num_components != 3)
  157507. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  157508. if (cinfo->in_color_space == JCS_RGB) {
  157509. cconvert->pub.start_pass = rgb_ycc_start;
  157510. cconvert->pub.color_convert = rgb_ycc_convert;
  157511. } else if (cinfo->in_color_space == JCS_YCbCr)
  157512. cconvert->pub.color_convert = null_convert;
  157513. else
  157514. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  157515. break;
  157516. case JCS_CMYK:
  157517. if (cinfo->num_components != 4)
  157518. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  157519. if (cinfo->in_color_space == JCS_CMYK)
  157520. cconvert->pub.color_convert = null_convert;
  157521. else
  157522. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  157523. break;
  157524. case JCS_YCCK:
  157525. if (cinfo->num_components != 4)
  157526. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  157527. if (cinfo->in_color_space == JCS_CMYK) {
  157528. cconvert->pub.start_pass = rgb_ycc_start;
  157529. cconvert->pub.color_convert = cmyk_ycck_convert;
  157530. } else if (cinfo->in_color_space == JCS_YCCK)
  157531. cconvert->pub.color_convert = null_convert;
  157532. else
  157533. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  157534. break;
  157535. default: /* allow null conversion of JCS_UNKNOWN */
  157536. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  157537. cinfo->num_components != cinfo->input_components)
  157538. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  157539. cconvert->pub.color_convert = null_convert;
  157540. break;
  157541. }
  157542. }
  157543. /********* End of inlined file: jccolor.c *********/
  157544. #undef FIX
  157545. /********* Start of inlined file: jcdctmgr.c *********/
  157546. #define JPEG_INTERNALS
  157547. /********* Start of inlined file: jdct.h *********/
  157548. /*
  157549. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  157550. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  157551. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  157552. * implementations use an array of type FAST_FLOAT, instead.)
  157553. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  157554. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  157555. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  157556. * convention improves accuracy in integer implementations and saves some
  157557. * work in floating-point ones.
  157558. * Quantization of the output coefficients is done by jcdctmgr.c.
  157559. */
  157560. #ifndef __jdct_h__
  157561. #define __jdct_h__
  157562. #if BITS_IN_JSAMPLE == 8
  157563. typedef int DCTELEM; /* 16 or 32 bits is fine */
  157564. #else
  157565. typedef INT32 DCTELEM; /* must have 32 bits */
  157566. #endif
  157567. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  157568. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  157569. /*
  157570. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  157571. * to an output sample array. The routine must dequantize the input data as
  157572. * well as perform the IDCT; for dequantization, it uses the multiplier table
  157573. * pointed to by compptr->dct_table. The output data is to be placed into the
  157574. * sample array starting at a specified column. (Any row offset needed will
  157575. * be applied to the array pointer before it is passed to the IDCT code.)
  157576. * Note that the number of samples emitted by the IDCT routine is
  157577. * DCT_scaled_size * DCT_scaled_size.
  157578. */
  157579. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  157580. /*
  157581. * Each IDCT routine has its own ideas about the best dct_table element type.
  157582. */
  157583. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  157584. #if BITS_IN_JSAMPLE == 8
  157585. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  157586. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  157587. #else
  157588. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  157589. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  157590. #endif
  157591. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  157592. /*
  157593. * Each IDCT routine is responsible for range-limiting its results and
  157594. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  157595. * be quite far out of range if the input data is corrupt, so a bulletproof
  157596. * range-limiting step is required. We use a mask-and-table-lookup method
  157597. * to do the combined operations quickly. See the comments with
  157598. * prepare_range_limit_table (in jdmaster.c) for more info.
  157599. */
  157600. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  157601. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  157602. /* Short forms of external names for systems with brain-damaged linkers. */
  157603. #ifdef NEED_SHORT_EXTERNAL_NAMES
  157604. #define jpeg_fdct_islow jFDislow
  157605. #define jpeg_fdct_ifast jFDifast
  157606. #define jpeg_fdct_float jFDfloat
  157607. #define jpeg_idct_islow jRDislow
  157608. #define jpeg_idct_ifast jRDifast
  157609. #define jpeg_idct_float jRDfloat
  157610. #define jpeg_idct_4x4 jRD4x4
  157611. #define jpeg_idct_2x2 jRD2x2
  157612. #define jpeg_idct_1x1 jRD1x1
  157613. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  157614. /* Extern declarations for the forward and inverse DCT routines. */
  157615. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  157616. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  157617. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  157618. EXTERN(void) jpeg_idct_islow
  157619. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157620. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  157621. EXTERN(void) jpeg_idct_ifast
  157622. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157623. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  157624. EXTERN(void) jpeg_idct_float
  157625. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157626. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  157627. EXTERN(void) jpeg_idct_4x4
  157628. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157629. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  157630. EXTERN(void) jpeg_idct_2x2
  157631. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157632. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  157633. EXTERN(void) jpeg_idct_1x1
  157634. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  157635. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  157636. /*
  157637. * Macros for handling fixed-point arithmetic; these are used by many
  157638. * but not all of the DCT/IDCT modules.
  157639. *
  157640. * All values are expected to be of type INT32.
  157641. * Fractional constants are scaled left by CONST_BITS bits.
  157642. * CONST_BITS is defined within each module using these macros,
  157643. * and may differ from one module to the next.
  157644. */
  157645. #define ONE ((INT32) 1)
  157646. #define CONST_SCALE (ONE << CONST_BITS)
  157647. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  157648. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  157649. * thus causing a lot of useless floating-point operations at run time.
  157650. */
  157651. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  157652. /* Descale and correctly round an INT32 value that's scaled by N bits.
  157653. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  157654. * the fudge factor is correct for either sign of X.
  157655. */
  157656. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  157657. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  157658. * This macro is used only when the two inputs will actually be no more than
  157659. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  157660. * full 32x32 multiply. This provides a useful speedup on many machines.
  157661. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  157662. * in C, but some C compilers will do the right thing if you provide the
  157663. * correct combination of casts.
  157664. */
  157665. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  157666. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  157667. #endif
  157668. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  157669. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  157670. #endif
  157671. #ifndef MULTIPLY16C16 /* default definition */
  157672. #define MULTIPLY16C16(var,const) ((var) * (const))
  157673. #endif
  157674. /* Same except both inputs are variables. */
  157675. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  157676. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  157677. #endif
  157678. #ifndef MULTIPLY16V16 /* default definition */
  157679. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  157680. #endif
  157681. #endif
  157682. /********* End of inlined file: jdct.h *********/
  157683. /* Private declarations for DCT subsystem */
  157684. /* Private subobject for this module */
  157685. typedef struct {
  157686. struct jpeg_forward_dct pub; /* public fields */
  157687. /* Pointer to the DCT routine actually in use */
  157688. forward_DCT_method_ptr do_dct;
  157689. /* The actual post-DCT divisors --- not identical to the quant table
  157690. * entries, because of scaling (especially for an unnormalized DCT).
  157691. * Each table is given in normal array order.
  157692. */
  157693. DCTELEM * divisors[NUM_QUANT_TBLS];
  157694. #ifdef DCT_FLOAT_SUPPORTED
  157695. /* Same as above for the floating-point case. */
  157696. float_DCT_method_ptr do_float_dct;
  157697. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  157698. #endif
  157699. } my_fdct_controller;
  157700. typedef my_fdct_controller * my_fdct_ptr;
  157701. /*
  157702. * Initialize for a processing pass.
  157703. * Verify that all referenced Q-tables are present, and set up
  157704. * the divisor table for each one.
  157705. * In the current implementation, DCT of all components is done during
  157706. * the first pass, even if only some components will be output in the
  157707. * first scan. Hence all components should be examined here.
  157708. */
  157709. METHODDEF(void)
  157710. start_pass_fdctmgr (j_compress_ptr cinfo)
  157711. {
  157712. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  157713. int ci, qtblno, i;
  157714. jpeg_component_info *compptr;
  157715. JQUANT_TBL * qtbl;
  157716. DCTELEM * dtbl;
  157717. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157718. ci++, compptr++) {
  157719. qtblno = compptr->quant_tbl_no;
  157720. /* Make sure specified quantization table is present */
  157721. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  157722. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  157723. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  157724. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  157725. /* Compute divisors for this quant table */
  157726. /* We may do this more than once for same table, but it's not a big deal */
  157727. switch (cinfo->dct_method) {
  157728. #ifdef DCT_ISLOW_SUPPORTED
  157729. case JDCT_ISLOW:
  157730. /* For LL&M IDCT method, divisors are equal to raw quantization
  157731. * coefficients multiplied by 8 (to counteract scaling).
  157732. */
  157733. if (fdct->divisors[qtblno] == NULL) {
  157734. fdct->divisors[qtblno] = (DCTELEM *)
  157735. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157736. DCTSIZE2 * SIZEOF(DCTELEM));
  157737. }
  157738. dtbl = fdct->divisors[qtblno];
  157739. for (i = 0; i < DCTSIZE2; i++) {
  157740. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  157741. }
  157742. break;
  157743. #endif
  157744. #ifdef DCT_IFAST_SUPPORTED
  157745. case JDCT_IFAST:
  157746. {
  157747. /* For AA&N IDCT method, divisors are equal to quantization
  157748. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  157749. * scalefactor[0] = 1
  157750. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  157751. * We apply a further scale factor of 8.
  157752. */
  157753. #define CONST_BITS 14
  157754. static const INT16 aanscales[DCTSIZE2] = {
  157755. /* precomputed values scaled up by 14 bits */
  157756. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  157757. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  157758. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  157759. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  157760. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  157761. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  157762. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  157763. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  157764. };
  157765. SHIFT_TEMPS
  157766. if (fdct->divisors[qtblno] == NULL) {
  157767. fdct->divisors[qtblno] = (DCTELEM *)
  157768. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157769. DCTSIZE2 * SIZEOF(DCTELEM));
  157770. }
  157771. dtbl = fdct->divisors[qtblno];
  157772. for (i = 0; i < DCTSIZE2; i++) {
  157773. dtbl[i] = (DCTELEM)
  157774. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  157775. (INT32) aanscales[i]),
  157776. CONST_BITS-3);
  157777. }
  157778. }
  157779. break;
  157780. #endif
  157781. #ifdef DCT_FLOAT_SUPPORTED
  157782. case JDCT_FLOAT:
  157783. {
  157784. /* For float AA&N IDCT method, divisors are equal to quantization
  157785. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  157786. * scalefactor[0] = 1
  157787. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  157788. * We apply a further scale factor of 8.
  157789. * What's actually stored is 1/divisor so that the inner loop can
  157790. * use a multiplication rather than a division.
  157791. */
  157792. FAST_FLOAT * fdtbl;
  157793. int row, col;
  157794. static const double aanscalefactor[DCTSIZE] = {
  157795. 1.0, 1.387039845, 1.306562965, 1.175875602,
  157796. 1.0, 0.785694958, 0.541196100, 0.275899379
  157797. };
  157798. if (fdct->float_divisors[qtblno] == NULL) {
  157799. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  157800. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157801. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  157802. }
  157803. fdtbl = fdct->float_divisors[qtblno];
  157804. i = 0;
  157805. for (row = 0; row < DCTSIZE; row++) {
  157806. for (col = 0; col < DCTSIZE; col++) {
  157807. fdtbl[i] = (FAST_FLOAT)
  157808. (1.0 / (((double) qtbl->quantval[i] *
  157809. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  157810. i++;
  157811. }
  157812. }
  157813. }
  157814. break;
  157815. #endif
  157816. default:
  157817. ERREXIT(cinfo, JERR_NOT_COMPILED);
  157818. break;
  157819. }
  157820. }
  157821. }
  157822. /*
  157823. * Perform forward DCT on one or more blocks of a component.
  157824. *
  157825. * The input samples are taken from the sample_data[] array starting at
  157826. * position start_row/start_col, and moving to the right for any additional
  157827. * blocks. The quantized coefficients are returned in coef_blocks[].
  157828. */
  157829. METHODDEF(void)
  157830. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  157831. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  157832. JDIMENSION start_row, JDIMENSION start_col,
  157833. JDIMENSION num_blocks)
  157834. /* This version is used for integer DCT implementations. */
  157835. {
  157836. /* This routine is heavily used, so it's worth coding it tightly. */
  157837. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  157838. forward_DCT_method_ptr do_dct = fdct->do_dct;
  157839. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  157840. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  157841. JDIMENSION bi;
  157842. sample_data += start_row; /* fold in the vertical offset once */
  157843. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  157844. /* Load data into workspace, applying unsigned->signed conversion */
  157845. { register DCTELEM *workspaceptr;
  157846. register JSAMPROW elemptr;
  157847. register int elemr;
  157848. workspaceptr = workspace;
  157849. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  157850. elemptr = sample_data[elemr] + start_col;
  157851. #if DCTSIZE == 8 /* unroll the inner loop */
  157852. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157853. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157854. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157855. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157856. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157857. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157858. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157859. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157860. #else
  157861. { register int elemc;
  157862. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  157863. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157864. }
  157865. }
  157866. #endif
  157867. }
  157868. }
  157869. /* Perform the DCT */
  157870. (*do_dct) (workspace);
  157871. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  157872. { register DCTELEM temp, qval;
  157873. register int i;
  157874. register JCOEFPTR output_ptr = coef_blocks[bi];
  157875. for (i = 0; i < DCTSIZE2; i++) {
  157876. qval = divisors[i];
  157877. temp = workspace[i];
  157878. /* Divide the coefficient value by qval, ensuring proper rounding.
  157879. * Since C does not specify the direction of rounding for negative
  157880. * quotients, we have to force the dividend positive for portability.
  157881. *
  157882. * In most files, at least half of the output values will be zero
  157883. * (at default quantization settings, more like three-quarters...)
  157884. * so we should ensure that this case is fast. On many machines,
  157885. * a comparison is enough cheaper than a divide to make a special test
  157886. * a win. Since both inputs will be nonnegative, we need only test
  157887. * for a < b to discover whether a/b is 0.
  157888. * If your machine's division is fast enough, define FAST_DIVIDE.
  157889. */
  157890. #ifdef FAST_DIVIDE
  157891. #define DIVIDE_BY(a,b) a /= b
  157892. #else
  157893. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  157894. #endif
  157895. if (temp < 0) {
  157896. temp = -temp;
  157897. temp += qval>>1; /* for rounding */
  157898. DIVIDE_BY(temp, qval);
  157899. temp = -temp;
  157900. } else {
  157901. temp += qval>>1; /* for rounding */
  157902. DIVIDE_BY(temp, qval);
  157903. }
  157904. output_ptr[i] = (JCOEF) temp;
  157905. }
  157906. }
  157907. }
  157908. }
  157909. #ifdef DCT_FLOAT_SUPPORTED
  157910. METHODDEF(void)
  157911. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  157912. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  157913. JDIMENSION start_row, JDIMENSION start_col,
  157914. JDIMENSION num_blocks)
  157915. /* This version is used for floating-point DCT implementations. */
  157916. {
  157917. /* This routine is heavily used, so it's worth coding it tightly. */
  157918. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  157919. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  157920. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  157921. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  157922. JDIMENSION bi;
  157923. sample_data += start_row; /* fold in the vertical offset once */
  157924. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  157925. /* Load data into workspace, applying unsigned->signed conversion */
  157926. { register FAST_FLOAT *workspaceptr;
  157927. register JSAMPROW elemptr;
  157928. register int elemr;
  157929. workspaceptr = workspace;
  157930. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  157931. elemptr = sample_data[elemr] + start_col;
  157932. #if DCTSIZE == 8 /* unroll the inner loop */
  157933. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157934. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157935. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157936. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157937. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157938. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157939. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157940. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157941. #else
  157942. { register int elemc;
  157943. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  157944. *workspaceptr++ = (FAST_FLOAT)
  157945. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157946. }
  157947. }
  157948. #endif
  157949. }
  157950. }
  157951. /* Perform the DCT */
  157952. (*do_dct) (workspace);
  157953. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  157954. { register FAST_FLOAT temp;
  157955. register int i;
  157956. register JCOEFPTR output_ptr = coef_blocks[bi];
  157957. for (i = 0; i < DCTSIZE2; i++) {
  157958. /* Apply the quantization and scaling factor */
  157959. temp = workspace[i] * divisors[i];
  157960. /* Round to nearest integer.
  157961. * Since C does not specify the direction of rounding for negative
  157962. * quotients, we have to force the dividend positive for portability.
  157963. * The maximum coefficient size is +-16K (for 12-bit data), so this
  157964. * code should work for either 16-bit or 32-bit ints.
  157965. */
  157966. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  157967. }
  157968. }
  157969. }
  157970. }
  157971. #endif /* DCT_FLOAT_SUPPORTED */
  157972. /*
  157973. * Initialize FDCT manager.
  157974. */
  157975. GLOBAL(void)
  157976. jinit_forward_dct (j_compress_ptr cinfo)
  157977. {
  157978. my_fdct_ptr fdct;
  157979. int i;
  157980. fdct = (my_fdct_ptr)
  157981. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157982. SIZEOF(my_fdct_controller));
  157983. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  157984. fdct->pub.start_pass = start_pass_fdctmgr;
  157985. switch (cinfo->dct_method) {
  157986. #ifdef DCT_ISLOW_SUPPORTED
  157987. case JDCT_ISLOW:
  157988. fdct->pub.forward_DCT = forward_DCT;
  157989. fdct->do_dct = jpeg_fdct_islow;
  157990. break;
  157991. #endif
  157992. #ifdef DCT_IFAST_SUPPORTED
  157993. case JDCT_IFAST:
  157994. fdct->pub.forward_DCT = forward_DCT;
  157995. fdct->do_dct = jpeg_fdct_ifast;
  157996. break;
  157997. #endif
  157998. #ifdef DCT_FLOAT_SUPPORTED
  157999. case JDCT_FLOAT:
  158000. fdct->pub.forward_DCT = forward_DCT_float;
  158001. fdct->do_float_dct = jpeg_fdct_float;
  158002. break;
  158003. #endif
  158004. default:
  158005. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158006. break;
  158007. }
  158008. /* Mark divisor tables unallocated */
  158009. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  158010. fdct->divisors[i] = NULL;
  158011. #ifdef DCT_FLOAT_SUPPORTED
  158012. fdct->float_divisors[i] = NULL;
  158013. #endif
  158014. }
  158015. }
  158016. /********* End of inlined file: jcdctmgr.c *********/
  158017. #undef CONST_BITS
  158018. /********* Start of inlined file: jchuff.c *********/
  158019. #define JPEG_INTERNALS
  158020. /********* Start of inlined file: jchuff.h *********/
  158021. /* The legal range of a DCT coefficient is
  158022. * -1024 .. +1023 for 8-bit data;
  158023. * -16384 .. +16383 for 12-bit data.
  158024. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  158025. */
  158026. #ifndef _jchuff_h_
  158027. #define _jchuff_h_
  158028. #if BITS_IN_JSAMPLE == 8
  158029. #define MAX_COEF_BITS 10
  158030. #else
  158031. #define MAX_COEF_BITS 14
  158032. #endif
  158033. /* Derived data constructed for each Huffman table */
  158034. typedef struct {
  158035. unsigned int ehufco[256]; /* code for each symbol */
  158036. char ehufsi[256]; /* length of code for each symbol */
  158037. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  158038. } c_derived_tbl;
  158039. /* Short forms of external names for systems with brain-damaged linkers. */
  158040. #ifdef NEED_SHORT_EXTERNAL_NAMES
  158041. #define jpeg_make_c_derived_tbl jMkCDerived
  158042. #define jpeg_gen_optimal_table jGenOptTbl
  158043. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  158044. /* Expand a Huffman table definition into the derived format */
  158045. EXTERN(void) jpeg_make_c_derived_tbl
  158046. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  158047. c_derived_tbl ** pdtbl));
  158048. /* Generate an optimal table definition given the specified counts */
  158049. EXTERN(void) jpeg_gen_optimal_table
  158050. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  158051. #endif
  158052. /********* End of inlined file: jchuff.h *********/
  158053. /* Declarations shared with jcphuff.c */
  158054. /* Expanded entropy encoder object for Huffman encoding.
  158055. *
  158056. * The savable_state subrecord contains fields that change within an MCU,
  158057. * but must not be updated permanently until we complete the MCU.
  158058. */
  158059. typedef struct {
  158060. INT32 put_buffer; /* current bit-accumulation buffer */
  158061. int put_bits; /* # of bits now in it */
  158062. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  158063. } savable_state;
  158064. /* This macro is to work around compilers with missing or broken
  158065. * structure assignment. You'll need to fix this code if you have
  158066. * such a compiler and you change MAX_COMPS_IN_SCAN.
  158067. */
  158068. #ifndef NO_STRUCT_ASSIGN
  158069. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  158070. #else
  158071. #if MAX_COMPS_IN_SCAN == 4
  158072. #define ASSIGN_STATE(dest,src) \
  158073. ((dest).put_buffer = (src).put_buffer, \
  158074. (dest).put_bits = (src).put_bits, \
  158075. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  158076. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  158077. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  158078. (dest).last_dc_val[3] = (src).last_dc_val[3])
  158079. #endif
  158080. #endif
  158081. typedef struct {
  158082. struct jpeg_entropy_encoder pub; /* public fields */
  158083. savable_state saved; /* Bit buffer & DC state at start of MCU */
  158084. /* These fields are NOT loaded into local working state. */
  158085. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  158086. int next_restart_num; /* next restart number to write (0-7) */
  158087. /* Pointers to derived tables (these workspaces have image lifespan) */
  158088. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  158089. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  158090. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  158091. long * dc_count_ptrs[NUM_HUFF_TBLS];
  158092. long * ac_count_ptrs[NUM_HUFF_TBLS];
  158093. #endif
  158094. } huff_entropy_encoder;
  158095. typedef huff_entropy_encoder * huff_entropy_ptr;
  158096. /* Working state while writing an MCU.
  158097. * This struct contains all the fields that are needed by subroutines.
  158098. */
  158099. typedef struct {
  158100. JOCTET * next_output_byte; /* => next byte to write in buffer */
  158101. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  158102. savable_state cur; /* Current bit buffer & DC state */
  158103. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  158104. } working_state;
  158105. /* Forward declarations */
  158106. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  158107. JBLOCKROW *MCU_data));
  158108. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  158109. #ifdef ENTROPY_OPT_SUPPORTED
  158110. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  158111. JBLOCKROW *MCU_data));
  158112. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  158113. #endif
  158114. /*
  158115. * Initialize for a Huffman-compressed scan.
  158116. * If gather_statistics is TRUE, we do not output anything during the scan,
  158117. * just count the Huffman symbols used and generate Huffman code tables.
  158118. */
  158119. METHODDEF(void)
  158120. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  158121. {
  158122. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  158123. int ci, dctbl, actbl;
  158124. jpeg_component_info * compptr;
  158125. if (gather_statistics) {
  158126. #ifdef ENTROPY_OPT_SUPPORTED
  158127. entropy->pub.encode_mcu = encode_mcu_gather;
  158128. entropy->pub.finish_pass = finish_pass_gather;
  158129. #else
  158130. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158131. #endif
  158132. } else {
  158133. entropy->pub.encode_mcu = encode_mcu_huff;
  158134. entropy->pub.finish_pass = finish_pass_huff;
  158135. }
  158136. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158137. compptr = cinfo->cur_comp_info[ci];
  158138. dctbl = compptr->dc_tbl_no;
  158139. actbl = compptr->ac_tbl_no;
  158140. if (gather_statistics) {
  158141. #ifdef ENTROPY_OPT_SUPPORTED
  158142. /* Check for invalid table indexes */
  158143. /* (make_c_derived_tbl does this in the other path) */
  158144. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  158145. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  158146. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  158147. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  158148. /* Allocate and zero the statistics tables */
  158149. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  158150. if (entropy->dc_count_ptrs[dctbl] == NULL)
  158151. entropy->dc_count_ptrs[dctbl] = (long *)
  158152. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158153. 257 * SIZEOF(long));
  158154. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  158155. if (entropy->ac_count_ptrs[actbl] == NULL)
  158156. entropy->ac_count_ptrs[actbl] = (long *)
  158157. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158158. 257 * SIZEOF(long));
  158159. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  158160. #endif
  158161. } else {
  158162. /* Compute derived values for Huffman tables */
  158163. /* We may do this more than once for a table, but it's not expensive */
  158164. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  158165. & entropy->dc_derived_tbls[dctbl]);
  158166. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  158167. & entropy->ac_derived_tbls[actbl]);
  158168. }
  158169. /* Initialize DC predictions to 0 */
  158170. entropy->saved.last_dc_val[ci] = 0;
  158171. }
  158172. /* Initialize bit buffer to empty */
  158173. entropy->saved.put_buffer = 0;
  158174. entropy->saved.put_bits = 0;
  158175. /* Initialize restart stuff */
  158176. entropy->restarts_to_go = cinfo->restart_interval;
  158177. entropy->next_restart_num = 0;
  158178. }
  158179. /*
  158180. * Compute the derived values for a Huffman table.
  158181. * This routine also performs some validation checks on the table.
  158182. *
  158183. * Note this is also used by jcphuff.c.
  158184. */
  158185. GLOBAL(void)
  158186. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  158187. c_derived_tbl ** pdtbl)
  158188. {
  158189. JHUFF_TBL *htbl;
  158190. c_derived_tbl *dtbl;
  158191. int p, i, l, lastp, si, maxsymbol;
  158192. char huffsize[257];
  158193. unsigned int huffcode[257];
  158194. unsigned int code;
  158195. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  158196. * paralleling the order of the symbols themselves in htbl->huffval[].
  158197. */
  158198. /* Find the input Huffman table */
  158199. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  158200. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  158201. htbl =
  158202. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  158203. if (htbl == NULL)
  158204. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  158205. /* Allocate a workspace if we haven't already done so. */
  158206. if (*pdtbl == NULL)
  158207. *pdtbl = (c_derived_tbl *)
  158208. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158209. SIZEOF(c_derived_tbl));
  158210. dtbl = *pdtbl;
  158211. /* Figure C.1: make table of Huffman code length for each symbol */
  158212. p = 0;
  158213. for (l = 1; l <= 16; l++) {
  158214. i = (int) htbl->bits[l];
  158215. if (i < 0 || p + i > 256) /* protect against table overrun */
  158216. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  158217. while (i--)
  158218. huffsize[p++] = (char) l;
  158219. }
  158220. huffsize[p] = 0;
  158221. lastp = p;
  158222. /* Figure C.2: generate the codes themselves */
  158223. /* We also validate that the counts represent a legal Huffman code tree. */
  158224. code = 0;
  158225. si = huffsize[0];
  158226. p = 0;
  158227. while (huffsize[p]) {
  158228. while (((int) huffsize[p]) == si) {
  158229. huffcode[p++] = code;
  158230. code++;
  158231. }
  158232. /* code is now 1 more than the last code used for codelength si; but
  158233. * it must still fit in si bits, since no code is allowed to be all ones.
  158234. */
  158235. if (((INT32) code) >= (((INT32) 1) << si))
  158236. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  158237. code <<= 1;
  158238. si++;
  158239. }
  158240. /* Figure C.3: generate encoding tables */
  158241. /* These are code and size indexed by symbol value */
  158242. /* Set all codeless symbols to have code length 0;
  158243. * this lets us detect duplicate VAL entries here, and later
  158244. * allows emit_bits to detect any attempt to emit such symbols.
  158245. */
  158246. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  158247. /* This is also a convenient place to check for out-of-range
  158248. * and duplicated VAL entries. We allow 0..255 for AC symbols
  158249. * but only 0..15 for DC. (We could constrain them further
  158250. * based on data depth and mode, but this seems enough.)
  158251. */
  158252. maxsymbol = isDC ? 15 : 255;
  158253. for (p = 0; p < lastp; p++) {
  158254. i = htbl->huffval[p];
  158255. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  158256. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  158257. dtbl->ehufco[i] = huffcode[p];
  158258. dtbl->ehufsi[i] = huffsize[p];
  158259. }
  158260. }
  158261. /* Outputting bytes to the file */
  158262. /* Emit a byte, taking 'action' if must suspend. */
  158263. #define emit_byte(state,val,action) \
  158264. { *(state)->next_output_byte++ = (JOCTET) (val); \
  158265. if (--(state)->free_in_buffer == 0) \
  158266. if (! dump_buffer(state)) \
  158267. { action; } }
  158268. LOCAL(boolean)
  158269. dump_buffer (working_state * state)
  158270. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  158271. {
  158272. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  158273. if (! (*dest->empty_output_buffer) (state->cinfo))
  158274. return FALSE;
  158275. /* After a successful buffer dump, must reset buffer pointers */
  158276. state->next_output_byte = dest->next_output_byte;
  158277. state->free_in_buffer = dest->free_in_buffer;
  158278. return TRUE;
  158279. }
  158280. /* Outputting bits to the file */
  158281. /* Only the right 24 bits of put_buffer are used; the valid bits are
  158282. * left-justified in this part. At most 16 bits can be passed to emit_bits
  158283. * in one call, and we never retain more than 7 bits in put_buffer
  158284. * between calls, so 24 bits are sufficient.
  158285. */
  158286. INLINE
  158287. LOCAL(boolean)
  158288. emit_bits (working_state * state, unsigned int code, int size)
  158289. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  158290. {
  158291. /* This routine is heavily used, so it's worth coding tightly. */
  158292. register INT32 put_buffer = (INT32) code;
  158293. register int put_bits = state->cur.put_bits;
  158294. /* if size is 0, caller used an invalid Huffman table entry */
  158295. if (size == 0)
  158296. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  158297. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  158298. put_bits += size; /* new number of bits in buffer */
  158299. put_buffer <<= 24 - put_bits; /* align incoming bits */
  158300. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  158301. while (put_bits >= 8) {
  158302. int c = (int) ((put_buffer >> 16) & 0xFF);
  158303. emit_byte(state, c, return FALSE);
  158304. if (c == 0xFF) { /* need to stuff a zero byte? */
  158305. emit_byte(state, 0, return FALSE);
  158306. }
  158307. put_buffer <<= 8;
  158308. put_bits -= 8;
  158309. }
  158310. state->cur.put_buffer = put_buffer; /* update state variables */
  158311. state->cur.put_bits = put_bits;
  158312. return TRUE;
  158313. }
  158314. LOCAL(boolean)
  158315. flush_bits (working_state * state)
  158316. {
  158317. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  158318. return FALSE;
  158319. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  158320. state->cur.put_bits = 0;
  158321. return TRUE;
  158322. }
  158323. /* Encode a single block's worth of coefficients */
  158324. LOCAL(boolean)
  158325. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  158326. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  158327. {
  158328. register int temp, temp2;
  158329. register int nbits;
  158330. register int k, r, i;
  158331. /* Encode the DC coefficient difference per section F.1.2.1 */
  158332. temp = temp2 = block[0] - last_dc_val;
  158333. if (temp < 0) {
  158334. temp = -temp; /* temp is abs value of input */
  158335. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  158336. /* This code assumes we are on a two's complement machine */
  158337. temp2--;
  158338. }
  158339. /* Find the number of bits needed for the magnitude of the coefficient */
  158340. nbits = 0;
  158341. while (temp) {
  158342. nbits++;
  158343. temp >>= 1;
  158344. }
  158345. /* Check for out-of-range coefficient values.
  158346. * Since we're encoding a difference, the range limit is twice as much.
  158347. */
  158348. if (nbits > MAX_COEF_BITS+1)
  158349. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  158350. /* Emit the Huffman-coded symbol for the number of bits */
  158351. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  158352. return FALSE;
  158353. /* Emit that number of bits of the value, if positive, */
  158354. /* or the complement of its magnitude, if negative. */
  158355. if (nbits) /* emit_bits rejects calls with size 0 */
  158356. if (! emit_bits(state, (unsigned int) temp2, nbits))
  158357. return FALSE;
  158358. /* Encode the AC coefficients per section F.1.2.2 */
  158359. r = 0; /* r = run length of zeros */
  158360. for (k = 1; k < DCTSIZE2; k++) {
  158361. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  158362. r++;
  158363. } else {
  158364. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  158365. while (r > 15) {
  158366. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  158367. return FALSE;
  158368. r -= 16;
  158369. }
  158370. temp2 = temp;
  158371. if (temp < 0) {
  158372. temp = -temp; /* temp is abs value of input */
  158373. /* This code assumes we are on a two's complement machine */
  158374. temp2--;
  158375. }
  158376. /* Find the number of bits needed for the magnitude of the coefficient */
  158377. nbits = 1; /* there must be at least one 1 bit */
  158378. while ((temp >>= 1))
  158379. nbits++;
  158380. /* Check for out-of-range coefficient values */
  158381. if (nbits > MAX_COEF_BITS)
  158382. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  158383. /* Emit Huffman symbol for run length / number of bits */
  158384. i = (r << 4) + nbits;
  158385. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  158386. return FALSE;
  158387. /* Emit that number of bits of the value, if positive, */
  158388. /* or the complement of its magnitude, if negative. */
  158389. if (! emit_bits(state, (unsigned int) temp2, nbits))
  158390. return FALSE;
  158391. r = 0;
  158392. }
  158393. }
  158394. /* If the last coef(s) were zero, emit an end-of-block code */
  158395. if (r > 0)
  158396. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  158397. return FALSE;
  158398. return TRUE;
  158399. }
  158400. /*
  158401. * Emit a restart marker & resynchronize predictions.
  158402. */
  158403. LOCAL(boolean)
  158404. emit_restart (working_state * state, int restart_num)
  158405. {
  158406. int ci;
  158407. if (! flush_bits(state))
  158408. return FALSE;
  158409. emit_byte(state, 0xFF, return FALSE);
  158410. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  158411. /* Re-initialize DC predictions to 0 */
  158412. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  158413. state->cur.last_dc_val[ci] = 0;
  158414. /* The restart counter is not updated until we successfully write the MCU. */
  158415. return TRUE;
  158416. }
  158417. /*
  158418. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  158419. */
  158420. METHODDEF(boolean)
  158421. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  158422. {
  158423. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  158424. working_state state;
  158425. int blkn, ci;
  158426. jpeg_component_info * compptr;
  158427. /* Load up working state */
  158428. state.next_output_byte = cinfo->dest->next_output_byte;
  158429. state.free_in_buffer = cinfo->dest->free_in_buffer;
  158430. ASSIGN_STATE(state.cur, entropy->saved);
  158431. state.cinfo = cinfo;
  158432. /* Emit restart marker if needed */
  158433. if (cinfo->restart_interval) {
  158434. if (entropy->restarts_to_go == 0)
  158435. if (! emit_restart(&state, entropy->next_restart_num))
  158436. return FALSE;
  158437. }
  158438. /* Encode the MCU data blocks */
  158439. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  158440. ci = cinfo->MCU_membership[blkn];
  158441. compptr = cinfo->cur_comp_info[ci];
  158442. if (! encode_one_block(&state,
  158443. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  158444. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  158445. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  158446. return FALSE;
  158447. /* Update last_dc_val */
  158448. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  158449. }
  158450. /* Completed MCU, so update state */
  158451. cinfo->dest->next_output_byte = state.next_output_byte;
  158452. cinfo->dest->free_in_buffer = state.free_in_buffer;
  158453. ASSIGN_STATE(entropy->saved, state.cur);
  158454. /* Update restart-interval state too */
  158455. if (cinfo->restart_interval) {
  158456. if (entropy->restarts_to_go == 0) {
  158457. entropy->restarts_to_go = cinfo->restart_interval;
  158458. entropy->next_restart_num++;
  158459. entropy->next_restart_num &= 7;
  158460. }
  158461. entropy->restarts_to_go--;
  158462. }
  158463. return TRUE;
  158464. }
  158465. /*
  158466. * Finish up at the end of a Huffman-compressed scan.
  158467. */
  158468. METHODDEF(void)
  158469. finish_pass_huff (j_compress_ptr cinfo)
  158470. {
  158471. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  158472. working_state state;
  158473. /* Load up working state ... flush_bits needs it */
  158474. state.next_output_byte = cinfo->dest->next_output_byte;
  158475. state.free_in_buffer = cinfo->dest->free_in_buffer;
  158476. ASSIGN_STATE(state.cur, entropy->saved);
  158477. state.cinfo = cinfo;
  158478. /* Flush out the last data */
  158479. if (! flush_bits(&state))
  158480. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  158481. /* Update state */
  158482. cinfo->dest->next_output_byte = state.next_output_byte;
  158483. cinfo->dest->free_in_buffer = state.free_in_buffer;
  158484. ASSIGN_STATE(entropy->saved, state.cur);
  158485. }
  158486. /*
  158487. * Huffman coding optimization.
  158488. *
  158489. * We first scan the supplied data and count the number of uses of each symbol
  158490. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  158491. * Then we build a Huffman coding tree for the observed counts.
  158492. * Symbols which are not needed at all for the particular image are not
  158493. * assigned any code, which saves space in the DHT marker as well as in
  158494. * the compressed data.
  158495. */
  158496. #ifdef ENTROPY_OPT_SUPPORTED
  158497. /* Process a single block's worth of coefficients */
  158498. LOCAL(void)
  158499. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  158500. long dc_counts[], long ac_counts[])
  158501. {
  158502. register int temp;
  158503. register int nbits;
  158504. register int k, r;
  158505. /* Encode the DC coefficient difference per section F.1.2.1 */
  158506. temp = block[0] - last_dc_val;
  158507. if (temp < 0)
  158508. temp = -temp;
  158509. /* Find the number of bits needed for the magnitude of the coefficient */
  158510. nbits = 0;
  158511. while (temp) {
  158512. nbits++;
  158513. temp >>= 1;
  158514. }
  158515. /* Check for out-of-range coefficient values.
  158516. * Since we're encoding a difference, the range limit is twice as much.
  158517. */
  158518. if (nbits > MAX_COEF_BITS+1)
  158519. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  158520. /* Count the Huffman symbol for the number of bits */
  158521. dc_counts[nbits]++;
  158522. /* Encode the AC coefficients per section F.1.2.2 */
  158523. r = 0; /* r = run length of zeros */
  158524. for (k = 1; k < DCTSIZE2; k++) {
  158525. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  158526. r++;
  158527. } else {
  158528. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  158529. while (r > 15) {
  158530. ac_counts[0xF0]++;
  158531. r -= 16;
  158532. }
  158533. /* Find the number of bits needed for the magnitude of the coefficient */
  158534. if (temp < 0)
  158535. temp = -temp;
  158536. /* Find the number of bits needed for the magnitude of the coefficient */
  158537. nbits = 1; /* there must be at least one 1 bit */
  158538. while ((temp >>= 1))
  158539. nbits++;
  158540. /* Check for out-of-range coefficient values */
  158541. if (nbits > MAX_COEF_BITS)
  158542. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  158543. /* Count Huffman symbol for run length / number of bits */
  158544. ac_counts[(r << 4) + nbits]++;
  158545. r = 0;
  158546. }
  158547. }
  158548. /* If the last coef(s) were zero, emit an end-of-block code */
  158549. if (r > 0)
  158550. ac_counts[0]++;
  158551. }
  158552. /*
  158553. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  158554. * No data is actually output, so no suspension return is possible.
  158555. */
  158556. METHODDEF(boolean)
  158557. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  158558. {
  158559. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  158560. int blkn, ci;
  158561. jpeg_component_info * compptr;
  158562. /* Take care of restart intervals if needed */
  158563. if (cinfo->restart_interval) {
  158564. if (entropy->restarts_to_go == 0) {
  158565. /* Re-initialize DC predictions to 0 */
  158566. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  158567. entropy->saved.last_dc_val[ci] = 0;
  158568. /* Update restart state */
  158569. entropy->restarts_to_go = cinfo->restart_interval;
  158570. }
  158571. entropy->restarts_to_go--;
  158572. }
  158573. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  158574. ci = cinfo->MCU_membership[blkn];
  158575. compptr = cinfo->cur_comp_info[ci];
  158576. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  158577. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  158578. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  158579. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  158580. }
  158581. return TRUE;
  158582. }
  158583. /*
  158584. * Generate the best Huffman code table for the given counts, fill htbl.
  158585. * Note this is also used by jcphuff.c.
  158586. *
  158587. * The JPEG standard requires that no symbol be assigned a codeword of all
  158588. * one bits (so that padding bits added at the end of a compressed segment
  158589. * can't look like a valid code). Because of the canonical ordering of
  158590. * codewords, this just means that there must be an unused slot in the
  158591. * longest codeword length category. Section K.2 of the JPEG spec suggests
  158592. * reserving such a slot by pretending that symbol 256 is a valid symbol
  158593. * with count 1. In theory that's not optimal; giving it count zero but
  158594. * including it in the symbol set anyway should give a better Huffman code.
  158595. * But the theoretically better code actually seems to come out worse in
  158596. * practice, because it produces more all-ones bytes (which incur stuffed
  158597. * zero bytes in the final file). In any case the difference is tiny.
  158598. *
  158599. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  158600. * If some symbols have a very small but nonzero probability, the Huffman tree
  158601. * must be adjusted to meet the code length restriction. We currently use
  158602. * the adjustment method suggested in JPEG section K.2. This method is *not*
  158603. * optimal; it may not choose the best possible limited-length code. But
  158604. * typically only very-low-frequency symbols will be given less-than-optimal
  158605. * lengths, so the code is almost optimal. Experimental comparisons against
  158606. * an optimal limited-length-code algorithm indicate that the difference is
  158607. * microscopic --- usually less than a hundredth of a percent of total size.
  158608. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  158609. */
  158610. GLOBAL(void)
  158611. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  158612. {
  158613. #define MAX_CLEN 32 /* assumed maximum initial code length */
  158614. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  158615. int codesize[257]; /* codesize[k] = code length of symbol k */
  158616. int others[257]; /* next symbol in current branch of tree */
  158617. int c1, c2;
  158618. int p, i, j;
  158619. long v;
  158620. /* This algorithm is explained in section K.2 of the JPEG standard */
  158621. MEMZERO(bits, SIZEOF(bits));
  158622. MEMZERO(codesize, SIZEOF(codesize));
  158623. for (i = 0; i < 257; i++)
  158624. others[i] = -1; /* init links to empty */
  158625. freq[256] = 1; /* make sure 256 has a nonzero count */
  158626. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  158627. * that no real symbol is given code-value of all ones, because 256
  158628. * will be placed last in the largest codeword category.
  158629. */
  158630. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  158631. for (;;) {
  158632. /* Find the smallest nonzero frequency, set c1 = its symbol */
  158633. /* In case of ties, take the larger symbol number */
  158634. c1 = -1;
  158635. v = 1000000000L;
  158636. for (i = 0; i <= 256; i++) {
  158637. if (freq[i] && freq[i] <= v) {
  158638. v = freq[i];
  158639. c1 = i;
  158640. }
  158641. }
  158642. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  158643. /* In case of ties, take the larger symbol number */
  158644. c2 = -1;
  158645. v = 1000000000L;
  158646. for (i = 0; i <= 256; i++) {
  158647. if (freq[i] && freq[i] <= v && i != c1) {
  158648. v = freq[i];
  158649. c2 = i;
  158650. }
  158651. }
  158652. /* Done if we've merged everything into one frequency */
  158653. if (c2 < 0)
  158654. break;
  158655. /* Else merge the two counts/trees */
  158656. freq[c1] += freq[c2];
  158657. freq[c2] = 0;
  158658. /* Increment the codesize of everything in c1's tree branch */
  158659. codesize[c1]++;
  158660. while (others[c1] >= 0) {
  158661. c1 = others[c1];
  158662. codesize[c1]++;
  158663. }
  158664. others[c1] = c2; /* chain c2 onto c1's tree branch */
  158665. /* Increment the codesize of everything in c2's tree branch */
  158666. codesize[c2]++;
  158667. while (others[c2] >= 0) {
  158668. c2 = others[c2];
  158669. codesize[c2]++;
  158670. }
  158671. }
  158672. /* Now count the number of symbols of each code length */
  158673. for (i = 0; i <= 256; i++) {
  158674. if (codesize[i]) {
  158675. /* The JPEG standard seems to think that this can't happen, */
  158676. /* but I'm paranoid... */
  158677. if (codesize[i] > MAX_CLEN)
  158678. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  158679. bits[codesize[i]]++;
  158680. }
  158681. }
  158682. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  158683. * Huffman procedure assigned any such lengths, we must adjust the coding.
  158684. * Here is what the JPEG spec says about how this next bit works:
  158685. * Since symbols are paired for the longest Huffman code, the symbols are
  158686. * removed from this length category two at a time. The prefix for the pair
  158687. * (which is one bit shorter) is allocated to one of the pair; then,
  158688. * skipping the BITS entry for that prefix length, a code word from the next
  158689. * shortest nonzero BITS entry is converted into a prefix for two code words
  158690. * one bit longer.
  158691. */
  158692. for (i = MAX_CLEN; i > 16; i--) {
  158693. while (bits[i] > 0) {
  158694. j = i - 2; /* find length of new prefix to be used */
  158695. while (bits[j] == 0)
  158696. j--;
  158697. bits[i] -= 2; /* remove two symbols */
  158698. bits[i-1]++; /* one goes in this length */
  158699. bits[j+1] += 2; /* two new symbols in this length */
  158700. bits[j]--; /* symbol of this length is now a prefix */
  158701. }
  158702. }
  158703. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  158704. while (bits[i] == 0) /* find largest codelength still in use */
  158705. i--;
  158706. bits[i]--;
  158707. /* Return final symbol counts (only for lengths 0..16) */
  158708. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  158709. /* Return a list of the symbols sorted by code length */
  158710. /* It's not real clear to me why we don't need to consider the codelength
  158711. * changes made above, but the JPEG spec seems to think this works.
  158712. */
  158713. p = 0;
  158714. for (i = 1; i <= MAX_CLEN; i++) {
  158715. for (j = 0; j <= 255; j++) {
  158716. if (codesize[j] == i) {
  158717. htbl->huffval[p] = (UINT8) j;
  158718. p++;
  158719. }
  158720. }
  158721. }
  158722. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  158723. htbl->sent_table = FALSE;
  158724. }
  158725. /*
  158726. * Finish up a statistics-gathering pass and create the new Huffman tables.
  158727. */
  158728. METHODDEF(void)
  158729. finish_pass_gather (j_compress_ptr cinfo)
  158730. {
  158731. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  158732. int ci, dctbl, actbl;
  158733. jpeg_component_info * compptr;
  158734. JHUFF_TBL **htblptr;
  158735. boolean did_dc[NUM_HUFF_TBLS];
  158736. boolean did_ac[NUM_HUFF_TBLS];
  158737. /* It's important not to apply jpeg_gen_optimal_table more than once
  158738. * per table, because it clobbers the input frequency counts!
  158739. */
  158740. MEMZERO(did_dc, SIZEOF(did_dc));
  158741. MEMZERO(did_ac, SIZEOF(did_ac));
  158742. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158743. compptr = cinfo->cur_comp_info[ci];
  158744. dctbl = compptr->dc_tbl_no;
  158745. actbl = compptr->ac_tbl_no;
  158746. if (! did_dc[dctbl]) {
  158747. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  158748. if (*htblptr == NULL)
  158749. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  158750. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  158751. did_dc[dctbl] = TRUE;
  158752. }
  158753. if (! did_ac[actbl]) {
  158754. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  158755. if (*htblptr == NULL)
  158756. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  158757. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  158758. did_ac[actbl] = TRUE;
  158759. }
  158760. }
  158761. }
  158762. #endif /* ENTROPY_OPT_SUPPORTED */
  158763. /*
  158764. * Module initialization routine for Huffman entropy encoding.
  158765. */
  158766. GLOBAL(void)
  158767. jinit_huff_encoder (j_compress_ptr cinfo)
  158768. {
  158769. huff_entropy_ptr entropy;
  158770. int i;
  158771. entropy = (huff_entropy_ptr)
  158772. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158773. SIZEOF(huff_entropy_encoder));
  158774. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  158775. entropy->pub.start_pass = start_pass_huff;
  158776. /* Mark tables unallocated */
  158777. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  158778. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  158779. #ifdef ENTROPY_OPT_SUPPORTED
  158780. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  158781. #endif
  158782. }
  158783. }
  158784. /********* End of inlined file: jchuff.c *********/
  158785. #undef emit_byte
  158786. /********* Start of inlined file: jcinit.c *********/
  158787. #define JPEG_INTERNALS
  158788. /*
  158789. * Master selection of compression modules.
  158790. * This is done once at the start of processing an image. We determine
  158791. * which modules will be used and give them appropriate initialization calls.
  158792. */
  158793. GLOBAL(void)
  158794. jinit_compress_master (j_compress_ptr cinfo)
  158795. {
  158796. /* Initialize master control (includes parameter checking/processing) */
  158797. jinit_c_master_control(cinfo, FALSE /* full compression */);
  158798. /* Preprocessing */
  158799. if (! cinfo->raw_data_in) {
  158800. jinit_color_converter(cinfo);
  158801. jinit_downsampler(cinfo);
  158802. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  158803. }
  158804. /* Forward DCT */
  158805. jinit_forward_dct(cinfo);
  158806. /* Entropy encoding: either Huffman or arithmetic coding. */
  158807. if (cinfo->arith_code) {
  158808. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  158809. } else {
  158810. if (cinfo->progressive_mode) {
  158811. #ifdef C_PROGRESSIVE_SUPPORTED
  158812. jinit_phuff_encoder(cinfo);
  158813. #else
  158814. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158815. #endif
  158816. } else
  158817. jinit_huff_encoder(cinfo);
  158818. }
  158819. /* Need a full-image coefficient buffer in any multi-pass mode. */
  158820. jinit_c_coef_controller(cinfo,
  158821. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  158822. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  158823. jinit_marker_writer(cinfo);
  158824. /* We can now tell the memory manager to allocate virtual arrays. */
  158825. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  158826. /* Write the datastream header (SOI) immediately.
  158827. * Frame and scan headers are postponed till later.
  158828. * This lets application insert special markers after the SOI.
  158829. */
  158830. (*cinfo->marker->write_file_header) (cinfo);
  158831. }
  158832. /********* End of inlined file: jcinit.c *********/
  158833. /********* Start of inlined file: jcmainct.c *********/
  158834. #define JPEG_INTERNALS
  158835. /* Note: currently, there is no operating mode in which a full-image buffer
  158836. * is needed at this step. If there were, that mode could not be used with
  158837. * "raw data" input, since this module is bypassed in that case. However,
  158838. * we've left the code here for possible use in special applications.
  158839. */
  158840. #undef FULL_MAIN_BUFFER_SUPPORTED
  158841. /* Private buffer controller object */
  158842. typedef struct {
  158843. struct jpeg_c_main_controller pub; /* public fields */
  158844. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  158845. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  158846. boolean suspended; /* remember if we suspended output */
  158847. J_BUF_MODE pass_mode; /* current operating mode */
  158848. /* If using just a strip buffer, this points to the entire set of buffers
  158849. * (we allocate one for each component). In the full-image case, this
  158850. * points to the currently accessible strips of the virtual arrays.
  158851. */
  158852. JSAMPARRAY buffer[MAX_COMPONENTS];
  158853. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158854. /* If using full-image storage, this array holds pointers to virtual-array
  158855. * control blocks for each component. Unused if not full-image storage.
  158856. */
  158857. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  158858. #endif
  158859. } my_main_controller;
  158860. typedef my_main_controller * my_main_ptr;
  158861. /* Forward declarations */
  158862. METHODDEF(void) process_data_simple_main
  158863. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  158864. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  158865. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158866. METHODDEF(void) process_data_buffer_main
  158867. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  158868. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  158869. #endif
  158870. /*
  158871. * Initialize for a processing pass.
  158872. */
  158873. METHODDEF(void)
  158874. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  158875. {
  158876. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  158877. /* Do nothing in raw-data mode. */
  158878. if (cinfo->raw_data_in)
  158879. return;
  158880. main_->cur_iMCU_row = 0; /* initialize counters */
  158881. main_->rowgroup_ctr = 0;
  158882. main_->suspended = FALSE;
  158883. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  158884. switch (pass_mode) {
  158885. case JBUF_PASS_THRU:
  158886. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158887. if (main_->whole_image[0] != NULL)
  158888. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158889. #endif
  158890. main_->pub.process_data = process_data_simple_main;
  158891. break;
  158892. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158893. case JBUF_SAVE_SOURCE:
  158894. case JBUF_CRANK_DEST:
  158895. case JBUF_SAVE_AND_PASS:
  158896. if (main_->whole_image[0] == NULL)
  158897. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158898. main_->pub.process_data = process_data_buffer_main;
  158899. break;
  158900. #endif
  158901. default:
  158902. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158903. break;
  158904. }
  158905. }
  158906. /*
  158907. * Process some data.
  158908. * This routine handles the simple pass-through mode,
  158909. * where we have only a strip buffer.
  158910. */
  158911. METHODDEF(void)
  158912. process_data_simple_main (j_compress_ptr cinfo,
  158913. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  158914. JDIMENSION in_rows_avail)
  158915. {
  158916. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  158917. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  158918. /* Read input data if we haven't filled the main buffer yet */
  158919. if (main_->rowgroup_ctr < DCTSIZE)
  158920. (*cinfo->prep->pre_process_data) (cinfo,
  158921. input_buf, in_row_ctr, in_rows_avail,
  158922. main_->buffer, &main_->rowgroup_ctr,
  158923. (JDIMENSION) DCTSIZE);
  158924. /* If we don't have a full iMCU row buffered, return to application for
  158925. * more data. Note that preprocessor will always pad to fill the iMCU row
  158926. * at the bottom of the image.
  158927. */
  158928. if (main_->rowgroup_ctr != DCTSIZE)
  158929. return;
  158930. /* Send the completed row to the compressor */
  158931. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  158932. /* If compressor did not consume the whole row, then we must need to
  158933. * suspend processing and return to the application. In this situation
  158934. * we pretend we didn't yet consume the last input row; otherwise, if
  158935. * it happened to be the last row of the image, the application would
  158936. * think we were done.
  158937. */
  158938. if (! main_->suspended) {
  158939. (*in_row_ctr)--;
  158940. main_->suspended = TRUE;
  158941. }
  158942. return;
  158943. }
  158944. /* We did finish the row. Undo our little suspension hack if a previous
  158945. * call suspended; then mark the main buffer empty.
  158946. */
  158947. if (main_->suspended) {
  158948. (*in_row_ctr)++;
  158949. main_->suspended = FALSE;
  158950. }
  158951. main_->rowgroup_ctr = 0;
  158952. main_->cur_iMCU_row++;
  158953. }
  158954. }
  158955. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158956. /*
  158957. * Process some data.
  158958. * This routine handles all of the modes that use a full-size buffer.
  158959. */
  158960. METHODDEF(void)
  158961. process_data_buffer_main (j_compress_ptr cinfo,
  158962. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  158963. JDIMENSION in_rows_avail)
  158964. {
  158965. my_main_ptr main = (my_main_ptr) cinfo->main;
  158966. int ci;
  158967. jpeg_component_info *compptr;
  158968. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  158969. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  158970. /* Realign the virtual buffers if at the start of an iMCU row. */
  158971. if (main->rowgroup_ctr == 0) {
  158972. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158973. ci++, compptr++) {
  158974. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  158975. ((j_common_ptr) cinfo, main->whole_image[ci],
  158976. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  158977. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  158978. }
  158979. /* In a read pass, pretend we just read some source data. */
  158980. if (! writing) {
  158981. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  158982. main->rowgroup_ctr = DCTSIZE;
  158983. }
  158984. }
  158985. /* If a write pass, read input data until the current iMCU row is full. */
  158986. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  158987. if (writing) {
  158988. (*cinfo->prep->pre_process_data) (cinfo,
  158989. input_buf, in_row_ctr, in_rows_avail,
  158990. main->buffer, &main->rowgroup_ctr,
  158991. (JDIMENSION) DCTSIZE);
  158992. /* Return to application if we need more data to fill the iMCU row. */
  158993. if (main->rowgroup_ctr < DCTSIZE)
  158994. return;
  158995. }
  158996. /* Emit data, unless this is a sink-only pass. */
  158997. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  158998. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  158999. /* If compressor did not consume the whole row, then we must need to
  159000. * suspend processing and return to the application. In this situation
  159001. * we pretend we didn't yet consume the last input row; otherwise, if
  159002. * it happened to be the last row of the image, the application would
  159003. * think we were done.
  159004. */
  159005. if (! main->suspended) {
  159006. (*in_row_ctr)--;
  159007. main->suspended = TRUE;
  159008. }
  159009. return;
  159010. }
  159011. /* We did finish the row. Undo our little suspension hack if a previous
  159012. * call suspended; then mark the main buffer empty.
  159013. */
  159014. if (main->suspended) {
  159015. (*in_row_ctr)++;
  159016. main->suspended = FALSE;
  159017. }
  159018. }
  159019. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  159020. main->rowgroup_ctr = 0;
  159021. main->cur_iMCU_row++;
  159022. }
  159023. }
  159024. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  159025. /*
  159026. * Initialize main buffer controller.
  159027. */
  159028. GLOBAL(void)
  159029. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  159030. {
  159031. my_main_ptr main_;
  159032. int ci;
  159033. jpeg_component_info *compptr;
  159034. main_ = (my_main_ptr)
  159035. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159036. SIZEOF(my_main_controller));
  159037. cinfo->main = (struct jpeg_c_main_controller *) main_;
  159038. main_->pub.start_pass = start_pass_main;
  159039. /* We don't need to create a buffer in raw-data mode. */
  159040. if (cinfo->raw_data_in)
  159041. return;
  159042. /* Create the buffer. It holds downsampled data, so each component
  159043. * may be of a different size.
  159044. */
  159045. if (need_full_buffer) {
  159046. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159047. /* Allocate a full-image virtual array for each component */
  159048. /* Note we pad the bottom to a multiple of the iMCU height */
  159049. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159050. ci++, compptr++) {
  159051. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  159052. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  159053. compptr->width_in_blocks * DCTSIZE,
  159054. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  159055. (long) compptr->v_samp_factor) * DCTSIZE,
  159056. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  159057. }
  159058. #else
  159059. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159060. #endif
  159061. } else {
  159062. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159063. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  159064. #endif
  159065. /* Allocate a strip buffer for each component */
  159066. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159067. ci++, compptr++) {
  159068. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  159069. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159070. compptr->width_in_blocks * DCTSIZE,
  159071. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  159072. }
  159073. }
  159074. }
  159075. /********* End of inlined file: jcmainct.c *********/
  159076. /********* Start of inlined file: jcmarker.c *********/
  159077. #define JPEG_INTERNALS
  159078. /* Private state */
  159079. typedef struct {
  159080. struct jpeg_marker_writer pub; /* public fields */
  159081. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  159082. } my_marker_writer;
  159083. typedef my_marker_writer * my_marker_ptr;
  159084. /*
  159085. * Basic output routines.
  159086. *
  159087. * Note that we do not support suspension while writing a marker.
  159088. * Therefore, an application using suspension must ensure that there is
  159089. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  159090. * calling jpeg_start_compress, and enough space to write the trailing EOI
  159091. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  159092. * modes are not supported at all with suspension, so those two are the only
  159093. * points where markers will be written.
  159094. */
  159095. LOCAL(void)
  159096. emit_byte (j_compress_ptr cinfo, int val)
  159097. /* Emit a byte */
  159098. {
  159099. struct jpeg_destination_mgr * dest = cinfo->dest;
  159100. *(dest->next_output_byte)++ = (JOCTET) val;
  159101. if (--dest->free_in_buffer == 0) {
  159102. if (! (*dest->empty_output_buffer) (cinfo))
  159103. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  159104. }
  159105. }
  159106. LOCAL(void)
  159107. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  159108. /* Emit a marker code */
  159109. {
  159110. emit_byte(cinfo, 0xFF);
  159111. emit_byte(cinfo, (int) mark);
  159112. }
  159113. LOCAL(void)
  159114. emit_2bytes (j_compress_ptr cinfo, int value)
  159115. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  159116. {
  159117. emit_byte(cinfo, (value >> 8) & 0xFF);
  159118. emit_byte(cinfo, value & 0xFF);
  159119. }
  159120. /*
  159121. * Routines to write specific marker types.
  159122. */
  159123. LOCAL(int)
  159124. emit_dqt (j_compress_ptr cinfo, int index)
  159125. /* Emit a DQT marker */
  159126. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  159127. {
  159128. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  159129. int prec;
  159130. int i;
  159131. if (qtbl == NULL)
  159132. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  159133. prec = 0;
  159134. for (i = 0; i < DCTSIZE2; i++) {
  159135. if (qtbl->quantval[i] > 255)
  159136. prec = 1;
  159137. }
  159138. if (! qtbl->sent_table) {
  159139. emit_marker(cinfo, M_DQT);
  159140. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  159141. emit_byte(cinfo, index + (prec<<4));
  159142. for (i = 0; i < DCTSIZE2; i++) {
  159143. /* The table entries must be emitted in zigzag order. */
  159144. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  159145. if (prec)
  159146. emit_byte(cinfo, (int) (qval >> 8));
  159147. emit_byte(cinfo, (int) (qval & 0xFF));
  159148. }
  159149. qtbl->sent_table = TRUE;
  159150. }
  159151. return prec;
  159152. }
  159153. LOCAL(void)
  159154. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  159155. /* Emit a DHT marker */
  159156. {
  159157. JHUFF_TBL * htbl;
  159158. int length, i;
  159159. if (is_ac) {
  159160. htbl = cinfo->ac_huff_tbl_ptrs[index];
  159161. index += 0x10; /* output index has AC bit set */
  159162. } else {
  159163. htbl = cinfo->dc_huff_tbl_ptrs[index];
  159164. }
  159165. if (htbl == NULL)
  159166. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  159167. if (! htbl->sent_table) {
  159168. emit_marker(cinfo, M_DHT);
  159169. length = 0;
  159170. for (i = 1; i <= 16; i++)
  159171. length += htbl->bits[i];
  159172. emit_2bytes(cinfo, length + 2 + 1 + 16);
  159173. emit_byte(cinfo, index);
  159174. for (i = 1; i <= 16; i++)
  159175. emit_byte(cinfo, htbl->bits[i]);
  159176. for (i = 0; i < length; i++)
  159177. emit_byte(cinfo, htbl->huffval[i]);
  159178. htbl->sent_table = TRUE;
  159179. }
  159180. }
  159181. LOCAL(void)
  159182. emit_dac (j_compress_ptr cinfo)
  159183. /* Emit a DAC marker */
  159184. /* Since the useful info is so small, we want to emit all the tables in */
  159185. /* one DAC marker. Therefore this routine does its own scan of the table. */
  159186. {
  159187. #ifdef C_ARITH_CODING_SUPPORTED
  159188. char dc_in_use[NUM_ARITH_TBLS];
  159189. char ac_in_use[NUM_ARITH_TBLS];
  159190. int length, i;
  159191. jpeg_component_info *compptr;
  159192. for (i = 0; i < NUM_ARITH_TBLS; i++)
  159193. dc_in_use[i] = ac_in_use[i] = 0;
  159194. for (i = 0; i < cinfo->comps_in_scan; i++) {
  159195. compptr = cinfo->cur_comp_info[i];
  159196. dc_in_use[compptr->dc_tbl_no] = 1;
  159197. ac_in_use[compptr->ac_tbl_no] = 1;
  159198. }
  159199. length = 0;
  159200. for (i = 0; i < NUM_ARITH_TBLS; i++)
  159201. length += dc_in_use[i] + ac_in_use[i];
  159202. emit_marker(cinfo, M_DAC);
  159203. emit_2bytes(cinfo, length*2 + 2);
  159204. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  159205. if (dc_in_use[i]) {
  159206. emit_byte(cinfo, i);
  159207. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  159208. }
  159209. if (ac_in_use[i]) {
  159210. emit_byte(cinfo, i + 0x10);
  159211. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  159212. }
  159213. }
  159214. #endif /* C_ARITH_CODING_SUPPORTED */
  159215. }
  159216. LOCAL(void)
  159217. emit_dri (j_compress_ptr cinfo)
  159218. /* Emit a DRI marker */
  159219. {
  159220. emit_marker(cinfo, M_DRI);
  159221. emit_2bytes(cinfo, 4); /* fixed length */
  159222. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  159223. }
  159224. LOCAL(void)
  159225. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  159226. /* Emit a SOF marker */
  159227. {
  159228. int ci;
  159229. jpeg_component_info *compptr;
  159230. emit_marker(cinfo, code);
  159231. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  159232. /* Make sure image isn't bigger than SOF field can handle */
  159233. if ((long) cinfo->image_height > 65535L ||
  159234. (long) cinfo->image_width > 65535L)
  159235. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  159236. emit_byte(cinfo, cinfo->data_precision);
  159237. emit_2bytes(cinfo, (int) cinfo->image_height);
  159238. emit_2bytes(cinfo, (int) cinfo->image_width);
  159239. emit_byte(cinfo, cinfo->num_components);
  159240. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159241. ci++, compptr++) {
  159242. emit_byte(cinfo, compptr->component_id);
  159243. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  159244. emit_byte(cinfo, compptr->quant_tbl_no);
  159245. }
  159246. }
  159247. LOCAL(void)
  159248. emit_sos (j_compress_ptr cinfo)
  159249. /* Emit a SOS marker */
  159250. {
  159251. int i, td, ta;
  159252. jpeg_component_info *compptr;
  159253. emit_marker(cinfo, M_SOS);
  159254. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  159255. emit_byte(cinfo, cinfo->comps_in_scan);
  159256. for (i = 0; i < cinfo->comps_in_scan; i++) {
  159257. compptr = cinfo->cur_comp_info[i];
  159258. emit_byte(cinfo, compptr->component_id);
  159259. td = compptr->dc_tbl_no;
  159260. ta = compptr->ac_tbl_no;
  159261. if (cinfo->progressive_mode) {
  159262. /* Progressive mode: only DC or only AC tables are used in one scan;
  159263. * furthermore, Huffman coding of DC refinement uses no table at all.
  159264. * We emit 0 for unused field(s); this is recommended by the P&M text
  159265. * but does not seem to be specified in the standard.
  159266. */
  159267. if (cinfo->Ss == 0) {
  159268. ta = 0; /* DC scan */
  159269. if (cinfo->Ah != 0 && !cinfo->arith_code)
  159270. td = 0; /* no DC table either */
  159271. } else {
  159272. td = 0; /* AC scan */
  159273. }
  159274. }
  159275. emit_byte(cinfo, (td << 4) + ta);
  159276. }
  159277. emit_byte(cinfo, cinfo->Ss);
  159278. emit_byte(cinfo, cinfo->Se);
  159279. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  159280. }
  159281. LOCAL(void)
  159282. emit_jfif_app0 (j_compress_ptr cinfo)
  159283. /* Emit a JFIF-compliant APP0 marker */
  159284. {
  159285. /*
  159286. * Length of APP0 block (2 bytes)
  159287. * Block ID (4 bytes - ASCII "JFIF")
  159288. * Zero byte (1 byte to terminate the ID string)
  159289. * Version Major, Minor (2 bytes - major first)
  159290. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  159291. * Xdpu (2 bytes - dots per unit horizontal)
  159292. * Ydpu (2 bytes - dots per unit vertical)
  159293. * Thumbnail X size (1 byte)
  159294. * Thumbnail Y size (1 byte)
  159295. */
  159296. emit_marker(cinfo, M_APP0);
  159297. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  159298. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  159299. emit_byte(cinfo, 0x46);
  159300. emit_byte(cinfo, 0x49);
  159301. emit_byte(cinfo, 0x46);
  159302. emit_byte(cinfo, 0);
  159303. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  159304. emit_byte(cinfo, cinfo->JFIF_minor_version);
  159305. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  159306. emit_2bytes(cinfo, (int) cinfo->X_density);
  159307. emit_2bytes(cinfo, (int) cinfo->Y_density);
  159308. emit_byte(cinfo, 0); /* No thumbnail image */
  159309. emit_byte(cinfo, 0);
  159310. }
  159311. LOCAL(void)
  159312. emit_adobe_app14 (j_compress_ptr cinfo)
  159313. /* Emit an Adobe APP14 marker */
  159314. {
  159315. /*
  159316. * Length of APP14 block (2 bytes)
  159317. * Block ID (5 bytes - ASCII "Adobe")
  159318. * Version Number (2 bytes - currently 100)
  159319. * Flags0 (2 bytes - currently 0)
  159320. * Flags1 (2 bytes - currently 0)
  159321. * Color transform (1 byte)
  159322. *
  159323. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  159324. * now in circulation seem to use Version = 100, so that's what we write.
  159325. *
  159326. * We write the color transform byte as 1 if the JPEG color space is
  159327. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  159328. * whether the encoder performed a transformation, which is pretty useless.
  159329. */
  159330. emit_marker(cinfo, M_APP14);
  159331. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  159332. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  159333. emit_byte(cinfo, 0x64);
  159334. emit_byte(cinfo, 0x6F);
  159335. emit_byte(cinfo, 0x62);
  159336. emit_byte(cinfo, 0x65);
  159337. emit_2bytes(cinfo, 100); /* Version */
  159338. emit_2bytes(cinfo, 0); /* Flags0 */
  159339. emit_2bytes(cinfo, 0); /* Flags1 */
  159340. switch (cinfo->jpeg_color_space) {
  159341. case JCS_YCbCr:
  159342. emit_byte(cinfo, 1); /* Color transform = 1 */
  159343. break;
  159344. case JCS_YCCK:
  159345. emit_byte(cinfo, 2); /* Color transform = 2 */
  159346. break;
  159347. default:
  159348. emit_byte(cinfo, 0); /* Color transform = 0 */
  159349. break;
  159350. }
  159351. }
  159352. /*
  159353. * These routines allow writing an arbitrary marker with parameters.
  159354. * The only intended use is to emit COM or APPn markers after calling
  159355. * write_file_header and before calling write_frame_header.
  159356. * Other uses are not guaranteed to produce desirable results.
  159357. * Counting the parameter bytes properly is the caller's responsibility.
  159358. */
  159359. METHODDEF(void)
  159360. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  159361. /* Emit an arbitrary marker header */
  159362. {
  159363. if (datalen > (unsigned int) 65533) /* safety check */
  159364. ERREXIT(cinfo, JERR_BAD_LENGTH);
  159365. emit_marker(cinfo, (JPEG_MARKER) marker);
  159366. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  159367. }
  159368. METHODDEF(void)
  159369. write_marker_byte (j_compress_ptr cinfo, int val)
  159370. /* Emit one byte of marker parameters following write_marker_header */
  159371. {
  159372. emit_byte(cinfo, val);
  159373. }
  159374. /*
  159375. * Write datastream header.
  159376. * This consists of an SOI and optional APPn markers.
  159377. * We recommend use of the JFIF marker, but not the Adobe marker,
  159378. * when using YCbCr or grayscale data. The JFIF marker should NOT
  159379. * be used for any other JPEG colorspace. The Adobe marker is helpful
  159380. * to distinguish RGB, CMYK, and YCCK colorspaces.
  159381. * Note that an application can write additional header markers after
  159382. * jpeg_start_compress returns.
  159383. */
  159384. METHODDEF(void)
  159385. write_file_header (j_compress_ptr cinfo)
  159386. {
  159387. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  159388. emit_marker(cinfo, M_SOI); /* first the SOI */
  159389. /* SOI is defined to reset restart interval to 0 */
  159390. marker->last_restart_interval = 0;
  159391. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  159392. emit_jfif_app0(cinfo);
  159393. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  159394. emit_adobe_app14(cinfo);
  159395. }
  159396. /*
  159397. * Write frame header.
  159398. * This consists of DQT and SOFn markers.
  159399. * Note that we do not emit the SOF until we have emitted the DQT(s).
  159400. * This avoids compatibility problems with incorrect implementations that
  159401. * try to error-check the quant table numbers as soon as they see the SOF.
  159402. */
  159403. METHODDEF(void)
  159404. write_frame_header (j_compress_ptr cinfo)
  159405. {
  159406. int ci, prec;
  159407. boolean is_baseline;
  159408. jpeg_component_info *compptr;
  159409. /* Emit DQT for each quantization table.
  159410. * Note that emit_dqt() suppresses any duplicate tables.
  159411. */
  159412. prec = 0;
  159413. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159414. ci++, compptr++) {
  159415. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  159416. }
  159417. /* now prec is nonzero iff there are any 16-bit quant tables. */
  159418. /* Check for a non-baseline specification.
  159419. * Note we assume that Huffman table numbers won't be changed later.
  159420. */
  159421. if (cinfo->arith_code || cinfo->progressive_mode ||
  159422. cinfo->data_precision != 8) {
  159423. is_baseline = FALSE;
  159424. } else {
  159425. is_baseline = TRUE;
  159426. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159427. ci++, compptr++) {
  159428. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  159429. is_baseline = FALSE;
  159430. }
  159431. if (prec && is_baseline) {
  159432. is_baseline = FALSE;
  159433. /* If it's baseline except for quantizer size, warn the user */
  159434. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  159435. }
  159436. }
  159437. /* Emit the proper SOF marker */
  159438. if (cinfo->arith_code) {
  159439. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  159440. } else {
  159441. if (cinfo->progressive_mode)
  159442. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  159443. else if (is_baseline)
  159444. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  159445. else
  159446. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  159447. }
  159448. }
  159449. /*
  159450. * Write scan header.
  159451. * This consists of DHT or DAC markers, optional DRI, and SOS.
  159452. * Compressed data will be written following the SOS.
  159453. */
  159454. METHODDEF(void)
  159455. write_scan_header (j_compress_ptr cinfo)
  159456. {
  159457. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  159458. int i;
  159459. jpeg_component_info *compptr;
  159460. if (cinfo->arith_code) {
  159461. /* Emit arith conditioning info. We may have some duplication
  159462. * if the file has multiple scans, but it's so small it's hardly
  159463. * worth worrying about.
  159464. */
  159465. emit_dac(cinfo);
  159466. } else {
  159467. /* Emit Huffman tables.
  159468. * Note that emit_dht() suppresses any duplicate tables.
  159469. */
  159470. for (i = 0; i < cinfo->comps_in_scan; i++) {
  159471. compptr = cinfo->cur_comp_info[i];
  159472. if (cinfo->progressive_mode) {
  159473. /* Progressive mode: only DC or only AC tables are used in one scan */
  159474. if (cinfo->Ss == 0) {
  159475. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  159476. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  159477. } else {
  159478. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  159479. }
  159480. } else {
  159481. /* Sequential mode: need both DC and AC tables */
  159482. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  159483. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  159484. }
  159485. }
  159486. }
  159487. /* Emit DRI if required --- note that DRI value could change for each scan.
  159488. * We avoid wasting space with unnecessary DRIs, however.
  159489. */
  159490. if (cinfo->restart_interval != marker->last_restart_interval) {
  159491. emit_dri(cinfo);
  159492. marker->last_restart_interval = cinfo->restart_interval;
  159493. }
  159494. emit_sos(cinfo);
  159495. }
  159496. /*
  159497. * Write datastream trailer.
  159498. */
  159499. METHODDEF(void)
  159500. write_file_trailer (j_compress_ptr cinfo)
  159501. {
  159502. emit_marker(cinfo, M_EOI);
  159503. }
  159504. /*
  159505. * Write an abbreviated table-specification datastream.
  159506. * This consists of SOI, DQT and DHT tables, and EOI.
  159507. * Any table that is defined and not marked sent_table = TRUE will be
  159508. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  159509. */
  159510. METHODDEF(void)
  159511. write_tables_only (j_compress_ptr cinfo)
  159512. {
  159513. int i;
  159514. emit_marker(cinfo, M_SOI);
  159515. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  159516. if (cinfo->quant_tbl_ptrs[i] != NULL)
  159517. (void) emit_dqt(cinfo, i);
  159518. }
  159519. if (! cinfo->arith_code) {
  159520. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  159521. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  159522. emit_dht(cinfo, i, FALSE);
  159523. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  159524. emit_dht(cinfo, i, TRUE);
  159525. }
  159526. }
  159527. emit_marker(cinfo, M_EOI);
  159528. }
  159529. /*
  159530. * Initialize the marker writer module.
  159531. */
  159532. GLOBAL(void)
  159533. jinit_marker_writer (j_compress_ptr cinfo)
  159534. {
  159535. my_marker_ptr marker;
  159536. /* Create the subobject */
  159537. marker = (my_marker_ptr)
  159538. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159539. SIZEOF(my_marker_writer));
  159540. cinfo->marker = (struct jpeg_marker_writer *) marker;
  159541. /* Initialize method pointers */
  159542. marker->pub.write_file_header = write_file_header;
  159543. marker->pub.write_frame_header = write_frame_header;
  159544. marker->pub.write_scan_header = write_scan_header;
  159545. marker->pub.write_file_trailer = write_file_trailer;
  159546. marker->pub.write_tables_only = write_tables_only;
  159547. marker->pub.write_marker_header = write_marker_header;
  159548. marker->pub.write_marker_byte = write_marker_byte;
  159549. /* Initialize private state */
  159550. marker->last_restart_interval = 0;
  159551. }
  159552. /********* End of inlined file: jcmarker.c *********/
  159553. /********* Start of inlined file: jcmaster.c *********/
  159554. #define JPEG_INTERNALS
  159555. /* Private state */
  159556. typedef enum {
  159557. main_pass, /* input data, also do first output step */
  159558. huff_opt_pass, /* Huffman code optimization pass */
  159559. output_pass /* data output pass */
  159560. } c_pass_type;
  159561. typedef struct {
  159562. struct jpeg_comp_master pub; /* public fields */
  159563. c_pass_type pass_type; /* the type of the current pass */
  159564. int pass_number; /* # of passes completed */
  159565. int total_passes; /* total # of passes needed */
  159566. int scan_number; /* current index in scan_info[] */
  159567. } my_comp_master;
  159568. typedef my_comp_master * my_master_ptr;
  159569. /*
  159570. * Support routines that do various essential calculations.
  159571. */
  159572. LOCAL(void)
  159573. initial_setup (j_compress_ptr cinfo)
  159574. /* Do computations that are needed before master selection phase */
  159575. {
  159576. int ci;
  159577. jpeg_component_info *compptr;
  159578. long samplesperrow;
  159579. JDIMENSION jd_samplesperrow;
  159580. /* Sanity check on image dimensions */
  159581. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  159582. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  159583. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  159584. /* Make sure image isn't bigger than I can handle */
  159585. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  159586. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  159587. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  159588. /* Width of an input scanline must be representable as JDIMENSION. */
  159589. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  159590. jd_samplesperrow = (JDIMENSION) samplesperrow;
  159591. if ((long) jd_samplesperrow != samplesperrow)
  159592. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  159593. /* For now, precision must match compiled-in value... */
  159594. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  159595. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  159596. /* Check that number of components won't exceed internal array sizes */
  159597. if (cinfo->num_components > MAX_COMPONENTS)
  159598. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  159599. MAX_COMPONENTS);
  159600. /* Compute maximum sampling factors; check factor validity */
  159601. cinfo->max_h_samp_factor = 1;
  159602. cinfo->max_v_samp_factor = 1;
  159603. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159604. ci++, compptr++) {
  159605. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  159606. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  159607. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  159608. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  159609. compptr->h_samp_factor);
  159610. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  159611. compptr->v_samp_factor);
  159612. }
  159613. /* Compute dimensions of components */
  159614. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159615. ci++, compptr++) {
  159616. /* Fill in the correct component_index value; don't rely on application */
  159617. compptr->component_index = ci;
  159618. /* For compression, we never do DCT scaling. */
  159619. compptr->DCT_scaled_size = DCTSIZE;
  159620. /* Size in DCT blocks */
  159621. compptr->width_in_blocks = (JDIMENSION)
  159622. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  159623. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  159624. compptr->height_in_blocks = (JDIMENSION)
  159625. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  159626. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  159627. /* Size in samples */
  159628. compptr->downsampled_width = (JDIMENSION)
  159629. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  159630. (long) cinfo->max_h_samp_factor);
  159631. compptr->downsampled_height = (JDIMENSION)
  159632. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  159633. (long) cinfo->max_v_samp_factor);
  159634. /* Mark component needed (this flag isn't actually used for compression) */
  159635. compptr->component_needed = TRUE;
  159636. }
  159637. /* Compute number of fully interleaved MCU rows (number of times that
  159638. * main controller will call coefficient controller).
  159639. */
  159640. cinfo->total_iMCU_rows = (JDIMENSION)
  159641. jdiv_round_up((long) cinfo->image_height,
  159642. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  159643. }
  159644. #ifdef C_MULTISCAN_FILES_SUPPORTED
  159645. LOCAL(void)
  159646. validate_script (j_compress_ptr cinfo)
  159647. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  159648. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  159649. */
  159650. {
  159651. const jpeg_scan_info * scanptr;
  159652. int scanno, ncomps, ci, coefi, thisi;
  159653. int Ss, Se, Ah, Al;
  159654. boolean component_sent[MAX_COMPONENTS];
  159655. #ifdef C_PROGRESSIVE_SUPPORTED
  159656. int * last_bitpos_ptr;
  159657. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  159658. /* -1 until that coefficient has been seen; then last Al for it */
  159659. #endif
  159660. if (cinfo->num_scans <= 0)
  159661. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  159662. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  159663. * for progressive JPEG, no scan can have this.
  159664. */
  159665. scanptr = cinfo->scan_info;
  159666. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  159667. #ifdef C_PROGRESSIVE_SUPPORTED
  159668. cinfo->progressive_mode = TRUE;
  159669. last_bitpos_ptr = & last_bitpos[0][0];
  159670. for (ci = 0; ci < cinfo->num_components; ci++)
  159671. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  159672. *last_bitpos_ptr++ = -1;
  159673. #else
  159674. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159675. #endif
  159676. } else {
  159677. cinfo->progressive_mode = FALSE;
  159678. for (ci = 0; ci < cinfo->num_components; ci++)
  159679. component_sent[ci] = FALSE;
  159680. }
  159681. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  159682. /* Validate component indexes */
  159683. ncomps = scanptr->comps_in_scan;
  159684. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  159685. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  159686. for (ci = 0; ci < ncomps; ci++) {
  159687. thisi = scanptr->component_index[ci];
  159688. if (thisi < 0 || thisi >= cinfo->num_components)
  159689. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  159690. /* Components must appear in SOF order within each scan */
  159691. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  159692. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  159693. }
  159694. /* Validate progression parameters */
  159695. Ss = scanptr->Ss;
  159696. Se = scanptr->Se;
  159697. Ah = scanptr->Ah;
  159698. Al = scanptr->Al;
  159699. if (cinfo->progressive_mode) {
  159700. #ifdef C_PROGRESSIVE_SUPPORTED
  159701. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  159702. * seems wrong: the upper bound ought to depend on data precision.
  159703. * Perhaps they really meant 0..N+1 for N-bit precision.
  159704. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  159705. * out-of-range reconstructed DC values during the first DC scan,
  159706. * which might cause problems for some decoders.
  159707. */
  159708. #if BITS_IN_JSAMPLE == 8
  159709. #define MAX_AH_AL 10
  159710. #else
  159711. #define MAX_AH_AL 13
  159712. #endif
  159713. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  159714. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  159715. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  159716. if (Ss == 0) {
  159717. if (Se != 0) /* DC and AC together not OK */
  159718. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  159719. } else {
  159720. if (ncomps != 1) /* AC scans must be for only one component */
  159721. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  159722. }
  159723. for (ci = 0; ci < ncomps; ci++) {
  159724. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  159725. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  159726. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  159727. for (coefi = Ss; coefi <= Se; coefi++) {
  159728. if (last_bitpos_ptr[coefi] < 0) {
  159729. /* first scan of this coefficient */
  159730. if (Ah != 0)
  159731. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  159732. } else {
  159733. /* not first scan */
  159734. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  159735. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  159736. }
  159737. last_bitpos_ptr[coefi] = Al;
  159738. }
  159739. }
  159740. #endif
  159741. } else {
  159742. /* For sequential JPEG, all progression parameters must be these: */
  159743. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  159744. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  159745. /* Make sure components are not sent twice */
  159746. for (ci = 0; ci < ncomps; ci++) {
  159747. thisi = scanptr->component_index[ci];
  159748. if (component_sent[thisi])
  159749. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  159750. component_sent[thisi] = TRUE;
  159751. }
  159752. }
  159753. }
  159754. /* Now verify that everything got sent. */
  159755. if (cinfo->progressive_mode) {
  159756. #ifdef C_PROGRESSIVE_SUPPORTED
  159757. /* For progressive mode, we only check that at least some DC data
  159758. * got sent for each component; the spec does not require that all bits
  159759. * of all coefficients be transmitted. Would it be wiser to enforce
  159760. * transmission of all coefficient bits??
  159761. */
  159762. for (ci = 0; ci < cinfo->num_components; ci++) {
  159763. if (last_bitpos[ci][0] < 0)
  159764. ERREXIT(cinfo, JERR_MISSING_DATA);
  159765. }
  159766. #endif
  159767. } else {
  159768. for (ci = 0; ci < cinfo->num_components; ci++) {
  159769. if (! component_sent[ci])
  159770. ERREXIT(cinfo, JERR_MISSING_DATA);
  159771. }
  159772. }
  159773. }
  159774. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  159775. LOCAL(void)
  159776. select_scan_parameters (j_compress_ptr cinfo)
  159777. /* Set up the scan parameters for the current scan */
  159778. {
  159779. int ci;
  159780. #ifdef C_MULTISCAN_FILES_SUPPORTED
  159781. if (cinfo->scan_info != NULL) {
  159782. /* Prepare for current scan --- the script is already validated */
  159783. my_master_ptr master = (my_master_ptr) cinfo->master;
  159784. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  159785. cinfo->comps_in_scan = scanptr->comps_in_scan;
  159786. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  159787. cinfo->cur_comp_info[ci] =
  159788. &cinfo->comp_info[scanptr->component_index[ci]];
  159789. }
  159790. cinfo->Ss = scanptr->Ss;
  159791. cinfo->Se = scanptr->Se;
  159792. cinfo->Ah = scanptr->Ah;
  159793. cinfo->Al = scanptr->Al;
  159794. }
  159795. else
  159796. #endif
  159797. {
  159798. /* Prepare for single sequential-JPEG scan containing all components */
  159799. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  159800. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  159801. MAX_COMPS_IN_SCAN);
  159802. cinfo->comps_in_scan = cinfo->num_components;
  159803. for (ci = 0; ci < cinfo->num_components; ci++) {
  159804. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  159805. }
  159806. cinfo->Ss = 0;
  159807. cinfo->Se = DCTSIZE2-1;
  159808. cinfo->Ah = 0;
  159809. cinfo->Al = 0;
  159810. }
  159811. }
  159812. LOCAL(void)
  159813. per_scan_setup (j_compress_ptr cinfo)
  159814. /* Do computations that are needed before processing a JPEG scan */
  159815. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  159816. {
  159817. int ci, mcublks, tmp;
  159818. jpeg_component_info *compptr;
  159819. if (cinfo->comps_in_scan == 1) {
  159820. /* Noninterleaved (single-component) scan */
  159821. compptr = cinfo->cur_comp_info[0];
  159822. /* Overall image size in MCUs */
  159823. cinfo->MCUs_per_row = compptr->width_in_blocks;
  159824. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  159825. /* For noninterleaved scan, always one block per MCU */
  159826. compptr->MCU_width = 1;
  159827. compptr->MCU_height = 1;
  159828. compptr->MCU_blocks = 1;
  159829. compptr->MCU_sample_width = DCTSIZE;
  159830. compptr->last_col_width = 1;
  159831. /* For noninterleaved scans, it is convenient to define last_row_height
  159832. * as the number of block rows present in the last iMCU row.
  159833. */
  159834. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  159835. if (tmp == 0) tmp = compptr->v_samp_factor;
  159836. compptr->last_row_height = tmp;
  159837. /* Prepare array describing MCU composition */
  159838. cinfo->blocks_in_MCU = 1;
  159839. cinfo->MCU_membership[0] = 0;
  159840. } else {
  159841. /* Interleaved (multi-component) scan */
  159842. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  159843. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  159844. MAX_COMPS_IN_SCAN);
  159845. /* Overall image size in MCUs */
  159846. cinfo->MCUs_per_row = (JDIMENSION)
  159847. jdiv_round_up((long) cinfo->image_width,
  159848. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  159849. cinfo->MCU_rows_in_scan = (JDIMENSION)
  159850. jdiv_round_up((long) cinfo->image_height,
  159851. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  159852. cinfo->blocks_in_MCU = 0;
  159853. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159854. compptr = cinfo->cur_comp_info[ci];
  159855. /* Sampling factors give # of blocks of component in each MCU */
  159856. compptr->MCU_width = compptr->h_samp_factor;
  159857. compptr->MCU_height = compptr->v_samp_factor;
  159858. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  159859. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  159860. /* Figure number of non-dummy blocks in last MCU column & row */
  159861. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  159862. if (tmp == 0) tmp = compptr->MCU_width;
  159863. compptr->last_col_width = tmp;
  159864. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  159865. if (tmp == 0) tmp = compptr->MCU_height;
  159866. compptr->last_row_height = tmp;
  159867. /* Prepare array describing MCU composition */
  159868. mcublks = compptr->MCU_blocks;
  159869. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  159870. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  159871. while (mcublks-- > 0) {
  159872. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  159873. }
  159874. }
  159875. }
  159876. /* Convert restart specified in rows to actual MCU count. */
  159877. /* Note that count must fit in 16 bits, so we provide limiting. */
  159878. if (cinfo->restart_in_rows > 0) {
  159879. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  159880. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  159881. }
  159882. }
  159883. /*
  159884. * Per-pass setup.
  159885. * This is called at the beginning of each pass. We determine which modules
  159886. * will be active during this pass and give them appropriate start_pass calls.
  159887. * We also set is_last_pass to indicate whether any more passes will be
  159888. * required.
  159889. */
  159890. METHODDEF(void)
  159891. prepare_for_pass (j_compress_ptr cinfo)
  159892. {
  159893. my_master_ptr master = (my_master_ptr) cinfo->master;
  159894. switch (master->pass_type) {
  159895. case main_pass:
  159896. /* Initial pass: will collect input data, and do either Huffman
  159897. * optimization or data output for the first scan.
  159898. */
  159899. select_scan_parameters(cinfo);
  159900. per_scan_setup(cinfo);
  159901. if (! cinfo->raw_data_in) {
  159902. (*cinfo->cconvert->start_pass) (cinfo);
  159903. (*cinfo->downsample->start_pass) (cinfo);
  159904. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  159905. }
  159906. (*cinfo->fdct->start_pass) (cinfo);
  159907. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  159908. (*cinfo->coef->start_pass) (cinfo,
  159909. (master->total_passes > 1 ?
  159910. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  159911. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  159912. if (cinfo->optimize_coding) {
  159913. /* No immediate data output; postpone writing frame/scan headers */
  159914. master->pub.call_pass_startup = FALSE;
  159915. } else {
  159916. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  159917. master->pub.call_pass_startup = TRUE;
  159918. }
  159919. break;
  159920. #ifdef ENTROPY_OPT_SUPPORTED
  159921. case huff_opt_pass:
  159922. /* Do Huffman optimization for a scan after the first one. */
  159923. select_scan_parameters(cinfo);
  159924. per_scan_setup(cinfo);
  159925. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  159926. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  159927. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  159928. master->pub.call_pass_startup = FALSE;
  159929. break;
  159930. }
  159931. /* Special case: Huffman DC refinement scans need no Huffman table
  159932. * and therefore we can skip the optimization pass for them.
  159933. */
  159934. master->pass_type = output_pass;
  159935. master->pass_number++;
  159936. /*FALLTHROUGH*/
  159937. #endif
  159938. case output_pass:
  159939. /* Do a data-output pass. */
  159940. /* We need not repeat per-scan setup if prior optimization pass did it. */
  159941. if (! cinfo->optimize_coding) {
  159942. select_scan_parameters(cinfo);
  159943. per_scan_setup(cinfo);
  159944. }
  159945. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  159946. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  159947. /* We emit frame/scan headers now */
  159948. if (master->scan_number == 0)
  159949. (*cinfo->marker->write_frame_header) (cinfo);
  159950. (*cinfo->marker->write_scan_header) (cinfo);
  159951. master->pub.call_pass_startup = FALSE;
  159952. break;
  159953. default:
  159954. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159955. }
  159956. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  159957. /* Set up progress monitor's pass info if present */
  159958. if (cinfo->progress != NULL) {
  159959. cinfo->progress->completed_passes = master->pass_number;
  159960. cinfo->progress->total_passes = master->total_passes;
  159961. }
  159962. }
  159963. /*
  159964. * Special start-of-pass hook.
  159965. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  159966. * In single-pass processing, we need this hook because we don't want to
  159967. * write frame/scan headers during jpeg_start_compress; we want to let the
  159968. * application write COM markers etc. between jpeg_start_compress and the
  159969. * jpeg_write_scanlines loop.
  159970. * In multi-pass processing, this routine is not used.
  159971. */
  159972. METHODDEF(void)
  159973. pass_startup (j_compress_ptr cinfo)
  159974. {
  159975. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  159976. (*cinfo->marker->write_frame_header) (cinfo);
  159977. (*cinfo->marker->write_scan_header) (cinfo);
  159978. }
  159979. /*
  159980. * Finish up at end of pass.
  159981. */
  159982. METHODDEF(void)
  159983. finish_pass_master (j_compress_ptr cinfo)
  159984. {
  159985. my_master_ptr master = (my_master_ptr) cinfo->master;
  159986. /* The entropy coder always needs an end-of-pass call,
  159987. * either to analyze statistics or to flush its output buffer.
  159988. */
  159989. (*cinfo->entropy->finish_pass) (cinfo);
  159990. /* Update state for next pass */
  159991. switch (master->pass_type) {
  159992. case main_pass:
  159993. /* next pass is either output of scan 0 (after optimization)
  159994. * or output of scan 1 (if no optimization).
  159995. */
  159996. master->pass_type = output_pass;
  159997. if (! cinfo->optimize_coding)
  159998. master->scan_number++;
  159999. break;
  160000. case huff_opt_pass:
  160001. /* next pass is always output of current scan */
  160002. master->pass_type = output_pass;
  160003. break;
  160004. case output_pass:
  160005. /* next pass is either optimization or output of next scan */
  160006. if (cinfo->optimize_coding)
  160007. master->pass_type = huff_opt_pass;
  160008. master->scan_number++;
  160009. break;
  160010. }
  160011. master->pass_number++;
  160012. }
  160013. /*
  160014. * Initialize master compression control.
  160015. */
  160016. GLOBAL(void)
  160017. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  160018. {
  160019. my_master_ptr master;
  160020. master = (my_master_ptr)
  160021. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160022. SIZEOF(my_comp_master));
  160023. cinfo->master = (struct jpeg_comp_master *) master;
  160024. master->pub.prepare_for_pass = prepare_for_pass;
  160025. master->pub.pass_startup = pass_startup;
  160026. master->pub.finish_pass = finish_pass_master;
  160027. master->pub.is_last_pass = FALSE;
  160028. /* Validate parameters, determine derived values */
  160029. initial_setup(cinfo);
  160030. if (cinfo->scan_info != NULL) {
  160031. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160032. validate_script(cinfo);
  160033. #else
  160034. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160035. #endif
  160036. } else {
  160037. cinfo->progressive_mode = FALSE;
  160038. cinfo->num_scans = 1;
  160039. }
  160040. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  160041. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  160042. /* Initialize my private state */
  160043. if (transcode_only) {
  160044. /* no main pass in transcoding */
  160045. if (cinfo->optimize_coding)
  160046. master->pass_type = huff_opt_pass;
  160047. else
  160048. master->pass_type = output_pass;
  160049. } else {
  160050. /* for normal compression, first pass is always this type: */
  160051. master->pass_type = main_pass;
  160052. }
  160053. master->scan_number = 0;
  160054. master->pass_number = 0;
  160055. if (cinfo->optimize_coding)
  160056. master->total_passes = cinfo->num_scans * 2;
  160057. else
  160058. master->total_passes = cinfo->num_scans;
  160059. }
  160060. /********* End of inlined file: jcmaster.c *********/
  160061. /********* Start of inlined file: jcomapi.c *********/
  160062. #define JPEG_INTERNALS
  160063. /*
  160064. * Abort processing of a JPEG compression or decompression operation,
  160065. * but don't destroy the object itself.
  160066. *
  160067. * For this, we merely clean up all the nonpermanent memory pools.
  160068. * Note that temp files (virtual arrays) are not allowed to belong to
  160069. * the permanent pool, so we will be able to close all temp files here.
  160070. * Closing a data source or destination, if necessary, is the application's
  160071. * responsibility.
  160072. */
  160073. GLOBAL(void)
  160074. jpeg_abort (j_common_ptr cinfo)
  160075. {
  160076. int pool;
  160077. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  160078. if (cinfo->mem == NULL)
  160079. return;
  160080. /* Releasing pools in reverse order might help avoid fragmentation
  160081. * with some (brain-damaged) malloc libraries.
  160082. */
  160083. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  160084. (*cinfo->mem->free_pool) (cinfo, pool);
  160085. }
  160086. /* Reset overall state for possible reuse of object */
  160087. if (cinfo->is_decompressor) {
  160088. cinfo->global_state = DSTATE_START;
  160089. /* Try to keep application from accessing now-deleted marker list.
  160090. * A bit kludgy to do it here, but this is the most central place.
  160091. */
  160092. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  160093. } else {
  160094. cinfo->global_state = CSTATE_START;
  160095. }
  160096. }
  160097. /*
  160098. * Destruction of a JPEG object.
  160099. *
  160100. * Everything gets deallocated except the master jpeg_compress_struct itself
  160101. * and the error manager struct. Both of these are supplied by the application
  160102. * and must be freed, if necessary, by the application. (Often they are on
  160103. * the stack and so don't need to be freed anyway.)
  160104. * Closing a data source or destination, if necessary, is the application's
  160105. * responsibility.
  160106. */
  160107. GLOBAL(void)
  160108. jpeg_destroy (j_common_ptr cinfo)
  160109. {
  160110. /* We need only tell the memory manager to release everything. */
  160111. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  160112. if (cinfo->mem != NULL)
  160113. (*cinfo->mem->self_destruct) (cinfo);
  160114. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  160115. cinfo->global_state = 0; /* mark it destroyed */
  160116. }
  160117. /*
  160118. * Convenience routines for allocating quantization and Huffman tables.
  160119. * (Would jutils.c be a more reasonable place to put these?)
  160120. */
  160121. GLOBAL(JQUANT_TBL *)
  160122. jpeg_alloc_quant_table (j_common_ptr cinfo)
  160123. {
  160124. JQUANT_TBL *tbl;
  160125. tbl = (JQUANT_TBL *)
  160126. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  160127. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  160128. return tbl;
  160129. }
  160130. GLOBAL(JHUFF_TBL *)
  160131. jpeg_alloc_huff_table (j_common_ptr cinfo)
  160132. {
  160133. JHUFF_TBL *tbl;
  160134. tbl = (JHUFF_TBL *)
  160135. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  160136. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  160137. return tbl;
  160138. }
  160139. /********* End of inlined file: jcomapi.c *********/
  160140. /********* Start of inlined file: jcparam.c *********/
  160141. #define JPEG_INTERNALS
  160142. /*
  160143. * Quantization table setup routines
  160144. */
  160145. GLOBAL(void)
  160146. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  160147. const unsigned int *basic_table,
  160148. int scale_factor, boolean force_baseline)
  160149. /* Define a quantization table equal to the basic_table times
  160150. * a scale factor (given as a percentage).
  160151. * If force_baseline is TRUE, the computed quantization table entries
  160152. * are limited to 1..255 for JPEG baseline compatibility.
  160153. */
  160154. {
  160155. JQUANT_TBL ** qtblptr;
  160156. int i;
  160157. long temp;
  160158. /* Safety check to ensure start_compress not called yet. */
  160159. if (cinfo->global_state != CSTATE_START)
  160160. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160161. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  160162. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  160163. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  160164. if (*qtblptr == NULL)
  160165. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  160166. for (i = 0; i < DCTSIZE2; i++) {
  160167. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  160168. /* limit the values to the valid range */
  160169. if (temp <= 0L) temp = 1L;
  160170. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  160171. if (force_baseline && temp > 255L)
  160172. temp = 255L; /* limit to baseline range if requested */
  160173. (*qtblptr)->quantval[i] = (UINT16) temp;
  160174. }
  160175. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  160176. (*qtblptr)->sent_table = FALSE;
  160177. }
  160178. GLOBAL(void)
  160179. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  160180. boolean force_baseline)
  160181. /* Set or change the 'quality' (quantization) setting, using default tables
  160182. * and a straight percentage-scaling quality scale. In most cases it's better
  160183. * to use jpeg_set_quality (below); this entry point is provided for
  160184. * applications that insist on a linear percentage scaling.
  160185. */
  160186. {
  160187. /* These are the sample quantization tables given in JPEG spec section K.1.
  160188. * The spec says that the values given produce "good" quality, and
  160189. * when divided by 2, "very good" quality.
  160190. */
  160191. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  160192. 16, 11, 10, 16, 24, 40, 51, 61,
  160193. 12, 12, 14, 19, 26, 58, 60, 55,
  160194. 14, 13, 16, 24, 40, 57, 69, 56,
  160195. 14, 17, 22, 29, 51, 87, 80, 62,
  160196. 18, 22, 37, 56, 68, 109, 103, 77,
  160197. 24, 35, 55, 64, 81, 104, 113, 92,
  160198. 49, 64, 78, 87, 103, 121, 120, 101,
  160199. 72, 92, 95, 98, 112, 100, 103, 99
  160200. };
  160201. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  160202. 17, 18, 24, 47, 99, 99, 99, 99,
  160203. 18, 21, 26, 66, 99, 99, 99, 99,
  160204. 24, 26, 56, 99, 99, 99, 99, 99,
  160205. 47, 66, 99, 99, 99, 99, 99, 99,
  160206. 99, 99, 99, 99, 99, 99, 99, 99,
  160207. 99, 99, 99, 99, 99, 99, 99, 99,
  160208. 99, 99, 99, 99, 99, 99, 99, 99,
  160209. 99, 99, 99, 99, 99, 99, 99, 99
  160210. };
  160211. /* Set up two quantization tables using the specified scaling */
  160212. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  160213. scale_factor, force_baseline);
  160214. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  160215. scale_factor, force_baseline);
  160216. }
  160217. GLOBAL(int)
  160218. jpeg_quality_scaling (int quality)
  160219. /* Convert a user-specified quality rating to a percentage scaling factor
  160220. * for an underlying quantization table, using our recommended scaling curve.
  160221. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  160222. */
  160223. {
  160224. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  160225. if (quality <= 0) quality = 1;
  160226. if (quality > 100) quality = 100;
  160227. /* The basic table is used as-is (scaling 100) for a quality of 50.
  160228. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  160229. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  160230. * to make all the table entries 1 (hence, minimum quantization loss).
  160231. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  160232. */
  160233. if (quality < 50)
  160234. quality = 5000 / quality;
  160235. else
  160236. quality = 200 - quality*2;
  160237. return quality;
  160238. }
  160239. GLOBAL(void)
  160240. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  160241. /* Set or change the 'quality' (quantization) setting, using default tables.
  160242. * This is the standard quality-adjusting entry point for typical user
  160243. * interfaces; only those who want detailed control over quantization tables
  160244. * would use the preceding three routines directly.
  160245. */
  160246. {
  160247. /* Convert user 0-100 rating to percentage scaling */
  160248. quality = jpeg_quality_scaling(quality);
  160249. /* Set up standard quality tables */
  160250. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  160251. }
  160252. /*
  160253. * Huffman table setup routines
  160254. */
  160255. LOCAL(void)
  160256. add_huff_table (j_compress_ptr cinfo,
  160257. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  160258. /* Define a Huffman table */
  160259. {
  160260. int nsymbols, len;
  160261. if (*htblptr == NULL)
  160262. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  160263. /* Copy the number-of-symbols-of-each-code-length counts */
  160264. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  160265. /* Validate the counts. We do this here mainly so we can copy the right
  160266. * number of symbols from the val[] array, without risking marching off
  160267. * the end of memory. jchuff.c will do a more thorough test later.
  160268. */
  160269. nsymbols = 0;
  160270. for (len = 1; len <= 16; len++)
  160271. nsymbols += bits[len];
  160272. if (nsymbols < 1 || nsymbols > 256)
  160273. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  160274. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  160275. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  160276. (*htblptr)->sent_table = FALSE;
  160277. }
  160278. LOCAL(void)
  160279. std_huff_tables (j_compress_ptr cinfo)
  160280. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  160281. /* IMPORTANT: these are only valid for 8-bit data precision! */
  160282. {
  160283. static const UINT8 bits_dc_luminance[17] =
  160284. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  160285. static const UINT8 val_dc_luminance[] =
  160286. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  160287. static const UINT8 bits_dc_chrominance[17] =
  160288. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  160289. static const UINT8 val_dc_chrominance[] =
  160290. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  160291. static const UINT8 bits_ac_luminance[17] =
  160292. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  160293. static const UINT8 val_ac_luminance[] =
  160294. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  160295. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  160296. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  160297. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  160298. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  160299. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  160300. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  160301. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  160302. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  160303. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  160304. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  160305. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  160306. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  160307. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  160308. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  160309. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  160310. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  160311. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  160312. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  160313. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  160314. 0xf9, 0xfa };
  160315. static const UINT8 bits_ac_chrominance[17] =
  160316. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  160317. static const UINT8 val_ac_chrominance[] =
  160318. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  160319. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  160320. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  160321. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  160322. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  160323. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  160324. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  160325. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  160326. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  160327. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  160328. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  160329. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  160330. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  160331. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  160332. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  160333. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  160334. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  160335. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  160336. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  160337. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  160338. 0xf9, 0xfa };
  160339. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  160340. bits_dc_luminance, val_dc_luminance);
  160341. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  160342. bits_ac_luminance, val_ac_luminance);
  160343. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  160344. bits_dc_chrominance, val_dc_chrominance);
  160345. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  160346. bits_ac_chrominance, val_ac_chrominance);
  160347. }
  160348. /*
  160349. * Default parameter setup for compression.
  160350. *
  160351. * Applications that don't choose to use this routine must do their
  160352. * own setup of all these parameters. Alternately, you can call this
  160353. * to establish defaults and then alter parameters selectively. This
  160354. * is the recommended approach since, if we add any new parameters,
  160355. * your code will still work (they'll be set to reasonable defaults).
  160356. */
  160357. GLOBAL(void)
  160358. jpeg_set_defaults (j_compress_ptr cinfo)
  160359. {
  160360. int i;
  160361. /* Safety check to ensure start_compress not called yet. */
  160362. if (cinfo->global_state != CSTATE_START)
  160363. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160364. /* Allocate comp_info array large enough for maximum component count.
  160365. * Array is made permanent in case application wants to compress
  160366. * multiple images at same param settings.
  160367. */
  160368. if (cinfo->comp_info == NULL)
  160369. cinfo->comp_info = (jpeg_component_info *)
  160370. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  160371. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  160372. /* Initialize everything not dependent on the color space */
  160373. cinfo->data_precision = BITS_IN_JSAMPLE;
  160374. /* Set up two quantization tables using default quality of 75 */
  160375. jpeg_set_quality(cinfo, 75, TRUE);
  160376. /* Set up two Huffman tables */
  160377. std_huff_tables(cinfo);
  160378. /* Initialize default arithmetic coding conditioning */
  160379. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  160380. cinfo->arith_dc_L[i] = 0;
  160381. cinfo->arith_dc_U[i] = 1;
  160382. cinfo->arith_ac_K[i] = 5;
  160383. }
  160384. /* Default is no multiple-scan output */
  160385. cinfo->scan_info = NULL;
  160386. cinfo->num_scans = 0;
  160387. /* Expect normal source image, not raw downsampled data */
  160388. cinfo->raw_data_in = FALSE;
  160389. /* Use Huffman coding, not arithmetic coding, by default */
  160390. cinfo->arith_code = FALSE;
  160391. /* By default, don't do extra passes to optimize entropy coding */
  160392. cinfo->optimize_coding = FALSE;
  160393. /* The standard Huffman tables are only valid for 8-bit data precision.
  160394. * If the precision is higher, force optimization on so that usable
  160395. * tables will be computed. This test can be removed if default tables
  160396. * are supplied that are valid for the desired precision.
  160397. */
  160398. if (cinfo->data_precision > 8)
  160399. cinfo->optimize_coding = TRUE;
  160400. /* By default, use the simpler non-cosited sampling alignment */
  160401. cinfo->CCIR601_sampling = FALSE;
  160402. /* No input smoothing */
  160403. cinfo->smoothing_factor = 0;
  160404. /* DCT algorithm preference */
  160405. cinfo->dct_method = JDCT_DEFAULT;
  160406. /* No restart markers */
  160407. cinfo->restart_interval = 0;
  160408. cinfo->restart_in_rows = 0;
  160409. /* Fill in default JFIF marker parameters. Note that whether the marker
  160410. * will actually be written is determined by jpeg_set_colorspace.
  160411. *
  160412. * By default, the library emits JFIF version code 1.01.
  160413. * An application that wants to emit JFIF 1.02 extension markers should set
  160414. * JFIF_minor_version to 2. We could probably get away with just defaulting
  160415. * to 1.02, but there may still be some decoders in use that will complain
  160416. * about that; saying 1.01 should minimize compatibility problems.
  160417. */
  160418. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  160419. cinfo->JFIF_minor_version = 1;
  160420. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  160421. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  160422. cinfo->Y_density = 1;
  160423. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  160424. jpeg_default_colorspace(cinfo);
  160425. }
  160426. /*
  160427. * Select an appropriate JPEG colorspace for in_color_space.
  160428. */
  160429. GLOBAL(void)
  160430. jpeg_default_colorspace (j_compress_ptr cinfo)
  160431. {
  160432. switch (cinfo->in_color_space) {
  160433. case JCS_GRAYSCALE:
  160434. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  160435. break;
  160436. case JCS_RGB:
  160437. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  160438. break;
  160439. case JCS_YCbCr:
  160440. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  160441. break;
  160442. case JCS_CMYK:
  160443. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  160444. break;
  160445. case JCS_YCCK:
  160446. jpeg_set_colorspace(cinfo, JCS_YCCK);
  160447. break;
  160448. case JCS_UNKNOWN:
  160449. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  160450. break;
  160451. default:
  160452. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  160453. }
  160454. }
  160455. /*
  160456. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  160457. */
  160458. GLOBAL(void)
  160459. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  160460. {
  160461. jpeg_component_info * compptr;
  160462. int ci;
  160463. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  160464. (compptr = &cinfo->comp_info[index], \
  160465. compptr->component_id = (id), \
  160466. compptr->h_samp_factor = (hsamp), \
  160467. compptr->v_samp_factor = (vsamp), \
  160468. compptr->quant_tbl_no = (quant), \
  160469. compptr->dc_tbl_no = (dctbl), \
  160470. compptr->ac_tbl_no = (actbl) )
  160471. /* Safety check to ensure start_compress not called yet. */
  160472. if (cinfo->global_state != CSTATE_START)
  160473. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160474. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  160475. * tables 1 for chrominance components.
  160476. */
  160477. cinfo->jpeg_color_space = colorspace;
  160478. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  160479. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  160480. switch (colorspace) {
  160481. case JCS_GRAYSCALE:
  160482. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  160483. cinfo->num_components = 1;
  160484. /* JFIF specifies component ID 1 */
  160485. SET_COMP(0, 1, 1,1, 0, 0,0);
  160486. break;
  160487. case JCS_RGB:
  160488. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  160489. cinfo->num_components = 3;
  160490. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  160491. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  160492. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  160493. break;
  160494. case JCS_YCbCr:
  160495. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  160496. cinfo->num_components = 3;
  160497. /* JFIF specifies component IDs 1,2,3 */
  160498. /* We default to 2x2 subsamples of chrominance */
  160499. SET_COMP(0, 1, 2,2, 0, 0,0);
  160500. SET_COMP(1, 2, 1,1, 1, 1,1);
  160501. SET_COMP(2, 3, 1,1, 1, 1,1);
  160502. break;
  160503. case JCS_CMYK:
  160504. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  160505. cinfo->num_components = 4;
  160506. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  160507. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  160508. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  160509. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  160510. break;
  160511. case JCS_YCCK:
  160512. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  160513. cinfo->num_components = 4;
  160514. SET_COMP(0, 1, 2,2, 0, 0,0);
  160515. SET_COMP(1, 2, 1,1, 1, 1,1);
  160516. SET_COMP(2, 3, 1,1, 1, 1,1);
  160517. SET_COMP(3, 4, 2,2, 0, 0,0);
  160518. break;
  160519. case JCS_UNKNOWN:
  160520. cinfo->num_components = cinfo->input_components;
  160521. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  160522. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  160523. MAX_COMPONENTS);
  160524. for (ci = 0; ci < cinfo->num_components; ci++) {
  160525. SET_COMP(ci, ci, 1,1, 0, 0,0);
  160526. }
  160527. break;
  160528. default:
  160529. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  160530. }
  160531. }
  160532. #ifdef C_PROGRESSIVE_SUPPORTED
  160533. LOCAL(jpeg_scan_info *)
  160534. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  160535. int Ss, int Se, int Ah, int Al)
  160536. /* Support routine: generate one scan for specified component */
  160537. {
  160538. scanptr->comps_in_scan = 1;
  160539. scanptr->component_index[0] = ci;
  160540. scanptr->Ss = Ss;
  160541. scanptr->Se = Se;
  160542. scanptr->Ah = Ah;
  160543. scanptr->Al = Al;
  160544. scanptr++;
  160545. return scanptr;
  160546. }
  160547. LOCAL(jpeg_scan_info *)
  160548. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  160549. int Ss, int Se, int Ah, int Al)
  160550. /* Support routine: generate one scan for each component */
  160551. {
  160552. int ci;
  160553. for (ci = 0; ci < ncomps; ci++) {
  160554. scanptr->comps_in_scan = 1;
  160555. scanptr->component_index[0] = ci;
  160556. scanptr->Ss = Ss;
  160557. scanptr->Se = Se;
  160558. scanptr->Ah = Ah;
  160559. scanptr->Al = Al;
  160560. scanptr++;
  160561. }
  160562. return scanptr;
  160563. }
  160564. LOCAL(jpeg_scan_info *)
  160565. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  160566. /* Support routine: generate interleaved DC scan if possible, else N scans */
  160567. {
  160568. int ci;
  160569. if (ncomps <= MAX_COMPS_IN_SCAN) {
  160570. /* Single interleaved DC scan */
  160571. scanptr->comps_in_scan = ncomps;
  160572. for (ci = 0; ci < ncomps; ci++)
  160573. scanptr->component_index[ci] = ci;
  160574. scanptr->Ss = scanptr->Se = 0;
  160575. scanptr->Ah = Ah;
  160576. scanptr->Al = Al;
  160577. scanptr++;
  160578. } else {
  160579. /* Noninterleaved DC scan for each component */
  160580. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  160581. }
  160582. return scanptr;
  160583. }
  160584. /*
  160585. * Create a recommended progressive-JPEG script.
  160586. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  160587. */
  160588. GLOBAL(void)
  160589. jpeg_simple_progression (j_compress_ptr cinfo)
  160590. {
  160591. int ncomps = cinfo->num_components;
  160592. int nscans;
  160593. jpeg_scan_info * scanptr;
  160594. /* Safety check to ensure start_compress not called yet. */
  160595. if (cinfo->global_state != CSTATE_START)
  160596. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160597. /* Figure space needed for script. Calculation must match code below! */
  160598. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  160599. /* Custom script for YCbCr color images. */
  160600. nscans = 10;
  160601. } else {
  160602. /* All-purpose script for other color spaces. */
  160603. if (ncomps > MAX_COMPS_IN_SCAN)
  160604. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  160605. else
  160606. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  160607. }
  160608. /* Allocate space for script.
  160609. * We need to put it in the permanent pool in case the application performs
  160610. * multiple compressions without changing the settings. To avoid a memory
  160611. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  160612. * object, we try to re-use previously allocated space, and we allocate
  160613. * enough space to handle YCbCr even if initially asked for grayscale.
  160614. */
  160615. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  160616. cinfo->script_space_size = MAX(nscans, 10);
  160617. cinfo->script_space = (jpeg_scan_info *)
  160618. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  160619. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  160620. }
  160621. scanptr = cinfo->script_space;
  160622. cinfo->scan_info = scanptr;
  160623. cinfo->num_scans = nscans;
  160624. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  160625. /* Custom script for YCbCr color images. */
  160626. /* Initial DC scan */
  160627. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  160628. /* Initial AC scan: get some luma data out in a hurry */
  160629. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  160630. /* Chroma data is too small to be worth expending many scans on */
  160631. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  160632. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  160633. /* Complete spectral selection for luma AC */
  160634. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  160635. /* Refine next bit of luma AC */
  160636. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  160637. /* Finish DC successive approximation */
  160638. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  160639. /* Finish AC successive approximation */
  160640. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  160641. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  160642. /* Luma bottom bit comes last since it's usually largest scan */
  160643. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  160644. } else {
  160645. /* All-purpose script for other color spaces. */
  160646. /* Successive approximation first pass */
  160647. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  160648. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  160649. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  160650. /* Successive approximation second pass */
  160651. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  160652. /* Successive approximation final pass */
  160653. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  160654. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  160655. }
  160656. }
  160657. #endif /* C_PROGRESSIVE_SUPPORTED */
  160658. /********* End of inlined file: jcparam.c *********/
  160659. /********* Start of inlined file: jcphuff.c *********/
  160660. #define JPEG_INTERNALS
  160661. #ifdef C_PROGRESSIVE_SUPPORTED
  160662. /* Expanded entropy encoder object for progressive Huffman encoding. */
  160663. typedef struct {
  160664. struct jpeg_entropy_encoder pub; /* public fields */
  160665. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  160666. boolean gather_statistics;
  160667. /* Bit-level coding status.
  160668. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  160669. */
  160670. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160671. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160672. INT32 put_buffer; /* current bit-accumulation buffer */
  160673. int put_bits; /* # of bits now in it */
  160674. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  160675. /* Coding status for DC components */
  160676. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  160677. /* Coding status for AC components */
  160678. int ac_tbl_no; /* the table number of the single component */
  160679. unsigned int EOBRUN; /* run length of EOBs */
  160680. unsigned int BE; /* # of buffered correction bits before MCU */
  160681. char * bit_buffer; /* buffer for correction bits (1 per char) */
  160682. /* packing correction bits tightly would save some space but cost time... */
  160683. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  160684. int next_restart_num; /* next restart number to write (0-7) */
  160685. /* Pointers to derived tables (these workspaces have image lifespan).
  160686. * Since any one scan codes only DC or only AC, we only need one set
  160687. * of tables, not one for DC and one for AC.
  160688. */
  160689. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  160690. /* Statistics tables for optimization; again, one set is enough */
  160691. long * count_ptrs[NUM_HUFF_TBLS];
  160692. } phuff_entropy_encoder;
  160693. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  160694. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  160695. * buffer can hold. Larger sizes may slightly improve compression, but
  160696. * 1000 is already well into the realm of overkill.
  160697. * The minimum safe size is 64 bits.
  160698. */
  160699. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  160700. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  160701. * We assume that int right shift is unsigned if INT32 right shift is,
  160702. * which should be safe.
  160703. */
  160704. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160705. #define ISHIFT_TEMPS int ishift_temp;
  160706. #define IRIGHT_SHIFT(x,shft) \
  160707. ((ishift_temp = (x)) < 0 ? \
  160708. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  160709. (ishift_temp >> (shft)))
  160710. #else
  160711. #define ISHIFT_TEMPS
  160712. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  160713. #endif
  160714. /* Forward declarations */
  160715. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  160716. JBLOCKROW *MCU_data));
  160717. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  160718. JBLOCKROW *MCU_data));
  160719. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  160720. JBLOCKROW *MCU_data));
  160721. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  160722. JBLOCKROW *MCU_data));
  160723. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  160724. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  160725. /*
  160726. * Initialize for a Huffman-compressed scan using progressive JPEG.
  160727. */
  160728. METHODDEF(void)
  160729. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  160730. {
  160731. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160732. boolean is_DC_band;
  160733. int ci, tbl;
  160734. jpeg_component_info * compptr;
  160735. entropy->cinfo = cinfo;
  160736. entropy->gather_statistics = gather_statistics;
  160737. is_DC_band = (cinfo->Ss == 0);
  160738. /* We assume jcmaster.c already validated the scan parameters. */
  160739. /* Select execution routines */
  160740. if (cinfo->Ah == 0) {
  160741. if (is_DC_band)
  160742. entropy->pub.encode_mcu = encode_mcu_DC_first;
  160743. else
  160744. entropy->pub.encode_mcu = encode_mcu_AC_first;
  160745. } else {
  160746. if (is_DC_band)
  160747. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  160748. else {
  160749. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  160750. /* AC refinement needs a correction bit buffer */
  160751. if (entropy->bit_buffer == NULL)
  160752. entropy->bit_buffer = (char *)
  160753. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160754. MAX_CORR_BITS * SIZEOF(char));
  160755. }
  160756. }
  160757. if (gather_statistics)
  160758. entropy->pub.finish_pass = finish_pass_gather_phuff;
  160759. else
  160760. entropy->pub.finish_pass = finish_pass_phuff;
  160761. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  160762. * for AC coefficients.
  160763. */
  160764. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160765. compptr = cinfo->cur_comp_info[ci];
  160766. /* Initialize DC predictions to 0 */
  160767. entropy->last_dc_val[ci] = 0;
  160768. /* Get table index */
  160769. if (is_DC_band) {
  160770. if (cinfo->Ah != 0) /* DC refinement needs no table */
  160771. continue;
  160772. tbl = compptr->dc_tbl_no;
  160773. } else {
  160774. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  160775. }
  160776. if (gather_statistics) {
  160777. /* Check for invalid table index */
  160778. /* (make_c_derived_tbl does this in the other path) */
  160779. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  160780. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  160781. /* Allocate and zero the statistics tables */
  160782. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  160783. if (entropy->count_ptrs[tbl] == NULL)
  160784. entropy->count_ptrs[tbl] = (long *)
  160785. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160786. 257 * SIZEOF(long));
  160787. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  160788. } else {
  160789. /* Compute derived values for Huffman table */
  160790. /* We may do this more than once for a table, but it's not expensive */
  160791. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  160792. & entropy->derived_tbls[tbl]);
  160793. }
  160794. }
  160795. /* Initialize AC stuff */
  160796. entropy->EOBRUN = 0;
  160797. entropy->BE = 0;
  160798. /* Initialize bit buffer to empty */
  160799. entropy->put_buffer = 0;
  160800. entropy->put_bits = 0;
  160801. /* Initialize restart stuff */
  160802. entropy->restarts_to_go = cinfo->restart_interval;
  160803. entropy->next_restart_num = 0;
  160804. }
  160805. /* Outputting bytes to the file.
  160806. * NB: these must be called only when actually outputting,
  160807. * that is, entropy->gather_statistics == FALSE.
  160808. */
  160809. /* Emit a byte */
  160810. #define emit_byte(entropy,val) \
  160811. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  160812. if (--(entropy)->free_in_buffer == 0) \
  160813. dump_buffer_p(entropy); }
  160814. LOCAL(void)
  160815. dump_buffer_p (phuff_entropy_ptr entropy)
  160816. /* Empty the output buffer; we do not support suspension in this module. */
  160817. {
  160818. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  160819. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  160820. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  160821. /* After a successful buffer dump, must reset buffer pointers */
  160822. entropy->next_output_byte = dest->next_output_byte;
  160823. entropy->free_in_buffer = dest->free_in_buffer;
  160824. }
  160825. /* Outputting bits to the file */
  160826. /* Only the right 24 bits of put_buffer are used; the valid bits are
  160827. * left-justified in this part. At most 16 bits can be passed to emit_bits
  160828. * in one call, and we never retain more than 7 bits in put_buffer
  160829. * between calls, so 24 bits are sufficient.
  160830. */
  160831. INLINE
  160832. LOCAL(void)
  160833. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  160834. /* Emit some bits, unless we are in gather mode */
  160835. {
  160836. /* This routine is heavily used, so it's worth coding tightly. */
  160837. register INT32 put_buffer = (INT32) code;
  160838. register int put_bits = entropy->put_bits;
  160839. /* if size is 0, caller used an invalid Huffman table entry */
  160840. if (size == 0)
  160841. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  160842. if (entropy->gather_statistics)
  160843. return; /* do nothing if we're only getting stats */
  160844. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  160845. put_bits += size; /* new number of bits in buffer */
  160846. put_buffer <<= 24 - put_bits; /* align incoming bits */
  160847. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  160848. while (put_bits >= 8) {
  160849. int c = (int) ((put_buffer >> 16) & 0xFF);
  160850. emit_byte(entropy, c);
  160851. if (c == 0xFF) { /* need to stuff a zero byte? */
  160852. emit_byte(entropy, 0);
  160853. }
  160854. put_buffer <<= 8;
  160855. put_bits -= 8;
  160856. }
  160857. entropy->put_buffer = put_buffer; /* update variables */
  160858. entropy->put_bits = put_bits;
  160859. }
  160860. LOCAL(void)
  160861. flush_bits_p (phuff_entropy_ptr entropy)
  160862. {
  160863. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  160864. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  160865. entropy->put_bits = 0;
  160866. }
  160867. /*
  160868. * Emit (or just count) a Huffman symbol.
  160869. */
  160870. INLINE
  160871. LOCAL(void)
  160872. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  160873. {
  160874. if (entropy->gather_statistics)
  160875. entropy->count_ptrs[tbl_no][symbol]++;
  160876. else {
  160877. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  160878. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  160879. }
  160880. }
  160881. /*
  160882. * Emit bits from a correction bit buffer.
  160883. */
  160884. LOCAL(void)
  160885. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  160886. unsigned int nbits)
  160887. {
  160888. if (entropy->gather_statistics)
  160889. return; /* no real work */
  160890. while (nbits > 0) {
  160891. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  160892. bufstart++;
  160893. nbits--;
  160894. }
  160895. }
  160896. /*
  160897. * Emit any pending EOBRUN symbol.
  160898. */
  160899. LOCAL(void)
  160900. emit_eobrun (phuff_entropy_ptr entropy)
  160901. {
  160902. register int temp, nbits;
  160903. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  160904. temp = entropy->EOBRUN;
  160905. nbits = 0;
  160906. while ((temp >>= 1))
  160907. nbits++;
  160908. /* safety check: shouldn't happen given limited correction-bit buffer */
  160909. if (nbits > 14)
  160910. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  160911. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  160912. if (nbits)
  160913. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  160914. entropy->EOBRUN = 0;
  160915. /* Emit any buffered correction bits */
  160916. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  160917. entropy->BE = 0;
  160918. }
  160919. }
  160920. /*
  160921. * Emit a restart marker & resynchronize predictions.
  160922. */
  160923. LOCAL(void)
  160924. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  160925. {
  160926. int ci;
  160927. emit_eobrun(entropy);
  160928. if (! entropy->gather_statistics) {
  160929. flush_bits_p(entropy);
  160930. emit_byte(entropy, 0xFF);
  160931. emit_byte(entropy, JPEG_RST0 + restart_num);
  160932. }
  160933. if (entropy->cinfo->Ss == 0) {
  160934. /* Re-initialize DC predictions to 0 */
  160935. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  160936. entropy->last_dc_val[ci] = 0;
  160937. } else {
  160938. /* Re-initialize all AC-related fields to 0 */
  160939. entropy->EOBRUN = 0;
  160940. entropy->BE = 0;
  160941. }
  160942. }
  160943. /*
  160944. * MCU encoding for DC initial scan (either spectral selection,
  160945. * or first pass of successive approximation).
  160946. */
  160947. METHODDEF(boolean)
  160948. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160949. {
  160950. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160951. register int temp, temp2;
  160952. register int nbits;
  160953. int blkn, ci;
  160954. int Al = cinfo->Al;
  160955. JBLOCKROW block;
  160956. jpeg_component_info * compptr;
  160957. ISHIFT_TEMPS
  160958. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160959. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160960. /* Emit restart marker if needed */
  160961. if (cinfo->restart_interval)
  160962. if (entropy->restarts_to_go == 0)
  160963. emit_restart_p(entropy, entropy->next_restart_num);
  160964. /* Encode the MCU data blocks */
  160965. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160966. block = MCU_data[blkn];
  160967. ci = cinfo->MCU_membership[blkn];
  160968. compptr = cinfo->cur_comp_info[ci];
  160969. /* Compute the DC value after the required point transform by Al.
  160970. * This is simply an arithmetic right shift.
  160971. */
  160972. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  160973. /* DC differences are figured on the point-transformed values. */
  160974. temp = temp2 - entropy->last_dc_val[ci];
  160975. entropy->last_dc_val[ci] = temp2;
  160976. /* Encode the DC coefficient difference per section G.1.2.1 */
  160977. temp2 = temp;
  160978. if (temp < 0) {
  160979. temp = -temp; /* temp is abs value of input */
  160980. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  160981. /* This code assumes we are on a two's complement machine */
  160982. temp2--;
  160983. }
  160984. /* Find the number of bits needed for the magnitude of the coefficient */
  160985. nbits = 0;
  160986. while (temp) {
  160987. nbits++;
  160988. temp >>= 1;
  160989. }
  160990. /* Check for out-of-range coefficient values.
  160991. * Since we're encoding a difference, the range limit is twice as much.
  160992. */
  160993. if (nbits > MAX_COEF_BITS+1)
  160994. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160995. /* Count/emit the Huffman-coded symbol for the number of bits */
  160996. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  160997. /* Emit that number of bits of the value, if positive, */
  160998. /* or the complement of its magnitude, if negative. */
  160999. if (nbits) /* emit_bits rejects calls with size 0 */
  161000. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  161001. }
  161002. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161003. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161004. /* Update restart-interval state too */
  161005. if (cinfo->restart_interval) {
  161006. if (entropy->restarts_to_go == 0) {
  161007. entropy->restarts_to_go = cinfo->restart_interval;
  161008. entropy->next_restart_num++;
  161009. entropy->next_restart_num &= 7;
  161010. }
  161011. entropy->restarts_to_go--;
  161012. }
  161013. return TRUE;
  161014. }
  161015. /*
  161016. * MCU encoding for AC initial scan (either spectral selection,
  161017. * or first pass of successive approximation).
  161018. */
  161019. METHODDEF(boolean)
  161020. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161021. {
  161022. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161023. register int temp, temp2;
  161024. register int nbits;
  161025. register int r, k;
  161026. int Se = cinfo->Se;
  161027. int Al = cinfo->Al;
  161028. JBLOCKROW block;
  161029. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161030. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161031. /* Emit restart marker if needed */
  161032. if (cinfo->restart_interval)
  161033. if (entropy->restarts_to_go == 0)
  161034. emit_restart_p(entropy, entropy->next_restart_num);
  161035. /* Encode the MCU data block */
  161036. block = MCU_data[0];
  161037. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  161038. r = 0; /* r = run length of zeros */
  161039. for (k = cinfo->Ss; k <= Se; k++) {
  161040. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  161041. r++;
  161042. continue;
  161043. }
  161044. /* We must apply the point transform by Al. For AC coefficients this
  161045. * is an integer division with rounding towards 0. To do this portably
  161046. * in C, we shift after obtaining the absolute value; so the code is
  161047. * interwoven with finding the abs value (temp) and output bits (temp2).
  161048. */
  161049. if (temp < 0) {
  161050. temp = -temp; /* temp is abs value of input */
  161051. temp >>= Al; /* apply the point transform */
  161052. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  161053. temp2 = ~temp;
  161054. } else {
  161055. temp >>= Al; /* apply the point transform */
  161056. temp2 = temp;
  161057. }
  161058. /* Watch out for case that nonzero coef is zero after point transform */
  161059. if (temp == 0) {
  161060. r++;
  161061. continue;
  161062. }
  161063. /* Emit any pending EOBRUN */
  161064. if (entropy->EOBRUN > 0)
  161065. emit_eobrun(entropy);
  161066. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  161067. while (r > 15) {
  161068. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  161069. r -= 16;
  161070. }
  161071. /* Find the number of bits needed for the magnitude of the coefficient */
  161072. nbits = 1; /* there must be at least one 1 bit */
  161073. while ((temp >>= 1))
  161074. nbits++;
  161075. /* Check for out-of-range coefficient values */
  161076. if (nbits > MAX_COEF_BITS)
  161077. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  161078. /* Count/emit Huffman symbol for run length / number of bits */
  161079. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  161080. /* Emit that number of bits of the value, if positive, */
  161081. /* or the complement of its magnitude, if negative. */
  161082. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  161083. r = 0; /* reset zero run length */
  161084. }
  161085. if (r > 0) { /* If there are trailing zeroes, */
  161086. entropy->EOBRUN++; /* count an EOB */
  161087. if (entropy->EOBRUN == 0x7FFF)
  161088. emit_eobrun(entropy); /* force it out to avoid overflow */
  161089. }
  161090. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161091. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161092. /* Update restart-interval state too */
  161093. if (cinfo->restart_interval) {
  161094. if (entropy->restarts_to_go == 0) {
  161095. entropy->restarts_to_go = cinfo->restart_interval;
  161096. entropy->next_restart_num++;
  161097. entropy->next_restart_num &= 7;
  161098. }
  161099. entropy->restarts_to_go--;
  161100. }
  161101. return TRUE;
  161102. }
  161103. /*
  161104. * MCU encoding for DC successive approximation refinement scan.
  161105. * Note: we assume such scans can be multi-component, although the spec
  161106. * is not very clear on the point.
  161107. */
  161108. METHODDEF(boolean)
  161109. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161110. {
  161111. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161112. register int temp;
  161113. int blkn;
  161114. int Al = cinfo->Al;
  161115. JBLOCKROW block;
  161116. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161117. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161118. /* Emit restart marker if needed */
  161119. if (cinfo->restart_interval)
  161120. if (entropy->restarts_to_go == 0)
  161121. emit_restart_p(entropy, entropy->next_restart_num);
  161122. /* Encode the MCU data blocks */
  161123. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  161124. block = MCU_data[blkn];
  161125. /* We simply emit the Al'th bit of the DC coefficient value. */
  161126. temp = (*block)[0];
  161127. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  161128. }
  161129. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161130. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161131. /* Update restart-interval state too */
  161132. if (cinfo->restart_interval) {
  161133. if (entropy->restarts_to_go == 0) {
  161134. entropy->restarts_to_go = cinfo->restart_interval;
  161135. entropy->next_restart_num++;
  161136. entropy->next_restart_num &= 7;
  161137. }
  161138. entropy->restarts_to_go--;
  161139. }
  161140. return TRUE;
  161141. }
  161142. /*
  161143. * MCU encoding for AC successive approximation refinement scan.
  161144. */
  161145. METHODDEF(boolean)
  161146. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161147. {
  161148. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161149. register int temp;
  161150. register int r, k;
  161151. int EOB;
  161152. char *BR_buffer;
  161153. unsigned int BR;
  161154. int Se = cinfo->Se;
  161155. int Al = cinfo->Al;
  161156. JBLOCKROW block;
  161157. int absvalues[DCTSIZE2];
  161158. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161159. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161160. /* Emit restart marker if needed */
  161161. if (cinfo->restart_interval)
  161162. if (entropy->restarts_to_go == 0)
  161163. emit_restart_p(entropy, entropy->next_restart_num);
  161164. /* Encode the MCU data block */
  161165. block = MCU_data[0];
  161166. /* It is convenient to make a pre-pass to determine the transformed
  161167. * coefficients' absolute values and the EOB position.
  161168. */
  161169. EOB = 0;
  161170. for (k = cinfo->Ss; k <= Se; k++) {
  161171. temp = (*block)[jpeg_natural_order[k]];
  161172. /* We must apply the point transform by Al. For AC coefficients this
  161173. * is an integer division with rounding towards 0. To do this portably
  161174. * in C, we shift after obtaining the absolute value.
  161175. */
  161176. if (temp < 0)
  161177. temp = -temp; /* temp is abs value of input */
  161178. temp >>= Al; /* apply the point transform */
  161179. absvalues[k] = temp; /* save abs value for main pass */
  161180. if (temp == 1)
  161181. EOB = k; /* EOB = index of last newly-nonzero coef */
  161182. }
  161183. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  161184. r = 0; /* r = run length of zeros */
  161185. BR = 0; /* BR = count of buffered bits added now */
  161186. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  161187. for (k = cinfo->Ss; k <= Se; k++) {
  161188. if ((temp = absvalues[k]) == 0) {
  161189. r++;
  161190. continue;
  161191. }
  161192. /* Emit any required ZRLs, but not if they can be folded into EOB */
  161193. while (r > 15 && k <= EOB) {
  161194. /* emit any pending EOBRUN and the BE correction bits */
  161195. emit_eobrun(entropy);
  161196. /* Emit ZRL */
  161197. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  161198. r -= 16;
  161199. /* Emit buffered correction bits that must be associated with ZRL */
  161200. emit_buffered_bits(entropy, BR_buffer, BR);
  161201. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  161202. BR = 0;
  161203. }
  161204. /* If the coef was previously nonzero, it only needs a correction bit.
  161205. * NOTE: a straight translation of the spec's figure G.7 would suggest
  161206. * that we also need to test r > 15. But if r > 15, we can only get here
  161207. * if k > EOB, which implies that this coefficient is not 1.
  161208. */
  161209. if (temp > 1) {
  161210. /* The correction bit is the next bit of the absolute value. */
  161211. BR_buffer[BR++] = (char) (temp & 1);
  161212. continue;
  161213. }
  161214. /* Emit any pending EOBRUN and the BE correction bits */
  161215. emit_eobrun(entropy);
  161216. /* Count/emit Huffman symbol for run length / number of bits */
  161217. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  161218. /* Emit output bit for newly-nonzero coef */
  161219. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  161220. emit_bits_p(entropy, (unsigned int) temp, 1);
  161221. /* Emit buffered correction bits that must be associated with this code */
  161222. emit_buffered_bits(entropy, BR_buffer, BR);
  161223. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  161224. BR = 0;
  161225. r = 0; /* reset zero run length */
  161226. }
  161227. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  161228. entropy->EOBRUN++; /* count an EOB */
  161229. entropy->BE += BR; /* concat my correction bits to older ones */
  161230. /* We force out the EOB if we risk either:
  161231. * 1. overflow of the EOB counter;
  161232. * 2. overflow of the correction bit buffer during the next MCU.
  161233. */
  161234. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  161235. emit_eobrun(entropy);
  161236. }
  161237. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161238. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161239. /* Update restart-interval state too */
  161240. if (cinfo->restart_interval) {
  161241. if (entropy->restarts_to_go == 0) {
  161242. entropy->restarts_to_go = cinfo->restart_interval;
  161243. entropy->next_restart_num++;
  161244. entropy->next_restart_num &= 7;
  161245. }
  161246. entropy->restarts_to_go--;
  161247. }
  161248. return TRUE;
  161249. }
  161250. /*
  161251. * Finish up at the end of a Huffman-compressed progressive scan.
  161252. */
  161253. METHODDEF(void)
  161254. finish_pass_phuff (j_compress_ptr cinfo)
  161255. {
  161256. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161257. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161258. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161259. /* Flush out any buffered data */
  161260. emit_eobrun(entropy);
  161261. flush_bits_p(entropy);
  161262. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161263. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161264. }
  161265. /*
  161266. * Finish up a statistics-gathering pass and create the new Huffman tables.
  161267. */
  161268. METHODDEF(void)
  161269. finish_pass_gather_phuff (j_compress_ptr cinfo)
  161270. {
  161271. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161272. boolean is_DC_band;
  161273. int ci, tbl;
  161274. jpeg_component_info * compptr;
  161275. JHUFF_TBL **htblptr;
  161276. boolean did[NUM_HUFF_TBLS];
  161277. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  161278. emit_eobrun(entropy);
  161279. is_DC_band = (cinfo->Ss == 0);
  161280. /* It's important not to apply jpeg_gen_optimal_table more than once
  161281. * per table, because it clobbers the input frequency counts!
  161282. */
  161283. MEMZERO(did, SIZEOF(did));
  161284. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161285. compptr = cinfo->cur_comp_info[ci];
  161286. if (is_DC_band) {
  161287. if (cinfo->Ah != 0) /* DC refinement needs no table */
  161288. continue;
  161289. tbl = compptr->dc_tbl_no;
  161290. } else {
  161291. tbl = compptr->ac_tbl_no;
  161292. }
  161293. if (! did[tbl]) {
  161294. if (is_DC_band)
  161295. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  161296. else
  161297. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  161298. if (*htblptr == NULL)
  161299. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  161300. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  161301. did[tbl] = TRUE;
  161302. }
  161303. }
  161304. }
  161305. /*
  161306. * Module initialization routine for progressive Huffman entropy encoding.
  161307. */
  161308. GLOBAL(void)
  161309. jinit_phuff_encoder (j_compress_ptr cinfo)
  161310. {
  161311. phuff_entropy_ptr entropy;
  161312. int i;
  161313. entropy = (phuff_entropy_ptr)
  161314. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161315. SIZEOF(phuff_entropy_encoder));
  161316. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  161317. entropy->pub.start_pass = start_pass_phuff;
  161318. /* Mark tables unallocated */
  161319. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161320. entropy->derived_tbls[i] = NULL;
  161321. entropy->count_ptrs[i] = NULL;
  161322. }
  161323. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  161324. }
  161325. #endif /* C_PROGRESSIVE_SUPPORTED */
  161326. /********* End of inlined file: jcphuff.c *********/
  161327. /********* Start of inlined file: jcprepct.c *********/
  161328. #define JPEG_INTERNALS
  161329. /* At present, jcsample.c can request context rows only for smoothing.
  161330. * In the future, we might also need context rows for CCIR601 sampling
  161331. * or other more-complex downsampling procedures. The code to support
  161332. * context rows should be compiled only if needed.
  161333. */
  161334. #ifdef INPUT_SMOOTHING_SUPPORTED
  161335. #define CONTEXT_ROWS_SUPPORTED
  161336. #endif
  161337. /*
  161338. * For the simple (no-context-row) case, we just need to buffer one
  161339. * row group's worth of pixels for the downsampling step. At the bottom of
  161340. * the image, we pad to a full row group by replicating the last pixel row.
  161341. * The downsampler's last output row is then replicated if needed to pad
  161342. * out to a full iMCU row.
  161343. *
  161344. * When providing context rows, we must buffer three row groups' worth of
  161345. * pixels. Three row groups are physically allocated, but the row pointer
  161346. * arrays are made five row groups high, with the extra pointers above and
  161347. * below "wrapping around" to point to the last and first real row groups.
  161348. * This allows the downsampler to access the proper context rows.
  161349. * At the top and bottom of the image, we create dummy context rows by
  161350. * copying the first or last real pixel row. This copying could be avoided
  161351. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  161352. * trouble on the compression side.
  161353. */
  161354. /* Private buffer controller object */
  161355. typedef struct {
  161356. struct jpeg_c_prep_controller pub; /* public fields */
  161357. /* Downsampling input buffer. This buffer holds color-converted data
  161358. * until we have enough to do a downsample step.
  161359. */
  161360. JSAMPARRAY color_buf[MAX_COMPONENTS];
  161361. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  161362. int next_buf_row; /* index of next row to store in color_buf */
  161363. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  161364. int this_row_group; /* starting row index of group to process */
  161365. int next_buf_stop; /* downsample when we reach this index */
  161366. #endif
  161367. } my_prep_controller;
  161368. typedef my_prep_controller * my_prep_ptr;
  161369. /*
  161370. * Initialize for a processing pass.
  161371. */
  161372. METHODDEF(void)
  161373. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161374. {
  161375. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  161376. if (pass_mode != JBUF_PASS_THRU)
  161377. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161378. /* Initialize total-height counter for detecting bottom of image */
  161379. prep->rows_to_go = cinfo->image_height;
  161380. /* Mark the conversion buffer empty */
  161381. prep->next_buf_row = 0;
  161382. #ifdef CONTEXT_ROWS_SUPPORTED
  161383. /* Preset additional state variables for context mode.
  161384. * These aren't used in non-context mode, so we needn't test which mode.
  161385. */
  161386. prep->this_row_group = 0;
  161387. /* Set next_buf_stop to stop after two row groups have been read in. */
  161388. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  161389. #endif
  161390. }
  161391. /*
  161392. * Expand an image vertically from height input_rows to height output_rows,
  161393. * by duplicating the bottom row.
  161394. */
  161395. LOCAL(void)
  161396. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  161397. int input_rows, int output_rows)
  161398. {
  161399. register int row;
  161400. for (row = input_rows; row < output_rows; row++) {
  161401. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  161402. 1, num_cols);
  161403. }
  161404. }
  161405. /*
  161406. * Process some data in the simple no-context case.
  161407. *
  161408. * Preprocessor output data is counted in "row groups". A row group
  161409. * is defined to be v_samp_factor sample rows of each component.
  161410. * Downsampling will produce this much data from each max_v_samp_factor
  161411. * input rows.
  161412. */
  161413. METHODDEF(void)
  161414. pre_process_data (j_compress_ptr cinfo,
  161415. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161416. JDIMENSION in_rows_avail,
  161417. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  161418. JDIMENSION out_row_groups_avail)
  161419. {
  161420. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  161421. int numrows, ci;
  161422. JDIMENSION inrows;
  161423. jpeg_component_info * compptr;
  161424. while (*in_row_ctr < in_rows_avail &&
  161425. *out_row_group_ctr < out_row_groups_avail) {
  161426. /* Do color conversion to fill the conversion buffer. */
  161427. inrows = in_rows_avail - *in_row_ctr;
  161428. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  161429. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  161430. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  161431. prep->color_buf,
  161432. (JDIMENSION) prep->next_buf_row,
  161433. numrows);
  161434. *in_row_ctr += numrows;
  161435. prep->next_buf_row += numrows;
  161436. prep->rows_to_go -= numrows;
  161437. /* If at bottom of image, pad to fill the conversion buffer. */
  161438. if (prep->rows_to_go == 0 &&
  161439. prep->next_buf_row < cinfo->max_v_samp_factor) {
  161440. for (ci = 0; ci < cinfo->num_components; ci++) {
  161441. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  161442. prep->next_buf_row, cinfo->max_v_samp_factor);
  161443. }
  161444. prep->next_buf_row = cinfo->max_v_samp_factor;
  161445. }
  161446. /* If we've filled the conversion buffer, empty it. */
  161447. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  161448. (*cinfo->downsample->downsample) (cinfo,
  161449. prep->color_buf, (JDIMENSION) 0,
  161450. output_buf, *out_row_group_ctr);
  161451. prep->next_buf_row = 0;
  161452. (*out_row_group_ctr)++;
  161453. }
  161454. /* If at bottom of image, pad the output to a full iMCU height.
  161455. * Note we assume the caller is providing a one-iMCU-height output buffer!
  161456. */
  161457. if (prep->rows_to_go == 0 &&
  161458. *out_row_group_ctr < out_row_groups_avail) {
  161459. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161460. ci++, compptr++) {
  161461. expand_bottom_edge(output_buf[ci],
  161462. compptr->width_in_blocks * DCTSIZE,
  161463. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  161464. (int) (out_row_groups_avail * compptr->v_samp_factor));
  161465. }
  161466. *out_row_group_ctr = out_row_groups_avail;
  161467. break; /* can exit outer loop without test */
  161468. }
  161469. }
  161470. }
  161471. #ifdef CONTEXT_ROWS_SUPPORTED
  161472. /*
  161473. * Process some data in the context case.
  161474. */
  161475. METHODDEF(void)
  161476. pre_process_context (j_compress_ptr cinfo,
  161477. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161478. JDIMENSION in_rows_avail,
  161479. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  161480. JDIMENSION out_row_groups_avail)
  161481. {
  161482. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  161483. int numrows, ci;
  161484. int buf_height = cinfo->max_v_samp_factor * 3;
  161485. JDIMENSION inrows;
  161486. while (*out_row_group_ctr < out_row_groups_avail) {
  161487. if (*in_row_ctr < in_rows_avail) {
  161488. /* Do color conversion to fill the conversion buffer. */
  161489. inrows = in_rows_avail - *in_row_ctr;
  161490. numrows = prep->next_buf_stop - prep->next_buf_row;
  161491. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  161492. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  161493. prep->color_buf,
  161494. (JDIMENSION) prep->next_buf_row,
  161495. numrows);
  161496. /* Pad at top of image, if first time through */
  161497. if (prep->rows_to_go == cinfo->image_height) {
  161498. for (ci = 0; ci < cinfo->num_components; ci++) {
  161499. int row;
  161500. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  161501. jcopy_sample_rows(prep->color_buf[ci], 0,
  161502. prep->color_buf[ci], -row,
  161503. 1, cinfo->image_width);
  161504. }
  161505. }
  161506. }
  161507. *in_row_ctr += numrows;
  161508. prep->next_buf_row += numrows;
  161509. prep->rows_to_go -= numrows;
  161510. } else {
  161511. /* Return for more data, unless we are at the bottom of the image. */
  161512. if (prep->rows_to_go != 0)
  161513. break;
  161514. /* When at bottom of image, pad to fill the conversion buffer. */
  161515. if (prep->next_buf_row < prep->next_buf_stop) {
  161516. for (ci = 0; ci < cinfo->num_components; ci++) {
  161517. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  161518. prep->next_buf_row, prep->next_buf_stop);
  161519. }
  161520. prep->next_buf_row = prep->next_buf_stop;
  161521. }
  161522. }
  161523. /* If we've gotten enough data, downsample a row group. */
  161524. if (prep->next_buf_row == prep->next_buf_stop) {
  161525. (*cinfo->downsample->downsample) (cinfo,
  161526. prep->color_buf,
  161527. (JDIMENSION) prep->this_row_group,
  161528. output_buf, *out_row_group_ctr);
  161529. (*out_row_group_ctr)++;
  161530. /* Advance pointers with wraparound as necessary. */
  161531. prep->this_row_group += cinfo->max_v_samp_factor;
  161532. if (prep->this_row_group >= buf_height)
  161533. prep->this_row_group = 0;
  161534. if (prep->next_buf_row >= buf_height)
  161535. prep->next_buf_row = 0;
  161536. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  161537. }
  161538. }
  161539. }
  161540. /*
  161541. * Create the wrapped-around downsampling input buffer needed for context mode.
  161542. */
  161543. LOCAL(void)
  161544. create_context_buffer (j_compress_ptr cinfo)
  161545. {
  161546. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  161547. int rgroup_height = cinfo->max_v_samp_factor;
  161548. int ci, i;
  161549. jpeg_component_info * compptr;
  161550. JSAMPARRAY true_buffer, fake_buffer;
  161551. /* Grab enough space for fake row pointers for all the components;
  161552. * we need five row groups' worth of pointers for each component.
  161553. */
  161554. fake_buffer = (JSAMPARRAY)
  161555. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161556. (cinfo->num_components * 5 * rgroup_height) *
  161557. SIZEOF(JSAMPROW));
  161558. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161559. ci++, compptr++) {
  161560. /* Allocate the actual buffer space (3 row groups) for this component.
  161561. * We make the buffer wide enough to allow the downsampler to edge-expand
  161562. * horizontally within the buffer, if it so chooses.
  161563. */
  161564. true_buffer = (*cinfo->mem->alloc_sarray)
  161565. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161566. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  161567. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  161568. (JDIMENSION) (3 * rgroup_height));
  161569. /* Copy true buffer row pointers into the middle of the fake row array */
  161570. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  161571. 3 * rgroup_height * SIZEOF(JSAMPROW));
  161572. /* Fill in the above and below wraparound pointers */
  161573. for (i = 0; i < rgroup_height; i++) {
  161574. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  161575. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  161576. }
  161577. prep->color_buf[ci] = fake_buffer + rgroup_height;
  161578. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  161579. }
  161580. }
  161581. #endif /* CONTEXT_ROWS_SUPPORTED */
  161582. /*
  161583. * Initialize preprocessing controller.
  161584. */
  161585. GLOBAL(void)
  161586. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161587. {
  161588. my_prep_ptr prep;
  161589. int ci;
  161590. jpeg_component_info * compptr;
  161591. if (need_full_buffer) /* safety check */
  161592. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161593. prep = (my_prep_ptr)
  161594. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161595. SIZEOF(my_prep_controller));
  161596. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  161597. prep->pub.start_pass = start_pass_prep;
  161598. /* Allocate the color conversion buffer.
  161599. * We make the buffer wide enough to allow the downsampler to edge-expand
  161600. * horizontally within the buffer, if it so chooses.
  161601. */
  161602. if (cinfo->downsample->need_context_rows) {
  161603. /* Set up to provide context rows */
  161604. #ifdef CONTEXT_ROWS_SUPPORTED
  161605. prep->pub.pre_process_data = pre_process_context;
  161606. create_context_buffer(cinfo);
  161607. #else
  161608. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161609. #endif
  161610. } else {
  161611. /* No context, just make it tall enough for one row group */
  161612. prep->pub.pre_process_data = pre_process_data;
  161613. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161614. ci++, compptr++) {
  161615. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  161616. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161617. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  161618. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  161619. (JDIMENSION) cinfo->max_v_samp_factor);
  161620. }
  161621. }
  161622. }
  161623. /********* End of inlined file: jcprepct.c *********/
  161624. /********* Start of inlined file: jcsample.c *********/
  161625. #define JPEG_INTERNALS
  161626. /* Pointer to routine to downsample a single component */
  161627. typedef JMETHOD(void, downsample1_ptr,
  161628. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161629. JSAMPARRAY input_data, JSAMPARRAY output_data));
  161630. /* Private subobject */
  161631. typedef struct {
  161632. struct jpeg_downsampler pub; /* public fields */
  161633. /* Downsampling method pointers, one per component */
  161634. downsample1_ptr methods[MAX_COMPONENTS];
  161635. } my_downsampler;
  161636. typedef my_downsampler * my_downsample_ptr;
  161637. /*
  161638. * Initialize for a downsampling pass.
  161639. */
  161640. METHODDEF(void)
  161641. start_pass_downsample (j_compress_ptr cinfo)
  161642. {
  161643. /* no work for now */
  161644. }
  161645. /*
  161646. * Expand a component horizontally from width input_cols to width output_cols,
  161647. * by duplicating the rightmost samples.
  161648. */
  161649. LOCAL(void)
  161650. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  161651. JDIMENSION input_cols, JDIMENSION output_cols)
  161652. {
  161653. register JSAMPROW ptr;
  161654. register JSAMPLE pixval;
  161655. register int count;
  161656. int row;
  161657. int numcols = (int) (output_cols - input_cols);
  161658. if (numcols > 0) {
  161659. for (row = 0; row < num_rows; row++) {
  161660. ptr = image_data[row] + input_cols;
  161661. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  161662. for (count = numcols; count > 0; count--)
  161663. *ptr++ = pixval;
  161664. }
  161665. }
  161666. }
  161667. /*
  161668. * Do downsampling for a whole row group (all components).
  161669. *
  161670. * In this version we simply downsample each component independently.
  161671. */
  161672. METHODDEF(void)
  161673. sep_downsample (j_compress_ptr cinfo,
  161674. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  161675. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  161676. {
  161677. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  161678. int ci;
  161679. jpeg_component_info * compptr;
  161680. JSAMPARRAY in_ptr, out_ptr;
  161681. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161682. ci++, compptr++) {
  161683. in_ptr = input_buf[ci] + in_row_index;
  161684. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  161685. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  161686. }
  161687. }
  161688. /*
  161689. * Downsample pixel values of a single component.
  161690. * One row group is processed per call.
  161691. * This version handles arbitrary integral sampling ratios, without smoothing.
  161692. * Note that this version is not actually used for customary sampling ratios.
  161693. */
  161694. METHODDEF(void)
  161695. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161696. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161697. {
  161698. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  161699. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  161700. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161701. JSAMPROW inptr, outptr;
  161702. INT32 outvalue;
  161703. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  161704. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  161705. numpix = h_expand * v_expand;
  161706. numpix2 = numpix/2;
  161707. /* Expand input data enough to let all the output samples be generated
  161708. * by the standard loop. Special-casing padded output would be more
  161709. * efficient.
  161710. */
  161711. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  161712. cinfo->image_width, output_cols * h_expand);
  161713. inrow = 0;
  161714. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161715. outptr = output_data[outrow];
  161716. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  161717. outcol++, outcol_h += h_expand) {
  161718. outvalue = 0;
  161719. for (v = 0; v < v_expand; v++) {
  161720. inptr = input_data[inrow+v] + outcol_h;
  161721. for (h = 0; h < h_expand; h++) {
  161722. outvalue += (INT32) GETJSAMPLE(*inptr++);
  161723. }
  161724. }
  161725. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  161726. }
  161727. inrow += v_expand;
  161728. }
  161729. }
  161730. /*
  161731. * Downsample pixel values of a single component.
  161732. * This version handles the special case of a full-size component,
  161733. * without smoothing.
  161734. */
  161735. METHODDEF(void)
  161736. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161737. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161738. {
  161739. /* Copy the data */
  161740. jcopy_sample_rows(input_data, 0, output_data, 0,
  161741. cinfo->max_v_samp_factor, cinfo->image_width);
  161742. /* Edge-expand */
  161743. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  161744. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  161745. }
  161746. /*
  161747. * Downsample pixel values of a single component.
  161748. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  161749. * without smoothing.
  161750. *
  161751. * A note about the "bias" calculations: when rounding fractional values to
  161752. * integer, we do not want to always round 0.5 up to the next integer.
  161753. * If we did that, we'd introduce a noticeable bias towards larger values.
  161754. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  161755. * alternate pixel locations (a simple ordered dither pattern).
  161756. */
  161757. METHODDEF(void)
  161758. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161759. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161760. {
  161761. int outrow;
  161762. JDIMENSION outcol;
  161763. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161764. register JSAMPROW inptr, outptr;
  161765. register int bias;
  161766. /* Expand input data enough to let all the output samples be generated
  161767. * by the standard loop. Special-casing padded output would be more
  161768. * efficient.
  161769. */
  161770. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  161771. cinfo->image_width, output_cols * 2);
  161772. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161773. outptr = output_data[outrow];
  161774. inptr = input_data[outrow];
  161775. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  161776. for (outcol = 0; outcol < output_cols; outcol++) {
  161777. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  161778. + bias) >> 1);
  161779. bias ^= 1; /* 0=>1, 1=>0 */
  161780. inptr += 2;
  161781. }
  161782. }
  161783. }
  161784. /*
  161785. * Downsample pixel values of a single component.
  161786. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  161787. * without smoothing.
  161788. */
  161789. METHODDEF(void)
  161790. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161791. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161792. {
  161793. int inrow, outrow;
  161794. JDIMENSION outcol;
  161795. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161796. register JSAMPROW inptr0, inptr1, outptr;
  161797. register int bias;
  161798. /* Expand input data enough to let all the output samples be generated
  161799. * by the standard loop. Special-casing padded output would be more
  161800. * efficient.
  161801. */
  161802. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  161803. cinfo->image_width, output_cols * 2);
  161804. inrow = 0;
  161805. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161806. outptr = output_data[outrow];
  161807. inptr0 = input_data[inrow];
  161808. inptr1 = input_data[inrow+1];
  161809. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  161810. for (outcol = 0; outcol < output_cols; outcol++) {
  161811. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161812. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  161813. + bias) >> 2);
  161814. bias ^= 3; /* 1=>2, 2=>1 */
  161815. inptr0 += 2; inptr1 += 2;
  161816. }
  161817. inrow += 2;
  161818. }
  161819. }
  161820. #ifdef INPUT_SMOOTHING_SUPPORTED
  161821. /*
  161822. * Downsample pixel values of a single component.
  161823. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  161824. * with smoothing. One row of context is required.
  161825. */
  161826. METHODDEF(void)
  161827. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161828. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161829. {
  161830. int inrow, outrow;
  161831. JDIMENSION colctr;
  161832. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161833. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  161834. INT32 membersum, neighsum, memberscale, neighscale;
  161835. /* Expand input data enough to let all the output samples be generated
  161836. * by the standard loop. Special-casing padded output would be more
  161837. * efficient.
  161838. */
  161839. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  161840. cinfo->image_width, output_cols * 2);
  161841. /* We don't bother to form the individual "smoothed" input pixel values;
  161842. * we can directly compute the output which is the average of the four
  161843. * smoothed values. Each of the four member pixels contributes a fraction
  161844. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  161845. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  161846. * output. The four corner-adjacent neighbor pixels contribute a fraction
  161847. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  161848. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  161849. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  161850. * factors are scaled by 2^16 = 65536.
  161851. * Also recall that SF = smoothing_factor / 1024.
  161852. */
  161853. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  161854. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  161855. inrow = 0;
  161856. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161857. outptr = output_data[outrow];
  161858. inptr0 = input_data[inrow];
  161859. inptr1 = input_data[inrow+1];
  161860. above_ptr = input_data[inrow-1];
  161861. below_ptr = input_data[inrow+2];
  161862. /* Special case for first column: pretend column -1 is same as column 0 */
  161863. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161864. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  161865. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  161866. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  161867. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  161868. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  161869. neighsum += neighsum;
  161870. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  161871. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  161872. membersum = membersum * memberscale + neighsum * neighscale;
  161873. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161874. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  161875. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  161876. /* sum of pixels directly mapped to this output element */
  161877. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161878. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  161879. /* sum of edge-neighbor pixels */
  161880. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  161881. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  161882. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  161883. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  161884. /* The edge-neighbors count twice as much as corner-neighbors */
  161885. neighsum += neighsum;
  161886. /* Add in the corner-neighbors */
  161887. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  161888. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  161889. /* form final output scaled up by 2^16 */
  161890. membersum = membersum * memberscale + neighsum * neighscale;
  161891. /* round, descale and output it */
  161892. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161893. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  161894. }
  161895. /* Special case for last column */
  161896. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161897. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  161898. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  161899. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  161900. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  161901. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  161902. neighsum += neighsum;
  161903. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  161904. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  161905. membersum = membersum * memberscale + neighsum * neighscale;
  161906. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  161907. inrow += 2;
  161908. }
  161909. }
  161910. /*
  161911. * Downsample pixel values of a single component.
  161912. * This version handles the special case of a full-size component,
  161913. * with smoothing. One row of context is required.
  161914. */
  161915. METHODDEF(void)
  161916. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  161917. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161918. {
  161919. int outrow;
  161920. JDIMENSION colctr;
  161921. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161922. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  161923. INT32 membersum, neighsum, memberscale, neighscale;
  161924. int colsum, lastcolsum, nextcolsum;
  161925. /* Expand input data enough to let all the output samples be generated
  161926. * by the standard loop. Special-casing padded output would be more
  161927. * efficient.
  161928. */
  161929. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  161930. cinfo->image_width, output_cols);
  161931. /* Each of the eight neighbor pixels contributes a fraction SF to the
  161932. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  161933. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  161934. * Also recall that SF = smoothing_factor / 1024.
  161935. */
  161936. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  161937. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  161938. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161939. outptr = output_data[outrow];
  161940. inptr = input_data[outrow];
  161941. above_ptr = input_data[outrow-1];
  161942. below_ptr = input_data[outrow+1];
  161943. /* Special case for first column */
  161944. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  161945. GETJSAMPLE(*inptr);
  161946. membersum = GETJSAMPLE(*inptr++);
  161947. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  161948. GETJSAMPLE(*inptr);
  161949. neighsum = colsum + (colsum - membersum) + nextcolsum;
  161950. membersum = membersum * memberscale + neighsum * neighscale;
  161951. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161952. lastcolsum = colsum; colsum = nextcolsum;
  161953. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  161954. membersum = GETJSAMPLE(*inptr++);
  161955. above_ptr++; below_ptr++;
  161956. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  161957. GETJSAMPLE(*inptr);
  161958. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  161959. membersum = membersum * memberscale + neighsum * neighscale;
  161960. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161961. lastcolsum = colsum; colsum = nextcolsum;
  161962. }
  161963. /* Special case for last column */
  161964. membersum = GETJSAMPLE(*inptr);
  161965. neighsum = lastcolsum + (colsum - membersum) + colsum;
  161966. membersum = membersum * memberscale + neighsum * neighscale;
  161967. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  161968. }
  161969. }
  161970. #endif /* INPUT_SMOOTHING_SUPPORTED */
  161971. /*
  161972. * Module initialization routine for downsampling.
  161973. * Note that we must select a routine for each component.
  161974. */
  161975. GLOBAL(void)
  161976. jinit_downsampler (j_compress_ptr cinfo)
  161977. {
  161978. my_downsample_ptr downsample;
  161979. int ci;
  161980. jpeg_component_info * compptr;
  161981. boolean smoothok = TRUE;
  161982. downsample = (my_downsample_ptr)
  161983. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161984. SIZEOF(my_downsampler));
  161985. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  161986. downsample->pub.start_pass = start_pass_downsample;
  161987. downsample->pub.downsample = sep_downsample;
  161988. downsample->pub.need_context_rows = FALSE;
  161989. if (cinfo->CCIR601_sampling)
  161990. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  161991. /* Verify we can handle the sampling factors, and set up method pointers */
  161992. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161993. ci++, compptr++) {
  161994. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  161995. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  161996. #ifdef INPUT_SMOOTHING_SUPPORTED
  161997. if (cinfo->smoothing_factor) {
  161998. downsample->methods[ci] = fullsize_smooth_downsample;
  161999. downsample->pub.need_context_rows = TRUE;
  162000. } else
  162001. #endif
  162002. downsample->methods[ci] = fullsize_downsample;
  162003. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  162004. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  162005. smoothok = FALSE;
  162006. downsample->methods[ci] = h2v1_downsample;
  162007. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  162008. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  162009. #ifdef INPUT_SMOOTHING_SUPPORTED
  162010. if (cinfo->smoothing_factor) {
  162011. downsample->methods[ci] = h2v2_smooth_downsample;
  162012. downsample->pub.need_context_rows = TRUE;
  162013. } else
  162014. #endif
  162015. downsample->methods[ci] = h2v2_downsample;
  162016. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  162017. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  162018. smoothok = FALSE;
  162019. downsample->methods[ci] = int_downsample;
  162020. } else
  162021. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  162022. }
  162023. #ifdef INPUT_SMOOTHING_SUPPORTED
  162024. if (cinfo->smoothing_factor && !smoothok)
  162025. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  162026. #endif
  162027. }
  162028. /********* End of inlined file: jcsample.c *********/
  162029. /********* Start of inlined file: jctrans.c *********/
  162030. #define JPEG_INTERNALS
  162031. /* Forward declarations */
  162032. LOCAL(void) transencode_master_selection
  162033. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  162034. LOCAL(void) transencode_coef_controller
  162035. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  162036. /*
  162037. * Compression initialization for writing raw-coefficient data.
  162038. * Before calling this, all parameters and a data destination must be set up.
  162039. * Call jpeg_finish_compress() to actually write the data.
  162040. *
  162041. * The number of passed virtual arrays must match cinfo->num_components.
  162042. * Note that the virtual arrays need not be filled or even realized at
  162043. * the time write_coefficients is called; indeed, if the virtual arrays
  162044. * were requested from this compression object's memory manager, they
  162045. * typically will be realized during this routine and filled afterwards.
  162046. */
  162047. GLOBAL(void)
  162048. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  162049. {
  162050. if (cinfo->global_state != CSTATE_START)
  162051. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162052. /* Mark all tables to be written */
  162053. jpeg_suppress_tables(cinfo, FALSE);
  162054. /* (Re)initialize error mgr and destination modules */
  162055. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  162056. (*cinfo->dest->init_destination) (cinfo);
  162057. /* Perform master selection of active modules */
  162058. transencode_master_selection(cinfo, coef_arrays);
  162059. /* Wait for jpeg_finish_compress() call */
  162060. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  162061. cinfo->global_state = CSTATE_WRCOEFS;
  162062. }
  162063. /*
  162064. * Initialize the compression object with default parameters,
  162065. * then copy from the source object all parameters needed for lossless
  162066. * transcoding. Parameters that can be varied without loss (such as
  162067. * scan script and Huffman optimization) are left in their default states.
  162068. */
  162069. GLOBAL(void)
  162070. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  162071. j_compress_ptr dstinfo)
  162072. {
  162073. JQUANT_TBL ** qtblptr;
  162074. jpeg_component_info *incomp, *outcomp;
  162075. JQUANT_TBL *c_quant, *slot_quant;
  162076. int tblno, ci, coefi;
  162077. /* Safety check to ensure start_compress not called yet. */
  162078. if (dstinfo->global_state != CSTATE_START)
  162079. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  162080. /* Copy fundamental image dimensions */
  162081. dstinfo->image_width = srcinfo->image_width;
  162082. dstinfo->image_height = srcinfo->image_height;
  162083. dstinfo->input_components = srcinfo->num_components;
  162084. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  162085. /* Initialize all parameters to default values */
  162086. jpeg_set_defaults(dstinfo);
  162087. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  162088. * Fix it to get the right header markers for the image colorspace.
  162089. */
  162090. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  162091. dstinfo->data_precision = srcinfo->data_precision;
  162092. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  162093. /* Copy the source's quantization tables. */
  162094. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  162095. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  162096. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  162097. if (*qtblptr == NULL)
  162098. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  162099. MEMCOPY((*qtblptr)->quantval,
  162100. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  162101. SIZEOF((*qtblptr)->quantval));
  162102. (*qtblptr)->sent_table = FALSE;
  162103. }
  162104. }
  162105. /* Copy the source's per-component info.
  162106. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  162107. */
  162108. dstinfo->num_components = srcinfo->num_components;
  162109. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  162110. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  162111. MAX_COMPONENTS);
  162112. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  162113. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  162114. outcomp->component_id = incomp->component_id;
  162115. outcomp->h_samp_factor = incomp->h_samp_factor;
  162116. outcomp->v_samp_factor = incomp->v_samp_factor;
  162117. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  162118. /* Make sure saved quantization table for component matches the qtable
  162119. * slot. If not, the input file re-used this qtable slot.
  162120. * IJG encoder currently cannot duplicate this.
  162121. */
  162122. tblno = outcomp->quant_tbl_no;
  162123. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  162124. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  162125. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  162126. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  162127. c_quant = incomp->quant_table;
  162128. if (c_quant != NULL) {
  162129. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  162130. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  162131. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  162132. }
  162133. }
  162134. /* Note: we do not copy the source's Huffman table assignments;
  162135. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  162136. */
  162137. }
  162138. /* Also copy JFIF version and resolution information, if available.
  162139. * Strictly speaking this isn't "critical" info, but it's nearly
  162140. * always appropriate to copy it if available. In particular,
  162141. * if the application chooses to copy JFIF 1.02 extension markers from
  162142. * the source file, we need to copy the version to make sure we don't
  162143. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  162144. * We will *not*, however, copy version info from mislabeled "2.01" files.
  162145. */
  162146. if (srcinfo->saw_JFIF_marker) {
  162147. if (srcinfo->JFIF_major_version == 1) {
  162148. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  162149. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  162150. }
  162151. dstinfo->density_unit = srcinfo->density_unit;
  162152. dstinfo->X_density = srcinfo->X_density;
  162153. dstinfo->Y_density = srcinfo->Y_density;
  162154. }
  162155. }
  162156. /*
  162157. * Master selection of compression modules for transcoding.
  162158. * This substitutes for jcinit.c's initialization of the full compressor.
  162159. */
  162160. LOCAL(void)
  162161. transencode_master_selection (j_compress_ptr cinfo,
  162162. jvirt_barray_ptr * coef_arrays)
  162163. {
  162164. /* Although we don't actually use input_components for transcoding,
  162165. * jcmaster.c's initial_setup will complain if input_components is 0.
  162166. */
  162167. cinfo->input_components = 1;
  162168. /* Initialize master control (includes parameter checking/processing) */
  162169. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  162170. /* Entropy encoding: either Huffman or arithmetic coding. */
  162171. if (cinfo->arith_code) {
  162172. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  162173. } else {
  162174. if (cinfo->progressive_mode) {
  162175. #ifdef C_PROGRESSIVE_SUPPORTED
  162176. jinit_phuff_encoder(cinfo);
  162177. #else
  162178. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162179. #endif
  162180. } else
  162181. jinit_huff_encoder(cinfo);
  162182. }
  162183. /* We need a special coefficient buffer controller. */
  162184. transencode_coef_controller(cinfo, coef_arrays);
  162185. jinit_marker_writer(cinfo);
  162186. /* We can now tell the memory manager to allocate virtual arrays. */
  162187. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  162188. /* Write the datastream header (SOI, JFIF) immediately.
  162189. * Frame and scan headers are postponed till later.
  162190. * This lets application insert special markers after the SOI.
  162191. */
  162192. (*cinfo->marker->write_file_header) (cinfo);
  162193. }
  162194. /*
  162195. * The rest of this file is a special implementation of the coefficient
  162196. * buffer controller. This is similar to jccoefct.c, but it handles only
  162197. * output from presupplied virtual arrays. Furthermore, we generate any
  162198. * dummy padding blocks on-the-fly rather than expecting them to be present
  162199. * in the arrays.
  162200. */
  162201. /* Private buffer controller object */
  162202. typedef struct {
  162203. struct jpeg_c_coef_controller pub; /* public fields */
  162204. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  162205. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  162206. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162207. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162208. /* Virtual block array for each component. */
  162209. jvirt_barray_ptr * whole_image;
  162210. /* Workspace for constructing dummy blocks at right/bottom edges. */
  162211. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  162212. } my_coef_controller2;
  162213. typedef my_coef_controller2 * my_coef_ptr2;
  162214. LOCAL(void)
  162215. start_iMCU_row2 (j_compress_ptr cinfo)
  162216. /* Reset within-iMCU-row counters for a new row */
  162217. {
  162218. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  162219. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162220. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162221. * But at the bottom of the image, process only what's left.
  162222. */
  162223. if (cinfo->comps_in_scan > 1) {
  162224. coef->MCU_rows_per_iMCU_row = 1;
  162225. } else {
  162226. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  162227. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162228. else
  162229. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162230. }
  162231. coef->mcu_ctr = 0;
  162232. coef->MCU_vert_offset = 0;
  162233. }
  162234. /*
  162235. * Initialize for a processing pass.
  162236. */
  162237. METHODDEF(void)
  162238. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162239. {
  162240. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  162241. if (pass_mode != JBUF_CRANK_DEST)
  162242. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162243. coef->iMCU_row_num = 0;
  162244. start_iMCU_row2(cinfo);
  162245. }
  162246. /*
  162247. * Process some data.
  162248. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162249. * per call, ie, v_samp_factor block rows for each component in the scan.
  162250. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162251. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162252. *
  162253. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162254. */
  162255. METHODDEF(boolean)
  162256. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162257. {
  162258. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  162259. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162260. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162261. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162262. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  162263. JDIMENSION start_col;
  162264. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162265. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  162266. JBLOCKROW buffer_ptr;
  162267. jpeg_component_info *compptr;
  162268. /* Align the virtual buffers for the components used in this scan. */
  162269. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162270. compptr = cinfo->cur_comp_info[ci];
  162271. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162272. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162273. coef->iMCU_row_num * compptr->v_samp_factor,
  162274. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162275. }
  162276. /* Loop to process one whole iMCU row */
  162277. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162278. yoffset++) {
  162279. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162280. MCU_col_num++) {
  162281. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162282. blkn = 0; /* index of current DCT block within MCU */
  162283. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162284. compptr = cinfo->cur_comp_info[ci];
  162285. start_col = MCU_col_num * compptr->MCU_width;
  162286. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162287. : compptr->last_col_width;
  162288. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162289. if (coef->iMCU_row_num < last_iMCU_row ||
  162290. yindex+yoffset < compptr->last_row_height) {
  162291. /* Fill in pointers to real blocks in this row */
  162292. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162293. for (xindex = 0; xindex < blockcnt; xindex++)
  162294. MCU_buffer[blkn++] = buffer_ptr++;
  162295. } else {
  162296. /* At bottom of image, need a whole row of dummy blocks */
  162297. xindex = 0;
  162298. }
  162299. /* Fill in any dummy blocks needed in this row.
  162300. * Dummy blocks are filled in the same way as in jccoefct.c:
  162301. * all zeroes in the AC entries, DC entries equal to previous
  162302. * block's DC value. The init routine has already zeroed the
  162303. * AC entries, so we need only set the DC entries correctly.
  162304. */
  162305. for (; xindex < compptr->MCU_width; xindex++) {
  162306. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  162307. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  162308. blkn++;
  162309. }
  162310. }
  162311. }
  162312. /* Try to write the MCU. */
  162313. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  162314. /* Suspension forced; update state counters and exit */
  162315. coef->MCU_vert_offset = yoffset;
  162316. coef->mcu_ctr = MCU_col_num;
  162317. return FALSE;
  162318. }
  162319. }
  162320. /* Completed an MCU row, but perhaps not an iMCU row */
  162321. coef->mcu_ctr = 0;
  162322. }
  162323. /* Completed the iMCU row, advance counters for next one */
  162324. coef->iMCU_row_num++;
  162325. start_iMCU_row2(cinfo);
  162326. return TRUE;
  162327. }
  162328. /*
  162329. * Initialize coefficient buffer controller.
  162330. *
  162331. * Each passed coefficient array must be the right size for that
  162332. * coefficient: width_in_blocks wide and height_in_blocks high,
  162333. * with unitheight at least v_samp_factor.
  162334. */
  162335. LOCAL(void)
  162336. transencode_coef_controller (j_compress_ptr cinfo,
  162337. jvirt_barray_ptr * coef_arrays)
  162338. {
  162339. my_coef_ptr2 coef;
  162340. JBLOCKROW buffer;
  162341. int i;
  162342. coef = (my_coef_ptr2)
  162343. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162344. SIZEOF(my_coef_controller2));
  162345. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162346. coef->pub.start_pass = start_pass_coef2;
  162347. coef->pub.compress_data = compress_output2;
  162348. /* Save pointer to virtual arrays */
  162349. coef->whole_image = coef_arrays;
  162350. /* Allocate and pre-zero space for dummy DCT blocks. */
  162351. buffer = (JBLOCKROW)
  162352. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162353. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162354. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162355. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162356. coef->dummy_buffer[i] = buffer + i;
  162357. }
  162358. }
  162359. /********* End of inlined file: jctrans.c *********/
  162360. /********* Start of inlined file: jdapistd.c *********/
  162361. #define JPEG_INTERNALS
  162362. /* Forward declarations */
  162363. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  162364. /*
  162365. * Decompression initialization.
  162366. * jpeg_read_header must be completed before calling this.
  162367. *
  162368. * If a multipass operating mode was selected, this will do all but the
  162369. * last pass, and thus may take a great deal of time.
  162370. *
  162371. * Returns FALSE if suspended. The return value need be inspected only if
  162372. * a suspending data source is used.
  162373. */
  162374. GLOBAL(boolean)
  162375. jpeg_start_decompress (j_decompress_ptr cinfo)
  162376. {
  162377. if (cinfo->global_state == DSTATE_READY) {
  162378. /* First call: initialize master control, select active modules */
  162379. jinit_master_decompress(cinfo);
  162380. if (cinfo->buffered_image) {
  162381. /* No more work here; expecting jpeg_start_output next */
  162382. cinfo->global_state = DSTATE_BUFIMAGE;
  162383. return TRUE;
  162384. }
  162385. cinfo->global_state = DSTATE_PRELOAD;
  162386. }
  162387. if (cinfo->global_state == DSTATE_PRELOAD) {
  162388. /* If file has multiple scans, absorb them all into the coef buffer */
  162389. if (cinfo->inputctl->has_multiple_scans) {
  162390. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162391. for (;;) {
  162392. int retcode;
  162393. /* Call progress monitor hook if present */
  162394. if (cinfo->progress != NULL)
  162395. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162396. /* Absorb some more input */
  162397. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  162398. if (retcode == JPEG_SUSPENDED)
  162399. return FALSE;
  162400. if (retcode == JPEG_REACHED_EOI)
  162401. break;
  162402. /* Advance progress counter if appropriate */
  162403. if (cinfo->progress != NULL &&
  162404. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  162405. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  162406. /* jdmaster underestimated number of scans; ratchet up one scan */
  162407. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  162408. }
  162409. }
  162410. }
  162411. #else
  162412. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162413. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  162414. }
  162415. cinfo->output_scan_number = cinfo->input_scan_number;
  162416. } else if (cinfo->global_state != DSTATE_PRESCAN)
  162417. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162418. /* Perform any dummy output passes, and set up for the final pass */
  162419. return output_pass_setup(cinfo);
  162420. }
  162421. /*
  162422. * Set up for an output pass, and perform any dummy pass(es) needed.
  162423. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  162424. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  162425. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  162426. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  162427. */
  162428. LOCAL(boolean)
  162429. output_pass_setup (j_decompress_ptr cinfo)
  162430. {
  162431. if (cinfo->global_state != DSTATE_PRESCAN) {
  162432. /* First call: do pass setup */
  162433. (*cinfo->master->prepare_for_output_pass) (cinfo);
  162434. cinfo->output_scanline = 0;
  162435. cinfo->global_state = DSTATE_PRESCAN;
  162436. }
  162437. /* Loop over any required dummy passes */
  162438. while (cinfo->master->is_dummy_pass) {
  162439. #ifdef QUANT_2PASS_SUPPORTED
  162440. /* Crank through the dummy pass */
  162441. while (cinfo->output_scanline < cinfo->output_height) {
  162442. JDIMENSION last_scanline;
  162443. /* Call progress monitor hook if present */
  162444. if (cinfo->progress != NULL) {
  162445. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  162446. cinfo->progress->pass_limit = (long) cinfo->output_height;
  162447. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162448. }
  162449. /* Process some data */
  162450. last_scanline = cinfo->output_scanline;
  162451. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  162452. &cinfo->output_scanline, (JDIMENSION) 0);
  162453. if (cinfo->output_scanline == last_scanline)
  162454. return FALSE; /* No progress made, must suspend */
  162455. }
  162456. /* Finish up dummy pass, and set up for another one */
  162457. (*cinfo->master->finish_output_pass) (cinfo);
  162458. (*cinfo->master->prepare_for_output_pass) (cinfo);
  162459. cinfo->output_scanline = 0;
  162460. #else
  162461. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162462. #endif /* QUANT_2PASS_SUPPORTED */
  162463. }
  162464. /* Ready for application to drive output pass through
  162465. * jpeg_read_scanlines or jpeg_read_raw_data.
  162466. */
  162467. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  162468. return TRUE;
  162469. }
  162470. /*
  162471. * Read some scanlines of data from the JPEG decompressor.
  162472. *
  162473. * The return value will be the number of lines actually read.
  162474. * This may be less than the number requested in several cases,
  162475. * including bottom of image, data source suspension, and operating
  162476. * modes that emit multiple scanlines at a time.
  162477. *
  162478. * Note: we warn about excess calls to jpeg_read_scanlines() since
  162479. * this likely signals an application programmer error. However,
  162480. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  162481. */
  162482. GLOBAL(JDIMENSION)
  162483. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  162484. JDIMENSION max_lines)
  162485. {
  162486. JDIMENSION row_ctr;
  162487. if (cinfo->global_state != DSTATE_SCANNING)
  162488. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162489. if (cinfo->output_scanline >= cinfo->output_height) {
  162490. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162491. return 0;
  162492. }
  162493. /* Call progress monitor hook if present */
  162494. if (cinfo->progress != NULL) {
  162495. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  162496. cinfo->progress->pass_limit = (long) cinfo->output_height;
  162497. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162498. }
  162499. /* Process some data */
  162500. row_ctr = 0;
  162501. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  162502. cinfo->output_scanline += row_ctr;
  162503. return row_ctr;
  162504. }
  162505. /*
  162506. * Alternate entry point to read raw data.
  162507. * Processes exactly one iMCU row per call, unless suspended.
  162508. */
  162509. GLOBAL(JDIMENSION)
  162510. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  162511. JDIMENSION max_lines)
  162512. {
  162513. JDIMENSION lines_per_iMCU_row;
  162514. if (cinfo->global_state != DSTATE_RAW_OK)
  162515. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162516. if (cinfo->output_scanline >= cinfo->output_height) {
  162517. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162518. return 0;
  162519. }
  162520. /* Call progress monitor hook if present */
  162521. if (cinfo->progress != NULL) {
  162522. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  162523. cinfo->progress->pass_limit = (long) cinfo->output_height;
  162524. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162525. }
  162526. /* Verify that at least one iMCU row can be returned. */
  162527. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  162528. if (max_lines < lines_per_iMCU_row)
  162529. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  162530. /* Decompress directly into user's buffer. */
  162531. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  162532. return 0; /* suspension forced, can do nothing more */
  162533. /* OK, we processed one iMCU row. */
  162534. cinfo->output_scanline += lines_per_iMCU_row;
  162535. return lines_per_iMCU_row;
  162536. }
  162537. /* Additional entry points for buffered-image mode. */
  162538. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162539. /*
  162540. * Initialize for an output pass in buffered-image mode.
  162541. */
  162542. GLOBAL(boolean)
  162543. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  162544. {
  162545. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  162546. cinfo->global_state != DSTATE_PRESCAN)
  162547. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162548. /* Limit scan number to valid range */
  162549. if (scan_number <= 0)
  162550. scan_number = 1;
  162551. if (cinfo->inputctl->eoi_reached &&
  162552. scan_number > cinfo->input_scan_number)
  162553. scan_number = cinfo->input_scan_number;
  162554. cinfo->output_scan_number = scan_number;
  162555. /* Perform any dummy output passes, and set up for the real pass */
  162556. return output_pass_setup(cinfo);
  162557. }
  162558. /*
  162559. * Finish up after an output pass in buffered-image mode.
  162560. *
  162561. * Returns FALSE if suspended. The return value need be inspected only if
  162562. * a suspending data source is used.
  162563. */
  162564. GLOBAL(boolean)
  162565. jpeg_finish_output (j_decompress_ptr cinfo)
  162566. {
  162567. if ((cinfo->global_state == DSTATE_SCANNING ||
  162568. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  162569. /* Terminate this pass. */
  162570. /* We do not require the whole pass to have been completed. */
  162571. (*cinfo->master->finish_output_pass) (cinfo);
  162572. cinfo->global_state = DSTATE_BUFPOST;
  162573. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  162574. /* BUFPOST = repeat call after a suspension, anything else is error */
  162575. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162576. }
  162577. /* Read markers looking for SOS or EOI */
  162578. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  162579. ! cinfo->inputctl->eoi_reached) {
  162580. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  162581. return FALSE; /* Suspend, come back later */
  162582. }
  162583. cinfo->global_state = DSTATE_BUFIMAGE;
  162584. return TRUE;
  162585. }
  162586. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  162587. /********* End of inlined file: jdapistd.c *********/
  162588. /********* Start of inlined file: jdapimin.c *********/
  162589. #define JPEG_INTERNALS
  162590. /*
  162591. * Initialization of a JPEG decompression object.
  162592. * The error manager must already be set up (in case memory manager fails).
  162593. */
  162594. GLOBAL(void)
  162595. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  162596. {
  162597. int i;
  162598. /* Guard against version mismatches between library and caller. */
  162599. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  162600. if (version != JPEG_LIB_VERSION)
  162601. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  162602. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  162603. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  162604. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  162605. /* For debugging purposes, we zero the whole master structure.
  162606. * But the application has already set the err pointer, and may have set
  162607. * client_data, so we have to save and restore those fields.
  162608. * Note: if application hasn't set client_data, tools like Purify may
  162609. * complain here.
  162610. */
  162611. {
  162612. struct jpeg_error_mgr * err = cinfo->err;
  162613. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  162614. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  162615. cinfo->err = err;
  162616. cinfo->client_data = client_data;
  162617. }
  162618. cinfo->is_decompressor = TRUE;
  162619. /* Initialize a memory manager instance for this object */
  162620. jinit_memory_mgr((j_common_ptr) cinfo);
  162621. /* Zero out pointers to permanent structures. */
  162622. cinfo->progress = NULL;
  162623. cinfo->src = NULL;
  162624. for (i = 0; i < NUM_QUANT_TBLS; i++)
  162625. cinfo->quant_tbl_ptrs[i] = NULL;
  162626. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  162627. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  162628. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  162629. }
  162630. /* Initialize marker processor so application can override methods
  162631. * for COM, APPn markers before calling jpeg_read_header.
  162632. */
  162633. cinfo->marker_list = NULL;
  162634. jinit_marker_reader(cinfo);
  162635. /* And initialize the overall input controller. */
  162636. jinit_input_controller(cinfo);
  162637. /* OK, I'm ready */
  162638. cinfo->global_state = DSTATE_START;
  162639. }
  162640. /*
  162641. * Destruction of a JPEG decompression object
  162642. */
  162643. GLOBAL(void)
  162644. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  162645. {
  162646. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  162647. }
  162648. /*
  162649. * Abort processing of a JPEG decompression operation,
  162650. * but don't destroy the object itself.
  162651. */
  162652. GLOBAL(void)
  162653. jpeg_abort_decompress (j_decompress_ptr cinfo)
  162654. {
  162655. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  162656. }
  162657. /*
  162658. * Set default decompression parameters.
  162659. */
  162660. LOCAL(void)
  162661. default_decompress_parms (j_decompress_ptr cinfo)
  162662. {
  162663. /* Guess the input colorspace, and set output colorspace accordingly. */
  162664. /* (Wish JPEG committee had provided a real way to specify this...) */
  162665. /* Note application may override our guesses. */
  162666. switch (cinfo->num_components) {
  162667. case 1:
  162668. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  162669. cinfo->out_color_space = JCS_GRAYSCALE;
  162670. break;
  162671. case 3:
  162672. if (cinfo->saw_JFIF_marker) {
  162673. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  162674. } else if (cinfo->saw_Adobe_marker) {
  162675. switch (cinfo->Adobe_transform) {
  162676. case 0:
  162677. cinfo->jpeg_color_space = JCS_RGB;
  162678. break;
  162679. case 1:
  162680. cinfo->jpeg_color_space = JCS_YCbCr;
  162681. break;
  162682. default:
  162683. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  162684. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  162685. break;
  162686. }
  162687. } else {
  162688. /* Saw no special markers, try to guess from the component IDs */
  162689. int cid0 = cinfo->comp_info[0].component_id;
  162690. int cid1 = cinfo->comp_info[1].component_id;
  162691. int cid2 = cinfo->comp_info[2].component_id;
  162692. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  162693. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  162694. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  162695. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  162696. else {
  162697. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  162698. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  162699. }
  162700. }
  162701. /* Always guess RGB is proper output colorspace. */
  162702. cinfo->out_color_space = JCS_RGB;
  162703. break;
  162704. case 4:
  162705. if (cinfo->saw_Adobe_marker) {
  162706. switch (cinfo->Adobe_transform) {
  162707. case 0:
  162708. cinfo->jpeg_color_space = JCS_CMYK;
  162709. break;
  162710. case 2:
  162711. cinfo->jpeg_color_space = JCS_YCCK;
  162712. break;
  162713. default:
  162714. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  162715. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  162716. break;
  162717. }
  162718. } else {
  162719. /* No special markers, assume straight CMYK. */
  162720. cinfo->jpeg_color_space = JCS_CMYK;
  162721. }
  162722. cinfo->out_color_space = JCS_CMYK;
  162723. break;
  162724. default:
  162725. cinfo->jpeg_color_space = JCS_UNKNOWN;
  162726. cinfo->out_color_space = JCS_UNKNOWN;
  162727. break;
  162728. }
  162729. /* Set defaults for other decompression parameters. */
  162730. cinfo->scale_num = 1; /* 1:1 scaling */
  162731. cinfo->scale_denom = 1;
  162732. cinfo->output_gamma = 1.0;
  162733. cinfo->buffered_image = FALSE;
  162734. cinfo->raw_data_out = FALSE;
  162735. cinfo->dct_method = JDCT_DEFAULT;
  162736. cinfo->do_fancy_upsampling = TRUE;
  162737. cinfo->do_block_smoothing = TRUE;
  162738. cinfo->quantize_colors = FALSE;
  162739. /* We set these in case application only sets quantize_colors. */
  162740. cinfo->dither_mode = JDITHER_FS;
  162741. #ifdef QUANT_2PASS_SUPPORTED
  162742. cinfo->two_pass_quantize = TRUE;
  162743. #else
  162744. cinfo->two_pass_quantize = FALSE;
  162745. #endif
  162746. cinfo->desired_number_of_colors = 256;
  162747. cinfo->colormap = NULL;
  162748. /* Initialize for no mode change in buffered-image mode. */
  162749. cinfo->enable_1pass_quant = FALSE;
  162750. cinfo->enable_external_quant = FALSE;
  162751. cinfo->enable_2pass_quant = FALSE;
  162752. }
  162753. /*
  162754. * Decompression startup: read start of JPEG datastream to see what's there.
  162755. * Need only initialize JPEG object and supply a data source before calling.
  162756. *
  162757. * This routine will read as far as the first SOS marker (ie, actual start of
  162758. * compressed data), and will save all tables and parameters in the JPEG
  162759. * object. It will also initialize the decompression parameters to default
  162760. * values, and finally return JPEG_HEADER_OK. On return, the application may
  162761. * adjust the decompression parameters and then call jpeg_start_decompress.
  162762. * (Or, if the application only wanted to determine the image parameters,
  162763. * the data need not be decompressed. In that case, call jpeg_abort or
  162764. * jpeg_destroy to release any temporary space.)
  162765. * If an abbreviated (tables only) datastream is presented, the routine will
  162766. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  162767. * re-use the JPEG object to read the abbreviated image datastream(s).
  162768. * It is unnecessary (but OK) to call jpeg_abort in this case.
  162769. * The JPEG_SUSPENDED return code only occurs if the data source module
  162770. * requests suspension of the decompressor. In this case the application
  162771. * should load more source data and then re-call jpeg_read_header to resume
  162772. * processing.
  162773. * If a non-suspending data source is used and require_image is TRUE, then the
  162774. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  162775. *
  162776. * This routine is now just a front end to jpeg_consume_input, with some
  162777. * extra error checking.
  162778. */
  162779. GLOBAL(int)
  162780. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  162781. {
  162782. int retcode;
  162783. if (cinfo->global_state != DSTATE_START &&
  162784. cinfo->global_state != DSTATE_INHEADER)
  162785. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162786. retcode = jpeg_consume_input(cinfo);
  162787. switch (retcode) {
  162788. case JPEG_REACHED_SOS:
  162789. retcode = JPEG_HEADER_OK;
  162790. break;
  162791. case JPEG_REACHED_EOI:
  162792. if (require_image) /* Complain if application wanted an image */
  162793. ERREXIT(cinfo, JERR_NO_IMAGE);
  162794. /* Reset to start state; it would be safer to require the application to
  162795. * call jpeg_abort, but we can't change it now for compatibility reasons.
  162796. * A side effect is to free any temporary memory (there shouldn't be any).
  162797. */
  162798. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  162799. retcode = JPEG_HEADER_TABLES_ONLY;
  162800. break;
  162801. case JPEG_SUSPENDED:
  162802. /* no work */
  162803. break;
  162804. }
  162805. return retcode;
  162806. }
  162807. /*
  162808. * Consume data in advance of what the decompressor requires.
  162809. * This can be called at any time once the decompressor object has
  162810. * been created and a data source has been set up.
  162811. *
  162812. * This routine is essentially a state machine that handles a couple
  162813. * of critical state-transition actions, namely initial setup and
  162814. * transition from header scanning to ready-for-start_decompress.
  162815. * All the actual input is done via the input controller's consume_input
  162816. * method.
  162817. */
  162818. GLOBAL(int)
  162819. jpeg_consume_input (j_decompress_ptr cinfo)
  162820. {
  162821. int retcode = JPEG_SUSPENDED;
  162822. /* NB: every possible DSTATE value should be listed in this switch */
  162823. switch (cinfo->global_state) {
  162824. case DSTATE_START:
  162825. /* Start-of-datastream actions: reset appropriate modules */
  162826. (*cinfo->inputctl->reset_input_controller) (cinfo);
  162827. /* Initialize application's data source module */
  162828. (*cinfo->src->init_source) (cinfo);
  162829. cinfo->global_state = DSTATE_INHEADER;
  162830. /*FALLTHROUGH*/
  162831. case DSTATE_INHEADER:
  162832. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  162833. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  162834. /* Set up default parameters based on header data */
  162835. default_decompress_parms(cinfo);
  162836. /* Set global state: ready for start_decompress */
  162837. cinfo->global_state = DSTATE_READY;
  162838. }
  162839. break;
  162840. case DSTATE_READY:
  162841. /* Can't advance past first SOS until start_decompress is called */
  162842. retcode = JPEG_REACHED_SOS;
  162843. break;
  162844. case DSTATE_PRELOAD:
  162845. case DSTATE_PRESCAN:
  162846. case DSTATE_SCANNING:
  162847. case DSTATE_RAW_OK:
  162848. case DSTATE_BUFIMAGE:
  162849. case DSTATE_BUFPOST:
  162850. case DSTATE_STOPPING:
  162851. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  162852. break;
  162853. default:
  162854. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162855. }
  162856. return retcode;
  162857. }
  162858. /*
  162859. * Have we finished reading the input file?
  162860. */
  162861. GLOBAL(boolean)
  162862. jpeg_input_complete (j_decompress_ptr cinfo)
  162863. {
  162864. /* Check for valid jpeg object */
  162865. if (cinfo->global_state < DSTATE_START ||
  162866. cinfo->global_state > DSTATE_STOPPING)
  162867. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162868. return cinfo->inputctl->eoi_reached;
  162869. }
  162870. /*
  162871. * Is there more than one scan?
  162872. */
  162873. GLOBAL(boolean)
  162874. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  162875. {
  162876. /* Only valid after jpeg_read_header completes */
  162877. if (cinfo->global_state < DSTATE_READY ||
  162878. cinfo->global_state > DSTATE_STOPPING)
  162879. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162880. return cinfo->inputctl->has_multiple_scans;
  162881. }
  162882. /*
  162883. * Finish JPEG decompression.
  162884. *
  162885. * This will normally just verify the file trailer and release temp storage.
  162886. *
  162887. * Returns FALSE if suspended. The return value need be inspected only if
  162888. * a suspending data source is used.
  162889. */
  162890. GLOBAL(boolean)
  162891. jpeg_finish_decompress (j_decompress_ptr cinfo)
  162892. {
  162893. if ((cinfo->global_state == DSTATE_SCANNING ||
  162894. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  162895. /* Terminate final pass of non-buffered mode */
  162896. if (cinfo->output_scanline < cinfo->output_height)
  162897. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  162898. (*cinfo->master->finish_output_pass) (cinfo);
  162899. cinfo->global_state = DSTATE_STOPPING;
  162900. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  162901. /* Finishing after a buffered-image operation */
  162902. cinfo->global_state = DSTATE_STOPPING;
  162903. } else if (cinfo->global_state != DSTATE_STOPPING) {
  162904. /* STOPPING = repeat call after a suspension, anything else is error */
  162905. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162906. }
  162907. /* Read until EOI */
  162908. while (! cinfo->inputctl->eoi_reached) {
  162909. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  162910. return FALSE; /* Suspend, come back later */
  162911. }
  162912. /* Do final cleanup */
  162913. (*cinfo->src->term_source) (cinfo);
  162914. /* We can use jpeg_abort to release memory and reset global_state */
  162915. jpeg_abort((j_common_ptr) cinfo);
  162916. return TRUE;
  162917. }
  162918. /********* End of inlined file: jdapimin.c *********/
  162919. /********* Start of inlined file: jdatasrc.c *********/
  162920. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  162921. /********* Start of inlined file: jerror.h *********/
  162922. /*
  162923. * To define the enum list of message codes, include this file without
  162924. * defining macro JMESSAGE. To create a message string table, include it
  162925. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  162926. */
  162927. #ifndef JMESSAGE
  162928. #ifndef JERROR_H
  162929. /* First time through, define the enum list */
  162930. #define JMAKE_ENUM_LIST
  162931. #else
  162932. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  162933. #define JMESSAGE(code,string)
  162934. #endif /* JERROR_H */
  162935. #endif /* JMESSAGE */
  162936. #ifdef JMAKE_ENUM_LIST
  162937. typedef enum {
  162938. #define JMESSAGE(code,string) code ,
  162939. #endif /* JMAKE_ENUM_LIST */
  162940. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  162941. /* For maintenance convenience, list is alphabetical by message code name */
  162942. JMESSAGE(JERR_ARITH_NOTIMPL,
  162943. "Sorry, there are legal restrictions on arithmetic coding")
  162944. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  162945. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  162946. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  162947. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  162948. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  162949. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  162950. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  162951. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  162952. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  162953. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  162954. JMESSAGE(JERR_BAD_LIB_VERSION,
  162955. "Wrong JPEG library version: library is %d, caller expects %d")
  162956. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  162957. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  162958. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  162959. JMESSAGE(JERR_BAD_PROGRESSION,
  162960. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  162961. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  162962. "Invalid progressive parameters at scan script entry %d")
  162963. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  162964. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  162965. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  162966. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  162967. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  162968. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  162969. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  162970. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  162971. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  162972. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  162973. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  162974. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  162975. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  162976. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  162977. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  162978. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  162979. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  162980. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  162981. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  162982. JMESSAGE(JERR_FILE_READ, "Input file read error")
  162983. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  162984. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  162985. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  162986. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  162987. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  162988. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  162989. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  162990. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  162991. "Cannot transcode due to multiple use of quantization table %d")
  162992. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  162993. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  162994. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  162995. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  162996. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  162997. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  162998. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  162999. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  163000. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  163001. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  163002. JMESSAGE(JERR_QUANT_COMPONENTS,
  163003. "Cannot quantize more than %d color components")
  163004. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  163005. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  163006. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  163007. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  163008. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  163009. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  163010. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  163011. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  163012. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  163013. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  163014. JMESSAGE(JERR_TFILE_WRITE,
  163015. "Write failed on temporary file --- out of disk space?")
  163016. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  163017. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  163018. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  163019. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  163020. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  163021. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  163022. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  163023. JMESSAGE(JMSG_VERSION, JVERSION)
  163024. JMESSAGE(JTRC_16BIT_TABLES,
  163025. "Caution: quantization tables are too coarse for baseline JPEG")
  163026. JMESSAGE(JTRC_ADOBE,
  163027. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  163028. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  163029. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  163030. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  163031. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  163032. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  163033. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  163034. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  163035. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  163036. JMESSAGE(JTRC_EOI, "End Of Image")
  163037. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  163038. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  163039. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  163040. "Warning: thumbnail image size does not match data length %u")
  163041. JMESSAGE(JTRC_JFIF_EXTENSION,
  163042. "JFIF extension marker: type 0x%02x, length %u")
  163043. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  163044. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  163045. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  163046. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  163047. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  163048. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  163049. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  163050. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  163051. JMESSAGE(JTRC_RST, "RST%d")
  163052. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  163053. "Smoothing not supported with nonstandard sampling ratios")
  163054. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  163055. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  163056. JMESSAGE(JTRC_SOI, "Start of Image")
  163057. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  163058. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  163059. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  163060. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  163061. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  163062. JMESSAGE(JTRC_THUMB_JPEG,
  163063. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  163064. JMESSAGE(JTRC_THUMB_PALETTE,
  163065. "JFIF extension marker: palette thumbnail image, length %u")
  163066. JMESSAGE(JTRC_THUMB_RGB,
  163067. "JFIF extension marker: RGB thumbnail image, length %u")
  163068. JMESSAGE(JTRC_UNKNOWN_IDS,
  163069. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  163070. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  163071. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  163072. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  163073. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  163074. "Inconsistent progression sequence for component %d coefficient %d")
  163075. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  163076. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  163077. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  163078. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  163079. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  163080. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  163081. JMESSAGE(JWRN_MUST_RESYNC,
  163082. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  163083. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  163084. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  163085. #ifdef JMAKE_ENUM_LIST
  163086. JMSG_LASTMSGCODE
  163087. } J_MESSAGE_CODE;
  163088. #undef JMAKE_ENUM_LIST
  163089. #endif /* JMAKE_ENUM_LIST */
  163090. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  163091. #undef JMESSAGE
  163092. #ifndef JERROR_H
  163093. #define JERROR_H
  163094. /* Macros to simplify using the error and trace message stuff */
  163095. /* The first parameter is either type of cinfo pointer */
  163096. /* Fatal errors (print message and exit) */
  163097. #define ERREXIT(cinfo,code) \
  163098. ((cinfo)->err->msg_code = (code), \
  163099. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163100. #define ERREXIT1(cinfo,code,p1) \
  163101. ((cinfo)->err->msg_code = (code), \
  163102. (cinfo)->err->msg_parm.i[0] = (p1), \
  163103. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163104. #define ERREXIT2(cinfo,code,p1,p2) \
  163105. ((cinfo)->err->msg_code = (code), \
  163106. (cinfo)->err->msg_parm.i[0] = (p1), \
  163107. (cinfo)->err->msg_parm.i[1] = (p2), \
  163108. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163109. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  163110. ((cinfo)->err->msg_code = (code), \
  163111. (cinfo)->err->msg_parm.i[0] = (p1), \
  163112. (cinfo)->err->msg_parm.i[1] = (p2), \
  163113. (cinfo)->err->msg_parm.i[2] = (p3), \
  163114. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163115. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  163116. ((cinfo)->err->msg_code = (code), \
  163117. (cinfo)->err->msg_parm.i[0] = (p1), \
  163118. (cinfo)->err->msg_parm.i[1] = (p2), \
  163119. (cinfo)->err->msg_parm.i[2] = (p3), \
  163120. (cinfo)->err->msg_parm.i[3] = (p4), \
  163121. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163122. #define ERREXITS(cinfo,code,str) \
  163123. ((cinfo)->err->msg_code = (code), \
  163124. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  163125. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163126. #define MAKESTMT(stuff) do { stuff } while (0)
  163127. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  163128. #define WARNMS(cinfo,code) \
  163129. ((cinfo)->err->msg_code = (code), \
  163130. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163131. #define WARNMS1(cinfo,code,p1) \
  163132. ((cinfo)->err->msg_code = (code), \
  163133. (cinfo)->err->msg_parm.i[0] = (p1), \
  163134. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163135. #define WARNMS2(cinfo,code,p1,p2) \
  163136. ((cinfo)->err->msg_code = (code), \
  163137. (cinfo)->err->msg_parm.i[0] = (p1), \
  163138. (cinfo)->err->msg_parm.i[1] = (p2), \
  163139. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163140. /* Informational/debugging messages */
  163141. #define TRACEMS(cinfo,lvl,code) \
  163142. ((cinfo)->err->msg_code = (code), \
  163143. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163144. #define TRACEMS1(cinfo,lvl,code,p1) \
  163145. ((cinfo)->err->msg_code = (code), \
  163146. (cinfo)->err->msg_parm.i[0] = (p1), \
  163147. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163148. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  163149. ((cinfo)->err->msg_code = (code), \
  163150. (cinfo)->err->msg_parm.i[0] = (p1), \
  163151. (cinfo)->err->msg_parm.i[1] = (p2), \
  163152. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163153. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  163154. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163155. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  163156. (cinfo)->err->msg_code = (code); \
  163157. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163158. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  163159. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163160. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  163161. (cinfo)->err->msg_code = (code); \
  163162. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163163. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  163164. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163165. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  163166. _mp[4] = (p5); \
  163167. (cinfo)->err->msg_code = (code); \
  163168. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163169. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  163170. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163171. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  163172. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  163173. (cinfo)->err->msg_code = (code); \
  163174. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163175. #define TRACEMSS(cinfo,lvl,code,str) \
  163176. ((cinfo)->err->msg_code = (code), \
  163177. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  163178. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163179. #endif /* JERROR_H */
  163180. /********* End of inlined file: jerror.h *********/
  163181. /* Expanded data source object for stdio input */
  163182. typedef struct {
  163183. struct jpeg_source_mgr pub; /* public fields */
  163184. FILE * infile; /* source stream */
  163185. JOCTET * buffer; /* start of buffer */
  163186. boolean start_of_file; /* have we gotten any data yet? */
  163187. } my_source_mgr;
  163188. typedef my_source_mgr * my_src_ptr;
  163189. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  163190. /*
  163191. * Initialize source --- called by jpeg_read_header
  163192. * before any data is actually read.
  163193. */
  163194. METHODDEF(void)
  163195. init_source (j_decompress_ptr cinfo)
  163196. {
  163197. my_src_ptr src = (my_src_ptr) cinfo->src;
  163198. /* We reset the empty-input-file flag for each image,
  163199. * but we don't clear the input buffer.
  163200. * This is correct behavior for reading a series of images from one source.
  163201. */
  163202. src->start_of_file = TRUE;
  163203. }
  163204. /*
  163205. * Fill the input buffer --- called whenever buffer is emptied.
  163206. *
  163207. * In typical applications, this should read fresh data into the buffer
  163208. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  163209. * reset the pointer & count to the start of the buffer, and return TRUE
  163210. * indicating that the buffer has been reloaded. It is not necessary to
  163211. * fill the buffer entirely, only to obtain at least one more byte.
  163212. *
  163213. * There is no such thing as an EOF return. If the end of the file has been
  163214. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  163215. * the buffer. In most cases, generating a warning message and inserting a
  163216. * fake EOI marker is the best course of action --- this will allow the
  163217. * decompressor to output however much of the image is there. However,
  163218. * the resulting error message is misleading if the real problem is an empty
  163219. * input file, so we handle that case specially.
  163220. *
  163221. * In applications that need to be able to suspend compression due to input
  163222. * not being available yet, a FALSE return indicates that no more data can be
  163223. * obtained right now, but more may be forthcoming later. In this situation,
  163224. * the decompressor will return to its caller (with an indication of the
  163225. * number of scanlines it has read, if any). The application should resume
  163226. * decompression after it has loaded more data into the input buffer. Note
  163227. * that there are substantial restrictions on the use of suspension --- see
  163228. * the documentation.
  163229. *
  163230. * When suspending, the decompressor will back up to a convenient restart point
  163231. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  163232. * indicate where the restart point will be if the current call returns FALSE.
  163233. * Data beyond this point must be rescanned after resumption, so move it to
  163234. * the front of the buffer rather than discarding it.
  163235. */
  163236. METHODDEF(boolean)
  163237. fill_input_buffer (j_decompress_ptr cinfo)
  163238. {
  163239. my_src_ptr src = (my_src_ptr) cinfo->src;
  163240. size_t nbytes;
  163241. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  163242. if (nbytes <= 0) {
  163243. if (src->start_of_file) /* Treat empty input file as fatal error */
  163244. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  163245. WARNMS(cinfo, JWRN_JPEG_EOF);
  163246. /* Insert a fake EOI marker */
  163247. src->buffer[0] = (JOCTET) 0xFF;
  163248. src->buffer[1] = (JOCTET) JPEG_EOI;
  163249. nbytes = 2;
  163250. }
  163251. src->pub.next_input_byte = src->buffer;
  163252. src->pub.bytes_in_buffer = nbytes;
  163253. src->start_of_file = FALSE;
  163254. return TRUE;
  163255. }
  163256. /*
  163257. * Skip data --- used to skip over a potentially large amount of
  163258. * uninteresting data (such as an APPn marker).
  163259. *
  163260. * Writers of suspendable-input applications must note that skip_input_data
  163261. * is not granted the right to give a suspension return. If the skip extends
  163262. * beyond the data currently in the buffer, the buffer can be marked empty so
  163263. * that the next read will cause a fill_input_buffer call that can suspend.
  163264. * Arranging for additional bytes to be discarded before reloading the input
  163265. * buffer is the application writer's problem.
  163266. */
  163267. METHODDEF(void)
  163268. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  163269. {
  163270. my_src_ptr src = (my_src_ptr) cinfo->src;
  163271. /* Just a dumb implementation for now. Could use fseek() except
  163272. * it doesn't work on pipes. Not clear that being smart is worth
  163273. * any trouble anyway --- large skips are infrequent.
  163274. */
  163275. if (num_bytes > 0) {
  163276. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  163277. num_bytes -= (long) src->pub.bytes_in_buffer;
  163278. (void) fill_input_buffer(cinfo);
  163279. /* note we assume that fill_input_buffer will never return FALSE,
  163280. * so suspension need not be handled.
  163281. */
  163282. }
  163283. src->pub.next_input_byte += (size_t) num_bytes;
  163284. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  163285. }
  163286. }
  163287. /*
  163288. * An additional method that can be provided by data source modules is the
  163289. * resync_to_restart method for error recovery in the presence of RST markers.
  163290. * For the moment, this source module just uses the default resync method
  163291. * provided by the JPEG library. That method assumes that no backtracking
  163292. * is possible.
  163293. */
  163294. /*
  163295. * Terminate source --- called by jpeg_finish_decompress
  163296. * after all data has been read. Often a no-op.
  163297. *
  163298. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  163299. * application must deal with any cleanup that should happen even
  163300. * for error exit.
  163301. */
  163302. METHODDEF(void)
  163303. term_source (j_decompress_ptr cinfo)
  163304. {
  163305. /* no work necessary here */
  163306. }
  163307. /*
  163308. * Prepare for input from a stdio stream.
  163309. * The caller must have already opened the stream, and is responsible
  163310. * for closing it after finishing decompression.
  163311. */
  163312. GLOBAL(void)
  163313. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  163314. {
  163315. my_src_ptr src;
  163316. /* The source object and input buffer are made permanent so that a series
  163317. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  163318. * only before the first one. (If we discarded the buffer at the end of
  163319. * one image, we'd likely lose the start of the next one.)
  163320. * This makes it unsafe to use this manager and a different source
  163321. * manager serially with the same JPEG object. Caveat programmer.
  163322. */
  163323. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  163324. cinfo->src = (struct jpeg_source_mgr *)
  163325. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  163326. SIZEOF(my_source_mgr));
  163327. src = (my_src_ptr) cinfo->src;
  163328. src->buffer = (JOCTET *)
  163329. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  163330. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  163331. }
  163332. src = (my_src_ptr) cinfo->src;
  163333. src->pub.init_source = init_source;
  163334. src->pub.fill_input_buffer = fill_input_buffer;
  163335. src->pub.skip_input_data = skip_input_data;
  163336. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  163337. src->pub.term_source = term_source;
  163338. src->infile = infile;
  163339. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  163340. src->pub.next_input_byte = NULL; /* until buffer loaded */
  163341. }
  163342. /********* End of inlined file: jdatasrc.c *********/
  163343. /********* Start of inlined file: jdcoefct.c *********/
  163344. #define JPEG_INTERNALS
  163345. /* Block smoothing is only applicable for progressive JPEG, so: */
  163346. #ifndef D_PROGRESSIVE_SUPPORTED
  163347. #undef BLOCK_SMOOTHING_SUPPORTED
  163348. #endif
  163349. /* Private buffer controller object */
  163350. typedef struct {
  163351. struct jpeg_d_coef_controller pub; /* public fields */
  163352. /* These variables keep track of the current location of the input side. */
  163353. /* cinfo->input_iMCU_row is also used for this. */
  163354. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  163355. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  163356. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  163357. /* The output side's location is represented by cinfo->output_iMCU_row. */
  163358. /* In single-pass modes, it's sufficient to buffer just one MCU.
  163359. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  163360. * and let the entropy decoder write into that workspace each time.
  163361. * (On 80x86, the workspace is FAR even though it's not really very big;
  163362. * this is to keep the module interfaces unchanged when a large coefficient
  163363. * buffer is necessary.)
  163364. * In multi-pass modes, this array points to the current MCU's blocks
  163365. * within the virtual arrays; it is used only by the input side.
  163366. */
  163367. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  163368. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163369. /* In multi-pass modes, we need a virtual block array for each component. */
  163370. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  163371. #endif
  163372. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163373. /* When doing block smoothing, we latch coefficient Al values here */
  163374. int * coef_bits_latch;
  163375. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  163376. #endif
  163377. } my_coef_controller3;
  163378. typedef my_coef_controller3 * my_coef_ptr3;
  163379. /* Forward declarations */
  163380. METHODDEF(int) decompress_onepass
  163381. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  163382. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163383. METHODDEF(int) decompress_data
  163384. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  163385. #endif
  163386. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163387. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  163388. METHODDEF(int) decompress_smooth_data
  163389. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  163390. #endif
  163391. LOCAL(void)
  163392. start_iMCU_row3 (j_decompress_ptr cinfo)
  163393. /* Reset within-iMCU-row counters for a new row (input side) */
  163394. {
  163395. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  163396. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  163397. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  163398. * But at the bottom of the image, process only what's left.
  163399. */
  163400. if (cinfo->comps_in_scan > 1) {
  163401. coef->MCU_rows_per_iMCU_row = 1;
  163402. } else {
  163403. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  163404. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  163405. else
  163406. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  163407. }
  163408. coef->MCU_ctr = 0;
  163409. coef->MCU_vert_offset = 0;
  163410. }
  163411. /*
  163412. * Initialize for an input processing pass.
  163413. */
  163414. METHODDEF(void)
  163415. start_input_pass (j_decompress_ptr cinfo)
  163416. {
  163417. cinfo->input_iMCU_row = 0;
  163418. start_iMCU_row3(cinfo);
  163419. }
  163420. /*
  163421. * Initialize for an output processing pass.
  163422. */
  163423. METHODDEF(void)
  163424. start_output_pass (j_decompress_ptr cinfo)
  163425. {
  163426. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163427. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  163428. /* If multipass, check to see whether to use block smoothing on this pass */
  163429. if (coef->pub.coef_arrays != NULL) {
  163430. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  163431. coef->pub.decompress_data = decompress_smooth_data;
  163432. else
  163433. coef->pub.decompress_data = decompress_data;
  163434. }
  163435. #endif
  163436. cinfo->output_iMCU_row = 0;
  163437. }
  163438. /*
  163439. * Decompress and return some data in the single-pass case.
  163440. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  163441. * Input and output must run in lockstep since we have only a one-MCU buffer.
  163442. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  163443. *
  163444. * NB: output_buf contains a plane for each component in image,
  163445. * which we index according to the component's SOF position.
  163446. */
  163447. METHODDEF(int)
  163448. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  163449. {
  163450. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  163451. JDIMENSION MCU_col_num; /* index of current MCU within row */
  163452. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  163453. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  163454. int blkn, ci, xindex, yindex, yoffset, useful_width;
  163455. JSAMPARRAY output_ptr;
  163456. JDIMENSION start_col, output_col;
  163457. jpeg_component_info *compptr;
  163458. inverse_DCT_method_ptr inverse_DCT;
  163459. /* Loop to process as much as one whole iMCU row */
  163460. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  163461. yoffset++) {
  163462. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  163463. MCU_col_num++) {
  163464. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  163465. jzero_far((void FAR *) coef->MCU_buffer[0],
  163466. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  163467. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  163468. /* Suspension forced; update state counters and exit */
  163469. coef->MCU_vert_offset = yoffset;
  163470. coef->MCU_ctr = MCU_col_num;
  163471. return JPEG_SUSPENDED;
  163472. }
  163473. /* Determine where data should go in output_buf and do the IDCT thing.
  163474. * We skip dummy blocks at the right and bottom edges (but blkn gets
  163475. * incremented past them!). Note the inner loop relies on having
  163476. * allocated the MCU_buffer[] blocks sequentially.
  163477. */
  163478. blkn = 0; /* index of current DCT block within MCU */
  163479. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163480. compptr = cinfo->cur_comp_info[ci];
  163481. /* Don't bother to IDCT an uninteresting component. */
  163482. if (! compptr->component_needed) {
  163483. blkn += compptr->MCU_blocks;
  163484. continue;
  163485. }
  163486. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  163487. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  163488. : compptr->last_col_width;
  163489. output_ptr = output_buf[compptr->component_index] +
  163490. yoffset * compptr->DCT_scaled_size;
  163491. start_col = MCU_col_num * compptr->MCU_sample_width;
  163492. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  163493. if (cinfo->input_iMCU_row < last_iMCU_row ||
  163494. yoffset+yindex < compptr->last_row_height) {
  163495. output_col = start_col;
  163496. for (xindex = 0; xindex < useful_width; xindex++) {
  163497. (*inverse_DCT) (cinfo, compptr,
  163498. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  163499. output_ptr, output_col);
  163500. output_col += compptr->DCT_scaled_size;
  163501. }
  163502. }
  163503. blkn += compptr->MCU_width;
  163504. output_ptr += compptr->DCT_scaled_size;
  163505. }
  163506. }
  163507. }
  163508. /* Completed an MCU row, but perhaps not an iMCU row */
  163509. coef->MCU_ctr = 0;
  163510. }
  163511. /* Completed the iMCU row, advance counters for next one */
  163512. cinfo->output_iMCU_row++;
  163513. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  163514. start_iMCU_row3(cinfo);
  163515. return JPEG_ROW_COMPLETED;
  163516. }
  163517. /* Completed the scan */
  163518. (*cinfo->inputctl->finish_input_pass) (cinfo);
  163519. return JPEG_SCAN_COMPLETED;
  163520. }
  163521. /*
  163522. * Dummy consume-input routine for single-pass operation.
  163523. */
  163524. METHODDEF(int)
  163525. dummy_consume_data (j_decompress_ptr cinfo)
  163526. {
  163527. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  163528. }
  163529. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163530. /*
  163531. * Consume input data and store it in the full-image coefficient buffer.
  163532. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  163533. * ie, v_samp_factor block rows for each component in the scan.
  163534. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  163535. */
  163536. METHODDEF(int)
  163537. consume_data (j_decompress_ptr cinfo)
  163538. {
  163539. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  163540. JDIMENSION MCU_col_num; /* index of current MCU within row */
  163541. int blkn, ci, xindex, yindex, yoffset;
  163542. JDIMENSION start_col;
  163543. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  163544. JBLOCKROW buffer_ptr;
  163545. jpeg_component_info *compptr;
  163546. /* Align the virtual buffers for the components used in this scan. */
  163547. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163548. compptr = cinfo->cur_comp_info[ci];
  163549. buffer[ci] = (*cinfo->mem->access_virt_barray)
  163550. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  163551. cinfo->input_iMCU_row * compptr->v_samp_factor,
  163552. (JDIMENSION) compptr->v_samp_factor, TRUE);
  163553. /* Note: entropy decoder expects buffer to be zeroed,
  163554. * but this is handled automatically by the memory manager
  163555. * because we requested a pre-zeroed array.
  163556. */
  163557. }
  163558. /* Loop to process one whole iMCU row */
  163559. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  163560. yoffset++) {
  163561. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  163562. MCU_col_num++) {
  163563. /* Construct list of pointers to DCT blocks belonging to this MCU */
  163564. blkn = 0; /* index of current DCT block within MCU */
  163565. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163566. compptr = cinfo->cur_comp_info[ci];
  163567. start_col = MCU_col_num * compptr->MCU_width;
  163568. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  163569. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  163570. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  163571. coef->MCU_buffer[blkn++] = buffer_ptr++;
  163572. }
  163573. }
  163574. }
  163575. /* Try to fetch the MCU. */
  163576. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  163577. /* Suspension forced; update state counters and exit */
  163578. coef->MCU_vert_offset = yoffset;
  163579. coef->MCU_ctr = MCU_col_num;
  163580. return JPEG_SUSPENDED;
  163581. }
  163582. }
  163583. /* Completed an MCU row, but perhaps not an iMCU row */
  163584. coef->MCU_ctr = 0;
  163585. }
  163586. /* Completed the iMCU row, advance counters for next one */
  163587. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  163588. start_iMCU_row3(cinfo);
  163589. return JPEG_ROW_COMPLETED;
  163590. }
  163591. /* Completed the scan */
  163592. (*cinfo->inputctl->finish_input_pass) (cinfo);
  163593. return JPEG_SCAN_COMPLETED;
  163594. }
  163595. /*
  163596. * Decompress and return some data in the multi-pass case.
  163597. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  163598. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  163599. *
  163600. * NB: output_buf contains a plane for each component in image.
  163601. */
  163602. METHODDEF(int)
  163603. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  163604. {
  163605. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  163606. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  163607. JDIMENSION block_num;
  163608. int ci, block_row, block_rows;
  163609. JBLOCKARRAY buffer;
  163610. JBLOCKROW buffer_ptr;
  163611. JSAMPARRAY output_ptr;
  163612. JDIMENSION output_col;
  163613. jpeg_component_info *compptr;
  163614. inverse_DCT_method_ptr inverse_DCT;
  163615. /* Force some input to be done if we are getting ahead of the input. */
  163616. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  163617. (cinfo->input_scan_number == cinfo->output_scan_number &&
  163618. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  163619. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  163620. return JPEG_SUSPENDED;
  163621. }
  163622. /* OK, output from the virtual arrays. */
  163623. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163624. ci++, compptr++) {
  163625. /* Don't bother to IDCT an uninteresting component. */
  163626. if (! compptr->component_needed)
  163627. continue;
  163628. /* Align the virtual buffer for this component. */
  163629. buffer = (*cinfo->mem->access_virt_barray)
  163630. ((j_common_ptr) cinfo, coef->whole_image[ci],
  163631. cinfo->output_iMCU_row * compptr->v_samp_factor,
  163632. (JDIMENSION) compptr->v_samp_factor, FALSE);
  163633. /* Count non-dummy DCT block rows in this iMCU row. */
  163634. if (cinfo->output_iMCU_row < last_iMCU_row)
  163635. block_rows = compptr->v_samp_factor;
  163636. else {
  163637. /* NB: can't use last_row_height here; it is input-side-dependent! */
  163638. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  163639. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  163640. }
  163641. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  163642. output_ptr = output_buf[ci];
  163643. /* Loop over all DCT blocks to be processed. */
  163644. for (block_row = 0; block_row < block_rows; block_row++) {
  163645. buffer_ptr = buffer[block_row];
  163646. output_col = 0;
  163647. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  163648. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  163649. output_ptr, output_col);
  163650. buffer_ptr++;
  163651. output_col += compptr->DCT_scaled_size;
  163652. }
  163653. output_ptr += compptr->DCT_scaled_size;
  163654. }
  163655. }
  163656. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  163657. return JPEG_ROW_COMPLETED;
  163658. return JPEG_SCAN_COMPLETED;
  163659. }
  163660. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  163661. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163662. /*
  163663. * This code applies interblock smoothing as described by section K.8
  163664. * of the JPEG standard: the first 5 AC coefficients are estimated from
  163665. * the DC values of a DCT block and its 8 neighboring blocks.
  163666. * We apply smoothing only for progressive JPEG decoding, and only if
  163667. * the coefficients it can estimate are not yet known to full precision.
  163668. */
  163669. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  163670. #define Q01_POS 1
  163671. #define Q10_POS 8
  163672. #define Q20_POS 16
  163673. #define Q11_POS 9
  163674. #define Q02_POS 2
  163675. /*
  163676. * Determine whether block smoothing is applicable and safe.
  163677. * We also latch the current states of the coef_bits[] entries for the
  163678. * AC coefficients; otherwise, if the input side of the decompressor
  163679. * advances into a new scan, we might think the coefficients are known
  163680. * more accurately than they really are.
  163681. */
  163682. LOCAL(boolean)
  163683. smoothing_ok (j_decompress_ptr cinfo)
  163684. {
  163685. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  163686. boolean smoothing_useful = FALSE;
  163687. int ci, coefi;
  163688. jpeg_component_info *compptr;
  163689. JQUANT_TBL * qtable;
  163690. int * coef_bits;
  163691. int * coef_bits_latch;
  163692. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  163693. return FALSE;
  163694. /* Allocate latch area if not already done */
  163695. if (coef->coef_bits_latch == NULL)
  163696. coef->coef_bits_latch = (int *)
  163697. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163698. cinfo->num_components *
  163699. (SAVED_COEFS * SIZEOF(int)));
  163700. coef_bits_latch = coef->coef_bits_latch;
  163701. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163702. ci++, compptr++) {
  163703. /* All components' quantization values must already be latched. */
  163704. if ((qtable = compptr->quant_table) == NULL)
  163705. return FALSE;
  163706. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  163707. if (qtable->quantval[0] == 0 ||
  163708. qtable->quantval[Q01_POS] == 0 ||
  163709. qtable->quantval[Q10_POS] == 0 ||
  163710. qtable->quantval[Q20_POS] == 0 ||
  163711. qtable->quantval[Q11_POS] == 0 ||
  163712. qtable->quantval[Q02_POS] == 0)
  163713. return FALSE;
  163714. /* DC values must be at least partly known for all components. */
  163715. coef_bits = cinfo->coef_bits[ci];
  163716. if (coef_bits[0] < 0)
  163717. return FALSE;
  163718. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  163719. for (coefi = 1; coefi <= 5; coefi++) {
  163720. coef_bits_latch[coefi] = coef_bits[coefi];
  163721. if (coef_bits[coefi] != 0)
  163722. smoothing_useful = TRUE;
  163723. }
  163724. coef_bits_latch += SAVED_COEFS;
  163725. }
  163726. return smoothing_useful;
  163727. }
  163728. /*
  163729. * Variant of decompress_data for use when doing block smoothing.
  163730. */
  163731. METHODDEF(int)
  163732. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  163733. {
  163734. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  163735. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  163736. JDIMENSION block_num, last_block_column;
  163737. int ci, block_row, block_rows, access_rows;
  163738. JBLOCKARRAY buffer;
  163739. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  163740. JSAMPARRAY output_ptr;
  163741. JDIMENSION output_col;
  163742. jpeg_component_info *compptr;
  163743. inverse_DCT_method_ptr inverse_DCT;
  163744. boolean first_row, last_row;
  163745. JBLOCK workspace;
  163746. int *coef_bits;
  163747. JQUANT_TBL *quanttbl;
  163748. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  163749. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  163750. int Al, pred;
  163751. /* Force some input to be done if we are getting ahead of the input. */
  163752. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  163753. ! cinfo->inputctl->eoi_reached) {
  163754. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  163755. /* If input is working on current scan, we ordinarily want it to
  163756. * have completed the current row. But if input scan is DC,
  163757. * we want it to keep one row ahead so that next block row's DC
  163758. * values are up to date.
  163759. */
  163760. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  163761. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  163762. break;
  163763. }
  163764. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  163765. return JPEG_SUSPENDED;
  163766. }
  163767. /* OK, output from the virtual arrays. */
  163768. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163769. ci++, compptr++) {
  163770. /* Don't bother to IDCT an uninteresting component. */
  163771. if (! compptr->component_needed)
  163772. continue;
  163773. /* Count non-dummy DCT block rows in this iMCU row. */
  163774. if (cinfo->output_iMCU_row < last_iMCU_row) {
  163775. block_rows = compptr->v_samp_factor;
  163776. access_rows = block_rows * 2; /* this and next iMCU row */
  163777. last_row = FALSE;
  163778. } else {
  163779. /* NB: can't use last_row_height here; it is input-side-dependent! */
  163780. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  163781. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  163782. access_rows = block_rows; /* this iMCU row only */
  163783. last_row = TRUE;
  163784. }
  163785. /* Align the virtual buffer for this component. */
  163786. if (cinfo->output_iMCU_row > 0) {
  163787. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  163788. buffer = (*cinfo->mem->access_virt_barray)
  163789. ((j_common_ptr) cinfo, coef->whole_image[ci],
  163790. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  163791. (JDIMENSION) access_rows, FALSE);
  163792. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  163793. first_row = FALSE;
  163794. } else {
  163795. buffer = (*cinfo->mem->access_virt_barray)
  163796. ((j_common_ptr) cinfo, coef->whole_image[ci],
  163797. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  163798. first_row = TRUE;
  163799. }
  163800. /* Fetch component-dependent info */
  163801. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  163802. quanttbl = compptr->quant_table;
  163803. Q00 = quanttbl->quantval[0];
  163804. Q01 = quanttbl->quantval[Q01_POS];
  163805. Q10 = quanttbl->quantval[Q10_POS];
  163806. Q20 = quanttbl->quantval[Q20_POS];
  163807. Q11 = quanttbl->quantval[Q11_POS];
  163808. Q02 = quanttbl->quantval[Q02_POS];
  163809. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  163810. output_ptr = output_buf[ci];
  163811. /* Loop over all DCT blocks to be processed. */
  163812. for (block_row = 0; block_row < block_rows; block_row++) {
  163813. buffer_ptr = buffer[block_row];
  163814. if (first_row && block_row == 0)
  163815. prev_block_row = buffer_ptr;
  163816. else
  163817. prev_block_row = buffer[block_row-1];
  163818. if (last_row && block_row == block_rows-1)
  163819. next_block_row = buffer_ptr;
  163820. else
  163821. next_block_row = buffer[block_row+1];
  163822. /* We fetch the surrounding DC values using a sliding-register approach.
  163823. * Initialize all nine here so as to do the right thing on narrow pics.
  163824. */
  163825. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  163826. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  163827. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  163828. output_col = 0;
  163829. last_block_column = compptr->width_in_blocks - 1;
  163830. for (block_num = 0; block_num <= last_block_column; block_num++) {
  163831. /* Fetch current DCT block into workspace so we can modify it. */
  163832. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  163833. /* Update DC values */
  163834. if (block_num < last_block_column) {
  163835. DC3 = (int) prev_block_row[1][0];
  163836. DC6 = (int) buffer_ptr[1][0];
  163837. DC9 = (int) next_block_row[1][0];
  163838. }
  163839. /* Compute coefficient estimates per K.8.
  163840. * An estimate is applied only if coefficient is still zero,
  163841. * and is not known to be fully accurate.
  163842. */
  163843. /* AC01 */
  163844. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  163845. num = 36 * Q00 * (DC4 - DC6);
  163846. if (num >= 0) {
  163847. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  163848. if (Al > 0 && pred >= (1<<Al))
  163849. pred = (1<<Al)-1;
  163850. } else {
  163851. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  163852. if (Al > 0 && pred >= (1<<Al))
  163853. pred = (1<<Al)-1;
  163854. pred = -pred;
  163855. }
  163856. workspace[1] = (JCOEF) pred;
  163857. }
  163858. /* AC10 */
  163859. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  163860. num = 36 * Q00 * (DC2 - DC8);
  163861. if (num >= 0) {
  163862. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  163863. if (Al > 0 && pred >= (1<<Al))
  163864. pred = (1<<Al)-1;
  163865. } else {
  163866. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  163867. if (Al > 0 && pred >= (1<<Al))
  163868. pred = (1<<Al)-1;
  163869. pred = -pred;
  163870. }
  163871. workspace[8] = (JCOEF) pred;
  163872. }
  163873. /* AC20 */
  163874. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  163875. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  163876. if (num >= 0) {
  163877. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  163878. if (Al > 0 && pred >= (1<<Al))
  163879. pred = (1<<Al)-1;
  163880. } else {
  163881. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  163882. if (Al > 0 && pred >= (1<<Al))
  163883. pred = (1<<Al)-1;
  163884. pred = -pred;
  163885. }
  163886. workspace[16] = (JCOEF) pred;
  163887. }
  163888. /* AC11 */
  163889. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  163890. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  163891. if (num >= 0) {
  163892. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  163893. if (Al > 0 && pred >= (1<<Al))
  163894. pred = (1<<Al)-1;
  163895. } else {
  163896. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  163897. if (Al > 0 && pred >= (1<<Al))
  163898. pred = (1<<Al)-1;
  163899. pred = -pred;
  163900. }
  163901. workspace[9] = (JCOEF) pred;
  163902. }
  163903. /* AC02 */
  163904. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  163905. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  163906. if (num >= 0) {
  163907. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  163908. if (Al > 0 && pred >= (1<<Al))
  163909. pred = (1<<Al)-1;
  163910. } else {
  163911. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  163912. if (Al > 0 && pred >= (1<<Al))
  163913. pred = (1<<Al)-1;
  163914. pred = -pred;
  163915. }
  163916. workspace[2] = (JCOEF) pred;
  163917. }
  163918. /* OK, do the IDCT */
  163919. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  163920. output_ptr, output_col);
  163921. /* Advance for next column */
  163922. DC1 = DC2; DC2 = DC3;
  163923. DC4 = DC5; DC5 = DC6;
  163924. DC7 = DC8; DC8 = DC9;
  163925. buffer_ptr++, prev_block_row++, next_block_row++;
  163926. output_col += compptr->DCT_scaled_size;
  163927. }
  163928. output_ptr += compptr->DCT_scaled_size;
  163929. }
  163930. }
  163931. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  163932. return JPEG_ROW_COMPLETED;
  163933. return JPEG_SCAN_COMPLETED;
  163934. }
  163935. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  163936. /*
  163937. * Initialize coefficient buffer controller.
  163938. */
  163939. GLOBAL(void)
  163940. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  163941. {
  163942. my_coef_ptr3 coef;
  163943. coef = (my_coef_ptr3)
  163944. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163945. SIZEOF(my_coef_controller3));
  163946. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  163947. coef->pub.start_input_pass = start_input_pass;
  163948. coef->pub.start_output_pass = start_output_pass;
  163949. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163950. coef->coef_bits_latch = NULL;
  163951. #endif
  163952. /* Create the coefficient buffer. */
  163953. if (need_full_buffer) {
  163954. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163955. /* Allocate a full-image virtual array for each component, */
  163956. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  163957. /* Note we ask for a pre-zeroed array. */
  163958. int ci, access_rows;
  163959. jpeg_component_info *compptr;
  163960. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163961. ci++, compptr++) {
  163962. access_rows = compptr->v_samp_factor;
  163963. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163964. /* If block smoothing could be used, need a bigger window */
  163965. if (cinfo->progressive_mode)
  163966. access_rows *= 3;
  163967. #endif
  163968. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  163969. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  163970. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  163971. (long) compptr->h_samp_factor),
  163972. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163973. (long) compptr->v_samp_factor),
  163974. (JDIMENSION) access_rows);
  163975. }
  163976. coef->pub.consume_data = consume_data;
  163977. coef->pub.decompress_data = decompress_data;
  163978. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  163979. #else
  163980. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163981. #endif
  163982. } else {
  163983. /* We only need a single-MCU buffer. */
  163984. JBLOCKROW buffer;
  163985. int i;
  163986. buffer = (JBLOCKROW)
  163987. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163988. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163989. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  163990. coef->MCU_buffer[i] = buffer + i;
  163991. }
  163992. coef->pub.consume_data = dummy_consume_data;
  163993. coef->pub.decompress_data = decompress_onepass;
  163994. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  163995. }
  163996. }
  163997. /********* End of inlined file: jdcoefct.c *********/
  163998. #undef FIX
  163999. /********* Start of inlined file: jdcolor.c *********/
  164000. #define JPEG_INTERNALS
  164001. /* Private subobject */
  164002. typedef struct {
  164003. struct jpeg_color_deconverter pub; /* public fields */
  164004. /* Private state for YCC->RGB conversion */
  164005. int * Cr_r_tab; /* => table for Cr to R conversion */
  164006. int * Cb_b_tab; /* => table for Cb to B conversion */
  164007. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  164008. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  164009. } my_color_deconverter2;
  164010. typedef my_color_deconverter2 * my_cconvert_ptr2;
  164011. /**************** YCbCr -> RGB conversion: most common case **************/
  164012. /*
  164013. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  164014. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  164015. * The conversion equations to be implemented are therefore
  164016. * R = Y + 1.40200 * Cr
  164017. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  164018. * B = Y + 1.77200 * Cb
  164019. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  164020. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  164021. *
  164022. * To avoid floating-point arithmetic, we represent the fractional constants
  164023. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  164024. * the products by 2^16, with appropriate rounding, to get the correct answer.
  164025. * Notice that Y, being an integral input, does not contribute any fraction
  164026. * so it need not participate in the rounding.
  164027. *
  164028. * For even more speed, we avoid doing any multiplications in the inner loop
  164029. * by precalculating the constants times Cb and Cr for all possible values.
  164030. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  164031. * for 12-bit samples it is still acceptable. It's not very reasonable for
  164032. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  164033. * colorspace anyway.
  164034. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  164035. * values for the G calculation are left scaled up, since we must add them
  164036. * together before rounding.
  164037. */
  164038. #define SCALEBITS 16 /* speediest right-shift on some machines */
  164039. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  164040. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  164041. /*
  164042. * Initialize tables for YCC->RGB colorspace conversion.
  164043. */
  164044. LOCAL(void)
  164045. build_ycc_rgb_table (j_decompress_ptr cinfo)
  164046. {
  164047. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164048. int i;
  164049. INT32 x;
  164050. SHIFT_TEMPS
  164051. cconvert->Cr_r_tab = (int *)
  164052. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164053. (MAXJSAMPLE+1) * SIZEOF(int));
  164054. cconvert->Cb_b_tab = (int *)
  164055. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164056. (MAXJSAMPLE+1) * SIZEOF(int));
  164057. cconvert->Cr_g_tab = (INT32 *)
  164058. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164059. (MAXJSAMPLE+1) * SIZEOF(INT32));
  164060. cconvert->Cb_g_tab = (INT32 *)
  164061. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164062. (MAXJSAMPLE+1) * SIZEOF(INT32));
  164063. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  164064. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  164065. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  164066. /* Cr=>R value is nearest int to 1.40200 * x */
  164067. cconvert->Cr_r_tab[i] = (int)
  164068. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  164069. /* Cb=>B value is nearest int to 1.77200 * x */
  164070. cconvert->Cb_b_tab[i] = (int)
  164071. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  164072. /* Cr=>G value is scaled-up -0.71414 * x */
  164073. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  164074. /* Cb=>G value is scaled-up -0.34414 * x */
  164075. /* We also add in ONE_HALF so that need not do it in inner loop */
  164076. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  164077. }
  164078. }
  164079. /*
  164080. * Convert some rows of samples to the output colorspace.
  164081. *
  164082. * Note that we change from noninterleaved, one-plane-per-component format
  164083. * to interleaved-pixel format. The output buffer is therefore three times
  164084. * as wide as the input buffer.
  164085. * A starting row offset is provided only for the input buffer. The caller
  164086. * can easily adjust the passed output_buf value to accommodate any row
  164087. * offset required on that side.
  164088. */
  164089. METHODDEF(void)
  164090. ycc_rgb_convert (j_decompress_ptr cinfo,
  164091. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164092. JSAMPARRAY output_buf, int num_rows)
  164093. {
  164094. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164095. register int y, cb, cr;
  164096. register JSAMPROW outptr;
  164097. register JSAMPROW inptr0, inptr1, inptr2;
  164098. register JDIMENSION col;
  164099. JDIMENSION num_cols = cinfo->output_width;
  164100. /* copy these pointers into registers if possible */
  164101. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  164102. register int * Crrtab = cconvert->Cr_r_tab;
  164103. register int * Cbbtab = cconvert->Cb_b_tab;
  164104. register INT32 * Crgtab = cconvert->Cr_g_tab;
  164105. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  164106. SHIFT_TEMPS
  164107. while (--num_rows >= 0) {
  164108. inptr0 = input_buf[0][input_row];
  164109. inptr1 = input_buf[1][input_row];
  164110. inptr2 = input_buf[2][input_row];
  164111. input_row++;
  164112. outptr = *output_buf++;
  164113. for (col = 0; col < num_cols; col++) {
  164114. y = GETJSAMPLE(inptr0[col]);
  164115. cb = GETJSAMPLE(inptr1[col]);
  164116. cr = GETJSAMPLE(inptr2[col]);
  164117. /* Range-limiting is essential due to noise introduced by DCT losses. */
  164118. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  164119. outptr[RGB_GREEN] = range_limit[y +
  164120. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  164121. SCALEBITS))];
  164122. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  164123. outptr += RGB_PIXELSIZE;
  164124. }
  164125. }
  164126. }
  164127. /**************** Cases other than YCbCr -> RGB **************/
  164128. /*
  164129. * Color conversion for no colorspace change: just copy the data,
  164130. * converting from separate-planes to interleaved representation.
  164131. */
  164132. METHODDEF(void)
  164133. null_convert2 (j_decompress_ptr cinfo,
  164134. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164135. JSAMPARRAY output_buf, int num_rows)
  164136. {
  164137. register JSAMPROW inptr, outptr;
  164138. register JDIMENSION count;
  164139. register int num_components = cinfo->num_components;
  164140. JDIMENSION num_cols = cinfo->output_width;
  164141. int ci;
  164142. while (--num_rows >= 0) {
  164143. for (ci = 0; ci < num_components; ci++) {
  164144. inptr = input_buf[ci][input_row];
  164145. outptr = output_buf[0] + ci;
  164146. for (count = num_cols; count > 0; count--) {
  164147. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  164148. outptr += num_components;
  164149. }
  164150. }
  164151. input_row++;
  164152. output_buf++;
  164153. }
  164154. }
  164155. /*
  164156. * Color conversion for grayscale: just copy the data.
  164157. * This also works for YCbCr -> grayscale conversion, in which
  164158. * we just copy the Y (luminance) component and ignore chrominance.
  164159. */
  164160. METHODDEF(void)
  164161. grayscale_convert2 (j_decompress_ptr cinfo,
  164162. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164163. JSAMPARRAY output_buf, int num_rows)
  164164. {
  164165. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  164166. num_rows, cinfo->output_width);
  164167. }
  164168. /*
  164169. * Convert grayscale to RGB: just duplicate the graylevel three times.
  164170. * This is provided to support applications that don't want to cope
  164171. * with grayscale as a separate case.
  164172. */
  164173. METHODDEF(void)
  164174. gray_rgb_convert (j_decompress_ptr cinfo,
  164175. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164176. JSAMPARRAY output_buf, int num_rows)
  164177. {
  164178. register JSAMPROW inptr, outptr;
  164179. register JDIMENSION col;
  164180. JDIMENSION num_cols = cinfo->output_width;
  164181. while (--num_rows >= 0) {
  164182. inptr = input_buf[0][input_row++];
  164183. outptr = *output_buf++;
  164184. for (col = 0; col < num_cols; col++) {
  164185. /* We can dispense with GETJSAMPLE() here */
  164186. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  164187. outptr += RGB_PIXELSIZE;
  164188. }
  164189. }
  164190. }
  164191. /*
  164192. * Adobe-style YCCK->CMYK conversion.
  164193. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  164194. * conversion as above, while passing K (black) unchanged.
  164195. * We assume build_ycc_rgb_table has been called.
  164196. */
  164197. METHODDEF(void)
  164198. ycck_cmyk_convert (j_decompress_ptr cinfo,
  164199. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164200. JSAMPARRAY output_buf, int num_rows)
  164201. {
  164202. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164203. register int y, cb, cr;
  164204. register JSAMPROW outptr;
  164205. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  164206. register JDIMENSION col;
  164207. JDIMENSION num_cols = cinfo->output_width;
  164208. /* copy these pointers into registers if possible */
  164209. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  164210. register int * Crrtab = cconvert->Cr_r_tab;
  164211. register int * Cbbtab = cconvert->Cb_b_tab;
  164212. register INT32 * Crgtab = cconvert->Cr_g_tab;
  164213. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  164214. SHIFT_TEMPS
  164215. while (--num_rows >= 0) {
  164216. inptr0 = input_buf[0][input_row];
  164217. inptr1 = input_buf[1][input_row];
  164218. inptr2 = input_buf[2][input_row];
  164219. inptr3 = input_buf[3][input_row];
  164220. input_row++;
  164221. outptr = *output_buf++;
  164222. for (col = 0; col < num_cols; col++) {
  164223. y = GETJSAMPLE(inptr0[col]);
  164224. cb = GETJSAMPLE(inptr1[col]);
  164225. cr = GETJSAMPLE(inptr2[col]);
  164226. /* Range-limiting is essential due to noise introduced by DCT losses. */
  164227. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  164228. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  164229. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  164230. SCALEBITS)))];
  164231. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  164232. /* K passes through unchanged */
  164233. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  164234. outptr += 4;
  164235. }
  164236. }
  164237. }
  164238. /*
  164239. * Empty method for start_pass.
  164240. */
  164241. METHODDEF(void)
  164242. start_pass_dcolor (j_decompress_ptr cinfo)
  164243. {
  164244. /* no work needed */
  164245. }
  164246. /*
  164247. * Module initialization routine for output colorspace conversion.
  164248. */
  164249. GLOBAL(void)
  164250. jinit_color_deconverter (j_decompress_ptr cinfo)
  164251. {
  164252. my_cconvert_ptr2 cconvert;
  164253. int ci;
  164254. cconvert = (my_cconvert_ptr2)
  164255. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164256. SIZEOF(my_color_deconverter2));
  164257. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  164258. cconvert->pub.start_pass = start_pass_dcolor;
  164259. /* Make sure num_components agrees with jpeg_color_space */
  164260. switch (cinfo->jpeg_color_space) {
  164261. case JCS_GRAYSCALE:
  164262. if (cinfo->num_components != 1)
  164263. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164264. break;
  164265. case JCS_RGB:
  164266. case JCS_YCbCr:
  164267. if (cinfo->num_components != 3)
  164268. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164269. break;
  164270. case JCS_CMYK:
  164271. case JCS_YCCK:
  164272. if (cinfo->num_components != 4)
  164273. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164274. break;
  164275. default: /* JCS_UNKNOWN can be anything */
  164276. if (cinfo->num_components < 1)
  164277. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164278. break;
  164279. }
  164280. /* Set out_color_components and conversion method based on requested space.
  164281. * Also clear the component_needed flags for any unused components,
  164282. * so that earlier pipeline stages can avoid useless computation.
  164283. */
  164284. switch (cinfo->out_color_space) {
  164285. case JCS_GRAYSCALE:
  164286. cinfo->out_color_components = 1;
  164287. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  164288. cinfo->jpeg_color_space == JCS_YCbCr) {
  164289. cconvert->pub.color_convert = grayscale_convert2;
  164290. /* For color->grayscale conversion, only the Y (0) component is needed */
  164291. for (ci = 1; ci < cinfo->num_components; ci++)
  164292. cinfo->comp_info[ci].component_needed = FALSE;
  164293. } else
  164294. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  164295. break;
  164296. case JCS_RGB:
  164297. cinfo->out_color_components = RGB_PIXELSIZE;
  164298. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  164299. cconvert->pub.color_convert = ycc_rgb_convert;
  164300. build_ycc_rgb_table(cinfo);
  164301. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  164302. cconvert->pub.color_convert = gray_rgb_convert;
  164303. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  164304. cconvert->pub.color_convert = null_convert2;
  164305. } else
  164306. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  164307. break;
  164308. case JCS_CMYK:
  164309. cinfo->out_color_components = 4;
  164310. if (cinfo->jpeg_color_space == JCS_YCCK) {
  164311. cconvert->pub.color_convert = ycck_cmyk_convert;
  164312. build_ycc_rgb_table(cinfo);
  164313. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  164314. cconvert->pub.color_convert = null_convert2;
  164315. } else
  164316. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  164317. break;
  164318. default:
  164319. /* Permit null conversion to same output space */
  164320. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  164321. cinfo->out_color_components = cinfo->num_components;
  164322. cconvert->pub.color_convert = null_convert2;
  164323. } else /* unsupported non-null conversion */
  164324. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  164325. break;
  164326. }
  164327. if (cinfo->quantize_colors)
  164328. cinfo->output_components = 1; /* single colormapped output component */
  164329. else
  164330. cinfo->output_components = cinfo->out_color_components;
  164331. }
  164332. /********* End of inlined file: jdcolor.c *********/
  164333. #undef FIX
  164334. /********* Start of inlined file: jddctmgr.c *********/
  164335. #define JPEG_INTERNALS
  164336. /*
  164337. * The decompressor input side (jdinput.c) saves away the appropriate
  164338. * quantization table for each component at the start of the first scan
  164339. * involving that component. (This is necessary in order to correctly
  164340. * decode files that reuse Q-table slots.)
  164341. * When we are ready to make an output pass, the saved Q-table is converted
  164342. * to a multiplier table that will actually be used by the IDCT routine.
  164343. * The multiplier table contents are IDCT-method-dependent. To support
  164344. * application changes in IDCT method between scans, we can remake the
  164345. * multiplier tables if necessary.
  164346. * In buffered-image mode, the first output pass may occur before any data
  164347. * has been seen for some components, and thus before their Q-tables have
  164348. * been saved away. To handle this case, multiplier tables are preset
  164349. * to zeroes; the result of the IDCT will be a neutral gray level.
  164350. */
  164351. /* Private subobject for this module */
  164352. typedef struct {
  164353. struct jpeg_inverse_dct pub; /* public fields */
  164354. /* This array contains the IDCT method code that each multiplier table
  164355. * is currently set up for, or -1 if it's not yet set up.
  164356. * The actual multiplier tables are pointed to by dct_table in the
  164357. * per-component comp_info structures.
  164358. */
  164359. int cur_method[MAX_COMPONENTS];
  164360. } my_idct_controller;
  164361. typedef my_idct_controller * my_idct_ptr;
  164362. /* Allocated multiplier tables: big enough for any supported variant */
  164363. typedef union {
  164364. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  164365. #ifdef DCT_IFAST_SUPPORTED
  164366. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  164367. #endif
  164368. #ifdef DCT_FLOAT_SUPPORTED
  164369. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  164370. #endif
  164371. } multiplier_table;
  164372. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  164373. * so be sure to compile that code if either ISLOW or SCALING is requested.
  164374. */
  164375. #ifdef DCT_ISLOW_SUPPORTED
  164376. #define PROVIDE_ISLOW_TABLES
  164377. #else
  164378. #ifdef IDCT_SCALING_SUPPORTED
  164379. #define PROVIDE_ISLOW_TABLES
  164380. #endif
  164381. #endif
  164382. /*
  164383. * Prepare for an output pass.
  164384. * Here we select the proper IDCT routine for each component and build
  164385. * a matching multiplier table.
  164386. */
  164387. METHODDEF(void)
  164388. start_pass (j_decompress_ptr cinfo)
  164389. {
  164390. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  164391. int ci, i;
  164392. jpeg_component_info *compptr;
  164393. int method = 0;
  164394. inverse_DCT_method_ptr method_ptr = NULL;
  164395. JQUANT_TBL * qtbl;
  164396. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164397. ci++, compptr++) {
  164398. /* Select the proper IDCT routine for this component's scaling */
  164399. switch (compptr->DCT_scaled_size) {
  164400. #ifdef IDCT_SCALING_SUPPORTED
  164401. case 1:
  164402. method_ptr = jpeg_idct_1x1;
  164403. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  164404. break;
  164405. case 2:
  164406. method_ptr = jpeg_idct_2x2;
  164407. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  164408. break;
  164409. case 4:
  164410. method_ptr = jpeg_idct_4x4;
  164411. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  164412. break;
  164413. #endif
  164414. case DCTSIZE:
  164415. switch (cinfo->dct_method) {
  164416. #ifdef DCT_ISLOW_SUPPORTED
  164417. case JDCT_ISLOW:
  164418. method_ptr = jpeg_idct_islow;
  164419. method = JDCT_ISLOW;
  164420. break;
  164421. #endif
  164422. #ifdef DCT_IFAST_SUPPORTED
  164423. case JDCT_IFAST:
  164424. method_ptr = jpeg_idct_ifast;
  164425. method = JDCT_IFAST;
  164426. break;
  164427. #endif
  164428. #ifdef DCT_FLOAT_SUPPORTED
  164429. case JDCT_FLOAT:
  164430. method_ptr = jpeg_idct_float;
  164431. method = JDCT_FLOAT;
  164432. break;
  164433. #endif
  164434. default:
  164435. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164436. break;
  164437. }
  164438. break;
  164439. default:
  164440. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  164441. break;
  164442. }
  164443. idct->pub.inverse_DCT[ci] = method_ptr;
  164444. /* Create multiplier table from quant table.
  164445. * However, we can skip this if the component is uninteresting
  164446. * or if we already built the table. Also, if no quant table
  164447. * has yet been saved for the component, we leave the
  164448. * multiplier table all-zero; we'll be reading zeroes from the
  164449. * coefficient controller's buffer anyway.
  164450. */
  164451. if (! compptr->component_needed || idct->cur_method[ci] == method)
  164452. continue;
  164453. qtbl = compptr->quant_table;
  164454. if (qtbl == NULL) /* happens if no data yet for component */
  164455. continue;
  164456. idct->cur_method[ci] = method;
  164457. switch (method) {
  164458. #ifdef PROVIDE_ISLOW_TABLES
  164459. case JDCT_ISLOW:
  164460. {
  164461. /* For LL&M IDCT method, multipliers are equal to raw quantization
  164462. * coefficients, but are stored as ints to ensure access efficiency.
  164463. */
  164464. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  164465. for (i = 0; i < DCTSIZE2; i++) {
  164466. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  164467. }
  164468. }
  164469. break;
  164470. #endif
  164471. #ifdef DCT_IFAST_SUPPORTED
  164472. case JDCT_IFAST:
  164473. {
  164474. /* For AA&N IDCT method, multipliers are equal to quantization
  164475. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  164476. * scalefactor[0] = 1
  164477. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  164478. * For integer operation, the multiplier table is to be scaled by
  164479. * IFAST_SCALE_BITS.
  164480. */
  164481. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  164482. #define CONST_BITS 14
  164483. static const INT16 aanscales[DCTSIZE2] = {
  164484. /* precomputed values scaled up by 14 bits */
  164485. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  164486. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  164487. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  164488. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  164489. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  164490. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  164491. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  164492. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  164493. };
  164494. SHIFT_TEMPS
  164495. for (i = 0; i < DCTSIZE2; i++) {
  164496. ifmtbl[i] = (IFAST_MULT_TYPE)
  164497. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  164498. (INT32) aanscales[i]),
  164499. CONST_BITS-IFAST_SCALE_BITS);
  164500. }
  164501. }
  164502. break;
  164503. #endif
  164504. #ifdef DCT_FLOAT_SUPPORTED
  164505. case JDCT_FLOAT:
  164506. {
  164507. /* For float AA&N IDCT method, multipliers are equal to quantization
  164508. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  164509. * scalefactor[0] = 1
  164510. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  164511. */
  164512. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  164513. int row, col;
  164514. static const double aanscalefactor[DCTSIZE] = {
  164515. 1.0, 1.387039845, 1.306562965, 1.175875602,
  164516. 1.0, 0.785694958, 0.541196100, 0.275899379
  164517. };
  164518. i = 0;
  164519. for (row = 0; row < DCTSIZE; row++) {
  164520. for (col = 0; col < DCTSIZE; col++) {
  164521. fmtbl[i] = (FLOAT_MULT_TYPE)
  164522. ((double) qtbl->quantval[i] *
  164523. aanscalefactor[row] * aanscalefactor[col]);
  164524. i++;
  164525. }
  164526. }
  164527. }
  164528. break;
  164529. #endif
  164530. default:
  164531. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164532. break;
  164533. }
  164534. }
  164535. }
  164536. /*
  164537. * Initialize IDCT manager.
  164538. */
  164539. GLOBAL(void)
  164540. jinit_inverse_dct (j_decompress_ptr cinfo)
  164541. {
  164542. my_idct_ptr idct;
  164543. int ci;
  164544. jpeg_component_info *compptr;
  164545. idct = (my_idct_ptr)
  164546. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164547. SIZEOF(my_idct_controller));
  164548. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  164549. idct->pub.start_pass = start_pass;
  164550. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164551. ci++, compptr++) {
  164552. /* Allocate and pre-zero a multiplier table for each component */
  164553. compptr->dct_table =
  164554. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164555. SIZEOF(multiplier_table));
  164556. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  164557. /* Mark multiplier table not yet set up for any method */
  164558. idct->cur_method[ci] = -1;
  164559. }
  164560. }
  164561. /********* End of inlined file: jddctmgr.c *********/
  164562. #undef CONST_BITS
  164563. #undef ASSIGN_STATE
  164564. /********* Start of inlined file: jdhuff.c *********/
  164565. #define JPEG_INTERNALS
  164566. /********* Start of inlined file: jdhuff.h *********/
  164567. /* Short forms of external names for systems with brain-damaged linkers. */
  164568. #ifndef __jdhuff_h__
  164569. #define __jdhuff_h__
  164570. #ifdef NEED_SHORT_EXTERNAL_NAMES
  164571. #define jpeg_make_d_derived_tbl jMkDDerived
  164572. #define jpeg_fill_bit_buffer jFilBitBuf
  164573. #define jpeg_huff_decode jHufDecode
  164574. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  164575. /* Derived data constructed for each Huffman table */
  164576. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  164577. typedef struct {
  164578. /* Basic tables: (element [0] of each array is unused) */
  164579. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  164580. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  164581. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  164582. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  164583. * the smallest code of length k; so given a code of length k, the
  164584. * corresponding symbol is huffval[code + valoffset[k]]
  164585. */
  164586. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  164587. JHUFF_TBL *pub;
  164588. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  164589. * the input data stream. If the next Huffman code is no more
  164590. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  164591. * the corresponding symbol directly from these tables.
  164592. */
  164593. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  164594. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  164595. } d_derived_tbl;
  164596. /* Expand a Huffman table definition into the derived format */
  164597. EXTERN(void) jpeg_make_d_derived_tbl
  164598. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  164599. d_derived_tbl ** pdtbl));
  164600. /*
  164601. * Fetching the next N bits from the input stream is a time-critical operation
  164602. * for the Huffman decoders. We implement it with a combination of inline
  164603. * macros and out-of-line subroutines. Note that N (the number of bits
  164604. * demanded at one time) never exceeds 15 for JPEG use.
  164605. *
  164606. * We read source bytes into get_buffer and dole out bits as needed.
  164607. * If get_buffer already contains enough bits, they are fetched in-line
  164608. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  164609. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  164610. * as full as possible (not just to the number of bits needed; this
  164611. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  164612. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  164613. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  164614. * at least the requested number of bits --- dummy zeroes are inserted if
  164615. * necessary.
  164616. */
  164617. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  164618. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  164619. /* If long is > 32 bits on your machine, and shifting/masking longs is
  164620. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  164621. * appropriately should be a win. Unfortunately we can't define the size
  164622. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  164623. * because not all machines measure sizeof in 8-bit bytes.
  164624. */
  164625. typedef struct { /* Bitreading state saved across MCUs */
  164626. bit_buf_type get_buffer; /* current bit-extraction buffer */
  164627. int bits_left; /* # of unused bits in it */
  164628. } bitread_perm_state;
  164629. typedef struct { /* Bitreading working state within an MCU */
  164630. /* Current data source location */
  164631. /* We need a copy, rather than munging the original, in case of suspension */
  164632. const JOCTET * next_input_byte; /* => next byte to read from source */
  164633. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  164634. /* Bit input buffer --- note these values are kept in register variables,
  164635. * not in this struct, inside the inner loops.
  164636. */
  164637. bit_buf_type get_buffer; /* current bit-extraction buffer */
  164638. int bits_left; /* # of unused bits in it */
  164639. /* Pointer needed by jpeg_fill_bit_buffer. */
  164640. j_decompress_ptr cinfo; /* back link to decompress master record */
  164641. } bitread_working_state;
  164642. /* Macros to declare and load/save bitread local variables. */
  164643. #define BITREAD_STATE_VARS \
  164644. register bit_buf_type get_buffer; \
  164645. register int bits_left; \
  164646. bitread_working_state br_state
  164647. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  164648. br_state.cinfo = cinfop; \
  164649. br_state.next_input_byte = cinfop->src->next_input_byte; \
  164650. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  164651. get_buffer = permstate.get_buffer; \
  164652. bits_left = permstate.bits_left;
  164653. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  164654. cinfop->src->next_input_byte = br_state.next_input_byte; \
  164655. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  164656. permstate.get_buffer = get_buffer; \
  164657. permstate.bits_left = bits_left
  164658. /*
  164659. * These macros provide the in-line portion of bit fetching.
  164660. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  164661. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  164662. * The variables get_buffer and bits_left are assumed to be locals,
  164663. * but the state struct might not be (jpeg_huff_decode needs this).
  164664. * CHECK_BIT_BUFFER(state,n,action);
  164665. * Ensure there are N bits in get_buffer; if suspend, take action.
  164666. * val = GET_BITS(n);
  164667. * Fetch next N bits.
  164668. * val = PEEK_BITS(n);
  164669. * Fetch next N bits without removing them from the buffer.
  164670. * DROP_BITS(n);
  164671. * Discard next N bits.
  164672. * The value N should be a simple variable, not an expression, because it
  164673. * is evaluated multiple times.
  164674. */
  164675. #define CHECK_BIT_BUFFER(state,nbits,action) \
  164676. { if (bits_left < (nbits)) { \
  164677. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  164678. { action; } \
  164679. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  164680. #define GET_BITS(nbits) \
  164681. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  164682. #define PEEK_BITS(nbits) \
  164683. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  164684. #define DROP_BITS(nbits) \
  164685. (bits_left -= (nbits))
  164686. /* Load up the bit buffer to a depth of at least nbits */
  164687. EXTERN(boolean) jpeg_fill_bit_buffer
  164688. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  164689. register int bits_left, int nbits));
  164690. /*
  164691. * Code for extracting next Huffman-coded symbol from input bit stream.
  164692. * Again, this is time-critical and we make the main paths be macros.
  164693. *
  164694. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  164695. * without looping. Usually, more than 95% of the Huffman codes will be 8
  164696. * or fewer bits long. The few overlength codes are handled with a loop,
  164697. * which need not be inline code.
  164698. *
  164699. * Notes about the HUFF_DECODE macro:
  164700. * 1. Near the end of the data segment, we may fail to get enough bits
  164701. * for a lookahead. In that case, we do it the hard way.
  164702. * 2. If the lookahead table contains no entry, the next code must be
  164703. * more than HUFF_LOOKAHEAD bits long.
  164704. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  164705. */
  164706. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  164707. { register int nb, look; \
  164708. if (bits_left < HUFF_LOOKAHEAD) { \
  164709. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  164710. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  164711. if (bits_left < HUFF_LOOKAHEAD) { \
  164712. nb = 1; goto slowlabel; \
  164713. } \
  164714. } \
  164715. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  164716. if ((nb = htbl->look_nbits[look]) != 0) { \
  164717. DROP_BITS(nb); \
  164718. result = htbl->look_sym[look]; \
  164719. } else { \
  164720. nb = HUFF_LOOKAHEAD+1; \
  164721. slowlabel: \
  164722. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  164723. { failaction; } \
  164724. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  164725. } \
  164726. }
  164727. /* Out-of-line case for Huffman code fetching */
  164728. EXTERN(int) jpeg_huff_decode
  164729. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  164730. register int bits_left, d_derived_tbl * htbl, int min_bits));
  164731. #endif
  164732. /********* End of inlined file: jdhuff.h *********/
  164733. /* Declarations shared with jdphuff.c */
  164734. /*
  164735. * Expanded entropy decoder object for Huffman decoding.
  164736. *
  164737. * The savable_state subrecord contains fields that change within an MCU,
  164738. * but must not be updated permanently until we complete the MCU.
  164739. */
  164740. typedef struct {
  164741. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  164742. } savable_state2;
  164743. /* This macro is to work around compilers with missing or broken
  164744. * structure assignment. You'll need to fix this code if you have
  164745. * such a compiler and you change MAX_COMPS_IN_SCAN.
  164746. */
  164747. #ifndef NO_STRUCT_ASSIGN
  164748. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  164749. #else
  164750. #if MAX_COMPS_IN_SCAN == 4
  164751. #define ASSIGN_STATE(dest,src) \
  164752. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  164753. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  164754. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  164755. (dest).last_dc_val[3] = (src).last_dc_val[3])
  164756. #endif
  164757. #endif
  164758. typedef struct {
  164759. struct jpeg_entropy_decoder pub; /* public fields */
  164760. /* These fields are loaded into local variables at start of each MCU.
  164761. * In case of suspension, we exit WITHOUT updating them.
  164762. */
  164763. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  164764. savable_state2 saved; /* Other state at start of MCU */
  164765. /* These fields are NOT loaded into local working state. */
  164766. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  164767. /* Pointers to derived tables (these workspaces have image lifespan) */
  164768. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  164769. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  164770. /* Precalculated info set up by start_pass for use in decode_mcu: */
  164771. /* Pointers to derived tables to be used for each block within an MCU */
  164772. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  164773. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  164774. /* Whether we care about the DC and AC coefficient values for each block */
  164775. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  164776. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  164777. } huff_entropy_decoder2;
  164778. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  164779. /*
  164780. * Initialize for a Huffman-compressed scan.
  164781. */
  164782. METHODDEF(void)
  164783. start_pass_huff_decoder (j_decompress_ptr cinfo)
  164784. {
  164785. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  164786. int ci, blkn, dctbl, actbl;
  164787. jpeg_component_info * compptr;
  164788. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  164789. * This ought to be an error condition, but we make it a warning because
  164790. * there are some baseline files out there with all zeroes in these bytes.
  164791. */
  164792. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  164793. cinfo->Ah != 0 || cinfo->Al != 0)
  164794. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  164795. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164796. compptr = cinfo->cur_comp_info[ci];
  164797. dctbl = compptr->dc_tbl_no;
  164798. actbl = compptr->ac_tbl_no;
  164799. /* Compute derived values for Huffman tables */
  164800. /* We may do this more than once for a table, but it's not expensive */
  164801. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  164802. & entropy->dc_derived_tbls[dctbl]);
  164803. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  164804. & entropy->ac_derived_tbls[actbl]);
  164805. /* Initialize DC predictions to 0 */
  164806. entropy->saved.last_dc_val[ci] = 0;
  164807. }
  164808. /* Precalculate decoding info for each block in an MCU of this scan */
  164809. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  164810. ci = cinfo->MCU_membership[blkn];
  164811. compptr = cinfo->cur_comp_info[ci];
  164812. /* Precalculate which table to use for each block */
  164813. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  164814. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  164815. /* Decide whether we really care about the coefficient values */
  164816. if (compptr->component_needed) {
  164817. entropy->dc_needed[blkn] = TRUE;
  164818. /* we don't need the ACs if producing a 1/8th-size image */
  164819. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  164820. } else {
  164821. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  164822. }
  164823. }
  164824. /* Initialize bitread state variables */
  164825. entropy->bitstate.bits_left = 0;
  164826. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  164827. entropy->pub.insufficient_data = FALSE;
  164828. /* Initialize restart counter */
  164829. entropy->restarts_to_go = cinfo->restart_interval;
  164830. }
  164831. /*
  164832. * Compute the derived values for a Huffman table.
  164833. * This routine also performs some validation checks on the table.
  164834. *
  164835. * Note this is also used by jdphuff.c.
  164836. */
  164837. GLOBAL(void)
  164838. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  164839. d_derived_tbl ** pdtbl)
  164840. {
  164841. JHUFF_TBL *htbl;
  164842. d_derived_tbl *dtbl;
  164843. int p, i, l, si, numsymbols;
  164844. int lookbits, ctr;
  164845. char huffsize[257];
  164846. unsigned int huffcode[257];
  164847. unsigned int code;
  164848. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  164849. * paralleling the order of the symbols themselves in htbl->huffval[].
  164850. */
  164851. /* Find the input Huffman table */
  164852. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  164853. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  164854. htbl =
  164855. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  164856. if (htbl == NULL)
  164857. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  164858. /* Allocate a workspace if we haven't already done so. */
  164859. if (*pdtbl == NULL)
  164860. *pdtbl = (d_derived_tbl *)
  164861. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164862. SIZEOF(d_derived_tbl));
  164863. dtbl = *pdtbl;
  164864. dtbl->pub = htbl; /* fill in back link */
  164865. /* Figure C.1: make table of Huffman code length for each symbol */
  164866. p = 0;
  164867. for (l = 1; l <= 16; l++) {
  164868. i = (int) htbl->bits[l];
  164869. if (i < 0 || p + i > 256) /* protect against table overrun */
  164870. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164871. while (i--)
  164872. huffsize[p++] = (char) l;
  164873. }
  164874. huffsize[p] = 0;
  164875. numsymbols = p;
  164876. /* Figure C.2: generate the codes themselves */
  164877. /* We also validate that the counts represent a legal Huffman code tree. */
  164878. code = 0;
  164879. si = huffsize[0];
  164880. p = 0;
  164881. while (huffsize[p]) {
  164882. while (((int) huffsize[p]) == si) {
  164883. huffcode[p++] = code;
  164884. code++;
  164885. }
  164886. /* code is now 1 more than the last code used for codelength si; but
  164887. * it must still fit in si bits, since no code is allowed to be all ones.
  164888. */
  164889. if (((INT32) code) >= (((INT32) 1) << si))
  164890. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164891. code <<= 1;
  164892. si++;
  164893. }
  164894. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  164895. p = 0;
  164896. for (l = 1; l <= 16; l++) {
  164897. if (htbl->bits[l]) {
  164898. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  164899. * minus the minimum code of length l
  164900. */
  164901. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  164902. p += htbl->bits[l];
  164903. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  164904. } else {
  164905. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  164906. }
  164907. }
  164908. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  164909. /* Compute lookahead tables to speed up decoding.
  164910. * First we set all the table entries to 0, indicating "too long";
  164911. * then we iterate through the Huffman codes that are short enough and
  164912. * fill in all the entries that correspond to bit sequences starting
  164913. * with that code.
  164914. */
  164915. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  164916. p = 0;
  164917. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  164918. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  164919. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  164920. /* Generate left-justified code followed by all possible bit sequences */
  164921. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  164922. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  164923. dtbl->look_nbits[lookbits] = l;
  164924. dtbl->look_sym[lookbits] = htbl->huffval[p];
  164925. lookbits++;
  164926. }
  164927. }
  164928. }
  164929. /* Validate symbols as being reasonable.
  164930. * For AC tables, we make no check, but accept all byte values 0..255.
  164931. * For DC tables, we require the symbols to be in range 0..15.
  164932. * (Tighter bounds could be applied depending on the data depth and mode,
  164933. * but this is sufficient to ensure safe decoding.)
  164934. */
  164935. if (isDC) {
  164936. for (i = 0; i < numsymbols; i++) {
  164937. int sym = htbl->huffval[i];
  164938. if (sym < 0 || sym > 15)
  164939. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164940. }
  164941. }
  164942. }
  164943. /*
  164944. * Out-of-line code for bit fetching (shared with jdphuff.c).
  164945. * See jdhuff.h for info about usage.
  164946. * Note: current values of get_buffer and bits_left are passed as parameters,
  164947. * but are returned in the corresponding fields of the state struct.
  164948. *
  164949. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  164950. * of get_buffer to be used. (On machines with wider words, an even larger
  164951. * buffer could be used.) However, on some machines 32-bit shifts are
  164952. * quite slow and take time proportional to the number of places shifted.
  164953. * (This is true with most PC compilers, for instance.) In this case it may
  164954. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  164955. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  164956. */
  164957. #ifdef SLOW_SHIFT_32
  164958. #define MIN_GET_BITS 15 /* minimum allowable value */
  164959. #else
  164960. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  164961. #endif
  164962. GLOBAL(boolean)
  164963. jpeg_fill_bit_buffer (bitread_working_state * state,
  164964. register bit_buf_type get_buffer, register int bits_left,
  164965. int nbits)
  164966. /* Load up the bit buffer to a depth of at least nbits */
  164967. {
  164968. /* Copy heavily used state fields into locals (hopefully registers) */
  164969. register const JOCTET * next_input_byte = state->next_input_byte;
  164970. register size_t bytes_in_buffer = state->bytes_in_buffer;
  164971. j_decompress_ptr cinfo = state->cinfo;
  164972. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  164973. /* (It is assumed that no request will be for more than that many bits.) */
  164974. /* We fail to do so only if we hit a marker or are forced to suspend. */
  164975. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  164976. while (bits_left < MIN_GET_BITS) {
  164977. register int c;
  164978. /* Attempt to read a byte */
  164979. if (bytes_in_buffer == 0) {
  164980. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  164981. return FALSE;
  164982. next_input_byte = cinfo->src->next_input_byte;
  164983. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  164984. }
  164985. bytes_in_buffer--;
  164986. c = GETJOCTET(*next_input_byte++);
  164987. /* If it's 0xFF, check and discard stuffed zero byte */
  164988. if (c == 0xFF) {
  164989. /* Loop here to discard any padding FF's on terminating marker,
  164990. * so that we can save a valid unread_marker value. NOTE: we will
  164991. * accept multiple FF's followed by a 0 as meaning a single FF data
  164992. * byte. This data pattern is not valid according to the standard.
  164993. */
  164994. do {
  164995. if (bytes_in_buffer == 0) {
  164996. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  164997. return FALSE;
  164998. next_input_byte = cinfo->src->next_input_byte;
  164999. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  165000. }
  165001. bytes_in_buffer--;
  165002. c = GETJOCTET(*next_input_byte++);
  165003. } while (c == 0xFF);
  165004. if (c == 0) {
  165005. /* Found FF/00, which represents an FF data byte */
  165006. c = 0xFF;
  165007. } else {
  165008. /* Oops, it's actually a marker indicating end of compressed data.
  165009. * Save the marker code for later use.
  165010. * Fine point: it might appear that we should save the marker into
  165011. * bitread working state, not straight into permanent state. But
  165012. * once we have hit a marker, we cannot need to suspend within the
  165013. * current MCU, because we will read no more bytes from the data
  165014. * source. So it is OK to update permanent state right away.
  165015. */
  165016. cinfo->unread_marker = c;
  165017. /* See if we need to insert some fake zero bits. */
  165018. goto no_more_bytes;
  165019. }
  165020. }
  165021. /* OK, load c into get_buffer */
  165022. get_buffer = (get_buffer << 8) | c;
  165023. bits_left += 8;
  165024. } /* end while */
  165025. } else {
  165026. no_more_bytes:
  165027. /* We get here if we've read the marker that terminates the compressed
  165028. * data segment. There should be enough bits in the buffer register
  165029. * to satisfy the request; if so, no problem.
  165030. */
  165031. if (nbits > bits_left) {
  165032. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  165033. * the data stream, so that we can produce some kind of image.
  165034. * We use a nonvolatile flag to ensure that only one warning message
  165035. * appears per data segment.
  165036. */
  165037. if (! cinfo->entropy->insufficient_data) {
  165038. WARNMS(cinfo, JWRN_HIT_MARKER);
  165039. cinfo->entropy->insufficient_data = TRUE;
  165040. }
  165041. /* Fill the buffer with zero bits */
  165042. get_buffer <<= MIN_GET_BITS - bits_left;
  165043. bits_left = MIN_GET_BITS;
  165044. }
  165045. }
  165046. /* Unload the local registers */
  165047. state->next_input_byte = next_input_byte;
  165048. state->bytes_in_buffer = bytes_in_buffer;
  165049. state->get_buffer = get_buffer;
  165050. state->bits_left = bits_left;
  165051. return TRUE;
  165052. }
  165053. /*
  165054. * Out-of-line code for Huffman code decoding.
  165055. * See jdhuff.h for info about usage.
  165056. */
  165057. GLOBAL(int)
  165058. jpeg_huff_decode (bitread_working_state * state,
  165059. register bit_buf_type get_buffer, register int bits_left,
  165060. d_derived_tbl * htbl, int min_bits)
  165061. {
  165062. register int l = min_bits;
  165063. register INT32 code;
  165064. /* HUFF_DECODE has determined that the code is at least min_bits */
  165065. /* bits long, so fetch that many bits in one swoop. */
  165066. CHECK_BIT_BUFFER(*state, l, return -1);
  165067. code = GET_BITS(l);
  165068. /* Collect the rest of the Huffman code one bit at a time. */
  165069. /* This is per Figure F.16 in the JPEG spec. */
  165070. while (code > htbl->maxcode[l]) {
  165071. code <<= 1;
  165072. CHECK_BIT_BUFFER(*state, 1, return -1);
  165073. code |= GET_BITS(1);
  165074. l++;
  165075. }
  165076. /* Unload the local registers */
  165077. state->get_buffer = get_buffer;
  165078. state->bits_left = bits_left;
  165079. /* With garbage input we may reach the sentinel value l = 17. */
  165080. if (l > 16) {
  165081. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  165082. return 0; /* fake a zero as the safest result */
  165083. }
  165084. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  165085. }
  165086. /*
  165087. * Check for a restart marker & resynchronize decoder.
  165088. * Returns FALSE if must suspend.
  165089. */
  165090. LOCAL(boolean)
  165091. process_restart (j_decompress_ptr cinfo)
  165092. {
  165093. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165094. int ci;
  165095. /* Throw away any unused bits remaining in bit buffer; */
  165096. /* include any full bytes in next_marker's count of discarded bytes */
  165097. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  165098. entropy->bitstate.bits_left = 0;
  165099. /* Advance past the RSTn marker */
  165100. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  165101. return FALSE;
  165102. /* Re-initialize DC predictions to 0 */
  165103. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  165104. entropy->saved.last_dc_val[ci] = 0;
  165105. /* Reset restart counter */
  165106. entropy->restarts_to_go = cinfo->restart_interval;
  165107. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  165108. * against a marker. In that case we will end up treating the next data
  165109. * segment as empty, and we can avoid producing bogus output pixels by
  165110. * leaving the flag set.
  165111. */
  165112. if (cinfo->unread_marker == 0)
  165113. entropy->pub.insufficient_data = FALSE;
  165114. return TRUE;
  165115. }
  165116. /*
  165117. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  165118. * The coefficients are reordered from zigzag order into natural array order,
  165119. * but are not dequantized.
  165120. *
  165121. * The i'th block of the MCU is stored into the block pointed to by
  165122. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  165123. * (Wholesale zeroing is usually a little faster than retail...)
  165124. *
  165125. * Returns FALSE if data source requested suspension. In that case no
  165126. * changes have been made to permanent state. (Exception: some output
  165127. * coefficients may already have been assigned. This is harmless for
  165128. * this module, since we'll just re-assign them on the next call.)
  165129. */
  165130. METHODDEF(boolean)
  165131. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  165132. {
  165133. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165134. int blkn;
  165135. BITREAD_STATE_VARS;
  165136. savable_state2 state;
  165137. /* Process restart marker if needed; may have to suspend */
  165138. if (cinfo->restart_interval) {
  165139. if (entropy->restarts_to_go == 0)
  165140. if (! process_restart(cinfo))
  165141. return FALSE;
  165142. }
  165143. /* If we've run out of data, just leave the MCU set to zeroes.
  165144. * This way, we return uniform gray for the remainder of the segment.
  165145. */
  165146. if (! entropy->pub.insufficient_data) {
  165147. /* Load up working state */
  165148. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  165149. ASSIGN_STATE(state, entropy->saved);
  165150. /* Outer loop handles each block in the MCU */
  165151. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165152. JBLOCKROW block = MCU_data[blkn];
  165153. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  165154. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  165155. register int s, k, r;
  165156. /* Decode a single block's worth of coefficients */
  165157. /* Section F.2.2.1: decode the DC coefficient difference */
  165158. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  165159. if (s) {
  165160. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  165161. r = GET_BITS(s);
  165162. s = HUFF_EXTEND(r, s);
  165163. }
  165164. if (entropy->dc_needed[blkn]) {
  165165. /* Convert DC difference to actual value, update last_dc_val */
  165166. int ci = cinfo->MCU_membership[blkn];
  165167. s += state.last_dc_val[ci];
  165168. state.last_dc_val[ci] = s;
  165169. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  165170. (*block)[0] = (JCOEF) s;
  165171. }
  165172. if (entropy->ac_needed[blkn]) {
  165173. /* Section F.2.2.2: decode the AC coefficients */
  165174. /* Since zeroes are skipped, output area must be cleared beforehand */
  165175. for (k = 1; k < DCTSIZE2; k++) {
  165176. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  165177. r = s >> 4;
  165178. s &= 15;
  165179. if (s) {
  165180. k += r;
  165181. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  165182. r = GET_BITS(s);
  165183. s = HUFF_EXTEND(r, s);
  165184. /* Output coefficient in natural (dezigzagged) order.
  165185. * Note: the extra entries in jpeg_natural_order[] will save us
  165186. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  165187. */
  165188. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  165189. } else {
  165190. if (r != 15)
  165191. break;
  165192. k += 15;
  165193. }
  165194. }
  165195. } else {
  165196. /* Section F.2.2.2: decode the AC coefficients */
  165197. /* In this path we just discard the values */
  165198. for (k = 1; k < DCTSIZE2; k++) {
  165199. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  165200. r = s >> 4;
  165201. s &= 15;
  165202. if (s) {
  165203. k += r;
  165204. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  165205. DROP_BITS(s);
  165206. } else {
  165207. if (r != 15)
  165208. break;
  165209. k += 15;
  165210. }
  165211. }
  165212. }
  165213. }
  165214. /* Completed MCU, so update state */
  165215. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  165216. ASSIGN_STATE(entropy->saved, state);
  165217. }
  165218. /* Account for restart interval (no-op if not using restarts) */
  165219. entropy->restarts_to_go--;
  165220. return TRUE;
  165221. }
  165222. /*
  165223. * Module initialization routine for Huffman entropy decoding.
  165224. */
  165225. GLOBAL(void)
  165226. jinit_huff_decoder (j_decompress_ptr cinfo)
  165227. {
  165228. huff_entropy_ptr2 entropy;
  165229. int i;
  165230. entropy = (huff_entropy_ptr2)
  165231. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165232. SIZEOF(huff_entropy_decoder2));
  165233. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  165234. entropy->pub.start_pass = start_pass_huff_decoder;
  165235. entropy->pub.decode_mcu = decode_mcu;
  165236. /* Mark tables unallocated */
  165237. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  165238. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  165239. }
  165240. }
  165241. /********* End of inlined file: jdhuff.c *********/
  165242. /********* Start of inlined file: jdinput.c *********/
  165243. #define JPEG_INTERNALS
  165244. /* Private state */
  165245. typedef struct {
  165246. struct jpeg_input_controller pub; /* public fields */
  165247. boolean inheaders; /* TRUE until first SOS is reached */
  165248. } my_input_controller;
  165249. typedef my_input_controller * my_inputctl_ptr;
  165250. /* Forward declarations */
  165251. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  165252. /*
  165253. * Routines to calculate various quantities related to the size of the image.
  165254. */
  165255. LOCAL(void)
  165256. initial_setup2 (j_decompress_ptr cinfo)
  165257. /* Called once, when first SOS marker is reached */
  165258. {
  165259. int ci;
  165260. jpeg_component_info *compptr;
  165261. /* Make sure image isn't bigger than I can handle */
  165262. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  165263. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  165264. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  165265. /* For now, precision must match compiled-in value... */
  165266. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  165267. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  165268. /* Check that number of components won't exceed internal array sizes */
  165269. if (cinfo->num_components > MAX_COMPONENTS)
  165270. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165271. MAX_COMPONENTS);
  165272. /* Compute maximum sampling factors; check factor validity */
  165273. cinfo->max_h_samp_factor = 1;
  165274. cinfo->max_v_samp_factor = 1;
  165275. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165276. ci++, compptr++) {
  165277. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  165278. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  165279. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  165280. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  165281. compptr->h_samp_factor);
  165282. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  165283. compptr->v_samp_factor);
  165284. }
  165285. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  165286. * In the full decompressor, this will be overridden by jdmaster.c;
  165287. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  165288. */
  165289. cinfo->min_DCT_scaled_size = DCTSIZE;
  165290. /* Compute dimensions of components */
  165291. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165292. ci++, compptr++) {
  165293. compptr->DCT_scaled_size = DCTSIZE;
  165294. /* Size in DCT blocks */
  165295. compptr->width_in_blocks = (JDIMENSION)
  165296. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  165297. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  165298. compptr->height_in_blocks = (JDIMENSION)
  165299. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  165300. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  165301. /* downsampled_width and downsampled_height will also be overridden by
  165302. * jdmaster.c if we are doing full decompression. The transcoder library
  165303. * doesn't use these values, but the calling application might.
  165304. */
  165305. /* Size in samples */
  165306. compptr->downsampled_width = (JDIMENSION)
  165307. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  165308. (long) cinfo->max_h_samp_factor);
  165309. compptr->downsampled_height = (JDIMENSION)
  165310. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  165311. (long) cinfo->max_v_samp_factor);
  165312. /* Mark component needed, until color conversion says otherwise */
  165313. compptr->component_needed = TRUE;
  165314. /* Mark no quantization table yet saved for component */
  165315. compptr->quant_table = NULL;
  165316. }
  165317. /* Compute number of fully interleaved MCU rows. */
  165318. cinfo->total_iMCU_rows = (JDIMENSION)
  165319. jdiv_round_up((long) cinfo->image_height,
  165320. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165321. /* Decide whether file contains multiple scans */
  165322. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  165323. cinfo->inputctl->has_multiple_scans = TRUE;
  165324. else
  165325. cinfo->inputctl->has_multiple_scans = FALSE;
  165326. }
  165327. LOCAL(void)
  165328. per_scan_setup2 (j_decompress_ptr cinfo)
  165329. /* Do computations that are needed before processing a JPEG scan */
  165330. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  165331. {
  165332. int ci, mcublks, tmp;
  165333. jpeg_component_info *compptr;
  165334. if (cinfo->comps_in_scan == 1) {
  165335. /* Noninterleaved (single-component) scan */
  165336. compptr = cinfo->cur_comp_info[0];
  165337. /* Overall image size in MCUs */
  165338. cinfo->MCUs_per_row = compptr->width_in_blocks;
  165339. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  165340. /* For noninterleaved scan, always one block per MCU */
  165341. compptr->MCU_width = 1;
  165342. compptr->MCU_height = 1;
  165343. compptr->MCU_blocks = 1;
  165344. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  165345. compptr->last_col_width = 1;
  165346. /* For noninterleaved scans, it is convenient to define last_row_height
  165347. * as the number of block rows present in the last iMCU row.
  165348. */
  165349. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165350. if (tmp == 0) tmp = compptr->v_samp_factor;
  165351. compptr->last_row_height = tmp;
  165352. /* Prepare array describing MCU composition */
  165353. cinfo->blocks_in_MCU = 1;
  165354. cinfo->MCU_membership[0] = 0;
  165355. } else {
  165356. /* Interleaved (multi-component) scan */
  165357. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  165358. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  165359. MAX_COMPS_IN_SCAN);
  165360. /* Overall image size in MCUs */
  165361. cinfo->MCUs_per_row = (JDIMENSION)
  165362. jdiv_round_up((long) cinfo->image_width,
  165363. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  165364. cinfo->MCU_rows_in_scan = (JDIMENSION)
  165365. jdiv_round_up((long) cinfo->image_height,
  165366. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165367. cinfo->blocks_in_MCU = 0;
  165368. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165369. compptr = cinfo->cur_comp_info[ci];
  165370. /* Sampling factors give # of blocks of component in each MCU */
  165371. compptr->MCU_width = compptr->h_samp_factor;
  165372. compptr->MCU_height = compptr->v_samp_factor;
  165373. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  165374. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  165375. /* Figure number of non-dummy blocks in last MCU column & row */
  165376. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  165377. if (tmp == 0) tmp = compptr->MCU_width;
  165378. compptr->last_col_width = tmp;
  165379. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  165380. if (tmp == 0) tmp = compptr->MCU_height;
  165381. compptr->last_row_height = tmp;
  165382. /* Prepare array describing MCU composition */
  165383. mcublks = compptr->MCU_blocks;
  165384. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  165385. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  165386. while (mcublks-- > 0) {
  165387. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165388. }
  165389. }
  165390. }
  165391. }
  165392. /*
  165393. * Save away a copy of the Q-table referenced by each component present
  165394. * in the current scan, unless already saved during a prior scan.
  165395. *
  165396. * In a multiple-scan JPEG file, the encoder could assign different components
  165397. * the same Q-table slot number, but change table definitions between scans
  165398. * so that each component uses a different Q-table. (The IJG encoder is not
  165399. * currently capable of doing this, but other encoders might.) Since we want
  165400. * to be able to dequantize all the components at the end of the file, this
  165401. * means that we have to save away the table actually used for each component.
  165402. * We do this by copying the table at the start of the first scan containing
  165403. * the component.
  165404. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  165405. * slot between scans of a component using that slot. If the encoder does so
  165406. * anyway, this decoder will simply use the Q-table values that were current
  165407. * at the start of the first scan for the component.
  165408. *
  165409. * The decompressor output side looks only at the saved quant tables,
  165410. * not at the current Q-table slots.
  165411. */
  165412. LOCAL(void)
  165413. latch_quant_tables (j_decompress_ptr cinfo)
  165414. {
  165415. int ci, qtblno;
  165416. jpeg_component_info *compptr;
  165417. JQUANT_TBL * qtbl;
  165418. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165419. compptr = cinfo->cur_comp_info[ci];
  165420. /* No work if we already saved Q-table for this component */
  165421. if (compptr->quant_table != NULL)
  165422. continue;
  165423. /* Make sure specified quantization table is present */
  165424. qtblno = compptr->quant_tbl_no;
  165425. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  165426. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  165427. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  165428. /* OK, save away the quantization table */
  165429. qtbl = (JQUANT_TBL *)
  165430. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165431. SIZEOF(JQUANT_TBL));
  165432. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  165433. compptr->quant_table = qtbl;
  165434. }
  165435. }
  165436. /*
  165437. * Initialize the input modules to read a scan of compressed data.
  165438. * The first call to this is done by jdmaster.c after initializing
  165439. * the entire decompressor (during jpeg_start_decompress).
  165440. * Subsequent calls come from consume_markers, below.
  165441. */
  165442. METHODDEF(void)
  165443. start_input_pass2 (j_decompress_ptr cinfo)
  165444. {
  165445. per_scan_setup2(cinfo);
  165446. latch_quant_tables(cinfo);
  165447. (*cinfo->entropy->start_pass) (cinfo);
  165448. (*cinfo->coef->start_input_pass) (cinfo);
  165449. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  165450. }
  165451. /*
  165452. * Finish up after inputting a compressed-data scan.
  165453. * This is called by the coefficient controller after it's read all
  165454. * the expected data of the scan.
  165455. */
  165456. METHODDEF(void)
  165457. finish_input_pass (j_decompress_ptr cinfo)
  165458. {
  165459. cinfo->inputctl->consume_input = consume_markers;
  165460. }
  165461. /*
  165462. * Read JPEG markers before, between, or after compressed-data scans.
  165463. * Change state as necessary when a new scan is reached.
  165464. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  165465. *
  165466. * The consume_input method pointer points either here or to the
  165467. * coefficient controller's consume_data routine, depending on whether
  165468. * we are reading a compressed data segment or inter-segment markers.
  165469. */
  165470. METHODDEF(int)
  165471. consume_markers (j_decompress_ptr cinfo)
  165472. {
  165473. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  165474. int val;
  165475. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  165476. return JPEG_REACHED_EOI;
  165477. val = (*cinfo->marker->read_markers) (cinfo);
  165478. switch (val) {
  165479. case JPEG_REACHED_SOS: /* Found SOS */
  165480. if (inputctl->inheaders) { /* 1st SOS */
  165481. initial_setup2(cinfo);
  165482. inputctl->inheaders = FALSE;
  165483. /* Note: start_input_pass must be called by jdmaster.c
  165484. * before any more input can be consumed. jdapimin.c is
  165485. * responsible for enforcing this sequencing.
  165486. */
  165487. } else { /* 2nd or later SOS marker */
  165488. if (! inputctl->pub.has_multiple_scans)
  165489. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  165490. start_input_pass2(cinfo);
  165491. }
  165492. break;
  165493. case JPEG_REACHED_EOI: /* Found EOI */
  165494. inputctl->pub.eoi_reached = TRUE;
  165495. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  165496. if (cinfo->marker->saw_SOF)
  165497. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  165498. } else {
  165499. /* Prevent infinite loop in coef ctlr's decompress_data routine
  165500. * if user set output_scan_number larger than number of scans.
  165501. */
  165502. if (cinfo->output_scan_number > cinfo->input_scan_number)
  165503. cinfo->output_scan_number = cinfo->input_scan_number;
  165504. }
  165505. break;
  165506. case JPEG_SUSPENDED:
  165507. break;
  165508. }
  165509. return val;
  165510. }
  165511. /*
  165512. * Reset state to begin a fresh datastream.
  165513. */
  165514. METHODDEF(void)
  165515. reset_input_controller (j_decompress_ptr cinfo)
  165516. {
  165517. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  165518. inputctl->pub.consume_input = consume_markers;
  165519. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  165520. inputctl->pub.eoi_reached = FALSE;
  165521. inputctl->inheaders = TRUE;
  165522. /* Reset other modules */
  165523. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  165524. (*cinfo->marker->reset_marker_reader) (cinfo);
  165525. /* Reset progression state -- would be cleaner if entropy decoder did this */
  165526. cinfo->coef_bits = NULL;
  165527. }
  165528. /*
  165529. * Initialize the input controller module.
  165530. * This is called only once, when the decompression object is created.
  165531. */
  165532. GLOBAL(void)
  165533. jinit_input_controller (j_decompress_ptr cinfo)
  165534. {
  165535. my_inputctl_ptr inputctl;
  165536. /* Create subobject in permanent pool */
  165537. inputctl = (my_inputctl_ptr)
  165538. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165539. SIZEOF(my_input_controller));
  165540. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  165541. /* Initialize method pointers */
  165542. inputctl->pub.consume_input = consume_markers;
  165543. inputctl->pub.reset_input_controller = reset_input_controller;
  165544. inputctl->pub.start_input_pass = start_input_pass2;
  165545. inputctl->pub.finish_input_pass = finish_input_pass;
  165546. /* Initialize state: can't use reset_input_controller since we don't
  165547. * want to try to reset other modules yet.
  165548. */
  165549. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  165550. inputctl->pub.eoi_reached = FALSE;
  165551. inputctl->inheaders = TRUE;
  165552. }
  165553. /********* End of inlined file: jdinput.c *********/
  165554. /********* Start of inlined file: jdmainct.c *********/
  165555. #define JPEG_INTERNALS
  165556. /*
  165557. * In the current system design, the main buffer need never be a full-image
  165558. * buffer; any full-height buffers will be found inside the coefficient or
  165559. * postprocessing controllers. Nonetheless, the main controller is not
  165560. * trivial. Its responsibility is to provide context rows for upsampling/
  165561. * rescaling, and doing this in an efficient fashion is a bit tricky.
  165562. *
  165563. * Postprocessor input data is counted in "row groups". A row group
  165564. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  165565. * sample rows of each component. (We require DCT_scaled_size values to be
  165566. * chosen such that these numbers are integers. In practice DCT_scaled_size
  165567. * values will likely be powers of two, so we actually have the stronger
  165568. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  165569. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  165570. * row group (times any additional scale factor that the upsampler is
  165571. * applying).
  165572. *
  165573. * The coefficient controller will deliver data to us one iMCU row at a time;
  165574. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  165575. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  165576. * to one row of MCUs when the image is fully interleaved.) Note that the
  165577. * number of sample rows varies across components, but the number of row
  165578. * groups does not. Some garbage sample rows may be included in the last iMCU
  165579. * row at the bottom of the image.
  165580. *
  165581. * Depending on the vertical scaling algorithm used, the upsampler may need
  165582. * access to the sample row(s) above and below its current input row group.
  165583. * The upsampler is required to set need_context_rows TRUE at global selection
  165584. * time if so. When need_context_rows is FALSE, this controller can simply
  165585. * obtain one iMCU row at a time from the coefficient controller and dole it
  165586. * out as row groups to the postprocessor.
  165587. *
  165588. * When need_context_rows is TRUE, this controller guarantees that the buffer
  165589. * passed to postprocessing contains at least one row group's worth of samples
  165590. * above and below the row group(s) being processed. Note that the context
  165591. * rows "above" the first passed row group appear at negative row offsets in
  165592. * the passed buffer. At the top and bottom of the image, the required
  165593. * context rows are manufactured by duplicating the first or last real sample
  165594. * row; this avoids having special cases in the upsampling inner loops.
  165595. *
  165596. * The amount of context is fixed at one row group just because that's a
  165597. * convenient number for this controller to work with. The existing
  165598. * upsamplers really only need one sample row of context. An upsampler
  165599. * supporting arbitrary output rescaling might wish for more than one row
  165600. * group of context when shrinking the image; tough, we don't handle that.
  165601. * (This is justified by the assumption that downsizing will be handled mostly
  165602. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  165603. * the upsample step needn't be much less than one.)
  165604. *
  165605. * To provide the desired context, we have to retain the last two row groups
  165606. * of one iMCU row while reading in the next iMCU row. (The last row group
  165607. * can't be processed until we have another row group for its below-context,
  165608. * and so we have to save the next-to-last group too for its above-context.)
  165609. * We could do this most simply by copying data around in our buffer, but
  165610. * that'd be very slow. We can avoid copying any data by creating a rather
  165611. * strange pointer structure. Here's how it works. We allocate a workspace
  165612. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  165613. * of row groups per iMCU row). We create two sets of redundant pointers to
  165614. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  165615. * pointer lists look like this:
  165616. * M+1 M-1
  165617. * master pointer --> 0 master pointer --> 0
  165618. * 1 1
  165619. * ... ...
  165620. * M-3 M-3
  165621. * M-2 M
  165622. * M-1 M+1
  165623. * M M-2
  165624. * M+1 M-1
  165625. * 0 0
  165626. * We read alternate iMCU rows using each master pointer; thus the last two
  165627. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  165628. * The pointer lists are set up so that the required context rows appear to
  165629. * be adjacent to the proper places when we pass the pointer lists to the
  165630. * upsampler.
  165631. *
  165632. * The above pictures describe the normal state of the pointer lists.
  165633. * At top and bottom of the image, we diddle the pointer lists to duplicate
  165634. * the first or last sample row as necessary (this is cheaper than copying
  165635. * sample rows around).
  165636. *
  165637. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  165638. * situation each iMCU row provides only one row group so the buffering logic
  165639. * must be different (eg, we must read two iMCU rows before we can emit the
  165640. * first row group). For now, we simply do not support providing context
  165641. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  165642. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  165643. * want it quick and dirty, so a context-free upsampler is sufficient.
  165644. */
  165645. /* Private buffer controller object */
  165646. typedef struct {
  165647. struct jpeg_d_main_controller pub; /* public fields */
  165648. /* Pointer to allocated workspace (M or M+2 row groups). */
  165649. JSAMPARRAY buffer[MAX_COMPONENTS];
  165650. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  165651. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  165652. /* Remaining fields are only used in the context case. */
  165653. /* These are the master pointers to the funny-order pointer lists. */
  165654. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  165655. int whichptr; /* indicates which pointer set is now in use */
  165656. int context_state; /* process_data state machine status */
  165657. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  165658. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  165659. } my_main_controller4;
  165660. typedef my_main_controller4 * my_main_ptr4;
  165661. /* context_state values: */
  165662. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  165663. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  165664. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  165665. /* Forward declarations */
  165666. METHODDEF(void) process_data_simple_main2
  165667. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  165668. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  165669. METHODDEF(void) process_data_context_main
  165670. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  165671. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  165672. #ifdef QUANT_2PASS_SUPPORTED
  165673. METHODDEF(void) process_data_crank_post
  165674. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  165675. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  165676. #endif
  165677. LOCAL(void)
  165678. alloc_funny_pointers (j_decompress_ptr cinfo)
  165679. /* Allocate space for the funny pointer lists.
  165680. * This is done only once, not once per pass.
  165681. */
  165682. {
  165683. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165684. int ci, rgroup;
  165685. int M = cinfo->min_DCT_scaled_size;
  165686. jpeg_component_info *compptr;
  165687. JSAMPARRAY xbuf;
  165688. /* Get top-level space for component array pointers.
  165689. * We alloc both arrays with one call to save a few cycles.
  165690. */
  165691. main_->xbuffer[0] = (JSAMPIMAGE)
  165692. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165693. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  165694. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  165695. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165696. ci++, compptr++) {
  165697. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  165698. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  165699. /* Get space for pointer lists --- M+4 row groups in each list.
  165700. * We alloc both pointer lists with one call to save a few cycles.
  165701. */
  165702. xbuf = (JSAMPARRAY)
  165703. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165704. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  165705. xbuf += rgroup; /* want one row group at negative offsets */
  165706. main_->xbuffer[0][ci] = xbuf;
  165707. xbuf += rgroup * (M + 4);
  165708. main_->xbuffer[1][ci] = xbuf;
  165709. }
  165710. }
  165711. LOCAL(void)
  165712. make_funny_pointers (j_decompress_ptr cinfo)
  165713. /* Create the funny pointer lists discussed in the comments above.
  165714. * The actual workspace is already allocated (in main->buffer),
  165715. * and the space for the pointer lists is allocated too.
  165716. * This routine just fills in the curiously ordered lists.
  165717. * This will be repeated at the beginning of each pass.
  165718. */
  165719. {
  165720. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165721. int ci, i, rgroup;
  165722. int M = cinfo->min_DCT_scaled_size;
  165723. jpeg_component_info *compptr;
  165724. JSAMPARRAY buf, xbuf0, xbuf1;
  165725. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165726. ci++, compptr++) {
  165727. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  165728. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  165729. xbuf0 = main_->xbuffer[0][ci];
  165730. xbuf1 = main_->xbuffer[1][ci];
  165731. /* First copy the workspace pointers as-is */
  165732. buf = main_->buffer[ci];
  165733. for (i = 0; i < rgroup * (M + 2); i++) {
  165734. xbuf0[i] = xbuf1[i] = buf[i];
  165735. }
  165736. /* In the second list, put the last four row groups in swapped order */
  165737. for (i = 0; i < rgroup * 2; i++) {
  165738. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  165739. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  165740. }
  165741. /* The wraparound pointers at top and bottom will be filled later
  165742. * (see set_wraparound_pointers, below). Initially we want the "above"
  165743. * pointers to duplicate the first actual data line. This only needs
  165744. * to happen in xbuffer[0].
  165745. */
  165746. for (i = 0; i < rgroup; i++) {
  165747. xbuf0[i - rgroup] = xbuf0[0];
  165748. }
  165749. }
  165750. }
  165751. LOCAL(void)
  165752. set_wraparound_pointers (j_decompress_ptr cinfo)
  165753. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  165754. * This changes the pointer list state from top-of-image to the normal state.
  165755. */
  165756. {
  165757. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165758. int ci, i, rgroup;
  165759. int M = cinfo->min_DCT_scaled_size;
  165760. jpeg_component_info *compptr;
  165761. JSAMPARRAY xbuf0, xbuf1;
  165762. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165763. ci++, compptr++) {
  165764. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  165765. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  165766. xbuf0 = main_->xbuffer[0][ci];
  165767. xbuf1 = main_->xbuffer[1][ci];
  165768. for (i = 0; i < rgroup; i++) {
  165769. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  165770. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  165771. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  165772. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  165773. }
  165774. }
  165775. }
  165776. LOCAL(void)
  165777. set_bottom_pointers (j_decompress_ptr cinfo)
  165778. /* Change the pointer lists to duplicate the last sample row at the bottom
  165779. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  165780. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  165781. */
  165782. {
  165783. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165784. int ci, i, rgroup, iMCUheight, rows_left;
  165785. jpeg_component_info *compptr;
  165786. JSAMPARRAY xbuf;
  165787. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165788. ci++, compptr++) {
  165789. /* Count sample rows in one iMCU row and in one row group */
  165790. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  165791. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  165792. /* Count nondummy sample rows remaining for this component */
  165793. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  165794. if (rows_left == 0) rows_left = iMCUheight;
  165795. /* Count nondummy row groups. Should get same answer for each component,
  165796. * so we need only do it once.
  165797. */
  165798. if (ci == 0) {
  165799. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  165800. }
  165801. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  165802. * last partial rowgroup and ensures at least one full rowgroup of context.
  165803. */
  165804. xbuf = main_->xbuffer[main_->whichptr][ci];
  165805. for (i = 0; i < rgroup * 2; i++) {
  165806. xbuf[rows_left + i] = xbuf[rows_left-1];
  165807. }
  165808. }
  165809. }
  165810. /*
  165811. * Initialize for a processing pass.
  165812. */
  165813. METHODDEF(void)
  165814. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  165815. {
  165816. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165817. switch (pass_mode) {
  165818. case JBUF_PASS_THRU:
  165819. if (cinfo->upsample->need_context_rows) {
  165820. main_->pub.process_data = process_data_context_main;
  165821. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  165822. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  165823. main_->context_state = CTX_PREPARE_FOR_IMCU;
  165824. main_->iMCU_row_ctr = 0;
  165825. } else {
  165826. /* Simple case with no context needed */
  165827. main_->pub.process_data = process_data_simple_main2;
  165828. }
  165829. main_->buffer_full = FALSE; /* Mark buffer empty */
  165830. main_->rowgroup_ctr = 0;
  165831. break;
  165832. #ifdef QUANT_2PASS_SUPPORTED
  165833. case JBUF_CRANK_DEST:
  165834. /* For last pass of 2-pass quantization, just crank the postprocessor */
  165835. main_->pub.process_data = process_data_crank_post;
  165836. break;
  165837. #endif
  165838. default:
  165839. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165840. break;
  165841. }
  165842. }
  165843. /*
  165844. * Process some data.
  165845. * This handles the simple case where no context is required.
  165846. */
  165847. METHODDEF(void)
  165848. process_data_simple_main2 (j_decompress_ptr cinfo,
  165849. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  165850. JDIMENSION out_rows_avail)
  165851. {
  165852. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165853. JDIMENSION rowgroups_avail;
  165854. /* Read input data if we haven't filled the main buffer yet */
  165855. if (! main_->buffer_full) {
  165856. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  165857. return; /* suspension forced, can do nothing more */
  165858. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  165859. }
  165860. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  165861. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  165862. /* Note: at the bottom of the image, we may pass extra garbage row groups
  165863. * to the postprocessor. The postprocessor has to check for bottom
  165864. * of image anyway (at row resolution), so no point in us doing it too.
  165865. */
  165866. /* Feed the postprocessor */
  165867. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  165868. &main_->rowgroup_ctr, rowgroups_avail,
  165869. output_buf, out_row_ctr, out_rows_avail);
  165870. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  165871. if (main_->rowgroup_ctr >= rowgroups_avail) {
  165872. main_->buffer_full = FALSE;
  165873. main_->rowgroup_ctr = 0;
  165874. }
  165875. }
  165876. /*
  165877. * Process some data.
  165878. * This handles the case where context rows must be provided.
  165879. */
  165880. METHODDEF(void)
  165881. process_data_context_main (j_decompress_ptr cinfo,
  165882. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  165883. JDIMENSION out_rows_avail)
  165884. {
  165885. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165886. /* Read input data if we haven't filled the main buffer yet */
  165887. if (! main_->buffer_full) {
  165888. if (! (*cinfo->coef->decompress_data) (cinfo,
  165889. main_->xbuffer[main_->whichptr]))
  165890. return; /* suspension forced, can do nothing more */
  165891. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  165892. main_->iMCU_row_ctr++; /* count rows received */
  165893. }
  165894. /* Postprocessor typically will not swallow all the input data it is handed
  165895. * in one call (due to filling the output buffer first). Must be prepared
  165896. * to exit and restart. This switch lets us keep track of how far we got.
  165897. * Note that each case falls through to the next on successful completion.
  165898. */
  165899. switch (main_->context_state) {
  165900. case CTX_POSTPONED_ROW:
  165901. /* Call postprocessor using previously set pointers for postponed row */
  165902. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  165903. &main_->rowgroup_ctr, main_->rowgroups_avail,
  165904. output_buf, out_row_ctr, out_rows_avail);
  165905. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  165906. return; /* Need to suspend */
  165907. main_->context_state = CTX_PREPARE_FOR_IMCU;
  165908. if (*out_row_ctr >= out_rows_avail)
  165909. return; /* Postprocessor exactly filled output buf */
  165910. /*FALLTHROUGH*/
  165911. case CTX_PREPARE_FOR_IMCU:
  165912. /* Prepare to process first M-1 row groups of this iMCU row */
  165913. main_->rowgroup_ctr = 0;
  165914. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  165915. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  165916. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  165917. */
  165918. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  165919. set_bottom_pointers(cinfo);
  165920. main_->context_state = CTX_PROCESS_IMCU;
  165921. /*FALLTHROUGH*/
  165922. case CTX_PROCESS_IMCU:
  165923. /* Call postprocessor using previously set pointers */
  165924. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  165925. &main_->rowgroup_ctr, main_->rowgroups_avail,
  165926. output_buf, out_row_ctr, out_rows_avail);
  165927. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  165928. return; /* Need to suspend */
  165929. /* After the first iMCU, change wraparound pointers to normal state */
  165930. if (main_->iMCU_row_ctr == 1)
  165931. set_wraparound_pointers(cinfo);
  165932. /* Prepare to load new iMCU row using other xbuffer list */
  165933. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  165934. main_->buffer_full = FALSE;
  165935. /* Still need to process last row group of this iMCU row, */
  165936. /* which is saved at index M+1 of the other xbuffer */
  165937. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  165938. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  165939. main_->context_state = CTX_POSTPONED_ROW;
  165940. }
  165941. }
  165942. /*
  165943. * Process some data.
  165944. * Final pass of two-pass quantization: just call the postprocessor.
  165945. * Source data will be the postprocessor controller's internal buffer.
  165946. */
  165947. #ifdef QUANT_2PASS_SUPPORTED
  165948. METHODDEF(void)
  165949. process_data_crank_post (j_decompress_ptr cinfo,
  165950. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  165951. JDIMENSION out_rows_avail)
  165952. {
  165953. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  165954. (JDIMENSION *) NULL, (JDIMENSION) 0,
  165955. output_buf, out_row_ctr, out_rows_avail);
  165956. }
  165957. #endif /* QUANT_2PASS_SUPPORTED */
  165958. /*
  165959. * Initialize main buffer controller.
  165960. */
  165961. GLOBAL(void)
  165962. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  165963. {
  165964. my_main_ptr4 main_;
  165965. int ci, rgroup, ngroups;
  165966. jpeg_component_info *compptr;
  165967. main_ = (my_main_ptr4)
  165968. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165969. SIZEOF(my_main_controller4));
  165970. cinfo->main = (struct jpeg_d_main_controller *) main_;
  165971. main_->pub.start_pass = start_pass_main2;
  165972. if (need_full_buffer) /* shouldn't happen */
  165973. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165974. /* Allocate the workspace.
  165975. * ngroups is the number of row groups we need.
  165976. */
  165977. if (cinfo->upsample->need_context_rows) {
  165978. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  165979. ERREXIT(cinfo, JERR_NOTIMPL);
  165980. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  165981. ngroups = cinfo->min_DCT_scaled_size + 2;
  165982. } else {
  165983. ngroups = cinfo->min_DCT_scaled_size;
  165984. }
  165985. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165986. ci++, compptr++) {
  165987. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  165988. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  165989. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  165990. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165991. compptr->width_in_blocks * compptr->DCT_scaled_size,
  165992. (JDIMENSION) (rgroup * ngroups));
  165993. }
  165994. }
  165995. /********* End of inlined file: jdmainct.c *********/
  165996. /********* Start of inlined file: jdmarker.c *********/
  165997. #define JPEG_INTERNALS
  165998. /* Private state */
  165999. typedef struct {
  166000. struct jpeg_marker_reader pub; /* public fields */
  166001. /* Application-overridable marker processing methods */
  166002. jpeg_marker_parser_method process_COM;
  166003. jpeg_marker_parser_method process_APPn[16];
  166004. /* Limit on marker data length to save for each marker type */
  166005. unsigned int length_limit_COM;
  166006. unsigned int length_limit_APPn[16];
  166007. /* Status of COM/APPn marker saving */
  166008. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  166009. unsigned int bytes_read; /* data bytes read so far in marker */
  166010. /* Note: cur_marker is not linked into marker_list until it's all read. */
  166011. } my_marker_reader;
  166012. typedef my_marker_reader * my_marker_ptr2;
  166013. /*
  166014. * Macros for fetching data from the data source module.
  166015. *
  166016. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  166017. * the current restart point; we update them only when we have reached a
  166018. * suitable place to restart if a suspension occurs.
  166019. */
  166020. /* Declare and initialize local copies of input pointer/count */
  166021. #define INPUT_VARS(cinfo) \
  166022. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  166023. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  166024. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  166025. /* Unload the local copies --- do this only at a restart boundary */
  166026. #define INPUT_SYNC(cinfo) \
  166027. ( datasrc->next_input_byte = next_input_byte, \
  166028. datasrc->bytes_in_buffer = bytes_in_buffer )
  166029. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  166030. #define INPUT_RELOAD(cinfo) \
  166031. ( next_input_byte = datasrc->next_input_byte, \
  166032. bytes_in_buffer = datasrc->bytes_in_buffer )
  166033. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  166034. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  166035. * but we must reload the local copies after a successful fill.
  166036. */
  166037. #define MAKE_BYTE_AVAIL(cinfo,action) \
  166038. if (bytes_in_buffer == 0) { \
  166039. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  166040. { action; } \
  166041. INPUT_RELOAD(cinfo); \
  166042. }
  166043. /* Read a byte into variable V.
  166044. * If must suspend, take the specified action (typically "return FALSE").
  166045. */
  166046. #define INPUT_BYTE(cinfo,V,action) \
  166047. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  166048. bytes_in_buffer--; \
  166049. V = GETJOCTET(*next_input_byte++); )
  166050. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  166051. * V should be declared unsigned int or perhaps INT32.
  166052. */
  166053. #define INPUT_2BYTES(cinfo,V,action) \
  166054. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  166055. bytes_in_buffer--; \
  166056. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  166057. MAKE_BYTE_AVAIL(cinfo,action); \
  166058. bytes_in_buffer--; \
  166059. V += GETJOCTET(*next_input_byte++); )
  166060. /*
  166061. * Routines to process JPEG markers.
  166062. *
  166063. * Entry condition: JPEG marker itself has been read and its code saved
  166064. * in cinfo->unread_marker; input restart point is just after the marker.
  166065. *
  166066. * Exit: if return TRUE, have read and processed any parameters, and have
  166067. * updated the restart point to point after the parameters.
  166068. * If return FALSE, was forced to suspend before reaching end of
  166069. * marker parameters; restart point has not been moved. Same routine
  166070. * will be called again after application supplies more input data.
  166071. *
  166072. * This approach to suspension assumes that all of a marker's parameters
  166073. * can fit into a single input bufferload. This should hold for "normal"
  166074. * markers. Some COM/APPn markers might have large parameter segments
  166075. * that might not fit. If we are simply dropping such a marker, we use
  166076. * skip_input_data to get past it, and thereby put the problem on the
  166077. * source manager's shoulders. If we are saving the marker's contents
  166078. * into memory, we use a slightly different convention: when forced to
  166079. * suspend, the marker processor updates the restart point to the end of
  166080. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  166081. * On resumption, cinfo->unread_marker still contains the marker code,
  166082. * but the data source will point to the next chunk of marker data.
  166083. * The marker processor must retain internal state to deal with this.
  166084. *
  166085. * Note that we don't bother to avoid duplicate trace messages if a
  166086. * suspension occurs within marker parameters. Other side effects
  166087. * require more care.
  166088. */
  166089. LOCAL(boolean)
  166090. get_soi (j_decompress_ptr cinfo)
  166091. /* Process an SOI marker */
  166092. {
  166093. int i;
  166094. TRACEMS(cinfo, 1, JTRC_SOI);
  166095. if (cinfo->marker->saw_SOI)
  166096. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  166097. /* Reset all parameters that are defined to be reset by SOI */
  166098. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  166099. cinfo->arith_dc_L[i] = 0;
  166100. cinfo->arith_dc_U[i] = 1;
  166101. cinfo->arith_ac_K[i] = 5;
  166102. }
  166103. cinfo->restart_interval = 0;
  166104. /* Set initial assumptions for colorspace etc */
  166105. cinfo->jpeg_color_space = JCS_UNKNOWN;
  166106. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  166107. cinfo->saw_JFIF_marker = FALSE;
  166108. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  166109. cinfo->JFIF_minor_version = 1;
  166110. cinfo->density_unit = 0;
  166111. cinfo->X_density = 1;
  166112. cinfo->Y_density = 1;
  166113. cinfo->saw_Adobe_marker = FALSE;
  166114. cinfo->Adobe_transform = 0;
  166115. cinfo->marker->saw_SOI = TRUE;
  166116. return TRUE;
  166117. }
  166118. LOCAL(boolean)
  166119. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  166120. /* Process a SOFn marker */
  166121. {
  166122. INT32 length;
  166123. int c, ci;
  166124. jpeg_component_info * compptr;
  166125. INPUT_VARS(cinfo);
  166126. cinfo->progressive_mode = is_prog;
  166127. cinfo->arith_code = is_arith;
  166128. INPUT_2BYTES(cinfo, length, return FALSE);
  166129. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  166130. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  166131. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  166132. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  166133. length -= 8;
  166134. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  166135. (int) cinfo->image_width, (int) cinfo->image_height,
  166136. cinfo->num_components);
  166137. if (cinfo->marker->saw_SOF)
  166138. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  166139. /* We don't support files in which the image height is initially specified */
  166140. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  166141. /* might as well have a general sanity check. */
  166142. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  166143. || cinfo->num_components <= 0)
  166144. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  166145. if (length != (cinfo->num_components * 3))
  166146. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166147. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  166148. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  166149. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166150. cinfo->num_components * SIZEOF(jpeg_component_info));
  166151. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166152. ci++, compptr++) {
  166153. compptr->component_index = ci;
  166154. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  166155. INPUT_BYTE(cinfo, c, return FALSE);
  166156. compptr->h_samp_factor = (c >> 4) & 15;
  166157. compptr->v_samp_factor = (c ) & 15;
  166158. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  166159. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  166160. compptr->component_id, compptr->h_samp_factor,
  166161. compptr->v_samp_factor, compptr->quant_tbl_no);
  166162. }
  166163. cinfo->marker->saw_SOF = TRUE;
  166164. INPUT_SYNC(cinfo);
  166165. return TRUE;
  166166. }
  166167. LOCAL(boolean)
  166168. get_sos (j_decompress_ptr cinfo)
  166169. /* Process a SOS marker */
  166170. {
  166171. INT32 length;
  166172. int i, ci, n, c, cc;
  166173. jpeg_component_info * compptr;
  166174. INPUT_VARS(cinfo);
  166175. if (! cinfo->marker->saw_SOF)
  166176. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  166177. INPUT_2BYTES(cinfo, length, return FALSE);
  166178. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  166179. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  166180. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  166181. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166182. cinfo->comps_in_scan = n;
  166183. /* Collect the component-spec parameters */
  166184. for (i = 0; i < n; i++) {
  166185. INPUT_BYTE(cinfo, cc, return FALSE);
  166186. INPUT_BYTE(cinfo, c, return FALSE);
  166187. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166188. ci++, compptr++) {
  166189. if (cc == compptr->component_id)
  166190. goto id_found;
  166191. }
  166192. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  166193. id_found:
  166194. cinfo->cur_comp_info[i] = compptr;
  166195. compptr->dc_tbl_no = (c >> 4) & 15;
  166196. compptr->ac_tbl_no = (c ) & 15;
  166197. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  166198. compptr->dc_tbl_no, compptr->ac_tbl_no);
  166199. }
  166200. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  166201. INPUT_BYTE(cinfo, c, return FALSE);
  166202. cinfo->Ss = c;
  166203. INPUT_BYTE(cinfo, c, return FALSE);
  166204. cinfo->Se = c;
  166205. INPUT_BYTE(cinfo, c, return FALSE);
  166206. cinfo->Ah = (c >> 4) & 15;
  166207. cinfo->Al = (c ) & 15;
  166208. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  166209. cinfo->Ah, cinfo->Al);
  166210. /* Prepare to scan data & restart markers */
  166211. cinfo->marker->next_restart_num = 0;
  166212. /* Count another SOS marker */
  166213. cinfo->input_scan_number++;
  166214. INPUT_SYNC(cinfo);
  166215. return TRUE;
  166216. }
  166217. #ifdef D_ARITH_CODING_SUPPORTED
  166218. LOCAL(boolean)
  166219. get_dac (j_decompress_ptr cinfo)
  166220. /* Process a DAC marker */
  166221. {
  166222. INT32 length;
  166223. int index, val;
  166224. INPUT_VARS(cinfo);
  166225. INPUT_2BYTES(cinfo, length, return FALSE);
  166226. length -= 2;
  166227. while (length > 0) {
  166228. INPUT_BYTE(cinfo, index, return FALSE);
  166229. INPUT_BYTE(cinfo, val, return FALSE);
  166230. length -= 2;
  166231. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  166232. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  166233. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  166234. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  166235. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  166236. } else { /* define DC table */
  166237. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  166238. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  166239. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  166240. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  166241. }
  166242. }
  166243. if (length != 0)
  166244. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166245. INPUT_SYNC(cinfo);
  166246. return TRUE;
  166247. }
  166248. #else /* ! D_ARITH_CODING_SUPPORTED */
  166249. #define get_dac(cinfo) skip_variable(cinfo)
  166250. #endif /* D_ARITH_CODING_SUPPORTED */
  166251. LOCAL(boolean)
  166252. get_dht (j_decompress_ptr cinfo)
  166253. /* Process a DHT marker */
  166254. {
  166255. INT32 length;
  166256. UINT8 bits[17];
  166257. UINT8 huffval[256];
  166258. int i, index, count;
  166259. JHUFF_TBL **htblptr;
  166260. INPUT_VARS(cinfo);
  166261. INPUT_2BYTES(cinfo, length, return FALSE);
  166262. length -= 2;
  166263. while (length > 16) {
  166264. INPUT_BYTE(cinfo, index, return FALSE);
  166265. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  166266. bits[0] = 0;
  166267. count = 0;
  166268. for (i = 1; i <= 16; i++) {
  166269. INPUT_BYTE(cinfo, bits[i], return FALSE);
  166270. count += bits[i];
  166271. }
  166272. length -= 1 + 16;
  166273. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  166274. bits[1], bits[2], bits[3], bits[4],
  166275. bits[5], bits[6], bits[7], bits[8]);
  166276. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  166277. bits[9], bits[10], bits[11], bits[12],
  166278. bits[13], bits[14], bits[15], bits[16]);
  166279. /* Here we just do minimal validation of the counts to avoid walking
  166280. * off the end of our table space. jdhuff.c will check more carefully.
  166281. */
  166282. if (count > 256 || ((INT32) count) > length)
  166283. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  166284. for (i = 0; i < count; i++)
  166285. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  166286. length -= count;
  166287. if (index & 0x10) { /* AC table definition */
  166288. index -= 0x10;
  166289. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  166290. } else { /* DC table definition */
  166291. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  166292. }
  166293. if (index < 0 || index >= NUM_HUFF_TBLS)
  166294. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  166295. if (*htblptr == NULL)
  166296. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166297. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  166298. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  166299. }
  166300. if (length != 0)
  166301. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166302. INPUT_SYNC(cinfo);
  166303. return TRUE;
  166304. }
  166305. LOCAL(boolean)
  166306. get_dqt (j_decompress_ptr cinfo)
  166307. /* Process a DQT marker */
  166308. {
  166309. INT32 length;
  166310. int n, i, prec;
  166311. unsigned int tmp;
  166312. JQUANT_TBL *quant_ptr;
  166313. INPUT_VARS(cinfo);
  166314. INPUT_2BYTES(cinfo, length, return FALSE);
  166315. length -= 2;
  166316. while (length > 0) {
  166317. INPUT_BYTE(cinfo, n, return FALSE);
  166318. prec = n >> 4;
  166319. n &= 0x0F;
  166320. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  166321. if (n >= NUM_QUANT_TBLS)
  166322. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  166323. if (cinfo->quant_tbl_ptrs[n] == NULL)
  166324. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  166325. quant_ptr = cinfo->quant_tbl_ptrs[n];
  166326. for (i = 0; i < DCTSIZE2; i++) {
  166327. if (prec)
  166328. INPUT_2BYTES(cinfo, tmp, return FALSE);
  166329. else
  166330. INPUT_BYTE(cinfo, tmp, return FALSE);
  166331. /* We convert the zigzag-order table to natural array order. */
  166332. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  166333. }
  166334. if (cinfo->err->trace_level >= 2) {
  166335. for (i = 0; i < DCTSIZE2; i += 8) {
  166336. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  166337. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  166338. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  166339. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  166340. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  166341. }
  166342. }
  166343. length -= DCTSIZE2+1;
  166344. if (prec) length -= DCTSIZE2;
  166345. }
  166346. if (length != 0)
  166347. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166348. INPUT_SYNC(cinfo);
  166349. return TRUE;
  166350. }
  166351. LOCAL(boolean)
  166352. get_dri (j_decompress_ptr cinfo)
  166353. /* Process a DRI marker */
  166354. {
  166355. INT32 length;
  166356. unsigned int tmp;
  166357. INPUT_VARS(cinfo);
  166358. INPUT_2BYTES(cinfo, length, return FALSE);
  166359. if (length != 4)
  166360. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166361. INPUT_2BYTES(cinfo, tmp, return FALSE);
  166362. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  166363. cinfo->restart_interval = tmp;
  166364. INPUT_SYNC(cinfo);
  166365. return TRUE;
  166366. }
  166367. /*
  166368. * Routines for processing APPn and COM markers.
  166369. * These are either saved in memory or discarded, per application request.
  166370. * APP0 and APP14 are specially checked to see if they are
  166371. * JFIF and Adobe markers, respectively.
  166372. */
  166373. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  166374. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  166375. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  166376. LOCAL(void)
  166377. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  166378. unsigned int datalen, INT32 remaining)
  166379. /* Examine first few bytes from an APP0.
  166380. * Take appropriate action if it is a JFIF marker.
  166381. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  166382. */
  166383. {
  166384. INT32 totallen = (INT32) datalen + remaining;
  166385. if (datalen >= APP0_DATA_LEN &&
  166386. GETJOCTET(data[0]) == 0x4A &&
  166387. GETJOCTET(data[1]) == 0x46 &&
  166388. GETJOCTET(data[2]) == 0x49 &&
  166389. GETJOCTET(data[3]) == 0x46 &&
  166390. GETJOCTET(data[4]) == 0) {
  166391. /* Found JFIF APP0 marker: save info */
  166392. cinfo->saw_JFIF_marker = TRUE;
  166393. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  166394. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  166395. cinfo->density_unit = GETJOCTET(data[7]);
  166396. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  166397. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  166398. /* Check version.
  166399. * Major version must be 1, anything else signals an incompatible change.
  166400. * (We used to treat this as an error, but now it's a nonfatal warning,
  166401. * because some bozo at Hijaak couldn't read the spec.)
  166402. * Minor version should be 0..2, but process anyway if newer.
  166403. */
  166404. if (cinfo->JFIF_major_version != 1)
  166405. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  166406. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  166407. /* Generate trace messages */
  166408. TRACEMS5(cinfo, 1, JTRC_JFIF,
  166409. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  166410. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  166411. /* Validate thumbnail dimensions and issue appropriate messages */
  166412. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  166413. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  166414. GETJOCTET(data[12]), GETJOCTET(data[13]));
  166415. totallen -= APP0_DATA_LEN;
  166416. if (totallen !=
  166417. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  166418. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  166419. } else if (datalen >= 6 &&
  166420. GETJOCTET(data[0]) == 0x4A &&
  166421. GETJOCTET(data[1]) == 0x46 &&
  166422. GETJOCTET(data[2]) == 0x58 &&
  166423. GETJOCTET(data[3]) == 0x58 &&
  166424. GETJOCTET(data[4]) == 0) {
  166425. /* Found JFIF "JFXX" extension APP0 marker */
  166426. /* The library doesn't actually do anything with these,
  166427. * but we try to produce a helpful trace message.
  166428. */
  166429. switch (GETJOCTET(data[5])) {
  166430. case 0x10:
  166431. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  166432. break;
  166433. case 0x11:
  166434. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  166435. break;
  166436. case 0x13:
  166437. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  166438. break;
  166439. default:
  166440. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  166441. GETJOCTET(data[5]), (int) totallen);
  166442. break;
  166443. }
  166444. } else {
  166445. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  166446. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  166447. }
  166448. }
  166449. LOCAL(void)
  166450. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  166451. unsigned int datalen, INT32 remaining)
  166452. /* Examine first few bytes from an APP14.
  166453. * Take appropriate action if it is an Adobe marker.
  166454. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  166455. */
  166456. {
  166457. unsigned int version, flags0, flags1, transform;
  166458. if (datalen >= APP14_DATA_LEN &&
  166459. GETJOCTET(data[0]) == 0x41 &&
  166460. GETJOCTET(data[1]) == 0x64 &&
  166461. GETJOCTET(data[2]) == 0x6F &&
  166462. GETJOCTET(data[3]) == 0x62 &&
  166463. GETJOCTET(data[4]) == 0x65) {
  166464. /* Found Adobe APP14 marker */
  166465. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  166466. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  166467. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  166468. transform = GETJOCTET(data[11]);
  166469. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  166470. cinfo->saw_Adobe_marker = TRUE;
  166471. cinfo->Adobe_transform = (UINT8) transform;
  166472. } else {
  166473. /* Start of APP14 does not match "Adobe", or too short */
  166474. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  166475. }
  166476. }
  166477. METHODDEF(boolean)
  166478. get_interesting_appn (j_decompress_ptr cinfo)
  166479. /* Process an APP0 or APP14 marker without saving it */
  166480. {
  166481. INT32 length;
  166482. JOCTET b[APPN_DATA_LEN];
  166483. unsigned int i, numtoread;
  166484. INPUT_VARS(cinfo);
  166485. INPUT_2BYTES(cinfo, length, return FALSE);
  166486. length -= 2;
  166487. /* get the interesting part of the marker data */
  166488. if (length >= APPN_DATA_LEN)
  166489. numtoread = APPN_DATA_LEN;
  166490. else if (length > 0)
  166491. numtoread = (unsigned int) length;
  166492. else
  166493. numtoread = 0;
  166494. for (i = 0; i < numtoread; i++)
  166495. INPUT_BYTE(cinfo, b[i], return FALSE);
  166496. length -= numtoread;
  166497. /* process it */
  166498. switch (cinfo->unread_marker) {
  166499. case M_APP0:
  166500. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  166501. break;
  166502. case M_APP14:
  166503. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  166504. break;
  166505. default:
  166506. /* can't get here unless jpeg_save_markers chooses wrong processor */
  166507. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  166508. break;
  166509. }
  166510. /* skip any remaining data -- could be lots */
  166511. INPUT_SYNC(cinfo);
  166512. if (length > 0)
  166513. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  166514. return TRUE;
  166515. }
  166516. #ifdef SAVE_MARKERS_SUPPORTED
  166517. METHODDEF(boolean)
  166518. save_marker (j_decompress_ptr cinfo)
  166519. /* Save an APPn or COM marker into the marker list */
  166520. {
  166521. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  166522. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  166523. unsigned int bytes_read, data_length;
  166524. JOCTET FAR * data;
  166525. INT32 length = 0;
  166526. INPUT_VARS(cinfo);
  166527. if (cur_marker == NULL) {
  166528. /* begin reading a marker */
  166529. INPUT_2BYTES(cinfo, length, return FALSE);
  166530. length -= 2;
  166531. if (length >= 0) { /* watch out for bogus length word */
  166532. /* figure out how much we want to save */
  166533. unsigned int limit;
  166534. if (cinfo->unread_marker == (int) M_COM)
  166535. limit = marker->length_limit_COM;
  166536. else
  166537. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  166538. if ((unsigned int) length < limit)
  166539. limit = (unsigned int) length;
  166540. /* allocate and initialize the marker item */
  166541. cur_marker = (jpeg_saved_marker_ptr)
  166542. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166543. SIZEOF(struct jpeg_marker_struct) + limit);
  166544. cur_marker->next = NULL;
  166545. cur_marker->marker = (UINT8) cinfo->unread_marker;
  166546. cur_marker->original_length = (unsigned int) length;
  166547. cur_marker->data_length = limit;
  166548. /* data area is just beyond the jpeg_marker_struct */
  166549. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  166550. marker->cur_marker = cur_marker;
  166551. marker->bytes_read = 0;
  166552. bytes_read = 0;
  166553. data_length = limit;
  166554. } else {
  166555. /* deal with bogus length word */
  166556. bytes_read = data_length = 0;
  166557. data = NULL;
  166558. }
  166559. } else {
  166560. /* resume reading a marker */
  166561. bytes_read = marker->bytes_read;
  166562. data_length = cur_marker->data_length;
  166563. data = cur_marker->data + bytes_read;
  166564. }
  166565. while (bytes_read < data_length) {
  166566. INPUT_SYNC(cinfo); /* move the restart point to here */
  166567. marker->bytes_read = bytes_read;
  166568. /* If there's not at least one byte in buffer, suspend */
  166569. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  166570. /* Copy bytes with reasonable rapidity */
  166571. while (bytes_read < data_length && bytes_in_buffer > 0) {
  166572. *data++ = *next_input_byte++;
  166573. bytes_in_buffer--;
  166574. bytes_read++;
  166575. }
  166576. }
  166577. /* Done reading what we want to read */
  166578. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  166579. /* Add new marker to end of list */
  166580. if (cinfo->marker_list == NULL) {
  166581. cinfo->marker_list = cur_marker;
  166582. } else {
  166583. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  166584. while (prev->next != NULL)
  166585. prev = prev->next;
  166586. prev->next = cur_marker;
  166587. }
  166588. /* Reset pointer & calc remaining data length */
  166589. data = cur_marker->data;
  166590. length = cur_marker->original_length - data_length;
  166591. }
  166592. /* Reset to initial state for next marker */
  166593. marker->cur_marker = NULL;
  166594. /* Process the marker if interesting; else just make a generic trace msg */
  166595. switch (cinfo->unread_marker) {
  166596. case M_APP0:
  166597. examine_app0(cinfo, data, data_length, length);
  166598. break;
  166599. case M_APP14:
  166600. examine_app14(cinfo, data, data_length, length);
  166601. break;
  166602. default:
  166603. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  166604. (int) (data_length + length));
  166605. break;
  166606. }
  166607. /* skip any remaining data -- could be lots */
  166608. INPUT_SYNC(cinfo); /* do before skip_input_data */
  166609. if (length > 0)
  166610. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  166611. return TRUE;
  166612. }
  166613. #endif /* SAVE_MARKERS_SUPPORTED */
  166614. METHODDEF(boolean)
  166615. skip_variable (j_decompress_ptr cinfo)
  166616. /* Skip over an unknown or uninteresting variable-length marker */
  166617. {
  166618. INT32 length;
  166619. INPUT_VARS(cinfo);
  166620. INPUT_2BYTES(cinfo, length, return FALSE);
  166621. length -= 2;
  166622. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  166623. INPUT_SYNC(cinfo); /* do before skip_input_data */
  166624. if (length > 0)
  166625. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  166626. return TRUE;
  166627. }
  166628. /*
  166629. * Find the next JPEG marker, save it in cinfo->unread_marker.
  166630. * Returns FALSE if had to suspend before reaching a marker;
  166631. * in that case cinfo->unread_marker is unchanged.
  166632. *
  166633. * Note that the result might not be a valid marker code,
  166634. * but it will never be 0 or FF.
  166635. */
  166636. LOCAL(boolean)
  166637. next_marker (j_decompress_ptr cinfo)
  166638. {
  166639. int c;
  166640. INPUT_VARS(cinfo);
  166641. for (;;) {
  166642. INPUT_BYTE(cinfo, c, return FALSE);
  166643. /* Skip any non-FF bytes.
  166644. * This may look a bit inefficient, but it will not occur in a valid file.
  166645. * We sync after each discarded byte so that a suspending data source
  166646. * can discard the byte from its buffer.
  166647. */
  166648. while (c != 0xFF) {
  166649. cinfo->marker->discarded_bytes++;
  166650. INPUT_SYNC(cinfo);
  166651. INPUT_BYTE(cinfo, c, return FALSE);
  166652. }
  166653. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  166654. * pad bytes, so don't count them in discarded_bytes. We assume there
  166655. * will not be so many consecutive FF bytes as to overflow a suspending
  166656. * data source's input buffer.
  166657. */
  166658. do {
  166659. INPUT_BYTE(cinfo, c, return FALSE);
  166660. } while (c == 0xFF);
  166661. if (c != 0)
  166662. break; /* found a valid marker, exit loop */
  166663. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  166664. * Discard it and loop back to try again.
  166665. */
  166666. cinfo->marker->discarded_bytes += 2;
  166667. INPUT_SYNC(cinfo);
  166668. }
  166669. if (cinfo->marker->discarded_bytes != 0) {
  166670. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  166671. cinfo->marker->discarded_bytes = 0;
  166672. }
  166673. cinfo->unread_marker = c;
  166674. INPUT_SYNC(cinfo);
  166675. return TRUE;
  166676. }
  166677. LOCAL(boolean)
  166678. first_marker (j_decompress_ptr cinfo)
  166679. /* Like next_marker, but used to obtain the initial SOI marker. */
  166680. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  166681. * we might well scan an entire input file before realizing it ain't JPEG.
  166682. * If an application wants to process non-JFIF files, it must seek to the
  166683. * SOI before calling the JPEG library.
  166684. */
  166685. {
  166686. int c, c2;
  166687. INPUT_VARS(cinfo);
  166688. INPUT_BYTE(cinfo, c, return FALSE);
  166689. INPUT_BYTE(cinfo, c2, return FALSE);
  166690. if (c != 0xFF || c2 != (int) M_SOI)
  166691. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  166692. cinfo->unread_marker = c2;
  166693. INPUT_SYNC(cinfo);
  166694. return TRUE;
  166695. }
  166696. /*
  166697. * Read markers until SOS or EOI.
  166698. *
  166699. * Returns same codes as are defined for jpeg_consume_input:
  166700. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  166701. */
  166702. METHODDEF(int)
  166703. read_markers (j_decompress_ptr cinfo)
  166704. {
  166705. /* Outer loop repeats once for each marker. */
  166706. for (;;) {
  166707. /* Collect the marker proper, unless we already did. */
  166708. /* NB: first_marker() enforces the requirement that SOI appear first. */
  166709. if (cinfo->unread_marker == 0) {
  166710. if (! cinfo->marker->saw_SOI) {
  166711. if (! first_marker(cinfo))
  166712. return JPEG_SUSPENDED;
  166713. } else {
  166714. if (! next_marker(cinfo))
  166715. return JPEG_SUSPENDED;
  166716. }
  166717. }
  166718. /* At this point cinfo->unread_marker contains the marker code and the
  166719. * input point is just past the marker proper, but before any parameters.
  166720. * A suspension will cause us to return with this state still true.
  166721. */
  166722. switch (cinfo->unread_marker) {
  166723. case M_SOI:
  166724. if (! get_soi(cinfo))
  166725. return JPEG_SUSPENDED;
  166726. break;
  166727. case M_SOF0: /* Baseline */
  166728. case M_SOF1: /* Extended sequential, Huffman */
  166729. if (! get_sof(cinfo, FALSE, FALSE))
  166730. return JPEG_SUSPENDED;
  166731. break;
  166732. case M_SOF2: /* Progressive, Huffman */
  166733. if (! get_sof(cinfo, TRUE, FALSE))
  166734. return JPEG_SUSPENDED;
  166735. break;
  166736. case M_SOF9: /* Extended sequential, arithmetic */
  166737. if (! get_sof(cinfo, FALSE, TRUE))
  166738. return JPEG_SUSPENDED;
  166739. break;
  166740. case M_SOF10: /* Progressive, arithmetic */
  166741. if (! get_sof(cinfo, TRUE, TRUE))
  166742. return JPEG_SUSPENDED;
  166743. break;
  166744. /* Currently unsupported SOFn types */
  166745. case M_SOF3: /* Lossless, Huffman */
  166746. case M_SOF5: /* Differential sequential, Huffman */
  166747. case M_SOF6: /* Differential progressive, Huffman */
  166748. case M_SOF7: /* Differential lossless, Huffman */
  166749. case M_JPG: /* Reserved for JPEG extensions */
  166750. case M_SOF11: /* Lossless, arithmetic */
  166751. case M_SOF13: /* Differential sequential, arithmetic */
  166752. case M_SOF14: /* Differential progressive, arithmetic */
  166753. case M_SOF15: /* Differential lossless, arithmetic */
  166754. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  166755. break;
  166756. case M_SOS:
  166757. if (! get_sos(cinfo))
  166758. return JPEG_SUSPENDED;
  166759. cinfo->unread_marker = 0; /* processed the marker */
  166760. return JPEG_REACHED_SOS;
  166761. case M_EOI:
  166762. TRACEMS(cinfo, 1, JTRC_EOI);
  166763. cinfo->unread_marker = 0; /* processed the marker */
  166764. return JPEG_REACHED_EOI;
  166765. case M_DAC:
  166766. if (! get_dac(cinfo))
  166767. return JPEG_SUSPENDED;
  166768. break;
  166769. case M_DHT:
  166770. if (! get_dht(cinfo))
  166771. return JPEG_SUSPENDED;
  166772. break;
  166773. case M_DQT:
  166774. if (! get_dqt(cinfo))
  166775. return JPEG_SUSPENDED;
  166776. break;
  166777. case M_DRI:
  166778. if (! get_dri(cinfo))
  166779. return JPEG_SUSPENDED;
  166780. break;
  166781. case M_APP0:
  166782. case M_APP1:
  166783. case M_APP2:
  166784. case M_APP3:
  166785. case M_APP4:
  166786. case M_APP5:
  166787. case M_APP6:
  166788. case M_APP7:
  166789. case M_APP8:
  166790. case M_APP9:
  166791. case M_APP10:
  166792. case M_APP11:
  166793. case M_APP12:
  166794. case M_APP13:
  166795. case M_APP14:
  166796. case M_APP15:
  166797. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  166798. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  166799. return JPEG_SUSPENDED;
  166800. break;
  166801. case M_COM:
  166802. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  166803. return JPEG_SUSPENDED;
  166804. break;
  166805. case M_RST0: /* these are all parameterless */
  166806. case M_RST1:
  166807. case M_RST2:
  166808. case M_RST3:
  166809. case M_RST4:
  166810. case M_RST5:
  166811. case M_RST6:
  166812. case M_RST7:
  166813. case M_TEM:
  166814. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  166815. break;
  166816. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  166817. if (! skip_variable(cinfo))
  166818. return JPEG_SUSPENDED;
  166819. break;
  166820. default: /* must be DHP, EXP, JPGn, or RESn */
  166821. /* For now, we treat the reserved markers as fatal errors since they are
  166822. * likely to be used to signal incompatible JPEG Part 3 extensions.
  166823. * Once the JPEG 3 version-number marker is well defined, this code
  166824. * ought to change!
  166825. */
  166826. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  166827. break;
  166828. }
  166829. /* Successfully processed marker, so reset state variable */
  166830. cinfo->unread_marker = 0;
  166831. } /* end loop */
  166832. }
  166833. /*
  166834. * Read a restart marker, which is expected to appear next in the datastream;
  166835. * if the marker is not there, take appropriate recovery action.
  166836. * Returns FALSE if suspension is required.
  166837. *
  166838. * This is called by the entropy decoder after it has read an appropriate
  166839. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  166840. * has already read a marker from the data source. Under normal conditions
  166841. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  166842. * it holds a marker which the decoder will be unable to read past.
  166843. */
  166844. METHODDEF(boolean)
  166845. read_restart_marker (j_decompress_ptr cinfo)
  166846. {
  166847. /* Obtain a marker unless we already did. */
  166848. /* Note that next_marker will complain if it skips any data. */
  166849. if (cinfo->unread_marker == 0) {
  166850. if (! next_marker(cinfo))
  166851. return FALSE;
  166852. }
  166853. if (cinfo->unread_marker ==
  166854. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  166855. /* Normal case --- swallow the marker and let entropy decoder continue */
  166856. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  166857. cinfo->unread_marker = 0;
  166858. } else {
  166859. /* Uh-oh, the restart markers have been messed up. */
  166860. /* Let the data source manager determine how to resync. */
  166861. if (! (*cinfo->src->resync_to_restart) (cinfo,
  166862. cinfo->marker->next_restart_num))
  166863. return FALSE;
  166864. }
  166865. /* Update next-restart state */
  166866. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  166867. return TRUE;
  166868. }
  166869. /*
  166870. * This is the default resync_to_restart method for data source managers
  166871. * to use if they don't have any better approach. Some data source managers
  166872. * may be able to back up, or may have additional knowledge about the data
  166873. * which permits a more intelligent recovery strategy; such managers would
  166874. * presumably supply their own resync method.
  166875. *
  166876. * read_restart_marker calls resync_to_restart if it finds a marker other than
  166877. * the restart marker it was expecting. (This code is *not* used unless
  166878. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  166879. * the marker code actually found (might be anything, except 0 or FF).
  166880. * The desired restart marker number (0..7) is passed as a parameter.
  166881. * This routine is supposed to apply whatever error recovery strategy seems
  166882. * appropriate in order to position the input stream to the next data segment.
  166883. * Note that cinfo->unread_marker is treated as a marker appearing before
  166884. * the current data-source input point; usually it should be reset to zero
  166885. * before returning.
  166886. * Returns FALSE if suspension is required.
  166887. *
  166888. * This implementation is substantially constrained by wanting to treat the
  166889. * input as a data stream; this means we can't back up. Therefore, we have
  166890. * only the following actions to work with:
  166891. * 1. Simply discard the marker and let the entropy decoder resume at next
  166892. * byte of file.
  166893. * 2. Read forward until we find another marker, discarding intervening
  166894. * data. (In theory we could look ahead within the current bufferload,
  166895. * without having to discard data if we don't find the desired marker.
  166896. * This idea is not implemented here, in part because it makes behavior
  166897. * dependent on buffer size and chance buffer-boundary positions.)
  166898. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  166899. * This will cause the entropy decoder to process an empty data segment,
  166900. * inserting dummy zeroes, and then we will reprocess the marker.
  166901. *
  166902. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  166903. * appropriate if the found marker is a future restart marker (indicating
  166904. * that we have missed the desired restart marker, probably because it got
  166905. * corrupted).
  166906. * We apply #2 or #3 if the found marker is a restart marker no more than
  166907. * two counts behind or ahead of the expected one. We also apply #2 if the
  166908. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  166909. * If the found marker is a restart marker more than 2 counts away, we do #1
  166910. * (too much risk that the marker is erroneous; with luck we will be able to
  166911. * resync at some future point).
  166912. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  166913. * overrunning the end of a scan. An implementation limited to single-scan
  166914. * files might find it better to apply #2 for markers other than EOI, since
  166915. * any other marker would have to be bogus data in that case.
  166916. */
  166917. GLOBAL(boolean)
  166918. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  166919. {
  166920. int marker = cinfo->unread_marker;
  166921. int action = 1;
  166922. /* Always put up a warning. */
  166923. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  166924. /* Outer loop handles repeated decision after scanning forward. */
  166925. for (;;) {
  166926. if (marker < (int) M_SOF0)
  166927. action = 2; /* invalid marker */
  166928. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  166929. action = 3; /* valid non-restart marker */
  166930. else {
  166931. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  166932. marker == ((int) M_RST0 + ((desired+2) & 7)))
  166933. action = 3; /* one of the next two expected restarts */
  166934. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  166935. marker == ((int) M_RST0 + ((desired-2) & 7)))
  166936. action = 2; /* a prior restart, so advance */
  166937. else
  166938. action = 1; /* desired restart or too far away */
  166939. }
  166940. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  166941. switch (action) {
  166942. case 1:
  166943. /* Discard marker and let entropy decoder resume processing. */
  166944. cinfo->unread_marker = 0;
  166945. return TRUE;
  166946. case 2:
  166947. /* Scan to the next marker, and repeat the decision loop. */
  166948. if (! next_marker(cinfo))
  166949. return FALSE;
  166950. marker = cinfo->unread_marker;
  166951. break;
  166952. case 3:
  166953. /* Return without advancing past this marker. */
  166954. /* Entropy decoder will be forced to process an empty segment. */
  166955. return TRUE;
  166956. }
  166957. } /* end loop */
  166958. }
  166959. /*
  166960. * Reset marker processing state to begin a fresh datastream.
  166961. */
  166962. METHODDEF(void)
  166963. reset_marker_reader (j_decompress_ptr cinfo)
  166964. {
  166965. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  166966. cinfo->comp_info = NULL; /* until allocated by get_sof */
  166967. cinfo->input_scan_number = 0; /* no SOS seen yet */
  166968. cinfo->unread_marker = 0; /* no pending marker */
  166969. marker->pub.saw_SOI = FALSE; /* set internal state too */
  166970. marker->pub.saw_SOF = FALSE;
  166971. marker->pub.discarded_bytes = 0;
  166972. marker->cur_marker = NULL;
  166973. }
  166974. /*
  166975. * Initialize the marker reader module.
  166976. * This is called only once, when the decompression object is created.
  166977. */
  166978. GLOBAL(void)
  166979. jinit_marker_reader (j_decompress_ptr cinfo)
  166980. {
  166981. my_marker_ptr2 marker;
  166982. int i;
  166983. /* Create subobject in permanent pool */
  166984. marker = (my_marker_ptr2)
  166985. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  166986. SIZEOF(my_marker_reader));
  166987. cinfo->marker = (struct jpeg_marker_reader *) marker;
  166988. /* Initialize public method pointers */
  166989. marker->pub.reset_marker_reader = reset_marker_reader;
  166990. marker->pub.read_markers = read_markers;
  166991. marker->pub.read_restart_marker = read_restart_marker;
  166992. /* Initialize COM/APPn processing.
  166993. * By default, we examine and then discard APP0 and APP14,
  166994. * but simply discard COM and all other APPn.
  166995. */
  166996. marker->process_COM = skip_variable;
  166997. marker->length_limit_COM = 0;
  166998. for (i = 0; i < 16; i++) {
  166999. marker->process_APPn[i] = skip_variable;
  167000. marker->length_limit_APPn[i] = 0;
  167001. }
  167002. marker->process_APPn[0] = get_interesting_appn;
  167003. marker->process_APPn[14] = get_interesting_appn;
  167004. /* Reset marker processing state */
  167005. reset_marker_reader(cinfo);
  167006. }
  167007. /*
  167008. * Control saving of COM and APPn markers into marker_list.
  167009. */
  167010. #ifdef SAVE_MARKERS_SUPPORTED
  167011. GLOBAL(void)
  167012. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  167013. unsigned int length_limit)
  167014. {
  167015. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167016. long maxlength;
  167017. jpeg_marker_parser_method processor;
  167018. /* Length limit mustn't be larger than what we can allocate
  167019. * (should only be a concern in a 16-bit environment).
  167020. */
  167021. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  167022. if (((long) length_limit) > maxlength)
  167023. length_limit = (unsigned int) maxlength;
  167024. /* Choose processor routine to use.
  167025. * APP0/APP14 have special requirements.
  167026. */
  167027. if (length_limit) {
  167028. processor = save_marker;
  167029. /* If saving APP0/APP14, save at least enough for our internal use. */
  167030. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  167031. length_limit = APP0_DATA_LEN;
  167032. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  167033. length_limit = APP14_DATA_LEN;
  167034. } else {
  167035. processor = skip_variable;
  167036. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  167037. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  167038. processor = get_interesting_appn;
  167039. }
  167040. if (marker_code == (int) M_COM) {
  167041. marker->process_COM = processor;
  167042. marker->length_limit_COM = length_limit;
  167043. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  167044. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  167045. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  167046. } else
  167047. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  167048. }
  167049. #endif /* SAVE_MARKERS_SUPPORTED */
  167050. /*
  167051. * Install a special processing method for COM or APPn markers.
  167052. */
  167053. GLOBAL(void)
  167054. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  167055. jpeg_marker_parser_method routine)
  167056. {
  167057. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167058. if (marker_code == (int) M_COM)
  167059. marker->process_COM = routine;
  167060. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  167061. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  167062. else
  167063. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  167064. }
  167065. /********* End of inlined file: jdmarker.c *********/
  167066. /********* Start of inlined file: jdmaster.c *********/
  167067. #define JPEG_INTERNALS
  167068. /* Private state */
  167069. typedef struct {
  167070. struct jpeg_decomp_master pub; /* public fields */
  167071. int pass_number; /* # of passes completed */
  167072. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  167073. /* Saved references to initialized quantizer modules,
  167074. * in case we need to switch modes.
  167075. */
  167076. struct jpeg_color_quantizer * quantizer_1pass;
  167077. struct jpeg_color_quantizer * quantizer_2pass;
  167078. } my_decomp_master;
  167079. typedef my_decomp_master * my_master_ptr6;
  167080. /*
  167081. * Determine whether merged upsample/color conversion should be used.
  167082. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  167083. */
  167084. LOCAL(boolean)
  167085. use_merged_upsample (j_decompress_ptr cinfo)
  167086. {
  167087. #ifdef UPSAMPLE_MERGING_SUPPORTED
  167088. /* Merging is the equivalent of plain box-filter upsampling */
  167089. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  167090. return FALSE;
  167091. /* jdmerge.c only supports YCC=>RGB color conversion */
  167092. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  167093. cinfo->out_color_space != JCS_RGB ||
  167094. cinfo->out_color_components != RGB_PIXELSIZE)
  167095. return FALSE;
  167096. /* and it only handles 2h1v or 2h2v sampling ratios */
  167097. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  167098. cinfo->comp_info[1].h_samp_factor != 1 ||
  167099. cinfo->comp_info[2].h_samp_factor != 1 ||
  167100. cinfo->comp_info[0].v_samp_factor > 2 ||
  167101. cinfo->comp_info[1].v_samp_factor != 1 ||
  167102. cinfo->comp_info[2].v_samp_factor != 1)
  167103. return FALSE;
  167104. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  167105. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  167106. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  167107. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  167108. return FALSE;
  167109. /* ??? also need to test for upsample-time rescaling, when & if supported */
  167110. return TRUE; /* by golly, it'll work... */
  167111. #else
  167112. return FALSE;
  167113. #endif
  167114. }
  167115. /*
  167116. * Compute output image dimensions and related values.
  167117. * NOTE: this is exported for possible use by application.
  167118. * Hence it mustn't do anything that can't be done twice.
  167119. * Also note that it may be called before the master module is initialized!
  167120. */
  167121. GLOBAL(void)
  167122. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  167123. /* Do computations that are needed before master selection phase */
  167124. {
  167125. #ifdef IDCT_SCALING_SUPPORTED
  167126. int ci;
  167127. jpeg_component_info *compptr;
  167128. #endif
  167129. /* Prevent application from calling me at wrong times */
  167130. if (cinfo->global_state != DSTATE_READY)
  167131. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167132. #ifdef IDCT_SCALING_SUPPORTED
  167133. /* Compute actual output image dimensions and DCT scaling choices. */
  167134. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  167135. /* Provide 1/8 scaling */
  167136. cinfo->output_width = (JDIMENSION)
  167137. jdiv_round_up((long) cinfo->image_width, 8L);
  167138. cinfo->output_height = (JDIMENSION)
  167139. jdiv_round_up((long) cinfo->image_height, 8L);
  167140. cinfo->min_DCT_scaled_size = 1;
  167141. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  167142. /* Provide 1/4 scaling */
  167143. cinfo->output_width = (JDIMENSION)
  167144. jdiv_round_up((long) cinfo->image_width, 4L);
  167145. cinfo->output_height = (JDIMENSION)
  167146. jdiv_round_up((long) cinfo->image_height, 4L);
  167147. cinfo->min_DCT_scaled_size = 2;
  167148. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  167149. /* Provide 1/2 scaling */
  167150. cinfo->output_width = (JDIMENSION)
  167151. jdiv_round_up((long) cinfo->image_width, 2L);
  167152. cinfo->output_height = (JDIMENSION)
  167153. jdiv_round_up((long) cinfo->image_height, 2L);
  167154. cinfo->min_DCT_scaled_size = 4;
  167155. } else {
  167156. /* Provide 1/1 scaling */
  167157. cinfo->output_width = cinfo->image_width;
  167158. cinfo->output_height = cinfo->image_height;
  167159. cinfo->min_DCT_scaled_size = DCTSIZE;
  167160. }
  167161. /* In selecting the actual DCT scaling for each component, we try to
  167162. * scale up the chroma components via IDCT scaling rather than upsampling.
  167163. * This saves time if the upsampler gets to use 1:1 scaling.
  167164. * Note this code assumes that the supported DCT scalings are powers of 2.
  167165. */
  167166. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167167. ci++, compptr++) {
  167168. int ssize = cinfo->min_DCT_scaled_size;
  167169. while (ssize < DCTSIZE &&
  167170. (compptr->h_samp_factor * ssize * 2 <=
  167171. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  167172. (compptr->v_samp_factor * ssize * 2 <=
  167173. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  167174. ssize = ssize * 2;
  167175. }
  167176. compptr->DCT_scaled_size = ssize;
  167177. }
  167178. /* Recompute downsampled dimensions of components;
  167179. * application needs to know these if using raw downsampled data.
  167180. */
  167181. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167182. ci++, compptr++) {
  167183. /* Size in samples, after IDCT scaling */
  167184. compptr->downsampled_width = (JDIMENSION)
  167185. jdiv_round_up((long) cinfo->image_width *
  167186. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  167187. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  167188. compptr->downsampled_height = (JDIMENSION)
  167189. jdiv_round_up((long) cinfo->image_height *
  167190. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  167191. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  167192. }
  167193. #else /* !IDCT_SCALING_SUPPORTED */
  167194. /* Hardwire it to "no scaling" */
  167195. cinfo->output_width = cinfo->image_width;
  167196. cinfo->output_height = cinfo->image_height;
  167197. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  167198. * and has computed unscaled downsampled_width and downsampled_height.
  167199. */
  167200. #endif /* IDCT_SCALING_SUPPORTED */
  167201. /* Report number of components in selected colorspace. */
  167202. /* Probably this should be in the color conversion module... */
  167203. switch (cinfo->out_color_space) {
  167204. case JCS_GRAYSCALE:
  167205. cinfo->out_color_components = 1;
  167206. break;
  167207. case JCS_RGB:
  167208. #if RGB_PIXELSIZE != 3
  167209. cinfo->out_color_components = RGB_PIXELSIZE;
  167210. break;
  167211. #endif /* else share code with YCbCr */
  167212. case JCS_YCbCr:
  167213. cinfo->out_color_components = 3;
  167214. break;
  167215. case JCS_CMYK:
  167216. case JCS_YCCK:
  167217. cinfo->out_color_components = 4;
  167218. break;
  167219. default: /* else must be same colorspace as in file */
  167220. cinfo->out_color_components = cinfo->num_components;
  167221. break;
  167222. }
  167223. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  167224. cinfo->out_color_components);
  167225. /* See if upsampler will want to emit more than one row at a time */
  167226. if (use_merged_upsample(cinfo))
  167227. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  167228. else
  167229. cinfo->rec_outbuf_height = 1;
  167230. }
  167231. /*
  167232. * Several decompression processes need to range-limit values to the range
  167233. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  167234. * due to noise introduced by quantization, roundoff error, etc. These
  167235. * processes are inner loops and need to be as fast as possible. On most
  167236. * machines, particularly CPUs with pipelines or instruction prefetch,
  167237. * a (subscript-check-less) C table lookup
  167238. * x = sample_range_limit[x];
  167239. * is faster than explicit tests
  167240. * if (x < 0) x = 0;
  167241. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  167242. * These processes all use a common table prepared by the routine below.
  167243. *
  167244. * For most steps we can mathematically guarantee that the initial value
  167245. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  167246. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  167247. * limiting step (just after the IDCT), a wildly out-of-range value is
  167248. * possible if the input data is corrupt. To avoid any chance of indexing
  167249. * off the end of memory and getting a bad-pointer trap, we perform the
  167250. * post-IDCT limiting thus:
  167251. * x = range_limit[x & MASK];
  167252. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  167253. * samples. Under normal circumstances this is more than enough range and
  167254. * a correct output will be generated; with bogus input data the mask will
  167255. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  167256. * For the post-IDCT step, we want to convert the data from signed to unsigned
  167257. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  167258. * So the post-IDCT limiting table ends up looking like this:
  167259. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  167260. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  167261. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  167262. * 0,1,...,CENTERJSAMPLE-1
  167263. * Negative inputs select values from the upper half of the table after
  167264. * masking.
  167265. *
  167266. * We can save some space by overlapping the start of the post-IDCT table
  167267. * with the simpler range limiting table. The post-IDCT table begins at
  167268. * sample_range_limit + CENTERJSAMPLE.
  167269. *
  167270. * Note that the table is allocated in near data space on PCs; it's small
  167271. * enough and used often enough to justify this.
  167272. */
  167273. LOCAL(void)
  167274. prepare_range_limit_table (j_decompress_ptr cinfo)
  167275. /* Allocate and fill in the sample_range_limit table */
  167276. {
  167277. JSAMPLE * table;
  167278. int i;
  167279. table = (JSAMPLE *)
  167280. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167281. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  167282. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  167283. cinfo->sample_range_limit = table;
  167284. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  167285. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  167286. /* Main part of "simple" table: limit[x] = x */
  167287. for (i = 0; i <= MAXJSAMPLE; i++)
  167288. table[i] = (JSAMPLE) i;
  167289. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  167290. /* End of simple table, rest of first half of post-IDCT table */
  167291. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  167292. table[i] = MAXJSAMPLE;
  167293. /* Second half of post-IDCT table */
  167294. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  167295. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  167296. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  167297. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  167298. }
  167299. /*
  167300. * Master selection of decompression modules.
  167301. * This is done once at jpeg_start_decompress time. We determine
  167302. * which modules will be used and give them appropriate initialization calls.
  167303. * We also initialize the decompressor input side to begin consuming data.
  167304. *
  167305. * Since jpeg_read_header has finished, we know what is in the SOF
  167306. * and (first) SOS markers. We also have all the application parameter
  167307. * settings.
  167308. */
  167309. LOCAL(void)
  167310. master_selection (j_decompress_ptr cinfo)
  167311. {
  167312. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  167313. boolean use_c_buffer;
  167314. long samplesperrow;
  167315. JDIMENSION jd_samplesperrow;
  167316. /* Initialize dimensions and other stuff */
  167317. jpeg_calc_output_dimensions(cinfo);
  167318. prepare_range_limit_table(cinfo);
  167319. /* Width of an output scanline must be representable as JDIMENSION. */
  167320. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  167321. jd_samplesperrow = (JDIMENSION) samplesperrow;
  167322. if ((long) jd_samplesperrow != samplesperrow)
  167323. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  167324. /* Initialize my private state */
  167325. master->pass_number = 0;
  167326. master->using_merged_upsample = use_merged_upsample(cinfo);
  167327. /* Color quantizer selection */
  167328. master->quantizer_1pass = NULL;
  167329. master->quantizer_2pass = NULL;
  167330. /* No mode changes if not using buffered-image mode. */
  167331. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  167332. cinfo->enable_1pass_quant = FALSE;
  167333. cinfo->enable_external_quant = FALSE;
  167334. cinfo->enable_2pass_quant = FALSE;
  167335. }
  167336. if (cinfo->quantize_colors) {
  167337. if (cinfo->raw_data_out)
  167338. ERREXIT(cinfo, JERR_NOTIMPL);
  167339. /* 2-pass quantizer only works in 3-component color space. */
  167340. if (cinfo->out_color_components != 3) {
  167341. cinfo->enable_1pass_quant = TRUE;
  167342. cinfo->enable_external_quant = FALSE;
  167343. cinfo->enable_2pass_quant = FALSE;
  167344. cinfo->colormap = NULL;
  167345. } else if (cinfo->colormap != NULL) {
  167346. cinfo->enable_external_quant = TRUE;
  167347. } else if (cinfo->two_pass_quantize) {
  167348. cinfo->enable_2pass_quant = TRUE;
  167349. } else {
  167350. cinfo->enable_1pass_quant = TRUE;
  167351. }
  167352. if (cinfo->enable_1pass_quant) {
  167353. #ifdef QUANT_1PASS_SUPPORTED
  167354. jinit_1pass_quantizer(cinfo);
  167355. master->quantizer_1pass = cinfo->cquantize;
  167356. #else
  167357. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167358. #endif
  167359. }
  167360. /* We use the 2-pass code to map to external colormaps. */
  167361. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  167362. #ifdef QUANT_2PASS_SUPPORTED
  167363. jinit_2pass_quantizer(cinfo);
  167364. master->quantizer_2pass = cinfo->cquantize;
  167365. #else
  167366. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167367. #endif
  167368. }
  167369. /* If both quantizers are initialized, the 2-pass one is left active;
  167370. * this is necessary for starting with quantization to an external map.
  167371. */
  167372. }
  167373. /* Post-processing: in particular, color conversion first */
  167374. if (! cinfo->raw_data_out) {
  167375. if (master->using_merged_upsample) {
  167376. #ifdef UPSAMPLE_MERGING_SUPPORTED
  167377. jinit_merged_upsampler(cinfo); /* does color conversion too */
  167378. #else
  167379. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167380. #endif
  167381. } else {
  167382. jinit_color_deconverter(cinfo);
  167383. jinit_upsampler(cinfo);
  167384. }
  167385. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  167386. }
  167387. /* Inverse DCT */
  167388. jinit_inverse_dct(cinfo);
  167389. /* Entropy decoding: either Huffman or arithmetic coding. */
  167390. if (cinfo->arith_code) {
  167391. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167392. } else {
  167393. if (cinfo->progressive_mode) {
  167394. #ifdef D_PROGRESSIVE_SUPPORTED
  167395. jinit_phuff_decoder(cinfo);
  167396. #else
  167397. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167398. #endif
  167399. } else
  167400. jinit_huff_decoder(cinfo);
  167401. }
  167402. /* Initialize principal buffer controllers. */
  167403. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  167404. jinit_d_coef_controller(cinfo, use_c_buffer);
  167405. if (! cinfo->raw_data_out)
  167406. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  167407. /* We can now tell the memory manager to allocate virtual arrays. */
  167408. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167409. /* Initialize input side of decompressor to consume first scan. */
  167410. (*cinfo->inputctl->start_input_pass) (cinfo);
  167411. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167412. /* If jpeg_start_decompress will read the whole file, initialize
  167413. * progress monitoring appropriately. The input step is counted
  167414. * as one pass.
  167415. */
  167416. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  167417. cinfo->inputctl->has_multiple_scans) {
  167418. int nscans;
  167419. /* Estimate number of scans to set pass_limit. */
  167420. if (cinfo->progressive_mode) {
  167421. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  167422. nscans = 2 + 3 * cinfo->num_components;
  167423. } else {
  167424. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  167425. nscans = cinfo->num_components;
  167426. }
  167427. cinfo->progress->pass_counter = 0L;
  167428. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  167429. cinfo->progress->completed_passes = 0;
  167430. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  167431. /* Count the input pass as done */
  167432. master->pass_number++;
  167433. }
  167434. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167435. }
  167436. /*
  167437. * Per-pass setup.
  167438. * This is called at the beginning of each output pass. We determine which
  167439. * modules will be active during this pass and give them appropriate
  167440. * start_pass calls. We also set is_dummy_pass to indicate whether this
  167441. * is a "real" output pass or a dummy pass for color quantization.
  167442. * (In the latter case, jdapistd.c will crank the pass to completion.)
  167443. */
  167444. METHODDEF(void)
  167445. prepare_for_output_pass (j_decompress_ptr cinfo)
  167446. {
  167447. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  167448. if (master->pub.is_dummy_pass) {
  167449. #ifdef QUANT_2PASS_SUPPORTED
  167450. /* Final pass of 2-pass quantization */
  167451. master->pub.is_dummy_pass = FALSE;
  167452. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  167453. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  167454. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  167455. #else
  167456. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167457. #endif /* QUANT_2PASS_SUPPORTED */
  167458. } else {
  167459. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  167460. /* Select new quantization method */
  167461. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  167462. cinfo->cquantize = master->quantizer_2pass;
  167463. master->pub.is_dummy_pass = TRUE;
  167464. } else if (cinfo->enable_1pass_quant) {
  167465. cinfo->cquantize = master->quantizer_1pass;
  167466. } else {
  167467. ERREXIT(cinfo, JERR_MODE_CHANGE);
  167468. }
  167469. }
  167470. (*cinfo->idct->start_pass) (cinfo);
  167471. (*cinfo->coef->start_output_pass) (cinfo);
  167472. if (! cinfo->raw_data_out) {
  167473. if (! master->using_merged_upsample)
  167474. (*cinfo->cconvert->start_pass) (cinfo);
  167475. (*cinfo->upsample->start_pass) (cinfo);
  167476. if (cinfo->quantize_colors)
  167477. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  167478. (*cinfo->post->start_pass) (cinfo,
  167479. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  167480. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  167481. }
  167482. }
  167483. /* Set up progress monitor's pass info if present */
  167484. if (cinfo->progress != NULL) {
  167485. cinfo->progress->completed_passes = master->pass_number;
  167486. cinfo->progress->total_passes = master->pass_number +
  167487. (master->pub.is_dummy_pass ? 2 : 1);
  167488. /* In buffered-image mode, we assume one more output pass if EOI not
  167489. * yet reached, but no more passes if EOI has been reached.
  167490. */
  167491. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  167492. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  167493. }
  167494. }
  167495. }
  167496. /*
  167497. * Finish up at end of an output pass.
  167498. */
  167499. METHODDEF(void)
  167500. finish_output_pass (j_decompress_ptr cinfo)
  167501. {
  167502. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  167503. if (cinfo->quantize_colors)
  167504. (*cinfo->cquantize->finish_pass) (cinfo);
  167505. master->pass_number++;
  167506. }
  167507. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167508. /*
  167509. * Switch to a new external colormap between output passes.
  167510. */
  167511. GLOBAL(void)
  167512. jpeg_new_colormap (j_decompress_ptr cinfo)
  167513. {
  167514. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  167515. /* Prevent application from calling me at wrong times */
  167516. if (cinfo->global_state != DSTATE_BUFIMAGE)
  167517. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167518. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  167519. cinfo->colormap != NULL) {
  167520. /* Select 2-pass quantizer for external colormap use */
  167521. cinfo->cquantize = master->quantizer_2pass;
  167522. /* Notify quantizer of colormap change */
  167523. (*cinfo->cquantize->new_color_map) (cinfo);
  167524. master->pub.is_dummy_pass = FALSE; /* just in case */
  167525. } else
  167526. ERREXIT(cinfo, JERR_MODE_CHANGE);
  167527. }
  167528. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167529. /*
  167530. * Initialize master decompression control and select active modules.
  167531. * This is performed at the start of jpeg_start_decompress.
  167532. */
  167533. GLOBAL(void)
  167534. jinit_master_decompress (j_decompress_ptr cinfo)
  167535. {
  167536. my_master_ptr6 master;
  167537. master = (my_master_ptr6)
  167538. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167539. SIZEOF(my_decomp_master));
  167540. cinfo->master = (struct jpeg_decomp_master *) master;
  167541. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  167542. master->pub.finish_output_pass = finish_output_pass;
  167543. master->pub.is_dummy_pass = FALSE;
  167544. master_selection(cinfo);
  167545. }
  167546. /********* End of inlined file: jdmaster.c *********/
  167547. #undef FIX
  167548. /********* Start of inlined file: jdmerge.c *********/
  167549. #define JPEG_INTERNALS
  167550. #ifdef UPSAMPLE_MERGING_SUPPORTED
  167551. /* Private subobject */
  167552. typedef struct {
  167553. struct jpeg_upsampler pub; /* public fields */
  167554. /* Pointer to routine to do actual upsampling/conversion of one row group */
  167555. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  167556. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  167557. JSAMPARRAY output_buf));
  167558. /* Private state for YCC->RGB conversion */
  167559. int * Cr_r_tab; /* => table for Cr to R conversion */
  167560. int * Cb_b_tab; /* => table for Cb to B conversion */
  167561. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  167562. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  167563. /* For 2:1 vertical sampling, we produce two output rows at a time.
  167564. * We need a "spare" row buffer to hold the second output row if the
  167565. * application provides just a one-row buffer; we also use the spare
  167566. * to discard the dummy last row if the image height is odd.
  167567. */
  167568. JSAMPROW spare_row;
  167569. boolean spare_full; /* T if spare buffer is occupied */
  167570. JDIMENSION out_row_width; /* samples per output row */
  167571. JDIMENSION rows_to_go; /* counts rows remaining in image */
  167572. } my_upsampler;
  167573. typedef my_upsampler * my_upsample_ptr;
  167574. #define SCALEBITS 16 /* speediest right-shift on some machines */
  167575. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  167576. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  167577. /*
  167578. * Initialize tables for YCC->RGB colorspace conversion.
  167579. * This is taken directly from jdcolor.c; see that file for more info.
  167580. */
  167581. LOCAL(void)
  167582. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  167583. {
  167584. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  167585. int i;
  167586. INT32 x;
  167587. SHIFT_TEMPS
  167588. upsample->Cr_r_tab = (int *)
  167589. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167590. (MAXJSAMPLE+1) * SIZEOF(int));
  167591. upsample->Cb_b_tab = (int *)
  167592. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167593. (MAXJSAMPLE+1) * SIZEOF(int));
  167594. upsample->Cr_g_tab = (INT32 *)
  167595. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167596. (MAXJSAMPLE+1) * SIZEOF(INT32));
  167597. upsample->Cb_g_tab = (INT32 *)
  167598. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167599. (MAXJSAMPLE+1) * SIZEOF(INT32));
  167600. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  167601. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  167602. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  167603. /* Cr=>R value is nearest int to 1.40200 * x */
  167604. upsample->Cr_r_tab[i] = (int)
  167605. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  167606. /* Cb=>B value is nearest int to 1.77200 * x */
  167607. upsample->Cb_b_tab[i] = (int)
  167608. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  167609. /* Cr=>G value is scaled-up -0.71414 * x */
  167610. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  167611. /* Cb=>G value is scaled-up -0.34414 * x */
  167612. /* We also add in ONE_HALF so that need not do it in inner loop */
  167613. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  167614. }
  167615. }
  167616. /*
  167617. * Initialize for an upsampling pass.
  167618. */
  167619. METHODDEF(void)
  167620. start_pass_merged_upsample (j_decompress_ptr cinfo)
  167621. {
  167622. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  167623. /* Mark the spare buffer empty */
  167624. upsample->spare_full = FALSE;
  167625. /* Initialize total-height counter for detecting bottom of image */
  167626. upsample->rows_to_go = cinfo->output_height;
  167627. }
  167628. /*
  167629. * Control routine to do upsampling (and color conversion).
  167630. *
  167631. * The control routine just handles the row buffering considerations.
  167632. */
  167633. METHODDEF(void)
  167634. merged_2v_upsample (j_decompress_ptr cinfo,
  167635. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167636. JDIMENSION in_row_groups_avail,
  167637. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167638. JDIMENSION out_rows_avail)
  167639. /* 2:1 vertical sampling case: may need a spare row. */
  167640. {
  167641. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  167642. JSAMPROW work_ptrs[2];
  167643. JDIMENSION num_rows; /* number of rows returned to caller */
  167644. if (upsample->spare_full) {
  167645. /* If we have a spare row saved from a previous cycle, just return it. */
  167646. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  167647. 1, upsample->out_row_width);
  167648. num_rows = 1;
  167649. upsample->spare_full = FALSE;
  167650. } else {
  167651. /* Figure number of rows to return to caller. */
  167652. num_rows = 2;
  167653. /* Not more than the distance to the end of the image. */
  167654. if (num_rows > upsample->rows_to_go)
  167655. num_rows = upsample->rows_to_go;
  167656. /* And not more than what the client can accept: */
  167657. out_rows_avail -= *out_row_ctr;
  167658. if (num_rows > out_rows_avail)
  167659. num_rows = out_rows_avail;
  167660. /* Create output pointer array for upsampler. */
  167661. work_ptrs[0] = output_buf[*out_row_ctr];
  167662. if (num_rows > 1) {
  167663. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  167664. } else {
  167665. work_ptrs[1] = upsample->spare_row;
  167666. upsample->spare_full = TRUE;
  167667. }
  167668. /* Now do the upsampling. */
  167669. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  167670. }
  167671. /* Adjust counts */
  167672. *out_row_ctr += num_rows;
  167673. upsample->rows_to_go -= num_rows;
  167674. /* When the buffer is emptied, declare this input row group consumed */
  167675. if (! upsample->spare_full)
  167676. (*in_row_group_ctr)++;
  167677. }
  167678. METHODDEF(void)
  167679. merged_1v_upsample (j_decompress_ptr cinfo,
  167680. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167681. JDIMENSION in_row_groups_avail,
  167682. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167683. JDIMENSION out_rows_avail)
  167684. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  167685. {
  167686. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  167687. /* Just do the upsampling. */
  167688. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  167689. output_buf + *out_row_ctr);
  167690. /* Adjust counts */
  167691. (*out_row_ctr)++;
  167692. (*in_row_group_ctr)++;
  167693. }
  167694. /*
  167695. * These are the routines invoked by the control routines to do
  167696. * the actual upsampling/conversion. One row group is processed per call.
  167697. *
  167698. * Note: since we may be writing directly into application-supplied buffers,
  167699. * we have to be honest about the output width; we can't assume the buffer
  167700. * has been rounded up to an even width.
  167701. */
  167702. /*
  167703. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  167704. */
  167705. METHODDEF(void)
  167706. h2v1_merged_upsample (j_decompress_ptr cinfo,
  167707. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  167708. JSAMPARRAY output_buf)
  167709. {
  167710. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  167711. register int y, cred, cgreen, cblue;
  167712. int cb, cr;
  167713. register JSAMPROW outptr;
  167714. JSAMPROW inptr0, inptr1, inptr2;
  167715. JDIMENSION col;
  167716. /* copy these pointers into registers if possible */
  167717. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  167718. int * Crrtab = upsample->Cr_r_tab;
  167719. int * Cbbtab = upsample->Cb_b_tab;
  167720. INT32 * Crgtab = upsample->Cr_g_tab;
  167721. INT32 * Cbgtab = upsample->Cb_g_tab;
  167722. SHIFT_TEMPS
  167723. inptr0 = input_buf[0][in_row_group_ctr];
  167724. inptr1 = input_buf[1][in_row_group_ctr];
  167725. inptr2 = input_buf[2][in_row_group_ctr];
  167726. outptr = output_buf[0];
  167727. /* Loop for each pair of output pixels */
  167728. for (col = cinfo->output_width >> 1; col > 0; col--) {
  167729. /* Do the chroma part of the calculation */
  167730. cb = GETJSAMPLE(*inptr1++);
  167731. cr = GETJSAMPLE(*inptr2++);
  167732. cred = Crrtab[cr];
  167733. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  167734. cblue = Cbbtab[cb];
  167735. /* Fetch 2 Y values and emit 2 pixels */
  167736. y = GETJSAMPLE(*inptr0++);
  167737. outptr[RGB_RED] = range_limit[y + cred];
  167738. outptr[RGB_GREEN] = range_limit[y + cgreen];
  167739. outptr[RGB_BLUE] = range_limit[y + cblue];
  167740. outptr += RGB_PIXELSIZE;
  167741. y = GETJSAMPLE(*inptr0++);
  167742. outptr[RGB_RED] = range_limit[y + cred];
  167743. outptr[RGB_GREEN] = range_limit[y + cgreen];
  167744. outptr[RGB_BLUE] = range_limit[y + cblue];
  167745. outptr += RGB_PIXELSIZE;
  167746. }
  167747. /* If image width is odd, do the last output column separately */
  167748. if (cinfo->output_width & 1) {
  167749. cb = GETJSAMPLE(*inptr1);
  167750. cr = GETJSAMPLE(*inptr2);
  167751. cred = Crrtab[cr];
  167752. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  167753. cblue = Cbbtab[cb];
  167754. y = GETJSAMPLE(*inptr0);
  167755. outptr[RGB_RED] = range_limit[y + cred];
  167756. outptr[RGB_GREEN] = range_limit[y + cgreen];
  167757. outptr[RGB_BLUE] = range_limit[y + cblue];
  167758. }
  167759. }
  167760. /*
  167761. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  167762. */
  167763. METHODDEF(void)
  167764. h2v2_merged_upsample (j_decompress_ptr cinfo,
  167765. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  167766. JSAMPARRAY output_buf)
  167767. {
  167768. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  167769. register int y, cred, cgreen, cblue;
  167770. int cb, cr;
  167771. register JSAMPROW outptr0, outptr1;
  167772. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  167773. JDIMENSION col;
  167774. /* copy these pointers into registers if possible */
  167775. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  167776. int * Crrtab = upsample->Cr_r_tab;
  167777. int * Cbbtab = upsample->Cb_b_tab;
  167778. INT32 * Crgtab = upsample->Cr_g_tab;
  167779. INT32 * Cbgtab = upsample->Cb_g_tab;
  167780. SHIFT_TEMPS
  167781. inptr00 = input_buf[0][in_row_group_ctr*2];
  167782. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  167783. inptr1 = input_buf[1][in_row_group_ctr];
  167784. inptr2 = input_buf[2][in_row_group_ctr];
  167785. outptr0 = output_buf[0];
  167786. outptr1 = output_buf[1];
  167787. /* Loop for each group of output pixels */
  167788. for (col = cinfo->output_width >> 1; col > 0; col--) {
  167789. /* Do the chroma part of the calculation */
  167790. cb = GETJSAMPLE(*inptr1++);
  167791. cr = GETJSAMPLE(*inptr2++);
  167792. cred = Crrtab[cr];
  167793. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  167794. cblue = Cbbtab[cb];
  167795. /* Fetch 4 Y values and emit 4 pixels */
  167796. y = GETJSAMPLE(*inptr00++);
  167797. outptr0[RGB_RED] = range_limit[y + cred];
  167798. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  167799. outptr0[RGB_BLUE] = range_limit[y + cblue];
  167800. outptr0 += RGB_PIXELSIZE;
  167801. y = GETJSAMPLE(*inptr00++);
  167802. outptr0[RGB_RED] = range_limit[y + cred];
  167803. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  167804. outptr0[RGB_BLUE] = range_limit[y + cblue];
  167805. outptr0 += RGB_PIXELSIZE;
  167806. y = GETJSAMPLE(*inptr01++);
  167807. outptr1[RGB_RED] = range_limit[y + cred];
  167808. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  167809. outptr1[RGB_BLUE] = range_limit[y + cblue];
  167810. outptr1 += RGB_PIXELSIZE;
  167811. y = GETJSAMPLE(*inptr01++);
  167812. outptr1[RGB_RED] = range_limit[y + cred];
  167813. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  167814. outptr1[RGB_BLUE] = range_limit[y + cblue];
  167815. outptr1 += RGB_PIXELSIZE;
  167816. }
  167817. /* If image width is odd, do the last output column separately */
  167818. if (cinfo->output_width & 1) {
  167819. cb = GETJSAMPLE(*inptr1);
  167820. cr = GETJSAMPLE(*inptr2);
  167821. cred = Crrtab[cr];
  167822. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  167823. cblue = Cbbtab[cb];
  167824. y = GETJSAMPLE(*inptr00);
  167825. outptr0[RGB_RED] = range_limit[y + cred];
  167826. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  167827. outptr0[RGB_BLUE] = range_limit[y + cblue];
  167828. y = GETJSAMPLE(*inptr01);
  167829. outptr1[RGB_RED] = range_limit[y + cred];
  167830. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  167831. outptr1[RGB_BLUE] = range_limit[y + cblue];
  167832. }
  167833. }
  167834. /*
  167835. * Module initialization routine for merged upsampling/color conversion.
  167836. *
  167837. * NB: this is called under the conditions determined by use_merged_upsample()
  167838. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  167839. * of this module; no safety checks are made here.
  167840. */
  167841. GLOBAL(void)
  167842. jinit_merged_upsampler (j_decompress_ptr cinfo)
  167843. {
  167844. my_upsample_ptr upsample;
  167845. upsample = (my_upsample_ptr)
  167846. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167847. SIZEOF(my_upsampler));
  167848. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  167849. upsample->pub.start_pass = start_pass_merged_upsample;
  167850. upsample->pub.need_context_rows = FALSE;
  167851. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  167852. if (cinfo->max_v_samp_factor == 2) {
  167853. upsample->pub.upsample = merged_2v_upsample;
  167854. upsample->upmethod = h2v2_merged_upsample;
  167855. /* Allocate a spare row buffer */
  167856. upsample->spare_row = (JSAMPROW)
  167857. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167858. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  167859. } else {
  167860. upsample->pub.upsample = merged_1v_upsample;
  167861. upsample->upmethod = h2v1_merged_upsample;
  167862. /* No spare row needed */
  167863. upsample->spare_row = NULL;
  167864. }
  167865. build_ycc_rgb_table2(cinfo);
  167866. }
  167867. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  167868. /********* End of inlined file: jdmerge.c *********/
  167869. #undef ASSIGN_STATE
  167870. /********* Start of inlined file: jdphuff.c *********/
  167871. #define JPEG_INTERNALS
  167872. #ifdef D_PROGRESSIVE_SUPPORTED
  167873. /*
  167874. * Expanded entropy decoder object for progressive Huffman decoding.
  167875. *
  167876. * The savable_state subrecord contains fields that change within an MCU,
  167877. * but must not be updated permanently until we complete the MCU.
  167878. */
  167879. typedef struct {
  167880. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  167881. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  167882. } savable_state3;
  167883. /* This macro is to work around compilers with missing or broken
  167884. * structure assignment. You'll need to fix this code if you have
  167885. * such a compiler and you change MAX_COMPS_IN_SCAN.
  167886. */
  167887. #ifndef NO_STRUCT_ASSIGN
  167888. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  167889. #else
  167890. #if MAX_COMPS_IN_SCAN == 4
  167891. #define ASSIGN_STATE(dest,src) \
  167892. ((dest).EOBRUN = (src).EOBRUN, \
  167893. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  167894. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  167895. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  167896. (dest).last_dc_val[3] = (src).last_dc_val[3])
  167897. #endif
  167898. #endif
  167899. typedef struct {
  167900. struct jpeg_entropy_decoder pub; /* public fields */
  167901. /* These fields are loaded into local variables at start of each MCU.
  167902. * In case of suspension, we exit WITHOUT updating them.
  167903. */
  167904. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  167905. savable_state3 saved; /* Other state at start of MCU */
  167906. /* These fields are NOT loaded into local working state. */
  167907. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  167908. /* Pointers to derived tables (these workspaces have image lifespan) */
  167909. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  167910. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  167911. } phuff_entropy_decoder;
  167912. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  167913. /* Forward declarations */
  167914. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  167915. JBLOCKROW *MCU_data));
  167916. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  167917. JBLOCKROW *MCU_data));
  167918. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  167919. JBLOCKROW *MCU_data));
  167920. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  167921. JBLOCKROW *MCU_data));
  167922. /*
  167923. * Initialize for a Huffman-compressed scan.
  167924. */
  167925. METHODDEF(void)
  167926. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  167927. {
  167928. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167929. boolean is_DC_band, bad;
  167930. int ci, coefi, tbl;
  167931. int *coef_bit_ptr;
  167932. jpeg_component_info * compptr;
  167933. is_DC_band = (cinfo->Ss == 0);
  167934. /* Validate scan parameters */
  167935. bad = FALSE;
  167936. if (is_DC_band) {
  167937. if (cinfo->Se != 0)
  167938. bad = TRUE;
  167939. } else {
  167940. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  167941. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  167942. bad = TRUE;
  167943. /* AC scans may have only one component */
  167944. if (cinfo->comps_in_scan != 1)
  167945. bad = TRUE;
  167946. }
  167947. if (cinfo->Ah != 0) {
  167948. /* Successive approximation refinement scan: must have Al = Ah-1. */
  167949. if (cinfo->Al != cinfo->Ah-1)
  167950. bad = TRUE;
  167951. }
  167952. if (cinfo->Al > 13) /* need not check for < 0 */
  167953. bad = TRUE;
  167954. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  167955. * but the spec doesn't say so, and we try to be liberal about what we
  167956. * accept. Note: large Al values could result in out-of-range DC
  167957. * coefficients during early scans, leading to bizarre displays due to
  167958. * overflows in the IDCT math. But we won't crash.
  167959. */
  167960. if (bad)
  167961. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  167962. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  167963. /* Update progression status, and verify that scan order is legal.
  167964. * Note that inter-scan inconsistencies are treated as warnings
  167965. * not fatal errors ... not clear if this is right way to behave.
  167966. */
  167967. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167968. int cindex = cinfo->cur_comp_info[ci]->component_index;
  167969. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  167970. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  167971. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  167972. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  167973. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  167974. if (cinfo->Ah != expected)
  167975. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  167976. coef_bit_ptr[coefi] = cinfo->Al;
  167977. }
  167978. }
  167979. /* Select MCU decoding routine */
  167980. if (cinfo->Ah == 0) {
  167981. if (is_DC_band)
  167982. entropy->pub.decode_mcu = decode_mcu_DC_first;
  167983. else
  167984. entropy->pub.decode_mcu = decode_mcu_AC_first;
  167985. } else {
  167986. if (is_DC_band)
  167987. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  167988. else
  167989. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  167990. }
  167991. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167992. compptr = cinfo->cur_comp_info[ci];
  167993. /* Make sure requested tables are present, and compute derived tables.
  167994. * We may build same derived table more than once, but it's not expensive.
  167995. */
  167996. if (is_DC_band) {
  167997. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  167998. tbl = compptr->dc_tbl_no;
  167999. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  168000. & entropy->derived_tbls[tbl]);
  168001. }
  168002. } else {
  168003. tbl = compptr->ac_tbl_no;
  168004. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  168005. & entropy->derived_tbls[tbl]);
  168006. /* remember the single active table */
  168007. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  168008. }
  168009. /* Initialize DC predictions to 0 */
  168010. entropy->saved.last_dc_val[ci] = 0;
  168011. }
  168012. /* Initialize bitread state variables */
  168013. entropy->bitstate.bits_left = 0;
  168014. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  168015. entropy->pub.insufficient_data = FALSE;
  168016. /* Initialize private state variables */
  168017. entropy->saved.EOBRUN = 0;
  168018. /* Initialize restart counter */
  168019. entropy->restarts_to_go = cinfo->restart_interval;
  168020. }
  168021. /*
  168022. * Check for a restart marker & resynchronize decoder.
  168023. * Returns FALSE if must suspend.
  168024. */
  168025. LOCAL(boolean)
  168026. process_restartp (j_decompress_ptr cinfo)
  168027. {
  168028. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168029. int ci;
  168030. /* Throw away any unused bits remaining in bit buffer; */
  168031. /* include any full bytes in next_marker's count of discarded bytes */
  168032. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  168033. entropy->bitstate.bits_left = 0;
  168034. /* Advance past the RSTn marker */
  168035. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  168036. return FALSE;
  168037. /* Re-initialize DC predictions to 0 */
  168038. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  168039. entropy->saved.last_dc_val[ci] = 0;
  168040. /* Re-init EOB run count, too */
  168041. entropy->saved.EOBRUN = 0;
  168042. /* Reset restart counter */
  168043. entropy->restarts_to_go = cinfo->restart_interval;
  168044. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  168045. * against a marker. In that case we will end up treating the next data
  168046. * segment as empty, and we can avoid producing bogus output pixels by
  168047. * leaving the flag set.
  168048. */
  168049. if (cinfo->unread_marker == 0)
  168050. entropy->pub.insufficient_data = FALSE;
  168051. return TRUE;
  168052. }
  168053. /*
  168054. * Huffman MCU decoding.
  168055. * Each of these routines decodes and returns one MCU's worth of
  168056. * Huffman-compressed coefficients.
  168057. * The coefficients are reordered from zigzag order into natural array order,
  168058. * but are not dequantized.
  168059. *
  168060. * The i'th block of the MCU is stored into the block pointed to by
  168061. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  168062. *
  168063. * We return FALSE if data source requested suspension. In that case no
  168064. * changes have been made to permanent state. (Exception: some output
  168065. * coefficients may already have been assigned. This is harmless for
  168066. * spectral selection, since we'll just re-assign them on the next call.
  168067. * Successive approximation AC refinement has to be more careful, however.)
  168068. */
  168069. /*
  168070. * MCU decoding for DC initial scan (either spectral selection,
  168071. * or first pass of successive approximation).
  168072. */
  168073. METHODDEF(boolean)
  168074. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168075. {
  168076. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168077. int Al = cinfo->Al;
  168078. register int s, r;
  168079. int blkn, ci;
  168080. JBLOCKROW block;
  168081. BITREAD_STATE_VARS;
  168082. savable_state3 state;
  168083. d_derived_tbl * tbl;
  168084. jpeg_component_info * compptr;
  168085. /* Process restart marker if needed; may have to suspend */
  168086. if (cinfo->restart_interval) {
  168087. if (entropy->restarts_to_go == 0)
  168088. if (! process_restartp(cinfo))
  168089. return FALSE;
  168090. }
  168091. /* If we've run out of data, just leave the MCU set to zeroes.
  168092. * This way, we return uniform gray for the remainder of the segment.
  168093. */
  168094. if (! entropy->pub.insufficient_data) {
  168095. /* Load up working state */
  168096. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168097. ASSIGN_STATE(state, entropy->saved);
  168098. /* Outer loop handles each block in the MCU */
  168099. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  168100. block = MCU_data[blkn];
  168101. ci = cinfo->MCU_membership[blkn];
  168102. compptr = cinfo->cur_comp_info[ci];
  168103. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  168104. /* Decode a single block's worth of coefficients */
  168105. /* Section F.2.2.1: decode the DC coefficient difference */
  168106. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  168107. if (s) {
  168108. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  168109. r = GET_BITS(s);
  168110. s = HUFF_EXTEND(r, s);
  168111. }
  168112. /* Convert DC difference to actual value, update last_dc_val */
  168113. s += state.last_dc_val[ci];
  168114. state.last_dc_val[ci] = s;
  168115. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  168116. (*block)[0] = (JCOEF) (s << Al);
  168117. }
  168118. /* Completed MCU, so update state */
  168119. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168120. ASSIGN_STATE(entropy->saved, state);
  168121. }
  168122. /* Account for restart interval (no-op if not using restarts) */
  168123. entropy->restarts_to_go--;
  168124. return TRUE;
  168125. }
  168126. /*
  168127. * MCU decoding for AC initial scan (either spectral selection,
  168128. * or first pass of successive approximation).
  168129. */
  168130. METHODDEF(boolean)
  168131. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168132. {
  168133. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168134. int Se = cinfo->Se;
  168135. int Al = cinfo->Al;
  168136. register int s, k, r;
  168137. unsigned int EOBRUN;
  168138. JBLOCKROW block;
  168139. BITREAD_STATE_VARS;
  168140. d_derived_tbl * tbl;
  168141. /* Process restart marker if needed; may have to suspend */
  168142. if (cinfo->restart_interval) {
  168143. if (entropy->restarts_to_go == 0)
  168144. if (! process_restartp(cinfo))
  168145. return FALSE;
  168146. }
  168147. /* If we've run out of data, just leave the MCU set to zeroes.
  168148. * This way, we return uniform gray for the remainder of the segment.
  168149. */
  168150. if (! entropy->pub.insufficient_data) {
  168151. /* Load up working state.
  168152. * We can avoid loading/saving bitread state if in an EOB run.
  168153. */
  168154. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  168155. /* There is always only one block per MCU */
  168156. if (EOBRUN > 0) /* if it's a band of zeroes... */
  168157. EOBRUN--; /* ...process it now (we do nothing) */
  168158. else {
  168159. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168160. block = MCU_data[0];
  168161. tbl = entropy->ac_derived_tbl;
  168162. for (k = cinfo->Ss; k <= Se; k++) {
  168163. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  168164. r = s >> 4;
  168165. s &= 15;
  168166. if (s) {
  168167. k += r;
  168168. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  168169. r = GET_BITS(s);
  168170. s = HUFF_EXTEND(r, s);
  168171. /* Scale and output coefficient in natural (dezigzagged) order */
  168172. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  168173. } else {
  168174. if (r == 15) { /* ZRL */
  168175. k += 15; /* skip 15 zeroes in band */
  168176. } else { /* EOBr, run length is 2^r + appended bits */
  168177. EOBRUN = 1 << r;
  168178. if (r) { /* EOBr, r > 0 */
  168179. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  168180. r = GET_BITS(r);
  168181. EOBRUN += r;
  168182. }
  168183. EOBRUN--; /* this band is processed at this moment */
  168184. break; /* force end-of-band */
  168185. }
  168186. }
  168187. }
  168188. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168189. }
  168190. /* Completed MCU, so update state */
  168191. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  168192. }
  168193. /* Account for restart interval (no-op if not using restarts) */
  168194. entropy->restarts_to_go--;
  168195. return TRUE;
  168196. }
  168197. /*
  168198. * MCU decoding for DC successive approximation refinement scan.
  168199. * Note: we assume such scans can be multi-component, although the spec
  168200. * is not very clear on the point.
  168201. */
  168202. METHODDEF(boolean)
  168203. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168204. {
  168205. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168206. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  168207. int blkn;
  168208. JBLOCKROW block;
  168209. BITREAD_STATE_VARS;
  168210. /* Process restart marker if needed; may have to suspend */
  168211. if (cinfo->restart_interval) {
  168212. if (entropy->restarts_to_go == 0)
  168213. if (! process_restartp(cinfo))
  168214. return FALSE;
  168215. }
  168216. /* Not worth the cycles to check insufficient_data here,
  168217. * since we will not change the data anyway if we read zeroes.
  168218. */
  168219. /* Load up working state */
  168220. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168221. /* Outer loop handles each block in the MCU */
  168222. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  168223. block = MCU_data[blkn];
  168224. /* Encoded data is simply the next bit of the two's-complement DC value */
  168225. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  168226. if (GET_BITS(1))
  168227. (*block)[0] |= p1;
  168228. /* Note: since we use |=, repeating the assignment later is safe */
  168229. }
  168230. /* Completed MCU, so update state */
  168231. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168232. /* Account for restart interval (no-op if not using restarts) */
  168233. entropy->restarts_to_go--;
  168234. return TRUE;
  168235. }
  168236. /*
  168237. * MCU decoding for AC successive approximation refinement scan.
  168238. */
  168239. METHODDEF(boolean)
  168240. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168241. {
  168242. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168243. int Se = cinfo->Se;
  168244. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  168245. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  168246. register int s, k, r;
  168247. unsigned int EOBRUN;
  168248. JBLOCKROW block;
  168249. JCOEFPTR thiscoef;
  168250. BITREAD_STATE_VARS;
  168251. d_derived_tbl * tbl;
  168252. int num_newnz;
  168253. int newnz_pos[DCTSIZE2];
  168254. /* Process restart marker if needed; may have to suspend */
  168255. if (cinfo->restart_interval) {
  168256. if (entropy->restarts_to_go == 0)
  168257. if (! process_restartp(cinfo))
  168258. return FALSE;
  168259. }
  168260. /* If we've run out of data, don't modify the MCU.
  168261. */
  168262. if (! entropy->pub.insufficient_data) {
  168263. /* Load up working state */
  168264. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168265. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  168266. /* There is always only one block per MCU */
  168267. block = MCU_data[0];
  168268. tbl = entropy->ac_derived_tbl;
  168269. /* If we are forced to suspend, we must undo the assignments to any newly
  168270. * nonzero coefficients in the block, because otherwise we'd get confused
  168271. * next time about which coefficients were already nonzero.
  168272. * But we need not undo addition of bits to already-nonzero coefficients;
  168273. * instead, we can test the current bit to see if we already did it.
  168274. */
  168275. num_newnz = 0;
  168276. /* initialize coefficient loop counter to start of band */
  168277. k = cinfo->Ss;
  168278. if (EOBRUN == 0) {
  168279. for (; k <= Se; k++) {
  168280. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  168281. r = s >> 4;
  168282. s &= 15;
  168283. if (s) {
  168284. if (s != 1) /* size of new coef should always be 1 */
  168285. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  168286. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  168287. if (GET_BITS(1))
  168288. s = p1; /* newly nonzero coef is positive */
  168289. else
  168290. s = m1; /* newly nonzero coef is negative */
  168291. } else {
  168292. if (r != 15) {
  168293. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  168294. if (r) {
  168295. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  168296. r = GET_BITS(r);
  168297. EOBRUN += r;
  168298. }
  168299. break; /* rest of block is handled by EOB logic */
  168300. }
  168301. /* note s = 0 for processing ZRL */
  168302. }
  168303. /* Advance over already-nonzero coefs and r still-zero coefs,
  168304. * appending correction bits to the nonzeroes. A correction bit is 1
  168305. * if the absolute value of the coefficient must be increased.
  168306. */
  168307. do {
  168308. thiscoef = *block + jpeg_natural_order[k];
  168309. if (*thiscoef != 0) {
  168310. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  168311. if (GET_BITS(1)) {
  168312. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  168313. if (*thiscoef >= 0)
  168314. *thiscoef += p1;
  168315. else
  168316. *thiscoef += m1;
  168317. }
  168318. }
  168319. } else {
  168320. if (--r < 0)
  168321. break; /* reached target zero coefficient */
  168322. }
  168323. k++;
  168324. } while (k <= Se);
  168325. if (s) {
  168326. int pos = jpeg_natural_order[k];
  168327. /* Output newly nonzero coefficient */
  168328. (*block)[pos] = (JCOEF) s;
  168329. /* Remember its position in case we have to suspend */
  168330. newnz_pos[num_newnz++] = pos;
  168331. }
  168332. }
  168333. }
  168334. if (EOBRUN > 0) {
  168335. /* Scan any remaining coefficient positions after the end-of-band
  168336. * (the last newly nonzero coefficient, if any). Append a correction
  168337. * bit to each already-nonzero coefficient. A correction bit is 1
  168338. * if the absolute value of the coefficient must be increased.
  168339. */
  168340. for (; k <= Se; k++) {
  168341. thiscoef = *block + jpeg_natural_order[k];
  168342. if (*thiscoef != 0) {
  168343. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  168344. if (GET_BITS(1)) {
  168345. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  168346. if (*thiscoef >= 0)
  168347. *thiscoef += p1;
  168348. else
  168349. *thiscoef += m1;
  168350. }
  168351. }
  168352. }
  168353. }
  168354. /* Count one block completed in EOB run */
  168355. EOBRUN--;
  168356. }
  168357. /* Completed MCU, so update state */
  168358. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168359. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  168360. }
  168361. /* Account for restart interval (no-op if not using restarts) */
  168362. entropy->restarts_to_go--;
  168363. return TRUE;
  168364. undoit:
  168365. /* Re-zero any output coefficients that we made newly nonzero */
  168366. while (num_newnz > 0)
  168367. (*block)[newnz_pos[--num_newnz]] = 0;
  168368. return FALSE;
  168369. }
  168370. /*
  168371. * Module initialization routine for progressive Huffman entropy decoding.
  168372. */
  168373. GLOBAL(void)
  168374. jinit_phuff_decoder (j_decompress_ptr cinfo)
  168375. {
  168376. phuff_entropy_ptr2 entropy;
  168377. int *coef_bit_ptr;
  168378. int ci, i;
  168379. entropy = (phuff_entropy_ptr2)
  168380. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168381. SIZEOF(phuff_entropy_decoder));
  168382. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  168383. entropy->pub.start_pass = start_pass_phuff_decoder;
  168384. /* Mark derived tables unallocated */
  168385. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  168386. entropy->derived_tbls[i] = NULL;
  168387. }
  168388. /* Create progression status table */
  168389. cinfo->coef_bits = (int (*)[DCTSIZE2])
  168390. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168391. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  168392. coef_bit_ptr = & cinfo->coef_bits[0][0];
  168393. for (ci = 0; ci < cinfo->num_components; ci++)
  168394. for (i = 0; i < DCTSIZE2; i++)
  168395. *coef_bit_ptr++ = -1;
  168396. }
  168397. #endif /* D_PROGRESSIVE_SUPPORTED */
  168398. /********* End of inlined file: jdphuff.c *********/
  168399. /********* Start of inlined file: jdpostct.c *********/
  168400. #define JPEG_INTERNALS
  168401. /* Private buffer controller object */
  168402. typedef struct {
  168403. struct jpeg_d_post_controller pub; /* public fields */
  168404. /* Color quantization source buffer: this holds output data from
  168405. * the upsample/color conversion step to be passed to the quantizer.
  168406. * For two-pass color quantization, we need a full-image buffer;
  168407. * for one-pass operation, a strip buffer is sufficient.
  168408. */
  168409. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  168410. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  168411. JDIMENSION strip_height; /* buffer size in rows */
  168412. /* for two-pass mode only: */
  168413. JDIMENSION starting_row; /* row # of first row in current strip */
  168414. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  168415. } my_post_controller;
  168416. typedef my_post_controller * my_post_ptr;
  168417. /* Forward declarations */
  168418. METHODDEF(void) post_process_1pass
  168419. JPP((j_decompress_ptr cinfo,
  168420. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168421. JDIMENSION in_row_groups_avail,
  168422. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168423. JDIMENSION out_rows_avail));
  168424. #ifdef QUANT_2PASS_SUPPORTED
  168425. METHODDEF(void) post_process_prepass
  168426. JPP((j_decompress_ptr cinfo,
  168427. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168428. JDIMENSION in_row_groups_avail,
  168429. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168430. JDIMENSION out_rows_avail));
  168431. METHODDEF(void) post_process_2pass
  168432. JPP((j_decompress_ptr cinfo,
  168433. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168434. JDIMENSION in_row_groups_avail,
  168435. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168436. JDIMENSION out_rows_avail));
  168437. #endif
  168438. /*
  168439. * Initialize for a processing pass.
  168440. */
  168441. METHODDEF(void)
  168442. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  168443. {
  168444. my_post_ptr post = (my_post_ptr) cinfo->post;
  168445. switch (pass_mode) {
  168446. case JBUF_PASS_THRU:
  168447. if (cinfo->quantize_colors) {
  168448. /* Single-pass processing with color quantization. */
  168449. post->pub.post_process_data = post_process_1pass;
  168450. /* We could be doing buffered-image output before starting a 2-pass
  168451. * color quantization; in that case, jinit_d_post_controller did not
  168452. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  168453. */
  168454. if (post->buffer == NULL) {
  168455. post->buffer = (*cinfo->mem->access_virt_sarray)
  168456. ((j_common_ptr) cinfo, post->whole_image,
  168457. (JDIMENSION) 0, post->strip_height, TRUE);
  168458. }
  168459. } else {
  168460. /* For single-pass processing without color quantization,
  168461. * I have no work to do; just call the upsampler directly.
  168462. */
  168463. post->pub.post_process_data = cinfo->upsample->upsample;
  168464. }
  168465. break;
  168466. #ifdef QUANT_2PASS_SUPPORTED
  168467. case JBUF_SAVE_AND_PASS:
  168468. /* First pass of 2-pass quantization */
  168469. if (post->whole_image == NULL)
  168470. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  168471. post->pub.post_process_data = post_process_prepass;
  168472. break;
  168473. case JBUF_CRANK_DEST:
  168474. /* Second pass of 2-pass quantization */
  168475. if (post->whole_image == NULL)
  168476. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  168477. post->pub.post_process_data = post_process_2pass;
  168478. break;
  168479. #endif /* QUANT_2PASS_SUPPORTED */
  168480. default:
  168481. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  168482. break;
  168483. }
  168484. post->starting_row = post->next_row = 0;
  168485. }
  168486. /*
  168487. * Process some data in the one-pass (strip buffer) case.
  168488. * This is used for color precision reduction as well as one-pass quantization.
  168489. */
  168490. METHODDEF(void)
  168491. post_process_1pass (j_decompress_ptr cinfo,
  168492. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168493. JDIMENSION in_row_groups_avail,
  168494. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168495. JDIMENSION out_rows_avail)
  168496. {
  168497. my_post_ptr post = (my_post_ptr) cinfo->post;
  168498. JDIMENSION num_rows, max_rows;
  168499. /* Fill the buffer, but not more than what we can dump out in one go. */
  168500. /* Note we rely on the upsampler to detect bottom of image. */
  168501. max_rows = out_rows_avail - *out_row_ctr;
  168502. if (max_rows > post->strip_height)
  168503. max_rows = post->strip_height;
  168504. num_rows = 0;
  168505. (*cinfo->upsample->upsample) (cinfo,
  168506. input_buf, in_row_group_ctr, in_row_groups_avail,
  168507. post->buffer, &num_rows, max_rows);
  168508. /* Quantize and emit data. */
  168509. (*cinfo->cquantize->color_quantize) (cinfo,
  168510. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  168511. *out_row_ctr += num_rows;
  168512. }
  168513. #ifdef QUANT_2PASS_SUPPORTED
  168514. /*
  168515. * Process some data in the first pass of 2-pass quantization.
  168516. */
  168517. METHODDEF(void)
  168518. post_process_prepass (j_decompress_ptr cinfo,
  168519. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168520. JDIMENSION in_row_groups_avail,
  168521. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168522. JDIMENSION out_rows_avail)
  168523. {
  168524. my_post_ptr post = (my_post_ptr) cinfo->post;
  168525. JDIMENSION old_next_row, num_rows;
  168526. /* Reposition virtual buffer if at start of strip. */
  168527. if (post->next_row == 0) {
  168528. post->buffer = (*cinfo->mem->access_virt_sarray)
  168529. ((j_common_ptr) cinfo, post->whole_image,
  168530. post->starting_row, post->strip_height, TRUE);
  168531. }
  168532. /* Upsample some data (up to a strip height's worth). */
  168533. old_next_row = post->next_row;
  168534. (*cinfo->upsample->upsample) (cinfo,
  168535. input_buf, in_row_group_ctr, in_row_groups_avail,
  168536. post->buffer, &post->next_row, post->strip_height);
  168537. /* Allow quantizer to scan new data. No data is emitted, */
  168538. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  168539. if (post->next_row > old_next_row) {
  168540. num_rows = post->next_row - old_next_row;
  168541. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  168542. (JSAMPARRAY) NULL, (int) num_rows);
  168543. *out_row_ctr += num_rows;
  168544. }
  168545. /* Advance if we filled the strip. */
  168546. if (post->next_row >= post->strip_height) {
  168547. post->starting_row += post->strip_height;
  168548. post->next_row = 0;
  168549. }
  168550. }
  168551. /*
  168552. * Process some data in the second pass of 2-pass quantization.
  168553. */
  168554. METHODDEF(void)
  168555. post_process_2pass (j_decompress_ptr cinfo,
  168556. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168557. JDIMENSION in_row_groups_avail,
  168558. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168559. JDIMENSION out_rows_avail)
  168560. {
  168561. my_post_ptr post = (my_post_ptr) cinfo->post;
  168562. JDIMENSION num_rows, max_rows;
  168563. /* Reposition virtual buffer if at start of strip. */
  168564. if (post->next_row == 0) {
  168565. post->buffer = (*cinfo->mem->access_virt_sarray)
  168566. ((j_common_ptr) cinfo, post->whole_image,
  168567. post->starting_row, post->strip_height, FALSE);
  168568. }
  168569. /* Determine number of rows to emit. */
  168570. num_rows = post->strip_height - post->next_row; /* available in strip */
  168571. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  168572. if (num_rows > max_rows)
  168573. num_rows = max_rows;
  168574. /* We have to check bottom of image here, can't depend on upsampler. */
  168575. max_rows = cinfo->output_height - post->starting_row;
  168576. if (num_rows > max_rows)
  168577. num_rows = max_rows;
  168578. /* Quantize and emit data. */
  168579. (*cinfo->cquantize->color_quantize) (cinfo,
  168580. post->buffer + post->next_row, output_buf + *out_row_ctr,
  168581. (int) num_rows);
  168582. *out_row_ctr += num_rows;
  168583. /* Advance if we filled the strip. */
  168584. post->next_row += num_rows;
  168585. if (post->next_row >= post->strip_height) {
  168586. post->starting_row += post->strip_height;
  168587. post->next_row = 0;
  168588. }
  168589. }
  168590. #endif /* QUANT_2PASS_SUPPORTED */
  168591. /*
  168592. * Initialize postprocessing controller.
  168593. */
  168594. GLOBAL(void)
  168595. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168596. {
  168597. my_post_ptr post;
  168598. post = (my_post_ptr)
  168599. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168600. SIZEOF(my_post_controller));
  168601. cinfo->post = (struct jpeg_d_post_controller *) post;
  168602. post->pub.start_pass = start_pass_dpost;
  168603. post->whole_image = NULL; /* flag for no virtual arrays */
  168604. post->buffer = NULL; /* flag for no strip buffer */
  168605. /* Create the quantization buffer, if needed */
  168606. if (cinfo->quantize_colors) {
  168607. /* The buffer strip height is max_v_samp_factor, which is typically
  168608. * an efficient number of rows for upsampling to return.
  168609. * (In the presence of output rescaling, we might want to be smarter?)
  168610. */
  168611. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  168612. if (need_full_buffer) {
  168613. /* Two-pass color quantization: need full-image storage. */
  168614. /* We round up the number of rows to a multiple of the strip height. */
  168615. #ifdef QUANT_2PASS_SUPPORTED
  168616. post->whole_image = (*cinfo->mem->request_virt_sarray)
  168617. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  168618. cinfo->output_width * cinfo->out_color_components,
  168619. (JDIMENSION) jround_up((long) cinfo->output_height,
  168620. (long) post->strip_height),
  168621. post->strip_height);
  168622. #else
  168623. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  168624. #endif /* QUANT_2PASS_SUPPORTED */
  168625. } else {
  168626. /* One-pass color quantization: just make a strip buffer. */
  168627. post->buffer = (*cinfo->mem->alloc_sarray)
  168628. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168629. cinfo->output_width * cinfo->out_color_components,
  168630. post->strip_height);
  168631. }
  168632. }
  168633. }
  168634. /********* End of inlined file: jdpostct.c *********/
  168635. #undef FIX
  168636. /********* Start of inlined file: jdsample.c *********/
  168637. #define JPEG_INTERNALS
  168638. /* Pointer to routine to upsample a single component */
  168639. typedef JMETHOD(void, upsample1_ptr,
  168640. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168641. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  168642. /* Private subobject */
  168643. typedef struct {
  168644. struct jpeg_upsampler pub; /* public fields */
  168645. /* Color conversion buffer. When using separate upsampling and color
  168646. * conversion steps, this buffer holds one upsampled row group until it
  168647. * has been color converted and output.
  168648. * Note: we do not allocate any storage for component(s) which are full-size,
  168649. * ie do not need rescaling. The corresponding entry of color_buf[] is
  168650. * simply set to point to the input data array, thereby avoiding copying.
  168651. */
  168652. JSAMPARRAY color_buf[MAX_COMPONENTS];
  168653. /* Per-component upsampling method pointers */
  168654. upsample1_ptr methods[MAX_COMPONENTS];
  168655. int next_row_out; /* counts rows emitted from color_buf */
  168656. JDIMENSION rows_to_go; /* counts rows remaining in image */
  168657. /* Height of an input row group for each component. */
  168658. int rowgroup_height[MAX_COMPONENTS];
  168659. /* These arrays save pixel expansion factors so that int_expand need not
  168660. * recompute them each time. They are unused for other upsampling methods.
  168661. */
  168662. UINT8 h_expand[MAX_COMPONENTS];
  168663. UINT8 v_expand[MAX_COMPONENTS];
  168664. } my_upsampler2;
  168665. typedef my_upsampler2 * my_upsample_ptr2;
  168666. /*
  168667. * Initialize for an upsampling pass.
  168668. */
  168669. METHODDEF(void)
  168670. start_pass_upsample (j_decompress_ptr cinfo)
  168671. {
  168672. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  168673. /* Mark the conversion buffer empty */
  168674. upsample->next_row_out = cinfo->max_v_samp_factor;
  168675. /* Initialize total-height counter for detecting bottom of image */
  168676. upsample->rows_to_go = cinfo->output_height;
  168677. }
  168678. /*
  168679. * Control routine to do upsampling (and color conversion).
  168680. *
  168681. * In this version we upsample each component independently.
  168682. * We upsample one row group into the conversion buffer, then apply
  168683. * color conversion a row at a time.
  168684. */
  168685. METHODDEF(void)
  168686. sep_upsample (j_decompress_ptr cinfo,
  168687. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168688. JDIMENSION in_row_groups_avail,
  168689. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168690. JDIMENSION out_rows_avail)
  168691. {
  168692. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  168693. int ci;
  168694. jpeg_component_info * compptr;
  168695. JDIMENSION num_rows;
  168696. /* Fill the conversion buffer, if it's empty */
  168697. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  168698. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168699. ci++, compptr++) {
  168700. /* Invoke per-component upsample method. Notice we pass a POINTER
  168701. * to color_buf[ci], so that fullsize_upsample can change it.
  168702. */
  168703. (*upsample->methods[ci]) (cinfo, compptr,
  168704. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  168705. upsample->color_buf + ci);
  168706. }
  168707. upsample->next_row_out = 0;
  168708. }
  168709. /* Color-convert and emit rows */
  168710. /* How many we have in the buffer: */
  168711. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  168712. /* Not more than the distance to the end of the image. Need this test
  168713. * in case the image height is not a multiple of max_v_samp_factor:
  168714. */
  168715. if (num_rows > upsample->rows_to_go)
  168716. num_rows = upsample->rows_to_go;
  168717. /* And not more than what the client can accept: */
  168718. out_rows_avail -= *out_row_ctr;
  168719. if (num_rows > out_rows_avail)
  168720. num_rows = out_rows_avail;
  168721. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  168722. (JDIMENSION) upsample->next_row_out,
  168723. output_buf + *out_row_ctr,
  168724. (int) num_rows);
  168725. /* Adjust counts */
  168726. *out_row_ctr += num_rows;
  168727. upsample->rows_to_go -= num_rows;
  168728. upsample->next_row_out += num_rows;
  168729. /* When the buffer is emptied, declare this input row group consumed */
  168730. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  168731. (*in_row_group_ctr)++;
  168732. }
  168733. /*
  168734. * These are the routines invoked by sep_upsample to upsample pixel values
  168735. * of a single component. One row group is processed per call.
  168736. */
  168737. /*
  168738. * For full-size components, we just make color_buf[ci] point at the
  168739. * input buffer, and thus avoid copying any data. Note that this is
  168740. * safe only because sep_upsample doesn't declare the input row group
  168741. * "consumed" until we are done color converting and emitting it.
  168742. */
  168743. METHODDEF(void)
  168744. fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168745. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168746. {
  168747. *output_data_ptr = input_data;
  168748. }
  168749. /*
  168750. * This is a no-op version used for "uninteresting" components.
  168751. * These components will not be referenced by color conversion.
  168752. */
  168753. METHODDEF(void)
  168754. noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168755. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168756. {
  168757. *output_data_ptr = NULL; /* safety check */
  168758. }
  168759. /*
  168760. * This version handles any integral sampling ratios.
  168761. * This is not used for typical JPEG files, so it need not be fast.
  168762. * Nor, for that matter, is it particularly accurate: the algorithm is
  168763. * simple replication of the input pixel onto the corresponding output
  168764. * pixels. The hi-falutin sampling literature refers to this as a
  168765. * "box filter". A box filter tends to introduce visible artifacts,
  168766. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  168767. * you would be well advised to improve this code.
  168768. */
  168769. METHODDEF(void)
  168770. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168771. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168772. {
  168773. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  168774. JSAMPARRAY output_data = *output_data_ptr;
  168775. register JSAMPROW inptr, outptr;
  168776. register JSAMPLE invalue;
  168777. register int h;
  168778. JSAMPROW outend;
  168779. int h_expand, v_expand;
  168780. int inrow, outrow;
  168781. h_expand = upsample->h_expand[compptr->component_index];
  168782. v_expand = upsample->v_expand[compptr->component_index];
  168783. inrow = outrow = 0;
  168784. while (outrow < cinfo->max_v_samp_factor) {
  168785. /* Generate one output row with proper horizontal expansion */
  168786. inptr = input_data[inrow];
  168787. outptr = output_data[outrow];
  168788. outend = outptr + cinfo->output_width;
  168789. while (outptr < outend) {
  168790. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  168791. for (h = h_expand; h > 0; h--) {
  168792. *outptr++ = invalue;
  168793. }
  168794. }
  168795. /* Generate any additional output rows by duplicating the first one */
  168796. if (v_expand > 1) {
  168797. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  168798. v_expand-1, cinfo->output_width);
  168799. }
  168800. inrow++;
  168801. outrow += v_expand;
  168802. }
  168803. }
  168804. /*
  168805. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  168806. * It's still a box filter.
  168807. */
  168808. METHODDEF(void)
  168809. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168810. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168811. {
  168812. JSAMPARRAY output_data = *output_data_ptr;
  168813. register JSAMPROW inptr, outptr;
  168814. register JSAMPLE invalue;
  168815. JSAMPROW outend;
  168816. int inrow;
  168817. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  168818. inptr = input_data[inrow];
  168819. outptr = output_data[inrow];
  168820. outend = outptr + cinfo->output_width;
  168821. while (outptr < outend) {
  168822. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  168823. *outptr++ = invalue;
  168824. *outptr++ = invalue;
  168825. }
  168826. }
  168827. }
  168828. /*
  168829. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  168830. * It's still a box filter.
  168831. */
  168832. METHODDEF(void)
  168833. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168834. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168835. {
  168836. JSAMPARRAY output_data = *output_data_ptr;
  168837. register JSAMPROW inptr, outptr;
  168838. register JSAMPLE invalue;
  168839. JSAMPROW outend;
  168840. int inrow, outrow;
  168841. inrow = outrow = 0;
  168842. while (outrow < cinfo->max_v_samp_factor) {
  168843. inptr = input_data[inrow];
  168844. outptr = output_data[outrow];
  168845. outend = outptr + cinfo->output_width;
  168846. while (outptr < outend) {
  168847. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  168848. *outptr++ = invalue;
  168849. *outptr++ = invalue;
  168850. }
  168851. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  168852. 1, cinfo->output_width);
  168853. inrow++;
  168854. outrow += 2;
  168855. }
  168856. }
  168857. /*
  168858. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  168859. *
  168860. * The upsampling algorithm is linear interpolation between pixel centers,
  168861. * also known as a "triangle filter". This is a good compromise between
  168862. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  168863. * of the way between input pixel centers.
  168864. *
  168865. * A note about the "bias" calculations: when rounding fractional values to
  168866. * integer, we do not want to always round 0.5 up to the next integer.
  168867. * If we did that, we'd introduce a noticeable bias towards larger values.
  168868. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  168869. * alternate pixel locations (a simple ordered dither pattern).
  168870. */
  168871. METHODDEF(void)
  168872. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168873. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168874. {
  168875. JSAMPARRAY output_data = *output_data_ptr;
  168876. register JSAMPROW inptr, outptr;
  168877. register int invalue;
  168878. register JDIMENSION colctr;
  168879. int inrow;
  168880. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  168881. inptr = input_data[inrow];
  168882. outptr = output_data[inrow];
  168883. /* Special case for first column */
  168884. invalue = GETJSAMPLE(*inptr++);
  168885. *outptr++ = (JSAMPLE) invalue;
  168886. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  168887. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  168888. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  168889. invalue = GETJSAMPLE(*inptr++) * 3;
  168890. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  168891. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  168892. }
  168893. /* Special case for last column */
  168894. invalue = GETJSAMPLE(*inptr);
  168895. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  168896. *outptr++ = (JSAMPLE) invalue;
  168897. }
  168898. }
  168899. /*
  168900. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  168901. * Again a triangle filter; see comments for h2v1 case, above.
  168902. *
  168903. * It is OK for us to reference the adjacent input rows because we demanded
  168904. * context from the main buffer controller (see initialization code).
  168905. */
  168906. METHODDEF(void)
  168907. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168908. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168909. {
  168910. JSAMPARRAY output_data = *output_data_ptr;
  168911. register JSAMPROW inptr0, inptr1, outptr;
  168912. #if BITS_IN_JSAMPLE == 8
  168913. register int thiscolsum, lastcolsum, nextcolsum;
  168914. #else
  168915. register INT32 thiscolsum, lastcolsum, nextcolsum;
  168916. #endif
  168917. register JDIMENSION colctr;
  168918. int inrow, outrow, v;
  168919. inrow = outrow = 0;
  168920. while (outrow < cinfo->max_v_samp_factor) {
  168921. for (v = 0; v < 2; v++) {
  168922. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  168923. inptr0 = input_data[inrow];
  168924. if (v == 0) /* next nearest is row above */
  168925. inptr1 = input_data[inrow-1];
  168926. else /* next nearest is row below */
  168927. inptr1 = input_data[inrow+1];
  168928. outptr = output_data[outrow++];
  168929. /* Special case for first column */
  168930. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  168931. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  168932. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  168933. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  168934. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  168935. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  168936. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  168937. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  168938. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  168939. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  168940. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  168941. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  168942. }
  168943. /* Special case for last column */
  168944. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  168945. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  168946. }
  168947. inrow++;
  168948. }
  168949. }
  168950. /*
  168951. * Module initialization routine for upsampling.
  168952. */
  168953. GLOBAL(void)
  168954. jinit_upsampler (j_decompress_ptr cinfo)
  168955. {
  168956. my_upsample_ptr2 upsample;
  168957. int ci;
  168958. jpeg_component_info * compptr;
  168959. boolean need_buffer, do_fancy;
  168960. int h_in_group, v_in_group, h_out_group, v_out_group;
  168961. upsample = (my_upsample_ptr2)
  168962. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168963. SIZEOF(my_upsampler2));
  168964. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  168965. upsample->pub.start_pass = start_pass_upsample;
  168966. upsample->pub.upsample = sep_upsample;
  168967. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  168968. if (cinfo->CCIR601_sampling) /* this isn't supported */
  168969. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  168970. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  168971. * so don't ask for it.
  168972. */
  168973. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  168974. /* Verify we can handle the sampling factors, select per-component methods,
  168975. * and create storage as needed.
  168976. */
  168977. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168978. ci++, compptr++) {
  168979. /* Compute size of an "input group" after IDCT scaling. This many samples
  168980. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  168981. */
  168982. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  168983. cinfo->min_DCT_scaled_size;
  168984. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  168985. cinfo->min_DCT_scaled_size;
  168986. h_out_group = cinfo->max_h_samp_factor;
  168987. v_out_group = cinfo->max_v_samp_factor;
  168988. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  168989. need_buffer = TRUE;
  168990. if (! compptr->component_needed) {
  168991. /* Don't bother to upsample an uninteresting component. */
  168992. upsample->methods[ci] = noop_upsample;
  168993. need_buffer = FALSE;
  168994. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  168995. /* Fullsize components can be processed without any work. */
  168996. upsample->methods[ci] = fullsize_upsample;
  168997. need_buffer = FALSE;
  168998. } else if (h_in_group * 2 == h_out_group &&
  168999. v_in_group == v_out_group) {
  169000. /* Special cases for 2h1v upsampling */
  169001. if (do_fancy && compptr->downsampled_width > 2)
  169002. upsample->methods[ci] = h2v1_fancy_upsample;
  169003. else
  169004. upsample->methods[ci] = h2v1_upsample;
  169005. } else if (h_in_group * 2 == h_out_group &&
  169006. v_in_group * 2 == v_out_group) {
  169007. /* Special cases for 2h2v upsampling */
  169008. if (do_fancy && compptr->downsampled_width > 2) {
  169009. upsample->methods[ci] = h2v2_fancy_upsample;
  169010. upsample->pub.need_context_rows = TRUE;
  169011. } else
  169012. upsample->methods[ci] = h2v2_upsample;
  169013. } else if ((h_out_group % h_in_group) == 0 &&
  169014. (v_out_group % v_in_group) == 0) {
  169015. /* Generic integral-factors upsampling method */
  169016. upsample->methods[ci] = int_upsample;
  169017. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  169018. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  169019. } else
  169020. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  169021. if (need_buffer) {
  169022. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  169023. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169024. (JDIMENSION) jround_up((long) cinfo->output_width,
  169025. (long) cinfo->max_h_samp_factor),
  169026. (JDIMENSION) cinfo->max_v_samp_factor);
  169027. }
  169028. }
  169029. }
  169030. /********* End of inlined file: jdsample.c *********/
  169031. /********* Start of inlined file: jdtrans.c *********/
  169032. #define JPEG_INTERNALS
  169033. /* Forward declarations */
  169034. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  169035. /*
  169036. * Read the coefficient arrays from a JPEG file.
  169037. * jpeg_read_header must be completed before calling this.
  169038. *
  169039. * The entire image is read into a set of virtual coefficient-block arrays,
  169040. * one per component. The return value is a pointer to the array of
  169041. * virtual-array descriptors. These can be manipulated directly via the
  169042. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  169043. * To release the memory occupied by the virtual arrays, call
  169044. * jpeg_finish_decompress() when done with the data.
  169045. *
  169046. * An alternative usage is to simply obtain access to the coefficient arrays
  169047. * during a buffered-image-mode decompression operation. This is allowed
  169048. * after any jpeg_finish_output() call. The arrays can be accessed until
  169049. * jpeg_finish_decompress() is called. (Note that any call to the library
  169050. * may reposition the arrays, so don't rely on access_virt_barray() results
  169051. * to stay valid across library calls.)
  169052. *
  169053. * Returns NULL if suspended. This case need be checked only if
  169054. * a suspending data source is used.
  169055. */
  169056. GLOBAL(jvirt_barray_ptr *)
  169057. jpeg_read_coefficients (j_decompress_ptr cinfo)
  169058. {
  169059. if (cinfo->global_state == DSTATE_READY) {
  169060. /* First call: initialize active modules */
  169061. transdecode_master_selection(cinfo);
  169062. cinfo->global_state = DSTATE_RDCOEFS;
  169063. }
  169064. if (cinfo->global_state == DSTATE_RDCOEFS) {
  169065. /* Absorb whole file into the coef buffer */
  169066. for (;;) {
  169067. int retcode;
  169068. /* Call progress monitor hook if present */
  169069. if (cinfo->progress != NULL)
  169070. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  169071. /* Absorb some more input */
  169072. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  169073. if (retcode == JPEG_SUSPENDED)
  169074. return NULL;
  169075. if (retcode == JPEG_REACHED_EOI)
  169076. break;
  169077. /* Advance progress counter if appropriate */
  169078. if (cinfo->progress != NULL &&
  169079. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  169080. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  169081. /* startup underestimated number of scans; ratchet up one scan */
  169082. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  169083. }
  169084. }
  169085. }
  169086. /* Set state so that jpeg_finish_decompress does the right thing */
  169087. cinfo->global_state = DSTATE_STOPPING;
  169088. }
  169089. /* At this point we should be in state DSTATE_STOPPING if being used
  169090. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  169091. * to the coefficients during a full buffered-image-mode decompression.
  169092. */
  169093. if ((cinfo->global_state == DSTATE_STOPPING ||
  169094. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  169095. return cinfo->coef->coef_arrays;
  169096. }
  169097. /* Oops, improper usage */
  169098. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169099. return NULL; /* keep compiler happy */
  169100. }
  169101. /*
  169102. * Master selection of decompression modules for transcoding.
  169103. * This substitutes for jdmaster.c's initialization of the full decompressor.
  169104. */
  169105. LOCAL(void)
  169106. transdecode_master_selection (j_decompress_ptr cinfo)
  169107. {
  169108. /* This is effectively a buffered-image operation. */
  169109. cinfo->buffered_image = TRUE;
  169110. /* Entropy decoding: either Huffman or arithmetic coding. */
  169111. if (cinfo->arith_code) {
  169112. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  169113. } else {
  169114. if (cinfo->progressive_mode) {
  169115. #ifdef D_PROGRESSIVE_SUPPORTED
  169116. jinit_phuff_decoder(cinfo);
  169117. #else
  169118. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169119. #endif
  169120. } else
  169121. jinit_huff_decoder(cinfo);
  169122. }
  169123. /* Always get a full-image coefficient buffer. */
  169124. jinit_d_coef_controller(cinfo, TRUE);
  169125. /* We can now tell the memory manager to allocate virtual arrays. */
  169126. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  169127. /* Initialize input side of decompressor to consume first scan. */
  169128. (*cinfo->inputctl->start_input_pass) (cinfo);
  169129. /* Initialize progress monitoring. */
  169130. if (cinfo->progress != NULL) {
  169131. int nscans;
  169132. /* Estimate number of scans to set pass_limit. */
  169133. if (cinfo->progressive_mode) {
  169134. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  169135. nscans = 2 + 3 * cinfo->num_components;
  169136. } else if (cinfo->inputctl->has_multiple_scans) {
  169137. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  169138. nscans = cinfo->num_components;
  169139. } else {
  169140. nscans = 1;
  169141. }
  169142. cinfo->progress->pass_counter = 0L;
  169143. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  169144. cinfo->progress->completed_passes = 0;
  169145. cinfo->progress->total_passes = 1;
  169146. }
  169147. }
  169148. /********* End of inlined file: jdtrans.c *********/
  169149. /********* Start of inlined file: jfdctflt.c *********/
  169150. #define JPEG_INTERNALS
  169151. #ifdef DCT_FLOAT_SUPPORTED
  169152. /*
  169153. * This module is specialized to the case DCTSIZE = 8.
  169154. */
  169155. #if DCTSIZE != 8
  169156. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169157. #endif
  169158. /*
  169159. * Perform the forward DCT on one block of samples.
  169160. */
  169161. GLOBAL(void)
  169162. jpeg_fdct_float (FAST_FLOAT * data)
  169163. {
  169164. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169165. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  169166. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  169167. FAST_FLOAT *dataptr;
  169168. int ctr;
  169169. /* Pass 1: process rows. */
  169170. dataptr = data;
  169171. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169172. tmp0 = dataptr[0] + dataptr[7];
  169173. tmp7 = dataptr[0] - dataptr[7];
  169174. tmp1 = dataptr[1] + dataptr[6];
  169175. tmp6 = dataptr[1] - dataptr[6];
  169176. tmp2 = dataptr[2] + dataptr[5];
  169177. tmp5 = dataptr[2] - dataptr[5];
  169178. tmp3 = dataptr[3] + dataptr[4];
  169179. tmp4 = dataptr[3] - dataptr[4];
  169180. /* Even part */
  169181. tmp10 = tmp0 + tmp3; /* phase 2 */
  169182. tmp13 = tmp0 - tmp3;
  169183. tmp11 = tmp1 + tmp2;
  169184. tmp12 = tmp1 - tmp2;
  169185. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  169186. dataptr[4] = tmp10 - tmp11;
  169187. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  169188. dataptr[2] = tmp13 + z1; /* phase 5 */
  169189. dataptr[6] = tmp13 - z1;
  169190. /* Odd part */
  169191. tmp10 = tmp4 + tmp5; /* phase 2 */
  169192. tmp11 = tmp5 + tmp6;
  169193. tmp12 = tmp6 + tmp7;
  169194. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  169195. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  169196. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  169197. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  169198. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  169199. z11 = tmp7 + z3; /* phase 5 */
  169200. z13 = tmp7 - z3;
  169201. dataptr[5] = z13 + z2; /* phase 6 */
  169202. dataptr[3] = z13 - z2;
  169203. dataptr[1] = z11 + z4;
  169204. dataptr[7] = z11 - z4;
  169205. dataptr += DCTSIZE; /* advance pointer to next row */
  169206. }
  169207. /* Pass 2: process columns. */
  169208. dataptr = data;
  169209. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169210. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  169211. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  169212. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  169213. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  169214. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  169215. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  169216. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  169217. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  169218. /* Even part */
  169219. tmp10 = tmp0 + tmp3; /* phase 2 */
  169220. tmp13 = tmp0 - tmp3;
  169221. tmp11 = tmp1 + tmp2;
  169222. tmp12 = tmp1 - tmp2;
  169223. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  169224. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  169225. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  169226. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  169227. dataptr[DCTSIZE*6] = tmp13 - z1;
  169228. /* Odd part */
  169229. tmp10 = tmp4 + tmp5; /* phase 2 */
  169230. tmp11 = tmp5 + tmp6;
  169231. tmp12 = tmp6 + tmp7;
  169232. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  169233. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  169234. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  169235. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  169236. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  169237. z11 = tmp7 + z3; /* phase 5 */
  169238. z13 = tmp7 - z3;
  169239. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  169240. dataptr[DCTSIZE*3] = z13 - z2;
  169241. dataptr[DCTSIZE*1] = z11 + z4;
  169242. dataptr[DCTSIZE*7] = z11 - z4;
  169243. dataptr++; /* advance pointer to next column */
  169244. }
  169245. }
  169246. #endif /* DCT_FLOAT_SUPPORTED */
  169247. /********* End of inlined file: jfdctflt.c *********/
  169248. /********* Start of inlined file: jfdctint.c *********/
  169249. #define JPEG_INTERNALS
  169250. #ifdef DCT_ISLOW_SUPPORTED
  169251. /*
  169252. * This module is specialized to the case DCTSIZE = 8.
  169253. */
  169254. #if DCTSIZE != 8
  169255. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169256. #endif
  169257. /*
  169258. * The poop on this scaling stuff is as follows:
  169259. *
  169260. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  169261. * larger than the true DCT outputs. The final outputs are therefore
  169262. * a factor of N larger than desired; since N=8 this can be cured by
  169263. * a simple right shift at the end of the algorithm. The advantage of
  169264. * this arrangement is that we save two multiplications per 1-D DCT,
  169265. * because the y0 and y4 outputs need not be divided by sqrt(N).
  169266. * In the IJG code, this factor of 8 is removed by the quantization step
  169267. * (in jcdctmgr.c), NOT in this module.
  169268. *
  169269. * We have to do addition and subtraction of the integer inputs, which
  169270. * is no problem, and multiplication by fractional constants, which is
  169271. * a problem to do in integer arithmetic. We multiply all the constants
  169272. * by CONST_SCALE and convert them to integer constants (thus retaining
  169273. * CONST_BITS bits of precision in the constants). After doing a
  169274. * multiplication we have to divide the product by CONST_SCALE, with proper
  169275. * rounding, to produce the correct output. This division can be done
  169276. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  169277. * as long as possible so that partial sums can be added together with
  169278. * full fractional precision.
  169279. *
  169280. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  169281. * they are represented to better-than-integral precision. These outputs
  169282. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  169283. * with the recommended scaling. (For 12-bit sample data, the intermediate
  169284. * array is INT32 anyway.)
  169285. *
  169286. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  169287. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  169288. * shows that the values given below are the most effective.
  169289. */
  169290. #if BITS_IN_JSAMPLE == 8
  169291. #define CONST_BITS 13
  169292. #define PASS1_BITS 2
  169293. #else
  169294. #define CONST_BITS 13
  169295. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  169296. #endif
  169297. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169298. * causing a lot of useless floating-point operations at run time.
  169299. * To get around this we use the following pre-calculated constants.
  169300. * If you change CONST_BITS you may want to add appropriate values.
  169301. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  169302. */
  169303. #if CONST_BITS == 13
  169304. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  169305. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  169306. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  169307. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  169308. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  169309. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  169310. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  169311. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  169312. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  169313. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  169314. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  169315. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  169316. #else
  169317. #define FIX_0_298631336 FIX(0.298631336)
  169318. #define FIX_0_390180644 FIX(0.390180644)
  169319. #define FIX_0_541196100 FIX(0.541196100)
  169320. #define FIX_0_765366865 FIX(0.765366865)
  169321. #define FIX_0_899976223 FIX(0.899976223)
  169322. #define FIX_1_175875602 FIX(1.175875602)
  169323. #define FIX_1_501321110 FIX(1.501321110)
  169324. #define FIX_1_847759065 FIX(1.847759065)
  169325. #define FIX_1_961570560 FIX(1.961570560)
  169326. #define FIX_2_053119869 FIX(2.053119869)
  169327. #define FIX_2_562915447 FIX(2.562915447)
  169328. #define FIX_3_072711026 FIX(3.072711026)
  169329. #endif
  169330. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  169331. * For 8-bit samples with the recommended scaling, all the variable
  169332. * and constant values involved are no more than 16 bits wide, so a
  169333. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  169334. * For 12-bit samples, a full 32-bit multiplication will be needed.
  169335. */
  169336. #if BITS_IN_JSAMPLE == 8
  169337. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  169338. #else
  169339. #define MULTIPLY(var,const) ((var) * (const))
  169340. #endif
  169341. /*
  169342. * Perform the forward DCT on one block of samples.
  169343. */
  169344. GLOBAL(void)
  169345. jpeg_fdct_islow (DCTELEM * data)
  169346. {
  169347. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169348. INT32 tmp10, tmp11, tmp12, tmp13;
  169349. INT32 z1, z2, z3, z4, z5;
  169350. DCTELEM *dataptr;
  169351. int ctr;
  169352. SHIFT_TEMPS
  169353. /* Pass 1: process rows. */
  169354. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  169355. /* furthermore, we scale the results by 2**PASS1_BITS. */
  169356. dataptr = data;
  169357. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169358. tmp0 = dataptr[0] + dataptr[7];
  169359. tmp7 = dataptr[0] - dataptr[7];
  169360. tmp1 = dataptr[1] + dataptr[6];
  169361. tmp6 = dataptr[1] - dataptr[6];
  169362. tmp2 = dataptr[2] + dataptr[5];
  169363. tmp5 = dataptr[2] - dataptr[5];
  169364. tmp3 = dataptr[3] + dataptr[4];
  169365. tmp4 = dataptr[3] - dataptr[4];
  169366. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  169367. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  169368. */
  169369. tmp10 = tmp0 + tmp3;
  169370. tmp13 = tmp0 - tmp3;
  169371. tmp11 = tmp1 + tmp2;
  169372. tmp12 = tmp1 - tmp2;
  169373. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  169374. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  169375. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  169376. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  169377. CONST_BITS-PASS1_BITS);
  169378. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  169379. CONST_BITS-PASS1_BITS);
  169380. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  169381. * cK represents cos(K*pi/16).
  169382. * i0..i3 in the paper are tmp4..tmp7 here.
  169383. */
  169384. z1 = tmp4 + tmp7;
  169385. z2 = tmp5 + tmp6;
  169386. z3 = tmp4 + tmp6;
  169387. z4 = tmp5 + tmp7;
  169388. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  169389. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  169390. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  169391. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  169392. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  169393. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  169394. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  169395. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  169396. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  169397. z3 += z5;
  169398. z4 += z5;
  169399. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  169400. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  169401. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  169402. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  169403. dataptr += DCTSIZE; /* advance pointer to next row */
  169404. }
  169405. /* Pass 2: process columns.
  169406. * We remove the PASS1_BITS scaling, but leave the results scaled up
  169407. * by an overall factor of 8.
  169408. */
  169409. dataptr = data;
  169410. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169411. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  169412. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  169413. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  169414. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  169415. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  169416. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  169417. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  169418. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  169419. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  169420. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  169421. */
  169422. tmp10 = tmp0 + tmp3;
  169423. tmp13 = tmp0 - tmp3;
  169424. tmp11 = tmp1 + tmp2;
  169425. tmp12 = tmp1 - tmp2;
  169426. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  169427. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  169428. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  169429. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  169430. CONST_BITS+PASS1_BITS);
  169431. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  169432. CONST_BITS+PASS1_BITS);
  169433. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  169434. * cK represents cos(K*pi/16).
  169435. * i0..i3 in the paper are tmp4..tmp7 here.
  169436. */
  169437. z1 = tmp4 + tmp7;
  169438. z2 = tmp5 + tmp6;
  169439. z3 = tmp4 + tmp6;
  169440. z4 = tmp5 + tmp7;
  169441. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  169442. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  169443. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  169444. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  169445. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  169446. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  169447. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  169448. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  169449. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  169450. z3 += z5;
  169451. z4 += z5;
  169452. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  169453. CONST_BITS+PASS1_BITS);
  169454. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  169455. CONST_BITS+PASS1_BITS);
  169456. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  169457. CONST_BITS+PASS1_BITS);
  169458. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  169459. CONST_BITS+PASS1_BITS);
  169460. dataptr++; /* advance pointer to next column */
  169461. }
  169462. }
  169463. #endif /* DCT_ISLOW_SUPPORTED */
  169464. /********* End of inlined file: jfdctint.c *********/
  169465. #undef CONST_BITS
  169466. #undef MULTIPLY
  169467. #undef FIX_0_541196100
  169468. /********* Start of inlined file: jfdctfst.c *********/
  169469. #define JPEG_INTERNALS
  169470. #ifdef DCT_IFAST_SUPPORTED
  169471. /*
  169472. * This module is specialized to the case DCTSIZE = 8.
  169473. */
  169474. #if DCTSIZE != 8
  169475. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169476. #endif
  169477. /* Scaling decisions are generally the same as in the LL&M algorithm;
  169478. * see jfdctint.c for more details. However, we choose to descale
  169479. * (right shift) multiplication products as soon as they are formed,
  169480. * rather than carrying additional fractional bits into subsequent additions.
  169481. * This compromises accuracy slightly, but it lets us save a few shifts.
  169482. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  169483. * everywhere except in the multiplications proper; this saves a good deal
  169484. * of work on 16-bit-int machines.
  169485. *
  169486. * Again to save a few shifts, the intermediate results between pass 1 and
  169487. * pass 2 are not upscaled, but are represented only to integral precision.
  169488. *
  169489. * A final compromise is to represent the multiplicative constants to only
  169490. * 8 fractional bits, rather than 13. This saves some shifting work on some
  169491. * machines, and may also reduce the cost of multiplication (since there
  169492. * are fewer one-bits in the constants).
  169493. */
  169494. #define CONST_BITS 8
  169495. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169496. * causing a lot of useless floating-point operations at run time.
  169497. * To get around this we use the following pre-calculated constants.
  169498. * If you change CONST_BITS you may want to add appropriate values.
  169499. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  169500. */
  169501. #if CONST_BITS == 8
  169502. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  169503. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  169504. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  169505. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  169506. #else
  169507. #define FIX_0_382683433 FIX(0.382683433)
  169508. #define FIX_0_541196100 FIX(0.541196100)
  169509. #define FIX_0_707106781 FIX(0.707106781)
  169510. #define FIX_1_306562965 FIX(1.306562965)
  169511. #endif
  169512. /* We can gain a little more speed, with a further compromise in accuracy,
  169513. * by omitting the addition in a descaling shift. This yields an incorrectly
  169514. * rounded result half the time...
  169515. */
  169516. #ifndef USE_ACCURATE_ROUNDING
  169517. #undef DESCALE
  169518. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  169519. #endif
  169520. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  169521. * descale to yield a DCTELEM result.
  169522. */
  169523. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  169524. /*
  169525. * Perform the forward DCT on one block of samples.
  169526. */
  169527. GLOBAL(void)
  169528. jpeg_fdct_ifast (DCTELEM * data)
  169529. {
  169530. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169531. DCTELEM tmp10, tmp11, tmp12, tmp13;
  169532. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  169533. DCTELEM *dataptr;
  169534. int ctr;
  169535. SHIFT_TEMPS
  169536. /* Pass 1: process rows. */
  169537. dataptr = data;
  169538. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169539. tmp0 = dataptr[0] + dataptr[7];
  169540. tmp7 = dataptr[0] - dataptr[7];
  169541. tmp1 = dataptr[1] + dataptr[6];
  169542. tmp6 = dataptr[1] - dataptr[6];
  169543. tmp2 = dataptr[2] + dataptr[5];
  169544. tmp5 = dataptr[2] - dataptr[5];
  169545. tmp3 = dataptr[3] + dataptr[4];
  169546. tmp4 = dataptr[3] - dataptr[4];
  169547. /* Even part */
  169548. tmp10 = tmp0 + tmp3; /* phase 2 */
  169549. tmp13 = tmp0 - tmp3;
  169550. tmp11 = tmp1 + tmp2;
  169551. tmp12 = tmp1 - tmp2;
  169552. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  169553. dataptr[4] = tmp10 - tmp11;
  169554. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  169555. dataptr[2] = tmp13 + z1; /* phase 5 */
  169556. dataptr[6] = tmp13 - z1;
  169557. /* Odd part */
  169558. tmp10 = tmp4 + tmp5; /* phase 2 */
  169559. tmp11 = tmp5 + tmp6;
  169560. tmp12 = tmp6 + tmp7;
  169561. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  169562. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  169563. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  169564. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  169565. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  169566. z11 = tmp7 + z3; /* phase 5 */
  169567. z13 = tmp7 - z3;
  169568. dataptr[5] = z13 + z2; /* phase 6 */
  169569. dataptr[3] = z13 - z2;
  169570. dataptr[1] = z11 + z4;
  169571. dataptr[7] = z11 - z4;
  169572. dataptr += DCTSIZE; /* advance pointer to next row */
  169573. }
  169574. /* Pass 2: process columns. */
  169575. dataptr = data;
  169576. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169577. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  169578. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  169579. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  169580. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  169581. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  169582. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  169583. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  169584. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  169585. /* Even part */
  169586. tmp10 = tmp0 + tmp3; /* phase 2 */
  169587. tmp13 = tmp0 - tmp3;
  169588. tmp11 = tmp1 + tmp2;
  169589. tmp12 = tmp1 - tmp2;
  169590. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  169591. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  169592. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  169593. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  169594. dataptr[DCTSIZE*6] = tmp13 - z1;
  169595. /* Odd part */
  169596. tmp10 = tmp4 + tmp5; /* phase 2 */
  169597. tmp11 = tmp5 + tmp6;
  169598. tmp12 = tmp6 + tmp7;
  169599. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  169600. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  169601. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  169602. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  169603. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  169604. z11 = tmp7 + z3; /* phase 5 */
  169605. z13 = tmp7 - z3;
  169606. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  169607. dataptr[DCTSIZE*3] = z13 - z2;
  169608. dataptr[DCTSIZE*1] = z11 + z4;
  169609. dataptr[DCTSIZE*7] = z11 - z4;
  169610. dataptr++; /* advance pointer to next column */
  169611. }
  169612. }
  169613. #endif /* DCT_IFAST_SUPPORTED */
  169614. /********* End of inlined file: jfdctfst.c *********/
  169615. #undef FIX_0_541196100
  169616. /********* Start of inlined file: jidctflt.c *********/
  169617. #define JPEG_INTERNALS
  169618. #ifdef DCT_FLOAT_SUPPORTED
  169619. /*
  169620. * This module is specialized to the case DCTSIZE = 8.
  169621. */
  169622. #if DCTSIZE != 8
  169623. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169624. #endif
  169625. /* Dequantize a coefficient by multiplying it by the multiplier-table
  169626. * entry; produce a float result.
  169627. */
  169628. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  169629. /*
  169630. * Perform dequantization and inverse DCT on one block of coefficients.
  169631. */
  169632. GLOBAL(void)
  169633. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169634. JCOEFPTR coef_block,
  169635. JSAMPARRAY output_buf, JDIMENSION output_col)
  169636. {
  169637. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169638. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  169639. FAST_FLOAT z5, z10, z11, z12, z13;
  169640. JCOEFPTR inptr;
  169641. FLOAT_MULT_TYPE * quantptr;
  169642. FAST_FLOAT * wsptr;
  169643. JSAMPROW outptr;
  169644. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169645. int ctr;
  169646. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  169647. SHIFT_TEMPS
  169648. /* Pass 1: process columns from input, store into work array. */
  169649. inptr = coef_block;
  169650. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169651. wsptr = workspace;
  169652. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  169653. /* Due to quantization, we will usually find that many of the input
  169654. * coefficients are zero, especially the AC terms. We can exploit this
  169655. * by short-circuiting the IDCT calculation for any column in which all
  169656. * the AC terms are zero. In that case each output is equal to the
  169657. * DC coefficient (with scale factor as needed).
  169658. * With typical images and quantization tables, half or more of the
  169659. * column DCT calculations can be simplified this way.
  169660. */
  169661. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  169662. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  169663. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  169664. inptr[DCTSIZE*7] == 0) {
  169665. /* AC terms all zero */
  169666. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169667. wsptr[DCTSIZE*0] = dcval;
  169668. wsptr[DCTSIZE*1] = dcval;
  169669. wsptr[DCTSIZE*2] = dcval;
  169670. wsptr[DCTSIZE*3] = dcval;
  169671. wsptr[DCTSIZE*4] = dcval;
  169672. wsptr[DCTSIZE*5] = dcval;
  169673. wsptr[DCTSIZE*6] = dcval;
  169674. wsptr[DCTSIZE*7] = dcval;
  169675. inptr++; /* advance pointers to next column */
  169676. quantptr++;
  169677. wsptr++;
  169678. continue;
  169679. }
  169680. /* Even part */
  169681. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169682. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  169683. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  169684. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  169685. tmp10 = tmp0 + tmp2; /* phase 3 */
  169686. tmp11 = tmp0 - tmp2;
  169687. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  169688. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  169689. tmp0 = tmp10 + tmp13; /* phase 2 */
  169690. tmp3 = tmp10 - tmp13;
  169691. tmp1 = tmp11 + tmp12;
  169692. tmp2 = tmp11 - tmp12;
  169693. /* Odd part */
  169694. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169695. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169696. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169697. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169698. z13 = tmp6 + tmp5; /* phase 6 */
  169699. z10 = tmp6 - tmp5;
  169700. z11 = tmp4 + tmp7;
  169701. z12 = tmp4 - tmp7;
  169702. tmp7 = z11 + z13; /* phase 5 */
  169703. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  169704. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  169705. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  169706. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  169707. tmp6 = tmp12 - tmp7; /* phase 2 */
  169708. tmp5 = tmp11 - tmp6;
  169709. tmp4 = tmp10 + tmp5;
  169710. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  169711. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  169712. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  169713. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  169714. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  169715. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  169716. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  169717. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  169718. inptr++; /* advance pointers to next column */
  169719. quantptr++;
  169720. wsptr++;
  169721. }
  169722. /* Pass 2: process rows from work array, store into output array. */
  169723. /* Note that we must descale the results by a factor of 8 == 2**3. */
  169724. wsptr = workspace;
  169725. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  169726. outptr = output_buf[ctr] + output_col;
  169727. /* Rows of zeroes can be exploited in the same way as we did with columns.
  169728. * However, the column calculation has created many nonzero AC terms, so
  169729. * the simplification applies less often (typically 5% to 10% of the time).
  169730. * And testing floats for zero is relatively expensive, so we don't bother.
  169731. */
  169732. /* Even part */
  169733. tmp10 = wsptr[0] + wsptr[4];
  169734. tmp11 = wsptr[0] - wsptr[4];
  169735. tmp13 = wsptr[2] + wsptr[6];
  169736. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  169737. tmp0 = tmp10 + tmp13;
  169738. tmp3 = tmp10 - tmp13;
  169739. tmp1 = tmp11 + tmp12;
  169740. tmp2 = tmp11 - tmp12;
  169741. /* Odd part */
  169742. z13 = wsptr[5] + wsptr[3];
  169743. z10 = wsptr[5] - wsptr[3];
  169744. z11 = wsptr[1] + wsptr[7];
  169745. z12 = wsptr[1] - wsptr[7];
  169746. tmp7 = z11 + z13;
  169747. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  169748. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  169749. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  169750. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  169751. tmp6 = tmp12 - tmp7;
  169752. tmp5 = tmp11 - tmp6;
  169753. tmp4 = tmp10 + tmp5;
  169754. /* Final output stage: scale down by a factor of 8 and range-limit */
  169755. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  169756. & RANGE_MASK];
  169757. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  169758. & RANGE_MASK];
  169759. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  169760. & RANGE_MASK];
  169761. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  169762. & RANGE_MASK];
  169763. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  169764. & RANGE_MASK];
  169765. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  169766. & RANGE_MASK];
  169767. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  169768. & RANGE_MASK];
  169769. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  169770. & RANGE_MASK];
  169771. wsptr += DCTSIZE; /* advance pointer to next row */
  169772. }
  169773. }
  169774. #endif /* DCT_FLOAT_SUPPORTED */
  169775. /********* End of inlined file: jidctflt.c *********/
  169776. #undef CONST_BITS
  169777. #undef FIX_1_847759065
  169778. #undef MULTIPLY
  169779. #undef DEQUANTIZE
  169780. #undef DESCALE
  169781. /********* Start of inlined file: jidctfst.c *********/
  169782. #define JPEG_INTERNALS
  169783. #ifdef DCT_IFAST_SUPPORTED
  169784. /*
  169785. * This module is specialized to the case DCTSIZE = 8.
  169786. */
  169787. #if DCTSIZE != 8
  169788. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169789. #endif
  169790. /* Scaling decisions are generally the same as in the LL&M algorithm;
  169791. * see jidctint.c for more details. However, we choose to descale
  169792. * (right shift) multiplication products as soon as they are formed,
  169793. * rather than carrying additional fractional bits into subsequent additions.
  169794. * This compromises accuracy slightly, but it lets us save a few shifts.
  169795. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  169796. * everywhere except in the multiplications proper; this saves a good deal
  169797. * of work on 16-bit-int machines.
  169798. *
  169799. * The dequantized coefficients are not integers because the AA&N scaling
  169800. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  169801. * so that the first and second IDCT rounds have the same input scaling.
  169802. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  169803. * avoid a descaling shift; this compromises accuracy rather drastically
  169804. * for small quantization table entries, but it saves a lot of shifts.
  169805. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  169806. * so we use a much larger scaling factor to preserve accuracy.
  169807. *
  169808. * A final compromise is to represent the multiplicative constants to only
  169809. * 8 fractional bits, rather than 13. This saves some shifting work on some
  169810. * machines, and may also reduce the cost of multiplication (since there
  169811. * are fewer one-bits in the constants).
  169812. */
  169813. #if BITS_IN_JSAMPLE == 8
  169814. #define CONST_BITS 8
  169815. #define PASS1_BITS 2
  169816. #else
  169817. #define CONST_BITS 8
  169818. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  169819. #endif
  169820. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169821. * causing a lot of useless floating-point operations at run time.
  169822. * To get around this we use the following pre-calculated constants.
  169823. * If you change CONST_BITS you may want to add appropriate values.
  169824. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  169825. */
  169826. #if CONST_BITS == 8
  169827. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  169828. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  169829. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  169830. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  169831. #else
  169832. #define FIX_1_082392200 FIX(1.082392200)
  169833. #define FIX_1_414213562 FIX(1.414213562)
  169834. #define FIX_1_847759065 FIX(1.847759065)
  169835. #define FIX_2_613125930 FIX(2.613125930)
  169836. #endif
  169837. /* We can gain a little more speed, with a further compromise in accuracy,
  169838. * by omitting the addition in a descaling shift. This yields an incorrectly
  169839. * rounded result half the time...
  169840. */
  169841. #ifndef USE_ACCURATE_ROUNDING
  169842. #undef DESCALE
  169843. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  169844. #endif
  169845. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  169846. * descale to yield a DCTELEM result.
  169847. */
  169848. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  169849. /* Dequantize a coefficient by multiplying it by the multiplier-table
  169850. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  169851. * multiplication will do. For 12-bit data, the multiplier table is
  169852. * declared INT32, so a 32-bit multiply will be used.
  169853. */
  169854. #if BITS_IN_JSAMPLE == 8
  169855. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  169856. #else
  169857. #define DEQUANTIZE(coef,quantval) \
  169858. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  169859. #endif
  169860. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  169861. * We assume that int right shift is unsigned if INT32 right shift is.
  169862. */
  169863. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  169864. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  169865. #if BITS_IN_JSAMPLE == 8
  169866. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  169867. #else
  169868. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  169869. #endif
  169870. #define IRIGHT_SHIFT(x,shft) \
  169871. ((ishift_temp = (x)) < 0 ? \
  169872. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  169873. (ishift_temp >> (shft)))
  169874. #else
  169875. #define ISHIFT_TEMPS
  169876. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  169877. #endif
  169878. #ifdef USE_ACCURATE_ROUNDING
  169879. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  169880. #else
  169881. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  169882. #endif
  169883. /*
  169884. * Perform dequantization and inverse DCT on one block of coefficients.
  169885. */
  169886. GLOBAL(void)
  169887. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169888. JCOEFPTR coef_block,
  169889. JSAMPARRAY output_buf, JDIMENSION output_col)
  169890. {
  169891. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169892. DCTELEM tmp10, tmp11, tmp12, tmp13;
  169893. DCTELEM z5, z10, z11, z12, z13;
  169894. JCOEFPTR inptr;
  169895. IFAST_MULT_TYPE * quantptr;
  169896. int * wsptr;
  169897. JSAMPROW outptr;
  169898. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169899. int ctr;
  169900. int workspace[DCTSIZE2]; /* buffers data between passes */
  169901. SHIFT_TEMPS /* for DESCALE */
  169902. ISHIFT_TEMPS /* for IDESCALE */
  169903. /* Pass 1: process columns from input, store into work array. */
  169904. inptr = coef_block;
  169905. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  169906. wsptr = workspace;
  169907. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  169908. /* Due to quantization, we will usually find that many of the input
  169909. * coefficients are zero, especially the AC terms. We can exploit this
  169910. * by short-circuiting the IDCT calculation for any column in which all
  169911. * the AC terms are zero. In that case each output is equal to the
  169912. * DC coefficient (with scale factor as needed).
  169913. * With typical images and quantization tables, half or more of the
  169914. * column DCT calculations can be simplified this way.
  169915. */
  169916. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  169917. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  169918. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  169919. inptr[DCTSIZE*7] == 0) {
  169920. /* AC terms all zero */
  169921. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169922. wsptr[DCTSIZE*0] = dcval;
  169923. wsptr[DCTSIZE*1] = dcval;
  169924. wsptr[DCTSIZE*2] = dcval;
  169925. wsptr[DCTSIZE*3] = dcval;
  169926. wsptr[DCTSIZE*4] = dcval;
  169927. wsptr[DCTSIZE*5] = dcval;
  169928. wsptr[DCTSIZE*6] = dcval;
  169929. wsptr[DCTSIZE*7] = dcval;
  169930. inptr++; /* advance pointers to next column */
  169931. quantptr++;
  169932. wsptr++;
  169933. continue;
  169934. }
  169935. /* Even part */
  169936. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169937. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  169938. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  169939. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  169940. tmp10 = tmp0 + tmp2; /* phase 3 */
  169941. tmp11 = tmp0 - tmp2;
  169942. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  169943. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  169944. tmp0 = tmp10 + tmp13; /* phase 2 */
  169945. tmp3 = tmp10 - tmp13;
  169946. tmp1 = tmp11 + tmp12;
  169947. tmp2 = tmp11 - tmp12;
  169948. /* Odd part */
  169949. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169950. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169951. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169952. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169953. z13 = tmp6 + tmp5; /* phase 6 */
  169954. z10 = tmp6 - tmp5;
  169955. z11 = tmp4 + tmp7;
  169956. z12 = tmp4 - tmp7;
  169957. tmp7 = z11 + z13; /* phase 5 */
  169958. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  169959. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  169960. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  169961. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  169962. tmp6 = tmp12 - tmp7; /* phase 2 */
  169963. tmp5 = tmp11 - tmp6;
  169964. tmp4 = tmp10 + tmp5;
  169965. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  169966. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  169967. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  169968. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  169969. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  169970. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  169971. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  169972. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  169973. inptr++; /* advance pointers to next column */
  169974. quantptr++;
  169975. wsptr++;
  169976. }
  169977. /* Pass 2: process rows from work array, store into output array. */
  169978. /* Note that we must descale the results by a factor of 8 == 2**3, */
  169979. /* and also undo the PASS1_BITS scaling. */
  169980. wsptr = workspace;
  169981. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  169982. outptr = output_buf[ctr] + output_col;
  169983. /* Rows of zeroes can be exploited in the same way as we did with columns.
  169984. * However, the column calculation has created many nonzero AC terms, so
  169985. * the simplification applies less often (typically 5% to 10% of the time).
  169986. * On machines with very fast multiplication, it's possible that the
  169987. * test takes more time than it's worth. In that case this section
  169988. * may be commented out.
  169989. */
  169990. #ifndef NO_ZERO_ROW_TEST
  169991. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  169992. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  169993. /* AC terms all zero */
  169994. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  169995. & RANGE_MASK];
  169996. outptr[0] = dcval;
  169997. outptr[1] = dcval;
  169998. outptr[2] = dcval;
  169999. outptr[3] = dcval;
  170000. outptr[4] = dcval;
  170001. outptr[5] = dcval;
  170002. outptr[6] = dcval;
  170003. outptr[7] = dcval;
  170004. wsptr += DCTSIZE; /* advance pointer to next row */
  170005. continue;
  170006. }
  170007. #endif
  170008. /* Even part */
  170009. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  170010. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  170011. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  170012. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  170013. - tmp13;
  170014. tmp0 = tmp10 + tmp13;
  170015. tmp3 = tmp10 - tmp13;
  170016. tmp1 = tmp11 + tmp12;
  170017. tmp2 = tmp11 - tmp12;
  170018. /* Odd part */
  170019. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  170020. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  170021. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  170022. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  170023. tmp7 = z11 + z13; /* phase 5 */
  170024. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  170025. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  170026. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  170027. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  170028. tmp6 = tmp12 - tmp7; /* phase 2 */
  170029. tmp5 = tmp11 - tmp6;
  170030. tmp4 = tmp10 + tmp5;
  170031. /* Final output stage: scale down by a factor of 8 and range-limit */
  170032. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  170033. & RANGE_MASK];
  170034. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  170035. & RANGE_MASK];
  170036. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  170037. & RANGE_MASK];
  170038. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  170039. & RANGE_MASK];
  170040. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  170041. & RANGE_MASK];
  170042. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  170043. & RANGE_MASK];
  170044. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  170045. & RANGE_MASK];
  170046. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  170047. & RANGE_MASK];
  170048. wsptr += DCTSIZE; /* advance pointer to next row */
  170049. }
  170050. }
  170051. #endif /* DCT_IFAST_SUPPORTED */
  170052. /********* End of inlined file: jidctfst.c *********/
  170053. #undef CONST_BITS
  170054. #undef FIX_1_847759065
  170055. #undef MULTIPLY
  170056. #undef DEQUANTIZE
  170057. /********* Start of inlined file: jidctint.c *********/
  170058. #define JPEG_INTERNALS
  170059. #ifdef DCT_ISLOW_SUPPORTED
  170060. /*
  170061. * This module is specialized to the case DCTSIZE = 8.
  170062. */
  170063. #if DCTSIZE != 8
  170064. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170065. #endif
  170066. /*
  170067. * The poop on this scaling stuff is as follows:
  170068. *
  170069. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  170070. * larger than the true IDCT outputs. The final outputs are therefore
  170071. * a factor of N larger than desired; since N=8 this can be cured by
  170072. * a simple right shift at the end of the algorithm. The advantage of
  170073. * this arrangement is that we save two multiplications per 1-D IDCT,
  170074. * because the y0 and y4 inputs need not be divided by sqrt(N).
  170075. *
  170076. * We have to do addition and subtraction of the integer inputs, which
  170077. * is no problem, and multiplication by fractional constants, which is
  170078. * a problem to do in integer arithmetic. We multiply all the constants
  170079. * by CONST_SCALE and convert them to integer constants (thus retaining
  170080. * CONST_BITS bits of precision in the constants). After doing a
  170081. * multiplication we have to divide the product by CONST_SCALE, with proper
  170082. * rounding, to produce the correct output. This division can be done
  170083. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  170084. * as long as possible so that partial sums can be added together with
  170085. * full fractional precision.
  170086. *
  170087. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  170088. * they are represented to better-than-integral precision. These outputs
  170089. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  170090. * with the recommended scaling. (To scale up 12-bit sample data further, an
  170091. * intermediate INT32 array would be needed.)
  170092. *
  170093. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  170094. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  170095. * shows that the values given below are the most effective.
  170096. */
  170097. #if BITS_IN_JSAMPLE == 8
  170098. #define CONST_BITS 13
  170099. #define PASS1_BITS 2
  170100. #else
  170101. #define CONST_BITS 13
  170102. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170103. #endif
  170104. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170105. * causing a lot of useless floating-point operations at run time.
  170106. * To get around this we use the following pre-calculated constants.
  170107. * If you change CONST_BITS you may want to add appropriate values.
  170108. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170109. */
  170110. #if CONST_BITS == 13
  170111. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  170112. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  170113. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  170114. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  170115. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  170116. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  170117. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  170118. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  170119. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  170120. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  170121. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  170122. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  170123. #else
  170124. #define FIX_0_298631336 FIX(0.298631336)
  170125. #define FIX_0_390180644 FIX(0.390180644)
  170126. #define FIX_0_541196100 FIX(0.541196100)
  170127. #define FIX_0_765366865 FIX(0.765366865)
  170128. #define FIX_0_899976223 FIX(0.899976223)
  170129. #define FIX_1_175875602 FIX(1.175875602)
  170130. #define FIX_1_501321110 FIX(1.501321110)
  170131. #define FIX_1_847759065 FIX(1.847759065)
  170132. #define FIX_1_961570560 FIX(1.961570560)
  170133. #define FIX_2_053119869 FIX(2.053119869)
  170134. #define FIX_2_562915447 FIX(2.562915447)
  170135. #define FIX_3_072711026 FIX(3.072711026)
  170136. #endif
  170137. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  170138. * For 8-bit samples with the recommended scaling, all the variable
  170139. * and constant values involved are no more than 16 bits wide, so a
  170140. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  170141. * For 12-bit samples, a full 32-bit multiplication will be needed.
  170142. */
  170143. #if BITS_IN_JSAMPLE == 8
  170144. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  170145. #else
  170146. #define MULTIPLY(var,const) ((var) * (const))
  170147. #endif
  170148. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170149. * entry; produce an int result. In this module, both inputs and result
  170150. * are 16 bits or less, so either int or short multiply will work.
  170151. */
  170152. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  170153. /*
  170154. * Perform dequantization and inverse DCT on one block of coefficients.
  170155. */
  170156. GLOBAL(void)
  170157. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170158. JCOEFPTR coef_block,
  170159. JSAMPARRAY output_buf, JDIMENSION output_col)
  170160. {
  170161. INT32 tmp0, tmp1, tmp2, tmp3;
  170162. INT32 tmp10, tmp11, tmp12, tmp13;
  170163. INT32 z1, z2, z3, z4, z5;
  170164. JCOEFPTR inptr;
  170165. ISLOW_MULT_TYPE * quantptr;
  170166. int * wsptr;
  170167. JSAMPROW outptr;
  170168. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170169. int ctr;
  170170. int workspace[DCTSIZE2]; /* buffers data between passes */
  170171. SHIFT_TEMPS
  170172. /* Pass 1: process columns from input, store into work array. */
  170173. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  170174. /* furthermore, we scale the results by 2**PASS1_BITS. */
  170175. inptr = coef_block;
  170176. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  170177. wsptr = workspace;
  170178. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  170179. /* Due to quantization, we will usually find that many of the input
  170180. * coefficients are zero, especially the AC terms. We can exploit this
  170181. * by short-circuiting the IDCT calculation for any column in which all
  170182. * the AC terms are zero. In that case each output is equal to the
  170183. * DC coefficient (with scale factor as needed).
  170184. * With typical images and quantization tables, half or more of the
  170185. * column DCT calculations can be simplified this way.
  170186. */
  170187. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170188. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  170189. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  170190. inptr[DCTSIZE*7] == 0) {
  170191. /* AC terms all zero */
  170192. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  170193. wsptr[DCTSIZE*0] = dcval;
  170194. wsptr[DCTSIZE*1] = dcval;
  170195. wsptr[DCTSIZE*2] = dcval;
  170196. wsptr[DCTSIZE*3] = dcval;
  170197. wsptr[DCTSIZE*4] = dcval;
  170198. wsptr[DCTSIZE*5] = dcval;
  170199. wsptr[DCTSIZE*6] = dcval;
  170200. wsptr[DCTSIZE*7] = dcval;
  170201. inptr++; /* advance pointers to next column */
  170202. quantptr++;
  170203. wsptr++;
  170204. continue;
  170205. }
  170206. /* Even part: reverse the even part of the forward DCT. */
  170207. /* The rotator is sqrt(2)*c(-6). */
  170208. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170209. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170210. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  170211. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  170212. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  170213. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170214. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  170215. tmp0 = (z2 + z3) << CONST_BITS;
  170216. tmp1 = (z2 - z3) << CONST_BITS;
  170217. tmp10 = tmp0 + tmp3;
  170218. tmp13 = tmp0 - tmp3;
  170219. tmp11 = tmp1 + tmp2;
  170220. tmp12 = tmp1 - tmp2;
  170221. /* Odd part per figure 8; the matrix is unitary and hence its
  170222. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  170223. */
  170224. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170225. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170226. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170227. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170228. z1 = tmp0 + tmp3;
  170229. z2 = tmp1 + tmp2;
  170230. z3 = tmp0 + tmp2;
  170231. z4 = tmp1 + tmp3;
  170232. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170233. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170234. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170235. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170236. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170237. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170238. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170239. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170240. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170241. z3 += z5;
  170242. z4 += z5;
  170243. tmp0 += z1 + z3;
  170244. tmp1 += z2 + z4;
  170245. tmp2 += z2 + z3;
  170246. tmp3 += z1 + z4;
  170247. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  170248. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  170249. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  170250. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  170251. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  170252. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  170253. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  170254. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  170255. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  170256. inptr++; /* advance pointers to next column */
  170257. quantptr++;
  170258. wsptr++;
  170259. }
  170260. /* Pass 2: process rows from work array, store into output array. */
  170261. /* Note that we must descale the results by a factor of 8 == 2**3, */
  170262. /* and also undo the PASS1_BITS scaling. */
  170263. wsptr = workspace;
  170264. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  170265. outptr = output_buf[ctr] + output_col;
  170266. /* Rows of zeroes can be exploited in the same way as we did with columns.
  170267. * However, the column calculation has created many nonzero AC terms, so
  170268. * the simplification applies less often (typically 5% to 10% of the time).
  170269. * On machines with very fast multiplication, it's possible that the
  170270. * test takes more time than it's worth. In that case this section
  170271. * may be commented out.
  170272. */
  170273. #ifndef NO_ZERO_ROW_TEST
  170274. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  170275. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  170276. /* AC terms all zero */
  170277. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  170278. & RANGE_MASK];
  170279. outptr[0] = dcval;
  170280. outptr[1] = dcval;
  170281. outptr[2] = dcval;
  170282. outptr[3] = dcval;
  170283. outptr[4] = dcval;
  170284. outptr[5] = dcval;
  170285. outptr[6] = dcval;
  170286. outptr[7] = dcval;
  170287. wsptr += DCTSIZE; /* advance pointer to next row */
  170288. continue;
  170289. }
  170290. #endif
  170291. /* Even part: reverse the even part of the forward DCT. */
  170292. /* The rotator is sqrt(2)*c(-6). */
  170293. z2 = (INT32) wsptr[2];
  170294. z3 = (INT32) wsptr[6];
  170295. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  170296. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  170297. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  170298. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  170299. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  170300. tmp10 = tmp0 + tmp3;
  170301. tmp13 = tmp0 - tmp3;
  170302. tmp11 = tmp1 + tmp2;
  170303. tmp12 = tmp1 - tmp2;
  170304. /* Odd part per figure 8; the matrix is unitary and hence its
  170305. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  170306. */
  170307. tmp0 = (INT32) wsptr[7];
  170308. tmp1 = (INT32) wsptr[5];
  170309. tmp2 = (INT32) wsptr[3];
  170310. tmp3 = (INT32) wsptr[1];
  170311. z1 = tmp0 + tmp3;
  170312. z2 = tmp1 + tmp2;
  170313. z3 = tmp0 + tmp2;
  170314. z4 = tmp1 + tmp3;
  170315. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170316. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170317. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170318. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170319. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170320. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170321. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170322. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170323. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170324. z3 += z5;
  170325. z4 += z5;
  170326. tmp0 += z1 + z3;
  170327. tmp1 += z2 + z4;
  170328. tmp2 += z2 + z3;
  170329. tmp3 += z1 + z4;
  170330. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  170331. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  170332. CONST_BITS+PASS1_BITS+3)
  170333. & RANGE_MASK];
  170334. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  170335. CONST_BITS+PASS1_BITS+3)
  170336. & RANGE_MASK];
  170337. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  170338. CONST_BITS+PASS1_BITS+3)
  170339. & RANGE_MASK];
  170340. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  170341. CONST_BITS+PASS1_BITS+3)
  170342. & RANGE_MASK];
  170343. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  170344. CONST_BITS+PASS1_BITS+3)
  170345. & RANGE_MASK];
  170346. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  170347. CONST_BITS+PASS1_BITS+3)
  170348. & RANGE_MASK];
  170349. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  170350. CONST_BITS+PASS1_BITS+3)
  170351. & RANGE_MASK];
  170352. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  170353. CONST_BITS+PASS1_BITS+3)
  170354. & RANGE_MASK];
  170355. wsptr += DCTSIZE; /* advance pointer to next row */
  170356. }
  170357. }
  170358. #endif /* DCT_ISLOW_SUPPORTED */
  170359. /********* End of inlined file: jidctint.c *********/
  170360. /********* Start of inlined file: jidctred.c *********/
  170361. #define JPEG_INTERNALS
  170362. #ifdef IDCT_SCALING_SUPPORTED
  170363. /*
  170364. * This module is specialized to the case DCTSIZE = 8.
  170365. */
  170366. #if DCTSIZE != 8
  170367. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170368. #endif
  170369. /* Scaling is the same as in jidctint.c. */
  170370. #if BITS_IN_JSAMPLE == 8
  170371. #define CONST_BITS 13
  170372. #define PASS1_BITS 2
  170373. #else
  170374. #define CONST_BITS 13
  170375. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170376. #endif
  170377. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170378. * causing a lot of useless floating-point operations at run time.
  170379. * To get around this we use the following pre-calculated constants.
  170380. * If you change CONST_BITS you may want to add appropriate values.
  170381. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170382. */
  170383. #if CONST_BITS == 13
  170384. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  170385. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  170386. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  170387. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  170388. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  170389. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  170390. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  170391. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  170392. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  170393. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  170394. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  170395. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  170396. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  170397. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  170398. #else
  170399. #define FIX_0_211164243 FIX(0.211164243)
  170400. #define FIX_0_509795579 FIX(0.509795579)
  170401. #define FIX_0_601344887 FIX(0.601344887)
  170402. #define FIX_0_720959822 FIX(0.720959822)
  170403. #define FIX_0_765366865 FIX(0.765366865)
  170404. #define FIX_0_850430095 FIX(0.850430095)
  170405. #define FIX_0_899976223 FIX(0.899976223)
  170406. #define FIX_1_061594337 FIX(1.061594337)
  170407. #define FIX_1_272758580 FIX(1.272758580)
  170408. #define FIX_1_451774981 FIX(1.451774981)
  170409. #define FIX_1_847759065 FIX(1.847759065)
  170410. #define FIX_2_172734803 FIX(2.172734803)
  170411. #define FIX_2_562915447 FIX(2.562915447)
  170412. #define FIX_3_624509785 FIX(3.624509785)
  170413. #endif
  170414. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  170415. * For 8-bit samples with the recommended scaling, all the variable
  170416. * and constant values involved are no more than 16 bits wide, so a
  170417. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  170418. * For 12-bit samples, a full 32-bit multiplication will be needed.
  170419. */
  170420. #if BITS_IN_JSAMPLE == 8
  170421. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  170422. #else
  170423. #define MULTIPLY(var,const) ((var) * (const))
  170424. #endif
  170425. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170426. * entry; produce an int result. In this module, both inputs and result
  170427. * are 16 bits or less, so either int or short multiply will work.
  170428. */
  170429. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  170430. /*
  170431. * Perform dequantization and inverse DCT on one block of coefficients,
  170432. * producing a reduced-size 4x4 output block.
  170433. */
  170434. GLOBAL(void)
  170435. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170436. JCOEFPTR coef_block,
  170437. JSAMPARRAY output_buf, JDIMENSION output_col)
  170438. {
  170439. INT32 tmp0, tmp2, tmp10, tmp12;
  170440. INT32 z1, z2, z3, z4;
  170441. JCOEFPTR inptr;
  170442. ISLOW_MULT_TYPE * quantptr;
  170443. int * wsptr;
  170444. JSAMPROW outptr;
  170445. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170446. int ctr;
  170447. int workspace[DCTSIZE*4]; /* buffers data between passes */
  170448. SHIFT_TEMPS
  170449. /* Pass 1: process columns from input, store into work array. */
  170450. inptr = coef_block;
  170451. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  170452. wsptr = workspace;
  170453. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  170454. /* Don't bother to process column 4, because second pass won't use it */
  170455. if (ctr == DCTSIZE-4)
  170456. continue;
  170457. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170458. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  170459. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  170460. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  170461. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  170462. wsptr[DCTSIZE*0] = dcval;
  170463. wsptr[DCTSIZE*1] = dcval;
  170464. wsptr[DCTSIZE*2] = dcval;
  170465. wsptr[DCTSIZE*3] = dcval;
  170466. continue;
  170467. }
  170468. /* Even part */
  170469. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170470. tmp0 <<= (CONST_BITS+1);
  170471. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170472. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170473. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  170474. tmp10 = tmp0 + tmp2;
  170475. tmp12 = tmp0 - tmp2;
  170476. /* Odd part */
  170477. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170478. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170479. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170480. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170481. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  170482. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  170483. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  170484. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  170485. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  170486. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  170487. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  170488. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  170489. /* Final output stage */
  170490. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  170491. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  170492. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  170493. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  170494. }
  170495. /* Pass 2: process 4 rows from work array, store into output array. */
  170496. wsptr = workspace;
  170497. for (ctr = 0; ctr < 4; ctr++) {
  170498. outptr = output_buf[ctr] + output_col;
  170499. /* It's not clear whether a zero row test is worthwhile here ... */
  170500. #ifndef NO_ZERO_ROW_TEST
  170501. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  170502. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  170503. /* AC terms all zero */
  170504. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  170505. & RANGE_MASK];
  170506. outptr[0] = dcval;
  170507. outptr[1] = dcval;
  170508. outptr[2] = dcval;
  170509. outptr[3] = dcval;
  170510. wsptr += DCTSIZE; /* advance pointer to next row */
  170511. continue;
  170512. }
  170513. #endif
  170514. /* Even part */
  170515. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  170516. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  170517. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  170518. tmp10 = tmp0 + tmp2;
  170519. tmp12 = tmp0 - tmp2;
  170520. /* Odd part */
  170521. z1 = (INT32) wsptr[7];
  170522. z2 = (INT32) wsptr[5];
  170523. z3 = (INT32) wsptr[3];
  170524. z4 = (INT32) wsptr[1];
  170525. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  170526. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  170527. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  170528. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  170529. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  170530. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  170531. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  170532. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  170533. /* Final output stage */
  170534. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  170535. CONST_BITS+PASS1_BITS+3+1)
  170536. & RANGE_MASK];
  170537. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  170538. CONST_BITS+PASS1_BITS+3+1)
  170539. & RANGE_MASK];
  170540. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  170541. CONST_BITS+PASS1_BITS+3+1)
  170542. & RANGE_MASK];
  170543. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  170544. CONST_BITS+PASS1_BITS+3+1)
  170545. & RANGE_MASK];
  170546. wsptr += DCTSIZE; /* advance pointer to next row */
  170547. }
  170548. }
  170549. /*
  170550. * Perform dequantization and inverse DCT on one block of coefficients,
  170551. * producing a reduced-size 2x2 output block.
  170552. */
  170553. GLOBAL(void)
  170554. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170555. JCOEFPTR coef_block,
  170556. JSAMPARRAY output_buf, JDIMENSION output_col)
  170557. {
  170558. INT32 tmp0, tmp10, z1;
  170559. JCOEFPTR inptr;
  170560. ISLOW_MULT_TYPE * quantptr;
  170561. int * wsptr;
  170562. JSAMPROW outptr;
  170563. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170564. int ctr;
  170565. int workspace[DCTSIZE*2]; /* buffers data between passes */
  170566. SHIFT_TEMPS
  170567. /* Pass 1: process columns from input, store into work array. */
  170568. inptr = coef_block;
  170569. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  170570. wsptr = workspace;
  170571. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  170572. /* Don't bother to process columns 2,4,6 */
  170573. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  170574. continue;
  170575. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  170576. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  170577. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  170578. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  170579. wsptr[DCTSIZE*0] = dcval;
  170580. wsptr[DCTSIZE*1] = dcval;
  170581. continue;
  170582. }
  170583. /* Even part */
  170584. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170585. tmp10 = z1 << (CONST_BITS+2);
  170586. /* Odd part */
  170587. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170588. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  170589. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170590. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  170591. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170592. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  170593. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170594. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  170595. /* Final output stage */
  170596. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  170597. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  170598. }
  170599. /* Pass 2: process 2 rows from work array, store into output array. */
  170600. wsptr = workspace;
  170601. for (ctr = 0; ctr < 2; ctr++) {
  170602. outptr = output_buf[ctr] + output_col;
  170603. /* It's not clear whether a zero row test is worthwhile here ... */
  170604. #ifndef NO_ZERO_ROW_TEST
  170605. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  170606. /* AC terms all zero */
  170607. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  170608. & RANGE_MASK];
  170609. outptr[0] = dcval;
  170610. outptr[1] = dcval;
  170611. wsptr += DCTSIZE; /* advance pointer to next row */
  170612. continue;
  170613. }
  170614. #endif
  170615. /* Even part */
  170616. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  170617. /* Odd part */
  170618. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  170619. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  170620. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  170621. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  170622. /* Final output stage */
  170623. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  170624. CONST_BITS+PASS1_BITS+3+2)
  170625. & RANGE_MASK];
  170626. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  170627. CONST_BITS+PASS1_BITS+3+2)
  170628. & RANGE_MASK];
  170629. wsptr += DCTSIZE; /* advance pointer to next row */
  170630. }
  170631. }
  170632. /*
  170633. * Perform dequantization and inverse DCT on one block of coefficients,
  170634. * producing a reduced-size 1x1 output block.
  170635. */
  170636. GLOBAL(void)
  170637. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170638. JCOEFPTR coef_block,
  170639. JSAMPARRAY output_buf, JDIMENSION output_col)
  170640. {
  170641. int dcval;
  170642. ISLOW_MULT_TYPE * quantptr;
  170643. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170644. SHIFT_TEMPS
  170645. /* We hardly need an inverse DCT routine for this: just take the
  170646. * average pixel value, which is one-eighth of the DC coefficient.
  170647. */
  170648. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  170649. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  170650. dcval = (int) DESCALE((INT32) dcval, 3);
  170651. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  170652. }
  170653. #endif /* IDCT_SCALING_SUPPORTED */
  170654. /********* End of inlined file: jidctred.c *********/
  170655. /********* Start of inlined file: jmemmgr.c *********/
  170656. #define JPEG_INTERNALS
  170657. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  170658. /********* Start of inlined file: jmemsys.h *********/
  170659. #ifndef __jmemsys_h__
  170660. #define __jmemsys_h__
  170661. /* Short forms of external names for systems with brain-damaged linkers. */
  170662. #ifdef NEED_SHORT_EXTERNAL_NAMES
  170663. #define jpeg_get_small jGetSmall
  170664. #define jpeg_free_small jFreeSmall
  170665. #define jpeg_get_large jGetLarge
  170666. #define jpeg_free_large jFreeLarge
  170667. #define jpeg_mem_available jMemAvail
  170668. #define jpeg_open_backing_store jOpenBackStore
  170669. #define jpeg_mem_init jMemInit
  170670. #define jpeg_mem_term jMemTerm
  170671. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  170672. /*
  170673. * These two functions are used to allocate and release small chunks of
  170674. * memory. (Typically the total amount requested through jpeg_get_small is
  170675. * no more than 20K or so; this will be requested in chunks of a few K each.)
  170676. * Behavior should be the same as for the standard library functions malloc
  170677. * and free; in particular, jpeg_get_small must return NULL on failure.
  170678. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  170679. * size of the object being freed, just in case it's needed.
  170680. * On an 80x86 machine using small-data memory model, these manage near heap.
  170681. */
  170682. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  170683. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  170684. size_t sizeofobject));
  170685. /*
  170686. * These two functions are used to allocate and release large chunks of
  170687. * memory (up to the total free space designated by jpeg_mem_available).
  170688. * The interface is the same as above, except that on an 80x86 machine,
  170689. * far pointers are used. On most other machines these are identical to
  170690. * the jpeg_get/free_small routines; but we keep them separate anyway,
  170691. * in case a different allocation strategy is desirable for large chunks.
  170692. */
  170693. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  170694. size_t sizeofobject));
  170695. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  170696. size_t sizeofobject));
  170697. /*
  170698. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  170699. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  170700. * matter, but that case should never come into play). This macro is needed
  170701. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  170702. * On those machines, we expect that jconfig.h will provide a proper value.
  170703. * On machines with 32-bit flat address spaces, any large constant may be used.
  170704. *
  170705. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  170706. * size_t and will be a multiple of sizeof(align_type).
  170707. */
  170708. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  170709. #define MAX_ALLOC_CHUNK 1000000000L
  170710. #endif
  170711. /*
  170712. * This routine computes the total space still available for allocation by
  170713. * jpeg_get_large. If more space than this is needed, backing store will be
  170714. * used. NOTE: any memory already allocated must not be counted.
  170715. *
  170716. * There is a minimum space requirement, corresponding to the minimum
  170717. * feasible buffer sizes; jmemmgr.c will request that much space even if
  170718. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  170719. * all working storage in memory, is also passed in case it is useful.
  170720. * Finally, the total space already allocated is passed. If no better
  170721. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  170722. * is often a suitable calculation.
  170723. *
  170724. * It is OK for jpeg_mem_available to underestimate the space available
  170725. * (that'll just lead to more backing-store access than is really necessary).
  170726. * However, an overestimate will lead to failure. Hence it's wise to subtract
  170727. * a slop factor from the true available space. 5% should be enough.
  170728. *
  170729. * On machines with lots of virtual memory, any large constant may be returned.
  170730. * Conversely, zero may be returned to always use the minimum amount of memory.
  170731. */
  170732. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  170733. long min_bytes_needed,
  170734. long max_bytes_needed,
  170735. long already_allocated));
  170736. /*
  170737. * This structure holds whatever state is needed to access a single
  170738. * backing-store object. The read/write/close method pointers are called
  170739. * by jmemmgr.c to manipulate the backing-store object; all other fields
  170740. * are private to the system-dependent backing store routines.
  170741. */
  170742. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  170743. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  170744. typedef unsigned short XMSH; /* type of extended-memory handles */
  170745. typedef unsigned short EMSH; /* type of expanded-memory handles */
  170746. typedef union {
  170747. short file_handle; /* DOS file handle if it's a temp file */
  170748. XMSH xms_handle; /* handle if it's a chunk of XMS */
  170749. EMSH ems_handle; /* handle if it's a chunk of EMS */
  170750. } handle_union;
  170751. #endif /* USE_MSDOS_MEMMGR */
  170752. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  170753. #include <Files.h>
  170754. #endif /* USE_MAC_MEMMGR */
  170755. //typedef struct backing_store_struct * backing_store_ptr;
  170756. typedef struct backing_store_struct {
  170757. /* Methods for reading/writing/closing this backing-store object */
  170758. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  170759. struct backing_store_struct *info,
  170760. void FAR * buffer_address,
  170761. long file_offset, long byte_count));
  170762. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  170763. struct backing_store_struct *info,
  170764. void FAR * buffer_address,
  170765. long file_offset, long byte_count));
  170766. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  170767. struct backing_store_struct *info));
  170768. /* Private fields for system-dependent backing-store management */
  170769. #ifdef USE_MSDOS_MEMMGR
  170770. /* For the MS-DOS manager (jmemdos.c), we need: */
  170771. handle_union handle; /* reference to backing-store storage object */
  170772. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  170773. #else
  170774. #ifdef USE_MAC_MEMMGR
  170775. /* For the Mac manager (jmemmac.c), we need: */
  170776. short temp_file; /* file reference number to temp file */
  170777. FSSpec tempSpec; /* the FSSpec for the temp file */
  170778. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  170779. #else
  170780. /* For a typical implementation with temp files, we need: */
  170781. FILE * temp_file; /* stdio reference to temp file */
  170782. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  170783. #endif
  170784. #endif
  170785. } backing_store_info;
  170786. /*
  170787. * Initial opening of a backing-store object. This must fill in the
  170788. * read/write/close pointers in the object. The read/write routines
  170789. * may take an error exit if the specified maximum file size is exceeded.
  170790. * (If jpeg_mem_available always returns a large value, this routine can
  170791. * just take an error exit.)
  170792. */
  170793. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  170794. struct backing_store_struct *info,
  170795. long total_bytes_needed));
  170796. /*
  170797. * These routines take care of any system-dependent initialization and
  170798. * cleanup required. jpeg_mem_init will be called before anything is
  170799. * allocated (and, therefore, nothing in cinfo is of use except the error
  170800. * manager pointer). It should return a suitable default value for
  170801. * max_memory_to_use; this may subsequently be overridden by the surrounding
  170802. * application. (Note that max_memory_to_use is only important if
  170803. * jpeg_mem_available chooses to consult it ... no one else will.)
  170804. * jpeg_mem_term may assume that all requested memory has been freed and that
  170805. * all opened backing-store objects have been closed.
  170806. */
  170807. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  170808. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  170809. #endif
  170810. /********* End of inlined file: jmemsys.h *********/
  170811. /* import the system-dependent declarations */
  170812. #ifndef NO_GETENV
  170813. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  170814. extern char * getenv JPP((const char * name));
  170815. #endif
  170816. #endif
  170817. /*
  170818. * Some important notes:
  170819. * The allocation routines provided here must never return NULL.
  170820. * They should exit to error_exit if unsuccessful.
  170821. *
  170822. * It's not a good idea to try to merge the sarray and barray routines,
  170823. * even though they are textually almost the same, because samples are
  170824. * usually stored as bytes while coefficients are shorts or ints. Thus,
  170825. * in machines where byte pointers have a different representation from
  170826. * word pointers, the resulting machine code could not be the same.
  170827. */
  170828. /*
  170829. * Many machines require storage alignment: longs must start on 4-byte
  170830. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  170831. * always returns pointers that are multiples of the worst-case alignment
  170832. * requirement, and we had better do so too.
  170833. * There isn't any really portable way to determine the worst-case alignment
  170834. * requirement. This module assumes that the alignment requirement is
  170835. * multiples of sizeof(ALIGN_TYPE).
  170836. * By default, we define ALIGN_TYPE as double. This is necessary on some
  170837. * workstations (where doubles really do need 8-byte alignment) and will work
  170838. * fine on nearly everything. If your machine has lesser alignment needs,
  170839. * you can save a few bytes by making ALIGN_TYPE smaller.
  170840. * The only place I know of where this will NOT work is certain Macintosh
  170841. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  170842. * Doing 10-byte alignment is counterproductive because longwords won't be
  170843. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  170844. * such a compiler.
  170845. */
  170846. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  170847. #define ALIGN_TYPE double
  170848. #endif
  170849. /*
  170850. * We allocate objects from "pools", where each pool is gotten with a single
  170851. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  170852. * overhead within a pool, except for alignment padding. Each pool has a
  170853. * header with a link to the next pool of the same class.
  170854. * Small and large pool headers are identical except that the latter's
  170855. * link pointer must be FAR on 80x86 machines.
  170856. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  170857. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  170858. * of the alignment requirement of ALIGN_TYPE.
  170859. */
  170860. typedef union small_pool_struct * small_pool_ptr;
  170861. typedef union small_pool_struct {
  170862. struct {
  170863. small_pool_ptr next; /* next in list of pools */
  170864. size_t bytes_used; /* how many bytes already used within pool */
  170865. size_t bytes_left; /* bytes still available in this pool */
  170866. } hdr;
  170867. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  170868. } small_pool_hdr;
  170869. typedef union large_pool_struct FAR * large_pool_ptr;
  170870. typedef union large_pool_struct {
  170871. struct {
  170872. large_pool_ptr next; /* next in list of pools */
  170873. size_t bytes_used; /* how many bytes already used within pool */
  170874. size_t bytes_left; /* bytes still available in this pool */
  170875. } hdr;
  170876. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  170877. } large_pool_hdr;
  170878. /*
  170879. * Here is the full definition of a memory manager object.
  170880. */
  170881. typedef struct {
  170882. struct jpeg_memory_mgr pub; /* public fields */
  170883. /* Each pool identifier (lifetime class) names a linked list of pools. */
  170884. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  170885. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  170886. /* Since we only have one lifetime class of virtual arrays, only one
  170887. * linked list is necessary (for each datatype). Note that the virtual
  170888. * array control blocks being linked together are actually stored somewhere
  170889. * in the small-pool list.
  170890. */
  170891. jvirt_sarray_ptr virt_sarray_list;
  170892. jvirt_barray_ptr virt_barray_list;
  170893. /* This counts total space obtained from jpeg_get_small/large */
  170894. long total_space_allocated;
  170895. /* alloc_sarray and alloc_barray set this value for use by virtual
  170896. * array routines.
  170897. */
  170898. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  170899. } my_memory_mgr;
  170900. typedef my_memory_mgr * my_mem_ptr;
  170901. /*
  170902. * The control blocks for virtual arrays.
  170903. * Note that these blocks are allocated in the "small" pool area.
  170904. * System-dependent info for the associated backing store (if any) is hidden
  170905. * inside the backing_store_info struct.
  170906. */
  170907. struct jvirt_sarray_control {
  170908. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  170909. JDIMENSION rows_in_array; /* total virtual array height */
  170910. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  170911. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  170912. JDIMENSION rows_in_mem; /* height of memory buffer */
  170913. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  170914. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  170915. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  170916. boolean pre_zero; /* pre-zero mode requested? */
  170917. boolean dirty; /* do current buffer contents need written? */
  170918. boolean b_s_open; /* is backing-store data valid? */
  170919. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  170920. backing_store_info b_s_info; /* System-dependent control info */
  170921. };
  170922. struct jvirt_barray_control {
  170923. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  170924. JDIMENSION rows_in_array; /* total virtual array height */
  170925. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  170926. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  170927. JDIMENSION rows_in_mem; /* height of memory buffer */
  170928. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  170929. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  170930. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  170931. boolean pre_zero; /* pre-zero mode requested? */
  170932. boolean dirty; /* do current buffer contents need written? */
  170933. boolean b_s_open; /* is backing-store data valid? */
  170934. jvirt_barray_ptr next; /* link to next virtual barray control block */
  170935. backing_store_info b_s_info; /* System-dependent control info */
  170936. };
  170937. #ifdef MEM_STATS /* optional extra stuff for statistics */
  170938. LOCAL(void)
  170939. print_mem_stats (j_common_ptr cinfo, int pool_id)
  170940. {
  170941. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170942. small_pool_ptr shdr_ptr;
  170943. large_pool_ptr lhdr_ptr;
  170944. /* Since this is only a debugging stub, we can cheat a little by using
  170945. * fprintf directly rather than going through the trace message code.
  170946. * This is helpful because message parm array can't handle longs.
  170947. */
  170948. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  170949. pool_id, mem->total_space_allocated);
  170950. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  170951. lhdr_ptr = lhdr_ptr->hdr.next) {
  170952. fprintf(stderr, " Large chunk used %ld\n",
  170953. (long) lhdr_ptr->hdr.bytes_used);
  170954. }
  170955. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  170956. shdr_ptr = shdr_ptr->hdr.next) {
  170957. fprintf(stderr, " Small chunk used %ld free %ld\n",
  170958. (long) shdr_ptr->hdr.bytes_used,
  170959. (long) shdr_ptr->hdr.bytes_left);
  170960. }
  170961. }
  170962. #endif /* MEM_STATS */
  170963. LOCAL(void)
  170964. out_of_memory (j_common_ptr cinfo, int which)
  170965. /* Report an out-of-memory error and stop execution */
  170966. /* If we compiled MEM_STATS support, report alloc requests before dying */
  170967. {
  170968. #ifdef MEM_STATS
  170969. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  170970. #endif
  170971. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  170972. }
  170973. /*
  170974. * Allocation of "small" objects.
  170975. *
  170976. * For these, we use pooled storage. When a new pool must be created,
  170977. * we try to get enough space for the current request plus a "slop" factor,
  170978. * where the slop will be the amount of leftover space in the new pool.
  170979. * The speed vs. space tradeoff is largely determined by the slop values.
  170980. * A different slop value is provided for each pool class (lifetime),
  170981. * and we also distinguish the first pool of a class from later ones.
  170982. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  170983. * machines, but may be too small if longs are 64 bits or more.
  170984. */
  170985. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  170986. {
  170987. 1600, /* first PERMANENT pool */
  170988. 16000 /* first IMAGE pool */
  170989. };
  170990. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  170991. {
  170992. 0, /* additional PERMANENT pools */
  170993. 5000 /* additional IMAGE pools */
  170994. };
  170995. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  170996. METHODDEF(void *)
  170997. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  170998. /* Allocate a "small" object */
  170999. {
  171000. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171001. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  171002. char * data_ptr;
  171003. size_t odd_bytes, min_request, slop;
  171004. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  171005. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  171006. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  171007. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  171008. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  171009. if (odd_bytes > 0)
  171010. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  171011. /* See if space is available in any existing pool */
  171012. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  171013. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171014. prev_hdr_ptr = NULL;
  171015. hdr_ptr = mem->small_list[pool_id];
  171016. while (hdr_ptr != NULL) {
  171017. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  171018. break; /* found pool with enough space */
  171019. prev_hdr_ptr = hdr_ptr;
  171020. hdr_ptr = hdr_ptr->hdr.next;
  171021. }
  171022. /* Time to make a new pool? */
  171023. if (hdr_ptr == NULL) {
  171024. /* min_request is what we need now, slop is what will be leftover */
  171025. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  171026. if (prev_hdr_ptr == NULL) /* first pool in class? */
  171027. slop = first_pool_slop[pool_id];
  171028. else
  171029. slop = extra_pool_slop[pool_id];
  171030. /* Don't ask for more than MAX_ALLOC_CHUNK */
  171031. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  171032. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  171033. /* Try to get space, if fail reduce slop and try again */
  171034. for (;;) {
  171035. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  171036. if (hdr_ptr != NULL)
  171037. break;
  171038. slop /= 2;
  171039. if (slop < MIN_SLOP) /* give up when it gets real small */
  171040. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  171041. }
  171042. mem->total_space_allocated += min_request + slop;
  171043. /* Success, initialize the new pool header and add to end of list */
  171044. hdr_ptr->hdr.next = NULL;
  171045. hdr_ptr->hdr.bytes_used = 0;
  171046. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  171047. if (prev_hdr_ptr == NULL) /* first pool in class? */
  171048. mem->small_list[pool_id] = hdr_ptr;
  171049. else
  171050. prev_hdr_ptr->hdr.next = hdr_ptr;
  171051. }
  171052. /* OK, allocate the object from the current pool */
  171053. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  171054. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  171055. hdr_ptr->hdr.bytes_used += sizeofobject;
  171056. hdr_ptr->hdr.bytes_left -= sizeofobject;
  171057. return (void *) data_ptr;
  171058. }
  171059. /*
  171060. * Allocation of "large" objects.
  171061. *
  171062. * The external semantics of these are the same as "small" objects,
  171063. * except that FAR pointers are used on 80x86. However the pool
  171064. * management heuristics are quite different. We assume that each
  171065. * request is large enough that it may as well be passed directly to
  171066. * jpeg_get_large; the pool management just links everything together
  171067. * so that we can free it all on demand.
  171068. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  171069. * structures. The routines that create these structures (see below)
  171070. * deliberately bunch rows together to ensure a large request size.
  171071. */
  171072. METHODDEF(void FAR *)
  171073. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  171074. /* Allocate a "large" object */
  171075. {
  171076. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171077. large_pool_ptr hdr_ptr;
  171078. size_t odd_bytes;
  171079. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  171080. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  171081. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  171082. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  171083. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  171084. if (odd_bytes > 0)
  171085. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  171086. /* Always make a new pool */
  171087. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  171088. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171089. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  171090. SIZEOF(large_pool_hdr));
  171091. if (hdr_ptr == NULL)
  171092. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  171093. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  171094. /* Success, initialize the new pool header and add to list */
  171095. hdr_ptr->hdr.next = mem->large_list[pool_id];
  171096. /* We maintain space counts in each pool header for statistical purposes,
  171097. * even though they are not needed for allocation.
  171098. */
  171099. hdr_ptr->hdr.bytes_used = sizeofobject;
  171100. hdr_ptr->hdr.bytes_left = 0;
  171101. mem->large_list[pool_id] = hdr_ptr;
  171102. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  171103. }
  171104. /*
  171105. * Creation of 2-D sample arrays.
  171106. * The pointers are in near heap, the samples themselves in FAR heap.
  171107. *
  171108. * To minimize allocation overhead and to allow I/O of large contiguous
  171109. * blocks, we allocate the sample rows in groups of as many rows as possible
  171110. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  171111. * NB: the virtual array control routines, later in this file, know about
  171112. * this chunking of rows. The rowsperchunk value is left in the mem manager
  171113. * object so that it can be saved away if this sarray is the workspace for
  171114. * a virtual array.
  171115. */
  171116. METHODDEF(JSAMPARRAY)
  171117. alloc_sarray (j_common_ptr cinfo, int pool_id,
  171118. JDIMENSION samplesperrow, JDIMENSION numrows)
  171119. /* Allocate a 2-D sample array */
  171120. {
  171121. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171122. JSAMPARRAY result;
  171123. JSAMPROW workspace;
  171124. JDIMENSION rowsperchunk, currow, i;
  171125. long ltemp;
  171126. /* Calculate max # of rows allowed in one allocation chunk */
  171127. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  171128. ((long) samplesperrow * SIZEOF(JSAMPLE));
  171129. if (ltemp <= 0)
  171130. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171131. if (ltemp < (long) numrows)
  171132. rowsperchunk = (JDIMENSION) ltemp;
  171133. else
  171134. rowsperchunk = numrows;
  171135. mem->last_rowsperchunk = rowsperchunk;
  171136. /* Get space for row pointers (small object) */
  171137. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  171138. (size_t) (numrows * SIZEOF(JSAMPROW)));
  171139. /* Get the rows themselves (large objects) */
  171140. currow = 0;
  171141. while (currow < numrows) {
  171142. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  171143. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  171144. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  171145. * SIZEOF(JSAMPLE)));
  171146. for (i = rowsperchunk; i > 0; i--) {
  171147. result[currow++] = workspace;
  171148. workspace += samplesperrow;
  171149. }
  171150. }
  171151. return result;
  171152. }
  171153. /*
  171154. * Creation of 2-D coefficient-block arrays.
  171155. * This is essentially the same as the code for sample arrays, above.
  171156. */
  171157. METHODDEF(JBLOCKARRAY)
  171158. alloc_barray (j_common_ptr cinfo, int pool_id,
  171159. JDIMENSION blocksperrow, JDIMENSION numrows)
  171160. /* Allocate a 2-D coefficient-block array */
  171161. {
  171162. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171163. JBLOCKARRAY result;
  171164. JBLOCKROW workspace;
  171165. JDIMENSION rowsperchunk, currow, i;
  171166. long ltemp;
  171167. /* Calculate max # of rows allowed in one allocation chunk */
  171168. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  171169. ((long) blocksperrow * SIZEOF(JBLOCK));
  171170. if (ltemp <= 0)
  171171. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171172. if (ltemp < (long) numrows)
  171173. rowsperchunk = (JDIMENSION) ltemp;
  171174. else
  171175. rowsperchunk = numrows;
  171176. mem->last_rowsperchunk = rowsperchunk;
  171177. /* Get space for row pointers (small object) */
  171178. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  171179. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  171180. /* Get the rows themselves (large objects) */
  171181. currow = 0;
  171182. while (currow < numrows) {
  171183. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  171184. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  171185. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  171186. * SIZEOF(JBLOCK)));
  171187. for (i = rowsperchunk; i > 0; i--) {
  171188. result[currow++] = workspace;
  171189. workspace += blocksperrow;
  171190. }
  171191. }
  171192. return result;
  171193. }
  171194. /*
  171195. * About virtual array management:
  171196. *
  171197. * The above "normal" array routines are only used to allocate strip buffers
  171198. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  171199. * are handled as "virtual" arrays. The array is still accessed a strip at a
  171200. * time, but the memory manager must save the whole array for repeated
  171201. * accesses. The intended implementation is that there is a strip buffer in
  171202. * memory (as high as is possible given the desired memory limit), plus a
  171203. * backing file that holds the rest of the array.
  171204. *
  171205. * The request_virt_array routines are told the total size of the image and
  171206. * the maximum number of rows that will be accessed at once. The in-memory
  171207. * buffer must be at least as large as the maxaccess value.
  171208. *
  171209. * The request routines create control blocks but not the in-memory buffers.
  171210. * That is postponed until realize_virt_arrays is called. At that time the
  171211. * total amount of space needed is known (approximately, anyway), so free
  171212. * memory can be divided up fairly.
  171213. *
  171214. * The access_virt_array routines are responsible for making a specific strip
  171215. * area accessible (after reading or writing the backing file, if necessary).
  171216. * Note that the access routines are told whether the caller intends to modify
  171217. * the accessed strip; during a read-only pass this saves having to rewrite
  171218. * data to disk. The access routines are also responsible for pre-zeroing
  171219. * any newly accessed rows, if pre-zeroing was requested.
  171220. *
  171221. * In current usage, the access requests are usually for nonoverlapping
  171222. * strips; that is, successive access start_row numbers differ by exactly
  171223. * num_rows = maxaccess. This means we can get good performance with simple
  171224. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  171225. * of the access height; then there will never be accesses across bufferload
  171226. * boundaries. The code will still work with overlapping access requests,
  171227. * but it doesn't handle bufferload overlaps very efficiently.
  171228. */
  171229. METHODDEF(jvirt_sarray_ptr)
  171230. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  171231. JDIMENSION samplesperrow, JDIMENSION numrows,
  171232. JDIMENSION maxaccess)
  171233. /* Request a virtual 2-D sample array */
  171234. {
  171235. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171236. jvirt_sarray_ptr result;
  171237. /* Only IMAGE-lifetime virtual arrays are currently supported */
  171238. if (pool_id != JPOOL_IMAGE)
  171239. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171240. /* get control block */
  171241. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  171242. SIZEOF(struct jvirt_sarray_control));
  171243. result->mem_buffer = NULL; /* marks array not yet realized */
  171244. result->rows_in_array = numrows;
  171245. result->samplesperrow = samplesperrow;
  171246. result->maxaccess = maxaccess;
  171247. result->pre_zero = pre_zero;
  171248. result->b_s_open = FALSE; /* no associated backing-store object */
  171249. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  171250. mem->virt_sarray_list = result;
  171251. return result;
  171252. }
  171253. METHODDEF(jvirt_barray_ptr)
  171254. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  171255. JDIMENSION blocksperrow, JDIMENSION numrows,
  171256. JDIMENSION maxaccess)
  171257. /* Request a virtual 2-D coefficient-block array */
  171258. {
  171259. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171260. jvirt_barray_ptr result;
  171261. /* Only IMAGE-lifetime virtual arrays are currently supported */
  171262. if (pool_id != JPOOL_IMAGE)
  171263. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171264. /* get control block */
  171265. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  171266. SIZEOF(struct jvirt_barray_control));
  171267. result->mem_buffer = NULL; /* marks array not yet realized */
  171268. result->rows_in_array = numrows;
  171269. result->blocksperrow = blocksperrow;
  171270. result->maxaccess = maxaccess;
  171271. result->pre_zero = pre_zero;
  171272. result->b_s_open = FALSE; /* no associated backing-store object */
  171273. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  171274. mem->virt_barray_list = result;
  171275. return result;
  171276. }
  171277. METHODDEF(void)
  171278. realize_virt_arrays (j_common_ptr cinfo)
  171279. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  171280. {
  171281. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171282. long space_per_minheight, maximum_space, avail_mem;
  171283. long minheights, max_minheights;
  171284. jvirt_sarray_ptr sptr;
  171285. jvirt_barray_ptr bptr;
  171286. /* Compute the minimum space needed (maxaccess rows in each buffer)
  171287. * and the maximum space needed (full image height in each buffer).
  171288. * These may be of use to the system-dependent jpeg_mem_available routine.
  171289. */
  171290. space_per_minheight = 0;
  171291. maximum_space = 0;
  171292. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  171293. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  171294. space_per_minheight += (long) sptr->maxaccess *
  171295. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  171296. maximum_space += (long) sptr->rows_in_array *
  171297. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  171298. }
  171299. }
  171300. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  171301. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  171302. space_per_minheight += (long) bptr->maxaccess *
  171303. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  171304. maximum_space += (long) bptr->rows_in_array *
  171305. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  171306. }
  171307. }
  171308. if (space_per_minheight <= 0)
  171309. return; /* no unrealized arrays, no work */
  171310. /* Determine amount of memory to actually use; this is system-dependent. */
  171311. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  171312. mem->total_space_allocated);
  171313. /* If the maximum space needed is available, make all the buffers full
  171314. * height; otherwise parcel it out with the same number of minheights
  171315. * in each buffer.
  171316. */
  171317. if (avail_mem >= maximum_space)
  171318. max_minheights = 1000000000L;
  171319. else {
  171320. max_minheights = avail_mem / space_per_minheight;
  171321. /* If there doesn't seem to be enough space, try to get the minimum
  171322. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  171323. */
  171324. if (max_minheights <= 0)
  171325. max_minheights = 1;
  171326. }
  171327. /* Allocate the in-memory buffers and initialize backing store as needed. */
  171328. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  171329. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  171330. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  171331. if (minheights <= max_minheights) {
  171332. /* This buffer fits in memory */
  171333. sptr->rows_in_mem = sptr->rows_in_array;
  171334. } else {
  171335. /* It doesn't fit in memory, create backing store. */
  171336. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  171337. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  171338. (long) sptr->rows_in_array *
  171339. (long) sptr->samplesperrow *
  171340. (long) SIZEOF(JSAMPLE));
  171341. sptr->b_s_open = TRUE;
  171342. }
  171343. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  171344. sptr->samplesperrow, sptr->rows_in_mem);
  171345. sptr->rowsperchunk = mem->last_rowsperchunk;
  171346. sptr->cur_start_row = 0;
  171347. sptr->first_undef_row = 0;
  171348. sptr->dirty = FALSE;
  171349. }
  171350. }
  171351. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  171352. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  171353. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  171354. if (minheights <= max_minheights) {
  171355. /* This buffer fits in memory */
  171356. bptr->rows_in_mem = bptr->rows_in_array;
  171357. } else {
  171358. /* It doesn't fit in memory, create backing store. */
  171359. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  171360. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  171361. (long) bptr->rows_in_array *
  171362. (long) bptr->blocksperrow *
  171363. (long) SIZEOF(JBLOCK));
  171364. bptr->b_s_open = TRUE;
  171365. }
  171366. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  171367. bptr->blocksperrow, bptr->rows_in_mem);
  171368. bptr->rowsperchunk = mem->last_rowsperchunk;
  171369. bptr->cur_start_row = 0;
  171370. bptr->first_undef_row = 0;
  171371. bptr->dirty = FALSE;
  171372. }
  171373. }
  171374. }
  171375. LOCAL(void)
  171376. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  171377. /* Do backing store read or write of a virtual sample array */
  171378. {
  171379. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  171380. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  171381. file_offset = ptr->cur_start_row * bytesperrow;
  171382. /* Loop to read or write each allocation chunk in mem_buffer */
  171383. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  171384. /* One chunk, but check for short chunk at end of buffer */
  171385. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  171386. /* Transfer no more than is currently defined */
  171387. thisrow = (long) ptr->cur_start_row + i;
  171388. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  171389. /* Transfer no more than fits in file */
  171390. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  171391. if (rows <= 0) /* this chunk might be past end of file! */
  171392. break;
  171393. byte_count = rows * bytesperrow;
  171394. if (writing)
  171395. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  171396. (void FAR *) ptr->mem_buffer[i],
  171397. file_offset, byte_count);
  171398. else
  171399. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  171400. (void FAR *) ptr->mem_buffer[i],
  171401. file_offset, byte_count);
  171402. file_offset += byte_count;
  171403. }
  171404. }
  171405. LOCAL(void)
  171406. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  171407. /* Do backing store read or write of a virtual coefficient-block array */
  171408. {
  171409. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  171410. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  171411. file_offset = ptr->cur_start_row * bytesperrow;
  171412. /* Loop to read or write each allocation chunk in mem_buffer */
  171413. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  171414. /* One chunk, but check for short chunk at end of buffer */
  171415. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  171416. /* Transfer no more than is currently defined */
  171417. thisrow = (long) ptr->cur_start_row + i;
  171418. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  171419. /* Transfer no more than fits in file */
  171420. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  171421. if (rows <= 0) /* this chunk might be past end of file! */
  171422. break;
  171423. byte_count = rows * bytesperrow;
  171424. if (writing)
  171425. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  171426. (void FAR *) ptr->mem_buffer[i],
  171427. file_offset, byte_count);
  171428. else
  171429. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  171430. (void FAR *) ptr->mem_buffer[i],
  171431. file_offset, byte_count);
  171432. file_offset += byte_count;
  171433. }
  171434. }
  171435. METHODDEF(JSAMPARRAY)
  171436. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  171437. JDIMENSION start_row, JDIMENSION num_rows,
  171438. boolean writable)
  171439. /* Access the part of a virtual sample array starting at start_row */
  171440. /* and extending for num_rows rows. writable is true if */
  171441. /* caller intends to modify the accessed area. */
  171442. {
  171443. JDIMENSION end_row = start_row + num_rows;
  171444. JDIMENSION undef_row;
  171445. /* debugging check */
  171446. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  171447. ptr->mem_buffer == NULL)
  171448. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  171449. /* Make the desired part of the virtual array accessible */
  171450. if (start_row < ptr->cur_start_row ||
  171451. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  171452. if (! ptr->b_s_open)
  171453. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  171454. /* Flush old buffer contents if necessary */
  171455. if (ptr->dirty) {
  171456. do_sarray_io(cinfo, ptr, TRUE);
  171457. ptr->dirty = FALSE;
  171458. }
  171459. /* Decide what part of virtual array to access.
  171460. * Algorithm: if target address > current window, assume forward scan,
  171461. * load starting at target address. If target address < current window,
  171462. * assume backward scan, load so that target area is top of window.
  171463. * Note that when switching from forward write to forward read, will have
  171464. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  171465. */
  171466. if (start_row > ptr->cur_start_row) {
  171467. ptr->cur_start_row = start_row;
  171468. } else {
  171469. /* use long arithmetic here to avoid overflow & unsigned problems */
  171470. long ltemp;
  171471. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  171472. if (ltemp < 0)
  171473. ltemp = 0; /* don't fall off front end of file */
  171474. ptr->cur_start_row = (JDIMENSION) ltemp;
  171475. }
  171476. /* Read in the selected part of the array.
  171477. * During the initial write pass, we will do no actual read
  171478. * because the selected part is all undefined.
  171479. */
  171480. do_sarray_io(cinfo, ptr, FALSE);
  171481. }
  171482. /* Ensure the accessed part of the array is defined; prezero if needed.
  171483. * To improve locality of access, we only prezero the part of the array
  171484. * that the caller is about to access, not the entire in-memory array.
  171485. */
  171486. if (ptr->first_undef_row < end_row) {
  171487. if (ptr->first_undef_row < start_row) {
  171488. if (writable) /* writer skipped over a section of array */
  171489. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  171490. undef_row = start_row; /* but reader is allowed to read ahead */
  171491. } else {
  171492. undef_row = ptr->first_undef_row;
  171493. }
  171494. if (writable)
  171495. ptr->first_undef_row = end_row;
  171496. if (ptr->pre_zero) {
  171497. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  171498. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  171499. end_row -= ptr->cur_start_row;
  171500. while (undef_row < end_row) {
  171501. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  171502. undef_row++;
  171503. }
  171504. } else {
  171505. if (! writable) /* reader looking at undefined data */
  171506. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  171507. }
  171508. }
  171509. /* Flag the buffer dirty if caller will write in it */
  171510. if (writable)
  171511. ptr->dirty = TRUE;
  171512. /* Return address of proper part of the buffer */
  171513. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  171514. }
  171515. METHODDEF(JBLOCKARRAY)
  171516. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  171517. JDIMENSION start_row, JDIMENSION num_rows,
  171518. boolean writable)
  171519. /* Access the part of a virtual block array starting at start_row */
  171520. /* and extending for num_rows rows. writable is true if */
  171521. /* caller intends to modify the accessed area. */
  171522. {
  171523. JDIMENSION end_row = start_row + num_rows;
  171524. JDIMENSION undef_row;
  171525. /* debugging check */
  171526. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  171527. ptr->mem_buffer == NULL)
  171528. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  171529. /* Make the desired part of the virtual array accessible */
  171530. if (start_row < ptr->cur_start_row ||
  171531. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  171532. if (! ptr->b_s_open)
  171533. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  171534. /* Flush old buffer contents if necessary */
  171535. if (ptr->dirty) {
  171536. do_barray_io(cinfo, ptr, TRUE);
  171537. ptr->dirty = FALSE;
  171538. }
  171539. /* Decide what part of virtual array to access.
  171540. * Algorithm: if target address > current window, assume forward scan,
  171541. * load starting at target address. If target address < current window,
  171542. * assume backward scan, load so that target area is top of window.
  171543. * Note that when switching from forward write to forward read, will have
  171544. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  171545. */
  171546. if (start_row > ptr->cur_start_row) {
  171547. ptr->cur_start_row = start_row;
  171548. } else {
  171549. /* use long arithmetic here to avoid overflow & unsigned problems */
  171550. long ltemp;
  171551. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  171552. if (ltemp < 0)
  171553. ltemp = 0; /* don't fall off front end of file */
  171554. ptr->cur_start_row = (JDIMENSION) ltemp;
  171555. }
  171556. /* Read in the selected part of the array.
  171557. * During the initial write pass, we will do no actual read
  171558. * because the selected part is all undefined.
  171559. */
  171560. do_barray_io(cinfo, ptr, FALSE);
  171561. }
  171562. /* Ensure the accessed part of the array is defined; prezero if needed.
  171563. * To improve locality of access, we only prezero the part of the array
  171564. * that the caller is about to access, not the entire in-memory array.
  171565. */
  171566. if (ptr->first_undef_row < end_row) {
  171567. if (ptr->first_undef_row < start_row) {
  171568. if (writable) /* writer skipped over a section of array */
  171569. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  171570. undef_row = start_row; /* but reader is allowed to read ahead */
  171571. } else {
  171572. undef_row = ptr->first_undef_row;
  171573. }
  171574. if (writable)
  171575. ptr->first_undef_row = end_row;
  171576. if (ptr->pre_zero) {
  171577. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  171578. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  171579. end_row -= ptr->cur_start_row;
  171580. while (undef_row < end_row) {
  171581. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  171582. undef_row++;
  171583. }
  171584. } else {
  171585. if (! writable) /* reader looking at undefined data */
  171586. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  171587. }
  171588. }
  171589. /* Flag the buffer dirty if caller will write in it */
  171590. if (writable)
  171591. ptr->dirty = TRUE;
  171592. /* Return address of proper part of the buffer */
  171593. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  171594. }
  171595. /*
  171596. * Release all objects belonging to a specified pool.
  171597. */
  171598. METHODDEF(void)
  171599. free_pool (j_common_ptr cinfo, int pool_id)
  171600. {
  171601. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171602. small_pool_ptr shdr_ptr;
  171603. large_pool_ptr lhdr_ptr;
  171604. size_t space_freed;
  171605. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  171606. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171607. #ifdef MEM_STATS
  171608. if (cinfo->err->trace_level > 1)
  171609. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  171610. #endif
  171611. /* If freeing IMAGE pool, close any virtual arrays first */
  171612. if (pool_id == JPOOL_IMAGE) {
  171613. jvirt_sarray_ptr sptr;
  171614. jvirt_barray_ptr bptr;
  171615. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  171616. if (sptr->b_s_open) { /* there may be no backing store */
  171617. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  171618. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  171619. }
  171620. }
  171621. mem->virt_sarray_list = NULL;
  171622. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  171623. if (bptr->b_s_open) { /* there may be no backing store */
  171624. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  171625. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  171626. }
  171627. }
  171628. mem->virt_barray_list = NULL;
  171629. }
  171630. /* Release large objects */
  171631. lhdr_ptr = mem->large_list[pool_id];
  171632. mem->large_list[pool_id] = NULL;
  171633. while (lhdr_ptr != NULL) {
  171634. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  171635. space_freed = lhdr_ptr->hdr.bytes_used +
  171636. lhdr_ptr->hdr.bytes_left +
  171637. SIZEOF(large_pool_hdr);
  171638. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  171639. mem->total_space_allocated -= space_freed;
  171640. lhdr_ptr = next_lhdr_ptr;
  171641. }
  171642. /* Release small objects */
  171643. shdr_ptr = mem->small_list[pool_id];
  171644. mem->small_list[pool_id] = NULL;
  171645. while (shdr_ptr != NULL) {
  171646. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  171647. space_freed = shdr_ptr->hdr.bytes_used +
  171648. shdr_ptr->hdr.bytes_left +
  171649. SIZEOF(small_pool_hdr);
  171650. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  171651. mem->total_space_allocated -= space_freed;
  171652. shdr_ptr = next_shdr_ptr;
  171653. }
  171654. }
  171655. /*
  171656. * Close up shop entirely.
  171657. * Note that this cannot be called unless cinfo->mem is non-NULL.
  171658. */
  171659. METHODDEF(void)
  171660. self_destruct (j_common_ptr cinfo)
  171661. {
  171662. int pool;
  171663. /* Close all backing store, release all memory.
  171664. * Releasing pools in reverse order might help avoid fragmentation
  171665. * with some (brain-damaged) malloc libraries.
  171666. */
  171667. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  171668. free_pool(cinfo, pool);
  171669. }
  171670. /* Release the memory manager control block too. */
  171671. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  171672. cinfo->mem = NULL; /* ensures I will be called only once */
  171673. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  171674. }
  171675. /*
  171676. * Memory manager initialization.
  171677. * When this is called, only the error manager pointer is valid in cinfo!
  171678. */
  171679. GLOBAL(void)
  171680. jinit_memory_mgr (j_common_ptr cinfo)
  171681. {
  171682. my_mem_ptr mem;
  171683. long max_to_use;
  171684. int pool;
  171685. size_t test_mac;
  171686. cinfo->mem = NULL; /* for safety if init fails */
  171687. /* Check for configuration errors.
  171688. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  171689. * doesn't reflect any real hardware alignment requirement.
  171690. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  171691. * in common if and only if X is a power of 2, ie has only one one-bit.
  171692. * Some compilers may give an "unreachable code" warning here; ignore it.
  171693. */
  171694. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  171695. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  171696. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  171697. * a multiple of SIZEOF(ALIGN_TYPE).
  171698. * Again, an "unreachable code" warning may be ignored here.
  171699. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  171700. */
  171701. test_mac = (size_t) MAX_ALLOC_CHUNK;
  171702. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  171703. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  171704. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  171705. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  171706. /* Attempt to allocate memory manager's control block */
  171707. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  171708. if (mem == NULL) {
  171709. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  171710. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  171711. }
  171712. /* OK, fill in the method pointers */
  171713. mem->pub.alloc_small = alloc_small;
  171714. mem->pub.alloc_large = alloc_large;
  171715. mem->pub.alloc_sarray = alloc_sarray;
  171716. mem->pub.alloc_barray = alloc_barray;
  171717. mem->pub.request_virt_sarray = request_virt_sarray;
  171718. mem->pub.request_virt_barray = request_virt_barray;
  171719. mem->pub.realize_virt_arrays = realize_virt_arrays;
  171720. mem->pub.access_virt_sarray = access_virt_sarray;
  171721. mem->pub.access_virt_barray = access_virt_barray;
  171722. mem->pub.free_pool = free_pool;
  171723. mem->pub.self_destruct = self_destruct;
  171724. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  171725. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  171726. /* Initialize working state */
  171727. mem->pub.max_memory_to_use = max_to_use;
  171728. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  171729. mem->small_list[pool] = NULL;
  171730. mem->large_list[pool] = NULL;
  171731. }
  171732. mem->virt_sarray_list = NULL;
  171733. mem->virt_barray_list = NULL;
  171734. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  171735. /* Declare ourselves open for business */
  171736. cinfo->mem = & mem->pub;
  171737. /* Check for an environment variable JPEGMEM; if found, override the
  171738. * default max_memory setting from jpeg_mem_init. Note that the
  171739. * surrounding application may again override this value.
  171740. * If your system doesn't support getenv(), define NO_GETENV to disable
  171741. * this feature.
  171742. */
  171743. #ifndef NO_GETENV
  171744. { char * memenv;
  171745. if ((memenv = getenv("JPEGMEM")) != NULL) {
  171746. char ch = 'x';
  171747. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  171748. if (ch == 'm' || ch == 'M')
  171749. max_to_use *= 1000L;
  171750. mem->pub.max_memory_to_use = max_to_use * 1000L;
  171751. }
  171752. }
  171753. }
  171754. #endif
  171755. }
  171756. /********* End of inlined file: jmemmgr.c *********/
  171757. /********* Start of inlined file: jmemnobs.c *********/
  171758. #define JPEG_INTERNALS
  171759. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  171760. extern void * malloc JPP((size_t size));
  171761. extern void free JPP((void *ptr));
  171762. #endif
  171763. /*
  171764. * Memory allocation and freeing are controlled by the regular library
  171765. * routines malloc() and free().
  171766. */
  171767. GLOBAL(void *)
  171768. jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
  171769. {
  171770. return (void *) malloc(sizeofobject);
  171771. }
  171772. GLOBAL(void)
  171773. jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
  171774. {
  171775. free(object);
  171776. }
  171777. /*
  171778. * "Large" objects are treated the same as "small" ones.
  171779. * NB: although we include FAR keywords in the routine declarations,
  171780. * this file won't actually work in 80x86 small/medium model; at least,
  171781. * you probably won't be able to process useful-size images in only 64KB.
  171782. */
  171783. GLOBAL(void FAR *)
  171784. jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
  171785. {
  171786. return (void FAR *) malloc(sizeofobject);
  171787. }
  171788. GLOBAL(void)
  171789. jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
  171790. {
  171791. free(object);
  171792. }
  171793. /*
  171794. * This routine computes the total memory space available for allocation.
  171795. * Here we always say, "we got all you want bud!"
  171796. */
  171797. GLOBAL(long)
  171798. jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
  171799. long max_bytes_needed, long already_allocated)
  171800. {
  171801. return max_bytes_needed;
  171802. }
  171803. /*
  171804. * Backing store (temporary file) management.
  171805. * Since jpeg_mem_available always promised the moon,
  171806. * this should never be called and we can just error out.
  171807. */
  171808. GLOBAL(void)
  171809. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *info,
  171810. long total_bytes_needed)
  171811. {
  171812. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  171813. }
  171814. /*
  171815. * These routines take care of any system-dependent initialization and
  171816. * cleanup required. Here, there isn't any.
  171817. */
  171818. GLOBAL(long)
  171819. jpeg_mem_init (j_common_ptr cinfo)
  171820. {
  171821. return 0; /* just set max_memory_to_use to 0 */
  171822. }
  171823. GLOBAL(void)
  171824. jpeg_mem_term (j_common_ptr cinfo)
  171825. {
  171826. /* no work */
  171827. }
  171828. /********* End of inlined file: jmemnobs.c *********/
  171829. /********* Start of inlined file: jquant1.c *********/
  171830. #define JPEG_INTERNALS
  171831. #ifdef QUANT_1PASS_SUPPORTED
  171832. /*
  171833. * The main purpose of 1-pass quantization is to provide a fast, if not very
  171834. * high quality, colormapped output capability. A 2-pass quantizer usually
  171835. * gives better visual quality; however, for quantized grayscale output this
  171836. * quantizer is perfectly adequate. Dithering is highly recommended with this
  171837. * quantizer, though you can turn it off if you really want to.
  171838. *
  171839. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  171840. * image. We use a map consisting of all combinations of Ncolors[i] color
  171841. * values for the i'th component. The Ncolors[] values are chosen so that
  171842. * their product, the total number of colors, is no more than that requested.
  171843. * (In most cases, the product will be somewhat less.)
  171844. *
  171845. * Since the colormap is orthogonal, the representative value for each color
  171846. * component can be determined without considering the other components;
  171847. * then these indexes can be combined into a colormap index by a standard
  171848. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  171849. * can be precalculated and stored in the lookup table colorindex[].
  171850. * colorindex[i][j] maps pixel value j in component i to the nearest
  171851. * representative value (grid plane) for that component; this index is
  171852. * multiplied by the array stride for component i, so that the
  171853. * index of the colormap entry closest to a given pixel value is just
  171854. * sum( colorindex[component-number][pixel-component-value] )
  171855. * Aside from being fast, this scheme allows for variable spacing between
  171856. * representative values with no additional lookup cost.
  171857. *
  171858. * If gamma correction has been applied in color conversion, it might be wise
  171859. * to adjust the color grid spacing so that the representative colors are
  171860. * equidistant in linear space. At this writing, gamma correction is not
  171861. * implemented by jdcolor, so nothing is done here.
  171862. */
  171863. /* Declarations for ordered dithering.
  171864. *
  171865. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  171866. * dithering is described in many references, for instance Dale Schumacher's
  171867. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  171868. * In place of Schumacher's comparisons against a "threshold" value, we add a
  171869. * "dither" value to the input pixel and then round the result to the nearest
  171870. * output value. The dither value is equivalent to (0.5 - threshold) times
  171871. * the distance between output values. For ordered dithering, we assume that
  171872. * the output colors are equally spaced; if not, results will probably be
  171873. * worse, since the dither may be too much or too little at a given point.
  171874. *
  171875. * The normal calculation would be to form pixel value + dither, range-limit
  171876. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  171877. * We can skip the separate range-limiting step by extending the colorindex
  171878. * table in both directions.
  171879. */
  171880. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  171881. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  171882. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  171883. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  171884. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  171885. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  171886. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  171887. /* Bayer's order-4 dither array. Generated by the code given in
  171888. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  171889. * The values in this array must range from 0 to ODITHER_CELLS-1.
  171890. */
  171891. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  171892. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  171893. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  171894. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  171895. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  171896. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  171897. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  171898. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  171899. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  171900. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  171901. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  171902. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  171903. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  171904. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  171905. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  171906. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  171907. };
  171908. /* Declarations for Floyd-Steinberg dithering.
  171909. *
  171910. * Errors are accumulated into the array fserrors[], at a resolution of
  171911. * 1/16th of a pixel count. The error at a given pixel is propagated
  171912. * to its not-yet-processed neighbors using the standard F-S fractions,
  171913. * ... (here) 7/16
  171914. * 3/16 5/16 1/16
  171915. * We work left-to-right on even rows, right-to-left on odd rows.
  171916. *
  171917. * We can get away with a single array (holding one row's worth of errors)
  171918. * by using it to store the current row's errors at pixel columns not yet
  171919. * processed, but the next row's errors at columns already processed. We
  171920. * need only a few extra variables to hold the errors immediately around the
  171921. * current column. (If we are lucky, those variables are in registers, but
  171922. * even if not, they're probably cheaper to access than array elements are.)
  171923. *
  171924. * The fserrors[] array is indexed [component#][position].
  171925. * We provide (#columns + 2) entries per component; the extra entry at each
  171926. * end saves us from special-casing the first and last pixels.
  171927. *
  171928. * Note: on a wide image, we might not have enough room in a PC's near data
  171929. * segment to hold the error array; so it is allocated with alloc_large.
  171930. */
  171931. #if BITS_IN_JSAMPLE == 8
  171932. typedef INT16 FSERROR; /* 16 bits should be enough */
  171933. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  171934. #else
  171935. typedef INT32 FSERROR; /* may need more than 16 bits */
  171936. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  171937. #endif
  171938. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  171939. /* Private subobject */
  171940. #define MAX_Q_COMPS 4 /* max components I can handle */
  171941. typedef struct {
  171942. struct jpeg_color_quantizer pub; /* public fields */
  171943. /* Initially allocated colormap is saved here */
  171944. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  171945. int sv_actual; /* number of entries in use */
  171946. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  171947. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  171948. * premultiplied as described above. Since colormap indexes must fit into
  171949. * JSAMPLEs, the entries of this array will too.
  171950. */
  171951. boolean is_padded; /* is the colorindex padded for odither? */
  171952. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  171953. /* Variables for ordered dithering */
  171954. int row_index; /* cur row's vertical index in dither matrix */
  171955. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  171956. /* Variables for Floyd-Steinberg dithering */
  171957. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  171958. boolean on_odd_row; /* flag to remember which row we are on */
  171959. } my_cquantizer;
  171960. typedef my_cquantizer * my_cquantize_ptr;
  171961. /*
  171962. * Policy-making subroutines for create_colormap and create_colorindex.
  171963. * These routines determine the colormap to be used. The rest of the module
  171964. * only assumes that the colormap is orthogonal.
  171965. *
  171966. * * select_ncolors decides how to divvy up the available colors
  171967. * among the components.
  171968. * * output_value defines the set of representative values for a component.
  171969. * * largest_input_value defines the mapping from input values to
  171970. * representative values for a component.
  171971. * Note that the latter two routines may impose different policies for
  171972. * different components, though this is not currently done.
  171973. */
  171974. LOCAL(int)
  171975. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  171976. /* Determine allocation of desired colors to components, */
  171977. /* and fill in Ncolors[] array to indicate choice. */
  171978. /* Return value is total number of colors (product of Ncolors[] values). */
  171979. {
  171980. int nc = cinfo->out_color_components; /* number of color components */
  171981. int max_colors = cinfo->desired_number_of_colors;
  171982. int total_colors, iroot, i, j;
  171983. boolean changed;
  171984. long temp;
  171985. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  171986. /* We can allocate at least the nc'th root of max_colors per component. */
  171987. /* Compute floor(nc'th root of max_colors). */
  171988. iroot = 1;
  171989. do {
  171990. iroot++;
  171991. temp = iroot; /* set temp = iroot ** nc */
  171992. for (i = 1; i < nc; i++)
  171993. temp *= iroot;
  171994. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  171995. iroot--; /* now iroot = floor(root) */
  171996. /* Must have at least 2 color values per component */
  171997. if (iroot < 2)
  171998. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  171999. /* Initialize to iroot color values for each component */
  172000. total_colors = 1;
  172001. for (i = 0; i < nc; i++) {
  172002. Ncolors[i] = iroot;
  172003. total_colors *= iroot;
  172004. }
  172005. /* We may be able to increment the count for one or more components without
  172006. * exceeding max_colors, though we know not all can be incremented.
  172007. * Sometimes, the first component can be incremented more than once!
  172008. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  172009. * In RGB colorspace, try to increment G first, then R, then B.
  172010. */
  172011. do {
  172012. changed = FALSE;
  172013. for (i = 0; i < nc; i++) {
  172014. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  172015. /* calculate new total_colors if Ncolors[j] is incremented */
  172016. temp = total_colors / Ncolors[j];
  172017. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  172018. if (temp > (long) max_colors)
  172019. break; /* won't fit, done with this pass */
  172020. Ncolors[j]++; /* OK, apply the increment */
  172021. total_colors = (int) temp;
  172022. changed = TRUE;
  172023. }
  172024. } while (changed);
  172025. return total_colors;
  172026. }
  172027. LOCAL(int)
  172028. output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  172029. /* Return j'th output value, where j will range from 0 to maxj */
  172030. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  172031. {
  172032. /* We always provide values 0 and MAXJSAMPLE for each component;
  172033. * any additional values are equally spaced between these limits.
  172034. * (Forcing the upper and lower values to the limits ensures that
  172035. * dithering can't produce a color outside the selected gamut.)
  172036. */
  172037. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  172038. }
  172039. LOCAL(int)
  172040. largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  172041. /* Return largest input value that should map to j'th output value */
  172042. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  172043. {
  172044. /* Breakpoints are halfway between values returned by output_value */
  172045. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  172046. }
  172047. /*
  172048. * Create the colormap.
  172049. */
  172050. LOCAL(void)
  172051. create_colormap (j_decompress_ptr cinfo)
  172052. {
  172053. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172054. JSAMPARRAY colormap; /* Created colormap */
  172055. int total_colors; /* Number of distinct output colors */
  172056. int i,j,k, nci, blksize, blkdist, ptr, val;
  172057. /* Select number of colors for each component */
  172058. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  172059. /* Report selected color counts */
  172060. if (cinfo->out_color_components == 3)
  172061. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  172062. total_colors, cquantize->Ncolors[0],
  172063. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  172064. else
  172065. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  172066. /* Allocate and fill in the colormap. */
  172067. /* The colors are ordered in the map in standard row-major order, */
  172068. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  172069. colormap = (*cinfo->mem->alloc_sarray)
  172070. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172071. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  172072. /* blksize is number of adjacent repeated entries for a component */
  172073. /* blkdist is distance between groups of identical entries for a component */
  172074. blkdist = total_colors;
  172075. for (i = 0; i < cinfo->out_color_components; i++) {
  172076. /* fill in colormap entries for i'th color component */
  172077. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172078. blksize = blkdist / nci;
  172079. for (j = 0; j < nci; j++) {
  172080. /* Compute j'th output value (out of nci) for component */
  172081. val = output_value(cinfo, i, j, nci-1);
  172082. /* Fill in all colormap entries that have this value of this component */
  172083. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  172084. /* fill in blksize entries beginning at ptr */
  172085. for (k = 0; k < blksize; k++)
  172086. colormap[i][ptr+k] = (JSAMPLE) val;
  172087. }
  172088. }
  172089. blkdist = blksize; /* blksize of this color is blkdist of next */
  172090. }
  172091. /* Save the colormap in private storage,
  172092. * where it will survive color quantization mode changes.
  172093. */
  172094. cquantize->sv_colormap = colormap;
  172095. cquantize->sv_actual = total_colors;
  172096. }
  172097. /*
  172098. * Create the color index table.
  172099. */
  172100. LOCAL(void)
  172101. create_colorindex (j_decompress_ptr cinfo)
  172102. {
  172103. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172104. JSAMPROW indexptr;
  172105. int i,j,k, nci, blksize, val, pad;
  172106. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  172107. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  172108. * This is not necessary in the other dithering modes. However, we
  172109. * flag whether it was done in case user changes dithering mode.
  172110. */
  172111. if (cinfo->dither_mode == JDITHER_ORDERED) {
  172112. pad = MAXJSAMPLE*2;
  172113. cquantize->is_padded = TRUE;
  172114. } else {
  172115. pad = 0;
  172116. cquantize->is_padded = FALSE;
  172117. }
  172118. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  172119. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172120. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  172121. (JDIMENSION) cinfo->out_color_components);
  172122. /* blksize is number of adjacent repeated entries for a component */
  172123. blksize = cquantize->sv_actual;
  172124. for (i = 0; i < cinfo->out_color_components; i++) {
  172125. /* fill in colorindex entries for i'th color component */
  172126. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172127. blksize = blksize / nci;
  172128. /* adjust colorindex pointers to provide padding at negative indexes. */
  172129. if (pad)
  172130. cquantize->colorindex[i] += MAXJSAMPLE;
  172131. /* in loop, val = index of current output value, */
  172132. /* and k = largest j that maps to current val */
  172133. indexptr = cquantize->colorindex[i];
  172134. val = 0;
  172135. k = largest_input_value(cinfo, i, 0, nci-1);
  172136. for (j = 0; j <= MAXJSAMPLE; j++) {
  172137. while (j > k) /* advance val if past boundary */
  172138. k = largest_input_value(cinfo, i, ++val, nci-1);
  172139. /* premultiply so that no multiplication needed in main processing */
  172140. indexptr[j] = (JSAMPLE) (val * blksize);
  172141. }
  172142. /* Pad at both ends if necessary */
  172143. if (pad)
  172144. for (j = 1; j <= MAXJSAMPLE; j++) {
  172145. indexptr[-j] = indexptr[0];
  172146. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  172147. }
  172148. }
  172149. }
  172150. /*
  172151. * Create an ordered-dither array for a component having ncolors
  172152. * distinct output values.
  172153. */
  172154. LOCAL(ODITHER_MATRIX_PTR)
  172155. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  172156. {
  172157. ODITHER_MATRIX_PTR odither;
  172158. int j,k;
  172159. INT32 num,den;
  172160. odither = (ODITHER_MATRIX_PTR)
  172161. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172162. SIZEOF(ODITHER_MATRIX));
  172163. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  172164. * Hence the dither value for the matrix cell with fill order f
  172165. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  172166. * On 16-bit-int machine, be careful to avoid overflow.
  172167. */
  172168. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  172169. for (j = 0; j < ODITHER_SIZE; j++) {
  172170. for (k = 0; k < ODITHER_SIZE; k++) {
  172171. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  172172. * MAXJSAMPLE;
  172173. /* Ensure round towards zero despite C's lack of consistency
  172174. * about rounding negative values in integer division...
  172175. */
  172176. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  172177. }
  172178. }
  172179. return odither;
  172180. }
  172181. /*
  172182. * Create the ordered-dither tables.
  172183. * Components having the same number of representative colors may
  172184. * share a dither table.
  172185. */
  172186. LOCAL(void)
  172187. create_odither_tables (j_decompress_ptr cinfo)
  172188. {
  172189. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172190. ODITHER_MATRIX_PTR odither;
  172191. int i, j, nci;
  172192. for (i = 0; i < cinfo->out_color_components; i++) {
  172193. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172194. odither = NULL; /* search for matching prior component */
  172195. for (j = 0; j < i; j++) {
  172196. if (nci == cquantize->Ncolors[j]) {
  172197. odither = cquantize->odither[j];
  172198. break;
  172199. }
  172200. }
  172201. if (odither == NULL) /* need a new table? */
  172202. odither = make_odither_array(cinfo, nci);
  172203. cquantize->odither[i] = odither;
  172204. }
  172205. }
  172206. /*
  172207. * Map some rows of pixels to the output colormapped representation.
  172208. */
  172209. METHODDEF(void)
  172210. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172211. JSAMPARRAY output_buf, int num_rows)
  172212. /* General case, no dithering */
  172213. {
  172214. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172215. JSAMPARRAY colorindex = cquantize->colorindex;
  172216. register int pixcode, ci;
  172217. register JSAMPROW ptrin, ptrout;
  172218. int row;
  172219. JDIMENSION col;
  172220. JDIMENSION width = cinfo->output_width;
  172221. register int nc = cinfo->out_color_components;
  172222. for (row = 0; row < num_rows; row++) {
  172223. ptrin = input_buf[row];
  172224. ptrout = output_buf[row];
  172225. for (col = width; col > 0; col--) {
  172226. pixcode = 0;
  172227. for (ci = 0; ci < nc; ci++) {
  172228. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  172229. }
  172230. *ptrout++ = (JSAMPLE) pixcode;
  172231. }
  172232. }
  172233. }
  172234. METHODDEF(void)
  172235. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172236. JSAMPARRAY output_buf, int num_rows)
  172237. /* Fast path for out_color_components==3, no dithering */
  172238. {
  172239. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172240. register int pixcode;
  172241. register JSAMPROW ptrin, ptrout;
  172242. JSAMPROW colorindex0 = cquantize->colorindex[0];
  172243. JSAMPROW colorindex1 = cquantize->colorindex[1];
  172244. JSAMPROW colorindex2 = cquantize->colorindex[2];
  172245. int row;
  172246. JDIMENSION col;
  172247. JDIMENSION width = cinfo->output_width;
  172248. for (row = 0; row < num_rows; row++) {
  172249. ptrin = input_buf[row];
  172250. ptrout = output_buf[row];
  172251. for (col = width; col > 0; col--) {
  172252. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  172253. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  172254. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  172255. *ptrout++ = (JSAMPLE) pixcode;
  172256. }
  172257. }
  172258. }
  172259. METHODDEF(void)
  172260. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172261. JSAMPARRAY output_buf, int num_rows)
  172262. /* General case, with ordered dithering */
  172263. {
  172264. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172265. register JSAMPROW input_ptr;
  172266. register JSAMPROW output_ptr;
  172267. JSAMPROW colorindex_ci;
  172268. int * dither; /* points to active row of dither matrix */
  172269. int row_index, col_index; /* current indexes into dither matrix */
  172270. int nc = cinfo->out_color_components;
  172271. int ci;
  172272. int row;
  172273. JDIMENSION col;
  172274. JDIMENSION width = cinfo->output_width;
  172275. for (row = 0; row < num_rows; row++) {
  172276. /* Initialize output values to 0 so can process components separately */
  172277. jzero_far((void FAR *) output_buf[row],
  172278. (size_t) (width * SIZEOF(JSAMPLE)));
  172279. row_index = cquantize->row_index;
  172280. for (ci = 0; ci < nc; ci++) {
  172281. input_ptr = input_buf[row] + ci;
  172282. output_ptr = output_buf[row];
  172283. colorindex_ci = cquantize->colorindex[ci];
  172284. dither = cquantize->odither[ci][row_index];
  172285. col_index = 0;
  172286. for (col = width; col > 0; col--) {
  172287. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  172288. * select output value, accumulate into output code for this pixel.
  172289. * Range-limiting need not be done explicitly, as we have extended
  172290. * the colorindex table to produce the right answers for out-of-range
  172291. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  172292. * required amount of padding.
  172293. */
  172294. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  172295. input_ptr += nc;
  172296. output_ptr++;
  172297. col_index = (col_index + 1) & ODITHER_MASK;
  172298. }
  172299. }
  172300. /* Advance row index for next row */
  172301. row_index = (row_index + 1) & ODITHER_MASK;
  172302. cquantize->row_index = row_index;
  172303. }
  172304. }
  172305. METHODDEF(void)
  172306. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172307. JSAMPARRAY output_buf, int num_rows)
  172308. /* Fast path for out_color_components==3, with ordered dithering */
  172309. {
  172310. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172311. register int pixcode;
  172312. register JSAMPROW input_ptr;
  172313. register JSAMPROW output_ptr;
  172314. JSAMPROW colorindex0 = cquantize->colorindex[0];
  172315. JSAMPROW colorindex1 = cquantize->colorindex[1];
  172316. JSAMPROW colorindex2 = cquantize->colorindex[2];
  172317. int * dither0; /* points to active row of dither matrix */
  172318. int * dither1;
  172319. int * dither2;
  172320. int row_index, col_index; /* current indexes into dither matrix */
  172321. int row;
  172322. JDIMENSION col;
  172323. JDIMENSION width = cinfo->output_width;
  172324. for (row = 0; row < num_rows; row++) {
  172325. row_index = cquantize->row_index;
  172326. input_ptr = input_buf[row];
  172327. output_ptr = output_buf[row];
  172328. dither0 = cquantize->odither[0][row_index];
  172329. dither1 = cquantize->odither[1][row_index];
  172330. dither2 = cquantize->odither[2][row_index];
  172331. col_index = 0;
  172332. for (col = width; col > 0; col--) {
  172333. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  172334. dither0[col_index]]);
  172335. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  172336. dither1[col_index]]);
  172337. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  172338. dither2[col_index]]);
  172339. *output_ptr++ = (JSAMPLE) pixcode;
  172340. col_index = (col_index + 1) & ODITHER_MASK;
  172341. }
  172342. row_index = (row_index + 1) & ODITHER_MASK;
  172343. cquantize->row_index = row_index;
  172344. }
  172345. }
  172346. METHODDEF(void)
  172347. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172348. JSAMPARRAY output_buf, int num_rows)
  172349. /* General case, with Floyd-Steinberg dithering */
  172350. {
  172351. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172352. register LOCFSERROR cur; /* current error or pixel value */
  172353. LOCFSERROR belowerr; /* error for pixel below cur */
  172354. LOCFSERROR bpreverr; /* error for below/prev col */
  172355. LOCFSERROR bnexterr; /* error for below/next col */
  172356. LOCFSERROR delta;
  172357. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  172358. register JSAMPROW input_ptr;
  172359. register JSAMPROW output_ptr;
  172360. JSAMPROW colorindex_ci;
  172361. JSAMPROW colormap_ci;
  172362. int pixcode;
  172363. int nc = cinfo->out_color_components;
  172364. int dir; /* 1 for left-to-right, -1 for right-to-left */
  172365. int dirnc; /* dir * nc */
  172366. int ci;
  172367. int row;
  172368. JDIMENSION col;
  172369. JDIMENSION width = cinfo->output_width;
  172370. JSAMPLE *range_limit = cinfo->sample_range_limit;
  172371. SHIFT_TEMPS
  172372. for (row = 0; row < num_rows; row++) {
  172373. /* Initialize output values to 0 so can process components separately */
  172374. jzero_far((void FAR *) output_buf[row],
  172375. (size_t) (width * SIZEOF(JSAMPLE)));
  172376. for (ci = 0; ci < nc; ci++) {
  172377. input_ptr = input_buf[row] + ci;
  172378. output_ptr = output_buf[row];
  172379. if (cquantize->on_odd_row) {
  172380. /* work right to left in this row */
  172381. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  172382. output_ptr += width-1;
  172383. dir = -1;
  172384. dirnc = -nc;
  172385. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  172386. } else {
  172387. /* work left to right in this row */
  172388. dir = 1;
  172389. dirnc = nc;
  172390. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  172391. }
  172392. colorindex_ci = cquantize->colorindex[ci];
  172393. colormap_ci = cquantize->sv_colormap[ci];
  172394. /* Preset error values: no error propagated to first pixel from left */
  172395. cur = 0;
  172396. /* and no error propagated to row below yet */
  172397. belowerr = bpreverr = 0;
  172398. for (col = width; col > 0; col--) {
  172399. /* cur holds the error propagated from the previous pixel on the
  172400. * current line. Add the error propagated from the previous line
  172401. * to form the complete error correction term for this pixel, and
  172402. * round the error term (which is expressed * 16) to an integer.
  172403. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  172404. * for either sign of the error value.
  172405. * Note: errorptr points to *previous* column's array entry.
  172406. */
  172407. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  172408. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  172409. * The maximum error is +- MAXJSAMPLE; this sets the required size
  172410. * of the range_limit array.
  172411. */
  172412. cur += GETJSAMPLE(*input_ptr);
  172413. cur = GETJSAMPLE(range_limit[cur]);
  172414. /* Select output value, accumulate into output code for this pixel */
  172415. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  172416. *output_ptr += (JSAMPLE) pixcode;
  172417. /* Compute actual representation error at this pixel */
  172418. /* Note: we can do this even though we don't have the final */
  172419. /* pixel code, because the colormap is orthogonal. */
  172420. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  172421. /* Compute error fractions to be propagated to adjacent pixels.
  172422. * Add these into the running sums, and simultaneously shift the
  172423. * next-line error sums left by 1 column.
  172424. */
  172425. bnexterr = cur;
  172426. delta = cur * 2;
  172427. cur += delta; /* form error * 3 */
  172428. errorptr[0] = (FSERROR) (bpreverr + cur);
  172429. cur += delta; /* form error * 5 */
  172430. bpreverr = belowerr + cur;
  172431. belowerr = bnexterr;
  172432. cur += delta; /* form error * 7 */
  172433. /* At this point cur contains the 7/16 error value to be propagated
  172434. * to the next pixel on the current line, and all the errors for the
  172435. * next line have been shifted over. We are therefore ready to move on.
  172436. */
  172437. input_ptr += dirnc; /* advance input ptr to next column */
  172438. output_ptr += dir; /* advance output ptr to next column */
  172439. errorptr += dir; /* advance errorptr to current column */
  172440. }
  172441. /* Post-loop cleanup: we must unload the final error value into the
  172442. * final fserrors[] entry. Note we need not unload belowerr because
  172443. * it is for the dummy column before or after the actual array.
  172444. */
  172445. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  172446. }
  172447. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  172448. }
  172449. }
  172450. /*
  172451. * Allocate workspace for Floyd-Steinberg errors.
  172452. */
  172453. LOCAL(void)
  172454. alloc_fs_workspace (j_decompress_ptr cinfo)
  172455. {
  172456. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172457. size_t arraysize;
  172458. int i;
  172459. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  172460. for (i = 0; i < cinfo->out_color_components; i++) {
  172461. cquantize->fserrors[i] = (FSERRPTR)
  172462. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  172463. }
  172464. }
  172465. /*
  172466. * Initialize for one-pass color quantization.
  172467. */
  172468. METHODDEF(void)
  172469. start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  172470. {
  172471. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172472. size_t arraysize;
  172473. int i;
  172474. /* Install my colormap. */
  172475. cinfo->colormap = cquantize->sv_colormap;
  172476. cinfo->actual_number_of_colors = cquantize->sv_actual;
  172477. /* Initialize for desired dithering mode. */
  172478. switch (cinfo->dither_mode) {
  172479. case JDITHER_NONE:
  172480. if (cinfo->out_color_components == 3)
  172481. cquantize->pub.color_quantize = color_quantize3;
  172482. else
  172483. cquantize->pub.color_quantize = color_quantize;
  172484. break;
  172485. case JDITHER_ORDERED:
  172486. if (cinfo->out_color_components == 3)
  172487. cquantize->pub.color_quantize = quantize3_ord_dither;
  172488. else
  172489. cquantize->pub.color_quantize = quantize_ord_dither;
  172490. cquantize->row_index = 0; /* initialize state for ordered dither */
  172491. /* If user changed to ordered dither from another mode,
  172492. * we must recreate the color index table with padding.
  172493. * This will cost extra space, but probably isn't very likely.
  172494. */
  172495. if (! cquantize->is_padded)
  172496. create_colorindex(cinfo);
  172497. /* Create ordered-dither tables if we didn't already. */
  172498. if (cquantize->odither[0] == NULL)
  172499. create_odither_tables(cinfo);
  172500. break;
  172501. case JDITHER_FS:
  172502. cquantize->pub.color_quantize = quantize_fs_dither;
  172503. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  172504. /* Allocate Floyd-Steinberg workspace if didn't already. */
  172505. if (cquantize->fserrors[0] == NULL)
  172506. alloc_fs_workspace(cinfo);
  172507. /* Initialize the propagated errors to zero. */
  172508. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  172509. for (i = 0; i < cinfo->out_color_components; i++)
  172510. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  172511. break;
  172512. default:
  172513. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172514. break;
  172515. }
  172516. }
  172517. /*
  172518. * Finish up at the end of the pass.
  172519. */
  172520. METHODDEF(void)
  172521. finish_pass_1_quant (j_decompress_ptr cinfo)
  172522. {
  172523. /* no work in 1-pass case */
  172524. }
  172525. /*
  172526. * Switch to a new external colormap between output passes.
  172527. * Shouldn't get to this module!
  172528. */
  172529. METHODDEF(void)
  172530. new_color_map_1_quant (j_decompress_ptr cinfo)
  172531. {
  172532. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172533. }
  172534. /*
  172535. * Module initialization routine for 1-pass color quantization.
  172536. */
  172537. GLOBAL(void)
  172538. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  172539. {
  172540. my_cquantize_ptr cquantize;
  172541. cquantize = (my_cquantize_ptr)
  172542. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172543. SIZEOF(my_cquantizer));
  172544. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  172545. cquantize->pub.start_pass = start_pass_1_quant;
  172546. cquantize->pub.finish_pass = finish_pass_1_quant;
  172547. cquantize->pub.new_color_map = new_color_map_1_quant;
  172548. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  172549. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  172550. /* Make sure my internal arrays won't overflow */
  172551. if (cinfo->out_color_components > MAX_Q_COMPS)
  172552. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  172553. /* Make sure colormap indexes can be represented by JSAMPLEs */
  172554. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  172555. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  172556. /* Create the colormap and color index table. */
  172557. create_colormap(cinfo);
  172558. create_colorindex(cinfo);
  172559. /* Allocate Floyd-Steinberg workspace now if requested.
  172560. * We do this now since it is FAR storage and may affect the memory
  172561. * manager's space calculations. If the user changes to FS dither
  172562. * mode in a later pass, we will allocate the space then, and will
  172563. * possibly overrun the max_memory_to_use setting.
  172564. */
  172565. if (cinfo->dither_mode == JDITHER_FS)
  172566. alloc_fs_workspace(cinfo);
  172567. }
  172568. #endif /* QUANT_1PASS_SUPPORTED */
  172569. /********* End of inlined file: jquant1.c *********/
  172570. /********* Start of inlined file: jquant2.c *********/
  172571. #define JPEG_INTERNALS
  172572. #ifdef QUANT_2PASS_SUPPORTED
  172573. /*
  172574. * This module implements the well-known Heckbert paradigm for color
  172575. * quantization. Most of the ideas used here can be traced back to
  172576. * Heckbert's seminal paper
  172577. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  172578. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  172579. *
  172580. * In the first pass over the image, we accumulate a histogram showing the
  172581. * usage count of each possible color. To keep the histogram to a reasonable
  172582. * size, we reduce the precision of the input; typical practice is to retain
  172583. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  172584. * in the same histogram cell.
  172585. *
  172586. * Next, the color-selection step begins with a box representing the whole
  172587. * color space, and repeatedly splits the "largest" remaining box until we
  172588. * have as many boxes as desired colors. Then the mean color in each
  172589. * remaining box becomes one of the possible output colors.
  172590. *
  172591. * The second pass over the image maps each input pixel to the closest output
  172592. * color (optionally after applying a Floyd-Steinberg dithering correction).
  172593. * This mapping is logically trivial, but making it go fast enough requires
  172594. * considerable care.
  172595. *
  172596. * Heckbert-style quantizers vary a good deal in their policies for choosing
  172597. * the "largest" box and deciding where to cut it. The particular policies
  172598. * used here have proved out well in experimental comparisons, but better ones
  172599. * may yet be found.
  172600. *
  172601. * In earlier versions of the IJG code, this module quantized in YCbCr color
  172602. * space, processing the raw upsampled data without a color conversion step.
  172603. * This allowed the color conversion math to be done only once per colormap
  172604. * entry, not once per pixel. However, that optimization precluded other
  172605. * useful optimizations (such as merging color conversion with upsampling)
  172606. * and it also interfered with desired capabilities such as quantizing to an
  172607. * externally-supplied colormap. We have therefore abandoned that approach.
  172608. * The present code works in the post-conversion color space, typically RGB.
  172609. *
  172610. * To improve the visual quality of the results, we actually work in scaled
  172611. * RGB space, giving G distances more weight than R, and R in turn more than
  172612. * B. To do everything in integer math, we must use integer scale factors.
  172613. * The 2/3/1 scale factors used here correspond loosely to the relative
  172614. * weights of the colors in the NTSC grayscale equation.
  172615. * If you want to use this code to quantize a non-RGB color space, you'll
  172616. * probably need to change these scale factors.
  172617. */
  172618. #define R_SCALE 2 /* scale R distances by this much */
  172619. #define G_SCALE 3 /* scale G distances by this much */
  172620. #define B_SCALE 1 /* and B by this much */
  172621. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  172622. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  172623. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  172624. * you'll get compile errors until you extend this logic. In that case
  172625. * you'll probably want to tweak the histogram sizes too.
  172626. */
  172627. #if RGB_RED == 0
  172628. #define C0_SCALE R_SCALE
  172629. #endif
  172630. #if RGB_BLUE == 0
  172631. #define C0_SCALE B_SCALE
  172632. #endif
  172633. #if RGB_GREEN == 1
  172634. #define C1_SCALE G_SCALE
  172635. #endif
  172636. #if RGB_RED == 2
  172637. #define C2_SCALE R_SCALE
  172638. #endif
  172639. #if RGB_BLUE == 2
  172640. #define C2_SCALE B_SCALE
  172641. #endif
  172642. /*
  172643. * First we have the histogram data structure and routines for creating it.
  172644. *
  172645. * The number of bits of precision can be adjusted by changing these symbols.
  172646. * We recommend keeping 6 bits for G and 5 each for R and B.
  172647. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  172648. * better results; if you are short of memory, 5 bits all around will save
  172649. * some space but degrade the results.
  172650. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  172651. * (preferably unsigned long) for each cell. In practice this is overkill;
  172652. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  172653. * and clamping those that do overflow to the maximum value will give close-
  172654. * enough results. This reduces the recommended histogram size from 256Kb
  172655. * to 128Kb, which is a useful savings on PC-class machines.
  172656. * (In the second pass the histogram space is re-used for pixel mapping data;
  172657. * in that capacity, each cell must be able to store zero to the number of
  172658. * desired colors. 16 bits/cell is plenty for that too.)
  172659. * Since the JPEG code is intended to run in small memory model on 80x86
  172660. * machines, we can't just allocate the histogram in one chunk. Instead
  172661. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  172662. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  172663. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  172664. * on 80x86 machines, the pointer row is in near memory but the actual
  172665. * arrays are in far memory (same arrangement as we use for image arrays).
  172666. */
  172667. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  172668. /* These will do the right thing for either R,G,B or B,G,R color order,
  172669. * but you may not like the results for other color orders.
  172670. */
  172671. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  172672. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  172673. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  172674. /* Number of elements along histogram axes. */
  172675. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  172676. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  172677. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  172678. /* These are the amounts to shift an input value to get a histogram index. */
  172679. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  172680. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  172681. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  172682. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  172683. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  172684. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  172685. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  172686. typedef hist2d * hist3d; /* type for top-level pointer */
  172687. /* Declarations for Floyd-Steinberg dithering.
  172688. *
  172689. * Errors are accumulated into the array fserrors[], at a resolution of
  172690. * 1/16th of a pixel count. The error at a given pixel is propagated
  172691. * to its not-yet-processed neighbors using the standard F-S fractions,
  172692. * ... (here) 7/16
  172693. * 3/16 5/16 1/16
  172694. * We work left-to-right on even rows, right-to-left on odd rows.
  172695. *
  172696. * We can get away with a single array (holding one row's worth of errors)
  172697. * by using it to store the current row's errors at pixel columns not yet
  172698. * processed, but the next row's errors at columns already processed. We
  172699. * need only a few extra variables to hold the errors immediately around the
  172700. * current column. (If we are lucky, those variables are in registers, but
  172701. * even if not, they're probably cheaper to access than array elements are.)
  172702. *
  172703. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  172704. * each end saves us from special-casing the first and last pixels.
  172705. * Each entry is three values long, one value for each color component.
  172706. *
  172707. * Note: on a wide image, we might not have enough room in a PC's near data
  172708. * segment to hold the error array; so it is allocated with alloc_large.
  172709. */
  172710. #if BITS_IN_JSAMPLE == 8
  172711. typedef INT16 FSERROR; /* 16 bits should be enough */
  172712. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  172713. #else
  172714. typedef INT32 FSERROR; /* may need more than 16 bits */
  172715. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  172716. #endif
  172717. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  172718. /* Private subobject */
  172719. typedef struct {
  172720. struct jpeg_color_quantizer pub; /* public fields */
  172721. /* Space for the eventually created colormap is stashed here */
  172722. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  172723. int desired; /* desired # of colors = size of colormap */
  172724. /* Variables for accumulating image statistics */
  172725. hist3d histogram; /* pointer to the histogram */
  172726. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  172727. /* Variables for Floyd-Steinberg dithering */
  172728. FSERRPTR fserrors; /* accumulated errors */
  172729. boolean on_odd_row; /* flag to remember which row we are on */
  172730. int * error_limiter; /* table for clamping the applied error */
  172731. } my_cquantizer2;
  172732. typedef my_cquantizer2 * my_cquantize_ptr2;
  172733. /*
  172734. * Prescan some rows of pixels.
  172735. * In this module the prescan simply updates the histogram, which has been
  172736. * initialized to zeroes by start_pass.
  172737. * An output_buf parameter is required by the method signature, but no data
  172738. * is actually output (in fact the buffer controller is probably passing a
  172739. * NULL pointer).
  172740. */
  172741. METHODDEF(void)
  172742. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172743. JSAMPARRAY output_buf, int num_rows)
  172744. {
  172745. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172746. register JSAMPROW ptr;
  172747. register histptr histp;
  172748. register hist3d histogram = cquantize->histogram;
  172749. int row;
  172750. JDIMENSION col;
  172751. JDIMENSION width = cinfo->output_width;
  172752. for (row = 0; row < num_rows; row++) {
  172753. ptr = input_buf[row];
  172754. for (col = width; col > 0; col--) {
  172755. /* get pixel value and index into the histogram */
  172756. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  172757. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  172758. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  172759. /* increment, check for overflow and undo increment if so. */
  172760. if (++(*histp) <= 0)
  172761. (*histp)--;
  172762. ptr += 3;
  172763. }
  172764. }
  172765. }
  172766. /*
  172767. * Next we have the really interesting routines: selection of a colormap
  172768. * given the completed histogram.
  172769. * These routines work with a list of "boxes", each representing a rectangular
  172770. * subset of the input color space (to histogram precision).
  172771. */
  172772. typedef struct {
  172773. /* The bounds of the box (inclusive); expressed as histogram indexes */
  172774. int c0min, c0max;
  172775. int c1min, c1max;
  172776. int c2min, c2max;
  172777. /* The volume (actually 2-norm) of the box */
  172778. INT32 volume;
  172779. /* The number of nonzero histogram cells within this box */
  172780. long colorcount;
  172781. } box;
  172782. typedef box * boxptr;
  172783. LOCAL(boxptr)
  172784. find_biggest_color_pop (boxptr boxlist, int numboxes)
  172785. /* Find the splittable box with the largest color population */
  172786. /* Returns NULL if no splittable boxes remain */
  172787. {
  172788. register boxptr boxp;
  172789. register int i;
  172790. register long maxc = 0;
  172791. boxptr which = NULL;
  172792. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  172793. if (boxp->colorcount > maxc && boxp->volume > 0) {
  172794. which = boxp;
  172795. maxc = boxp->colorcount;
  172796. }
  172797. }
  172798. return which;
  172799. }
  172800. LOCAL(boxptr)
  172801. find_biggest_volume (boxptr boxlist, int numboxes)
  172802. /* Find the splittable box with the largest (scaled) volume */
  172803. /* Returns NULL if no splittable boxes remain */
  172804. {
  172805. register boxptr boxp;
  172806. register int i;
  172807. register INT32 maxv = 0;
  172808. boxptr which = NULL;
  172809. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  172810. if (boxp->volume > maxv) {
  172811. which = boxp;
  172812. maxv = boxp->volume;
  172813. }
  172814. }
  172815. return which;
  172816. }
  172817. LOCAL(void)
  172818. update_box (j_decompress_ptr cinfo, boxptr boxp)
  172819. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  172820. /* and recompute its volume and population */
  172821. {
  172822. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172823. hist3d histogram = cquantize->histogram;
  172824. histptr histp;
  172825. int c0,c1,c2;
  172826. int c0min,c0max,c1min,c1max,c2min,c2max;
  172827. INT32 dist0,dist1,dist2;
  172828. long ccount;
  172829. c0min = boxp->c0min; c0max = boxp->c0max;
  172830. c1min = boxp->c1min; c1max = boxp->c1max;
  172831. c2min = boxp->c2min; c2max = boxp->c2max;
  172832. if (c0max > c0min)
  172833. for (c0 = c0min; c0 <= c0max; c0++)
  172834. for (c1 = c1min; c1 <= c1max; c1++) {
  172835. histp = & histogram[c0][c1][c2min];
  172836. for (c2 = c2min; c2 <= c2max; c2++)
  172837. if (*histp++ != 0) {
  172838. boxp->c0min = c0min = c0;
  172839. goto have_c0min;
  172840. }
  172841. }
  172842. have_c0min:
  172843. if (c0max > c0min)
  172844. for (c0 = c0max; c0 >= c0min; c0--)
  172845. for (c1 = c1min; c1 <= c1max; c1++) {
  172846. histp = & histogram[c0][c1][c2min];
  172847. for (c2 = c2min; c2 <= c2max; c2++)
  172848. if (*histp++ != 0) {
  172849. boxp->c0max = c0max = c0;
  172850. goto have_c0max;
  172851. }
  172852. }
  172853. have_c0max:
  172854. if (c1max > c1min)
  172855. for (c1 = c1min; c1 <= c1max; c1++)
  172856. for (c0 = c0min; c0 <= c0max; c0++) {
  172857. histp = & histogram[c0][c1][c2min];
  172858. for (c2 = c2min; c2 <= c2max; c2++)
  172859. if (*histp++ != 0) {
  172860. boxp->c1min = c1min = c1;
  172861. goto have_c1min;
  172862. }
  172863. }
  172864. have_c1min:
  172865. if (c1max > c1min)
  172866. for (c1 = c1max; c1 >= c1min; c1--)
  172867. for (c0 = c0min; c0 <= c0max; c0++) {
  172868. histp = & histogram[c0][c1][c2min];
  172869. for (c2 = c2min; c2 <= c2max; c2++)
  172870. if (*histp++ != 0) {
  172871. boxp->c1max = c1max = c1;
  172872. goto have_c1max;
  172873. }
  172874. }
  172875. have_c1max:
  172876. if (c2max > c2min)
  172877. for (c2 = c2min; c2 <= c2max; c2++)
  172878. for (c0 = c0min; c0 <= c0max; c0++) {
  172879. histp = & histogram[c0][c1min][c2];
  172880. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  172881. if (*histp != 0) {
  172882. boxp->c2min = c2min = c2;
  172883. goto have_c2min;
  172884. }
  172885. }
  172886. have_c2min:
  172887. if (c2max > c2min)
  172888. for (c2 = c2max; c2 >= c2min; c2--)
  172889. for (c0 = c0min; c0 <= c0max; c0++) {
  172890. histp = & histogram[c0][c1min][c2];
  172891. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  172892. if (*histp != 0) {
  172893. boxp->c2max = c2max = c2;
  172894. goto have_c2max;
  172895. }
  172896. }
  172897. have_c2max:
  172898. /* Update box volume.
  172899. * We use 2-norm rather than real volume here; this biases the method
  172900. * against making long narrow boxes, and it has the side benefit that
  172901. * a box is splittable iff norm > 0.
  172902. * Since the differences are expressed in histogram-cell units,
  172903. * we have to shift back to JSAMPLE units to get consistent distances;
  172904. * after which, we scale according to the selected distance scale factors.
  172905. */
  172906. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  172907. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  172908. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  172909. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  172910. /* Now scan remaining volume of box and compute population */
  172911. ccount = 0;
  172912. for (c0 = c0min; c0 <= c0max; c0++)
  172913. for (c1 = c1min; c1 <= c1max; c1++) {
  172914. histp = & histogram[c0][c1][c2min];
  172915. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  172916. if (*histp != 0) {
  172917. ccount++;
  172918. }
  172919. }
  172920. boxp->colorcount = ccount;
  172921. }
  172922. LOCAL(int)
  172923. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  172924. int desired_colors)
  172925. /* Repeatedly select and split the largest box until we have enough boxes */
  172926. {
  172927. int n,lb;
  172928. int c0,c1,c2,cmax;
  172929. register boxptr b1,b2;
  172930. while (numboxes < desired_colors) {
  172931. /* Select box to split.
  172932. * Current algorithm: by population for first half, then by volume.
  172933. */
  172934. if (numboxes*2 <= desired_colors) {
  172935. b1 = find_biggest_color_pop(boxlist, numboxes);
  172936. } else {
  172937. b1 = find_biggest_volume(boxlist, numboxes);
  172938. }
  172939. if (b1 == NULL) /* no splittable boxes left! */
  172940. break;
  172941. b2 = &boxlist[numboxes]; /* where new box will go */
  172942. /* Copy the color bounds to the new box. */
  172943. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  172944. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  172945. /* Choose which axis to split the box on.
  172946. * Current algorithm: longest scaled axis.
  172947. * See notes in update_box about scaling distances.
  172948. */
  172949. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  172950. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  172951. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  172952. /* We want to break any ties in favor of green, then red, blue last.
  172953. * This code does the right thing for R,G,B or B,G,R color orders only.
  172954. */
  172955. #if RGB_RED == 0
  172956. cmax = c1; n = 1;
  172957. if (c0 > cmax) { cmax = c0; n = 0; }
  172958. if (c2 > cmax) { n = 2; }
  172959. #else
  172960. cmax = c1; n = 1;
  172961. if (c2 > cmax) { cmax = c2; n = 2; }
  172962. if (c0 > cmax) { n = 0; }
  172963. #endif
  172964. /* Choose split point along selected axis, and update box bounds.
  172965. * Current algorithm: split at halfway point.
  172966. * (Since the box has been shrunk to minimum volume,
  172967. * any split will produce two nonempty subboxes.)
  172968. * Note that lb value is max for lower box, so must be < old max.
  172969. */
  172970. switch (n) {
  172971. case 0:
  172972. lb = (b1->c0max + b1->c0min) / 2;
  172973. b1->c0max = lb;
  172974. b2->c0min = lb+1;
  172975. break;
  172976. case 1:
  172977. lb = (b1->c1max + b1->c1min) / 2;
  172978. b1->c1max = lb;
  172979. b2->c1min = lb+1;
  172980. break;
  172981. case 2:
  172982. lb = (b1->c2max + b1->c2min) / 2;
  172983. b1->c2max = lb;
  172984. b2->c2min = lb+1;
  172985. break;
  172986. }
  172987. /* Update stats for boxes */
  172988. update_box(cinfo, b1);
  172989. update_box(cinfo, b2);
  172990. numboxes++;
  172991. }
  172992. return numboxes;
  172993. }
  172994. LOCAL(void)
  172995. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  172996. /* Compute representative color for a box, put it in colormap[icolor] */
  172997. {
  172998. /* Current algorithm: mean weighted by pixels (not colors) */
  172999. /* Note it is important to get the rounding correct! */
  173000. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173001. hist3d histogram = cquantize->histogram;
  173002. histptr histp;
  173003. int c0,c1,c2;
  173004. int c0min,c0max,c1min,c1max,c2min,c2max;
  173005. long count;
  173006. long total = 0;
  173007. long c0total = 0;
  173008. long c1total = 0;
  173009. long c2total = 0;
  173010. c0min = boxp->c0min; c0max = boxp->c0max;
  173011. c1min = boxp->c1min; c1max = boxp->c1max;
  173012. c2min = boxp->c2min; c2max = boxp->c2max;
  173013. for (c0 = c0min; c0 <= c0max; c0++)
  173014. for (c1 = c1min; c1 <= c1max; c1++) {
  173015. histp = & histogram[c0][c1][c2min];
  173016. for (c2 = c2min; c2 <= c2max; c2++) {
  173017. if ((count = *histp++) != 0) {
  173018. total += count;
  173019. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  173020. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  173021. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  173022. }
  173023. }
  173024. }
  173025. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  173026. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  173027. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  173028. }
  173029. LOCAL(void)
  173030. select_colors (j_decompress_ptr cinfo, int desired_colors)
  173031. /* Master routine for color selection */
  173032. {
  173033. boxptr boxlist;
  173034. int numboxes;
  173035. int i;
  173036. /* Allocate workspace for box list */
  173037. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  173038. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  173039. /* Initialize one box containing whole space */
  173040. numboxes = 1;
  173041. boxlist[0].c0min = 0;
  173042. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  173043. boxlist[0].c1min = 0;
  173044. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  173045. boxlist[0].c2min = 0;
  173046. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  173047. /* Shrink it to actually-used volume and set its statistics */
  173048. update_box(cinfo, & boxlist[0]);
  173049. /* Perform median-cut to produce final box list */
  173050. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  173051. /* Compute the representative color for each box, fill colormap */
  173052. for (i = 0; i < numboxes; i++)
  173053. compute_color(cinfo, & boxlist[i], i);
  173054. cinfo->actual_number_of_colors = numboxes;
  173055. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  173056. }
  173057. /*
  173058. * These routines are concerned with the time-critical task of mapping input
  173059. * colors to the nearest color in the selected colormap.
  173060. *
  173061. * We re-use the histogram space as an "inverse color map", essentially a
  173062. * cache for the results of nearest-color searches. All colors within a
  173063. * histogram cell will be mapped to the same colormap entry, namely the one
  173064. * closest to the cell's center. This may not be quite the closest entry to
  173065. * the actual input color, but it's almost as good. A zero in the cache
  173066. * indicates we haven't found the nearest color for that cell yet; the array
  173067. * is cleared to zeroes before starting the mapping pass. When we find the
  173068. * nearest color for a cell, its colormap index plus one is recorded in the
  173069. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  173070. * when they need to use an unfilled entry in the cache.
  173071. *
  173072. * Our method of efficiently finding nearest colors is based on the "locally
  173073. * sorted search" idea described by Heckbert and on the incremental distance
  173074. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  173075. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  173076. * the distances from a given colormap entry to each cell of the histogram can
  173077. * be computed quickly using an incremental method: the differences between
  173078. * distances to adjacent cells themselves differ by a constant. This allows a
  173079. * fairly fast implementation of the "brute force" approach of computing the
  173080. * distance from every colormap entry to every histogram cell. Unfortunately,
  173081. * it needs a work array to hold the best-distance-so-far for each histogram
  173082. * cell (because the inner loop has to be over cells, not colormap entries).
  173083. * The work array elements have to be INT32s, so the work array would need
  173084. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  173085. *
  173086. * To get around these problems, we apply Thomas' method to compute the
  173087. * nearest colors for only the cells within a small subbox of the histogram.
  173088. * The work array need be only as big as the subbox, so the memory usage
  173089. * problem is solved. Furthermore, we need not fill subboxes that are never
  173090. * referenced in pass2; many images use only part of the color gamut, so a
  173091. * fair amount of work is saved. An additional advantage of this
  173092. * approach is that we can apply Heckbert's locality criterion to quickly
  173093. * eliminate colormap entries that are far away from the subbox; typically
  173094. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  173095. * and we need not compute their distances to individual cells in the subbox.
  173096. * The speed of this approach is heavily influenced by the subbox size: too
  173097. * small means too much overhead, too big loses because Heckbert's criterion
  173098. * can't eliminate as many colormap entries. Empirically the best subbox
  173099. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  173100. *
  173101. * Thomas' article also describes a refined method which is asymptotically
  173102. * faster than the brute-force method, but it is also far more complex and
  173103. * cannot efficiently be applied to small subboxes. It is therefore not
  173104. * useful for programs intended to be portable to DOS machines. On machines
  173105. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  173106. * refined method might be faster than the present code --- but then again,
  173107. * it might not be any faster, and it's certainly more complicated.
  173108. */
  173109. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  173110. #define BOX_C0_LOG (HIST_C0_BITS-3)
  173111. #define BOX_C1_LOG (HIST_C1_BITS-3)
  173112. #define BOX_C2_LOG (HIST_C2_BITS-3)
  173113. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  173114. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  173115. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  173116. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  173117. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  173118. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  173119. /*
  173120. * The next three routines implement inverse colormap filling. They could
  173121. * all be folded into one big routine, but splitting them up this way saves
  173122. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  173123. * and may allow some compilers to produce better code by registerizing more
  173124. * inner-loop variables.
  173125. */
  173126. LOCAL(int)
  173127. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  173128. JSAMPLE colorlist[])
  173129. /* Locate the colormap entries close enough to an update box to be candidates
  173130. * for the nearest entry to some cell(s) in the update box. The update box
  173131. * is specified by the center coordinates of its first cell. The number of
  173132. * candidate colormap entries is returned, and their colormap indexes are
  173133. * placed in colorlist[].
  173134. * This routine uses Heckbert's "locally sorted search" criterion to select
  173135. * the colors that need further consideration.
  173136. */
  173137. {
  173138. int numcolors = cinfo->actual_number_of_colors;
  173139. int maxc0, maxc1, maxc2;
  173140. int centerc0, centerc1, centerc2;
  173141. int i, x, ncolors;
  173142. INT32 minmaxdist, min_dist, max_dist, tdist;
  173143. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  173144. /* Compute true coordinates of update box's upper corner and center.
  173145. * Actually we compute the coordinates of the center of the upper-corner
  173146. * histogram cell, which are the upper bounds of the volume we care about.
  173147. * Note that since ">>" rounds down, the "center" values may be closer to
  173148. * min than to max; hence comparisons to them must be "<=", not "<".
  173149. */
  173150. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  173151. centerc0 = (minc0 + maxc0) >> 1;
  173152. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  173153. centerc1 = (minc1 + maxc1) >> 1;
  173154. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  173155. centerc2 = (minc2 + maxc2) >> 1;
  173156. /* For each color in colormap, find:
  173157. * 1. its minimum squared-distance to any point in the update box
  173158. * (zero if color is within update box);
  173159. * 2. its maximum squared-distance to any point in the update box.
  173160. * Both of these can be found by considering only the corners of the box.
  173161. * We save the minimum distance for each color in mindist[];
  173162. * only the smallest maximum distance is of interest.
  173163. */
  173164. minmaxdist = 0x7FFFFFFFL;
  173165. for (i = 0; i < numcolors; i++) {
  173166. /* We compute the squared-c0-distance term, then add in the other two. */
  173167. x = GETJSAMPLE(cinfo->colormap[0][i]);
  173168. if (x < minc0) {
  173169. tdist = (x - minc0) * C0_SCALE;
  173170. min_dist = tdist*tdist;
  173171. tdist = (x - maxc0) * C0_SCALE;
  173172. max_dist = tdist*tdist;
  173173. } else if (x > maxc0) {
  173174. tdist = (x - maxc0) * C0_SCALE;
  173175. min_dist = tdist*tdist;
  173176. tdist = (x - minc0) * C0_SCALE;
  173177. max_dist = tdist*tdist;
  173178. } else {
  173179. /* within cell range so no contribution to min_dist */
  173180. min_dist = 0;
  173181. if (x <= centerc0) {
  173182. tdist = (x - maxc0) * C0_SCALE;
  173183. max_dist = tdist*tdist;
  173184. } else {
  173185. tdist = (x - minc0) * C0_SCALE;
  173186. max_dist = tdist*tdist;
  173187. }
  173188. }
  173189. x = GETJSAMPLE(cinfo->colormap[1][i]);
  173190. if (x < minc1) {
  173191. tdist = (x - minc1) * C1_SCALE;
  173192. min_dist += tdist*tdist;
  173193. tdist = (x - maxc1) * C1_SCALE;
  173194. max_dist += tdist*tdist;
  173195. } else if (x > maxc1) {
  173196. tdist = (x - maxc1) * C1_SCALE;
  173197. min_dist += tdist*tdist;
  173198. tdist = (x - minc1) * C1_SCALE;
  173199. max_dist += tdist*tdist;
  173200. } else {
  173201. /* within cell range so no contribution to min_dist */
  173202. if (x <= centerc1) {
  173203. tdist = (x - maxc1) * C1_SCALE;
  173204. max_dist += tdist*tdist;
  173205. } else {
  173206. tdist = (x - minc1) * C1_SCALE;
  173207. max_dist += tdist*tdist;
  173208. }
  173209. }
  173210. x = GETJSAMPLE(cinfo->colormap[2][i]);
  173211. if (x < minc2) {
  173212. tdist = (x - minc2) * C2_SCALE;
  173213. min_dist += tdist*tdist;
  173214. tdist = (x - maxc2) * C2_SCALE;
  173215. max_dist += tdist*tdist;
  173216. } else if (x > maxc2) {
  173217. tdist = (x - maxc2) * C2_SCALE;
  173218. min_dist += tdist*tdist;
  173219. tdist = (x - minc2) * C2_SCALE;
  173220. max_dist += tdist*tdist;
  173221. } else {
  173222. /* within cell range so no contribution to min_dist */
  173223. if (x <= centerc2) {
  173224. tdist = (x - maxc2) * C2_SCALE;
  173225. max_dist += tdist*tdist;
  173226. } else {
  173227. tdist = (x - minc2) * C2_SCALE;
  173228. max_dist += tdist*tdist;
  173229. }
  173230. }
  173231. mindist[i] = min_dist; /* save away the results */
  173232. if (max_dist < minmaxdist)
  173233. minmaxdist = max_dist;
  173234. }
  173235. /* Now we know that no cell in the update box is more than minmaxdist
  173236. * away from some colormap entry. Therefore, only colors that are
  173237. * within minmaxdist of some part of the box need be considered.
  173238. */
  173239. ncolors = 0;
  173240. for (i = 0; i < numcolors; i++) {
  173241. if (mindist[i] <= minmaxdist)
  173242. colorlist[ncolors++] = (JSAMPLE) i;
  173243. }
  173244. return ncolors;
  173245. }
  173246. LOCAL(void)
  173247. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  173248. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  173249. /* Find the closest colormap entry for each cell in the update box,
  173250. * given the list of candidate colors prepared by find_nearby_colors.
  173251. * Return the indexes of the closest entries in the bestcolor[] array.
  173252. * This routine uses Thomas' incremental distance calculation method to
  173253. * find the distance from a colormap entry to successive cells in the box.
  173254. */
  173255. {
  173256. int ic0, ic1, ic2;
  173257. int i, icolor;
  173258. register INT32 * bptr; /* pointer into bestdist[] array */
  173259. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  173260. INT32 dist0, dist1; /* initial distance values */
  173261. register INT32 dist2; /* current distance in inner loop */
  173262. INT32 xx0, xx1; /* distance increments */
  173263. register INT32 xx2;
  173264. INT32 inc0, inc1, inc2; /* initial values for increments */
  173265. /* This array holds the distance to the nearest-so-far color for each cell */
  173266. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  173267. /* Initialize best-distance for each cell of the update box */
  173268. bptr = bestdist;
  173269. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  173270. *bptr++ = 0x7FFFFFFFL;
  173271. /* For each color selected by find_nearby_colors,
  173272. * compute its distance to the center of each cell in the box.
  173273. * If that's less than best-so-far, update best distance and color number.
  173274. */
  173275. /* Nominal steps between cell centers ("x" in Thomas article) */
  173276. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  173277. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  173278. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  173279. for (i = 0; i < numcolors; i++) {
  173280. icolor = GETJSAMPLE(colorlist[i]);
  173281. /* Compute (square of) distance from minc0/c1/c2 to this color */
  173282. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  173283. dist0 = inc0*inc0;
  173284. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  173285. dist0 += inc1*inc1;
  173286. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  173287. dist0 += inc2*inc2;
  173288. /* Form the initial difference increments */
  173289. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  173290. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  173291. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  173292. /* Now loop over all cells in box, updating distance per Thomas method */
  173293. bptr = bestdist;
  173294. cptr = bestcolor;
  173295. xx0 = inc0;
  173296. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  173297. dist1 = dist0;
  173298. xx1 = inc1;
  173299. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  173300. dist2 = dist1;
  173301. xx2 = inc2;
  173302. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  173303. if (dist2 < *bptr) {
  173304. *bptr = dist2;
  173305. *cptr = (JSAMPLE) icolor;
  173306. }
  173307. dist2 += xx2;
  173308. xx2 += 2 * STEP_C2 * STEP_C2;
  173309. bptr++;
  173310. cptr++;
  173311. }
  173312. dist1 += xx1;
  173313. xx1 += 2 * STEP_C1 * STEP_C1;
  173314. }
  173315. dist0 += xx0;
  173316. xx0 += 2 * STEP_C0 * STEP_C0;
  173317. }
  173318. }
  173319. }
  173320. LOCAL(void)
  173321. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  173322. /* Fill the inverse-colormap entries in the update box that contains */
  173323. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  173324. /* we can fill as many others as we wish.) */
  173325. {
  173326. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173327. hist3d histogram = cquantize->histogram;
  173328. int minc0, minc1, minc2; /* lower left corner of update box */
  173329. int ic0, ic1, ic2;
  173330. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  173331. register histptr cachep; /* pointer into main cache array */
  173332. /* This array lists the candidate colormap indexes. */
  173333. JSAMPLE colorlist[MAXNUMCOLORS];
  173334. int numcolors; /* number of candidate colors */
  173335. /* This array holds the actually closest colormap index for each cell. */
  173336. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  173337. /* Convert cell coordinates to update box ID */
  173338. c0 >>= BOX_C0_LOG;
  173339. c1 >>= BOX_C1_LOG;
  173340. c2 >>= BOX_C2_LOG;
  173341. /* Compute true coordinates of update box's origin corner.
  173342. * Actually we compute the coordinates of the center of the corner
  173343. * histogram cell, which are the lower bounds of the volume we care about.
  173344. */
  173345. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  173346. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  173347. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  173348. /* Determine which colormap entries are close enough to be candidates
  173349. * for the nearest entry to some cell in the update box.
  173350. */
  173351. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  173352. /* Determine the actually nearest colors. */
  173353. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  173354. bestcolor);
  173355. /* Save the best color numbers (plus 1) in the main cache array */
  173356. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  173357. c1 <<= BOX_C1_LOG;
  173358. c2 <<= BOX_C2_LOG;
  173359. cptr = bestcolor;
  173360. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  173361. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  173362. cachep = & histogram[c0+ic0][c1+ic1][c2];
  173363. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  173364. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  173365. }
  173366. }
  173367. }
  173368. }
  173369. /*
  173370. * Map some rows of pixels to the output colormapped representation.
  173371. */
  173372. METHODDEF(void)
  173373. pass2_no_dither (j_decompress_ptr cinfo,
  173374. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  173375. /* This version performs no dithering */
  173376. {
  173377. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173378. hist3d histogram = cquantize->histogram;
  173379. register JSAMPROW inptr, outptr;
  173380. register histptr cachep;
  173381. register int c0, c1, c2;
  173382. int row;
  173383. JDIMENSION col;
  173384. JDIMENSION width = cinfo->output_width;
  173385. for (row = 0; row < num_rows; row++) {
  173386. inptr = input_buf[row];
  173387. outptr = output_buf[row];
  173388. for (col = width; col > 0; col--) {
  173389. /* get pixel value and index into the cache */
  173390. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  173391. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  173392. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  173393. cachep = & histogram[c0][c1][c2];
  173394. /* If we have not seen this color before, find nearest colormap entry */
  173395. /* and update the cache */
  173396. if (*cachep == 0)
  173397. fill_inverse_cmap(cinfo, c0,c1,c2);
  173398. /* Now emit the colormap index for this cell */
  173399. *outptr++ = (JSAMPLE) (*cachep - 1);
  173400. }
  173401. }
  173402. }
  173403. METHODDEF(void)
  173404. pass2_fs_dither (j_decompress_ptr cinfo,
  173405. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  173406. /* This version performs Floyd-Steinberg dithering */
  173407. {
  173408. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173409. hist3d histogram = cquantize->histogram;
  173410. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  173411. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  173412. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  173413. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  173414. JSAMPROW inptr; /* => current input pixel */
  173415. JSAMPROW outptr; /* => current output pixel */
  173416. histptr cachep;
  173417. int dir; /* +1 or -1 depending on direction */
  173418. int dir3; /* 3*dir, for advancing inptr & errorptr */
  173419. int row;
  173420. JDIMENSION col;
  173421. JDIMENSION width = cinfo->output_width;
  173422. JSAMPLE *range_limit = cinfo->sample_range_limit;
  173423. int *error_limit = cquantize->error_limiter;
  173424. JSAMPROW colormap0 = cinfo->colormap[0];
  173425. JSAMPROW colormap1 = cinfo->colormap[1];
  173426. JSAMPROW colormap2 = cinfo->colormap[2];
  173427. SHIFT_TEMPS
  173428. for (row = 0; row < num_rows; row++) {
  173429. inptr = input_buf[row];
  173430. outptr = output_buf[row];
  173431. if (cquantize->on_odd_row) {
  173432. /* work right to left in this row */
  173433. inptr += (width-1) * 3; /* so point to rightmost pixel */
  173434. outptr += width-1;
  173435. dir = -1;
  173436. dir3 = -3;
  173437. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  173438. cquantize->on_odd_row = FALSE; /* flip for next time */
  173439. } else {
  173440. /* work left to right in this row */
  173441. dir = 1;
  173442. dir3 = 3;
  173443. errorptr = cquantize->fserrors; /* => entry before first real column */
  173444. cquantize->on_odd_row = TRUE; /* flip for next time */
  173445. }
  173446. /* Preset error values: no error propagated to first pixel from left */
  173447. cur0 = cur1 = cur2 = 0;
  173448. /* and no error propagated to row below yet */
  173449. belowerr0 = belowerr1 = belowerr2 = 0;
  173450. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  173451. for (col = width; col > 0; col--) {
  173452. /* curN holds the error propagated from the previous pixel on the
  173453. * current line. Add the error propagated from the previous line
  173454. * to form the complete error correction term for this pixel, and
  173455. * round the error term (which is expressed * 16) to an integer.
  173456. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  173457. * for either sign of the error value.
  173458. * Note: errorptr points to *previous* column's array entry.
  173459. */
  173460. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  173461. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  173462. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  173463. /* Limit the error using transfer function set by init_error_limit.
  173464. * See comments with init_error_limit for rationale.
  173465. */
  173466. cur0 = error_limit[cur0];
  173467. cur1 = error_limit[cur1];
  173468. cur2 = error_limit[cur2];
  173469. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  173470. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  173471. * this sets the required size of the range_limit array.
  173472. */
  173473. cur0 += GETJSAMPLE(inptr[0]);
  173474. cur1 += GETJSAMPLE(inptr[1]);
  173475. cur2 += GETJSAMPLE(inptr[2]);
  173476. cur0 = GETJSAMPLE(range_limit[cur0]);
  173477. cur1 = GETJSAMPLE(range_limit[cur1]);
  173478. cur2 = GETJSAMPLE(range_limit[cur2]);
  173479. /* Index into the cache with adjusted pixel value */
  173480. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  173481. /* If we have not seen this color before, find nearest colormap */
  173482. /* entry and update the cache */
  173483. if (*cachep == 0)
  173484. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  173485. /* Now emit the colormap index for this cell */
  173486. { register int pixcode = *cachep - 1;
  173487. *outptr = (JSAMPLE) pixcode;
  173488. /* Compute representation error for this pixel */
  173489. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  173490. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  173491. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  173492. }
  173493. /* Compute error fractions to be propagated to adjacent pixels.
  173494. * Add these into the running sums, and simultaneously shift the
  173495. * next-line error sums left by 1 column.
  173496. */
  173497. { register LOCFSERROR bnexterr, delta;
  173498. bnexterr = cur0; /* Process component 0 */
  173499. delta = cur0 * 2;
  173500. cur0 += delta; /* form error * 3 */
  173501. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  173502. cur0 += delta; /* form error * 5 */
  173503. bpreverr0 = belowerr0 + cur0;
  173504. belowerr0 = bnexterr;
  173505. cur0 += delta; /* form error * 7 */
  173506. bnexterr = cur1; /* Process component 1 */
  173507. delta = cur1 * 2;
  173508. cur1 += delta; /* form error * 3 */
  173509. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  173510. cur1 += delta; /* form error * 5 */
  173511. bpreverr1 = belowerr1 + cur1;
  173512. belowerr1 = bnexterr;
  173513. cur1 += delta; /* form error * 7 */
  173514. bnexterr = cur2; /* Process component 2 */
  173515. delta = cur2 * 2;
  173516. cur2 += delta; /* form error * 3 */
  173517. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  173518. cur2 += delta; /* form error * 5 */
  173519. bpreverr2 = belowerr2 + cur2;
  173520. belowerr2 = bnexterr;
  173521. cur2 += delta; /* form error * 7 */
  173522. }
  173523. /* At this point curN contains the 7/16 error value to be propagated
  173524. * to the next pixel on the current line, and all the errors for the
  173525. * next line have been shifted over. We are therefore ready to move on.
  173526. */
  173527. inptr += dir3; /* Advance pixel pointers to next column */
  173528. outptr += dir;
  173529. errorptr += dir3; /* advance errorptr to current column */
  173530. }
  173531. /* Post-loop cleanup: we must unload the final error values into the
  173532. * final fserrors[] entry. Note we need not unload belowerrN because
  173533. * it is for the dummy column before or after the actual array.
  173534. */
  173535. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  173536. errorptr[1] = (FSERROR) bpreverr1;
  173537. errorptr[2] = (FSERROR) bpreverr2;
  173538. }
  173539. }
  173540. /*
  173541. * Initialize the error-limiting transfer function (lookup table).
  173542. * The raw F-S error computation can potentially compute error values of up to
  173543. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  173544. * much less, otherwise obviously wrong pixels will be created. (Typical
  173545. * effects include weird fringes at color-area boundaries, isolated bright
  173546. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  173547. * is to ensure that the "corners" of the color cube are allocated as output
  173548. * colors; then repeated errors in the same direction cannot cause cascading
  173549. * error buildup. However, that only prevents the error from getting
  173550. * completely out of hand; Aaron Giles reports that error limiting improves
  173551. * the results even with corner colors allocated.
  173552. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  173553. * well, but the smoother transfer function used below is even better. Thanks
  173554. * to Aaron Giles for this idea.
  173555. */
  173556. LOCAL(void)
  173557. init_error_limit (j_decompress_ptr cinfo)
  173558. /* Allocate and fill in the error_limiter table */
  173559. {
  173560. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173561. int * table;
  173562. int in, out;
  173563. table = (int *) (*cinfo->mem->alloc_small)
  173564. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  173565. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  173566. cquantize->error_limiter = table;
  173567. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  173568. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  173569. out = 0;
  173570. for (in = 0; in < STEPSIZE; in++, out++) {
  173571. table[in] = out; table[-in] = -out;
  173572. }
  173573. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  173574. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  173575. table[in] = out; table[-in] = -out;
  173576. }
  173577. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  173578. for (; in <= MAXJSAMPLE; in++) {
  173579. table[in] = out; table[-in] = -out;
  173580. }
  173581. #undef STEPSIZE
  173582. }
  173583. /*
  173584. * Finish up at the end of each pass.
  173585. */
  173586. METHODDEF(void)
  173587. finish_pass1 (j_decompress_ptr cinfo)
  173588. {
  173589. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173590. /* Select the representative colors and fill in cinfo->colormap */
  173591. cinfo->colormap = cquantize->sv_colormap;
  173592. select_colors(cinfo, cquantize->desired);
  173593. /* Force next pass to zero the color index table */
  173594. cquantize->needs_zeroed = TRUE;
  173595. }
  173596. METHODDEF(void)
  173597. finish_pass2 (j_decompress_ptr cinfo)
  173598. {
  173599. /* no work */
  173600. }
  173601. /*
  173602. * Initialize for each processing pass.
  173603. */
  173604. METHODDEF(void)
  173605. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  173606. {
  173607. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173608. hist3d histogram = cquantize->histogram;
  173609. int i;
  173610. /* Only F-S dithering or no dithering is supported. */
  173611. /* If user asks for ordered dither, give him F-S. */
  173612. if (cinfo->dither_mode != JDITHER_NONE)
  173613. cinfo->dither_mode = JDITHER_FS;
  173614. if (is_pre_scan) {
  173615. /* Set up method pointers */
  173616. cquantize->pub.color_quantize = prescan_quantize;
  173617. cquantize->pub.finish_pass = finish_pass1;
  173618. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  173619. } else {
  173620. /* Set up method pointers */
  173621. if (cinfo->dither_mode == JDITHER_FS)
  173622. cquantize->pub.color_quantize = pass2_fs_dither;
  173623. else
  173624. cquantize->pub.color_quantize = pass2_no_dither;
  173625. cquantize->pub.finish_pass = finish_pass2;
  173626. /* Make sure color count is acceptable */
  173627. i = cinfo->actual_number_of_colors;
  173628. if (i < 1)
  173629. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  173630. if (i > MAXNUMCOLORS)
  173631. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  173632. if (cinfo->dither_mode == JDITHER_FS) {
  173633. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  173634. (3 * SIZEOF(FSERROR)));
  173635. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  173636. if (cquantize->fserrors == NULL)
  173637. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  173638. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  173639. /* Initialize the propagated errors to zero. */
  173640. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  173641. /* Make the error-limit table if we didn't already. */
  173642. if (cquantize->error_limiter == NULL)
  173643. init_error_limit(cinfo);
  173644. cquantize->on_odd_row = FALSE;
  173645. }
  173646. }
  173647. /* Zero the histogram or inverse color map, if necessary */
  173648. if (cquantize->needs_zeroed) {
  173649. for (i = 0; i < HIST_C0_ELEMS; i++) {
  173650. jzero_far((void FAR *) histogram[i],
  173651. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  173652. }
  173653. cquantize->needs_zeroed = FALSE;
  173654. }
  173655. }
  173656. /*
  173657. * Switch to a new external colormap between output passes.
  173658. */
  173659. METHODDEF(void)
  173660. new_color_map_2_quant (j_decompress_ptr cinfo)
  173661. {
  173662. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173663. /* Reset the inverse color map */
  173664. cquantize->needs_zeroed = TRUE;
  173665. }
  173666. /*
  173667. * Module initialization routine for 2-pass color quantization.
  173668. */
  173669. GLOBAL(void)
  173670. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  173671. {
  173672. my_cquantize_ptr2 cquantize;
  173673. int i;
  173674. cquantize = (my_cquantize_ptr2)
  173675. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173676. SIZEOF(my_cquantizer2));
  173677. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  173678. cquantize->pub.start_pass = start_pass_2_quant;
  173679. cquantize->pub.new_color_map = new_color_map_2_quant;
  173680. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  173681. cquantize->error_limiter = NULL;
  173682. /* Make sure jdmaster didn't give me a case I can't handle */
  173683. if (cinfo->out_color_components != 3)
  173684. ERREXIT(cinfo, JERR_NOTIMPL);
  173685. /* Allocate the histogram/inverse colormap storage */
  173686. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  173687. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  173688. for (i = 0; i < HIST_C0_ELEMS; i++) {
  173689. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  173690. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173691. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  173692. }
  173693. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  173694. /* Allocate storage for the completed colormap, if required.
  173695. * We do this now since it is FAR storage and may affect
  173696. * the memory manager's space calculations.
  173697. */
  173698. if (cinfo->enable_2pass_quant) {
  173699. /* Make sure color count is acceptable */
  173700. int desired = cinfo->desired_number_of_colors;
  173701. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  173702. if (desired < 8)
  173703. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  173704. /* Make sure colormap indexes can be represented by JSAMPLEs */
  173705. if (desired > MAXNUMCOLORS)
  173706. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  173707. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  173708. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  173709. cquantize->desired = desired;
  173710. } else
  173711. cquantize->sv_colormap = NULL;
  173712. /* Only F-S dithering or no dithering is supported. */
  173713. /* If user asks for ordered dither, give him F-S. */
  173714. if (cinfo->dither_mode != JDITHER_NONE)
  173715. cinfo->dither_mode = JDITHER_FS;
  173716. /* Allocate Floyd-Steinberg workspace if necessary.
  173717. * This isn't really needed until pass 2, but again it is FAR storage.
  173718. * Although we will cope with a later change in dither_mode,
  173719. * we do not promise to honor max_memory_to_use if dither_mode changes.
  173720. */
  173721. if (cinfo->dither_mode == JDITHER_FS) {
  173722. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  173723. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173724. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  173725. /* Might as well create the error-limiting table too. */
  173726. init_error_limit(cinfo);
  173727. }
  173728. }
  173729. #endif /* QUANT_2PASS_SUPPORTED */
  173730. /********* End of inlined file: jquant2.c *********/
  173731. /********* Start of inlined file: jutils.c *********/
  173732. #define JPEG_INTERNALS
  173733. /*
  173734. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  173735. * of a DCT block read in natural order (left to right, top to bottom).
  173736. */
  173737. #if 0 /* This table is not actually needed in v6a */
  173738. const int jpeg_zigzag_order[DCTSIZE2] = {
  173739. 0, 1, 5, 6, 14, 15, 27, 28,
  173740. 2, 4, 7, 13, 16, 26, 29, 42,
  173741. 3, 8, 12, 17, 25, 30, 41, 43,
  173742. 9, 11, 18, 24, 31, 40, 44, 53,
  173743. 10, 19, 23, 32, 39, 45, 52, 54,
  173744. 20, 22, 33, 38, 46, 51, 55, 60,
  173745. 21, 34, 37, 47, 50, 56, 59, 61,
  173746. 35, 36, 48, 49, 57, 58, 62, 63
  173747. };
  173748. #endif
  173749. /*
  173750. * jpeg_natural_order[i] is the natural-order position of the i'th element
  173751. * of zigzag order.
  173752. *
  173753. * When reading corrupted data, the Huffman decoders could attempt
  173754. * to reference an entry beyond the end of this array (if the decoded
  173755. * zero run length reaches past the end of the block). To prevent
  173756. * wild stores without adding an inner-loop test, we put some extra
  173757. * "63"s after the real entries. This will cause the extra coefficient
  173758. * to be stored in location 63 of the block, not somewhere random.
  173759. * The worst case would be a run-length of 15, which means we need 16
  173760. * fake entries.
  173761. */
  173762. const int jpeg_natural_order[DCTSIZE2+16] = {
  173763. 0, 1, 8, 16, 9, 2, 3, 10,
  173764. 17, 24, 32, 25, 18, 11, 4, 5,
  173765. 12, 19, 26, 33, 40, 48, 41, 34,
  173766. 27, 20, 13, 6, 7, 14, 21, 28,
  173767. 35, 42, 49, 56, 57, 50, 43, 36,
  173768. 29, 22, 15, 23, 30, 37, 44, 51,
  173769. 58, 59, 52, 45, 38, 31, 39, 46,
  173770. 53, 60, 61, 54, 47, 55, 62, 63,
  173771. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  173772. 63, 63, 63, 63, 63, 63, 63, 63
  173773. };
  173774. /*
  173775. * Arithmetic utilities
  173776. */
  173777. GLOBAL(long)
  173778. jdiv_round_up (long a, long b)
  173779. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  173780. /* Assumes a >= 0, b > 0 */
  173781. {
  173782. return (a + b - 1L) / b;
  173783. }
  173784. GLOBAL(long)
  173785. jround_up (long a, long b)
  173786. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  173787. /* Assumes a >= 0, b > 0 */
  173788. {
  173789. a += b - 1L;
  173790. return a - (a % b);
  173791. }
  173792. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  173793. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  173794. * are FAR and we're assuming a small-pointer memory model. However, some
  173795. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  173796. * in the small-model libraries. These will be used if USE_FMEM is defined.
  173797. * Otherwise, the routines below do it the hard way. (The performance cost
  173798. * is not all that great, because these routines aren't very heavily used.)
  173799. */
  173800. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  173801. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  173802. #define FMEMZERO(target,size) MEMZERO(target,size)
  173803. #else /* 80x86 case, define if we can */
  173804. #ifdef USE_FMEM
  173805. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  173806. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  173807. #endif
  173808. #endif
  173809. GLOBAL(void)
  173810. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  173811. JSAMPARRAY output_array, int dest_row,
  173812. int num_rows, JDIMENSION num_cols)
  173813. /* Copy some rows of samples from one place to another.
  173814. * num_rows rows are copied from input_array[source_row++]
  173815. * to output_array[dest_row++]; these areas may overlap for duplication.
  173816. * The source and destination arrays must be at least as wide as num_cols.
  173817. */
  173818. {
  173819. register JSAMPROW inptr, outptr;
  173820. #ifdef FMEMCOPY
  173821. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  173822. #else
  173823. register JDIMENSION count;
  173824. #endif
  173825. register int row;
  173826. input_array += source_row;
  173827. output_array += dest_row;
  173828. for (row = num_rows; row > 0; row--) {
  173829. inptr = *input_array++;
  173830. outptr = *output_array++;
  173831. #ifdef FMEMCOPY
  173832. FMEMCOPY(outptr, inptr, count);
  173833. #else
  173834. for (count = num_cols; count > 0; count--)
  173835. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  173836. #endif
  173837. }
  173838. }
  173839. GLOBAL(void)
  173840. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  173841. JDIMENSION num_blocks)
  173842. /* Copy a row of coefficient blocks from one place to another. */
  173843. {
  173844. #ifdef FMEMCOPY
  173845. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  173846. #else
  173847. register JCOEFPTR inptr, outptr;
  173848. register long count;
  173849. inptr = (JCOEFPTR) input_row;
  173850. outptr = (JCOEFPTR) output_row;
  173851. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  173852. *outptr++ = *inptr++;
  173853. }
  173854. #endif
  173855. }
  173856. GLOBAL(void)
  173857. jzero_far (void FAR * target, size_t bytestozero)
  173858. /* Zero out a chunk of FAR memory. */
  173859. /* This might be sample-array data, block-array data, or alloc_large data. */
  173860. {
  173861. #ifdef FMEMZERO
  173862. FMEMZERO(target, bytestozero);
  173863. #else
  173864. register char FAR * ptr = (char FAR *) target;
  173865. register size_t count;
  173866. for (count = bytestozero; count > 0; count--) {
  173867. *ptr++ = 0;
  173868. }
  173869. #endif
  173870. }
  173871. /********* End of inlined file: jutils.c *********/
  173872. /********* Start of inlined file: transupp.c *********/
  173873. /* Although this file really shouldn't have access to the library internals,
  173874. * it's helpful to let it call jround_up() and jcopy_block_row().
  173875. */
  173876. #define JPEG_INTERNALS
  173877. /********* Start of inlined file: transupp.h *********/
  173878. /* If you happen not to want the image transform support, disable it here */
  173879. #ifndef TRANSFORMS_SUPPORTED
  173880. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  173881. #endif
  173882. /* Short forms of external names for systems with brain-damaged linkers. */
  173883. #ifdef NEED_SHORT_EXTERNAL_NAMES
  173884. #define jtransform_request_workspace jTrRequest
  173885. #define jtransform_adjust_parameters jTrAdjust
  173886. #define jtransform_execute_transformation jTrExec
  173887. #define jcopy_markers_setup jCMrkSetup
  173888. #define jcopy_markers_execute jCMrkExec
  173889. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  173890. /*
  173891. * Codes for supported types of image transformations.
  173892. */
  173893. typedef enum {
  173894. JXFORM_NONE, /* no transformation */
  173895. JXFORM_FLIP_H, /* horizontal flip */
  173896. JXFORM_FLIP_V, /* vertical flip */
  173897. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  173898. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  173899. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  173900. JXFORM_ROT_180, /* 180-degree rotation */
  173901. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  173902. } JXFORM_CODE;
  173903. /*
  173904. * Although rotating and flipping data expressed as DCT coefficients is not
  173905. * hard, there is an asymmetry in the JPEG format specification for images
  173906. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  173907. * image edges are padded out to the next iMCU boundary with junk data; but
  173908. * no padding is possible at the top and left edges. If we were to flip
  173909. * the whole image including the pad data, then pad garbage would become
  173910. * visible at the top and/or left, and real pixels would disappear into the
  173911. * pad margins --- perhaps permanently, since encoders & decoders may not
  173912. * bother to preserve DCT blocks that appear to be completely outside the
  173913. * nominal image area. So, we have to exclude any partial iMCUs from the
  173914. * basic transformation.
  173915. *
  173916. * Transpose is the only transformation that can handle partial iMCUs at the
  173917. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  173918. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  173919. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  173920. * The other transforms are defined as combinations of these basic transforms
  173921. * and process edge blocks in a way that preserves the equivalence.
  173922. *
  173923. * The "trim" option causes untransformable partial iMCUs to be dropped;
  173924. * this is not strictly lossless, but it usually gives the best-looking
  173925. * result for odd-size images. Note that when this option is active,
  173926. * the expected mathematical equivalences between the transforms may not hold.
  173927. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  173928. * followed by -rot 180 -trim trims both edges.)
  173929. *
  173930. * We also offer a "force to grayscale" option, which simply discards the
  173931. * chrominance channels of a YCbCr image. This is lossless in the sense that
  173932. * the luminance channel is preserved exactly. It's not the same kind of
  173933. * thing as the rotate/flip transformations, but it's convenient to handle it
  173934. * as part of this package, mainly because the transformation routines have to
  173935. * be aware of the option to know how many components to work on.
  173936. */
  173937. typedef struct {
  173938. /* Options: set by caller */
  173939. JXFORM_CODE transform; /* image transform operator */
  173940. boolean trim; /* if TRUE, trim partial MCUs as needed */
  173941. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  173942. /* Internal workspace: caller should not touch these */
  173943. int num_components; /* # of components in workspace */
  173944. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  173945. } jpeg_transform_info;
  173946. #if TRANSFORMS_SUPPORTED
  173947. /* Request any required workspace */
  173948. EXTERN(void) jtransform_request_workspace
  173949. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  173950. /* Adjust output image parameters */
  173951. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  173952. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173953. jvirt_barray_ptr *src_coef_arrays,
  173954. jpeg_transform_info *info));
  173955. /* Execute the actual transformation, if any */
  173956. EXTERN(void) jtransform_execute_transformation
  173957. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173958. jvirt_barray_ptr *src_coef_arrays,
  173959. jpeg_transform_info *info));
  173960. #endif /* TRANSFORMS_SUPPORTED */
  173961. /*
  173962. * Support for copying optional markers from source to destination file.
  173963. */
  173964. typedef enum {
  173965. JCOPYOPT_NONE, /* copy no optional markers */
  173966. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  173967. JCOPYOPT_ALL /* copy all optional markers */
  173968. } JCOPY_OPTION;
  173969. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  173970. /* Setup decompression object to save desired markers in memory */
  173971. EXTERN(void) jcopy_markers_setup
  173972. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  173973. /* Copy markers saved in the given source object to the destination object */
  173974. EXTERN(void) jcopy_markers_execute
  173975. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173976. JCOPY_OPTION option));
  173977. /********* End of inlined file: transupp.h *********/
  173978. /* My own external interface */
  173979. #if TRANSFORMS_SUPPORTED
  173980. /*
  173981. * Lossless image transformation routines. These routines work on DCT
  173982. * coefficient arrays and thus do not require any lossy decompression
  173983. * or recompression of the image.
  173984. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  173985. *
  173986. * Horizontal flipping is done in-place, using a single top-to-bottom
  173987. * pass through the virtual source array. It will thus be much the
  173988. * fastest option for images larger than main memory.
  173989. *
  173990. * The other routines require a set of destination virtual arrays, so they
  173991. * need twice as much memory as jpegtran normally does. The destination
  173992. * arrays are always written in normal scan order (top to bottom) because
  173993. * the virtual array manager expects this. The source arrays will be scanned
  173994. * in the corresponding order, which means multiple passes through the source
  173995. * arrays for most of the transforms. That could result in much thrashing
  173996. * if the image is larger than main memory.
  173997. *
  173998. * Some notes about the operating environment of the individual transform
  173999. * routines:
  174000. * 1. Both the source and destination virtual arrays are allocated from the
  174001. * source JPEG object, and therefore should be manipulated by calling the
  174002. * source's memory manager.
  174003. * 2. The destination's component count should be used. It may be smaller
  174004. * than the source's when forcing to grayscale.
  174005. * 3. Likewise the destination's sampling factors should be used. When
  174006. * forcing to grayscale the destination's sampling factors will be all 1,
  174007. * and we may as well take that as the effective iMCU size.
  174008. * 4. When "trim" is in effect, the destination's dimensions will be the
  174009. * trimmed values but the source's will be untrimmed.
  174010. * 5. All the routines assume that the source and destination buffers are
  174011. * padded out to a full iMCU boundary. This is true, although for the
  174012. * source buffer it is an undocumented property of jdcoefct.c.
  174013. * Notes 2,3,4 boil down to this: generally we should use the destination's
  174014. * dimensions and ignore the source's.
  174015. */
  174016. LOCAL(void)
  174017. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174018. jvirt_barray_ptr *src_coef_arrays)
  174019. /* Horizontal flip; done in-place, so no separate dest array is required */
  174020. {
  174021. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  174022. int ci, k, offset_y;
  174023. JBLOCKARRAY buffer;
  174024. JCOEFPTR ptr1, ptr2;
  174025. JCOEF temp1, temp2;
  174026. jpeg_component_info *compptr;
  174027. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  174028. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  174029. * mirroring by changing the signs of odd-numbered columns.
  174030. * Partial iMCUs at the right edge are left untouched.
  174031. */
  174032. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174033. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174034. compptr = dstinfo->comp_info + ci;
  174035. comp_width = MCU_cols * compptr->h_samp_factor;
  174036. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  174037. blk_y += compptr->v_samp_factor) {
  174038. buffer = (*srcinfo->mem->access_virt_barray)
  174039. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  174040. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174041. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174042. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  174043. ptr1 = buffer[offset_y][blk_x];
  174044. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  174045. /* this unrolled loop doesn't need to know which row it's on... */
  174046. for (k = 0; k < DCTSIZE2; k += 2) {
  174047. temp1 = *ptr1; /* swap even column */
  174048. temp2 = *ptr2;
  174049. *ptr1++ = temp2;
  174050. *ptr2++ = temp1;
  174051. temp1 = *ptr1; /* swap odd column with sign change */
  174052. temp2 = *ptr2;
  174053. *ptr1++ = -temp2;
  174054. *ptr2++ = -temp1;
  174055. }
  174056. }
  174057. }
  174058. }
  174059. }
  174060. }
  174061. LOCAL(void)
  174062. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174063. jvirt_barray_ptr *src_coef_arrays,
  174064. jvirt_barray_ptr *dst_coef_arrays)
  174065. /* Vertical flip */
  174066. {
  174067. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  174068. int ci, i, j, offset_y;
  174069. JBLOCKARRAY src_buffer, dst_buffer;
  174070. JBLOCKROW src_row_ptr, dst_row_ptr;
  174071. JCOEFPTR src_ptr, dst_ptr;
  174072. jpeg_component_info *compptr;
  174073. /* We output into a separate array because we can't touch different
  174074. * rows of the source virtual array simultaneously. Otherwise, this
  174075. * is a pretty straightforward analog of horizontal flip.
  174076. * Within a DCT block, vertical mirroring is done by changing the signs
  174077. * of odd-numbered rows.
  174078. * Partial iMCUs at the bottom edge are copied verbatim.
  174079. */
  174080. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174081. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174082. compptr = dstinfo->comp_info + ci;
  174083. comp_height = MCU_rows * compptr->v_samp_factor;
  174084. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174085. dst_blk_y += compptr->v_samp_factor) {
  174086. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174087. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174088. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174089. if (dst_blk_y < comp_height) {
  174090. /* Row is within the mirrorable area. */
  174091. src_buffer = (*srcinfo->mem->access_virt_barray)
  174092. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  174093. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  174094. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174095. } else {
  174096. /* Bottom-edge blocks will be copied verbatim. */
  174097. src_buffer = (*srcinfo->mem->access_virt_barray)
  174098. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  174099. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174100. }
  174101. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174102. if (dst_blk_y < comp_height) {
  174103. /* Row is within the mirrorable area. */
  174104. dst_row_ptr = dst_buffer[offset_y];
  174105. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  174106. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174107. dst_blk_x++) {
  174108. dst_ptr = dst_row_ptr[dst_blk_x];
  174109. src_ptr = src_row_ptr[dst_blk_x];
  174110. for (i = 0; i < DCTSIZE; i += 2) {
  174111. /* copy even row */
  174112. for (j = 0; j < DCTSIZE; j++)
  174113. *dst_ptr++ = *src_ptr++;
  174114. /* copy odd row with sign change */
  174115. for (j = 0; j < DCTSIZE; j++)
  174116. *dst_ptr++ = - *src_ptr++;
  174117. }
  174118. }
  174119. } else {
  174120. /* Just copy row verbatim. */
  174121. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  174122. compptr->width_in_blocks);
  174123. }
  174124. }
  174125. }
  174126. }
  174127. }
  174128. LOCAL(void)
  174129. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174130. jvirt_barray_ptr *src_coef_arrays,
  174131. jvirt_barray_ptr *dst_coef_arrays)
  174132. /* Transpose source into destination */
  174133. {
  174134. JDIMENSION dst_blk_x, dst_blk_y;
  174135. int ci, i, j, offset_x, offset_y;
  174136. JBLOCKARRAY src_buffer, dst_buffer;
  174137. JCOEFPTR src_ptr, dst_ptr;
  174138. jpeg_component_info *compptr;
  174139. /* Transposing pixels within a block just requires transposing the
  174140. * DCT coefficients.
  174141. * Partial iMCUs at the edges require no special treatment; we simply
  174142. * process all the available DCT blocks for every component.
  174143. */
  174144. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174145. compptr = dstinfo->comp_info + ci;
  174146. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174147. dst_blk_y += compptr->v_samp_factor) {
  174148. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174149. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174150. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174151. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174152. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174153. dst_blk_x += compptr->h_samp_factor) {
  174154. src_buffer = (*srcinfo->mem->access_virt_barray)
  174155. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174156. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174157. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174158. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174159. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174160. for (i = 0; i < DCTSIZE; i++)
  174161. for (j = 0; j < DCTSIZE; j++)
  174162. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174163. }
  174164. }
  174165. }
  174166. }
  174167. }
  174168. }
  174169. LOCAL(void)
  174170. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174171. jvirt_barray_ptr *src_coef_arrays,
  174172. jvirt_barray_ptr *dst_coef_arrays)
  174173. /* 90 degree rotation is equivalent to
  174174. * 1. Transposing the image;
  174175. * 2. Horizontal mirroring.
  174176. * These two steps are merged into a single processing routine.
  174177. */
  174178. {
  174179. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  174180. int ci, i, j, offset_x, offset_y;
  174181. JBLOCKARRAY src_buffer, dst_buffer;
  174182. JCOEFPTR src_ptr, dst_ptr;
  174183. jpeg_component_info *compptr;
  174184. /* Because of the horizontal mirror step, we can't process partial iMCUs
  174185. * at the (output) right edge properly. They just get transposed and
  174186. * not mirrored.
  174187. */
  174188. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174189. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174190. compptr = dstinfo->comp_info + ci;
  174191. comp_width = MCU_cols * compptr->h_samp_factor;
  174192. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174193. dst_blk_y += compptr->v_samp_factor) {
  174194. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174195. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174196. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174197. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174198. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174199. dst_blk_x += compptr->h_samp_factor) {
  174200. src_buffer = (*srcinfo->mem->access_virt_barray)
  174201. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174202. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174203. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174204. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174205. if (dst_blk_x < comp_width) {
  174206. /* Block is within the mirrorable area. */
  174207. dst_ptr = dst_buffer[offset_y]
  174208. [comp_width - dst_blk_x - offset_x - 1];
  174209. for (i = 0; i < DCTSIZE; i++) {
  174210. for (j = 0; j < DCTSIZE; j++)
  174211. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174212. i++;
  174213. for (j = 0; j < DCTSIZE; j++)
  174214. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174215. }
  174216. } else {
  174217. /* Edge blocks are transposed but not mirrored. */
  174218. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174219. for (i = 0; i < DCTSIZE; i++)
  174220. for (j = 0; j < DCTSIZE; j++)
  174221. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174222. }
  174223. }
  174224. }
  174225. }
  174226. }
  174227. }
  174228. }
  174229. LOCAL(void)
  174230. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174231. jvirt_barray_ptr *src_coef_arrays,
  174232. jvirt_barray_ptr *dst_coef_arrays)
  174233. /* 270 degree rotation is equivalent to
  174234. * 1. Horizontal mirroring;
  174235. * 2. Transposing the image.
  174236. * These two steps are merged into a single processing routine.
  174237. */
  174238. {
  174239. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  174240. int ci, i, j, offset_x, offset_y;
  174241. JBLOCKARRAY src_buffer, dst_buffer;
  174242. JCOEFPTR src_ptr, dst_ptr;
  174243. jpeg_component_info *compptr;
  174244. /* Because of the horizontal mirror step, we can't process partial iMCUs
  174245. * at the (output) bottom edge properly. They just get transposed and
  174246. * not mirrored.
  174247. */
  174248. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174249. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174250. compptr = dstinfo->comp_info + ci;
  174251. comp_height = MCU_rows * compptr->v_samp_factor;
  174252. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174253. dst_blk_y += compptr->v_samp_factor) {
  174254. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174255. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174256. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174257. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174258. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174259. dst_blk_x += compptr->h_samp_factor) {
  174260. src_buffer = (*srcinfo->mem->access_virt_barray)
  174261. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174262. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174263. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174264. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174265. if (dst_blk_y < comp_height) {
  174266. /* Block is within the mirrorable area. */
  174267. src_ptr = src_buffer[offset_x]
  174268. [comp_height - dst_blk_y - offset_y - 1];
  174269. for (i = 0; i < DCTSIZE; i++) {
  174270. for (j = 0; j < DCTSIZE; j++) {
  174271. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174272. j++;
  174273. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174274. }
  174275. }
  174276. } else {
  174277. /* Edge blocks are transposed but not mirrored. */
  174278. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174279. for (i = 0; i < DCTSIZE; i++)
  174280. for (j = 0; j < DCTSIZE; j++)
  174281. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174282. }
  174283. }
  174284. }
  174285. }
  174286. }
  174287. }
  174288. }
  174289. LOCAL(void)
  174290. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174291. jvirt_barray_ptr *src_coef_arrays,
  174292. jvirt_barray_ptr *dst_coef_arrays)
  174293. /* 180 degree rotation is equivalent to
  174294. * 1. Vertical mirroring;
  174295. * 2. Horizontal mirroring.
  174296. * These two steps are merged into a single processing routine.
  174297. */
  174298. {
  174299. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  174300. int ci, i, j, offset_y;
  174301. JBLOCKARRAY src_buffer, dst_buffer;
  174302. JBLOCKROW src_row_ptr, dst_row_ptr;
  174303. JCOEFPTR src_ptr, dst_ptr;
  174304. jpeg_component_info *compptr;
  174305. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174306. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174307. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174308. compptr = dstinfo->comp_info + ci;
  174309. comp_width = MCU_cols * compptr->h_samp_factor;
  174310. comp_height = MCU_rows * compptr->v_samp_factor;
  174311. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174312. dst_blk_y += compptr->v_samp_factor) {
  174313. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174314. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174315. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174316. if (dst_blk_y < comp_height) {
  174317. /* Row is within the vertically mirrorable area. */
  174318. src_buffer = (*srcinfo->mem->access_virt_barray)
  174319. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  174320. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  174321. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174322. } else {
  174323. /* Bottom-edge rows are only mirrored horizontally. */
  174324. src_buffer = (*srcinfo->mem->access_virt_barray)
  174325. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  174326. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174327. }
  174328. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174329. if (dst_blk_y < comp_height) {
  174330. /* Row is within the mirrorable area. */
  174331. dst_row_ptr = dst_buffer[offset_y];
  174332. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  174333. /* Process the blocks that can be mirrored both ways. */
  174334. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  174335. dst_ptr = dst_row_ptr[dst_blk_x];
  174336. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  174337. for (i = 0; i < DCTSIZE; i += 2) {
  174338. /* For even row, negate every odd column. */
  174339. for (j = 0; j < DCTSIZE; j += 2) {
  174340. *dst_ptr++ = *src_ptr++;
  174341. *dst_ptr++ = - *src_ptr++;
  174342. }
  174343. /* For odd row, negate every even column. */
  174344. for (j = 0; j < DCTSIZE; j += 2) {
  174345. *dst_ptr++ = - *src_ptr++;
  174346. *dst_ptr++ = *src_ptr++;
  174347. }
  174348. }
  174349. }
  174350. /* Any remaining right-edge blocks are only mirrored vertically. */
  174351. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  174352. dst_ptr = dst_row_ptr[dst_blk_x];
  174353. src_ptr = src_row_ptr[dst_blk_x];
  174354. for (i = 0; i < DCTSIZE; i += 2) {
  174355. for (j = 0; j < DCTSIZE; j++)
  174356. *dst_ptr++ = *src_ptr++;
  174357. for (j = 0; j < DCTSIZE; j++)
  174358. *dst_ptr++ = - *src_ptr++;
  174359. }
  174360. }
  174361. } else {
  174362. /* Remaining rows are just mirrored horizontally. */
  174363. dst_row_ptr = dst_buffer[offset_y];
  174364. src_row_ptr = src_buffer[offset_y];
  174365. /* Process the blocks that can be mirrored. */
  174366. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  174367. dst_ptr = dst_row_ptr[dst_blk_x];
  174368. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  174369. for (i = 0; i < DCTSIZE2; i += 2) {
  174370. *dst_ptr++ = *src_ptr++;
  174371. *dst_ptr++ = - *src_ptr++;
  174372. }
  174373. }
  174374. /* Any remaining right-edge blocks are only copied. */
  174375. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  174376. dst_ptr = dst_row_ptr[dst_blk_x];
  174377. src_ptr = src_row_ptr[dst_blk_x];
  174378. for (i = 0; i < DCTSIZE2; i++)
  174379. *dst_ptr++ = *src_ptr++;
  174380. }
  174381. }
  174382. }
  174383. }
  174384. }
  174385. }
  174386. LOCAL(void)
  174387. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174388. jvirt_barray_ptr *src_coef_arrays,
  174389. jvirt_barray_ptr *dst_coef_arrays)
  174390. /* Transverse transpose is equivalent to
  174391. * 1. 180 degree rotation;
  174392. * 2. Transposition;
  174393. * or
  174394. * 1. Horizontal mirroring;
  174395. * 2. Transposition;
  174396. * 3. Horizontal mirroring.
  174397. * These steps are merged into a single processing routine.
  174398. */
  174399. {
  174400. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  174401. int ci, i, j, offset_x, offset_y;
  174402. JBLOCKARRAY src_buffer, dst_buffer;
  174403. JCOEFPTR src_ptr, dst_ptr;
  174404. jpeg_component_info *compptr;
  174405. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174406. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174407. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174408. compptr = dstinfo->comp_info + ci;
  174409. comp_width = MCU_cols * compptr->h_samp_factor;
  174410. comp_height = MCU_rows * compptr->v_samp_factor;
  174411. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174412. dst_blk_y += compptr->v_samp_factor) {
  174413. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174414. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174415. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174416. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174417. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174418. dst_blk_x += compptr->h_samp_factor) {
  174419. src_buffer = (*srcinfo->mem->access_virt_barray)
  174420. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174421. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174422. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174423. if (dst_blk_y < comp_height) {
  174424. src_ptr = src_buffer[offset_x]
  174425. [comp_height - dst_blk_y - offset_y - 1];
  174426. if (dst_blk_x < comp_width) {
  174427. /* Block is within the mirrorable area. */
  174428. dst_ptr = dst_buffer[offset_y]
  174429. [comp_width - dst_blk_x - offset_x - 1];
  174430. for (i = 0; i < DCTSIZE; i++) {
  174431. for (j = 0; j < DCTSIZE; j++) {
  174432. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174433. j++;
  174434. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174435. }
  174436. i++;
  174437. for (j = 0; j < DCTSIZE; j++) {
  174438. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174439. j++;
  174440. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174441. }
  174442. }
  174443. } else {
  174444. /* Right-edge blocks are mirrored in y only */
  174445. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174446. for (i = 0; i < DCTSIZE; i++) {
  174447. for (j = 0; j < DCTSIZE; j++) {
  174448. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174449. j++;
  174450. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174451. }
  174452. }
  174453. }
  174454. } else {
  174455. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174456. if (dst_blk_x < comp_width) {
  174457. /* Bottom-edge blocks are mirrored in x only */
  174458. dst_ptr = dst_buffer[offset_y]
  174459. [comp_width - dst_blk_x - offset_x - 1];
  174460. for (i = 0; i < DCTSIZE; i++) {
  174461. for (j = 0; j < DCTSIZE; j++)
  174462. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174463. i++;
  174464. for (j = 0; j < DCTSIZE; j++)
  174465. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174466. }
  174467. } else {
  174468. /* At lower right corner, just transpose, no mirroring */
  174469. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174470. for (i = 0; i < DCTSIZE; i++)
  174471. for (j = 0; j < DCTSIZE; j++)
  174472. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174473. }
  174474. }
  174475. }
  174476. }
  174477. }
  174478. }
  174479. }
  174480. }
  174481. /* Request any required workspace.
  174482. *
  174483. * We allocate the workspace virtual arrays from the source decompression
  174484. * object, so that all the arrays (both the original data and the workspace)
  174485. * will be taken into account while making memory management decisions.
  174486. * Hence, this routine must be called after jpeg_read_header (which reads
  174487. * the image dimensions) and before jpeg_read_coefficients (which realizes
  174488. * the source's virtual arrays).
  174489. */
  174490. GLOBAL(void)
  174491. jtransform_request_workspace (j_decompress_ptr srcinfo,
  174492. jpeg_transform_info *info)
  174493. {
  174494. jvirt_barray_ptr *coef_arrays = NULL;
  174495. jpeg_component_info *compptr;
  174496. int ci;
  174497. if (info->force_grayscale &&
  174498. srcinfo->jpeg_color_space == JCS_YCbCr &&
  174499. srcinfo->num_components == 3) {
  174500. /* We'll only process the first component */
  174501. info->num_components = 1;
  174502. } else {
  174503. /* Process all the components */
  174504. info->num_components = srcinfo->num_components;
  174505. }
  174506. switch (info->transform) {
  174507. case JXFORM_NONE:
  174508. case JXFORM_FLIP_H:
  174509. /* Don't need a workspace array */
  174510. break;
  174511. case JXFORM_FLIP_V:
  174512. case JXFORM_ROT_180:
  174513. /* Need workspace arrays having same dimensions as source image.
  174514. * Note that we allocate arrays padded out to the next iMCU boundary,
  174515. * so that transform routines need not worry about missing edge blocks.
  174516. */
  174517. coef_arrays = (jvirt_barray_ptr *)
  174518. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  174519. SIZEOF(jvirt_barray_ptr) * info->num_components);
  174520. for (ci = 0; ci < info->num_components; ci++) {
  174521. compptr = srcinfo->comp_info + ci;
  174522. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  174523. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  174524. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  174525. (long) compptr->h_samp_factor),
  174526. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  174527. (long) compptr->v_samp_factor),
  174528. (JDIMENSION) compptr->v_samp_factor);
  174529. }
  174530. break;
  174531. case JXFORM_TRANSPOSE:
  174532. case JXFORM_TRANSVERSE:
  174533. case JXFORM_ROT_90:
  174534. case JXFORM_ROT_270:
  174535. /* Need workspace arrays having transposed dimensions.
  174536. * Note that we allocate arrays padded out to the next iMCU boundary,
  174537. * so that transform routines need not worry about missing edge blocks.
  174538. */
  174539. coef_arrays = (jvirt_barray_ptr *)
  174540. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  174541. SIZEOF(jvirt_barray_ptr) * info->num_components);
  174542. for (ci = 0; ci < info->num_components; ci++) {
  174543. compptr = srcinfo->comp_info + ci;
  174544. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  174545. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  174546. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  174547. (long) compptr->v_samp_factor),
  174548. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  174549. (long) compptr->h_samp_factor),
  174550. (JDIMENSION) compptr->h_samp_factor);
  174551. }
  174552. break;
  174553. }
  174554. info->workspace_coef_arrays = coef_arrays;
  174555. }
  174556. /* Transpose destination image parameters */
  174557. LOCAL(void)
  174558. transpose_critical_parameters (j_compress_ptr dstinfo)
  174559. {
  174560. int tblno, i, j, ci, itemp;
  174561. jpeg_component_info *compptr;
  174562. JQUANT_TBL *qtblptr;
  174563. JDIMENSION dtemp;
  174564. UINT16 qtemp;
  174565. /* Transpose basic image dimensions */
  174566. dtemp = dstinfo->image_width;
  174567. dstinfo->image_width = dstinfo->image_height;
  174568. dstinfo->image_height = dtemp;
  174569. /* Transpose sampling factors */
  174570. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174571. compptr = dstinfo->comp_info + ci;
  174572. itemp = compptr->h_samp_factor;
  174573. compptr->h_samp_factor = compptr->v_samp_factor;
  174574. compptr->v_samp_factor = itemp;
  174575. }
  174576. /* Transpose quantization tables */
  174577. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  174578. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  174579. if (qtblptr != NULL) {
  174580. for (i = 0; i < DCTSIZE; i++) {
  174581. for (j = 0; j < i; j++) {
  174582. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  174583. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  174584. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  174585. }
  174586. }
  174587. }
  174588. }
  174589. }
  174590. /* Trim off any partial iMCUs on the indicated destination edge */
  174591. LOCAL(void)
  174592. trim_right_edge (j_compress_ptr dstinfo)
  174593. {
  174594. int ci, max_h_samp_factor;
  174595. JDIMENSION MCU_cols;
  174596. /* We have to compute max_h_samp_factor ourselves,
  174597. * because it hasn't been set yet in the destination
  174598. * (and we don't want to use the source's value).
  174599. */
  174600. max_h_samp_factor = 1;
  174601. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174602. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  174603. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  174604. }
  174605. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  174606. if (MCU_cols > 0) /* can't trim to 0 pixels */
  174607. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  174608. }
  174609. LOCAL(void)
  174610. trim_bottom_edge (j_compress_ptr dstinfo)
  174611. {
  174612. int ci, max_v_samp_factor;
  174613. JDIMENSION MCU_rows;
  174614. /* We have to compute max_v_samp_factor ourselves,
  174615. * because it hasn't been set yet in the destination
  174616. * (and we don't want to use the source's value).
  174617. */
  174618. max_v_samp_factor = 1;
  174619. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174620. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  174621. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  174622. }
  174623. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  174624. if (MCU_rows > 0) /* can't trim to 0 pixels */
  174625. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  174626. }
  174627. /* Adjust output image parameters as needed.
  174628. *
  174629. * This must be called after jpeg_copy_critical_parameters()
  174630. * and before jpeg_write_coefficients().
  174631. *
  174632. * The return value is the set of virtual coefficient arrays to be written
  174633. * (either the ones allocated by jtransform_request_workspace, or the
  174634. * original source data arrays). The caller will need to pass this value
  174635. * to jpeg_write_coefficients().
  174636. */
  174637. GLOBAL(jvirt_barray_ptr *)
  174638. jtransform_adjust_parameters (j_decompress_ptr srcinfo,
  174639. j_compress_ptr dstinfo,
  174640. jvirt_barray_ptr *src_coef_arrays,
  174641. jpeg_transform_info *info)
  174642. {
  174643. /* If force-to-grayscale is requested, adjust destination parameters */
  174644. if (info->force_grayscale) {
  174645. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  174646. * properly. Among other things, the target h_samp_factor & v_samp_factor
  174647. * will get set to 1, which typically won't match the source.
  174648. * In fact we do this even if the source is already grayscale; that
  174649. * provides an easy way of coercing a grayscale JPEG with funny sampling
  174650. * factors to the customary 1,1. (Some decoders fail on other factors.)
  174651. */
  174652. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  174653. dstinfo->num_components == 3) ||
  174654. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  174655. dstinfo->num_components == 1)) {
  174656. /* We have to preserve the source's quantization table number. */
  174657. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  174658. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  174659. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  174660. } else {
  174661. /* Sorry, can't do it */
  174662. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  174663. }
  174664. }
  174665. /* Correct the destination's image dimensions etc if necessary */
  174666. switch (info->transform) {
  174667. case JXFORM_NONE:
  174668. /* Nothing to do */
  174669. break;
  174670. case JXFORM_FLIP_H:
  174671. if (info->trim)
  174672. trim_right_edge(dstinfo);
  174673. break;
  174674. case JXFORM_FLIP_V:
  174675. if (info->trim)
  174676. trim_bottom_edge(dstinfo);
  174677. break;
  174678. case JXFORM_TRANSPOSE:
  174679. transpose_critical_parameters(dstinfo);
  174680. /* transpose does NOT have to trim anything */
  174681. break;
  174682. case JXFORM_TRANSVERSE:
  174683. transpose_critical_parameters(dstinfo);
  174684. if (info->trim) {
  174685. trim_right_edge(dstinfo);
  174686. trim_bottom_edge(dstinfo);
  174687. }
  174688. break;
  174689. case JXFORM_ROT_90:
  174690. transpose_critical_parameters(dstinfo);
  174691. if (info->trim)
  174692. trim_right_edge(dstinfo);
  174693. break;
  174694. case JXFORM_ROT_180:
  174695. if (info->trim) {
  174696. trim_right_edge(dstinfo);
  174697. trim_bottom_edge(dstinfo);
  174698. }
  174699. break;
  174700. case JXFORM_ROT_270:
  174701. transpose_critical_parameters(dstinfo);
  174702. if (info->trim)
  174703. trim_bottom_edge(dstinfo);
  174704. break;
  174705. }
  174706. /* Return the appropriate output data set */
  174707. if (info->workspace_coef_arrays != NULL)
  174708. return info->workspace_coef_arrays;
  174709. return src_coef_arrays;
  174710. }
  174711. /* Execute the actual transformation, if any.
  174712. *
  174713. * This must be called *after* jpeg_write_coefficients, because it depends
  174714. * on jpeg_write_coefficients to have computed subsidiary values such as
  174715. * the per-component width and height fields in the destination object.
  174716. *
  174717. * Note that some transformations will modify the source data arrays!
  174718. */
  174719. GLOBAL(void)
  174720. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  174721. j_compress_ptr dstinfo,
  174722. jvirt_barray_ptr *src_coef_arrays,
  174723. jpeg_transform_info *info)
  174724. {
  174725. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  174726. switch (info->transform) {
  174727. case JXFORM_NONE:
  174728. break;
  174729. case JXFORM_FLIP_H:
  174730. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  174731. break;
  174732. case JXFORM_FLIP_V:
  174733. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  174734. break;
  174735. case JXFORM_TRANSPOSE:
  174736. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  174737. break;
  174738. case JXFORM_TRANSVERSE:
  174739. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  174740. break;
  174741. case JXFORM_ROT_90:
  174742. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  174743. break;
  174744. case JXFORM_ROT_180:
  174745. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  174746. break;
  174747. case JXFORM_ROT_270:
  174748. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  174749. break;
  174750. }
  174751. }
  174752. #endif /* TRANSFORMS_SUPPORTED */
  174753. /* Setup decompression object to save desired markers in memory.
  174754. * This must be called before jpeg_read_header() to have the desired effect.
  174755. */
  174756. GLOBAL(void)
  174757. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  174758. {
  174759. #ifdef SAVE_MARKERS_SUPPORTED
  174760. int m;
  174761. /* Save comments except under NONE option */
  174762. if (option != JCOPYOPT_NONE) {
  174763. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  174764. }
  174765. /* Save all types of APPn markers iff ALL option */
  174766. if (option == JCOPYOPT_ALL) {
  174767. for (m = 0; m < 16; m++)
  174768. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  174769. }
  174770. #endif /* SAVE_MARKERS_SUPPORTED */
  174771. }
  174772. /* Copy markers saved in the given source object to the destination object.
  174773. * This should be called just after jpeg_start_compress() or
  174774. * jpeg_write_coefficients().
  174775. * Note that those routines will have written the SOI, and also the
  174776. * JFIF APP0 or Adobe APP14 markers if selected.
  174777. */
  174778. GLOBAL(void)
  174779. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174780. JCOPY_OPTION option)
  174781. {
  174782. jpeg_saved_marker_ptr marker;
  174783. /* In the current implementation, we don't actually need to examine the
  174784. * option flag here; we just copy everything that got saved.
  174785. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  174786. * if the encoder library already wrote one.
  174787. */
  174788. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  174789. if (dstinfo->write_JFIF_header &&
  174790. marker->marker == JPEG_APP0 &&
  174791. marker->data_length >= 5 &&
  174792. GETJOCTET(marker->data[0]) == 0x4A &&
  174793. GETJOCTET(marker->data[1]) == 0x46 &&
  174794. GETJOCTET(marker->data[2]) == 0x49 &&
  174795. GETJOCTET(marker->data[3]) == 0x46 &&
  174796. GETJOCTET(marker->data[4]) == 0)
  174797. continue; /* reject duplicate JFIF */
  174798. if (dstinfo->write_Adobe_marker &&
  174799. marker->marker == JPEG_APP0+14 &&
  174800. marker->data_length >= 5 &&
  174801. GETJOCTET(marker->data[0]) == 0x41 &&
  174802. GETJOCTET(marker->data[1]) == 0x64 &&
  174803. GETJOCTET(marker->data[2]) == 0x6F &&
  174804. GETJOCTET(marker->data[3]) == 0x62 &&
  174805. GETJOCTET(marker->data[4]) == 0x65)
  174806. continue; /* reject duplicate Adobe */
  174807. #ifdef NEED_FAR_POINTERS
  174808. /* We could use jpeg_write_marker if the data weren't FAR... */
  174809. {
  174810. unsigned int i;
  174811. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  174812. for (i = 0; i < marker->data_length; i++)
  174813. jpeg_write_m_byte(dstinfo, marker->data[i]);
  174814. }
  174815. #else
  174816. jpeg_write_marker(dstinfo, marker->marker,
  174817. marker->data, marker->data_length);
  174818. #endif
  174819. }
  174820. }
  174821. /********* End of inlined file: transupp.c *********/
  174822. }
  174823. #else
  174824. #define JPEG_INTERNALS
  174825. #undef FAR
  174826. #include <jpeglib.h>
  174827. #endif
  174828. }
  174829. #if JUCE_MSVC
  174830. #pragma warning (pop)
  174831. #endif
  174832. BEGIN_JUCE_NAMESPACE
  174833. using namespace jpeglibNamespace;
  174834. #if ! JUCE_WIN32
  174835. using jpeglibNamespace::boolean;
  174836. #endif
  174837. struct JPEGDecodingFailure {};
  174838. static void fatalErrorHandler (j_common_ptr)
  174839. {
  174840. throw JPEGDecodingFailure();
  174841. }
  174842. static void silentErrorCallback1 (j_common_ptr) {}
  174843. static void silentErrorCallback2 (j_common_ptr, int) {}
  174844. static void silentErrorCallback3 (j_common_ptr, char*) {}
  174845. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  174846. {
  174847. zerostruct (err);
  174848. err.error_exit = fatalErrorHandler;
  174849. err.emit_message = silentErrorCallback2;
  174850. err.output_message = silentErrorCallback1;
  174851. err.format_message = silentErrorCallback3;
  174852. err.reset_error_mgr = silentErrorCallback1;
  174853. }
  174854. static void dummyCallback1 (j_decompress_ptr) throw()
  174855. {
  174856. }
  174857. static void jpegSkip (j_decompress_ptr decompStruct, long num) throw()
  174858. {
  174859. decompStruct->src->next_input_byte += num;
  174860. num = jmin (num, (int) decompStruct->src->bytes_in_buffer);
  174861. decompStruct->src->bytes_in_buffer -= num;
  174862. }
  174863. static boolean jpegFill (j_decompress_ptr) throw()
  174864. {
  174865. return 0;
  174866. }
  174867. Image* juce_loadJPEGImageFromStream (InputStream& in) throw()
  174868. {
  174869. MemoryBlock mb;
  174870. in.readIntoMemoryBlock (mb);
  174871. Image* image = 0;
  174872. if (mb.getSize() > 16)
  174873. {
  174874. struct jpeg_decompress_struct jpegDecompStruct;
  174875. struct jpeg_error_mgr jerr;
  174876. setupSilentErrorHandler (jerr);
  174877. jpegDecompStruct.err = &jerr;
  174878. jpeg_create_decompress (&jpegDecompStruct);
  174879. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  174880. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  174881. jpegDecompStruct.src->init_source = dummyCallback1;
  174882. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  174883. jpegDecompStruct.src->skip_input_data = jpegSkip;
  174884. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  174885. jpegDecompStruct.src->term_source = dummyCallback1;
  174886. jpegDecompStruct.src->next_input_byte = (const unsigned char*) mb.getData();
  174887. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  174888. try
  174889. {
  174890. jpeg_read_header (&jpegDecompStruct, TRUE);
  174891. jpeg_calc_output_dimensions (&jpegDecompStruct);
  174892. const int width = jpegDecompStruct.output_width;
  174893. const int height = jpegDecompStruct.output_height;
  174894. jpegDecompStruct.out_color_space = JCS_RGB;
  174895. JSAMPARRAY buffer
  174896. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  174897. JPOOL_IMAGE,
  174898. width * 3, 1);
  174899. if (jpeg_start_decompress (&jpegDecompStruct))
  174900. {
  174901. image = new Image (Image::RGB, width, height, false);
  174902. for (int y = 0; y < height; ++y)
  174903. {
  174904. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  174905. int stride, pixelStride;
  174906. uint8* pixels = image->lockPixelDataReadWrite (0, y, width, 1, stride, pixelStride);
  174907. const uint8* src = *buffer;
  174908. uint8* dest = pixels;
  174909. for (int i = width; --i >= 0;)
  174910. {
  174911. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  174912. dest += pixelStride;
  174913. src += 3;
  174914. }
  174915. image->releasePixelDataReadWrite (pixels);
  174916. }
  174917. jpeg_finish_decompress (&jpegDecompStruct);
  174918. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  174919. }
  174920. jpeg_destroy_decompress (&jpegDecompStruct);
  174921. }
  174922. catch (...)
  174923. {}
  174924. }
  174925. return image;
  174926. }
  174927. static const int bufferSize = 512;
  174928. struct JuceJpegDest : public jpeg_destination_mgr
  174929. {
  174930. OutputStream* output;
  174931. char* buffer;
  174932. };
  174933. static void jpegWriteInit (j_compress_ptr) throw()
  174934. {
  174935. }
  174936. static void jpegWriteTerminate (j_compress_ptr cinfo) throw()
  174937. {
  174938. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  174939. const int numToWrite = bufferSize - dest->free_in_buffer;
  174940. dest->output->write (dest->buffer, numToWrite);
  174941. }
  174942. static boolean jpegWriteFlush (j_compress_ptr cinfo) throw()
  174943. {
  174944. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  174945. const int numToWrite = bufferSize;
  174946. dest->next_output_byte = (JOCTET*) dest->buffer;
  174947. dest->free_in_buffer = bufferSize;
  174948. return dest->output->write (dest->buffer, numToWrite);
  174949. }
  174950. bool juce_writeJPEGImageToStream (const Image& image,
  174951. OutputStream& out,
  174952. float quality) throw()
  174953. {
  174954. if (image.hasAlphaChannel())
  174955. {
  174956. // this method could fill the background in white and still save the image..
  174957. jassertfalse
  174958. return true;
  174959. }
  174960. struct jpeg_compress_struct jpegCompStruct;
  174961. struct jpeg_error_mgr jerr;
  174962. setupSilentErrorHandler (jerr);
  174963. jpegCompStruct.err = &jerr;
  174964. jpeg_create_compress (&jpegCompStruct);
  174965. JuceJpegDest dest;
  174966. jpegCompStruct.dest = &dest;
  174967. dest.output = &out;
  174968. dest.buffer = (char*) juce_malloc (bufferSize);
  174969. dest.next_output_byte = (JOCTET*) dest.buffer;
  174970. dest.free_in_buffer = bufferSize;
  174971. dest.init_destination = jpegWriteInit;
  174972. dest.empty_output_buffer = jpegWriteFlush;
  174973. dest.term_destination = jpegWriteTerminate;
  174974. jpegCompStruct.image_width = image.getWidth();
  174975. jpegCompStruct.image_height = image.getHeight();
  174976. jpegCompStruct.input_components = 3;
  174977. jpegCompStruct.in_color_space = JCS_RGB;
  174978. jpegCompStruct.write_JFIF_header = 1;
  174979. jpegCompStruct.X_density = 72;
  174980. jpegCompStruct.Y_density = 72;
  174981. jpeg_set_defaults (&jpegCompStruct);
  174982. jpegCompStruct.dct_method = JDCT_FLOAT;
  174983. jpegCompStruct.optimize_coding = 1;
  174984. // jpegCompStruct.smoothing_factor = 10;
  174985. if (quality < 0.0f)
  174986. quality = 0.85f;
  174987. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundFloatToInt (quality * 100.0f)), TRUE);
  174988. jpeg_start_compress (&jpegCompStruct, TRUE);
  174989. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  174990. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  174991. JPOOL_IMAGE,
  174992. strideBytes, 1);
  174993. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  174994. {
  174995. int stride, pixelStride;
  174996. const uint8* pixels = image.lockPixelDataReadOnly (0, jpegCompStruct.next_scanline, jpegCompStruct.image_width, 1, stride, pixelStride);
  174997. const uint8* src = pixels;
  174998. uint8* dst = *buffer;
  174999. for (int i = jpegCompStruct.image_width; --i >= 0;)
  175000. {
  175001. *dst++ = ((const PixelRGB*) src)->getRed();
  175002. *dst++ = ((const PixelRGB*) src)->getGreen();
  175003. *dst++ = ((const PixelRGB*) src)->getBlue();
  175004. src += pixelStride;
  175005. }
  175006. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  175007. image.releasePixelDataReadOnly (pixels);
  175008. }
  175009. jpeg_finish_compress (&jpegCompStruct);
  175010. jpeg_destroy_compress (&jpegCompStruct);
  175011. juce_free (dest.buffer);
  175012. out.flush();
  175013. return true;
  175014. }
  175015. END_JUCE_NAMESPACE
  175016. /********* End of inlined file: juce_JPEGLoader.cpp *********/
  175017. /********* Start of inlined file: juce_PNGLoader.cpp *********/
  175018. #ifdef _MSC_VER
  175019. #pragma warning (push)
  175020. #pragma warning (disable: 4390 4611)
  175021. #endif
  175022. namespace zlibNamespace
  175023. {
  175024. #if JUCE_INCLUDE_ZLIB_CODE
  175025. #undef OS_CODE
  175026. #undef fdopen
  175027. #undef OS_CODE
  175028. #else
  175029. #include <zlib.h>
  175030. #endif
  175031. }
  175032. namespace pnglibNamespace
  175033. {
  175034. using namespace zlibNamespace;
  175035. #if JUCE_INCLUDE_PNGLIB_CODE
  175036. #if _MSC_VER != 1310
  175037. using ::calloc; // (causes conflict in VS.NET 2003)
  175038. using ::malloc;
  175039. using ::free;
  175040. #endif
  175041. extern "C"
  175042. {
  175043. using ::abs;
  175044. #define PNG_INTERNAL
  175045. #define NO_DUMMY_DECL
  175046. #define PNG_SETJMP_NOT_SUPPORTED
  175047. /********* Start of inlined file: png.h *********/
  175048. /* png.h - header file for PNG reference library
  175049. *
  175050. * libpng version 1.2.21 - October 4, 2007
  175051. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  175052. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  175053. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  175054. *
  175055. * Authors and maintainers:
  175056. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  175057. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  175058. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  175059. * See also "Contributing Authors", below.
  175060. *
  175061. * Note about libpng version numbers:
  175062. *
  175063. * Due to various miscommunications, unforeseen code incompatibilities
  175064. * and occasional factors outside the authors' control, version numbering
  175065. * on the library has not always been consistent and straightforward.
  175066. * The following table summarizes matters since version 0.89c, which was
  175067. * the first widely used release:
  175068. *
  175069. * source png.h png.h shared-lib
  175070. * version string int version
  175071. * ------- ------ ----- ----------
  175072. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  175073. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  175074. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  175075. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  175076. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  175077. * 0.97c 0.97 97 2.0.97
  175078. * 0.98 0.98 98 2.0.98
  175079. * 0.99 0.99 98 2.0.99
  175080. * 0.99a-m 0.99 99 2.0.99
  175081. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  175082. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  175083. * 1.0.1 png.h string is 10001 2.1.0
  175084. * 1.0.1a-e identical to the 10002 from here on, the shared library
  175085. * 1.0.2 source version) 10002 is 2.V where V is the source code
  175086. * 1.0.2a-b 10003 version, except as noted.
  175087. * 1.0.3 10003
  175088. * 1.0.3a-d 10004
  175089. * 1.0.4 10004
  175090. * 1.0.4a-f 10005
  175091. * 1.0.5 (+ 2 patches) 10005
  175092. * 1.0.5a-d 10006
  175093. * 1.0.5e-r 10100 (not source compatible)
  175094. * 1.0.5s-v 10006 (not binary compatible)
  175095. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  175096. * 1.0.6d-f 10007 (still binary incompatible)
  175097. * 1.0.6g 10007
  175098. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  175099. * 1.0.6i 10007 10.6i
  175100. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  175101. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  175102. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  175103. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  175104. * 1.0.7 1 10007 (still compatible)
  175105. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  175106. * 1.0.8rc1 1 10008 2.1.0.8rc1
  175107. * 1.0.8 1 10008 2.1.0.8
  175108. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  175109. * 1.0.9rc1 1 10009 2.1.0.9rc1
  175110. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  175111. * 1.0.9rc2 1 10009 2.1.0.9rc2
  175112. * 1.0.9 1 10009 2.1.0.9
  175113. * 1.0.10beta1 1 10010 2.1.0.10beta1
  175114. * 1.0.10rc1 1 10010 2.1.0.10rc1
  175115. * 1.0.10 1 10010 2.1.0.10
  175116. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  175117. * 1.0.11rc1 1 10011 2.1.0.11rc1
  175118. * 1.0.11 1 10011 2.1.0.11
  175119. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  175120. * 1.0.12rc1 2 10012 2.1.0.12rc1
  175121. * 1.0.12 2 10012 2.1.0.12
  175122. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  175123. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  175124. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  175125. * 1.2.0rc1 3 10200 3.1.2.0rc1
  175126. * 1.2.0 3 10200 3.1.2.0
  175127. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  175128. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  175129. * 1.2.1 3 10201 3.1.2.1
  175130. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  175131. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  175132. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  175133. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  175134. * 1.0.13 10 10013 10.so.0.1.0.13
  175135. * 1.2.2 12 10202 12.so.0.1.2.2
  175136. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  175137. * 1.2.3 12 10203 12.so.0.1.2.3
  175138. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  175139. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  175140. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  175141. * 1.0.14 10 10014 10.so.0.1.0.14
  175142. * 1.2.4 13 10204 12.so.0.1.2.4
  175143. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  175144. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  175145. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  175146. * 1.0.15 10 10015 10.so.0.1.0.15
  175147. * 1.2.5 13 10205 12.so.0.1.2.5
  175148. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  175149. * 1.0.16 10 10016 10.so.0.1.0.16
  175150. * 1.2.6 13 10206 12.so.0.1.2.6
  175151. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  175152. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  175153. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  175154. * 1.0.17 10 10017 10.so.0.1.0.17
  175155. * 1.2.7 13 10207 12.so.0.1.2.7
  175156. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  175157. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  175158. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  175159. * 1.0.18 10 10018 10.so.0.1.0.18
  175160. * 1.2.8 13 10208 12.so.0.1.2.8
  175161. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  175162. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  175163. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  175164. * 1.2.9 13 10209 12.so.0.9[.0]
  175165. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  175166. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  175167. * 1.2.10 13 10210 12.so.0.10[.0]
  175168. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  175169. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  175170. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  175171. * 1.0.19 10 10019 10.so.0.19[.0]
  175172. * 1.2.11 13 10211 12.so.0.11[.0]
  175173. * 1.0.20 10 10020 10.so.0.20[.0]
  175174. * 1.2.12 13 10212 12.so.0.12[.0]
  175175. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  175176. * 1.0.21 10 10021 10.so.0.21[.0]
  175177. * 1.2.13 13 10213 12.so.0.13[.0]
  175178. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  175179. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  175180. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  175181. * 1.0.22 10 10022 10.so.0.22[.0]
  175182. * 1.2.14 13 10214 12.so.0.14[.0]
  175183. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  175184. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  175185. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  175186. * 1.0.23 10 10023 10.so.0.23[.0]
  175187. * 1.2.15 13 10215 12.so.0.15[.0]
  175188. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  175189. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  175190. * 1.0.24 10 10024 10.so.0.24[.0]
  175191. * 1.2.16 13 10216 12.so.0.16[.0]
  175192. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  175193. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  175194. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  175195. * 1.0.25 10 10025 10.so.0.25[.0]
  175196. * 1.2.17 13 10217 12.so.0.17[.0]
  175197. * 1.0.26 10 10026 10.so.0.26[.0]
  175198. * 1.2.18 13 10218 12.so.0.18[.0]
  175199. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  175200. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  175201. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  175202. * 1.0.27 10 10027 10.so.0.27[.0]
  175203. * 1.2.19 13 10219 12.so.0.19[.0]
  175204. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  175205. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  175206. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  175207. * 1.0.28 10 10028 10.so.0.28[.0]
  175208. * 1.2.20 13 10220 12.so.0.20[.0]
  175209. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  175210. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  175211. * 1.0.29 10 10029 10.so.0.29[.0]
  175212. * 1.2.21 13 10221 12.so.0.21[.0]
  175213. *
  175214. * Henceforth the source version will match the shared-library major
  175215. * and minor numbers; the shared-library major version number will be
  175216. * used for changes in backward compatibility, as it is intended. The
  175217. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  175218. * for applications, is an unsigned integer of the form xyyzz corresponding
  175219. * to the source version x.y.z (leading zeros in y and z). Beta versions
  175220. * were given the previous public release number plus a letter, until
  175221. * version 1.0.6j; from then on they were given the upcoming public
  175222. * release number plus "betaNN" or "rcN".
  175223. *
  175224. * Binary incompatibility exists only when applications make direct access
  175225. * to the info_ptr or png_ptr members through png.h, and the compiled
  175226. * application is loaded with a different version of the library.
  175227. *
  175228. * DLLNUM will change each time there are forward or backward changes
  175229. * in binary compatibility (e.g., when a new feature is added).
  175230. *
  175231. * See libpng.txt or libpng.3 for more information. The PNG specification
  175232. * is available as a W3C Recommendation and as an ISO Specification,
  175233. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  175234. */
  175235. /*
  175236. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  175237. *
  175238. * If you modify libpng you may insert additional notices immediately following
  175239. * this sentence.
  175240. *
  175241. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  175242. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  175243. * distributed according to the same disclaimer and license as libpng-1.2.5
  175244. * with the following individual added to the list of Contributing Authors:
  175245. *
  175246. * Cosmin Truta
  175247. *
  175248. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  175249. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  175250. * distributed according to the same disclaimer and license as libpng-1.0.6
  175251. * with the following individuals added to the list of Contributing Authors:
  175252. *
  175253. * Simon-Pierre Cadieux
  175254. * Eric S. Raymond
  175255. * Gilles Vollant
  175256. *
  175257. * and with the following additions to the disclaimer:
  175258. *
  175259. * There is no warranty against interference with your enjoyment of the
  175260. * library or against infringement. There is no warranty that our
  175261. * efforts or the library will fulfill any of your particular purposes
  175262. * or needs. This library is provided with all faults, and the entire
  175263. * risk of satisfactory quality, performance, accuracy, and effort is with
  175264. * the user.
  175265. *
  175266. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  175267. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  175268. * distributed according to the same disclaimer and license as libpng-0.96,
  175269. * with the following individuals added to the list of Contributing Authors:
  175270. *
  175271. * Tom Lane
  175272. * Glenn Randers-Pehrson
  175273. * Willem van Schaik
  175274. *
  175275. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  175276. * Copyright (c) 1996, 1997 Andreas Dilger
  175277. * Distributed according to the same disclaimer and license as libpng-0.88,
  175278. * with the following individuals added to the list of Contributing Authors:
  175279. *
  175280. * John Bowler
  175281. * Kevin Bracey
  175282. * Sam Bushell
  175283. * Magnus Holmgren
  175284. * Greg Roelofs
  175285. * Tom Tanner
  175286. *
  175287. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  175288. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  175289. *
  175290. * For the purposes of this copyright and license, "Contributing Authors"
  175291. * is defined as the following set of individuals:
  175292. *
  175293. * Andreas Dilger
  175294. * Dave Martindale
  175295. * Guy Eric Schalnat
  175296. * Paul Schmidt
  175297. * Tim Wegner
  175298. *
  175299. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  175300. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  175301. * including, without limitation, the warranties of merchantability and of
  175302. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  175303. * assume no liability for direct, indirect, incidental, special, exemplary,
  175304. * or consequential damages, which may result from the use of the PNG
  175305. * Reference Library, even if advised of the possibility of such damage.
  175306. *
  175307. * Permission is hereby granted to use, copy, modify, and distribute this
  175308. * source code, or portions hereof, for any purpose, without fee, subject
  175309. * to the following restrictions:
  175310. *
  175311. * 1. The origin of this source code must not be misrepresented.
  175312. *
  175313. * 2. Altered versions must be plainly marked as such and
  175314. * must not be misrepresented as being the original source.
  175315. *
  175316. * 3. This Copyright notice may not be removed or altered from
  175317. * any source or altered source distribution.
  175318. *
  175319. * The Contributing Authors and Group 42, Inc. specifically permit, without
  175320. * fee, and encourage the use of this source code as a component to
  175321. * supporting the PNG file format in commercial products. If you use this
  175322. * source code in a product, acknowledgment is not required but would be
  175323. * appreciated.
  175324. */
  175325. /*
  175326. * A "png_get_copyright" function is available, for convenient use in "about"
  175327. * boxes and the like:
  175328. *
  175329. * printf("%s",png_get_copyright(NULL));
  175330. *
  175331. * Also, the PNG logo (in PNG format, of course) is supplied in the
  175332. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  175333. */
  175334. /*
  175335. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  175336. * certification mark of the Open Source Initiative.
  175337. */
  175338. /*
  175339. * The contributing authors would like to thank all those who helped
  175340. * with testing, bug fixes, and patience. This wouldn't have been
  175341. * possible without all of you.
  175342. *
  175343. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  175344. */
  175345. /*
  175346. * Y2K compliance in libpng:
  175347. * =========================
  175348. *
  175349. * October 4, 2007
  175350. *
  175351. * Since the PNG Development group is an ad-hoc body, we can't make
  175352. * an official declaration.
  175353. *
  175354. * This is your unofficial assurance that libpng from version 0.71 and
  175355. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  175356. * versions were also Y2K compliant.
  175357. *
  175358. * Libpng only has three year fields. One is a 2-byte unsigned integer
  175359. * that will hold years up to 65535. The other two hold the date in text
  175360. * format, and will hold years up to 9999.
  175361. *
  175362. * The integer is
  175363. * "png_uint_16 year" in png_time_struct.
  175364. *
  175365. * The strings are
  175366. * "png_charp time_buffer" in png_struct and
  175367. * "near_time_buffer", which is a local character string in png.c.
  175368. *
  175369. * There are seven time-related functions:
  175370. * png.c: png_convert_to_rfc_1123() in png.c
  175371. * (formerly png_convert_to_rfc_1152() in error)
  175372. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  175373. * png_convert_from_time_t() in pngwrite.c
  175374. * png_get_tIME() in pngget.c
  175375. * png_handle_tIME() in pngrutil.c, called in pngread.c
  175376. * png_set_tIME() in pngset.c
  175377. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  175378. *
  175379. * All handle dates properly in a Y2K environment. The
  175380. * png_convert_from_time_t() function calls gmtime() to convert from system
  175381. * clock time, which returns (year - 1900), which we properly convert to
  175382. * the full 4-digit year. There is a possibility that applications using
  175383. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  175384. * function, or that they are incorrectly passing only a 2-digit year
  175385. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  175386. * but this is not under our control. The libpng documentation has always
  175387. * stated that it works with 4-digit years, and the APIs have been
  175388. * documented as such.
  175389. *
  175390. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  175391. * integer to hold the year, and can hold years as large as 65535.
  175392. *
  175393. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  175394. * no date-related code.
  175395. *
  175396. * Glenn Randers-Pehrson
  175397. * libpng maintainer
  175398. * PNG Development Group
  175399. */
  175400. #ifndef PNG_H
  175401. #define PNG_H
  175402. /* This is not the place to learn how to use libpng. The file libpng.txt
  175403. * describes how to use libpng, and the file example.c summarizes it
  175404. * with some code on which to build. This file is useful for looking
  175405. * at the actual function definitions and structure components.
  175406. */
  175407. /* Version information for png.h - this should match the version in png.c */
  175408. #define PNG_LIBPNG_VER_STRING "1.2.21"
  175409. #define PNG_HEADER_VERSION_STRING \
  175410. " libpng version 1.2.21 - October 4, 2007\n"
  175411. #define PNG_LIBPNG_VER_SONUM 0
  175412. #define PNG_LIBPNG_VER_DLLNUM 13
  175413. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  175414. #define PNG_LIBPNG_VER_MAJOR 1
  175415. #define PNG_LIBPNG_VER_MINOR 2
  175416. #define PNG_LIBPNG_VER_RELEASE 21
  175417. /* This should match the numeric part of the final component of
  175418. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  175419. #define PNG_LIBPNG_VER_BUILD 0
  175420. /* Release Status */
  175421. #define PNG_LIBPNG_BUILD_ALPHA 1
  175422. #define PNG_LIBPNG_BUILD_BETA 2
  175423. #define PNG_LIBPNG_BUILD_RC 3
  175424. #define PNG_LIBPNG_BUILD_STABLE 4
  175425. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  175426. /* Release-Specific Flags */
  175427. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  175428. PNG_LIBPNG_BUILD_STABLE only */
  175429. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  175430. PNG_LIBPNG_BUILD_SPECIAL */
  175431. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  175432. PNG_LIBPNG_BUILD_PRIVATE */
  175433. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  175434. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  175435. * We must not include leading zeros.
  175436. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  175437. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  175438. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  175439. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  175440. #ifndef PNG_VERSION_INFO_ONLY
  175441. /* include the compression library's header */
  175442. #endif
  175443. /* include all user configurable info, including optional assembler routines */
  175444. /********* Start of inlined file: pngconf.h *********/
  175445. /* pngconf.h - machine configurable file for libpng
  175446. *
  175447. * libpng version 1.2.21 - October 4, 2007
  175448. * For conditions of distribution and use, see copyright notice in png.h
  175449. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  175450. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  175451. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  175452. */
  175453. /* Any machine specific code is near the front of this file, so if you
  175454. * are configuring libpng for a machine, you may want to read the section
  175455. * starting here down to where it starts to typedef png_color, png_text,
  175456. * and png_info.
  175457. */
  175458. #ifndef PNGCONF_H
  175459. #define PNGCONF_H
  175460. #define PNG_1_2_X
  175461. // These are some Juce config settings that should remove any unnecessary code bloat..
  175462. #define PNG_NO_STDIO 1
  175463. #define PNG_DEBUG 0
  175464. #define PNG_NO_WARNINGS 1
  175465. #define PNG_NO_ERROR_TEXT 1
  175466. #define PNG_NO_ERROR_NUMBERS 1
  175467. #define PNG_NO_USER_MEM 1
  175468. #define PNG_NO_READ_iCCP 1
  175469. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  175470. #define PNG_NO_READ_USER_CHUNKS 1
  175471. #define PNG_NO_READ_iTXt 1
  175472. #define PNG_NO_READ_sCAL 1
  175473. #define PNG_NO_READ_sPLT 1
  175474. #define png_error(a, b) png_err(a)
  175475. #define png_warning(a, b)
  175476. #define png_chunk_error(a, b) png_err(a)
  175477. #define png_chunk_warning(a, b)
  175478. /*
  175479. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  175480. * includes the resource compiler for Windows DLL configurations.
  175481. */
  175482. #ifdef PNG_USER_CONFIG
  175483. # ifndef PNG_USER_PRIVATEBUILD
  175484. # define PNG_USER_PRIVATEBUILD
  175485. # endif
  175486. #include "pngusr.h"
  175487. #endif
  175488. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  175489. #ifdef PNG_CONFIGURE_LIBPNG
  175490. #ifdef HAVE_CONFIG_H
  175491. #include "config.h"
  175492. #endif
  175493. #endif
  175494. /*
  175495. * Added at libpng-1.2.8
  175496. *
  175497. * If you create a private DLL you need to define in "pngusr.h" the followings:
  175498. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  175499. * the DLL was built>
  175500. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  175501. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  175502. * distinguish your DLL from those of the official release. These
  175503. * correspond to the trailing letters that come after the version
  175504. * number and must match your private DLL name>
  175505. * e.g. // private DLL "libpng13gx.dll"
  175506. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  175507. *
  175508. * The following macros are also at your disposal if you want to complete the
  175509. * DLL VERSIONINFO structure.
  175510. * - PNG_USER_VERSIONINFO_COMMENTS
  175511. * - PNG_USER_VERSIONINFO_COMPANYNAME
  175512. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  175513. */
  175514. #ifdef __STDC__
  175515. #ifdef SPECIALBUILD
  175516. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  175517. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  175518. #endif
  175519. #ifdef PRIVATEBUILD
  175520. # pragma message("PRIVATEBUILD is deprecated.\
  175521. Use PNG_USER_PRIVATEBUILD instead.")
  175522. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  175523. #endif
  175524. #endif /* __STDC__ */
  175525. #ifndef PNG_VERSION_INFO_ONLY
  175526. /* End of material added to libpng-1.2.8 */
  175527. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  175528. Restored at libpng-1.2.21 */
  175529. # define PNG_WARN_UNINITIALIZED_ROW 1
  175530. /* End of material added at libpng-1.2.19/1.2.21 */
  175531. /* This is the size of the compression buffer, and thus the size of
  175532. * an IDAT chunk. Make this whatever size you feel is best for your
  175533. * machine. One of these will be allocated per png_struct. When this
  175534. * is full, it writes the data to the disk, and does some other
  175535. * calculations. Making this an extremely small size will slow
  175536. * the library down, but you may want to experiment to determine
  175537. * where it becomes significant, if you are concerned with memory
  175538. * usage. Note that zlib allocates at least 32Kb also. For readers,
  175539. * this describes the size of the buffer available to read the data in.
  175540. * Unless this gets smaller than the size of a row (compressed),
  175541. * it should not make much difference how big this is.
  175542. */
  175543. #ifndef PNG_ZBUF_SIZE
  175544. # define PNG_ZBUF_SIZE 8192
  175545. #endif
  175546. /* Enable if you want a write-only libpng */
  175547. #ifndef PNG_NO_READ_SUPPORTED
  175548. # define PNG_READ_SUPPORTED
  175549. #endif
  175550. /* Enable if you want a read-only libpng */
  175551. #ifndef PNG_NO_WRITE_SUPPORTED
  175552. # define PNG_WRITE_SUPPORTED
  175553. #endif
  175554. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  175555. support PNGs that are embedded in MNG datastreams */
  175556. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  175557. # ifndef PNG_MNG_FEATURES_SUPPORTED
  175558. # define PNG_MNG_FEATURES_SUPPORTED
  175559. # endif
  175560. #endif
  175561. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  175562. # ifndef PNG_FLOATING_POINT_SUPPORTED
  175563. # define PNG_FLOATING_POINT_SUPPORTED
  175564. # endif
  175565. #endif
  175566. /* If you are running on a machine where you cannot allocate more
  175567. * than 64K of memory at once, uncomment this. While libpng will not
  175568. * normally need that much memory in a chunk (unless you load up a very
  175569. * large file), zlib needs to know how big of a chunk it can use, and
  175570. * libpng thus makes sure to check any memory allocation to verify it
  175571. * will fit into memory.
  175572. #define PNG_MAX_MALLOC_64K
  175573. */
  175574. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  175575. # define PNG_MAX_MALLOC_64K
  175576. #endif
  175577. /* Special munging to support doing things the 'cygwin' way:
  175578. * 'Normal' png-on-win32 defines/defaults:
  175579. * PNG_BUILD_DLL -- building dll
  175580. * PNG_USE_DLL -- building an application, linking to dll
  175581. * (no define) -- building static library, or building an
  175582. * application and linking to the static lib
  175583. * 'Cygwin' defines/defaults:
  175584. * PNG_BUILD_DLL -- (ignored) building the dll
  175585. * (no define) -- (ignored) building an application, linking to the dll
  175586. * PNG_STATIC -- (ignored) building the static lib, or building an
  175587. * application that links to the static lib.
  175588. * ALL_STATIC -- (ignored) building various static libs, or building an
  175589. * application that links to the static libs.
  175590. * Thus,
  175591. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  175592. * this bit of #ifdefs will define the 'correct' config variables based on
  175593. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  175594. * unnecessary.
  175595. *
  175596. * Also, the precedence order is:
  175597. * ALL_STATIC (since we can't #undef something outside our namespace)
  175598. * PNG_BUILD_DLL
  175599. * PNG_STATIC
  175600. * (nothing) == PNG_USE_DLL
  175601. *
  175602. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  175603. * of auto-import in binutils, we no longer need to worry about
  175604. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  175605. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  175606. * to __declspec() stuff. However, we DO need to worry about
  175607. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  175608. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  175609. */
  175610. #if defined(__CYGWIN__)
  175611. # if defined(ALL_STATIC)
  175612. # if defined(PNG_BUILD_DLL)
  175613. # undef PNG_BUILD_DLL
  175614. # endif
  175615. # if defined(PNG_USE_DLL)
  175616. # undef PNG_USE_DLL
  175617. # endif
  175618. # if defined(PNG_DLL)
  175619. # undef PNG_DLL
  175620. # endif
  175621. # if !defined(PNG_STATIC)
  175622. # define PNG_STATIC
  175623. # endif
  175624. # else
  175625. # if defined (PNG_BUILD_DLL)
  175626. # if defined(PNG_STATIC)
  175627. # undef PNG_STATIC
  175628. # endif
  175629. # if defined(PNG_USE_DLL)
  175630. # undef PNG_USE_DLL
  175631. # endif
  175632. # if !defined(PNG_DLL)
  175633. # define PNG_DLL
  175634. # endif
  175635. # else
  175636. # if defined(PNG_STATIC)
  175637. # if defined(PNG_USE_DLL)
  175638. # undef PNG_USE_DLL
  175639. # endif
  175640. # if defined(PNG_DLL)
  175641. # undef PNG_DLL
  175642. # endif
  175643. # else
  175644. # if !defined(PNG_USE_DLL)
  175645. # define PNG_USE_DLL
  175646. # endif
  175647. # if !defined(PNG_DLL)
  175648. # define PNG_DLL
  175649. # endif
  175650. # endif
  175651. # endif
  175652. # endif
  175653. #endif
  175654. /* This protects us against compilers that run on a windowing system
  175655. * and thus don't have or would rather us not use the stdio types:
  175656. * stdin, stdout, and stderr. The only one currently used is stderr
  175657. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  175658. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  175659. * will also prevent these, plus will prevent the entire set of stdio
  175660. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  175661. * unless (PNG_DEBUG > 0) has been #defined.
  175662. *
  175663. * #define PNG_NO_CONSOLE_IO
  175664. * #define PNG_NO_STDIO
  175665. */
  175666. #if defined(_WIN32_WCE)
  175667. # include <windows.h>
  175668. /* Console I/O functions are not supported on WindowsCE */
  175669. # define PNG_NO_CONSOLE_IO
  175670. # ifdef PNG_DEBUG
  175671. # undef PNG_DEBUG
  175672. # endif
  175673. #endif
  175674. #ifdef PNG_BUILD_DLL
  175675. # ifndef PNG_CONSOLE_IO_SUPPORTED
  175676. # ifndef PNG_NO_CONSOLE_IO
  175677. # define PNG_NO_CONSOLE_IO
  175678. # endif
  175679. # endif
  175680. #endif
  175681. # ifdef PNG_NO_STDIO
  175682. # ifndef PNG_NO_CONSOLE_IO
  175683. # define PNG_NO_CONSOLE_IO
  175684. # endif
  175685. # ifdef PNG_DEBUG
  175686. # if (PNG_DEBUG > 0)
  175687. # include <stdio.h>
  175688. # endif
  175689. # endif
  175690. # else
  175691. # if !defined(_WIN32_WCE)
  175692. /* "stdio.h" functions are not supported on WindowsCE */
  175693. # include <stdio.h>
  175694. # endif
  175695. # endif
  175696. /* This macro protects us against machines that don't have function
  175697. * prototypes (ie K&R style headers). If your compiler does not handle
  175698. * function prototypes, define this macro and use the included ansi2knr.
  175699. * I've always been able to use _NO_PROTO as the indicator, but you may
  175700. * need to drag the empty declaration out in front of here, or change the
  175701. * ifdef to suit your own needs.
  175702. */
  175703. #ifndef PNGARG
  175704. #ifdef OF /* zlib prototype munger */
  175705. # define PNGARG(arglist) OF(arglist)
  175706. #else
  175707. #ifdef _NO_PROTO
  175708. # define PNGARG(arglist) ()
  175709. # ifndef PNG_TYPECAST_NULL
  175710. # define PNG_TYPECAST_NULL
  175711. # endif
  175712. #else
  175713. # define PNGARG(arglist) arglist
  175714. #endif /* _NO_PROTO */
  175715. #endif /* OF */
  175716. #endif /* PNGARG */
  175717. /* Try to determine if we are compiling on a Mac. Note that testing for
  175718. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  175719. * on non-Mac platforms.
  175720. */
  175721. #ifndef MACOS
  175722. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  175723. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  175724. # define MACOS
  175725. # endif
  175726. #endif
  175727. /* enough people need this for various reasons to include it here */
  175728. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  175729. # include <sys/types.h>
  175730. #endif
  175731. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  175732. # define PNG_SETJMP_SUPPORTED
  175733. #endif
  175734. #ifdef PNG_SETJMP_SUPPORTED
  175735. /* This is an attempt to force a single setjmp behaviour on Linux. If
  175736. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  175737. */
  175738. # ifdef __linux__
  175739. # ifdef _BSD_SOURCE
  175740. # define PNG_SAVE_BSD_SOURCE
  175741. # undef _BSD_SOURCE
  175742. # endif
  175743. # ifdef _SETJMP_H
  175744. /* If you encounter a compiler error here, see the explanation
  175745. * near the end of INSTALL.
  175746. */
  175747. __png.h__ already includes setjmp.h;
  175748. __dont__ include it again.;
  175749. # endif
  175750. # endif /* __linux__ */
  175751. /* include setjmp.h for error handling */
  175752. # include <setjmp.h>
  175753. # ifdef __linux__
  175754. # ifdef PNG_SAVE_BSD_SOURCE
  175755. # define _BSD_SOURCE
  175756. # undef PNG_SAVE_BSD_SOURCE
  175757. # endif
  175758. # endif /* __linux__ */
  175759. #endif /* PNG_SETJMP_SUPPORTED */
  175760. #ifdef BSD
  175761. #if ! JUCE_MAC
  175762. # include <strings.h>
  175763. #endif
  175764. #else
  175765. # include <string.h>
  175766. #endif
  175767. /* Other defines for things like memory and the like can go here. */
  175768. #ifdef PNG_INTERNAL
  175769. #include <stdlib.h>
  175770. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  175771. * aren't usually used outside the library (as far as I know), so it is
  175772. * debatable if they should be exported at all. In the future, when it is
  175773. * possible to have run-time registry of chunk-handling functions, some of
  175774. * these will be made available again.
  175775. #define PNG_EXTERN extern
  175776. */
  175777. #define PNG_EXTERN
  175778. /* Other defines specific to compilers can go here. Try to keep
  175779. * them inside an appropriate ifdef/endif pair for portability.
  175780. */
  175781. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  175782. # if defined(MACOS)
  175783. /* We need to check that <math.h> hasn't already been included earlier
  175784. * as it seems it doesn't agree with <fp.h>, yet we should really use
  175785. * <fp.h> if possible.
  175786. */
  175787. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  175788. # include <fp.h>
  175789. # endif
  175790. # else
  175791. # include <math.h>
  175792. # endif
  175793. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  175794. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  175795. * MATH=68881
  175796. */
  175797. # include <m68881.h>
  175798. # endif
  175799. #endif
  175800. /* Codewarrior on NT has linking problems without this. */
  175801. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  175802. # define PNG_ALWAYS_EXTERN
  175803. #endif
  175804. /* This provides the non-ANSI (far) memory allocation routines. */
  175805. #if defined(__TURBOC__) && defined(__MSDOS__)
  175806. # include <mem.h>
  175807. # include <alloc.h>
  175808. #endif
  175809. /* I have no idea why is this necessary... */
  175810. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  175811. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  175812. # include <malloc.h>
  175813. #endif
  175814. /* This controls how fine the dithering gets. As this allocates
  175815. * a largish chunk of memory (32K), those who are not as concerned
  175816. * with dithering quality can decrease some or all of these.
  175817. */
  175818. #ifndef PNG_DITHER_RED_BITS
  175819. # define PNG_DITHER_RED_BITS 5
  175820. #endif
  175821. #ifndef PNG_DITHER_GREEN_BITS
  175822. # define PNG_DITHER_GREEN_BITS 5
  175823. #endif
  175824. #ifndef PNG_DITHER_BLUE_BITS
  175825. # define PNG_DITHER_BLUE_BITS 5
  175826. #endif
  175827. /* This controls how fine the gamma correction becomes when you
  175828. * are only interested in 8 bits anyway. Increasing this value
  175829. * results in more memory being used, and more pow() functions
  175830. * being called to fill in the gamma tables. Don't set this value
  175831. * less then 8, and even that may not work (I haven't tested it).
  175832. */
  175833. #ifndef PNG_MAX_GAMMA_8
  175834. # define PNG_MAX_GAMMA_8 11
  175835. #endif
  175836. /* This controls how much a difference in gamma we can tolerate before
  175837. * we actually start doing gamma conversion.
  175838. */
  175839. #ifndef PNG_GAMMA_THRESHOLD
  175840. # define PNG_GAMMA_THRESHOLD 0.05
  175841. #endif
  175842. #endif /* PNG_INTERNAL */
  175843. /* The following uses const char * instead of char * for error
  175844. * and warning message functions, so some compilers won't complain.
  175845. * If you do not want to use const, define PNG_NO_CONST here.
  175846. */
  175847. #ifndef PNG_NO_CONST
  175848. # define PNG_CONST const
  175849. #else
  175850. # define PNG_CONST
  175851. #endif
  175852. /* The following defines give you the ability to remove code from the
  175853. * library that you will not be using. I wish I could figure out how to
  175854. * automate this, but I can't do that without making it seriously hard
  175855. * on the users. So if you are not using an ability, change the #define
  175856. * to and #undef, and that part of the library will not be compiled. If
  175857. * your linker can't find a function, you may want to make sure the
  175858. * ability is defined here. Some of these depend upon some others being
  175859. * defined. I haven't figured out all the interactions here, so you may
  175860. * have to experiment awhile to get everything to compile. If you are
  175861. * creating or using a shared library, you probably shouldn't touch this,
  175862. * as it will affect the size of the structures, and this will cause bad
  175863. * things to happen if the library and/or application ever change.
  175864. */
  175865. /* Any features you will not be using can be undef'ed here */
  175866. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  175867. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  175868. * on the compile line, then pick and choose which ones to define without
  175869. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  175870. * if you only want to have a png-compliant reader/writer but don't need
  175871. * any of the extra transformations. This saves about 80 kbytes in a
  175872. * typical installation of the library. (PNG_NO_* form added in version
  175873. * 1.0.1c, for consistency)
  175874. */
  175875. /* The size of the png_text structure changed in libpng-1.0.6 when
  175876. * iTXt support was added. iTXt support was turned off by default through
  175877. * libpng-1.2.x, to support old apps that malloc the png_text structure
  175878. * instead of calling png_set_text() and letting libpng malloc it. It
  175879. * was turned on by default in libpng-1.3.0.
  175880. */
  175881. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  175882. # ifndef PNG_NO_iTXt_SUPPORTED
  175883. # define PNG_NO_iTXt_SUPPORTED
  175884. # endif
  175885. # ifndef PNG_NO_READ_iTXt
  175886. # define PNG_NO_READ_iTXt
  175887. # endif
  175888. # ifndef PNG_NO_WRITE_iTXt
  175889. # define PNG_NO_WRITE_iTXt
  175890. # endif
  175891. #endif
  175892. #if !defined(PNG_NO_iTXt_SUPPORTED)
  175893. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  175894. # define PNG_READ_iTXt
  175895. # endif
  175896. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  175897. # define PNG_WRITE_iTXt
  175898. # endif
  175899. #endif
  175900. /* The following support, added after version 1.0.0, can be turned off here en
  175901. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  175902. * with old applications that require the length of png_struct and png_info
  175903. * to remain unchanged.
  175904. */
  175905. #ifdef PNG_LEGACY_SUPPORTED
  175906. # define PNG_NO_FREE_ME
  175907. # define PNG_NO_READ_UNKNOWN_CHUNKS
  175908. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  175909. # define PNG_NO_READ_USER_CHUNKS
  175910. # define PNG_NO_READ_iCCP
  175911. # define PNG_NO_WRITE_iCCP
  175912. # define PNG_NO_READ_iTXt
  175913. # define PNG_NO_WRITE_iTXt
  175914. # define PNG_NO_READ_sCAL
  175915. # define PNG_NO_WRITE_sCAL
  175916. # define PNG_NO_READ_sPLT
  175917. # define PNG_NO_WRITE_sPLT
  175918. # define PNG_NO_INFO_IMAGE
  175919. # define PNG_NO_READ_RGB_TO_GRAY
  175920. # define PNG_NO_READ_USER_TRANSFORM
  175921. # define PNG_NO_WRITE_USER_TRANSFORM
  175922. # define PNG_NO_USER_MEM
  175923. # define PNG_NO_READ_EMPTY_PLTE
  175924. # define PNG_NO_MNG_FEATURES
  175925. # define PNG_NO_FIXED_POINT_SUPPORTED
  175926. #endif
  175927. /* Ignore attempt to turn off both floating and fixed point support */
  175928. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  175929. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  175930. # define PNG_FIXED_POINT_SUPPORTED
  175931. #endif
  175932. #ifndef PNG_NO_FREE_ME
  175933. # define PNG_FREE_ME_SUPPORTED
  175934. #endif
  175935. #if defined(PNG_READ_SUPPORTED)
  175936. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  175937. !defined(PNG_NO_READ_TRANSFORMS)
  175938. # define PNG_READ_TRANSFORMS_SUPPORTED
  175939. #endif
  175940. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  175941. # ifndef PNG_NO_READ_EXPAND
  175942. # define PNG_READ_EXPAND_SUPPORTED
  175943. # endif
  175944. # ifndef PNG_NO_READ_SHIFT
  175945. # define PNG_READ_SHIFT_SUPPORTED
  175946. # endif
  175947. # ifndef PNG_NO_READ_PACK
  175948. # define PNG_READ_PACK_SUPPORTED
  175949. # endif
  175950. # ifndef PNG_NO_READ_BGR
  175951. # define PNG_READ_BGR_SUPPORTED
  175952. # endif
  175953. # ifndef PNG_NO_READ_SWAP
  175954. # define PNG_READ_SWAP_SUPPORTED
  175955. # endif
  175956. # ifndef PNG_NO_READ_PACKSWAP
  175957. # define PNG_READ_PACKSWAP_SUPPORTED
  175958. # endif
  175959. # ifndef PNG_NO_READ_INVERT
  175960. # define PNG_READ_INVERT_SUPPORTED
  175961. # endif
  175962. # ifndef PNG_NO_READ_DITHER
  175963. # define PNG_READ_DITHER_SUPPORTED
  175964. # endif
  175965. # ifndef PNG_NO_READ_BACKGROUND
  175966. # define PNG_READ_BACKGROUND_SUPPORTED
  175967. # endif
  175968. # ifndef PNG_NO_READ_16_TO_8
  175969. # define PNG_READ_16_TO_8_SUPPORTED
  175970. # endif
  175971. # ifndef PNG_NO_READ_FILLER
  175972. # define PNG_READ_FILLER_SUPPORTED
  175973. # endif
  175974. # ifndef PNG_NO_READ_GAMMA
  175975. # define PNG_READ_GAMMA_SUPPORTED
  175976. # endif
  175977. # ifndef PNG_NO_READ_GRAY_TO_RGB
  175978. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  175979. # endif
  175980. # ifndef PNG_NO_READ_SWAP_ALPHA
  175981. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  175982. # endif
  175983. # ifndef PNG_NO_READ_INVERT_ALPHA
  175984. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  175985. # endif
  175986. # ifndef PNG_NO_READ_STRIP_ALPHA
  175987. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  175988. # endif
  175989. # ifndef PNG_NO_READ_USER_TRANSFORM
  175990. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  175991. # endif
  175992. # ifndef PNG_NO_READ_RGB_TO_GRAY
  175993. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  175994. # endif
  175995. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  175996. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  175997. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  175998. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  175999. #endif /* about interlacing capability! You'll */
  176000. /* still have interlacing unless you change the following line: */
  176001. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  176002. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  176003. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  176004. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  176005. # endif
  176006. #endif
  176007. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176008. /* Deprecated, will be removed from version 2.0.0.
  176009. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  176010. #ifndef PNG_NO_READ_EMPTY_PLTE
  176011. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  176012. #endif
  176013. #endif
  176014. #endif /* PNG_READ_SUPPORTED */
  176015. #if defined(PNG_WRITE_SUPPORTED)
  176016. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  176017. !defined(PNG_NO_WRITE_TRANSFORMS)
  176018. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  176019. #endif
  176020. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  176021. # ifndef PNG_NO_WRITE_SHIFT
  176022. # define PNG_WRITE_SHIFT_SUPPORTED
  176023. # endif
  176024. # ifndef PNG_NO_WRITE_PACK
  176025. # define PNG_WRITE_PACK_SUPPORTED
  176026. # endif
  176027. # ifndef PNG_NO_WRITE_BGR
  176028. # define PNG_WRITE_BGR_SUPPORTED
  176029. # endif
  176030. # ifndef PNG_NO_WRITE_SWAP
  176031. # define PNG_WRITE_SWAP_SUPPORTED
  176032. # endif
  176033. # ifndef PNG_NO_WRITE_PACKSWAP
  176034. # define PNG_WRITE_PACKSWAP_SUPPORTED
  176035. # endif
  176036. # ifndef PNG_NO_WRITE_INVERT
  176037. # define PNG_WRITE_INVERT_SUPPORTED
  176038. # endif
  176039. # ifndef PNG_NO_WRITE_FILLER
  176040. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  176041. # endif
  176042. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  176043. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  176044. # endif
  176045. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  176046. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  176047. # endif
  176048. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  176049. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  176050. # endif
  176051. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  176052. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  176053. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  176054. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  176055. encoders, but can cause trouble
  176056. if left undefined */
  176057. #endif
  176058. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  176059. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  176060. defined(PNG_FLOATING_POINT_SUPPORTED)
  176061. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  176062. #endif
  176063. #ifndef PNG_NO_WRITE_FLUSH
  176064. # define PNG_WRITE_FLUSH_SUPPORTED
  176065. #endif
  176066. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176067. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  176068. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  176069. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  176070. #endif
  176071. #endif
  176072. #endif /* PNG_WRITE_SUPPORTED */
  176073. #ifndef PNG_1_0_X
  176074. # ifndef PNG_NO_ERROR_NUMBERS
  176075. # define PNG_ERROR_NUMBERS_SUPPORTED
  176076. # endif
  176077. #endif /* PNG_1_0_X */
  176078. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176079. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  176080. # ifndef PNG_NO_USER_TRANSFORM_PTR
  176081. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  176082. # endif
  176083. #endif
  176084. #ifndef PNG_NO_STDIO
  176085. # define PNG_TIME_RFC1123_SUPPORTED
  176086. #endif
  176087. /* This adds extra functions in pngget.c for accessing data from the
  176088. * info pointer (added in version 0.99)
  176089. * png_get_image_width()
  176090. * png_get_image_height()
  176091. * png_get_bit_depth()
  176092. * png_get_color_type()
  176093. * png_get_compression_type()
  176094. * png_get_filter_type()
  176095. * png_get_interlace_type()
  176096. * png_get_pixel_aspect_ratio()
  176097. * png_get_pixels_per_meter()
  176098. * png_get_x_offset_pixels()
  176099. * png_get_y_offset_pixels()
  176100. * png_get_x_offset_microns()
  176101. * png_get_y_offset_microns()
  176102. */
  176103. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  176104. # define PNG_EASY_ACCESS_SUPPORTED
  176105. #endif
  176106. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  176107. * and removed from version 1.2.20. The following will be removed
  176108. * from libpng-1.4.0
  176109. */
  176110. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  176111. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  176112. # define PNG_OPTIMIZED_CODE_SUPPORTED
  176113. # endif
  176114. #endif
  176115. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  176116. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  176117. # define PNG_ASSEMBLER_CODE_SUPPORTED
  176118. # endif
  176119. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  176120. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  176121. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176122. # define PNG_NO_MMX_CODE
  176123. # endif
  176124. # endif
  176125. # if defined(__APPLE__)
  176126. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176127. # define PNG_NO_MMX_CODE
  176128. # endif
  176129. # endif
  176130. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  176131. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176132. # define PNG_NO_MMX_CODE
  176133. # endif
  176134. # endif
  176135. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176136. # define PNG_MMX_CODE_SUPPORTED
  176137. # endif
  176138. #endif
  176139. /* end of obsolete code to be removed from libpng-1.4.0 */
  176140. #if !defined(PNG_1_0_X)
  176141. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  176142. # define PNG_USER_MEM_SUPPORTED
  176143. #endif
  176144. #endif /* PNG_1_0_X */
  176145. /* Added at libpng-1.2.6 */
  176146. #if !defined(PNG_1_0_X)
  176147. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  176148. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  176149. # define PNG_SET_USER_LIMITS_SUPPORTED
  176150. #endif
  176151. #endif
  176152. #endif /* PNG_1_0_X */
  176153. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  176154. * how large, set these limits to 0x7fffffffL
  176155. */
  176156. #ifndef PNG_USER_WIDTH_MAX
  176157. # define PNG_USER_WIDTH_MAX 1000000L
  176158. #endif
  176159. #ifndef PNG_USER_HEIGHT_MAX
  176160. # define PNG_USER_HEIGHT_MAX 1000000L
  176161. #endif
  176162. /* These are currently experimental features, define them if you want */
  176163. /* very little testing */
  176164. /*
  176165. #ifdef PNG_READ_SUPPORTED
  176166. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  176167. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  176168. # endif
  176169. #endif
  176170. */
  176171. /* This is only for PowerPC big-endian and 680x0 systems */
  176172. /* some testing */
  176173. /*
  176174. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  176175. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  176176. #endif
  176177. */
  176178. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  176179. /*
  176180. #define PNG_NO_POINTER_INDEXING
  176181. */
  176182. /* These functions are turned off by default, as they will be phased out. */
  176183. /*
  176184. #define PNG_USELESS_TESTS_SUPPORTED
  176185. #define PNG_CORRECT_PALETTE_SUPPORTED
  176186. */
  176187. /* Any chunks you are not interested in, you can undef here. The
  176188. * ones that allocate memory may be expecially important (hIST,
  176189. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  176190. * a bit smaller.
  176191. */
  176192. #if defined(PNG_READ_SUPPORTED) && \
  176193. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  176194. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  176195. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  176196. #endif
  176197. #if defined(PNG_WRITE_SUPPORTED) && \
  176198. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  176199. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  176200. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  176201. #endif
  176202. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  176203. #ifdef PNG_NO_READ_TEXT
  176204. # define PNG_NO_READ_iTXt
  176205. # define PNG_NO_READ_tEXt
  176206. # define PNG_NO_READ_zTXt
  176207. #endif
  176208. #ifndef PNG_NO_READ_bKGD
  176209. # define PNG_READ_bKGD_SUPPORTED
  176210. # define PNG_bKGD_SUPPORTED
  176211. #endif
  176212. #ifndef PNG_NO_READ_cHRM
  176213. # define PNG_READ_cHRM_SUPPORTED
  176214. # define PNG_cHRM_SUPPORTED
  176215. #endif
  176216. #ifndef PNG_NO_READ_gAMA
  176217. # define PNG_READ_gAMA_SUPPORTED
  176218. # define PNG_gAMA_SUPPORTED
  176219. #endif
  176220. #ifndef PNG_NO_READ_hIST
  176221. # define PNG_READ_hIST_SUPPORTED
  176222. # define PNG_hIST_SUPPORTED
  176223. #endif
  176224. #ifndef PNG_NO_READ_iCCP
  176225. # define PNG_READ_iCCP_SUPPORTED
  176226. # define PNG_iCCP_SUPPORTED
  176227. #endif
  176228. #ifndef PNG_NO_READ_iTXt
  176229. # ifndef PNG_READ_iTXt_SUPPORTED
  176230. # define PNG_READ_iTXt_SUPPORTED
  176231. # endif
  176232. # ifndef PNG_iTXt_SUPPORTED
  176233. # define PNG_iTXt_SUPPORTED
  176234. # endif
  176235. #endif
  176236. #ifndef PNG_NO_READ_oFFs
  176237. # define PNG_READ_oFFs_SUPPORTED
  176238. # define PNG_oFFs_SUPPORTED
  176239. #endif
  176240. #ifndef PNG_NO_READ_pCAL
  176241. # define PNG_READ_pCAL_SUPPORTED
  176242. # define PNG_pCAL_SUPPORTED
  176243. #endif
  176244. #ifndef PNG_NO_READ_sCAL
  176245. # define PNG_READ_sCAL_SUPPORTED
  176246. # define PNG_sCAL_SUPPORTED
  176247. #endif
  176248. #ifndef PNG_NO_READ_pHYs
  176249. # define PNG_READ_pHYs_SUPPORTED
  176250. # define PNG_pHYs_SUPPORTED
  176251. #endif
  176252. #ifndef PNG_NO_READ_sBIT
  176253. # define PNG_READ_sBIT_SUPPORTED
  176254. # define PNG_sBIT_SUPPORTED
  176255. #endif
  176256. #ifndef PNG_NO_READ_sPLT
  176257. # define PNG_READ_sPLT_SUPPORTED
  176258. # define PNG_sPLT_SUPPORTED
  176259. #endif
  176260. #ifndef PNG_NO_READ_sRGB
  176261. # define PNG_READ_sRGB_SUPPORTED
  176262. # define PNG_sRGB_SUPPORTED
  176263. #endif
  176264. #ifndef PNG_NO_READ_tEXt
  176265. # define PNG_READ_tEXt_SUPPORTED
  176266. # define PNG_tEXt_SUPPORTED
  176267. #endif
  176268. #ifndef PNG_NO_READ_tIME
  176269. # define PNG_READ_tIME_SUPPORTED
  176270. # define PNG_tIME_SUPPORTED
  176271. #endif
  176272. #ifndef PNG_NO_READ_tRNS
  176273. # define PNG_READ_tRNS_SUPPORTED
  176274. # define PNG_tRNS_SUPPORTED
  176275. #endif
  176276. #ifndef PNG_NO_READ_zTXt
  176277. # define PNG_READ_zTXt_SUPPORTED
  176278. # define PNG_zTXt_SUPPORTED
  176279. #endif
  176280. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  176281. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  176282. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  176283. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  176284. # endif
  176285. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  176286. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  176287. # endif
  176288. #endif
  176289. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  176290. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  176291. # define PNG_READ_USER_CHUNKS_SUPPORTED
  176292. # define PNG_USER_CHUNKS_SUPPORTED
  176293. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  176294. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  176295. # endif
  176296. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  176297. # undef PNG_NO_HANDLE_AS_UNKNOWN
  176298. # endif
  176299. #endif
  176300. #ifndef PNG_NO_READ_OPT_PLTE
  176301. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  176302. #endif /* optional PLTE chunk in RGB and RGBA images */
  176303. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  176304. defined(PNG_READ_zTXt_SUPPORTED)
  176305. # define PNG_READ_TEXT_SUPPORTED
  176306. # define PNG_TEXT_SUPPORTED
  176307. #endif
  176308. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  176309. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  176310. #ifdef PNG_NO_WRITE_TEXT
  176311. # define PNG_NO_WRITE_iTXt
  176312. # define PNG_NO_WRITE_tEXt
  176313. # define PNG_NO_WRITE_zTXt
  176314. #endif
  176315. #ifndef PNG_NO_WRITE_bKGD
  176316. # define PNG_WRITE_bKGD_SUPPORTED
  176317. # ifndef PNG_bKGD_SUPPORTED
  176318. # define PNG_bKGD_SUPPORTED
  176319. # endif
  176320. #endif
  176321. #ifndef PNG_NO_WRITE_cHRM
  176322. # define PNG_WRITE_cHRM_SUPPORTED
  176323. # ifndef PNG_cHRM_SUPPORTED
  176324. # define PNG_cHRM_SUPPORTED
  176325. # endif
  176326. #endif
  176327. #ifndef PNG_NO_WRITE_gAMA
  176328. # define PNG_WRITE_gAMA_SUPPORTED
  176329. # ifndef PNG_gAMA_SUPPORTED
  176330. # define PNG_gAMA_SUPPORTED
  176331. # endif
  176332. #endif
  176333. #ifndef PNG_NO_WRITE_hIST
  176334. # define PNG_WRITE_hIST_SUPPORTED
  176335. # ifndef PNG_hIST_SUPPORTED
  176336. # define PNG_hIST_SUPPORTED
  176337. # endif
  176338. #endif
  176339. #ifndef PNG_NO_WRITE_iCCP
  176340. # define PNG_WRITE_iCCP_SUPPORTED
  176341. # ifndef PNG_iCCP_SUPPORTED
  176342. # define PNG_iCCP_SUPPORTED
  176343. # endif
  176344. #endif
  176345. #ifndef PNG_NO_WRITE_iTXt
  176346. # ifndef PNG_WRITE_iTXt_SUPPORTED
  176347. # define PNG_WRITE_iTXt_SUPPORTED
  176348. # endif
  176349. # ifndef PNG_iTXt_SUPPORTED
  176350. # define PNG_iTXt_SUPPORTED
  176351. # endif
  176352. #endif
  176353. #ifndef PNG_NO_WRITE_oFFs
  176354. # define PNG_WRITE_oFFs_SUPPORTED
  176355. # ifndef PNG_oFFs_SUPPORTED
  176356. # define PNG_oFFs_SUPPORTED
  176357. # endif
  176358. #endif
  176359. #ifndef PNG_NO_WRITE_pCAL
  176360. # define PNG_WRITE_pCAL_SUPPORTED
  176361. # ifndef PNG_pCAL_SUPPORTED
  176362. # define PNG_pCAL_SUPPORTED
  176363. # endif
  176364. #endif
  176365. #ifndef PNG_NO_WRITE_sCAL
  176366. # define PNG_WRITE_sCAL_SUPPORTED
  176367. # ifndef PNG_sCAL_SUPPORTED
  176368. # define PNG_sCAL_SUPPORTED
  176369. # endif
  176370. #endif
  176371. #ifndef PNG_NO_WRITE_pHYs
  176372. # define PNG_WRITE_pHYs_SUPPORTED
  176373. # ifndef PNG_pHYs_SUPPORTED
  176374. # define PNG_pHYs_SUPPORTED
  176375. # endif
  176376. #endif
  176377. #ifndef PNG_NO_WRITE_sBIT
  176378. # define PNG_WRITE_sBIT_SUPPORTED
  176379. # ifndef PNG_sBIT_SUPPORTED
  176380. # define PNG_sBIT_SUPPORTED
  176381. # endif
  176382. #endif
  176383. #ifndef PNG_NO_WRITE_sPLT
  176384. # define PNG_WRITE_sPLT_SUPPORTED
  176385. # ifndef PNG_sPLT_SUPPORTED
  176386. # define PNG_sPLT_SUPPORTED
  176387. # endif
  176388. #endif
  176389. #ifndef PNG_NO_WRITE_sRGB
  176390. # define PNG_WRITE_sRGB_SUPPORTED
  176391. # ifndef PNG_sRGB_SUPPORTED
  176392. # define PNG_sRGB_SUPPORTED
  176393. # endif
  176394. #endif
  176395. #ifndef PNG_NO_WRITE_tEXt
  176396. # define PNG_WRITE_tEXt_SUPPORTED
  176397. # ifndef PNG_tEXt_SUPPORTED
  176398. # define PNG_tEXt_SUPPORTED
  176399. # endif
  176400. #endif
  176401. #ifndef PNG_NO_WRITE_tIME
  176402. # define PNG_WRITE_tIME_SUPPORTED
  176403. # ifndef PNG_tIME_SUPPORTED
  176404. # define PNG_tIME_SUPPORTED
  176405. # endif
  176406. #endif
  176407. #ifndef PNG_NO_WRITE_tRNS
  176408. # define PNG_WRITE_tRNS_SUPPORTED
  176409. # ifndef PNG_tRNS_SUPPORTED
  176410. # define PNG_tRNS_SUPPORTED
  176411. # endif
  176412. #endif
  176413. #ifndef PNG_NO_WRITE_zTXt
  176414. # define PNG_WRITE_zTXt_SUPPORTED
  176415. # ifndef PNG_zTXt_SUPPORTED
  176416. # define PNG_zTXt_SUPPORTED
  176417. # endif
  176418. #endif
  176419. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  176420. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  176421. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  176422. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  176423. # endif
  176424. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  176425. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  176426. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  176427. # endif
  176428. # endif
  176429. #endif
  176430. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  176431. defined(PNG_WRITE_zTXt_SUPPORTED)
  176432. # define PNG_WRITE_TEXT_SUPPORTED
  176433. # ifndef PNG_TEXT_SUPPORTED
  176434. # define PNG_TEXT_SUPPORTED
  176435. # endif
  176436. #endif
  176437. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  176438. /* Turn this off to disable png_read_png() and
  176439. * png_write_png() and leave the row_pointers member
  176440. * out of the info structure.
  176441. */
  176442. #ifndef PNG_NO_INFO_IMAGE
  176443. # define PNG_INFO_IMAGE_SUPPORTED
  176444. #endif
  176445. /* need the time information for reading tIME chunks */
  176446. #if defined(PNG_tIME_SUPPORTED)
  176447. # if !defined(_WIN32_WCE)
  176448. /* "time.h" functions are not supported on WindowsCE */
  176449. # include <time.h>
  176450. # endif
  176451. #endif
  176452. /* Some typedefs to get us started. These should be safe on most of the
  176453. * common platforms. The typedefs should be at least as large as the
  176454. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  176455. * don't have to be exactly that size. Some compilers dislike passing
  176456. * unsigned shorts as function parameters, so you may be better off using
  176457. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  176458. * want to have unsigned int for png_uint_32 instead of unsigned long.
  176459. */
  176460. typedef unsigned long png_uint_32;
  176461. typedef long png_int_32;
  176462. typedef unsigned short png_uint_16;
  176463. typedef short png_int_16;
  176464. typedef unsigned char png_byte;
  176465. /* This is usually size_t. It is typedef'ed just in case you need it to
  176466. change (I'm not sure if you will or not, so I thought I'd be safe) */
  176467. #ifdef PNG_SIZE_T
  176468. typedef PNG_SIZE_T png_size_t;
  176469. # define png_sizeof(x) png_convert_size(sizeof (x))
  176470. #else
  176471. typedef size_t png_size_t;
  176472. # define png_sizeof(x) sizeof (x)
  176473. #endif
  176474. /* The following is needed for medium model support. It cannot be in the
  176475. * PNG_INTERNAL section. Needs modification for other compilers besides
  176476. * MSC. Model independent support declares all arrays and pointers to be
  176477. * large using the far keyword. The zlib version used must also support
  176478. * model independent data. As of version zlib 1.0.4, the necessary changes
  176479. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  176480. * changes that are needed. (Tim Wegner)
  176481. */
  176482. /* Separate compiler dependencies (problem here is that zlib.h always
  176483. defines FAR. (SJT) */
  176484. #ifdef __BORLANDC__
  176485. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  176486. # define LDATA 1
  176487. # else
  176488. # define LDATA 0
  176489. # endif
  176490. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  176491. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  176492. # define PNG_MAX_MALLOC_64K
  176493. # if (LDATA != 1)
  176494. # ifndef FAR
  176495. # define FAR __far
  176496. # endif
  176497. # define USE_FAR_KEYWORD
  176498. # endif /* LDATA != 1 */
  176499. /* Possibly useful for moving data out of default segment.
  176500. * Uncomment it if you want. Could also define FARDATA as
  176501. * const if your compiler supports it. (SJT)
  176502. # define FARDATA FAR
  176503. */
  176504. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  176505. #endif /* __BORLANDC__ */
  176506. /* Suggest testing for specific compiler first before testing for
  176507. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  176508. * making reliance oncertain keywords suspect. (SJT)
  176509. */
  176510. /* MSC Medium model */
  176511. #if defined(FAR)
  176512. # if defined(M_I86MM)
  176513. # define USE_FAR_KEYWORD
  176514. # define FARDATA FAR
  176515. # include <dos.h>
  176516. # endif
  176517. #endif
  176518. /* SJT: default case */
  176519. #ifndef FAR
  176520. # define FAR
  176521. #endif
  176522. /* At this point FAR is always defined */
  176523. #ifndef FARDATA
  176524. # define FARDATA
  176525. #endif
  176526. /* Typedef for floating-point numbers that are converted
  176527. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  176528. typedef png_int_32 png_fixed_point;
  176529. /* Add typedefs for pointers */
  176530. typedef void FAR * png_voidp;
  176531. typedef png_byte FAR * png_bytep;
  176532. typedef png_uint_32 FAR * png_uint_32p;
  176533. typedef png_int_32 FAR * png_int_32p;
  176534. typedef png_uint_16 FAR * png_uint_16p;
  176535. typedef png_int_16 FAR * png_int_16p;
  176536. typedef PNG_CONST char FAR * png_const_charp;
  176537. typedef char FAR * png_charp;
  176538. typedef png_fixed_point FAR * png_fixed_point_p;
  176539. #ifndef PNG_NO_STDIO
  176540. #if defined(_WIN32_WCE)
  176541. typedef HANDLE png_FILE_p;
  176542. #else
  176543. typedef FILE * png_FILE_p;
  176544. #endif
  176545. #endif
  176546. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176547. typedef double FAR * png_doublep;
  176548. #endif
  176549. /* Pointers to pointers; i.e. arrays */
  176550. typedef png_byte FAR * FAR * png_bytepp;
  176551. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  176552. typedef png_int_32 FAR * FAR * png_int_32pp;
  176553. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  176554. typedef png_int_16 FAR * FAR * png_int_16pp;
  176555. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  176556. typedef char FAR * FAR * png_charpp;
  176557. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  176558. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176559. typedef double FAR * FAR * png_doublepp;
  176560. #endif
  176561. /* Pointers to pointers to pointers; i.e., pointer to array */
  176562. typedef char FAR * FAR * FAR * png_charppp;
  176563. #if 0
  176564. /* SPC - Is this stuff deprecated? */
  176565. /* It'll be removed as of libpng-1.3.0 - GR-P */
  176566. /* libpng typedefs for types in zlib. If zlib changes
  176567. * or another compression library is used, then change these.
  176568. * Eliminates need to change all the source files.
  176569. */
  176570. typedef charf * png_zcharp;
  176571. typedef charf * FAR * png_zcharpp;
  176572. typedef z_stream FAR * png_zstreamp;
  176573. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  176574. /*
  176575. * Define PNG_BUILD_DLL if the module being built is a Windows
  176576. * LIBPNG DLL.
  176577. *
  176578. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  176579. * It is equivalent to Microsoft predefined macro _DLL that is
  176580. * automatically defined when you compile using the share
  176581. * version of the CRT (C Run-Time library)
  176582. *
  176583. * The cygwin mods make this behavior a little different:
  176584. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  176585. * Define PNG_STATIC if you are building a static library for use with cygwin,
  176586. * -or- if you are building an application that you want to link to the
  176587. * static library.
  176588. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  176589. * the other flags is defined.
  176590. */
  176591. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  176592. # define PNG_DLL
  176593. #endif
  176594. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  176595. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  176596. * command-line override
  176597. */
  176598. #if defined(__CYGWIN__)
  176599. # if !defined(PNG_STATIC)
  176600. # if defined(PNG_USE_GLOBAL_ARRAYS)
  176601. # undef PNG_USE_GLOBAL_ARRAYS
  176602. # endif
  176603. # if !defined(PNG_USE_LOCAL_ARRAYS)
  176604. # define PNG_USE_LOCAL_ARRAYS
  176605. # endif
  176606. # else
  176607. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  176608. # if defined(PNG_USE_GLOBAL_ARRAYS)
  176609. # undef PNG_USE_GLOBAL_ARRAYS
  176610. # endif
  176611. # endif
  176612. # endif
  176613. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  176614. # define PNG_USE_LOCAL_ARRAYS
  176615. # endif
  176616. #endif
  176617. /* Do not use global arrays (helps with building DLL's)
  176618. * They are no longer used in libpng itself, since version 1.0.5c,
  176619. * but might be required for some pre-1.0.5c applications.
  176620. */
  176621. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  176622. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  176623. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  176624. # define PNG_USE_LOCAL_ARRAYS
  176625. # else
  176626. # define PNG_USE_GLOBAL_ARRAYS
  176627. # endif
  176628. #endif
  176629. #if defined(__CYGWIN__)
  176630. # undef PNGAPI
  176631. # define PNGAPI __cdecl
  176632. # undef PNG_IMPEXP
  176633. # define PNG_IMPEXP
  176634. #endif
  176635. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  176636. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  176637. * Don't ignore those warnings; you must also reset the default calling
  176638. * convention in your compiler to match your PNGAPI, and you must build
  176639. * zlib and your applications the same way you build libpng.
  176640. */
  176641. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  176642. # ifndef PNG_NO_MODULEDEF
  176643. # define PNG_NO_MODULEDEF
  176644. # endif
  176645. #endif
  176646. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  176647. # define PNG_IMPEXP
  176648. #endif
  176649. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  176650. (( defined(_Windows) || defined(_WINDOWS) || \
  176651. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  176652. # ifndef PNGAPI
  176653. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  176654. # define PNGAPI __cdecl
  176655. # else
  176656. # define PNGAPI _cdecl
  176657. # endif
  176658. # endif
  176659. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  176660. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  176661. # define PNG_IMPEXP
  176662. # endif
  176663. # if !defined(PNG_IMPEXP)
  176664. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  176665. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  176666. /* Borland/Microsoft */
  176667. # if defined(_MSC_VER) || defined(__BORLANDC__)
  176668. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  176669. # define PNG_EXPORT PNG_EXPORT_TYPE1
  176670. # else
  176671. # define PNG_EXPORT PNG_EXPORT_TYPE2
  176672. # if defined(PNG_BUILD_DLL)
  176673. # define PNG_IMPEXP __export
  176674. # else
  176675. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  176676. VC++ */
  176677. # endif /* Exists in Borland C++ for
  176678. C++ classes (== huge) */
  176679. # endif
  176680. # endif
  176681. # if !defined(PNG_IMPEXP)
  176682. # if defined(PNG_BUILD_DLL)
  176683. # define PNG_IMPEXP __declspec(dllexport)
  176684. # else
  176685. # define PNG_IMPEXP __declspec(dllimport)
  176686. # endif
  176687. # endif
  176688. # endif /* PNG_IMPEXP */
  176689. #else /* !(DLL || non-cygwin WINDOWS) */
  176690. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  176691. # ifndef PNGAPI
  176692. # define PNGAPI _System
  176693. # endif
  176694. # else
  176695. # if 0 /* ... other platforms, with other meanings */
  176696. # endif
  176697. # endif
  176698. #endif
  176699. #ifndef PNGAPI
  176700. # define PNGAPI
  176701. #endif
  176702. #ifndef PNG_IMPEXP
  176703. # define PNG_IMPEXP
  176704. #endif
  176705. #ifdef PNG_BUILDSYMS
  176706. # ifndef PNG_EXPORT
  176707. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  176708. # endif
  176709. # ifdef PNG_USE_GLOBAL_ARRAYS
  176710. # ifndef PNG_EXPORT_VAR
  176711. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  176712. # endif
  176713. # endif
  176714. #endif
  176715. #ifndef PNG_EXPORT
  176716. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  176717. #endif
  176718. #ifdef PNG_USE_GLOBAL_ARRAYS
  176719. # ifndef PNG_EXPORT_VAR
  176720. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  176721. # endif
  176722. #endif
  176723. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  176724. * functions that are passed far data must be model independent.
  176725. */
  176726. #ifndef PNG_ABORT
  176727. # define PNG_ABORT() abort()
  176728. #endif
  176729. #ifdef PNG_SETJMP_SUPPORTED
  176730. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  176731. #else
  176732. # define png_jmpbuf(png_ptr) \
  176733. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  176734. #endif
  176735. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  176736. /* use this to make far-to-near assignments */
  176737. # define CHECK 1
  176738. # define NOCHECK 0
  176739. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  176740. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  176741. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  176742. # define png_strcpy _fstrcpy
  176743. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  176744. # define png_strlen _fstrlen
  176745. # define png_memcmp _fmemcmp /* SJT: added */
  176746. # define png_memcpy _fmemcpy
  176747. # define png_memset _fmemset
  176748. #else /* use the usual functions */
  176749. # define CVT_PTR(ptr) (ptr)
  176750. # define CVT_PTR_NOCHECK(ptr) (ptr)
  176751. # ifndef PNG_NO_SNPRINTF
  176752. # ifdef _MSC_VER
  176753. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  176754. # define png_snprintf2 _snprintf
  176755. # define png_snprintf6 _snprintf
  176756. # else
  176757. # define png_snprintf snprintf /* Added to v 1.2.19 */
  176758. # define png_snprintf2 snprintf
  176759. # define png_snprintf6 snprintf
  176760. # endif
  176761. # else
  176762. /* You don't have or don't want to use snprintf(). Caution: Using
  176763. * sprintf instead of snprintf exposes your application to accidental
  176764. * or malevolent buffer overflows. If you don't have snprintf()
  176765. * as a general rule you should provide one (you can get one from
  176766. * Portable OpenSSH). */
  176767. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  176768. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  176769. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  176770. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  176771. # endif
  176772. # define png_strcpy strcpy
  176773. # define png_strncpy strncpy /* Added to v 1.2.6 */
  176774. # define png_strlen strlen
  176775. # define png_memcmp memcmp /* SJT: added */
  176776. # define png_memcpy memcpy
  176777. # define png_memset memset
  176778. #endif
  176779. /* End of memory model independent support */
  176780. /* Just a little check that someone hasn't tried to define something
  176781. * contradictory.
  176782. */
  176783. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  176784. # undef PNG_ZBUF_SIZE
  176785. # define PNG_ZBUF_SIZE 65536L
  176786. #endif
  176787. /* Added at libpng-1.2.8 */
  176788. #endif /* PNG_VERSION_INFO_ONLY */
  176789. #endif /* PNGCONF_H */
  176790. /********* End of inlined file: pngconf.h *********/
  176791. #ifdef _MSC_VER
  176792. #pragma warning (disable: 4996 4100)
  176793. #endif
  176794. /*
  176795. * Added at libpng-1.2.8 */
  176796. /* Ref MSDN: Private as priority over Special
  176797. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  176798. * procedures. If this value is given, the StringFileInfo block must
  176799. * contain a PrivateBuild string.
  176800. *
  176801. * VS_FF_SPECIALBUILD File *was* built by the original company using
  176802. * standard release procedures but is a variation of the standard
  176803. * file of the same version number. If this value is given, the
  176804. * StringFileInfo block must contain a SpecialBuild string.
  176805. */
  176806. #if defined(PNG_USER_PRIVATEBUILD)
  176807. # define PNG_LIBPNG_BUILD_TYPE \
  176808. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  176809. #else
  176810. # if defined(PNG_LIBPNG_SPECIALBUILD)
  176811. # define PNG_LIBPNG_BUILD_TYPE \
  176812. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  176813. # else
  176814. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  176815. # endif
  176816. #endif
  176817. #ifndef PNG_VERSION_INFO_ONLY
  176818. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  176819. #ifdef __cplusplus
  176820. extern "C" {
  176821. #endif /* __cplusplus */
  176822. /* This file is arranged in several sections. The first section contains
  176823. * structure and type definitions. The second section contains the external
  176824. * library functions, while the third has the internal library functions,
  176825. * which applications aren't expected to use directly.
  176826. */
  176827. #ifndef PNG_NO_TYPECAST_NULL
  176828. #define int_p_NULL (int *)NULL
  176829. #define png_bytep_NULL (png_bytep)NULL
  176830. #define png_bytepp_NULL (png_bytepp)NULL
  176831. #define png_doublep_NULL (png_doublep)NULL
  176832. #define png_error_ptr_NULL (png_error_ptr)NULL
  176833. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  176834. #define png_free_ptr_NULL (png_free_ptr)NULL
  176835. #define png_infopp_NULL (png_infopp)NULL
  176836. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  176837. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  176838. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  176839. #define png_structp_NULL (png_structp)NULL
  176840. #define png_uint_16p_NULL (png_uint_16p)NULL
  176841. #define png_voidp_NULL (png_voidp)NULL
  176842. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  176843. #else
  176844. #define int_p_NULL NULL
  176845. #define png_bytep_NULL NULL
  176846. #define png_bytepp_NULL NULL
  176847. #define png_doublep_NULL NULL
  176848. #define png_error_ptr_NULL NULL
  176849. #define png_flush_ptr_NULL NULL
  176850. #define png_free_ptr_NULL NULL
  176851. #define png_infopp_NULL NULL
  176852. #define png_malloc_ptr_NULL NULL
  176853. #define png_read_status_ptr_NULL NULL
  176854. #define png_rw_ptr_NULL NULL
  176855. #define png_structp_NULL NULL
  176856. #define png_uint_16p_NULL NULL
  176857. #define png_voidp_NULL NULL
  176858. #define png_write_status_ptr_NULL NULL
  176859. #endif
  176860. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  176861. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  176862. /* Version information for C files, stored in png.c. This had better match
  176863. * the version above.
  176864. */
  176865. #ifdef PNG_USE_GLOBAL_ARRAYS
  176866. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  176867. /* need room for 99.99.99beta99z */
  176868. #else
  176869. #define png_libpng_ver png_get_header_ver(NULL)
  176870. #endif
  176871. #ifdef PNG_USE_GLOBAL_ARRAYS
  176872. /* This was removed in version 1.0.5c */
  176873. /* Structures to facilitate easy interlacing. See png.c for more details */
  176874. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  176875. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  176876. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  176877. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  176878. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  176879. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  176880. /* This isn't currently used. If you need it, see png.c for more details.
  176881. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  176882. */
  176883. #endif
  176884. #endif /* PNG_NO_EXTERN */
  176885. /* Three color definitions. The order of the red, green, and blue, (and the
  176886. * exact size) is not important, although the size of the fields need to
  176887. * be png_byte or png_uint_16 (as defined below).
  176888. */
  176889. typedef struct png_color_struct
  176890. {
  176891. png_byte red;
  176892. png_byte green;
  176893. png_byte blue;
  176894. } png_color;
  176895. typedef png_color FAR * png_colorp;
  176896. typedef png_color FAR * FAR * png_colorpp;
  176897. typedef struct png_color_16_struct
  176898. {
  176899. png_byte index; /* used for palette files */
  176900. png_uint_16 red; /* for use in red green blue files */
  176901. png_uint_16 green;
  176902. png_uint_16 blue;
  176903. png_uint_16 gray; /* for use in grayscale files */
  176904. } png_color_16;
  176905. typedef png_color_16 FAR * png_color_16p;
  176906. typedef png_color_16 FAR * FAR * png_color_16pp;
  176907. typedef struct png_color_8_struct
  176908. {
  176909. png_byte red; /* for use in red green blue files */
  176910. png_byte green;
  176911. png_byte blue;
  176912. png_byte gray; /* for use in grayscale files */
  176913. png_byte alpha; /* for alpha channel files */
  176914. } png_color_8;
  176915. typedef png_color_8 FAR * png_color_8p;
  176916. typedef png_color_8 FAR * FAR * png_color_8pp;
  176917. /*
  176918. * The following two structures are used for the in-core representation
  176919. * of sPLT chunks.
  176920. */
  176921. typedef struct png_sPLT_entry_struct
  176922. {
  176923. png_uint_16 red;
  176924. png_uint_16 green;
  176925. png_uint_16 blue;
  176926. png_uint_16 alpha;
  176927. png_uint_16 frequency;
  176928. } png_sPLT_entry;
  176929. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  176930. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  176931. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  176932. * occupy the LSB of their respective members, and the MSB of each member
  176933. * is zero-filled. The frequency member always occupies the full 16 bits.
  176934. */
  176935. typedef struct png_sPLT_struct
  176936. {
  176937. png_charp name; /* palette name */
  176938. png_byte depth; /* depth of palette samples */
  176939. png_sPLT_entryp entries; /* palette entries */
  176940. png_int_32 nentries; /* number of palette entries */
  176941. } png_sPLT_t;
  176942. typedef png_sPLT_t FAR * png_sPLT_tp;
  176943. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  176944. #ifdef PNG_TEXT_SUPPORTED
  176945. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  176946. * and whether that contents is compressed or not. The "key" field
  176947. * points to a regular zero-terminated C string. The "text", "lang", and
  176948. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  176949. * However, the * structure returned by png_get_text() will always contain
  176950. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  176951. * so they can be safely used in printf() and other string-handling functions.
  176952. */
  176953. typedef struct png_text_struct
  176954. {
  176955. int compression; /* compression value:
  176956. -1: tEXt, none
  176957. 0: zTXt, deflate
  176958. 1: iTXt, none
  176959. 2: iTXt, deflate */
  176960. png_charp key; /* keyword, 1-79 character description of "text" */
  176961. png_charp text; /* comment, may be an empty string (ie "")
  176962. or a NULL pointer */
  176963. png_size_t text_length; /* length of the text string */
  176964. #ifdef PNG_iTXt_SUPPORTED
  176965. png_size_t itxt_length; /* length of the itxt string */
  176966. png_charp lang; /* language code, 0-79 characters
  176967. or a NULL pointer */
  176968. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  176969. chars or a NULL pointer */
  176970. #endif
  176971. } png_text;
  176972. typedef png_text FAR * png_textp;
  176973. typedef png_text FAR * FAR * png_textpp;
  176974. #endif
  176975. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  176976. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  176977. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  176978. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  176979. #define PNG_TEXT_COMPRESSION_NONE -1
  176980. #define PNG_TEXT_COMPRESSION_zTXt 0
  176981. #define PNG_ITXT_COMPRESSION_NONE 1
  176982. #define PNG_ITXT_COMPRESSION_zTXt 2
  176983. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  176984. /* png_time is a way to hold the time in an machine independent way.
  176985. * Two conversions are provided, both from time_t and struct tm. There
  176986. * is no portable way to convert to either of these structures, as far
  176987. * as I know. If you know of a portable way, send it to me. As a side
  176988. * note - PNG has always been Year 2000 compliant!
  176989. */
  176990. typedef struct png_time_struct
  176991. {
  176992. png_uint_16 year; /* full year, as in, 1995 */
  176993. png_byte month; /* month of year, 1 - 12 */
  176994. png_byte day; /* day of month, 1 - 31 */
  176995. png_byte hour; /* hour of day, 0 - 23 */
  176996. png_byte minute; /* minute of hour, 0 - 59 */
  176997. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  176998. } png_time;
  176999. typedef png_time FAR * png_timep;
  177000. typedef png_time FAR * FAR * png_timepp;
  177001. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177002. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  177003. * no specific support. The idea is that we can use this to queue
  177004. * up private chunks for output even though the library doesn't actually
  177005. * know about their semantics.
  177006. */
  177007. typedef struct png_unknown_chunk_t
  177008. {
  177009. png_byte name[5];
  177010. png_byte *data;
  177011. png_size_t size;
  177012. /* libpng-using applications should NOT directly modify this byte. */
  177013. png_byte location; /* mode of operation at read time */
  177014. }
  177015. png_unknown_chunk;
  177016. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  177017. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  177018. #endif
  177019. /* png_info is a structure that holds the information in a PNG file so
  177020. * that the application can find out the characteristics of the image.
  177021. * If you are reading the file, this structure will tell you what is
  177022. * in the PNG file. If you are writing the file, fill in the information
  177023. * you want to put into the PNG file, then call png_write_info().
  177024. * The names chosen should be very close to the PNG specification, so
  177025. * consult that document for information about the meaning of each field.
  177026. *
  177027. * With libpng < 0.95, it was only possible to directly set and read the
  177028. * the values in the png_info_struct, which meant that the contents and
  177029. * order of the values had to remain fixed. With libpng 0.95 and later,
  177030. * however, there are now functions that abstract the contents of
  177031. * png_info_struct from the application, so this makes it easier to use
  177032. * libpng with dynamic libraries, and even makes it possible to use
  177033. * libraries that don't have all of the libpng ancillary chunk-handing
  177034. * functionality.
  177035. *
  177036. * In any case, the order of the parameters in png_info_struct should NOT
  177037. * be changed for as long as possible to keep compatibility with applications
  177038. * that use the old direct-access method with png_info_struct.
  177039. *
  177040. * The following members may have allocated storage attached that should be
  177041. * cleaned up before the structure is discarded: palette, trans, text,
  177042. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  177043. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  177044. * are automatically freed when the info structure is deallocated, if they were
  177045. * allocated internally by libpng. This behavior can be changed by means
  177046. * of the png_data_freer() function.
  177047. *
  177048. * More allocation details: all the chunk-reading functions that
  177049. * change these members go through the corresponding png_set_*
  177050. * functions. A function to clear these members is available: see
  177051. * png_free_data(). The png_set_* functions do not depend on being
  177052. * able to point info structure members to any of the storage they are
  177053. * passed (they make their own copies), EXCEPT that the png_set_text
  177054. * functions use the same storage passed to them in the text_ptr or
  177055. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  177056. * functions do not make their own copies.
  177057. */
  177058. typedef struct png_info_struct
  177059. {
  177060. /* the following are necessary for every PNG file */
  177061. png_uint_32 width; /* width of image in pixels (from IHDR) */
  177062. png_uint_32 height; /* height of image in pixels (from IHDR) */
  177063. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  177064. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  177065. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  177066. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  177067. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  177068. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  177069. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  177070. /* The following three should have been named *_method not *_type */
  177071. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  177072. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  177073. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  177074. /* The following is informational only on read, and not used on writes. */
  177075. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  177076. png_byte pixel_depth; /* number of bits per pixel */
  177077. png_byte spare_byte; /* to align the data, and for future use */
  177078. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  177079. /* The rest of the data is optional. If you are reading, check the
  177080. * valid field to see if the information in these are valid. If you
  177081. * are writing, set the valid field to those chunks you want written,
  177082. * and initialize the appropriate fields below.
  177083. */
  177084. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  177085. /* The gAMA chunk describes the gamma characteristics of the system
  177086. * on which the image was created, normally in the range [1.0, 2.5].
  177087. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  177088. */
  177089. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  177090. #endif
  177091. #if defined(PNG_sRGB_SUPPORTED)
  177092. /* GR-P, 0.96a */
  177093. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  177094. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  177095. #endif
  177096. #if defined(PNG_TEXT_SUPPORTED)
  177097. /* The tEXt, and zTXt chunks contain human-readable textual data in
  177098. * uncompressed, compressed, and optionally compressed forms, respectively.
  177099. * The data in "text" is an array of pointers to uncompressed,
  177100. * null-terminated C strings. Each chunk has a keyword that describes the
  177101. * textual data contained in that chunk. Keywords are not required to be
  177102. * unique, and the text string may be empty. Any number of text chunks may
  177103. * be in an image.
  177104. */
  177105. int num_text; /* number of comments read/to write */
  177106. int max_text; /* current size of text array */
  177107. png_textp text; /* array of comments read/to write */
  177108. #endif /* PNG_TEXT_SUPPORTED */
  177109. #if defined(PNG_tIME_SUPPORTED)
  177110. /* The tIME chunk holds the last time the displayed image data was
  177111. * modified. See the png_time struct for the contents of this struct.
  177112. */
  177113. png_time mod_time;
  177114. #endif
  177115. #if defined(PNG_sBIT_SUPPORTED)
  177116. /* The sBIT chunk specifies the number of significant high-order bits
  177117. * in the pixel data. Values are in the range [1, bit_depth], and are
  177118. * only specified for the channels in the pixel data. The contents of
  177119. * the low-order bits is not specified. Data is valid if
  177120. * (valid & PNG_INFO_sBIT) is non-zero.
  177121. */
  177122. png_color_8 sig_bit; /* significant bits in color channels */
  177123. #endif
  177124. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  177125. defined(PNG_READ_BACKGROUND_SUPPORTED)
  177126. /* The tRNS chunk supplies transparency data for paletted images and
  177127. * other image types that don't need a full alpha channel. There are
  177128. * "num_trans" transparency values for a paletted image, stored in the
  177129. * same order as the palette colors, starting from index 0. Values
  177130. * for the data are in the range [0, 255], ranging from fully transparent
  177131. * to fully opaque, respectively. For non-paletted images, there is a
  177132. * single color specified that should be treated as fully transparent.
  177133. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  177134. */
  177135. png_bytep trans; /* transparent values for paletted image */
  177136. png_color_16 trans_values; /* transparent color for non-palette image */
  177137. #endif
  177138. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  177139. /* The bKGD chunk gives the suggested image background color if the
  177140. * display program does not have its own background color and the image
  177141. * is needs to composited onto a background before display. The colors
  177142. * in "background" are normally in the same color space/depth as the
  177143. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  177144. */
  177145. png_color_16 background;
  177146. #endif
  177147. #if defined(PNG_oFFs_SUPPORTED)
  177148. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  177149. * and downwards from the top-left corner of the display, page, or other
  177150. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  177151. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  177152. */
  177153. png_int_32 x_offset; /* x offset on page */
  177154. png_int_32 y_offset; /* y offset on page */
  177155. png_byte offset_unit_type; /* offset units type */
  177156. #endif
  177157. #if defined(PNG_pHYs_SUPPORTED)
  177158. /* The pHYs chunk gives the physical pixel density of the image for
  177159. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  177160. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  177161. */
  177162. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  177163. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  177164. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  177165. #endif
  177166. #if defined(PNG_hIST_SUPPORTED)
  177167. /* The hIST chunk contains the relative frequency or importance of the
  177168. * various palette entries, so that a viewer can intelligently select a
  177169. * reduced-color palette, if required. Data is an array of "num_palette"
  177170. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  177171. * is non-zero.
  177172. */
  177173. png_uint_16p hist;
  177174. #endif
  177175. #ifdef PNG_cHRM_SUPPORTED
  177176. /* The cHRM chunk describes the CIE color characteristics of the monitor
  177177. * on which the PNG was created. This data allows the viewer to do gamut
  177178. * mapping of the input image to ensure that the viewer sees the same
  177179. * colors in the image as the creator. Values are in the range
  177180. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  177181. */
  177182. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177183. float x_white;
  177184. float y_white;
  177185. float x_red;
  177186. float y_red;
  177187. float x_green;
  177188. float y_green;
  177189. float x_blue;
  177190. float y_blue;
  177191. #endif
  177192. #endif
  177193. #if defined(PNG_pCAL_SUPPORTED)
  177194. /* The pCAL chunk describes a transformation between the stored pixel
  177195. * values and original physical data values used to create the image.
  177196. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  177197. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  177198. * (possibly non-linear) transformation function given by "pcal_type"
  177199. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  177200. * defines below, and the PNG-Group's PNG extensions document for a
  177201. * complete description of the transformations and how they should be
  177202. * implemented, and for a description of the ASCII parameter strings.
  177203. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  177204. */
  177205. png_charp pcal_purpose; /* pCAL chunk description string */
  177206. png_int_32 pcal_X0; /* minimum value */
  177207. png_int_32 pcal_X1; /* maximum value */
  177208. png_charp pcal_units; /* Latin-1 string giving physical units */
  177209. png_charpp pcal_params; /* ASCII strings containing parameter values */
  177210. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  177211. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  177212. #endif
  177213. /* New members added in libpng-1.0.6 */
  177214. #ifdef PNG_FREE_ME_SUPPORTED
  177215. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  177216. #endif
  177217. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177218. /* storage for unknown chunks that the library doesn't recognize. */
  177219. png_unknown_chunkp unknown_chunks;
  177220. png_size_t unknown_chunks_num;
  177221. #endif
  177222. #if defined(PNG_iCCP_SUPPORTED)
  177223. /* iCCP chunk data. */
  177224. png_charp iccp_name; /* profile name */
  177225. png_charp iccp_profile; /* International Color Consortium profile data */
  177226. /* Note to maintainer: should be png_bytep */
  177227. png_uint_32 iccp_proflen; /* ICC profile data length */
  177228. png_byte iccp_compression; /* Always zero */
  177229. #endif
  177230. #if defined(PNG_sPLT_SUPPORTED)
  177231. /* data on sPLT chunks (there may be more than one). */
  177232. png_sPLT_tp splt_palettes;
  177233. png_uint_32 splt_palettes_num;
  177234. #endif
  177235. #if defined(PNG_sCAL_SUPPORTED)
  177236. /* The sCAL chunk describes the actual physical dimensions of the
  177237. * subject matter of the graphic. The chunk contains a unit specification
  177238. * a byte value, and two ASCII strings representing floating-point
  177239. * values. The values are width and height corresponsing to one pixel
  177240. * in the image. This external representation is converted to double
  177241. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  177242. */
  177243. png_byte scal_unit; /* unit of physical scale */
  177244. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177245. double scal_pixel_width; /* width of one pixel */
  177246. double scal_pixel_height; /* height of one pixel */
  177247. #endif
  177248. #ifdef PNG_FIXED_POINT_SUPPORTED
  177249. png_charp scal_s_width; /* string containing height */
  177250. png_charp scal_s_height; /* string containing width */
  177251. #endif
  177252. #endif
  177253. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  177254. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  177255. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  177256. png_bytepp row_pointers; /* the image bits */
  177257. #endif
  177258. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  177259. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  177260. #endif
  177261. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  177262. png_fixed_point int_x_white;
  177263. png_fixed_point int_y_white;
  177264. png_fixed_point int_x_red;
  177265. png_fixed_point int_y_red;
  177266. png_fixed_point int_x_green;
  177267. png_fixed_point int_y_green;
  177268. png_fixed_point int_x_blue;
  177269. png_fixed_point int_y_blue;
  177270. #endif
  177271. } png_info;
  177272. typedef png_info FAR * png_infop;
  177273. typedef png_info FAR * FAR * png_infopp;
  177274. /* Maximum positive integer used in PNG is (2^31)-1 */
  177275. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  177276. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  177277. #define PNG_SIZE_MAX ((png_size_t)(-1))
  177278. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177279. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  177280. #define PNG_MAX_UINT PNG_UINT_31_MAX
  177281. #endif
  177282. /* These describe the color_type field in png_info. */
  177283. /* color type masks */
  177284. #define PNG_COLOR_MASK_PALETTE 1
  177285. #define PNG_COLOR_MASK_COLOR 2
  177286. #define PNG_COLOR_MASK_ALPHA 4
  177287. /* color types. Note that not all combinations are legal */
  177288. #define PNG_COLOR_TYPE_GRAY 0
  177289. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  177290. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  177291. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  177292. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  177293. /* aliases */
  177294. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  177295. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  177296. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  177297. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  177298. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  177299. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  177300. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  177301. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  177302. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  177303. /* These are for the interlacing type. These values should NOT be changed. */
  177304. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  177305. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  177306. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  177307. /* These are for the oFFs chunk. These values should NOT be changed. */
  177308. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  177309. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  177310. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  177311. /* These are for the pCAL chunk. These values should NOT be changed. */
  177312. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  177313. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  177314. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  177315. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  177316. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  177317. /* These are for the sCAL chunk. These values should NOT be changed. */
  177318. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  177319. #define PNG_SCALE_METER 1 /* meters per pixel */
  177320. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  177321. #define PNG_SCALE_LAST 3 /* Not a valid value */
  177322. /* These are for the pHYs chunk. These values should NOT be changed. */
  177323. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  177324. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  177325. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  177326. /* These are for the sRGB chunk. These values should NOT be changed. */
  177327. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  177328. #define PNG_sRGB_INTENT_RELATIVE 1
  177329. #define PNG_sRGB_INTENT_SATURATION 2
  177330. #define PNG_sRGB_INTENT_ABSOLUTE 3
  177331. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  177332. /* This is for text chunks */
  177333. #define PNG_KEYWORD_MAX_LENGTH 79
  177334. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  177335. #define PNG_MAX_PALETTE_LENGTH 256
  177336. /* These determine if an ancillary chunk's data has been successfully read
  177337. * from the PNG header, or if the application has filled in the corresponding
  177338. * data in the info_struct to be written into the output file. The values
  177339. * of the PNG_INFO_<chunk> defines should NOT be changed.
  177340. */
  177341. #define PNG_INFO_gAMA 0x0001
  177342. #define PNG_INFO_sBIT 0x0002
  177343. #define PNG_INFO_cHRM 0x0004
  177344. #define PNG_INFO_PLTE 0x0008
  177345. #define PNG_INFO_tRNS 0x0010
  177346. #define PNG_INFO_bKGD 0x0020
  177347. #define PNG_INFO_hIST 0x0040
  177348. #define PNG_INFO_pHYs 0x0080
  177349. #define PNG_INFO_oFFs 0x0100
  177350. #define PNG_INFO_tIME 0x0200
  177351. #define PNG_INFO_pCAL 0x0400
  177352. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  177353. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  177354. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  177355. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  177356. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  177357. /* This is used for the transformation routines, as some of them
  177358. * change these values for the row. It also should enable using
  177359. * the routines for other purposes.
  177360. */
  177361. typedef struct png_row_info_struct
  177362. {
  177363. png_uint_32 width; /* width of row */
  177364. png_uint_32 rowbytes; /* number of bytes in row */
  177365. png_byte color_type; /* color type of row */
  177366. png_byte bit_depth; /* bit depth of row */
  177367. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  177368. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  177369. } png_row_info;
  177370. typedef png_row_info FAR * png_row_infop;
  177371. typedef png_row_info FAR * FAR * png_row_infopp;
  177372. /* These are the function types for the I/O functions and for the functions
  177373. * that allow the user to override the default I/O functions with his or her
  177374. * own. The png_error_ptr type should match that of user-supplied warning
  177375. * and error functions, while the png_rw_ptr type should match that of the
  177376. * user read/write data functions.
  177377. */
  177378. typedef struct png_struct_def png_struct;
  177379. typedef png_struct FAR * png_structp;
  177380. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  177381. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  177382. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  177383. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  177384. int));
  177385. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  177386. int));
  177387. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  177388. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  177389. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  177390. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  177391. png_uint_32, int));
  177392. #endif
  177393. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  177394. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  177395. defined(PNG_LEGACY_SUPPORTED)
  177396. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  177397. png_row_infop, png_bytep));
  177398. #endif
  177399. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  177400. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  177401. #endif
  177402. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177403. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  177404. #endif
  177405. /* Transform masks for the high-level interface */
  177406. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  177407. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  177408. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  177409. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  177410. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  177411. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  177412. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  177413. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  177414. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  177415. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  177416. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  177417. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  177418. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  177419. /* Flags for MNG supported features */
  177420. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  177421. #define PNG_FLAG_MNG_FILTER_64 0x04
  177422. #define PNG_ALL_MNG_FEATURES 0x05
  177423. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  177424. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  177425. /* The structure that holds the information to read and write PNG files.
  177426. * The only people who need to care about what is inside of this are the
  177427. * people who will be modifying the library for their own special needs.
  177428. * It should NOT be accessed directly by an application, except to store
  177429. * the jmp_buf.
  177430. */
  177431. struct png_struct_def
  177432. {
  177433. #ifdef PNG_SETJMP_SUPPORTED
  177434. jmp_buf jmpbuf; /* used in png_error */
  177435. #endif
  177436. png_error_ptr error_fn; /* function for printing errors and aborting */
  177437. png_error_ptr warning_fn; /* function for printing warnings */
  177438. png_voidp error_ptr; /* user supplied struct for error functions */
  177439. png_rw_ptr write_data_fn; /* function for writing output data */
  177440. png_rw_ptr read_data_fn; /* function for reading input data */
  177441. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  177442. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  177443. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  177444. #endif
  177445. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  177446. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  177447. #endif
  177448. /* These were added in libpng-1.0.2 */
  177449. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  177450. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  177451. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  177452. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  177453. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  177454. png_byte user_transform_channels; /* channels in user transformed pixels */
  177455. #endif
  177456. #endif
  177457. png_uint_32 mode; /* tells us where we are in the PNG file */
  177458. png_uint_32 flags; /* flags indicating various things to libpng */
  177459. png_uint_32 transformations; /* which transformations to perform */
  177460. z_stream zstream; /* pointer to decompression structure (below) */
  177461. png_bytep zbuf; /* buffer for zlib */
  177462. png_size_t zbuf_size; /* size of zbuf */
  177463. int zlib_level; /* holds zlib compression level */
  177464. int zlib_method; /* holds zlib compression method */
  177465. int zlib_window_bits; /* holds zlib compression window bits */
  177466. int zlib_mem_level; /* holds zlib compression memory level */
  177467. int zlib_strategy; /* holds zlib compression strategy */
  177468. png_uint_32 width; /* width of image in pixels */
  177469. png_uint_32 height; /* height of image in pixels */
  177470. png_uint_32 num_rows; /* number of rows in current pass */
  177471. png_uint_32 usr_width; /* width of row at start of write */
  177472. png_uint_32 rowbytes; /* size of row in bytes */
  177473. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  177474. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  177475. png_uint_32 row_number; /* current row in interlace pass */
  177476. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  177477. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  177478. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  177479. png_bytep up_row; /* buffer to save "up" row when filtering */
  177480. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  177481. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  177482. png_row_info row_info; /* used for transformation routines */
  177483. png_uint_32 idat_size; /* current IDAT size for read */
  177484. png_uint_32 crc; /* current chunk CRC value */
  177485. png_colorp palette; /* palette from the input file */
  177486. png_uint_16 num_palette; /* number of color entries in palette */
  177487. png_uint_16 num_trans; /* number of transparency values */
  177488. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  177489. png_byte compression; /* file compression type (always 0) */
  177490. png_byte filter; /* file filter type (always 0) */
  177491. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  177492. png_byte pass; /* current interlace pass (0 - 6) */
  177493. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  177494. png_byte color_type; /* color type of file */
  177495. png_byte bit_depth; /* bit depth of file */
  177496. png_byte usr_bit_depth; /* bit depth of users row */
  177497. png_byte pixel_depth; /* number of bits per pixel */
  177498. png_byte channels; /* number of channels in file */
  177499. png_byte usr_channels; /* channels at start of write */
  177500. png_byte sig_bytes; /* magic bytes read/written from start of file */
  177501. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  177502. #ifdef PNG_LEGACY_SUPPORTED
  177503. png_byte filler; /* filler byte for pixel expansion */
  177504. #else
  177505. png_uint_16 filler; /* filler bytes for pixel expansion */
  177506. #endif
  177507. #endif
  177508. #if defined(PNG_bKGD_SUPPORTED)
  177509. png_byte background_gamma_type;
  177510. # ifdef PNG_FLOATING_POINT_SUPPORTED
  177511. float background_gamma;
  177512. # endif
  177513. png_color_16 background; /* background color in screen gamma space */
  177514. #if defined(PNG_READ_GAMMA_SUPPORTED)
  177515. png_color_16 background_1; /* background normalized to gamma 1.0 */
  177516. #endif
  177517. #endif /* PNG_bKGD_SUPPORTED */
  177518. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  177519. png_flush_ptr output_flush_fn;/* Function for flushing output */
  177520. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  177521. png_uint_32 flush_rows; /* number of rows written since last flush */
  177522. #endif
  177523. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  177524. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  177525. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177526. float gamma; /* file gamma value */
  177527. float screen_gamma; /* screen gamma value (display_exponent) */
  177528. #endif
  177529. #endif
  177530. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  177531. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  177532. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  177533. png_bytep gamma_to_1; /* converts from file to 1.0 */
  177534. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  177535. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  177536. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  177537. #endif
  177538. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  177539. png_color_8 sig_bit; /* significant bits in each available channel */
  177540. #endif
  177541. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  177542. png_color_8 shift; /* shift for significant bit tranformation */
  177543. #endif
  177544. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  177545. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  177546. png_bytep trans; /* transparency values for paletted files */
  177547. png_color_16 trans_values; /* transparency values for non-paletted files */
  177548. #endif
  177549. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  177550. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  177551. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  177552. png_progressive_info_ptr info_fn; /* called after header data fully read */
  177553. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  177554. png_progressive_end_ptr end_fn; /* called after image is complete */
  177555. png_bytep save_buffer_ptr; /* current location in save_buffer */
  177556. png_bytep save_buffer; /* buffer for previously read data */
  177557. png_bytep current_buffer_ptr; /* current location in current_buffer */
  177558. png_bytep current_buffer; /* buffer for recently used data */
  177559. png_uint_32 push_length; /* size of current input chunk */
  177560. png_uint_32 skip_length; /* bytes to skip in input data */
  177561. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  177562. png_size_t save_buffer_max; /* total size of save_buffer */
  177563. png_size_t buffer_size; /* total amount of available input data */
  177564. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  177565. int process_mode; /* what push library is currently doing */
  177566. int cur_palette; /* current push library palette index */
  177567. # if defined(PNG_TEXT_SUPPORTED)
  177568. png_size_t current_text_size; /* current size of text input data */
  177569. png_size_t current_text_left; /* how much text left to read in input */
  177570. png_charp current_text; /* current text chunk buffer */
  177571. png_charp current_text_ptr; /* current location in current_text */
  177572. # endif /* PNG_TEXT_SUPPORTED */
  177573. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  177574. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  177575. /* for the Borland special 64K segment handler */
  177576. png_bytepp offset_table_ptr;
  177577. png_bytep offset_table;
  177578. png_uint_16 offset_table_number;
  177579. png_uint_16 offset_table_count;
  177580. png_uint_16 offset_table_count_free;
  177581. #endif
  177582. #if defined(PNG_READ_DITHER_SUPPORTED)
  177583. png_bytep palette_lookup; /* lookup table for dithering */
  177584. png_bytep dither_index; /* index translation for palette files */
  177585. #endif
  177586. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  177587. png_uint_16p hist; /* histogram */
  177588. #endif
  177589. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  177590. png_byte heuristic_method; /* heuristic for row filter selection */
  177591. png_byte num_prev_filters; /* number of weights for previous rows */
  177592. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  177593. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  177594. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  177595. png_uint_16p filter_costs; /* relative filter calculation cost */
  177596. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  177597. #endif
  177598. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  177599. png_charp time_buffer; /* String to hold RFC 1123 time text */
  177600. #endif
  177601. /* New members added in libpng-1.0.6 */
  177602. #ifdef PNG_FREE_ME_SUPPORTED
  177603. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  177604. #endif
  177605. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  177606. png_voidp user_chunk_ptr;
  177607. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  177608. #endif
  177609. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177610. int num_chunk_list;
  177611. png_bytep chunk_list;
  177612. #endif
  177613. /* New members added in libpng-1.0.3 */
  177614. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  177615. png_byte rgb_to_gray_status;
  177616. /* These were changed from png_byte in libpng-1.0.6 */
  177617. png_uint_16 rgb_to_gray_red_coeff;
  177618. png_uint_16 rgb_to_gray_green_coeff;
  177619. png_uint_16 rgb_to_gray_blue_coeff;
  177620. #endif
  177621. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  177622. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  177623. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  177624. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  177625. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  177626. #ifdef PNG_1_0_X
  177627. png_byte mng_features_permitted;
  177628. #else
  177629. png_uint_32 mng_features_permitted;
  177630. #endif /* PNG_1_0_X */
  177631. #endif
  177632. /* New member added in libpng-1.0.7 */
  177633. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  177634. png_fixed_point int_gamma;
  177635. #endif
  177636. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  177637. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  177638. png_byte filter_type;
  177639. #endif
  177640. #if defined(PNG_1_0_X)
  177641. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  177642. png_uint_32 row_buf_size;
  177643. #endif
  177644. /* New members added in libpng-1.2.0 */
  177645. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  177646. # if !defined(PNG_1_0_X)
  177647. # if defined(PNG_MMX_CODE_SUPPORTED)
  177648. png_byte mmx_bitdepth_threshold;
  177649. png_uint_32 mmx_rowbytes_threshold;
  177650. # endif
  177651. png_uint_32 asm_flags;
  177652. # endif
  177653. #endif
  177654. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  177655. #ifdef PNG_USER_MEM_SUPPORTED
  177656. png_voidp mem_ptr; /* user supplied struct for mem functions */
  177657. png_malloc_ptr malloc_fn; /* function for allocating memory */
  177658. png_free_ptr free_fn; /* function for freeing memory */
  177659. #endif
  177660. /* New member added in libpng-1.0.13 and 1.2.0 */
  177661. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  177662. #if defined(PNG_READ_DITHER_SUPPORTED)
  177663. /* The following three members were added at version 1.0.14 and 1.2.4 */
  177664. png_bytep dither_sort; /* working sort array */
  177665. png_bytep index_to_palette; /* where the original index currently is */
  177666. /* in the palette */
  177667. png_bytep palette_to_index; /* which original index points to this */
  177668. /* palette color */
  177669. #endif
  177670. /* New members added in libpng-1.0.16 and 1.2.6 */
  177671. png_byte compression_type;
  177672. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  177673. png_uint_32 user_width_max;
  177674. png_uint_32 user_height_max;
  177675. #endif
  177676. /* New member added in libpng-1.0.25 and 1.2.17 */
  177677. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177678. /* storage for unknown chunk that the library doesn't recognize. */
  177679. png_unknown_chunk unknown_chunk;
  177680. #endif
  177681. };
  177682. /* This triggers a compiler error in png.c, if png.c and png.h
  177683. * do not agree upon the version number.
  177684. */
  177685. typedef png_structp version_1_2_21;
  177686. typedef png_struct FAR * FAR * png_structpp;
  177687. /* Here are the function definitions most commonly used. This is not
  177688. * the place to find out how to use libpng. See libpng.txt for the
  177689. * full explanation, see example.c for the summary. This just provides
  177690. * a simple one line description of the use of each function.
  177691. */
  177692. /* Returns the version number of the library */
  177693. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  177694. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  177695. * Handling more than 8 bytes from the beginning of the file is an error.
  177696. */
  177697. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  177698. int num_bytes));
  177699. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  177700. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  177701. * signature, and non-zero otherwise. Having num_to_check == 0 or
  177702. * start > 7 will always fail (ie return non-zero).
  177703. */
  177704. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  177705. png_size_t num_to_check));
  177706. /* Simple signature checking function. This is the same as calling
  177707. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  177708. */
  177709. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  177710. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  177711. extern PNG_EXPORT(png_structp,png_create_read_struct)
  177712. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  177713. png_error_ptr error_fn, png_error_ptr warn_fn));
  177714. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  177715. extern PNG_EXPORT(png_structp,png_create_write_struct)
  177716. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  177717. png_error_ptr error_fn, png_error_ptr warn_fn));
  177718. #ifdef PNG_WRITE_SUPPORTED
  177719. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  177720. PNGARG((png_structp png_ptr));
  177721. #endif
  177722. #ifdef PNG_WRITE_SUPPORTED
  177723. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  177724. PNGARG((png_structp png_ptr, png_uint_32 size));
  177725. #endif
  177726. /* Reset the compression stream */
  177727. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  177728. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  177729. #ifdef PNG_USER_MEM_SUPPORTED
  177730. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  177731. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  177732. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  177733. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  177734. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  177735. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  177736. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  177737. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  177738. #endif
  177739. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  177740. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  177741. png_bytep chunk_name, png_bytep data, png_size_t length));
  177742. /* Write the start of a PNG chunk - length and chunk name. */
  177743. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  177744. png_bytep chunk_name, png_uint_32 length));
  177745. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  177746. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  177747. png_bytep data, png_size_t length));
  177748. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  177749. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  177750. /* Allocate and initialize the info structure */
  177751. extern PNG_EXPORT(png_infop,png_create_info_struct)
  177752. PNGARG((png_structp png_ptr));
  177753. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177754. /* Initialize the info structure (old interface - DEPRECATED) */
  177755. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  177756. #undef png_info_init
  177757. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  177758. png_sizeof(png_info));
  177759. #endif
  177760. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  177761. png_size_t png_info_struct_size));
  177762. /* Writes all the PNG information before the image. */
  177763. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  177764. png_infop info_ptr));
  177765. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  177766. png_infop info_ptr));
  177767. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177768. /* read the information before the actual image data. */
  177769. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  177770. png_infop info_ptr));
  177771. #endif
  177772. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  177773. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  177774. PNGARG((png_structp png_ptr, png_timep ptime));
  177775. #endif
  177776. #if !defined(_WIN32_WCE)
  177777. /* "time.h" functions are not supported on WindowsCE */
  177778. #if defined(PNG_WRITE_tIME_SUPPORTED)
  177779. /* convert from a struct tm to png_time */
  177780. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  177781. struct tm FAR * ttime));
  177782. /* convert from time_t to png_time. Uses gmtime() */
  177783. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  177784. time_t ttime));
  177785. #endif /* PNG_WRITE_tIME_SUPPORTED */
  177786. #endif /* _WIN32_WCE */
  177787. #if defined(PNG_READ_EXPAND_SUPPORTED)
  177788. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  177789. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  177790. #if !defined(PNG_1_0_X)
  177791. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  177792. png_ptr));
  177793. #endif
  177794. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  177795. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  177796. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177797. /* Deprecated */
  177798. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  177799. #endif
  177800. #endif
  177801. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  177802. /* Use blue, green, red order for pixels. */
  177803. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  177804. #endif
  177805. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  177806. /* Expand the grayscale to 24-bit RGB if necessary. */
  177807. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  177808. #endif
  177809. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  177810. /* Reduce RGB to grayscale. */
  177811. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177812. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  177813. int error_action, double red, double green ));
  177814. #endif
  177815. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  177816. int error_action, png_fixed_point red, png_fixed_point green ));
  177817. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  177818. png_ptr));
  177819. #endif
  177820. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  177821. png_colorp palette));
  177822. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  177823. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  177824. #endif
  177825. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  177826. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  177827. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  177828. #endif
  177829. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  177830. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  177831. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  177832. #endif
  177833. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  177834. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  177835. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  177836. png_uint_32 filler, int flags));
  177837. /* The values of the PNG_FILLER_ defines should NOT be changed */
  177838. #define PNG_FILLER_BEFORE 0
  177839. #define PNG_FILLER_AFTER 1
  177840. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  177841. #if !defined(PNG_1_0_X)
  177842. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  177843. png_uint_32 filler, int flags));
  177844. #endif
  177845. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  177846. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  177847. /* Swap bytes in 16-bit depth files. */
  177848. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  177849. #endif
  177850. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  177851. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  177852. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  177853. #endif
  177854. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  177855. /* Swap packing order of pixels in bytes. */
  177856. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  177857. #endif
  177858. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  177859. /* Converts files to legal bit depths. */
  177860. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  177861. png_color_8p true_bits));
  177862. #endif
  177863. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  177864. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  177865. /* Have the code handle the interlacing. Returns the number of passes. */
  177866. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  177867. #endif
  177868. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  177869. /* Invert monochrome files */
  177870. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  177871. #endif
  177872. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  177873. /* Handle alpha and tRNS by replacing with a background color. */
  177874. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177875. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  177876. png_color_16p background_color, int background_gamma_code,
  177877. int need_expand, double background_gamma));
  177878. #endif
  177879. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  177880. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  177881. #define PNG_BACKGROUND_GAMMA_FILE 2
  177882. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  177883. #endif
  177884. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  177885. /* strip the second byte of information from a 16-bit depth file. */
  177886. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  177887. #endif
  177888. #if defined(PNG_READ_DITHER_SUPPORTED)
  177889. /* Turn on dithering, and reduce the palette to the number of colors available. */
  177890. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  177891. png_colorp palette, int num_palette, int maximum_colors,
  177892. png_uint_16p histogram, int full_dither));
  177893. #endif
  177894. #if defined(PNG_READ_GAMMA_SUPPORTED)
  177895. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  177896. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177897. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  177898. double screen_gamma, double default_file_gamma));
  177899. #endif
  177900. #endif
  177901. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177902. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  177903. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  177904. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  177905. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  177906. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  177907. int empty_plte_permitted));
  177908. #endif
  177909. #endif
  177910. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  177911. /* Set how many lines between output flushes - 0 for no flushing */
  177912. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  177913. /* Flush the current PNG output buffer */
  177914. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  177915. #endif
  177916. /* optional update palette with requested transformations */
  177917. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  177918. /* optional call to update the users info structure */
  177919. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  177920. png_infop info_ptr));
  177921. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177922. /* read one or more rows of image data. */
  177923. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  177924. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  177925. #endif
  177926. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177927. /* read a row of data. */
  177928. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  177929. png_bytep row,
  177930. png_bytep display_row));
  177931. #endif
  177932. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177933. /* read the whole image into memory at once. */
  177934. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  177935. png_bytepp image));
  177936. #endif
  177937. /* write a row of image data */
  177938. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  177939. png_bytep row));
  177940. /* write a few rows of image data */
  177941. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  177942. png_bytepp row, png_uint_32 num_rows));
  177943. /* write the image data */
  177944. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  177945. png_bytepp image));
  177946. /* writes the end of the PNG file. */
  177947. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  177948. png_infop info_ptr));
  177949. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177950. /* read the end of the PNG file. */
  177951. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  177952. png_infop info_ptr));
  177953. #endif
  177954. /* free any memory associated with the png_info_struct */
  177955. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  177956. png_infopp info_ptr_ptr));
  177957. /* free any memory associated with the png_struct and the png_info_structs */
  177958. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  177959. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  177960. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  177961. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  177962. png_infop end_info_ptr));
  177963. /* free any memory associated with the png_struct and the png_info_structs */
  177964. extern PNG_EXPORT(void,png_destroy_write_struct)
  177965. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  177966. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  177967. extern void png_write_destroy PNGARG((png_structp png_ptr));
  177968. /* set the libpng method of handling chunk CRC errors */
  177969. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  177970. int crit_action, int ancil_action));
  177971. /* Values for png_set_crc_action() to say how to handle CRC errors in
  177972. * ancillary and critical chunks, and whether to use the data contained
  177973. * therein. Note that it is impossible to "discard" data in a critical
  177974. * chunk. For versions prior to 0.90, the action was always error/quit,
  177975. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  177976. * chunks is warn/discard. These values should NOT be changed.
  177977. *
  177978. * value action:critical action:ancillary
  177979. */
  177980. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  177981. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  177982. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  177983. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  177984. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  177985. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  177986. /* These functions give the user control over the scan-line filtering in
  177987. * libpng and the compression methods used by zlib. These functions are
  177988. * mainly useful for testing, as the defaults should work with most users.
  177989. * Those users who are tight on memory or want faster performance at the
  177990. * expense of compression can modify them. See the compression library
  177991. * header file (zlib.h) for an explination of the compression functions.
  177992. */
  177993. /* set the filtering method(s) used by libpng. Currently, the only valid
  177994. * value for "method" is 0.
  177995. */
  177996. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  177997. int filters));
  177998. /* Flags for png_set_filter() to say which filters to use. The flags
  177999. * are chosen so that they don't conflict with real filter types
  178000. * below, in case they are supplied instead of the #defined constants.
  178001. * These values should NOT be changed.
  178002. */
  178003. #define PNG_NO_FILTERS 0x00
  178004. #define PNG_FILTER_NONE 0x08
  178005. #define PNG_FILTER_SUB 0x10
  178006. #define PNG_FILTER_UP 0x20
  178007. #define PNG_FILTER_AVG 0x40
  178008. #define PNG_FILTER_PAETH 0x80
  178009. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  178010. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  178011. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  178012. * These defines should NOT be changed.
  178013. */
  178014. #define PNG_FILTER_VALUE_NONE 0
  178015. #define PNG_FILTER_VALUE_SUB 1
  178016. #define PNG_FILTER_VALUE_UP 2
  178017. #define PNG_FILTER_VALUE_AVG 3
  178018. #define PNG_FILTER_VALUE_PAETH 4
  178019. #define PNG_FILTER_VALUE_LAST 5
  178020. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  178021. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  178022. * defines, either the default (minimum-sum-of-absolute-differences), or
  178023. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  178024. *
  178025. * Weights are factors >= 1.0, indicating how important it is to keep the
  178026. * filter type consistent between rows. Larger numbers mean the current
  178027. * filter is that many times as likely to be the same as the "num_weights"
  178028. * previous filters. This is cumulative for each previous row with a weight.
  178029. * There needs to be "num_weights" values in "filter_weights", or it can be
  178030. * NULL if the weights aren't being specified. Weights have no influence on
  178031. * the selection of the first row filter. Well chosen weights can (in theory)
  178032. * improve the compression for a given image.
  178033. *
  178034. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  178035. * filter type. Higher costs indicate more decoding expense, and are
  178036. * therefore less likely to be selected over a filter with lower computational
  178037. * costs. There needs to be a value in "filter_costs" for each valid filter
  178038. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  178039. * setting the costs. Costs try to improve the speed of decompression without
  178040. * unduly increasing the compressed image size.
  178041. *
  178042. * A negative weight or cost indicates the default value is to be used, and
  178043. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  178044. * The default values for both weights and costs are currently 1.0, but may
  178045. * change if good general weighting/cost heuristics can be found. If both
  178046. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  178047. * to the UNWEIGHTED method, but with added encoding time/computation.
  178048. */
  178049. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178050. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  178051. int heuristic_method, int num_weights, png_doublep filter_weights,
  178052. png_doublep filter_costs));
  178053. #endif
  178054. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  178055. /* Heuristic used for row filter selection. These defines should NOT be
  178056. * changed.
  178057. */
  178058. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  178059. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  178060. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  178061. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  178062. /* Set the library compression level. Currently, valid values range from
  178063. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  178064. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  178065. * shown that zlib compression levels 3-6 usually perform as well as level 9
  178066. * for PNG images, and do considerably fewer caclulations. In the future,
  178067. * these values may not correspond directly to the zlib compression levels.
  178068. */
  178069. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  178070. int level));
  178071. extern PNG_EXPORT(void,png_set_compression_mem_level)
  178072. PNGARG((png_structp png_ptr, int mem_level));
  178073. extern PNG_EXPORT(void,png_set_compression_strategy)
  178074. PNGARG((png_structp png_ptr, int strategy));
  178075. extern PNG_EXPORT(void,png_set_compression_window_bits)
  178076. PNGARG((png_structp png_ptr, int window_bits));
  178077. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  178078. int method));
  178079. /* These next functions are called for input/output, memory, and error
  178080. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  178081. * and call standard C I/O routines such as fread(), fwrite(), and
  178082. * fprintf(). These functions can be made to use other I/O routines
  178083. * at run time for those applications that need to handle I/O in a
  178084. * different manner by calling png_set_???_fn(). See libpng.txt for
  178085. * more information.
  178086. */
  178087. #if !defined(PNG_NO_STDIO)
  178088. /* Initialize the input/output for the PNG file to the default functions. */
  178089. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  178090. #endif
  178091. /* Replace the (error and abort), and warning functions with user
  178092. * supplied functions. If no messages are to be printed you must still
  178093. * write and use replacement functions. The replacement error_fn should
  178094. * still do a longjmp to the last setjmp location if you are using this
  178095. * method of error handling. If error_fn or warning_fn is NULL, the
  178096. * default function will be used.
  178097. */
  178098. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  178099. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  178100. /* Return the user pointer associated with the error functions */
  178101. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  178102. /* Replace the default data output functions with a user supplied one(s).
  178103. * If buffered output is not used, then output_flush_fn can be set to NULL.
  178104. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  178105. * output_flush_fn will be ignored (and thus can be NULL).
  178106. */
  178107. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  178108. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  178109. /* Replace the default data input function with a user supplied one. */
  178110. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  178111. png_voidp io_ptr, png_rw_ptr read_data_fn));
  178112. /* Return the user pointer associated with the I/O functions */
  178113. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  178114. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  178115. png_read_status_ptr read_row_fn));
  178116. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  178117. png_write_status_ptr write_row_fn));
  178118. #ifdef PNG_USER_MEM_SUPPORTED
  178119. /* Replace the default memory allocation functions with user supplied one(s). */
  178120. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  178121. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  178122. /* Return the user pointer associated with the memory functions */
  178123. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  178124. #endif
  178125. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178126. defined(PNG_LEGACY_SUPPORTED)
  178127. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  178128. png_ptr, png_user_transform_ptr read_user_transform_fn));
  178129. #endif
  178130. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  178131. defined(PNG_LEGACY_SUPPORTED)
  178132. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  178133. png_ptr, png_user_transform_ptr write_user_transform_fn));
  178134. #endif
  178135. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178136. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  178137. defined(PNG_LEGACY_SUPPORTED)
  178138. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  178139. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  178140. int user_transform_channels));
  178141. /* Return the user pointer associated with the user transform functions */
  178142. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  178143. PNGARG((png_structp png_ptr));
  178144. #endif
  178145. #ifdef PNG_USER_CHUNKS_SUPPORTED
  178146. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  178147. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  178148. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  178149. png_ptr));
  178150. #endif
  178151. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178152. /* Sets the function callbacks for the push reader, and a pointer to a
  178153. * user-defined structure available to the callback functions.
  178154. */
  178155. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  178156. png_voidp progressive_ptr,
  178157. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  178158. png_progressive_end_ptr end_fn));
  178159. /* returns the user pointer associated with the push read functions */
  178160. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  178161. PNGARG((png_structp png_ptr));
  178162. /* function to be called when data becomes available */
  178163. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  178164. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  178165. /* function that combines rows. Not very much different than the
  178166. * png_combine_row() call. Is this even used?????
  178167. */
  178168. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  178169. png_bytep old_row, png_bytep new_row));
  178170. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  178171. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  178172. png_uint_32 size));
  178173. #if defined(PNG_1_0_X)
  178174. # define png_malloc_warn png_malloc
  178175. #else
  178176. /* Added at libpng version 1.2.4 */
  178177. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  178178. png_uint_32 size));
  178179. #endif
  178180. /* frees a pointer allocated by png_malloc() */
  178181. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  178182. #if defined(PNG_1_0_X)
  178183. /* Function to allocate memory for zlib. */
  178184. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  178185. uInt size));
  178186. /* Function to free memory for zlib */
  178187. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  178188. #endif
  178189. /* Free data that was allocated internally */
  178190. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  178191. png_infop info_ptr, png_uint_32 free_me, int num));
  178192. #ifdef PNG_FREE_ME_SUPPORTED
  178193. /* Reassign responsibility for freeing existing data, whether allocated
  178194. * by libpng or by the application */
  178195. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  178196. png_infop info_ptr, int freer, png_uint_32 mask));
  178197. #endif
  178198. /* assignments for png_data_freer */
  178199. #define PNG_DESTROY_WILL_FREE_DATA 1
  178200. #define PNG_SET_WILL_FREE_DATA 1
  178201. #define PNG_USER_WILL_FREE_DATA 2
  178202. /* Flags for png_ptr->free_me and info_ptr->free_me */
  178203. #define PNG_FREE_HIST 0x0008
  178204. #define PNG_FREE_ICCP 0x0010
  178205. #define PNG_FREE_SPLT 0x0020
  178206. #define PNG_FREE_ROWS 0x0040
  178207. #define PNG_FREE_PCAL 0x0080
  178208. #define PNG_FREE_SCAL 0x0100
  178209. #define PNG_FREE_UNKN 0x0200
  178210. #define PNG_FREE_LIST 0x0400
  178211. #define PNG_FREE_PLTE 0x1000
  178212. #define PNG_FREE_TRNS 0x2000
  178213. #define PNG_FREE_TEXT 0x4000
  178214. #define PNG_FREE_ALL 0x7fff
  178215. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  178216. #ifdef PNG_USER_MEM_SUPPORTED
  178217. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  178218. png_uint_32 size));
  178219. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  178220. png_voidp ptr));
  178221. #endif
  178222. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  178223. png_voidp s1, png_voidp s2, png_uint_32 size));
  178224. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  178225. png_voidp s1, int value, png_uint_32 size));
  178226. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  178227. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  178228. int check));
  178229. #endif /* USE_FAR_KEYWORD */
  178230. #ifndef PNG_NO_ERROR_TEXT
  178231. /* Fatal error in PNG image of libpng - can't continue */
  178232. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  178233. png_const_charp error_message));
  178234. /* The same, but the chunk name is prepended to the error string. */
  178235. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  178236. png_const_charp error_message));
  178237. #else
  178238. /* Fatal error in PNG image of libpng - can't continue */
  178239. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  178240. #endif
  178241. #ifndef PNG_NO_WARNINGS
  178242. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  178243. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  178244. png_const_charp warning_message));
  178245. #ifdef PNG_READ_SUPPORTED
  178246. /* Non-fatal error in libpng, chunk name is prepended to message. */
  178247. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  178248. png_const_charp warning_message));
  178249. #endif /* PNG_READ_SUPPORTED */
  178250. #endif /* PNG_NO_WARNINGS */
  178251. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  178252. * Similarly, the png_get_<chunk> calls are used to read values from the
  178253. * png_info_struct, either storing the parameters in the passed variables, or
  178254. * setting pointers into the png_info_struct where the data is stored. The
  178255. * png_get_<chunk> functions return a non-zero value if the data was available
  178256. * in info_ptr, or return zero and do not change any of the parameters if the
  178257. * data was not available.
  178258. *
  178259. * These functions should be used instead of directly accessing png_info
  178260. * to avoid problems with future changes in the size and internal layout of
  178261. * png_info_struct.
  178262. */
  178263. /* Returns "flag" if chunk data is valid in info_ptr. */
  178264. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  178265. png_infop info_ptr, png_uint_32 flag));
  178266. /* Returns number of bytes needed to hold a transformed row. */
  178267. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  178268. png_infop info_ptr));
  178269. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  178270. /* Returns row_pointers, which is an array of pointers to scanlines that was
  178271. returned from png_read_png(). */
  178272. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  178273. png_infop info_ptr));
  178274. /* Set row_pointers, which is an array of pointers to scanlines for use
  178275. by png_write_png(). */
  178276. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  178277. png_infop info_ptr, png_bytepp row_pointers));
  178278. #endif
  178279. /* Returns number of color channels in image. */
  178280. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  178281. png_infop info_ptr));
  178282. #ifdef PNG_EASY_ACCESS_SUPPORTED
  178283. /* Returns image width in pixels. */
  178284. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  178285. png_ptr, png_infop info_ptr));
  178286. /* Returns image height in pixels. */
  178287. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  178288. png_ptr, png_infop info_ptr));
  178289. /* Returns image bit_depth. */
  178290. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  178291. png_ptr, png_infop info_ptr));
  178292. /* Returns image color_type. */
  178293. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  178294. png_ptr, png_infop info_ptr));
  178295. /* Returns image filter_type. */
  178296. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  178297. png_ptr, png_infop info_ptr));
  178298. /* Returns image interlace_type. */
  178299. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  178300. png_ptr, png_infop info_ptr));
  178301. /* Returns image compression_type. */
  178302. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  178303. png_ptr, png_infop info_ptr));
  178304. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  178305. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  178306. png_ptr, png_infop info_ptr));
  178307. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  178308. png_ptr, png_infop info_ptr));
  178309. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  178310. png_ptr, png_infop info_ptr));
  178311. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  178312. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178313. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  178314. png_ptr, png_infop info_ptr));
  178315. #endif
  178316. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  178317. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  178318. png_ptr, png_infop info_ptr));
  178319. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  178320. png_ptr, png_infop info_ptr));
  178321. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  178322. png_ptr, png_infop info_ptr));
  178323. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  178324. png_ptr, png_infop info_ptr));
  178325. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  178326. /* Returns pointer to signature string read from PNG header */
  178327. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  178328. png_infop info_ptr));
  178329. #if defined(PNG_bKGD_SUPPORTED)
  178330. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  178331. png_infop info_ptr, png_color_16p *background));
  178332. #endif
  178333. #if defined(PNG_bKGD_SUPPORTED)
  178334. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  178335. png_infop info_ptr, png_color_16p background));
  178336. #endif
  178337. #if defined(PNG_cHRM_SUPPORTED)
  178338. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178339. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  178340. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  178341. double *red_y, double *green_x, double *green_y, double *blue_x,
  178342. double *blue_y));
  178343. #endif
  178344. #ifdef PNG_FIXED_POINT_SUPPORTED
  178345. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  178346. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  178347. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  178348. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  178349. *int_blue_x, png_fixed_point *int_blue_y));
  178350. #endif
  178351. #endif
  178352. #if defined(PNG_cHRM_SUPPORTED)
  178353. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178354. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  178355. png_infop info_ptr, double white_x, double white_y, double red_x,
  178356. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  178357. #endif
  178358. #ifdef PNG_FIXED_POINT_SUPPORTED
  178359. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  178360. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  178361. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  178362. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  178363. png_fixed_point int_blue_y));
  178364. #endif
  178365. #endif
  178366. #if defined(PNG_gAMA_SUPPORTED)
  178367. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178368. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  178369. png_infop info_ptr, double *file_gamma));
  178370. #endif
  178371. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  178372. png_infop info_ptr, png_fixed_point *int_file_gamma));
  178373. #endif
  178374. #if defined(PNG_gAMA_SUPPORTED)
  178375. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178376. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  178377. png_infop info_ptr, double file_gamma));
  178378. #endif
  178379. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  178380. png_infop info_ptr, png_fixed_point int_file_gamma));
  178381. #endif
  178382. #if defined(PNG_hIST_SUPPORTED)
  178383. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  178384. png_infop info_ptr, png_uint_16p *hist));
  178385. #endif
  178386. #if defined(PNG_hIST_SUPPORTED)
  178387. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  178388. png_infop info_ptr, png_uint_16p hist));
  178389. #endif
  178390. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  178391. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  178392. int *bit_depth, int *color_type, int *interlace_method,
  178393. int *compression_method, int *filter_method));
  178394. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  178395. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  178396. int color_type, int interlace_method, int compression_method,
  178397. int filter_method));
  178398. #if defined(PNG_oFFs_SUPPORTED)
  178399. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  178400. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  178401. int *unit_type));
  178402. #endif
  178403. #if defined(PNG_oFFs_SUPPORTED)
  178404. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  178405. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  178406. int unit_type));
  178407. #endif
  178408. #if defined(PNG_pCAL_SUPPORTED)
  178409. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  178410. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  178411. int *type, int *nparams, png_charp *units, png_charpp *params));
  178412. #endif
  178413. #if defined(PNG_pCAL_SUPPORTED)
  178414. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  178415. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  178416. int type, int nparams, png_charp units, png_charpp params));
  178417. #endif
  178418. #if defined(PNG_pHYs_SUPPORTED)
  178419. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  178420. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  178421. #endif
  178422. #if defined(PNG_pHYs_SUPPORTED)
  178423. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  178424. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  178425. #endif
  178426. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  178427. png_infop info_ptr, png_colorp *palette, int *num_palette));
  178428. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  178429. png_infop info_ptr, png_colorp palette, int num_palette));
  178430. #if defined(PNG_sBIT_SUPPORTED)
  178431. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  178432. png_infop info_ptr, png_color_8p *sig_bit));
  178433. #endif
  178434. #if defined(PNG_sBIT_SUPPORTED)
  178435. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  178436. png_infop info_ptr, png_color_8p sig_bit));
  178437. #endif
  178438. #if defined(PNG_sRGB_SUPPORTED)
  178439. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  178440. png_infop info_ptr, int *intent));
  178441. #endif
  178442. #if defined(PNG_sRGB_SUPPORTED)
  178443. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  178444. png_infop info_ptr, int intent));
  178445. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  178446. png_infop info_ptr, int intent));
  178447. #endif
  178448. #if defined(PNG_iCCP_SUPPORTED)
  178449. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  178450. png_infop info_ptr, png_charpp name, int *compression_type,
  178451. png_charpp profile, png_uint_32 *proflen));
  178452. /* Note to maintainer: profile should be png_bytepp */
  178453. #endif
  178454. #if defined(PNG_iCCP_SUPPORTED)
  178455. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  178456. png_infop info_ptr, png_charp name, int compression_type,
  178457. png_charp profile, png_uint_32 proflen));
  178458. /* Note to maintainer: profile should be png_bytep */
  178459. #endif
  178460. #if defined(PNG_sPLT_SUPPORTED)
  178461. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  178462. png_infop info_ptr, png_sPLT_tpp entries));
  178463. #endif
  178464. #if defined(PNG_sPLT_SUPPORTED)
  178465. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  178466. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  178467. #endif
  178468. #if defined(PNG_TEXT_SUPPORTED)
  178469. /* png_get_text also returns the number of text chunks in *num_text */
  178470. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  178471. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  178472. #endif
  178473. /*
  178474. * Note while png_set_text() will accept a structure whose text,
  178475. * language, and translated keywords are NULL pointers, the structure
  178476. * returned by png_get_text will always contain regular
  178477. * zero-terminated C strings. They might be empty strings but
  178478. * they will never be NULL pointers.
  178479. */
  178480. #if defined(PNG_TEXT_SUPPORTED)
  178481. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  178482. png_infop info_ptr, png_textp text_ptr, int num_text));
  178483. #endif
  178484. #if defined(PNG_tIME_SUPPORTED)
  178485. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  178486. png_infop info_ptr, png_timep *mod_time));
  178487. #endif
  178488. #if defined(PNG_tIME_SUPPORTED)
  178489. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  178490. png_infop info_ptr, png_timep mod_time));
  178491. #endif
  178492. #if defined(PNG_tRNS_SUPPORTED)
  178493. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  178494. png_infop info_ptr, png_bytep *trans, int *num_trans,
  178495. png_color_16p *trans_values));
  178496. #endif
  178497. #if defined(PNG_tRNS_SUPPORTED)
  178498. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  178499. png_infop info_ptr, png_bytep trans, int num_trans,
  178500. png_color_16p trans_values));
  178501. #endif
  178502. #if defined(PNG_tRNS_SUPPORTED)
  178503. #endif
  178504. #if defined(PNG_sCAL_SUPPORTED)
  178505. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178506. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  178507. png_infop info_ptr, int *unit, double *width, double *height));
  178508. #else
  178509. #ifdef PNG_FIXED_POINT_SUPPORTED
  178510. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  178511. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  178512. #endif
  178513. #endif
  178514. #endif /* PNG_sCAL_SUPPORTED */
  178515. #if defined(PNG_sCAL_SUPPORTED)
  178516. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178517. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  178518. png_infop info_ptr, int unit, double width, double height));
  178519. #else
  178520. #ifdef PNG_FIXED_POINT_SUPPORTED
  178521. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  178522. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  178523. #endif
  178524. #endif
  178525. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  178526. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178527. /* provide a list of chunks and how they are to be handled, if the built-in
  178528. handling or default unknown chunk handling is not desired. Any chunks not
  178529. listed will be handled in the default manner. The IHDR and IEND chunks
  178530. must not be listed.
  178531. keep = 0: follow default behaviour
  178532. = 1: do not keep
  178533. = 2: keep only if safe-to-copy
  178534. = 3: keep even if unsafe-to-copy
  178535. */
  178536. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  178537. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  178538. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  178539. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  178540. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  178541. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  178542. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  178543. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  178544. #endif
  178545. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  178546. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  178547. chunk_name));
  178548. #endif
  178549. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  178550. If you need to turn it off for a chunk that your application has freed,
  178551. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  178552. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  178553. png_infop info_ptr, int mask));
  178554. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  178555. /* The "params" pointer is currently not used and is for future expansion. */
  178556. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  178557. png_infop info_ptr,
  178558. int transforms,
  178559. png_voidp params));
  178560. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  178561. png_infop info_ptr,
  178562. int transforms,
  178563. png_voidp params));
  178564. #endif
  178565. /* Define PNG_DEBUG at compile time for debugging information. Higher
  178566. * numbers for PNG_DEBUG mean more debugging information. This has
  178567. * only been added since version 0.95 so it is not implemented throughout
  178568. * libpng yet, but more support will be added as needed.
  178569. */
  178570. #ifdef PNG_DEBUG
  178571. #if (PNG_DEBUG > 0)
  178572. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  178573. #include <crtdbg.h>
  178574. #if (PNG_DEBUG > 1)
  178575. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  178576. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  178577. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  178578. #endif
  178579. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  178580. #ifndef PNG_DEBUG_FILE
  178581. #define PNG_DEBUG_FILE stderr
  178582. #endif /* PNG_DEBUG_FILE */
  178583. #if (PNG_DEBUG > 1)
  178584. #define png_debug(l,m) \
  178585. { \
  178586. int num_tabs=l; \
  178587. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  178588. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  178589. }
  178590. #define png_debug1(l,m,p1) \
  178591. { \
  178592. int num_tabs=l; \
  178593. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  178594. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  178595. }
  178596. #define png_debug2(l,m,p1,p2) \
  178597. { \
  178598. int num_tabs=l; \
  178599. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  178600. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  178601. }
  178602. #endif /* (PNG_DEBUG > 1) */
  178603. #endif /* _MSC_VER */
  178604. #endif /* (PNG_DEBUG > 0) */
  178605. #endif /* PNG_DEBUG */
  178606. #ifndef png_debug
  178607. #define png_debug(l, m)
  178608. #endif
  178609. #ifndef png_debug1
  178610. #define png_debug1(l, m, p1)
  178611. #endif
  178612. #ifndef png_debug2
  178613. #define png_debug2(l, m, p1, p2)
  178614. #endif
  178615. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  178616. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  178617. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  178618. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  178619. #ifdef PNG_MNG_FEATURES_SUPPORTED
  178620. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  178621. png_ptr, png_uint_32 mng_features_permitted));
  178622. #endif
  178623. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  178624. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  178625. #define PNG_HANDLE_CHUNK_NEVER 1
  178626. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  178627. #define PNG_HANDLE_CHUNK_ALWAYS 3
  178628. /* Added to version 1.2.0 */
  178629. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  178630. #if defined(PNG_MMX_CODE_SUPPORTED)
  178631. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  178632. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  178633. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  178634. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  178635. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  178636. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  178637. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  178638. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  178639. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  178640. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  178641. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  178642. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  178643. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  178644. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  178645. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  178646. #define PNG_MMX_WRITE_FLAGS ( 0 )
  178647. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  178648. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  178649. | PNG_MMX_READ_FLAGS \
  178650. | PNG_MMX_WRITE_FLAGS )
  178651. #define PNG_SELECT_READ 1
  178652. #define PNG_SELECT_WRITE 2
  178653. #endif /* PNG_MMX_CODE_SUPPORTED */
  178654. #if !defined(PNG_1_0_X)
  178655. /* pngget.c */
  178656. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  178657. PNGARG((int flag_select, int *compilerID));
  178658. /* pngget.c */
  178659. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  178660. PNGARG((int flag_select));
  178661. /* pngget.c */
  178662. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  178663. PNGARG((png_structp png_ptr));
  178664. /* pngget.c */
  178665. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  178666. PNGARG((png_structp png_ptr));
  178667. /* pngget.c */
  178668. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  178669. PNGARG((png_structp png_ptr));
  178670. /* pngset.c */
  178671. extern PNG_EXPORT(void,png_set_asm_flags)
  178672. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  178673. /* pngset.c */
  178674. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  178675. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  178676. png_uint_32 mmx_rowbytes_threshold));
  178677. #endif /* PNG_1_0_X */
  178678. #if !defined(PNG_1_0_X)
  178679. /* png.c, pnggccrd.c, or pngvcrd.c */
  178680. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  178681. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  178682. /* Strip the prepended error numbers ("#nnn ") from error and warning
  178683. * messages before passing them to the error or warning handler. */
  178684. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  178685. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  178686. png_ptr, png_uint_32 strip_mode));
  178687. #endif
  178688. #endif /* PNG_1_0_X */
  178689. /* Added at libpng-1.2.6 */
  178690. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  178691. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  178692. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  178693. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  178694. png_ptr));
  178695. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  178696. png_ptr));
  178697. #endif
  178698. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  178699. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  178700. /* With these routines we avoid an integer divide, which will be slower on
  178701. * most machines. However, it does take more operations than the corresponding
  178702. * divide method, so it may be slower on a few RISC systems. There are two
  178703. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  178704. *
  178705. * Note that the rounding factors are NOT supposed to be the same! 128 and
  178706. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  178707. * standard method.
  178708. *
  178709. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  178710. */
  178711. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  178712. # define png_composite(composite, fg, alpha, bg) \
  178713. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  178714. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  178715. (png_uint_16)(alpha)) + (png_uint_16)128); \
  178716. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  178717. # define png_composite_16(composite, fg, alpha, bg) \
  178718. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  178719. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  178720. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  178721. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  178722. #else /* standard method using integer division */
  178723. # define png_composite(composite, fg, alpha, bg) \
  178724. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  178725. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  178726. (png_uint_16)127) / 255)
  178727. # define png_composite_16(composite, fg, alpha, bg) \
  178728. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  178729. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  178730. (png_uint_32)32767) / (png_uint_32)65535L)
  178731. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  178732. /* Inline macros to do direct reads of bytes from the input buffer. These
  178733. * require that you are using an architecture that uses PNG byte ordering
  178734. * (MSB first) and supports unaligned data storage. I think that PowerPC
  178735. * in big-endian mode and 680x0 are the only ones that will support this.
  178736. * The x86 line of processors definitely do not. The png_get_int_32()
  178737. * routine also assumes we are using two's complement format for negative
  178738. * values, which is almost certainly true.
  178739. */
  178740. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  178741. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  178742. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  178743. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  178744. #else
  178745. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  178746. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  178747. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  178748. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  178749. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  178750. PNGARG((png_structp png_ptr, png_bytep buf));
  178751. /* No png_get_int_16 -- may be added if there's a real need for it. */
  178752. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  178753. */
  178754. extern PNG_EXPORT(void,png_save_uint_32)
  178755. PNGARG((png_bytep buf, png_uint_32 i));
  178756. extern PNG_EXPORT(void,png_save_int_32)
  178757. PNGARG((png_bytep buf, png_int_32 i));
  178758. /* Place a 16-bit number into a buffer in PNG byte order.
  178759. * The parameter is declared unsigned int, not png_uint_16,
  178760. * just to avoid potential problems on pre-ANSI C compilers.
  178761. */
  178762. extern PNG_EXPORT(void,png_save_uint_16)
  178763. PNGARG((png_bytep buf, unsigned int i));
  178764. /* No png_save_int_16 -- may be added if there's a real need for it. */
  178765. /* ************************************************************************* */
  178766. /* These next functions are used internally in the code. They generally
  178767. * shouldn't be used unless you are writing code to add or replace some
  178768. * functionality in libpng. More information about most functions can
  178769. * be found in the files where the functions are located.
  178770. */
  178771. /* Various modes of operation, that are visible to applications because
  178772. * they are used for unknown chunk location.
  178773. */
  178774. #define PNG_HAVE_IHDR 0x01
  178775. #define PNG_HAVE_PLTE 0x02
  178776. #define PNG_HAVE_IDAT 0x04
  178777. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  178778. #define PNG_HAVE_IEND 0x10
  178779. #if defined(PNG_INTERNAL)
  178780. /* More modes of operation. Note that after an init, mode is set to
  178781. * zero automatically when the structure is created.
  178782. */
  178783. #define PNG_HAVE_gAMA 0x20
  178784. #define PNG_HAVE_cHRM 0x40
  178785. #define PNG_HAVE_sRGB 0x80
  178786. #define PNG_HAVE_CHUNK_HEADER 0x100
  178787. #define PNG_WROTE_tIME 0x200
  178788. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  178789. #define PNG_BACKGROUND_IS_GRAY 0x800
  178790. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  178791. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  178792. /* flags for the transformations the PNG library does on the image data */
  178793. #define PNG_BGR 0x0001
  178794. #define PNG_INTERLACE 0x0002
  178795. #define PNG_PACK 0x0004
  178796. #define PNG_SHIFT 0x0008
  178797. #define PNG_SWAP_BYTES 0x0010
  178798. #define PNG_INVERT_MONO 0x0020
  178799. #define PNG_DITHER 0x0040
  178800. #define PNG_BACKGROUND 0x0080
  178801. #define PNG_BACKGROUND_EXPAND 0x0100
  178802. /* 0x0200 unused */
  178803. #define PNG_16_TO_8 0x0400
  178804. #define PNG_RGBA 0x0800
  178805. #define PNG_EXPAND 0x1000
  178806. #define PNG_GAMMA 0x2000
  178807. #define PNG_GRAY_TO_RGB 0x4000
  178808. #define PNG_FILLER 0x8000L
  178809. #define PNG_PACKSWAP 0x10000L
  178810. #define PNG_SWAP_ALPHA 0x20000L
  178811. #define PNG_STRIP_ALPHA 0x40000L
  178812. #define PNG_INVERT_ALPHA 0x80000L
  178813. #define PNG_USER_TRANSFORM 0x100000L
  178814. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  178815. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  178816. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  178817. /* 0x800000L Unused */
  178818. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  178819. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  178820. /* 0x4000000L unused */
  178821. /* 0x8000000L unused */
  178822. /* 0x10000000L unused */
  178823. /* 0x20000000L unused */
  178824. /* 0x40000000L unused */
  178825. /* flags for png_create_struct */
  178826. #define PNG_STRUCT_PNG 0x0001
  178827. #define PNG_STRUCT_INFO 0x0002
  178828. /* Scaling factor for filter heuristic weighting calculations */
  178829. #define PNG_WEIGHT_SHIFT 8
  178830. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  178831. #define PNG_COST_SHIFT 3
  178832. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  178833. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  178834. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  178835. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  178836. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  178837. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  178838. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  178839. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  178840. #define PNG_FLAG_ROW_INIT 0x0040
  178841. #define PNG_FLAG_FILLER_AFTER 0x0080
  178842. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  178843. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  178844. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  178845. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  178846. #define PNG_FLAG_FREE_PLTE 0x1000
  178847. #define PNG_FLAG_FREE_TRNS 0x2000
  178848. #define PNG_FLAG_FREE_HIST 0x4000
  178849. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  178850. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  178851. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  178852. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  178853. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  178854. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  178855. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  178856. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  178857. /* 0x800000L unused */
  178858. /* 0x1000000L unused */
  178859. /* 0x2000000L unused */
  178860. /* 0x4000000L unused */
  178861. /* 0x8000000L unused */
  178862. /* 0x10000000L unused */
  178863. /* 0x20000000L unused */
  178864. /* 0x40000000L unused */
  178865. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  178866. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  178867. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  178868. PNG_FLAG_CRC_CRITICAL_IGNORE)
  178869. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  178870. PNG_FLAG_CRC_CRITICAL_MASK)
  178871. /* save typing and make code easier to understand */
  178872. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  178873. abs((int)((c1).green) - (int)((c2).green)) + \
  178874. abs((int)((c1).blue) - (int)((c2).blue)))
  178875. /* Added to libpng-1.2.6 JB */
  178876. #define PNG_ROWBYTES(pixel_bits, width) \
  178877. ((pixel_bits) >= 8 ? \
  178878. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  178879. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  178880. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  178881. ideal-delta..ideal+delta. Each argument is evaluated twice.
  178882. "ideal" and "delta" should be constants, normally simple
  178883. integers, "value" a variable. Added to libpng-1.2.6 JB */
  178884. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  178885. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  178886. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  178887. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  178888. /* place to hold the signature string for a PNG file. */
  178889. #ifdef PNG_USE_GLOBAL_ARRAYS
  178890. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  178891. #else
  178892. #endif
  178893. #endif /* PNG_NO_EXTERN */
  178894. /* Constant strings for known chunk types. If you need to add a chunk,
  178895. * define the name here, and add an invocation of the macro in png.c and
  178896. * wherever it's needed.
  178897. */
  178898. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  178899. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  178900. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  178901. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  178902. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  178903. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  178904. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  178905. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  178906. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  178907. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  178908. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  178909. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  178910. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  178911. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  178912. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  178913. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  178914. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  178915. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  178916. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  178917. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  178918. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  178919. #ifdef PNG_USE_GLOBAL_ARRAYS
  178920. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  178921. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  178922. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  178923. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  178924. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  178925. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  178926. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  178927. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  178928. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  178929. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  178930. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  178931. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  178932. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  178933. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  178934. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  178935. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  178936. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  178937. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  178938. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  178939. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  178940. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  178941. #endif /* PNG_USE_GLOBAL_ARRAYS */
  178942. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178943. /* Initialize png_ptr struct for reading, and allocate any other memory.
  178944. * (old interface - DEPRECATED - use png_create_read_struct instead).
  178945. */
  178946. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  178947. #undef png_read_init
  178948. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  178949. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  178950. #endif
  178951. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  178952. png_const_charp user_png_ver, png_size_t png_struct_size));
  178953. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178954. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  178955. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  178956. png_info_size));
  178957. #endif
  178958. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178959. /* Initialize png_ptr struct for writing, and allocate any other memory.
  178960. * (old interface - DEPRECATED - use png_create_write_struct instead).
  178961. */
  178962. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  178963. #undef png_write_init
  178964. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  178965. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  178966. #endif
  178967. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  178968. png_const_charp user_png_ver, png_size_t png_struct_size));
  178969. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  178970. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  178971. png_info_size));
  178972. /* Allocate memory for an internal libpng struct */
  178973. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  178974. /* Free memory from internal libpng struct */
  178975. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  178976. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  178977. malloc_fn, png_voidp mem_ptr));
  178978. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  178979. png_free_ptr free_fn, png_voidp mem_ptr));
  178980. /* Free any memory that info_ptr points to and reset struct. */
  178981. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  178982. png_infop info_ptr));
  178983. #ifndef PNG_1_0_X
  178984. /* Function to allocate memory for zlib. */
  178985. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  178986. /* Function to free memory for zlib */
  178987. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  178988. #ifdef PNG_SIZE_T
  178989. /* Function to convert a sizeof an item to png_sizeof item */
  178990. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  178991. #endif
  178992. /* Next four functions are used internally as callbacks. PNGAPI is required
  178993. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  178994. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  178995. png_bytep data, png_size_t length));
  178996. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178997. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  178998. png_bytep buffer, png_size_t length));
  178999. #endif
  179000. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  179001. png_bytep data, png_size_t length));
  179002. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179003. #if !defined(PNG_NO_STDIO)
  179004. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  179005. #endif
  179006. #endif
  179007. #else /* PNG_1_0_X */
  179008. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179009. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  179010. png_bytep buffer, png_size_t length));
  179011. #endif
  179012. #endif /* PNG_1_0_X */
  179013. /* Reset the CRC variable */
  179014. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  179015. /* Write the "data" buffer to whatever output you are using. */
  179016. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  179017. png_size_t length));
  179018. /* Read data from whatever input you are using into the "data" buffer */
  179019. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  179020. png_size_t length));
  179021. /* Read bytes into buf, and update png_ptr->crc */
  179022. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  179023. png_size_t length));
  179024. /* Decompress data in a chunk that uses compression */
  179025. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  179026. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  179027. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  179028. int comp_type, png_charp chunkdata, png_size_t chunklength,
  179029. png_size_t prefix_length, png_size_t *data_length));
  179030. #endif
  179031. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  179032. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  179033. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  179034. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  179035. /* Calculate the CRC over a section of data. Note that we are only
  179036. * passing a maximum of 64K on systems that have this as a memory limit,
  179037. * since this is the maximum buffer size we can specify.
  179038. */
  179039. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  179040. png_size_t length));
  179041. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179042. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  179043. #endif
  179044. /* simple function to write the signature */
  179045. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  179046. /* write various chunks */
  179047. /* Write the IHDR chunk, and update the png_struct with the necessary
  179048. * information.
  179049. */
  179050. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  179051. png_uint_32 height,
  179052. int bit_depth, int color_type, int compression_method, int filter_method,
  179053. int interlace_method));
  179054. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  179055. png_uint_32 num_pal));
  179056. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  179057. png_size_t length));
  179058. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  179059. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  179060. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179061. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  179062. #endif
  179063. #ifdef PNG_FIXED_POINT_SUPPORTED
  179064. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  179065. file_gamma));
  179066. #endif
  179067. #endif
  179068. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  179069. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  179070. int color_type));
  179071. #endif
  179072. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  179073. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179074. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  179075. double white_x, double white_y,
  179076. double red_x, double red_y, double green_x, double green_y,
  179077. double blue_x, double blue_y));
  179078. #endif
  179079. #ifdef PNG_FIXED_POINT_SUPPORTED
  179080. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  179081. png_fixed_point int_white_x, png_fixed_point int_white_y,
  179082. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  179083. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  179084. png_fixed_point int_blue_y));
  179085. #endif
  179086. #endif
  179087. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  179088. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  179089. int intent));
  179090. #endif
  179091. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  179092. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  179093. png_charp name, int compression_type,
  179094. png_charp profile, int proflen));
  179095. /* Note to maintainer: profile should be png_bytep */
  179096. #endif
  179097. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  179098. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  179099. png_sPLT_tp palette));
  179100. #endif
  179101. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  179102. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  179103. png_color_16p values, int number, int color_type));
  179104. #endif
  179105. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  179106. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  179107. png_color_16p values, int color_type));
  179108. #endif
  179109. #if defined(PNG_WRITE_hIST_SUPPORTED)
  179110. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  179111. int num_hist));
  179112. #endif
  179113. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  179114. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  179115. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  179116. png_charp key, png_charpp new_key));
  179117. #endif
  179118. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  179119. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  179120. png_charp text, png_size_t text_len));
  179121. #endif
  179122. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  179123. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  179124. png_charp text, png_size_t text_len, int compression));
  179125. #endif
  179126. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  179127. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  179128. int compression, png_charp key, png_charp lang, png_charp lang_key,
  179129. png_charp text));
  179130. #endif
  179131. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  179132. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  179133. png_infop info_ptr, png_textp text_ptr, int num_text));
  179134. #endif
  179135. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  179136. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  179137. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  179138. #endif
  179139. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  179140. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  179141. png_int_32 X0, png_int_32 X1, int type, int nparams,
  179142. png_charp units, png_charpp params));
  179143. #endif
  179144. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  179145. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  179146. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  179147. int unit_type));
  179148. #endif
  179149. #if defined(PNG_WRITE_tIME_SUPPORTED)
  179150. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  179151. png_timep mod_time));
  179152. #endif
  179153. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  179154. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  179155. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  179156. int unit, double width, double height));
  179157. #else
  179158. #ifdef PNG_FIXED_POINT_SUPPORTED
  179159. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  179160. int unit, png_charp width, png_charp height));
  179161. #endif
  179162. #endif
  179163. #endif
  179164. /* Called when finished processing a row of data */
  179165. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  179166. /* Internal use only. Called before first row of data */
  179167. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  179168. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179169. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  179170. #endif
  179171. /* combine a row of data, dealing with alpha, etc. if requested */
  179172. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  179173. int mask));
  179174. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  179175. /* expand an interlaced row */
  179176. /* OLD pre-1.0.9 interface:
  179177. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  179178. png_bytep row, int pass, png_uint_32 transformations));
  179179. */
  179180. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  179181. #endif
  179182. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  179183. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  179184. /* grab pixels out of a row for an interlaced pass */
  179185. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  179186. png_bytep row, int pass));
  179187. #endif
  179188. /* unfilter a row */
  179189. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  179190. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  179191. /* Choose the best filter to use and filter the row data */
  179192. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  179193. png_row_infop row_info));
  179194. /* Write out the filtered row. */
  179195. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  179196. png_bytep filtered_row));
  179197. /* finish a row while reading, dealing with interlacing passes, etc. */
  179198. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  179199. /* initialize the row buffers, etc. */
  179200. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  179201. /* optional call to update the users info structure */
  179202. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  179203. png_infop info_ptr));
  179204. /* these are the functions that do the transformations */
  179205. #if defined(PNG_READ_FILLER_SUPPORTED)
  179206. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  179207. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  179208. #endif
  179209. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  179210. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  179211. png_bytep row));
  179212. #endif
  179213. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  179214. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  179215. png_bytep row));
  179216. #endif
  179217. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  179218. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  179219. png_bytep row));
  179220. #endif
  179221. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  179222. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  179223. png_bytep row));
  179224. #endif
  179225. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  179226. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  179227. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  179228. png_bytep row, png_uint_32 flags));
  179229. #endif
  179230. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  179231. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  179232. #endif
  179233. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  179234. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  179235. #endif
  179236. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  179237. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  179238. row_info, png_bytep row));
  179239. #endif
  179240. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  179241. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  179242. png_bytep row));
  179243. #endif
  179244. #if defined(PNG_READ_PACK_SUPPORTED)
  179245. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  179246. #endif
  179247. #if defined(PNG_READ_SHIFT_SUPPORTED)
  179248. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  179249. png_color_8p sig_bits));
  179250. #endif
  179251. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  179252. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  179253. #endif
  179254. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  179255. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  179256. #endif
  179257. #if defined(PNG_READ_DITHER_SUPPORTED)
  179258. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  179259. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  179260. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  179261. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  179262. png_colorp palette, int num_palette));
  179263. # endif
  179264. #endif
  179265. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  179266. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  179267. #endif
  179268. #if defined(PNG_WRITE_PACK_SUPPORTED)
  179269. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  179270. png_bytep row, png_uint_32 bit_depth));
  179271. #endif
  179272. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  179273. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  179274. png_color_8p bit_depth));
  179275. #endif
  179276. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  179277. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179278. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  179279. png_color_16p trans_values, png_color_16p background,
  179280. png_color_16p background_1,
  179281. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  179282. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  179283. png_uint_16pp gamma_16_to_1, int gamma_shift));
  179284. #else
  179285. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  179286. png_color_16p trans_values, png_color_16p background));
  179287. #endif
  179288. #endif
  179289. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179290. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  179291. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  179292. int gamma_shift));
  179293. #endif
  179294. #if defined(PNG_READ_EXPAND_SUPPORTED)
  179295. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  179296. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  179297. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  179298. png_bytep row, png_color_16p trans_value));
  179299. #endif
  179300. /* The following decodes the appropriate chunks, and does error correction,
  179301. * then calls the appropriate callback for the chunk if it is valid.
  179302. */
  179303. /* decode the IHDR chunk */
  179304. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  179305. png_uint_32 length));
  179306. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  179307. png_uint_32 length));
  179308. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  179309. png_uint_32 length));
  179310. #if defined(PNG_READ_bKGD_SUPPORTED)
  179311. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  179312. png_uint_32 length));
  179313. #endif
  179314. #if defined(PNG_READ_cHRM_SUPPORTED)
  179315. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  179316. png_uint_32 length));
  179317. #endif
  179318. #if defined(PNG_READ_gAMA_SUPPORTED)
  179319. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  179320. png_uint_32 length));
  179321. #endif
  179322. #if defined(PNG_READ_hIST_SUPPORTED)
  179323. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  179324. png_uint_32 length));
  179325. #endif
  179326. #if defined(PNG_READ_iCCP_SUPPORTED)
  179327. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  179328. png_uint_32 length));
  179329. #endif /* PNG_READ_iCCP_SUPPORTED */
  179330. #if defined(PNG_READ_iTXt_SUPPORTED)
  179331. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  179332. png_uint_32 length));
  179333. #endif
  179334. #if defined(PNG_READ_oFFs_SUPPORTED)
  179335. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  179336. png_uint_32 length));
  179337. #endif
  179338. #if defined(PNG_READ_pCAL_SUPPORTED)
  179339. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  179340. png_uint_32 length));
  179341. #endif
  179342. #if defined(PNG_READ_pHYs_SUPPORTED)
  179343. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  179344. png_uint_32 length));
  179345. #endif
  179346. #if defined(PNG_READ_sBIT_SUPPORTED)
  179347. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  179348. png_uint_32 length));
  179349. #endif
  179350. #if defined(PNG_READ_sCAL_SUPPORTED)
  179351. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  179352. png_uint_32 length));
  179353. #endif
  179354. #if defined(PNG_READ_sPLT_SUPPORTED)
  179355. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  179356. png_uint_32 length));
  179357. #endif /* PNG_READ_sPLT_SUPPORTED */
  179358. #if defined(PNG_READ_sRGB_SUPPORTED)
  179359. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  179360. png_uint_32 length));
  179361. #endif
  179362. #if defined(PNG_READ_tEXt_SUPPORTED)
  179363. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  179364. png_uint_32 length));
  179365. #endif
  179366. #if defined(PNG_READ_tIME_SUPPORTED)
  179367. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  179368. png_uint_32 length));
  179369. #endif
  179370. #if defined(PNG_READ_tRNS_SUPPORTED)
  179371. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  179372. png_uint_32 length));
  179373. #endif
  179374. #if defined(PNG_READ_zTXt_SUPPORTED)
  179375. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  179376. png_uint_32 length));
  179377. #endif
  179378. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  179379. png_infop info_ptr, png_uint_32 length));
  179380. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  179381. png_bytep chunk_name));
  179382. /* handle the transformations for reading and writing */
  179383. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  179384. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  179385. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  179386. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179387. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  179388. png_infop info_ptr));
  179389. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  179390. png_infop info_ptr));
  179391. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  179392. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  179393. png_uint_32 length));
  179394. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  179395. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  179396. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  179397. png_bytep buffer, png_size_t buffer_length));
  179398. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  179399. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  179400. png_bytep buffer, png_size_t buffer_length));
  179401. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  179402. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  179403. png_infop info_ptr, png_uint_32 length));
  179404. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  179405. png_infop info_ptr));
  179406. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  179407. png_infop info_ptr));
  179408. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  179409. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  179410. png_infop info_ptr));
  179411. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  179412. png_infop info_ptr));
  179413. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  179414. #if defined(PNG_READ_tEXt_SUPPORTED)
  179415. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  179416. png_infop info_ptr, png_uint_32 length));
  179417. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  179418. png_infop info_ptr));
  179419. #endif
  179420. #if defined(PNG_READ_zTXt_SUPPORTED)
  179421. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  179422. png_infop info_ptr, png_uint_32 length));
  179423. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  179424. png_infop info_ptr));
  179425. #endif
  179426. #if defined(PNG_READ_iTXt_SUPPORTED)
  179427. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  179428. png_infop info_ptr, png_uint_32 length));
  179429. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  179430. png_infop info_ptr));
  179431. #endif
  179432. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  179433. #ifdef PNG_MNG_FEATURES_SUPPORTED
  179434. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  179435. png_bytep row));
  179436. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  179437. png_bytep row));
  179438. #endif
  179439. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  179440. #if defined(PNG_MMX_CODE_SUPPORTED)
  179441. /* png.c */ /* PRIVATE */
  179442. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  179443. #endif
  179444. #endif
  179445. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  179446. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  179447. png_infop info_ptr));
  179448. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  179449. png_infop info_ptr));
  179450. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  179451. png_infop info_ptr));
  179452. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  179453. png_infop info_ptr));
  179454. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  179455. png_infop info_ptr));
  179456. #if defined(PNG_pHYs_SUPPORTED)
  179457. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  179458. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  179459. #endif /* PNG_pHYs_SUPPORTED */
  179460. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  179461. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  179462. #endif /* PNG_INTERNAL */
  179463. #ifdef __cplusplus
  179464. }
  179465. #endif
  179466. #endif /* PNG_VERSION_INFO_ONLY */
  179467. /* do not put anything past this line */
  179468. #endif /* PNG_H */
  179469. /********* End of inlined file: png.h *********/
  179470. #define PNG_NO_EXTERN
  179471. /********* Start of inlined file: png.c *********/
  179472. /* png.c - location for general purpose libpng functions
  179473. *
  179474. * Last changed in libpng 1.2.21 [October 4, 2007]
  179475. * For conditions of distribution and use, see copyright notice in png.h
  179476. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179477. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179478. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179479. */
  179480. #define PNG_INTERNAL
  179481. #define PNG_NO_EXTERN
  179482. /* Generate a compiler error if there is an old png.h in the search path. */
  179483. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  179484. /* Version information for C files. This had better match the version
  179485. * string defined in png.h. */
  179486. #ifdef PNG_USE_GLOBAL_ARRAYS
  179487. /* png_libpng_ver was changed to a function in version 1.0.5c */
  179488. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  179489. #ifdef PNG_READ_SUPPORTED
  179490. /* png_sig was changed to a function in version 1.0.5c */
  179491. /* Place to hold the signature string for a PNG file. */
  179492. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  179493. #endif /* PNG_READ_SUPPORTED */
  179494. /* Invoke global declarations for constant strings for known chunk types */
  179495. PNG_IHDR;
  179496. PNG_IDAT;
  179497. PNG_IEND;
  179498. PNG_PLTE;
  179499. PNG_bKGD;
  179500. PNG_cHRM;
  179501. PNG_gAMA;
  179502. PNG_hIST;
  179503. PNG_iCCP;
  179504. PNG_iTXt;
  179505. PNG_oFFs;
  179506. PNG_pCAL;
  179507. PNG_sCAL;
  179508. PNG_pHYs;
  179509. PNG_sBIT;
  179510. PNG_sPLT;
  179511. PNG_sRGB;
  179512. PNG_tEXt;
  179513. PNG_tIME;
  179514. PNG_tRNS;
  179515. PNG_zTXt;
  179516. #ifdef PNG_READ_SUPPORTED
  179517. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  179518. /* start of interlace block */
  179519. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  179520. /* offset to next interlace block */
  179521. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  179522. /* start of interlace block in the y direction */
  179523. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  179524. /* offset to next interlace block in the y direction */
  179525. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  179526. /* Height of interlace block. This is not currently used - if you need
  179527. * it, uncomment it here and in png.h
  179528. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  179529. */
  179530. /* Mask to determine which pixels are valid in a pass */
  179531. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  179532. /* Mask to determine which pixels to overwrite while displaying */
  179533. PNG_CONST int FARDATA png_pass_dsp_mask[]
  179534. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  179535. #endif /* PNG_READ_SUPPORTED */
  179536. #endif /* PNG_USE_GLOBAL_ARRAYS */
  179537. /* Tells libpng that we have already handled the first "num_bytes" bytes
  179538. * of the PNG file signature. If the PNG data is embedded into another
  179539. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  179540. * or write any of the magic bytes before it starts on the IHDR.
  179541. */
  179542. #ifdef PNG_READ_SUPPORTED
  179543. void PNGAPI
  179544. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  179545. {
  179546. if(png_ptr == NULL) return;
  179547. png_debug(1, "in png_set_sig_bytes\n");
  179548. if (num_bytes > 8)
  179549. png_error(png_ptr, "Too many bytes for PNG signature.");
  179550. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  179551. }
  179552. /* Checks whether the supplied bytes match the PNG signature. We allow
  179553. * checking less than the full 8-byte signature so that those apps that
  179554. * already read the first few bytes of a file to determine the file type
  179555. * can simply check the remaining bytes for extra assurance. Returns
  179556. * an integer less than, equal to, or greater than zero if sig is found,
  179557. * respectively, to be less than, to match, or be greater than the correct
  179558. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  179559. */
  179560. int PNGAPI
  179561. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  179562. {
  179563. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  179564. if (num_to_check > 8)
  179565. num_to_check = 8;
  179566. else if (num_to_check < 1)
  179567. return (-1);
  179568. if (start > 7)
  179569. return (-1);
  179570. if (start + num_to_check > 8)
  179571. num_to_check = 8 - start;
  179572. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  179573. }
  179574. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  179575. /* (Obsolete) function to check signature bytes. It does not allow one
  179576. * to check a partial signature. This function might be removed in the
  179577. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  179578. */
  179579. int PNGAPI
  179580. png_check_sig(png_bytep sig, int num)
  179581. {
  179582. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  179583. }
  179584. #endif
  179585. #endif /* PNG_READ_SUPPORTED */
  179586. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179587. /* Function to allocate memory for zlib and clear it to 0. */
  179588. #ifdef PNG_1_0_X
  179589. voidpf PNGAPI
  179590. #else
  179591. voidpf /* private */
  179592. #endif
  179593. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  179594. {
  179595. png_voidp ptr;
  179596. png_structp p=(png_structp)png_ptr;
  179597. png_uint_32 save_flags=p->flags;
  179598. png_uint_32 num_bytes;
  179599. if(png_ptr == NULL) return (NULL);
  179600. if (items > PNG_UINT_32_MAX/size)
  179601. {
  179602. png_warning (p, "Potential overflow in png_zalloc()");
  179603. return (NULL);
  179604. }
  179605. num_bytes = (png_uint_32)items * size;
  179606. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  179607. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  179608. p->flags=save_flags;
  179609. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  179610. if (ptr == NULL)
  179611. return ((voidpf)ptr);
  179612. if (num_bytes > (png_uint_32)0x8000L)
  179613. {
  179614. png_memset(ptr, 0, (png_size_t)0x8000L);
  179615. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  179616. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  179617. }
  179618. else
  179619. {
  179620. png_memset(ptr, 0, (png_size_t)num_bytes);
  179621. }
  179622. #endif
  179623. return ((voidpf)ptr);
  179624. }
  179625. /* function to free memory for zlib */
  179626. #ifdef PNG_1_0_X
  179627. void PNGAPI
  179628. #else
  179629. void /* private */
  179630. #endif
  179631. png_zfree(voidpf png_ptr, voidpf ptr)
  179632. {
  179633. png_free((png_structp)png_ptr, (png_voidp)ptr);
  179634. }
  179635. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  179636. * in case CRC is > 32 bits to leave the top bits 0.
  179637. */
  179638. void /* PRIVATE */
  179639. png_reset_crc(png_structp png_ptr)
  179640. {
  179641. png_ptr->crc = crc32(0, Z_NULL, 0);
  179642. }
  179643. /* Calculate the CRC over a section of data. We can only pass as
  179644. * much data to this routine as the largest single buffer size. We
  179645. * also check that this data will actually be used before going to the
  179646. * trouble of calculating it.
  179647. */
  179648. void /* PRIVATE */
  179649. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  179650. {
  179651. int need_crc = 1;
  179652. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  179653. {
  179654. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  179655. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  179656. need_crc = 0;
  179657. }
  179658. else /* critical */
  179659. {
  179660. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  179661. need_crc = 0;
  179662. }
  179663. if (need_crc)
  179664. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  179665. }
  179666. /* Allocate the memory for an info_struct for the application. We don't
  179667. * really need the png_ptr, but it could potentially be useful in the
  179668. * future. This should be used in favour of malloc(png_sizeof(png_info))
  179669. * and png_info_init() so that applications that want to use a shared
  179670. * libpng don't have to be recompiled if png_info changes size.
  179671. */
  179672. png_infop PNGAPI
  179673. png_create_info_struct(png_structp png_ptr)
  179674. {
  179675. png_infop info_ptr;
  179676. png_debug(1, "in png_create_info_struct\n");
  179677. if(png_ptr == NULL) return (NULL);
  179678. #ifdef PNG_USER_MEM_SUPPORTED
  179679. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  179680. png_ptr->malloc_fn, png_ptr->mem_ptr);
  179681. #else
  179682. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  179683. #endif
  179684. if (info_ptr != NULL)
  179685. png_info_init_3(&info_ptr, png_sizeof(png_info));
  179686. return (info_ptr);
  179687. }
  179688. /* This function frees the memory associated with a single info struct.
  179689. * Normally, one would use either png_destroy_read_struct() or
  179690. * png_destroy_write_struct() to free an info struct, but this may be
  179691. * useful for some applications.
  179692. */
  179693. void PNGAPI
  179694. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  179695. {
  179696. png_infop info_ptr = NULL;
  179697. if(png_ptr == NULL) return;
  179698. png_debug(1, "in png_destroy_info_struct\n");
  179699. if (info_ptr_ptr != NULL)
  179700. info_ptr = *info_ptr_ptr;
  179701. if (info_ptr != NULL)
  179702. {
  179703. png_info_destroy(png_ptr, info_ptr);
  179704. #ifdef PNG_USER_MEM_SUPPORTED
  179705. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  179706. png_ptr->mem_ptr);
  179707. #else
  179708. png_destroy_struct((png_voidp)info_ptr);
  179709. #endif
  179710. *info_ptr_ptr = NULL;
  179711. }
  179712. }
  179713. /* Initialize the info structure. This is now an internal function (0.89)
  179714. * and applications using it are urged to use png_create_info_struct()
  179715. * instead.
  179716. */
  179717. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  179718. #undef png_info_init
  179719. void PNGAPI
  179720. png_info_init(png_infop info_ptr)
  179721. {
  179722. /* We only come here via pre-1.0.12-compiled applications */
  179723. png_info_init_3(&info_ptr, 0);
  179724. }
  179725. #endif
  179726. void PNGAPI
  179727. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  179728. {
  179729. png_infop info_ptr = *ptr_ptr;
  179730. if(info_ptr == NULL) return;
  179731. png_debug(1, "in png_info_init_3\n");
  179732. if(png_sizeof(png_info) > png_info_struct_size)
  179733. {
  179734. png_destroy_struct(info_ptr);
  179735. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  179736. *ptr_ptr = info_ptr;
  179737. }
  179738. /* set everything to 0 */
  179739. png_memset(info_ptr, 0, png_sizeof (png_info));
  179740. }
  179741. #ifdef PNG_FREE_ME_SUPPORTED
  179742. void PNGAPI
  179743. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  179744. int freer, png_uint_32 mask)
  179745. {
  179746. png_debug(1, "in png_data_freer\n");
  179747. if (png_ptr == NULL || info_ptr == NULL)
  179748. return;
  179749. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  179750. info_ptr->free_me |= mask;
  179751. else if(freer == PNG_USER_WILL_FREE_DATA)
  179752. info_ptr->free_me &= ~mask;
  179753. else
  179754. png_warning(png_ptr,
  179755. "Unknown freer parameter in png_data_freer.");
  179756. }
  179757. #endif
  179758. void PNGAPI
  179759. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  179760. int num)
  179761. {
  179762. png_debug(1, "in png_free_data\n");
  179763. if (png_ptr == NULL || info_ptr == NULL)
  179764. return;
  179765. #if defined(PNG_TEXT_SUPPORTED)
  179766. /* free text item num or (if num == -1) all text items */
  179767. #ifdef PNG_FREE_ME_SUPPORTED
  179768. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  179769. #else
  179770. if (mask & PNG_FREE_TEXT)
  179771. #endif
  179772. {
  179773. if (num != -1)
  179774. {
  179775. if (info_ptr->text && info_ptr->text[num].key)
  179776. {
  179777. png_free(png_ptr, info_ptr->text[num].key);
  179778. info_ptr->text[num].key = NULL;
  179779. }
  179780. }
  179781. else
  179782. {
  179783. int i;
  179784. for (i = 0; i < info_ptr->num_text; i++)
  179785. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  179786. png_free(png_ptr, info_ptr->text);
  179787. info_ptr->text = NULL;
  179788. info_ptr->num_text=0;
  179789. }
  179790. }
  179791. #endif
  179792. #if defined(PNG_tRNS_SUPPORTED)
  179793. /* free any tRNS entry */
  179794. #ifdef PNG_FREE_ME_SUPPORTED
  179795. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  179796. #else
  179797. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  179798. #endif
  179799. {
  179800. png_free(png_ptr, info_ptr->trans);
  179801. info_ptr->valid &= ~PNG_INFO_tRNS;
  179802. #ifndef PNG_FREE_ME_SUPPORTED
  179803. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  179804. #endif
  179805. info_ptr->trans = NULL;
  179806. }
  179807. #endif
  179808. #if defined(PNG_sCAL_SUPPORTED)
  179809. /* free any sCAL entry */
  179810. #ifdef PNG_FREE_ME_SUPPORTED
  179811. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  179812. #else
  179813. if (mask & PNG_FREE_SCAL)
  179814. #endif
  179815. {
  179816. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  179817. png_free(png_ptr, info_ptr->scal_s_width);
  179818. png_free(png_ptr, info_ptr->scal_s_height);
  179819. info_ptr->scal_s_width = NULL;
  179820. info_ptr->scal_s_height = NULL;
  179821. #endif
  179822. info_ptr->valid &= ~PNG_INFO_sCAL;
  179823. }
  179824. #endif
  179825. #if defined(PNG_pCAL_SUPPORTED)
  179826. /* free any pCAL entry */
  179827. #ifdef PNG_FREE_ME_SUPPORTED
  179828. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  179829. #else
  179830. if (mask & PNG_FREE_PCAL)
  179831. #endif
  179832. {
  179833. png_free(png_ptr, info_ptr->pcal_purpose);
  179834. png_free(png_ptr, info_ptr->pcal_units);
  179835. info_ptr->pcal_purpose = NULL;
  179836. info_ptr->pcal_units = NULL;
  179837. if (info_ptr->pcal_params != NULL)
  179838. {
  179839. int i;
  179840. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  179841. {
  179842. png_free(png_ptr, info_ptr->pcal_params[i]);
  179843. info_ptr->pcal_params[i]=NULL;
  179844. }
  179845. png_free(png_ptr, info_ptr->pcal_params);
  179846. info_ptr->pcal_params = NULL;
  179847. }
  179848. info_ptr->valid &= ~PNG_INFO_pCAL;
  179849. }
  179850. #endif
  179851. #if defined(PNG_iCCP_SUPPORTED)
  179852. /* free any iCCP entry */
  179853. #ifdef PNG_FREE_ME_SUPPORTED
  179854. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  179855. #else
  179856. if (mask & PNG_FREE_ICCP)
  179857. #endif
  179858. {
  179859. png_free(png_ptr, info_ptr->iccp_name);
  179860. png_free(png_ptr, info_ptr->iccp_profile);
  179861. info_ptr->iccp_name = NULL;
  179862. info_ptr->iccp_profile = NULL;
  179863. info_ptr->valid &= ~PNG_INFO_iCCP;
  179864. }
  179865. #endif
  179866. #if defined(PNG_sPLT_SUPPORTED)
  179867. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  179868. #ifdef PNG_FREE_ME_SUPPORTED
  179869. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  179870. #else
  179871. if (mask & PNG_FREE_SPLT)
  179872. #endif
  179873. {
  179874. if (num != -1)
  179875. {
  179876. if(info_ptr->splt_palettes)
  179877. {
  179878. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  179879. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  179880. info_ptr->splt_palettes[num].name = NULL;
  179881. info_ptr->splt_palettes[num].entries = NULL;
  179882. }
  179883. }
  179884. else
  179885. {
  179886. if(info_ptr->splt_palettes_num)
  179887. {
  179888. int i;
  179889. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  179890. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  179891. png_free(png_ptr, info_ptr->splt_palettes);
  179892. info_ptr->splt_palettes = NULL;
  179893. info_ptr->splt_palettes_num = 0;
  179894. }
  179895. info_ptr->valid &= ~PNG_INFO_sPLT;
  179896. }
  179897. }
  179898. #endif
  179899. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179900. if(png_ptr->unknown_chunk.data)
  179901. {
  179902. png_free(png_ptr, png_ptr->unknown_chunk.data);
  179903. png_ptr->unknown_chunk.data = NULL;
  179904. }
  179905. #ifdef PNG_FREE_ME_SUPPORTED
  179906. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  179907. #else
  179908. if (mask & PNG_FREE_UNKN)
  179909. #endif
  179910. {
  179911. if (num != -1)
  179912. {
  179913. if(info_ptr->unknown_chunks)
  179914. {
  179915. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  179916. info_ptr->unknown_chunks[num].data = NULL;
  179917. }
  179918. }
  179919. else
  179920. {
  179921. int i;
  179922. if(info_ptr->unknown_chunks_num)
  179923. {
  179924. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  179925. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  179926. png_free(png_ptr, info_ptr->unknown_chunks);
  179927. info_ptr->unknown_chunks = NULL;
  179928. info_ptr->unknown_chunks_num = 0;
  179929. }
  179930. }
  179931. }
  179932. #endif
  179933. #if defined(PNG_hIST_SUPPORTED)
  179934. /* free any hIST entry */
  179935. #ifdef PNG_FREE_ME_SUPPORTED
  179936. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  179937. #else
  179938. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  179939. #endif
  179940. {
  179941. png_free(png_ptr, info_ptr->hist);
  179942. info_ptr->hist = NULL;
  179943. info_ptr->valid &= ~PNG_INFO_hIST;
  179944. #ifndef PNG_FREE_ME_SUPPORTED
  179945. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  179946. #endif
  179947. }
  179948. #endif
  179949. /* free any PLTE entry that was internally allocated */
  179950. #ifdef PNG_FREE_ME_SUPPORTED
  179951. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  179952. #else
  179953. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  179954. #endif
  179955. {
  179956. png_zfree(png_ptr, info_ptr->palette);
  179957. info_ptr->palette = NULL;
  179958. info_ptr->valid &= ~PNG_INFO_PLTE;
  179959. #ifndef PNG_FREE_ME_SUPPORTED
  179960. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  179961. #endif
  179962. info_ptr->num_palette = 0;
  179963. }
  179964. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179965. /* free any image bits attached to the info structure */
  179966. #ifdef PNG_FREE_ME_SUPPORTED
  179967. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  179968. #else
  179969. if (mask & PNG_FREE_ROWS)
  179970. #endif
  179971. {
  179972. if(info_ptr->row_pointers)
  179973. {
  179974. int row;
  179975. for (row = 0; row < (int)info_ptr->height; row++)
  179976. {
  179977. png_free(png_ptr, info_ptr->row_pointers[row]);
  179978. info_ptr->row_pointers[row]=NULL;
  179979. }
  179980. png_free(png_ptr, info_ptr->row_pointers);
  179981. info_ptr->row_pointers=NULL;
  179982. }
  179983. info_ptr->valid &= ~PNG_INFO_IDAT;
  179984. }
  179985. #endif
  179986. #ifdef PNG_FREE_ME_SUPPORTED
  179987. if(num == -1)
  179988. info_ptr->free_me &= ~mask;
  179989. else
  179990. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  179991. #endif
  179992. }
  179993. /* This is an internal routine to free any memory that the info struct is
  179994. * pointing to before re-using it or freeing the struct itself. Recall
  179995. * that png_free() checks for NULL pointers for us.
  179996. */
  179997. void /* PRIVATE */
  179998. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  179999. {
  180000. png_debug(1, "in png_info_destroy\n");
  180001. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  180002. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180003. if (png_ptr->num_chunk_list)
  180004. {
  180005. png_free(png_ptr, png_ptr->chunk_list);
  180006. png_ptr->chunk_list=NULL;
  180007. png_ptr->num_chunk_list=0;
  180008. }
  180009. #endif
  180010. png_info_init_3(&info_ptr, png_sizeof(png_info));
  180011. }
  180012. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180013. /* This function returns a pointer to the io_ptr associated with the user
  180014. * functions. The application should free any memory associated with this
  180015. * pointer before png_write_destroy() or png_read_destroy() are called.
  180016. */
  180017. png_voidp PNGAPI
  180018. png_get_io_ptr(png_structp png_ptr)
  180019. {
  180020. if(png_ptr == NULL) return (NULL);
  180021. return (png_ptr->io_ptr);
  180022. }
  180023. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180024. #if !defined(PNG_NO_STDIO)
  180025. /* Initialize the default input/output functions for the PNG file. If you
  180026. * use your own read or write routines, you can call either png_set_read_fn()
  180027. * or png_set_write_fn() instead of png_init_io(). If you have defined
  180028. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  180029. * necessarily available.
  180030. */
  180031. void PNGAPI
  180032. png_init_io(png_structp png_ptr, png_FILE_p fp)
  180033. {
  180034. png_debug(1, "in png_init_io\n");
  180035. if(png_ptr == NULL) return;
  180036. png_ptr->io_ptr = (png_voidp)fp;
  180037. }
  180038. #endif
  180039. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  180040. /* Convert the supplied time into an RFC 1123 string suitable for use in
  180041. * a "Creation Time" or other text-based time string.
  180042. */
  180043. png_charp PNGAPI
  180044. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  180045. {
  180046. static PNG_CONST char short_months[12][4] =
  180047. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  180048. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  180049. if(png_ptr == NULL) return (NULL);
  180050. if (png_ptr->time_buffer == NULL)
  180051. {
  180052. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  180053. png_sizeof(char)));
  180054. }
  180055. #if defined(_WIN32_WCE)
  180056. {
  180057. wchar_t time_buf[29];
  180058. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  180059. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180060. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180061. ptime->second % 61);
  180062. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  180063. NULL, NULL);
  180064. }
  180065. #else
  180066. #ifdef USE_FAR_KEYWORD
  180067. {
  180068. char near_time_buf[29];
  180069. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  180070. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180071. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180072. ptime->second % 61);
  180073. png_memcpy(png_ptr->time_buffer, near_time_buf,
  180074. 29*png_sizeof(char));
  180075. }
  180076. #else
  180077. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  180078. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180079. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180080. ptime->second % 61);
  180081. #endif
  180082. #endif /* _WIN32_WCE */
  180083. return ((png_charp)png_ptr->time_buffer);
  180084. }
  180085. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  180086. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180087. png_charp PNGAPI
  180088. png_get_copyright(png_structp png_ptr)
  180089. {
  180090. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180091. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  180092. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  180093. Copyright (c) 1996-1997 Andreas Dilger\n\
  180094. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  180095. }
  180096. /* The following return the library version as a short string in the
  180097. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  180098. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  180099. * is defined in png.h.
  180100. * Note: now there is no difference between png_get_libpng_ver() and
  180101. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  180102. * it is guaranteed that png.c uses the correct version of png.h.
  180103. */
  180104. png_charp PNGAPI
  180105. png_get_libpng_ver(png_structp png_ptr)
  180106. {
  180107. /* Version of *.c files used when building libpng */
  180108. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180109. return ((png_charp) PNG_LIBPNG_VER_STRING);
  180110. }
  180111. png_charp PNGAPI
  180112. png_get_header_ver(png_structp png_ptr)
  180113. {
  180114. /* Version of *.h files used when building libpng */
  180115. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180116. return ((png_charp) PNG_LIBPNG_VER_STRING);
  180117. }
  180118. png_charp PNGAPI
  180119. png_get_header_version(png_structp png_ptr)
  180120. {
  180121. /* Returns longer string containing both version and date */
  180122. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180123. return ((png_charp) PNG_HEADER_VERSION_STRING
  180124. #ifndef PNG_READ_SUPPORTED
  180125. " (NO READ SUPPORT)"
  180126. #endif
  180127. "\n");
  180128. }
  180129. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180130. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180131. int PNGAPI
  180132. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  180133. {
  180134. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  180135. int i;
  180136. png_bytep p;
  180137. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  180138. return 0;
  180139. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  180140. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  180141. if (!png_memcmp(chunk_name, p, 4))
  180142. return ((int)*(p+4));
  180143. return 0;
  180144. }
  180145. #endif
  180146. /* This function, added to libpng-1.0.6g, is untested. */
  180147. int PNGAPI
  180148. png_reset_zstream(png_structp png_ptr)
  180149. {
  180150. if (png_ptr == NULL) return Z_STREAM_ERROR;
  180151. return (inflateReset(&png_ptr->zstream));
  180152. }
  180153. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180154. /* This function was added to libpng-1.0.7 */
  180155. png_uint_32 PNGAPI
  180156. png_access_version_number(void)
  180157. {
  180158. /* Version of *.c files used when building libpng */
  180159. return((png_uint_32) PNG_LIBPNG_VER);
  180160. }
  180161. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  180162. #if !defined(PNG_1_0_X)
  180163. /* this function was added to libpng 1.2.0 */
  180164. int PNGAPI
  180165. png_mmx_support(void)
  180166. {
  180167. /* obsolete, to be removed from libpng-1.4.0 */
  180168. return -1;
  180169. }
  180170. #endif /* PNG_1_0_X */
  180171. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  180172. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180173. #ifdef PNG_SIZE_T
  180174. /* Added at libpng version 1.2.6 */
  180175. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  180176. png_size_t PNGAPI
  180177. png_convert_size(size_t size)
  180178. {
  180179. if (size > (png_size_t)-1)
  180180. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  180181. return ((png_size_t)size);
  180182. }
  180183. #endif /* PNG_SIZE_T */
  180184. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180185. /********* End of inlined file: png.c *********/
  180186. /********* Start of inlined file: pngerror.c *********/
  180187. /* pngerror.c - stub functions for i/o and memory allocation
  180188. *
  180189. * Last changed in libpng 1.2.20 October 4, 2007
  180190. * For conditions of distribution and use, see copyright notice in png.h
  180191. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180192. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180193. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180194. *
  180195. * This file provides a location for all error handling. Users who
  180196. * need special error handling are expected to write replacement functions
  180197. * and use png_set_error_fn() to use those functions. See the instructions
  180198. * at each function.
  180199. */
  180200. #define PNG_INTERNAL
  180201. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180202. static void /* PRIVATE */
  180203. png_default_error PNGARG((png_structp png_ptr,
  180204. png_const_charp error_message));
  180205. #ifndef PNG_NO_WARNINGS
  180206. static void /* PRIVATE */
  180207. png_default_warning PNGARG((png_structp png_ptr,
  180208. png_const_charp warning_message));
  180209. #endif /* PNG_NO_WARNINGS */
  180210. /* This function is called whenever there is a fatal error. This function
  180211. * should not be changed. If there is a need to handle errors differently,
  180212. * you should supply a replacement error function and use png_set_error_fn()
  180213. * to replace the error function at run-time.
  180214. */
  180215. #ifndef PNG_NO_ERROR_TEXT
  180216. void PNGAPI
  180217. png_error(png_structp png_ptr, png_const_charp error_message)
  180218. {
  180219. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180220. char msg[16];
  180221. if (png_ptr != NULL)
  180222. {
  180223. if (png_ptr->flags&
  180224. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  180225. {
  180226. if (*error_message == '#')
  180227. {
  180228. int offset;
  180229. for (offset=1; offset<15; offset++)
  180230. if (*(error_message+offset) == ' ')
  180231. break;
  180232. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  180233. {
  180234. int i;
  180235. for (i=0; i<offset-1; i++)
  180236. msg[i]=error_message[i+1];
  180237. msg[i]='\0';
  180238. error_message=msg;
  180239. }
  180240. else
  180241. error_message+=offset;
  180242. }
  180243. else
  180244. {
  180245. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  180246. {
  180247. msg[0]='0';
  180248. msg[1]='\0';
  180249. error_message=msg;
  180250. }
  180251. }
  180252. }
  180253. }
  180254. #endif
  180255. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  180256. (*(png_ptr->error_fn))(png_ptr, error_message);
  180257. /* If the custom handler doesn't exist, or if it returns,
  180258. use the default handler, which will not return. */
  180259. png_default_error(png_ptr, error_message);
  180260. }
  180261. #else
  180262. void PNGAPI
  180263. png_err(png_structp png_ptr)
  180264. {
  180265. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  180266. (*(png_ptr->error_fn))(png_ptr, '\0');
  180267. /* If the custom handler doesn't exist, or if it returns,
  180268. use the default handler, which will not return. */
  180269. png_default_error(png_ptr, '\0');
  180270. }
  180271. #endif /* PNG_NO_ERROR_TEXT */
  180272. #ifndef PNG_NO_WARNINGS
  180273. /* This function is called whenever there is a non-fatal error. This function
  180274. * should not be changed. If there is a need to handle warnings differently,
  180275. * you should supply a replacement warning function and use
  180276. * png_set_error_fn() to replace the warning function at run-time.
  180277. */
  180278. void PNGAPI
  180279. png_warning(png_structp png_ptr, png_const_charp warning_message)
  180280. {
  180281. int offset = 0;
  180282. if (png_ptr != NULL)
  180283. {
  180284. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180285. if (png_ptr->flags&
  180286. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  180287. #endif
  180288. {
  180289. if (*warning_message == '#')
  180290. {
  180291. for (offset=1; offset<15; offset++)
  180292. if (*(warning_message+offset) == ' ')
  180293. break;
  180294. }
  180295. }
  180296. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  180297. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  180298. }
  180299. else
  180300. png_default_warning(png_ptr, warning_message+offset);
  180301. }
  180302. #endif /* PNG_NO_WARNINGS */
  180303. /* These utilities are used internally to build an error message that relates
  180304. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  180305. * this is used to prefix the message. The message is limited in length
  180306. * to 63 bytes, the name characters are output as hex digits wrapped in []
  180307. * if the character is invalid.
  180308. */
  180309. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  180310. /*static PNG_CONST char png_digit[16] = {
  180311. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  180312. 'A', 'B', 'C', 'D', 'E', 'F'
  180313. };*/
  180314. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  180315. static void /* PRIVATE */
  180316. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  180317. error_message)
  180318. {
  180319. int iout = 0, iin = 0;
  180320. while (iin < 4)
  180321. {
  180322. int c = png_ptr->chunk_name[iin++];
  180323. if (isnonalpha(c))
  180324. {
  180325. buffer[iout++] = '[';
  180326. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  180327. buffer[iout++] = png_digit[c & 0x0f];
  180328. buffer[iout++] = ']';
  180329. }
  180330. else
  180331. {
  180332. buffer[iout++] = (png_byte)c;
  180333. }
  180334. }
  180335. if (error_message == NULL)
  180336. buffer[iout] = 0;
  180337. else
  180338. {
  180339. buffer[iout++] = ':';
  180340. buffer[iout++] = ' ';
  180341. png_strncpy(buffer+iout, error_message, 63);
  180342. buffer[iout+63] = 0;
  180343. }
  180344. }
  180345. #ifdef PNG_READ_SUPPORTED
  180346. void PNGAPI
  180347. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  180348. {
  180349. char msg[18+64];
  180350. if (png_ptr == NULL)
  180351. png_error(png_ptr, error_message);
  180352. else
  180353. {
  180354. png_format_buffer(png_ptr, msg, error_message);
  180355. png_error(png_ptr, msg);
  180356. }
  180357. }
  180358. #endif /* PNG_READ_SUPPORTED */
  180359. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  180360. #ifndef PNG_NO_WARNINGS
  180361. void PNGAPI
  180362. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  180363. {
  180364. char msg[18+64];
  180365. if (png_ptr == NULL)
  180366. png_warning(png_ptr, warning_message);
  180367. else
  180368. {
  180369. png_format_buffer(png_ptr, msg, warning_message);
  180370. png_warning(png_ptr, msg);
  180371. }
  180372. }
  180373. #endif /* PNG_NO_WARNINGS */
  180374. /* This is the default error handling function. Note that replacements for
  180375. * this function MUST NOT RETURN, or the program will likely crash. This
  180376. * function is used by default, or if the program supplies NULL for the
  180377. * error function pointer in png_set_error_fn().
  180378. */
  180379. static void /* PRIVATE */
  180380. png_default_error(png_structp png_ptr, png_const_charp error_message)
  180381. {
  180382. #ifndef PNG_NO_CONSOLE_IO
  180383. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180384. if (*error_message == '#')
  180385. {
  180386. int offset;
  180387. char error_number[16];
  180388. for (offset=0; offset<15; offset++)
  180389. {
  180390. error_number[offset] = *(error_message+offset+1);
  180391. if (*(error_message+offset) == ' ')
  180392. break;
  180393. }
  180394. if((offset > 1) && (offset < 15))
  180395. {
  180396. error_number[offset-1]='\0';
  180397. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  180398. error_message+offset);
  180399. }
  180400. else
  180401. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  180402. }
  180403. else
  180404. #endif
  180405. fprintf(stderr, "libpng error: %s\n", error_message);
  180406. #endif
  180407. #ifdef PNG_SETJMP_SUPPORTED
  180408. if (png_ptr)
  180409. {
  180410. # ifdef USE_FAR_KEYWORD
  180411. {
  180412. jmp_buf jmpbuf;
  180413. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  180414. longjmp(jmpbuf, 1);
  180415. }
  180416. # else
  180417. longjmp(png_ptr->jmpbuf, 1);
  180418. # endif
  180419. }
  180420. #else
  180421. PNG_ABORT();
  180422. #endif
  180423. #ifdef PNG_NO_CONSOLE_IO
  180424. error_message = error_message; /* make compiler happy */
  180425. #endif
  180426. }
  180427. #ifndef PNG_NO_WARNINGS
  180428. /* This function is called when there is a warning, but the library thinks
  180429. * it can continue anyway. Replacement functions don't have to do anything
  180430. * here if you don't want them to. In the default configuration, png_ptr is
  180431. * not used, but it is passed in case it may be useful.
  180432. */
  180433. static void /* PRIVATE */
  180434. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  180435. {
  180436. #ifndef PNG_NO_CONSOLE_IO
  180437. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180438. if (*warning_message == '#')
  180439. {
  180440. int offset;
  180441. char warning_number[16];
  180442. for (offset=0; offset<15; offset++)
  180443. {
  180444. warning_number[offset]=*(warning_message+offset+1);
  180445. if (*(warning_message+offset) == ' ')
  180446. break;
  180447. }
  180448. if((offset > 1) && (offset < 15))
  180449. {
  180450. warning_number[offset-1]='\0';
  180451. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  180452. warning_message+offset);
  180453. }
  180454. else
  180455. fprintf(stderr, "libpng warning: %s\n", warning_message);
  180456. }
  180457. else
  180458. # endif
  180459. fprintf(stderr, "libpng warning: %s\n", warning_message);
  180460. #else
  180461. warning_message = warning_message; /* make compiler happy */
  180462. #endif
  180463. png_ptr = png_ptr; /* make compiler happy */
  180464. }
  180465. #endif /* PNG_NO_WARNINGS */
  180466. /* This function is called when the application wants to use another method
  180467. * of handling errors and warnings. Note that the error function MUST NOT
  180468. * return to the calling routine or serious problems will occur. The return
  180469. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  180470. */
  180471. void PNGAPI
  180472. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  180473. png_error_ptr error_fn, png_error_ptr warning_fn)
  180474. {
  180475. if (png_ptr == NULL)
  180476. return;
  180477. png_ptr->error_ptr = error_ptr;
  180478. png_ptr->error_fn = error_fn;
  180479. png_ptr->warning_fn = warning_fn;
  180480. }
  180481. /* This function returns a pointer to the error_ptr associated with the user
  180482. * functions. The application should free any memory associated with this
  180483. * pointer before png_write_destroy and png_read_destroy are called.
  180484. */
  180485. png_voidp PNGAPI
  180486. png_get_error_ptr(png_structp png_ptr)
  180487. {
  180488. if (png_ptr == NULL)
  180489. return NULL;
  180490. return ((png_voidp)png_ptr->error_ptr);
  180491. }
  180492. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180493. void PNGAPI
  180494. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  180495. {
  180496. if(png_ptr != NULL)
  180497. {
  180498. png_ptr->flags &=
  180499. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  180500. }
  180501. }
  180502. #endif
  180503. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  180504. /********* End of inlined file: pngerror.c *********/
  180505. /********* Start of inlined file: pngget.c *********/
  180506. /* pngget.c - retrieval of values from info struct
  180507. *
  180508. * Last changed in libpng 1.2.15 January 5, 2007
  180509. * For conditions of distribution and use, see copyright notice in png.h
  180510. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180511. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180512. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180513. */
  180514. #define PNG_INTERNAL
  180515. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180516. png_uint_32 PNGAPI
  180517. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  180518. {
  180519. if (png_ptr != NULL && info_ptr != NULL)
  180520. return(info_ptr->valid & flag);
  180521. else
  180522. return(0);
  180523. }
  180524. png_uint_32 PNGAPI
  180525. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  180526. {
  180527. if (png_ptr != NULL && info_ptr != NULL)
  180528. return(info_ptr->rowbytes);
  180529. else
  180530. return(0);
  180531. }
  180532. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  180533. png_bytepp PNGAPI
  180534. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  180535. {
  180536. if (png_ptr != NULL && info_ptr != NULL)
  180537. return(info_ptr->row_pointers);
  180538. else
  180539. return(0);
  180540. }
  180541. #endif
  180542. #ifdef PNG_EASY_ACCESS_SUPPORTED
  180543. /* easy access to info, added in libpng-0.99 */
  180544. png_uint_32 PNGAPI
  180545. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  180546. {
  180547. if (png_ptr != NULL && info_ptr != NULL)
  180548. {
  180549. return info_ptr->width;
  180550. }
  180551. return (0);
  180552. }
  180553. png_uint_32 PNGAPI
  180554. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  180555. {
  180556. if (png_ptr != NULL && info_ptr != NULL)
  180557. {
  180558. return info_ptr->height;
  180559. }
  180560. return (0);
  180561. }
  180562. png_byte PNGAPI
  180563. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  180564. {
  180565. if (png_ptr != NULL && info_ptr != NULL)
  180566. {
  180567. return info_ptr->bit_depth;
  180568. }
  180569. return (0);
  180570. }
  180571. png_byte PNGAPI
  180572. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  180573. {
  180574. if (png_ptr != NULL && info_ptr != NULL)
  180575. {
  180576. return info_ptr->color_type;
  180577. }
  180578. return (0);
  180579. }
  180580. png_byte PNGAPI
  180581. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  180582. {
  180583. if (png_ptr != NULL && info_ptr != NULL)
  180584. {
  180585. return info_ptr->filter_type;
  180586. }
  180587. return (0);
  180588. }
  180589. png_byte PNGAPI
  180590. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  180591. {
  180592. if (png_ptr != NULL && info_ptr != NULL)
  180593. {
  180594. return info_ptr->interlace_type;
  180595. }
  180596. return (0);
  180597. }
  180598. png_byte PNGAPI
  180599. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  180600. {
  180601. if (png_ptr != NULL && info_ptr != NULL)
  180602. {
  180603. return info_ptr->compression_type;
  180604. }
  180605. return (0);
  180606. }
  180607. png_uint_32 PNGAPI
  180608. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  180609. {
  180610. if (png_ptr != NULL && info_ptr != NULL)
  180611. #if defined(PNG_pHYs_SUPPORTED)
  180612. if (info_ptr->valid & PNG_INFO_pHYs)
  180613. {
  180614. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  180615. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  180616. return (0);
  180617. else return (info_ptr->x_pixels_per_unit);
  180618. }
  180619. #else
  180620. return (0);
  180621. #endif
  180622. return (0);
  180623. }
  180624. png_uint_32 PNGAPI
  180625. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  180626. {
  180627. if (png_ptr != NULL && info_ptr != NULL)
  180628. #if defined(PNG_pHYs_SUPPORTED)
  180629. if (info_ptr->valid & PNG_INFO_pHYs)
  180630. {
  180631. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  180632. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  180633. return (0);
  180634. else return (info_ptr->y_pixels_per_unit);
  180635. }
  180636. #else
  180637. return (0);
  180638. #endif
  180639. return (0);
  180640. }
  180641. png_uint_32 PNGAPI
  180642. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  180643. {
  180644. if (png_ptr != NULL && info_ptr != NULL)
  180645. #if defined(PNG_pHYs_SUPPORTED)
  180646. if (info_ptr->valid & PNG_INFO_pHYs)
  180647. {
  180648. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  180649. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  180650. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  180651. return (0);
  180652. else return (info_ptr->x_pixels_per_unit);
  180653. }
  180654. #else
  180655. return (0);
  180656. #endif
  180657. return (0);
  180658. }
  180659. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180660. float PNGAPI
  180661. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  180662. {
  180663. if (png_ptr != NULL && info_ptr != NULL)
  180664. #if defined(PNG_pHYs_SUPPORTED)
  180665. if (info_ptr->valid & PNG_INFO_pHYs)
  180666. {
  180667. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  180668. if (info_ptr->x_pixels_per_unit == 0)
  180669. return ((float)0.0);
  180670. else
  180671. return ((float)((float)info_ptr->y_pixels_per_unit
  180672. /(float)info_ptr->x_pixels_per_unit));
  180673. }
  180674. #else
  180675. return (0.0);
  180676. #endif
  180677. return ((float)0.0);
  180678. }
  180679. #endif
  180680. png_int_32 PNGAPI
  180681. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  180682. {
  180683. if (png_ptr != NULL && info_ptr != NULL)
  180684. #if defined(PNG_oFFs_SUPPORTED)
  180685. if (info_ptr->valid & PNG_INFO_oFFs)
  180686. {
  180687. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  180688. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  180689. return (0);
  180690. else return (info_ptr->x_offset);
  180691. }
  180692. #else
  180693. return (0);
  180694. #endif
  180695. return (0);
  180696. }
  180697. png_int_32 PNGAPI
  180698. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  180699. {
  180700. if (png_ptr != NULL && info_ptr != NULL)
  180701. #if defined(PNG_oFFs_SUPPORTED)
  180702. if (info_ptr->valid & PNG_INFO_oFFs)
  180703. {
  180704. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  180705. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  180706. return (0);
  180707. else return (info_ptr->y_offset);
  180708. }
  180709. #else
  180710. return (0);
  180711. #endif
  180712. return (0);
  180713. }
  180714. png_int_32 PNGAPI
  180715. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  180716. {
  180717. if (png_ptr != NULL && info_ptr != NULL)
  180718. #if defined(PNG_oFFs_SUPPORTED)
  180719. if (info_ptr->valid & PNG_INFO_oFFs)
  180720. {
  180721. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  180722. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  180723. return (0);
  180724. else return (info_ptr->x_offset);
  180725. }
  180726. #else
  180727. return (0);
  180728. #endif
  180729. return (0);
  180730. }
  180731. png_int_32 PNGAPI
  180732. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  180733. {
  180734. if (png_ptr != NULL && info_ptr != NULL)
  180735. #if defined(PNG_oFFs_SUPPORTED)
  180736. if (info_ptr->valid & PNG_INFO_oFFs)
  180737. {
  180738. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  180739. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  180740. return (0);
  180741. else return (info_ptr->y_offset);
  180742. }
  180743. #else
  180744. return (0);
  180745. #endif
  180746. return (0);
  180747. }
  180748. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  180749. png_uint_32 PNGAPI
  180750. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  180751. {
  180752. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  180753. *.0254 +.5));
  180754. }
  180755. png_uint_32 PNGAPI
  180756. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  180757. {
  180758. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  180759. *.0254 +.5));
  180760. }
  180761. png_uint_32 PNGAPI
  180762. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  180763. {
  180764. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  180765. *.0254 +.5));
  180766. }
  180767. float PNGAPI
  180768. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  180769. {
  180770. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  180771. *.00003937);
  180772. }
  180773. float PNGAPI
  180774. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  180775. {
  180776. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  180777. *.00003937);
  180778. }
  180779. #if defined(PNG_pHYs_SUPPORTED)
  180780. png_uint_32 PNGAPI
  180781. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  180782. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  180783. {
  180784. png_uint_32 retval = 0;
  180785. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  180786. {
  180787. png_debug1(1, "in %s retrieval function\n", "pHYs");
  180788. if (res_x != NULL)
  180789. {
  180790. *res_x = info_ptr->x_pixels_per_unit;
  180791. retval |= PNG_INFO_pHYs;
  180792. }
  180793. if (res_y != NULL)
  180794. {
  180795. *res_y = info_ptr->y_pixels_per_unit;
  180796. retval |= PNG_INFO_pHYs;
  180797. }
  180798. if (unit_type != NULL)
  180799. {
  180800. *unit_type = (int)info_ptr->phys_unit_type;
  180801. retval |= PNG_INFO_pHYs;
  180802. if(*unit_type == 1)
  180803. {
  180804. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  180805. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  180806. }
  180807. }
  180808. }
  180809. return (retval);
  180810. }
  180811. #endif /* PNG_pHYs_SUPPORTED */
  180812. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  180813. /* png_get_channels really belongs in here, too, but it's been around longer */
  180814. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  180815. png_byte PNGAPI
  180816. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  180817. {
  180818. if (png_ptr != NULL && info_ptr != NULL)
  180819. return(info_ptr->channels);
  180820. else
  180821. return (0);
  180822. }
  180823. png_bytep PNGAPI
  180824. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  180825. {
  180826. if (png_ptr != NULL && info_ptr != NULL)
  180827. return(info_ptr->signature);
  180828. else
  180829. return (NULL);
  180830. }
  180831. #if defined(PNG_bKGD_SUPPORTED)
  180832. png_uint_32 PNGAPI
  180833. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  180834. png_color_16p *background)
  180835. {
  180836. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  180837. && background != NULL)
  180838. {
  180839. png_debug1(1, "in %s retrieval function\n", "bKGD");
  180840. *background = &(info_ptr->background);
  180841. return (PNG_INFO_bKGD);
  180842. }
  180843. return (0);
  180844. }
  180845. #endif
  180846. #if defined(PNG_cHRM_SUPPORTED)
  180847. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180848. png_uint_32 PNGAPI
  180849. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  180850. double *white_x, double *white_y, double *red_x, double *red_y,
  180851. double *green_x, double *green_y, double *blue_x, double *blue_y)
  180852. {
  180853. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  180854. {
  180855. png_debug1(1, "in %s retrieval function\n", "cHRM");
  180856. if (white_x != NULL)
  180857. *white_x = (double)info_ptr->x_white;
  180858. if (white_y != NULL)
  180859. *white_y = (double)info_ptr->y_white;
  180860. if (red_x != NULL)
  180861. *red_x = (double)info_ptr->x_red;
  180862. if (red_y != NULL)
  180863. *red_y = (double)info_ptr->y_red;
  180864. if (green_x != NULL)
  180865. *green_x = (double)info_ptr->x_green;
  180866. if (green_y != NULL)
  180867. *green_y = (double)info_ptr->y_green;
  180868. if (blue_x != NULL)
  180869. *blue_x = (double)info_ptr->x_blue;
  180870. if (blue_y != NULL)
  180871. *blue_y = (double)info_ptr->y_blue;
  180872. return (PNG_INFO_cHRM);
  180873. }
  180874. return (0);
  180875. }
  180876. #endif
  180877. #ifdef PNG_FIXED_POINT_SUPPORTED
  180878. png_uint_32 PNGAPI
  180879. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  180880. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  180881. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  180882. png_fixed_point *blue_x, png_fixed_point *blue_y)
  180883. {
  180884. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  180885. {
  180886. png_debug1(1, "in %s retrieval function\n", "cHRM");
  180887. if (white_x != NULL)
  180888. *white_x = info_ptr->int_x_white;
  180889. if (white_y != NULL)
  180890. *white_y = info_ptr->int_y_white;
  180891. if (red_x != NULL)
  180892. *red_x = info_ptr->int_x_red;
  180893. if (red_y != NULL)
  180894. *red_y = info_ptr->int_y_red;
  180895. if (green_x != NULL)
  180896. *green_x = info_ptr->int_x_green;
  180897. if (green_y != NULL)
  180898. *green_y = info_ptr->int_y_green;
  180899. if (blue_x != NULL)
  180900. *blue_x = info_ptr->int_x_blue;
  180901. if (blue_y != NULL)
  180902. *blue_y = info_ptr->int_y_blue;
  180903. return (PNG_INFO_cHRM);
  180904. }
  180905. return (0);
  180906. }
  180907. #endif
  180908. #endif
  180909. #if defined(PNG_gAMA_SUPPORTED)
  180910. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180911. png_uint_32 PNGAPI
  180912. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  180913. {
  180914. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  180915. && file_gamma != NULL)
  180916. {
  180917. png_debug1(1, "in %s retrieval function\n", "gAMA");
  180918. *file_gamma = (double)info_ptr->gamma;
  180919. return (PNG_INFO_gAMA);
  180920. }
  180921. return (0);
  180922. }
  180923. #endif
  180924. #ifdef PNG_FIXED_POINT_SUPPORTED
  180925. png_uint_32 PNGAPI
  180926. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  180927. png_fixed_point *int_file_gamma)
  180928. {
  180929. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  180930. && int_file_gamma != NULL)
  180931. {
  180932. png_debug1(1, "in %s retrieval function\n", "gAMA");
  180933. *int_file_gamma = info_ptr->int_gamma;
  180934. return (PNG_INFO_gAMA);
  180935. }
  180936. return (0);
  180937. }
  180938. #endif
  180939. #endif
  180940. #if defined(PNG_sRGB_SUPPORTED)
  180941. png_uint_32 PNGAPI
  180942. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  180943. {
  180944. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  180945. && file_srgb_intent != NULL)
  180946. {
  180947. png_debug1(1, "in %s retrieval function\n", "sRGB");
  180948. *file_srgb_intent = (int)info_ptr->srgb_intent;
  180949. return (PNG_INFO_sRGB);
  180950. }
  180951. return (0);
  180952. }
  180953. #endif
  180954. #if defined(PNG_iCCP_SUPPORTED)
  180955. png_uint_32 PNGAPI
  180956. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  180957. png_charpp name, int *compression_type,
  180958. png_charpp profile, png_uint_32 *proflen)
  180959. {
  180960. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  180961. && name != NULL && profile != NULL && proflen != NULL)
  180962. {
  180963. png_debug1(1, "in %s retrieval function\n", "iCCP");
  180964. *name = info_ptr->iccp_name;
  180965. *profile = info_ptr->iccp_profile;
  180966. /* compression_type is a dummy so the API won't have to change
  180967. if we introduce multiple compression types later. */
  180968. *proflen = (int)info_ptr->iccp_proflen;
  180969. *compression_type = (int)info_ptr->iccp_compression;
  180970. return (PNG_INFO_iCCP);
  180971. }
  180972. return (0);
  180973. }
  180974. #endif
  180975. #if defined(PNG_sPLT_SUPPORTED)
  180976. png_uint_32 PNGAPI
  180977. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  180978. png_sPLT_tpp spalettes)
  180979. {
  180980. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  180981. {
  180982. *spalettes = info_ptr->splt_palettes;
  180983. return ((png_uint_32)info_ptr->splt_palettes_num);
  180984. }
  180985. return (0);
  180986. }
  180987. #endif
  180988. #if defined(PNG_hIST_SUPPORTED)
  180989. png_uint_32 PNGAPI
  180990. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  180991. {
  180992. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  180993. && hist != NULL)
  180994. {
  180995. png_debug1(1, "in %s retrieval function\n", "hIST");
  180996. *hist = info_ptr->hist;
  180997. return (PNG_INFO_hIST);
  180998. }
  180999. return (0);
  181000. }
  181001. #endif
  181002. png_uint_32 PNGAPI
  181003. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  181004. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  181005. int *color_type, int *interlace_type, int *compression_type,
  181006. int *filter_type)
  181007. {
  181008. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  181009. bit_depth != NULL && color_type != NULL)
  181010. {
  181011. png_debug1(1, "in %s retrieval function\n", "IHDR");
  181012. *width = info_ptr->width;
  181013. *height = info_ptr->height;
  181014. *bit_depth = info_ptr->bit_depth;
  181015. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  181016. png_error(png_ptr, "Invalid bit depth");
  181017. *color_type = info_ptr->color_type;
  181018. if (info_ptr->color_type > 6)
  181019. png_error(png_ptr, "Invalid color type");
  181020. if (compression_type != NULL)
  181021. *compression_type = info_ptr->compression_type;
  181022. if (filter_type != NULL)
  181023. *filter_type = info_ptr->filter_type;
  181024. if (interlace_type != NULL)
  181025. *interlace_type = info_ptr->interlace_type;
  181026. /* check for potential overflow of rowbytes */
  181027. if (*width == 0 || *width > PNG_UINT_31_MAX)
  181028. png_error(png_ptr, "Invalid image width");
  181029. if (*height == 0 || *height > PNG_UINT_31_MAX)
  181030. png_error(png_ptr, "Invalid image height");
  181031. if (info_ptr->width > (PNG_UINT_32_MAX
  181032. >> 3) /* 8-byte RGBA pixels */
  181033. - 64 /* bigrowbuf hack */
  181034. - 1 /* filter byte */
  181035. - 7*8 /* rounding of width to multiple of 8 pixels */
  181036. - 8) /* extra max_pixel_depth pad */
  181037. {
  181038. png_warning(png_ptr,
  181039. "Width too large for libpng to process image data.");
  181040. }
  181041. return (1);
  181042. }
  181043. return (0);
  181044. }
  181045. #if defined(PNG_oFFs_SUPPORTED)
  181046. png_uint_32 PNGAPI
  181047. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  181048. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  181049. {
  181050. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  181051. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  181052. {
  181053. png_debug1(1, "in %s retrieval function\n", "oFFs");
  181054. *offset_x = info_ptr->x_offset;
  181055. *offset_y = info_ptr->y_offset;
  181056. *unit_type = (int)info_ptr->offset_unit_type;
  181057. return (PNG_INFO_oFFs);
  181058. }
  181059. return (0);
  181060. }
  181061. #endif
  181062. #if defined(PNG_pCAL_SUPPORTED)
  181063. png_uint_32 PNGAPI
  181064. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  181065. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  181066. png_charp *units, png_charpp *params)
  181067. {
  181068. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  181069. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  181070. nparams != NULL && units != NULL && params != NULL)
  181071. {
  181072. png_debug1(1, "in %s retrieval function\n", "pCAL");
  181073. *purpose = info_ptr->pcal_purpose;
  181074. *X0 = info_ptr->pcal_X0;
  181075. *X1 = info_ptr->pcal_X1;
  181076. *type = (int)info_ptr->pcal_type;
  181077. *nparams = (int)info_ptr->pcal_nparams;
  181078. *units = info_ptr->pcal_units;
  181079. *params = info_ptr->pcal_params;
  181080. return (PNG_INFO_pCAL);
  181081. }
  181082. return (0);
  181083. }
  181084. #endif
  181085. #if defined(PNG_sCAL_SUPPORTED)
  181086. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181087. png_uint_32 PNGAPI
  181088. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  181089. int *unit, double *width, double *height)
  181090. {
  181091. if (png_ptr != NULL && info_ptr != NULL &&
  181092. (info_ptr->valid & PNG_INFO_sCAL))
  181093. {
  181094. *unit = info_ptr->scal_unit;
  181095. *width = info_ptr->scal_pixel_width;
  181096. *height = info_ptr->scal_pixel_height;
  181097. return (PNG_INFO_sCAL);
  181098. }
  181099. return(0);
  181100. }
  181101. #else
  181102. #ifdef PNG_FIXED_POINT_SUPPORTED
  181103. png_uint_32 PNGAPI
  181104. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  181105. int *unit, png_charpp width, png_charpp height)
  181106. {
  181107. if (png_ptr != NULL && info_ptr != NULL &&
  181108. (info_ptr->valid & PNG_INFO_sCAL))
  181109. {
  181110. *unit = info_ptr->scal_unit;
  181111. *width = info_ptr->scal_s_width;
  181112. *height = info_ptr->scal_s_height;
  181113. return (PNG_INFO_sCAL);
  181114. }
  181115. return(0);
  181116. }
  181117. #endif
  181118. #endif
  181119. #endif
  181120. #if defined(PNG_pHYs_SUPPORTED)
  181121. png_uint_32 PNGAPI
  181122. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  181123. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  181124. {
  181125. png_uint_32 retval = 0;
  181126. if (png_ptr != NULL && info_ptr != NULL &&
  181127. (info_ptr->valid & PNG_INFO_pHYs))
  181128. {
  181129. png_debug1(1, "in %s retrieval function\n", "pHYs");
  181130. if (res_x != NULL)
  181131. {
  181132. *res_x = info_ptr->x_pixels_per_unit;
  181133. retval |= PNG_INFO_pHYs;
  181134. }
  181135. if (res_y != NULL)
  181136. {
  181137. *res_y = info_ptr->y_pixels_per_unit;
  181138. retval |= PNG_INFO_pHYs;
  181139. }
  181140. if (unit_type != NULL)
  181141. {
  181142. *unit_type = (int)info_ptr->phys_unit_type;
  181143. retval |= PNG_INFO_pHYs;
  181144. }
  181145. }
  181146. return (retval);
  181147. }
  181148. #endif
  181149. png_uint_32 PNGAPI
  181150. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  181151. int *num_palette)
  181152. {
  181153. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  181154. && palette != NULL)
  181155. {
  181156. png_debug1(1, "in %s retrieval function\n", "PLTE");
  181157. *palette = info_ptr->palette;
  181158. *num_palette = info_ptr->num_palette;
  181159. png_debug1(3, "num_palette = %d\n", *num_palette);
  181160. return (PNG_INFO_PLTE);
  181161. }
  181162. return (0);
  181163. }
  181164. #if defined(PNG_sBIT_SUPPORTED)
  181165. png_uint_32 PNGAPI
  181166. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  181167. {
  181168. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  181169. && sig_bit != NULL)
  181170. {
  181171. png_debug1(1, "in %s retrieval function\n", "sBIT");
  181172. *sig_bit = &(info_ptr->sig_bit);
  181173. return (PNG_INFO_sBIT);
  181174. }
  181175. return (0);
  181176. }
  181177. #endif
  181178. #if defined(PNG_TEXT_SUPPORTED)
  181179. png_uint_32 PNGAPI
  181180. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  181181. int *num_text)
  181182. {
  181183. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  181184. {
  181185. png_debug1(1, "in %s retrieval function\n",
  181186. (png_ptr->chunk_name[0] == '\0' ? "text"
  181187. : (png_const_charp)png_ptr->chunk_name));
  181188. if (text_ptr != NULL)
  181189. *text_ptr = info_ptr->text;
  181190. if (num_text != NULL)
  181191. *num_text = info_ptr->num_text;
  181192. return ((png_uint_32)info_ptr->num_text);
  181193. }
  181194. if (num_text != NULL)
  181195. *num_text = 0;
  181196. return(0);
  181197. }
  181198. #endif
  181199. #if defined(PNG_tIME_SUPPORTED)
  181200. png_uint_32 PNGAPI
  181201. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  181202. {
  181203. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  181204. && mod_time != NULL)
  181205. {
  181206. png_debug1(1, "in %s retrieval function\n", "tIME");
  181207. *mod_time = &(info_ptr->mod_time);
  181208. return (PNG_INFO_tIME);
  181209. }
  181210. return (0);
  181211. }
  181212. #endif
  181213. #if defined(PNG_tRNS_SUPPORTED)
  181214. png_uint_32 PNGAPI
  181215. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  181216. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  181217. {
  181218. png_uint_32 retval = 0;
  181219. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  181220. {
  181221. png_debug1(1, "in %s retrieval function\n", "tRNS");
  181222. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  181223. {
  181224. if (trans != NULL)
  181225. {
  181226. *trans = info_ptr->trans;
  181227. retval |= PNG_INFO_tRNS;
  181228. }
  181229. if (trans_values != NULL)
  181230. *trans_values = &(info_ptr->trans_values);
  181231. }
  181232. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  181233. {
  181234. if (trans_values != NULL)
  181235. {
  181236. *trans_values = &(info_ptr->trans_values);
  181237. retval |= PNG_INFO_tRNS;
  181238. }
  181239. if(trans != NULL)
  181240. *trans = NULL;
  181241. }
  181242. if(num_trans != NULL)
  181243. {
  181244. *num_trans = info_ptr->num_trans;
  181245. retval |= PNG_INFO_tRNS;
  181246. }
  181247. }
  181248. return (retval);
  181249. }
  181250. #endif
  181251. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181252. png_uint_32 PNGAPI
  181253. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  181254. png_unknown_chunkpp unknowns)
  181255. {
  181256. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  181257. {
  181258. *unknowns = info_ptr->unknown_chunks;
  181259. return ((png_uint_32)info_ptr->unknown_chunks_num);
  181260. }
  181261. return (0);
  181262. }
  181263. #endif
  181264. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  181265. png_byte PNGAPI
  181266. png_get_rgb_to_gray_status (png_structp png_ptr)
  181267. {
  181268. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  181269. }
  181270. #endif
  181271. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  181272. png_voidp PNGAPI
  181273. png_get_user_chunk_ptr(png_structp png_ptr)
  181274. {
  181275. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  181276. }
  181277. #endif
  181278. #ifdef PNG_WRITE_SUPPORTED
  181279. png_uint_32 PNGAPI
  181280. png_get_compression_buffer_size(png_structp png_ptr)
  181281. {
  181282. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  181283. }
  181284. #endif
  181285. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  181286. #ifndef PNG_1_0_X
  181287. /* this function was added to libpng 1.2.0 and should exist by default */
  181288. png_uint_32 PNGAPI
  181289. png_get_asm_flags (png_structp png_ptr)
  181290. {
  181291. /* obsolete, to be removed from libpng-1.4.0 */
  181292. return (png_ptr? 0L: 0L);
  181293. }
  181294. /* this function was added to libpng 1.2.0 and should exist by default */
  181295. png_uint_32 PNGAPI
  181296. png_get_asm_flagmask (int flag_select)
  181297. {
  181298. /* obsolete, to be removed from libpng-1.4.0 */
  181299. flag_select=flag_select;
  181300. return 0L;
  181301. }
  181302. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  181303. /* this function was added to libpng 1.2.0 */
  181304. png_uint_32 PNGAPI
  181305. png_get_mmx_flagmask (int flag_select, int *compilerID)
  181306. {
  181307. /* obsolete, to be removed from libpng-1.4.0 */
  181308. flag_select=flag_select;
  181309. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  181310. return 0L;
  181311. }
  181312. /* this function was added to libpng 1.2.0 */
  181313. png_byte PNGAPI
  181314. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  181315. {
  181316. /* obsolete, to be removed from libpng-1.4.0 */
  181317. return (png_ptr? 0: 0);
  181318. }
  181319. /* this function was added to libpng 1.2.0 */
  181320. png_uint_32 PNGAPI
  181321. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  181322. {
  181323. /* obsolete, to be removed from libpng-1.4.0 */
  181324. return (png_ptr? 0L: 0L);
  181325. }
  181326. #endif /* ?PNG_1_0_X */
  181327. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  181328. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  181329. /* these functions were added to libpng 1.2.6 */
  181330. png_uint_32 PNGAPI
  181331. png_get_user_width_max (png_structp png_ptr)
  181332. {
  181333. return (png_ptr? png_ptr->user_width_max : 0);
  181334. }
  181335. png_uint_32 PNGAPI
  181336. png_get_user_height_max (png_structp png_ptr)
  181337. {
  181338. return (png_ptr? png_ptr->user_height_max : 0);
  181339. }
  181340. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  181341. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  181342. /********* End of inlined file: pngget.c *********/
  181343. /********* Start of inlined file: pngmem.c *********/
  181344. /* pngmem.c - stub functions for memory allocation
  181345. *
  181346. * Last changed in libpng 1.2.13 November 13, 2006
  181347. * For conditions of distribution and use, see copyright notice in png.h
  181348. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  181349. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181350. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181351. *
  181352. * This file provides a location for all memory allocation. Users who
  181353. * need special memory handling are expected to supply replacement
  181354. * functions for png_malloc() and png_free(), and to use
  181355. * png_create_read_struct_2() and png_create_write_struct_2() to
  181356. * identify the replacement functions.
  181357. */
  181358. #define PNG_INTERNAL
  181359. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181360. /* Borland DOS special memory handler */
  181361. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  181362. /* if you change this, be sure to change the one in png.h also */
  181363. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  181364. by a single call to calloc() if this is thought to improve performance. */
  181365. png_voidp /* PRIVATE */
  181366. png_create_struct(int type)
  181367. {
  181368. #ifdef PNG_USER_MEM_SUPPORTED
  181369. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  181370. }
  181371. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  181372. png_voidp /* PRIVATE */
  181373. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  181374. {
  181375. #endif /* PNG_USER_MEM_SUPPORTED */
  181376. png_size_t size;
  181377. png_voidp struct_ptr;
  181378. if (type == PNG_STRUCT_INFO)
  181379. size = png_sizeof(png_info);
  181380. else if (type == PNG_STRUCT_PNG)
  181381. size = png_sizeof(png_struct);
  181382. else
  181383. return (png_get_copyright(NULL));
  181384. #ifdef PNG_USER_MEM_SUPPORTED
  181385. if(malloc_fn != NULL)
  181386. {
  181387. png_struct dummy_struct;
  181388. png_structp png_ptr = &dummy_struct;
  181389. png_ptr->mem_ptr=mem_ptr;
  181390. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  181391. }
  181392. else
  181393. #endif /* PNG_USER_MEM_SUPPORTED */
  181394. struct_ptr = (png_voidp)farmalloc(size);
  181395. if (struct_ptr != NULL)
  181396. png_memset(struct_ptr, 0, size);
  181397. return (struct_ptr);
  181398. }
  181399. /* Free memory allocated by a png_create_struct() call */
  181400. void /* PRIVATE */
  181401. png_destroy_struct(png_voidp struct_ptr)
  181402. {
  181403. #ifdef PNG_USER_MEM_SUPPORTED
  181404. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  181405. }
  181406. /* Free memory allocated by a png_create_struct() call */
  181407. void /* PRIVATE */
  181408. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  181409. png_voidp mem_ptr)
  181410. {
  181411. #endif
  181412. if (struct_ptr != NULL)
  181413. {
  181414. #ifdef PNG_USER_MEM_SUPPORTED
  181415. if(free_fn != NULL)
  181416. {
  181417. png_struct dummy_struct;
  181418. png_structp png_ptr = &dummy_struct;
  181419. png_ptr->mem_ptr=mem_ptr;
  181420. (*(free_fn))(png_ptr, struct_ptr);
  181421. return;
  181422. }
  181423. #endif /* PNG_USER_MEM_SUPPORTED */
  181424. farfree (struct_ptr);
  181425. }
  181426. }
  181427. /* Allocate memory. For reasonable files, size should never exceed
  181428. * 64K. However, zlib may allocate more then 64K if you don't tell
  181429. * it not to. See zconf.h and png.h for more information. zlib does
  181430. * need to allocate exactly 64K, so whatever you call here must
  181431. * have the ability to do that.
  181432. *
  181433. * Borland seems to have a problem in DOS mode for exactly 64K.
  181434. * It gives you a segment with an offset of 8 (perhaps to store its
  181435. * memory stuff). zlib doesn't like this at all, so we have to
  181436. * detect and deal with it. This code should not be needed in
  181437. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  181438. * been updated by Alexander Lehmann for version 0.89 to waste less
  181439. * memory.
  181440. *
  181441. * Note that we can't use png_size_t for the "size" declaration,
  181442. * since on some systems a png_size_t is a 16-bit quantity, and as a
  181443. * result, we would be truncating potentially larger memory requests
  181444. * (which should cause a fatal error) and introducing major problems.
  181445. */
  181446. png_voidp PNGAPI
  181447. png_malloc(png_structp png_ptr, png_uint_32 size)
  181448. {
  181449. png_voidp ret;
  181450. if (png_ptr == NULL || size == 0)
  181451. return (NULL);
  181452. #ifdef PNG_USER_MEM_SUPPORTED
  181453. if(png_ptr->malloc_fn != NULL)
  181454. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  181455. else
  181456. ret = (png_malloc_default(png_ptr, size));
  181457. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181458. png_error(png_ptr, "Out of memory!");
  181459. return (ret);
  181460. }
  181461. png_voidp PNGAPI
  181462. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  181463. {
  181464. png_voidp ret;
  181465. #endif /* PNG_USER_MEM_SUPPORTED */
  181466. if (png_ptr == NULL || size == 0)
  181467. return (NULL);
  181468. #ifdef PNG_MAX_MALLOC_64K
  181469. if (size > (png_uint_32)65536L)
  181470. {
  181471. png_warning(png_ptr, "Cannot Allocate > 64K");
  181472. ret = NULL;
  181473. }
  181474. else
  181475. #endif
  181476. if (size != (size_t)size)
  181477. ret = NULL;
  181478. else if (size == (png_uint_32)65536L)
  181479. {
  181480. if (png_ptr->offset_table == NULL)
  181481. {
  181482. /* try to see if we need to do any of this fancy stuff */
  181483. ret = farmalloc(size);
  181484. if (ret == NULL || ((png_size_t)ret & 0xffff))
  181485. {
  181486. int num_blocks;
  181487. png_uint_32 total_size;
  181488. png_bytep table;
  181489. int i;
  181490. png_byte huge * hptr;
  181491. if (ret != NULL)
  181492. {
  181493. farfree(ret);
  181494. ret = NULL;
  181495. }
  181496. if(png_ptr->zlib_window_bits > 14)
  181497. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  181498. else
  181499. num_blocks = 1;
  181500. if (png_ptr->zlib_mem_level >= 7)
  181501. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  181502. else
  181503. num_blocks++;
  181504. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  181505. table = farmalloc(total_size);
  181506. if (table == NULL)
  181507. {
  181508. #ifndef PNG_USER_MEM_SUPPORTED
  181509. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181510. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  181511. else
  181512. png_warning(png_ptr, "Out Of Memory.");
  181513. #endif
  181514. return (NULL);
  181515. }
  181516. if ((png_size_t)table & 0xfff0)
  181517. {
  181518. #ifndef PNG_USER_MEM_SUPPORTED
  181519. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181520. png_error(png_ptr,
  181521. "Farmalloc didn't return normalized pointer");
  181522. else
  181523. png_warning(png_ptr,
  181524. "Farmalloc didn't return normalized pointer");
  181525. #endif
  181526. return (NULL);
  181527. }
  181528. png_ptr->offset_table = table;
  181529. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  181530. png_sizeof (png_bytep));
  181531. if (png_ptr->offset_table_ptr == NULL)
  181532. {
  181533. #ifndef PNG_USER_MEM_SUPPORTED
  181534. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181535. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  181536. else
  181537. png_warning(png_ptr, "Out Of memory.");
  181538. #endif
  181539. return (NULL);
  181540. }
  181541. hptr = (png_byte huge *)table;
  181542. if ((png_size_t)hptr & 0xf)
  181543. {
  181544. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  181545. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  181546. }
  181547. for (i = 0; i < num_blocks; i++)
  181548. {
  181549. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  181550. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  181551. }
  181552. png_ptr->offset_table_number = num_blocks;
  181553. png_ptr->offset_table_count = 0;
  181554. png_ptr->offset_table_count_free = 0;
  181555. }
  181556. }
  181557. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  181558. {
  181559. #ifndef PNG_USER_MEM_SUPPORTED
  181560. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181561. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  181562. else
  181563. png_warning(png_ptr, "Out of Memory.");
  181564. #endif
  181565. return (NULL);
  181566. }
  181567. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  181568. }
  181569. else
  181570. ret = farmalloc(size);
  181571. #ifndef PNG_USER_MEM_SUPPORTED
  181572. if (ret == NULL)
  181573. {
  181574. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181575. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  181576. else
  181577. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  181578. }
  181579. #endif
  181580. return (ret);
  181581. }
  181582. /* free a pointer allocated by png_malloc(). In the default
  181583. configuration, png_ptr is not used, but is passed in case it
  181584. is needed. If ptr is NULL, return without taking any action. */
  181585. void PNGAPI
  181586. png_free(png_structp png_ptr, png_voidp ptr)
  181587. {
  181588. if (png_ptr == NULL || ptr == NULL)
  181589. return;
  181590. #ifdef PNG_USER_MEM_SUPPORTED
  181591. if (png_ptr->free_fn != NULL)
  181592. {
  181593. (*(png_ptr->free_fn))(png_ptr, ptr);
  181594. return;
  181595. }
  181596. else png_free_default(png_ptr, ptr);
  181597. }
  181598. void PNGAPI
  181599. png_free_default(png_structp png_ptr, png_voidp ptr)
  181600. {
  181601. #endif /* PNG_USER_MEM_SUPPORTED */
  181602. if(png_ptr == NULL) return;
  181603. if (png_ptr->offset_table != NULL)
  181604. {
  181605. int i;
  181606. for (i = 0; i < png_ptr->offset_table_count; i++)
  181607. {
  181608. if (ptr == png_ptr->offset_table_ptr[i])
  181609. {
  181610. ptr = NULL;
  181611. png_ptr->offset_table_count_free++;
  181612. break;
  181613. }
  181614. }
  181615. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  181616. {
  181617. farfree(png_ptr->offset_table);
  181618. farfree(png_ptr->offset_table_ptr);
  181619. png_ptr->offset_table = NULL;
  181620. png_ptr->offset_table_ptr = NULL;
  181621. }
  181622. }
  181623. if (ptr != NULL)
  181624. {
  181625. farfree(ptr);
  181626. }
  181627. }
  181628. #else /* Not the Borland DOS special memory handler */
  181629. /* Allocate memory for a png_struct or a png_info. The malloc and
  181630. memset can be replaced by a single call to calloc() if this is thought
  181631. to improve performance noticably. */
  181632. png_voidp /* PRIVATE */
  181633. png_create_struct(int type)
  181634. {
  181635. #ifdef PNG_USER_MEM_SUPPORTED
  181636. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  181637. }
  181638. /* Allocate memory for a png_struct or a png_info. The malloc and
  181639. memset can be replaced by a single call to calloc() if this is thought
  181640. to improve performance noticably. */
  181641. png_voidp /* PRIVATE */
  181642. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  181643. {
  181644. #endif /* PNG_USER_MEM_SUPPORTED */
  181645. png_size_t size;
  181646. png_voidp struct_ptr;
  181647. if (type == PNG_STRUCT_INFO)
  181648. size = png_sizeof(png_info);
  181649. else if (type == PNG_STRUCT_PNG)
  181650. size = png_sizeof(png_struct);
  181651. else
  181652. return (NULL);
  181653. #ifdef PNG_USER_MEM_SUPPORTED
  181654. if(malloc_fn != NULL)
  181655. {
  181656. png_struct dummy_struct;
  181657. png_structp png_ptr = &dummy_struct;
  181658. png_ptr->mem_ptr=mem_ptr;
  181659. struct_ptr = (*(malloc_fn))(png_ptr, size);
  181660. if (struct_ptr != NULL)
  181661. png_memset(struct_ptr, 0, size);
  181662. return (struct_ptr);
  181663. }
  181664. #endif /* PNG_USER_MEM_SUPPORTED */
  181665. #if defined(__TURBOC__) && !defined(__FLAT__)
  181666. struct_ptr = (png_voidp)farmalloc(size);
  181667. #else
  181668. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  181669. struct_ptr = (png_voidp)halloc(size,1);
  181670. # else
  181671. struct_ptr = (png_voidp)malloc(size);
  181672. # endif
  181673. #endif
  181674. if (struct_ptr != NULL)
  181675. png_memset(struct_ptr, 0, size);
  181676. return (struct_ptr);
  181677. }
  181678. /* Free memory allocated by a png_create_struct() call */
  181679. void /* PRIVATE */
  181680. png_destroy_struct(png_voidp struct_ptr)
  181681. {
  181682. #ifdef PNG_USER_MEM_SUPPORTED
  181683. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  181684. }
  181685. /* Free memory allocated by a png_create_struct() call */
  181686. void /* PRIVATE */
  181687. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  181688. png_voidp mem_ptr)
  181689. {
  181690. #endif /* PNG_USER_MEM_SUPPORTED */
  181691. if (struct_ptr != NULL)
  181692. {
  181693. #ifdef PNG_USER_MEM_SUPPORTED
  181694. if(free_fn != NULL)
  181695. {
  181696. png_struct dummy_struct;
  181697. png_structp png_ptr = &dummy_struct;
  181698. png_ptr->mem_ptr=mem_ptr;
  181699. (*(free_fn))(png_ptr, struct_ptr);
  181700. return;
  181701. }
  181702. #endif /* PNG_USER_MEM_SUPPORTED */
  181703. #if defined(__TURBOC__) && !defined(__FLAT__)
  181704. farfree(struct_ptr);
  181705. #else
  181706. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  181707. hfree(struct_ptr);
  181708. # else
  181709. free(struct_ptr);
  181710. # endif
  181711. #endif
  181712. }
  181713. }
  181714. /* Allocate memory. For reasonable files, size should never exceed
  181715. 64K. However, zlib may allocate more then 64K if you don't tell
  181716. it not to. See zconf.h and png.h for more information. zlib does
  181717. need to allocate exactly 64K, so whatever you call here must
  181718. have the ability to do that. */
  181719. png_voidp PNGAPI
  181720. png_malloc(png_structp png_ptr, png_uint_32 size)
  181721. {
  181722. png_voidp ret;
  181723. #ifdef PNG_USER_MEM_SUPPORTED
  181724. if (png_ptr == NULL || size == 0)
  181725. return (NULL);
  181726. if(png_ptr->malloc_fn != NULL)
  181727. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  181728. else
  181729. ret = (png_malloc_default(png_ptr, size));
  181730. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181731. png_error(png_ptr, "Out of Memory!");
  181732. return (ret);
  181733. }
  181734. png_voidp PNGAPI
  181735. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  181736. {
  181737. png_voidp ret;
  181738. #endif /* PNG_USER_MEM_SUPPORTED */
  181739. if (png_ptr == NULL || size == 0)
  181740. return (NULL);
  181741. #ifdef PNG_MAX_MALLOC_64K
  181742. if (size > (png_uint_32)65536L)
  181743. {
  181744. #ifndef PNG_USER_MEM_SUPPORTED
  181745. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181746. png_error(png_ptr, "Cannot Allocate > 64K");
  181747. else
  181748. #endif
  181749. return NULL;
  181750. }
  181751. #endif
  181752. /* Check for overflow */
  181753. #if defined(__TURBOC__) && !defined(__FLAT__)
  181754. if (size != (unsigned long)size)
  181755. ret = NULL;
  181756. else
  181757. ret = farmalloc(size);
  181758. #else
  181759. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  181760. if (size != (unsigned long)size)
  181761. ret = NULL;
  181762. else
  181763. ret = halloc(size, 1);
  181764. # else
  181765. if (size != (size_t)size)
  181766. ret = NULL;
  181767. else
  181768. ret = malloc((size_t)size);
  181769. # endif
  181770. #endif
  181771. #ifndef PNG_USER_MEM_SUPPORTED
  181772. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181773. png_error(png_ptr, "Out of Memory");
  181774. #endif
  181775. return (ret);
  181776. }
  181777. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  181778. without taking any action. */
  181779. void PNGAPI
  181780. png_free(png_structp png_ptr, png_voidp ptr)
  181781. {
  181782. if (png_ptr == NULL || ptr == NULL)
  181783. return;
  181784. #ifdef PNG_USER_MEM_SUPPORTED
  181785. if (png_ptr->free_fn != NULL)
  181786. {
  181787. (*(png_ptr->free_fn))(png_ptr, ptr);
  181788. return;
  181789. }
  181790. else png_free_default(png_ptr, ptr);
  181791. }
  181792. void PNGAPI
  181793. png_free_default(png_structp png_ptr, png_voidp ptr)
  181794. {
  181795. if (png_ptr == NULL || ptr == NULL)
  181796. return;
  181797. #endif /* PNG_USER_MEM_SUPPORTED */
  181798. #if defined(__TURBOC__) && !defined(__FLAT__)
  181799. farfree(ptr);
  181800. #else
  181801. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  181802. hfree(ptr);
  181803. # else
  181804. free(ptr);
  181805. # endif
  181806. #endif
  181807. }
  181808. #endif /* Not Borland DOS special memory handler */
  181809. #if defined(PNG_1_0_X)
  181810. # define png_malloc_warn png_malloc
  181811. #else
  181812. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  181813. * function will set up png_malloc() to issue a png_warning and return NULL
  181814. * instead of issuing a png_error, if it fails to allocate the requested
  181815. * memory.
  181816. */
  181817. png_voidp PNGAPI
  181818. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  181819. {
  181820. png_voidp ptr;
  181821. png_uint_32 save_flags;
  181822. if(png_ptr == NULL) return (NULL);
  181823. save_flags=png_ptr->flags;
  181824. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  181825. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  181826. png_ptr->flags=save_flags;
  181827. return(ptr);
  181828. }
  181829. #endif
  181830. png_voidp PNGAPI
  181831. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  181832. png_uint_32 length)
  181833. {
  181834. png_size_t size;
  181835. size = (png_size_t)length;
  181836. if ((png_uint_32)size != length)
  181837. png_error(png_ptr,"Overflow in png_memcpy_check.");
  181838. return(png_memcpy (s1, s2, size));
  181839. }
  181840. png_voidp PNGAPI
  181841. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  181842. png_uint_32 length)
  181843. {
  181844. png_size_t size;
  181845. size = (png_size_t)length;
  181846. if ((png_uint_32)size != length)
  181847. png_error(png_ptr,"Overflow in png_memset_check.");
  181848. return (png_memset (s1, value, size));
  181849. }
  181850. #ifdef PNG_USER_MEM_SUPPORTED
  181851. /* This function is called when the application wants to use another method
  181852. * of allocating and freeing memory.
  181853. */
  181854. void PNGAPI
  181855. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  181856. malloc_fn, png_free_ptr free_fn)
  181857. {
  181858. if(png_ptr != NULL) {
  181859. png_ptr->mem_ptr = mem_ptr;
  181860. png_ptr->malloc_fn = malloc_fn;
  181861. png_ptr->free_fn = free_fn;
  181862. }
  181863. }
  181864. /* This function returns a pointer to the mem_ptr associated with the user
  181865. * functions. The application should free any memory associated with this
  181866. * pointer before png_write_destroy and png_read_destroy are called.
  181867. */
  181868. png_voidp PNGAPI
  181869. png_get_mem_ptr(png_structp png_ptr)
  181870. {
  181871. if(png_ptr == NULL) return (NULL);
  181872. return ((png_voidp)png_ptr->mem_ptr);
  181873. }
  181874. #endif /* PNG_USER_MEM_SUPPORTED */
  181875. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  181876. /********* End of inlined file: pngmem.c *********/
  181877. /********* Start of inlined file: pngread.c *********/
  181878. /* pngread.c - read a PNG file
  181879. *
  181880. * Last changed in libpng 1.2.20 September 7, 2007
  181881. * For conditions of distribution and use, see copyright notice in png.h
  181882. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181883. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181884. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181885. *
  181886. * This file contains routines that an application calls directly to
  181887. * read a PNG file or stream.
  181888. */
  181889. #define PNG_INTERNAL
  181890. #if defined(PNG_READ_SUPPORTED)
  181891. /* Create a PNG structure for reading, and allocate any memory needed. */
  181892. png_structp PNGAPI
  181893. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  181894. png_error_ptr error_fn, png_error_ptr warn_fn)
  181895. {
  181896. #ifdef PNG_USER_MEM_SUPPORTED
  181897. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  181898. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  181899. }
  181900. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  181901. png_structp PNGAPI
  181902. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  181903. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  181904. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  181905. {
  181906. #endif /* PNG_USER_MEM_SUPPORTED */
  181907. png_structp png_ptr;
  181908. #ifdef PNG_SETJMP_SUPPORTED
  181909. #ifdef USE_FAR_KEYWORD
  181910. jmp_buf jmpbuf;
  181911. #endif
  181912. #endif
  181913. int i;
  181914. png_debug(1, "in png_create_read_struct\n");
  181915. #ifdef PNG_USER_MEM_SUPPORTED
  181916. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  181917. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  181918. #else
  181919. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  181920. #endif
  181921. if (png_ptr == NULL)
  181922. return (NULL);
  181923. /* added at libpng-1.2.6 */
  181924. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  181925. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  181926. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  181927. #endif
  181928. #ifdef PNG_SETJMP_SUPPORTED
  181929. #ifdef USE_FAR_KEYWORD
  181930. if (setjmp(jmpbuf))
  181931. #else
  181932. if (setjmp(png_ptr->jmpbuf))
  181933. #endif
  181934. {
  181935. png_free(png_ptr, png_ptr->zbuf);
  181936. png_ptr->zbuf=NULL;
  181937. #ifdef PNG_USER_MEM_SUPPORTED
  181938. png_destroy_struct_2((png_voidp)png_ptr,
  181939. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  181940. #else
  181941. png_destroy_struct((png_voidp)png_ptr);
  181942. #endif
  181943. return (NULL);
  181944. }
  181945. #ifdef USE_FAR_KEYWORD
  181946. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  181947. #endif
  181948. #endif
  181949. #ifdef PNG_USER_MEM_SUPPORTED
  181950. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  181951. #endif
  181952. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  181953. i=0;
  181954. do
  181955. {
  181956. if(user_png_ver[i] != png_libpng_ver[i])
  181957. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  181958. } while (png_libpng_ver[i++]);
  181959. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  181960. {
  181961. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  181962. * we must recompile any applications that use any older library version.
  181963. * For versions after libpng 1.0, we will be compatible, so we need
  181964. * only check the first digit.
  181965. */
  181966. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  181967. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  181968. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  181969. {
  181970. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  181971. char msg[80];
  181972. if (user_png_ver)
  181973. {
  181974. png_snprintf(msg, 80,
  181975. "Application was compiled with png.h from libpng-%.20s",
  181976. user_png_ver);
  181977. png_warning(png_ptr, msg);
  181978. }
  181979. png_snprintf(msg, 80,
  181980. "Application is running with png.c from libpng-%.20s",
  181981. png_libpng_ver);
  181982. png_warning(png_ptr, msg);
  181983. #endif
  181984. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181985. png_ptr->flags=0;
  181986. #endif
  181987. png_error(png_ptr,
  181988. "Incompatible libpng version in application and library");
  181989. }
  181990. }
  181991. /* initialize zbuf - compression buffer */
  181992. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  181993. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  181994. (png_uint_32)png_ptr->zbuf_size);
  181995. png_ptr->zstream.zalloc = png_zalloc;
  181996. png_ptr->zstream.zfree = png_zfree;
  181997. png_ptr->zstream.opaque = (voidpf)png_ptr;
  181998. switch (inflateInit(&png_ptr->zstream))
  181999. {
  182000. case Z_OK: /* Do nothing */ break;
  182001. case Z_MEM_ERROR:
  182002. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  182003. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  182004. default: png_error(png_ptr, "Unknown zlib error");
  182005. }
  182006. png_ptr->zstream.next_out = png_ptr->zbuf;
  182007. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182008. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  182009. #ifdef PNG_SETJMP_SUPPORTED
  182010. /* Applications that neglect to set up their own setjmp() and then encounter
  182011. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  182012. abort instead of returning. */
  182013. #ifdef USE_FAR_KEYWORD
  182014. if (setjmp(jmpbuf))
  182015. PNG_ABORT();
  182016. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  182017. #else
  182018. if (setjmp(png_ptr->jmpbuf))
  182019. PNG_ABORT();
  182020. #endif
  182021. #endif
  182022. return (png_ptr);
  182023. }
  182024. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  182025. /* Initialize PNG structure for reading, and allocate any memory needed.
  182026. This interface is deprecated in favour of the png_create_read_struct(),
  182027. and it will disappear as of libpng-1.3.0. */
  182028. #undef png_read_init
  182029. void PNGAPI
  182030. png_read_init(png_structp png_ptr)
  182031. {
  182032. /* We only come here via pre-1.0.7-compiled applications */
  182033. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  182034. }
  182035. void PNGAPI
  182036. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  182037. png_size_t png_struct_size, png_size_t png_info_size)
  182038. {
  182039. /* We only come here via pre-1.0.12-compiled applications */
  182040. if(png_ptr == NULL) return;
  182041. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  182042. if(png_sizeof(png_struct) > png_struct_size ||
  182043. png_sizeof(png_info) > png_info_size)
  182044. {
  182045. char msg[80];
  182046. png_ptr->warning_fn=NULL;
  182047. if (user_png_ver)
  182048. {
  182049. png_snprintf(msg, 80,
  182050. "Application was compiled with png.h from libpng-%.20s",
  182051. user_png_ver);
  182052. png_warning(png_ptr, msg);
  182053. }
  182054. png_snprintf(msg, 80,
  182055. "Application is running with png.c from libpng-%.20s",
  182056. png_libpng_ver);
  182057. png_warning(png_ptr, msg);
  182058. }
  182059. #endif
  182060. if(png_sizeof(png_struct) > png_struct_size)
  182061. {
  182062. png_ptr->error_fn=NULL;
  182063. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182064. png_ptr->flags=0;
  182065. #endif
  182066. png_error(png_ptr,
  182067. "The png struct allocated by the application for reading is too small.");
  182068. }
  182069. if(png_sizeof(png_info) > png_info_size)
  182070. {
  182071. png_ptr->error_fn=NULL;
  182072. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182073. png_ptr->flags=0;
  182074. #endif
  182075. png_error(png_ptr,
  182076. "The info struct allocated by application for reading is too small.");
  182077. }
  182078. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  182079. }
  182080. #endif /* PNG_1_0_X || PNG_1_2_X */
  182081. void PNGAPI
  182082. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  182083. png_size_t png_struct_size)
  182084. {
  182085. #ifdef PNG_SETJMP_SUPPORTED
  182086. jmp_buf tmp_jmp; /* to save current jump buffer */
  182087. #endif
  182088. int i=0;
  182089. png_structp png_ptr=*ptr_ptr;
  182090. if(png_ptr == NULL) return;
  182091. do
  182092. {
  182093. if(user_png_ver[i] != png_libpng_ver[i])
  182094. {
  182095. #ifdef PNG_LEGACY_SUPPORTED
  182096. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  182097. #else
  182098. png_ptr->warning_fn=NULL;
  182099. png_warning(png_ptr,
  182100. "Application uses deprecated png_read_init() and should be recompiled.");
  182101. break;
  182102. #endif
  182103. }
  182104. } while (png_libpng_ver[i++]);
  182105. png_debug(1, "in png_read_init_3\n");
  182106. #ifdef PNG_SETJMP_SUPPORTED
  182107. /* save jump buffer and error functions */
  182108. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  182109. #endif
  182110. if(png_sizeof(png_struct) > png_struct_size)
  182111. {
  182112. png_destroy_struct(png_ptr);
  182113. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  182114. png_ptr = *ptr_ptr;
  182115. }
  182116. /* reset all variables to 0 */
  182117. png_memset(png_ptr, 0, png_sizeof (png_struct));
  182118. #ifdef PNG_SETJMP_SUPPORTED
  182119. /* restore jump buffer */
  182120. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  182121. #endif
  182122. /* added at libpng-1.2.6 */
  182123. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182124. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  182125. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  182126. #endif
  182127. /* initialize zbuf - compression buffer */
  182128. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  182129. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  182130. (png_uint_32)png_ptr->zbuf_size);
  182131. png_ptr->zstream.zalloc = png_zalloc;
  182132. png_ptr->zstream.zfree = png_zfree;
  182133. png_ptr->zstream.opaque = (voidpf)png_ptr;
  182134. switch (inflateInit(&png_ptr->zstream))
  182135. {
  182136. case Z_OK: /* Do nothing */ break;
  182137. case Z_MEM_ERROR:
  182138. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  182139. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  182140. default: png_error(png_ptr, "Unknown zlib error");
  182141. }
  182142. png_ptr->zstream.next_out = png_ptr->zbuf;
  182143. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182144. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  182145. }
  182146. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182147. /* Read the information before the actual image data. This has been
  182148. * changed in v0.90 to allow reading a file that already has the magic
  182149. * bytes read from the stream. You can tell libpng how many bytes have
  182150. * been read from the beginning of the stream (up to the maximum of 8)
  182151. * via png_set_sig_bytes(), and we will only check the remaining bytes
  182152. * here. The application can then have access to the signature bytes we
  182153. * read if it is determined that this isn't a valid PNG file.
  182154. */
  182155. void PNGAPI
  182156. png_read_info(png_structp png_ptr, png_infop info_ptr)
  182157. {
  182158. if(png_ptr == NULL) return;
  182159. png_debug(1, "in png_read_info\n");
  182160. /* If we haven't checked all of the PNG signature bytes, do so now. */
  182161. if (png_ptr->sig_bytes < 8)
  182162. {
  182163. png_size_t num_checked = png_ptr->sig_bytes,
  182164. num_to_check = 8 - num_checked;
  182165. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  182166. png_ptr->sig_bytes = 8;
  182167. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  182168. {
  182169. if (num_checked < 4 &&
  182170. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  182171. png_error(png_ptr, "Not a PNG file");
  182172. else
  182173. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  182174. }
  182175. if (num_checked < 3)
  182176. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  182177. }
  182178. for(;;)
  182179. {
  182180. #ifdef PNG_USE_LOCAL_ARRAYS
  182181. PNG_CONST PNG_IHDR;
  182182. PNG_CONST PNG_IDAT;
  182183. PNG_CONST PNG_IEND;
  182184. PNG_CONST PNG_PLTE;
  182185. #if defined(PNG_READ_bKGD_SUPPORTED)
  182186. PNG_CONST PNG_bKGD;
  182187. #endif
  182188. #if defined(PNG_READ_cHRM_SUPPORTED)
  182189. PNG_CONST PNG_cHRM;
  182190. #endif
  182191. #if defined(PNG_READ_gAMA_SUPPORTED)
  182192. PNG_CONST PNG_gAMA;
  182193. #endif
  182194. #if defined(PNG_READ_hIST_SUPPORTED)
  182195. PNG_CONST PNG_hIST;
  182196. #endif
  182197. #if defined(PNG_READ_iCCP_SUPPORTED)
  182198. PNG_CONST PNG_iCCP;
  182199. #endif
  182200. #if defined(PNG_READ_iTXt_SUPPORTED)
  182201. PNG_CONST PNG_iTXt;
  182202. #endif
  182203. #if defined(PNG_READ_oFFs_SUPPORTED)
  182204. PNG_CONST PNG_oFFs;
  182205. #endif
  182206. #if defined(PNG_READ_pCAL_SUPPORTED)
  182207. PNG_CONST PNG_pCAL;
  182208. #endif
  182209. #if defined(PNG_READ_pHYs_SUPPORTED)
  182210. PNG_CONST PNG_pHYs;
  182211. #endif
  182212. #if defined(PNG_READ_sBIT_SUPPORTED)
  182213. PNG_CONST PNG_sBIT;
  182214. #endif
  182215. #if defined(PNG_READ_sCAL_SUPPORTED)
  182216. PNG_CONST PNG_sCAL;
  182217. #endif
  182218. #if defined(PNG_READ_sPLT_SUPPORTED)
  182219. PNG_CONST PNG_sPLT;
  182220. #endif
  182221. #if defined(PNG_READ_sRGB_SUPPORTED)
  182222. PNG_CONST PNG_sRGB;
  182223. #endif
  182224. #if defined(PNG_READ_tEXt_SUPPORTED)
  182225. PNG_CONST PNG_tEXt;
  182226. #endif
  182227. #if defined(PNG_READ_tIME_SUPPORTED)
  182228. PNG_CONST PNG_tIME;
  182229. #endif
  182230. #if defined(PNG_READ_tRNS_SUPPORTED)
  182231. PNG_CONST PNG_tRNS;
  182232. #endif
  182233. #if defined(PNG_READ_zTXt_SUPPORTED)
  182234. PNG_CONST PNG_zTXt;
  182235. #endif
  182236. #endif /* PNG_USE_LOCAL_ARRAYS */
  182237. png_byte chunk_length[4];
  182238. png_uint_32 length;
  182239. png_read_data(png_ptr, chunk_length, 4);
  182240. length = png_get_uint_31(png_ptr,chunk_length);
  182241. png_reset_crc(png_ptr);
  182242. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182243. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  182244. length);
  182245. /* This should be a binary subdivision search or a hash for
  182246. * matching the chunk name rather than a linear search.
  182247. */
  182248. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182249. if(png_ptr->mode & PNG_AFTER_IDAT)
  182250. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  182251. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  182252. png_handle_IHDR(png_ptr, info_ptr, length);
  182253. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  182254. png_handle_IEND(png_ptr, info_ptr, length);
  182255. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182256. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  182257. {
  182258. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182259. png_ptr->mode |= PNG_HAVE_IDAT;
  182260. png_handle_unknown(png_ptr, info_ptr, length);
  182261. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182262. png_ptr->mode |= PNG_HAVE_PLTE;
  182263. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182264. {
  182265. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  182266. png_error(png_ptr, "Missing IHDR before IDAT");
  182267. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  182268. !(png_ptr->mode & PNG_HAVE_PLTE))
  182269. png_error(png_ptr, "Missing PLTE before IDAT");
  182270. break;
  182271. }
  182272. }
  182273. #endif
  182274. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182275. png_handle_PLTE(png_ptr, info_ptr, length);
  182276. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182277. {
  182278. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  182279. png_error(png_ptr, "Missing IHDR before IDAT");
  182280. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  182281. !(png_ptr->mode & PNG_HAVE_PLTE))
  182282. png_error(png_ptr, "Missing PLTE before IDAT");
  182283. png_ptr->idat_size = length;
  182284. png_ptr->mode |= PNG_HAVE_IDAT;
  182285. break;
  182286. }
  182287. #if defined(PNG_READ_bKGD_SUPPORTED)
  182288. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  182289. png_handle_bKGD(png_ptr, info_ptr, length);
  182290. #endif
  182291. #if defined(PNG_READ_cHRM_SUPPORTED)
  182292. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  182293. png_handle_cHRM(png_ptr, info_ptr, length);
  182294. #endif
  182295. #if defined(PNG_READ_gAMA_SUPPORTED)
  182296. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  182297. png_handle_gAMA(png_ptr, info_ptr, length);
  182298. #endif
  182299. #if defined(PNG_READ_hIST_SUPPORTED)
  182300. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  182301. png_handle_hIST(png_ptr, info_ptr, length);
  182302. #endif
  182303. #if defined(PNG_READ_oFFs_SUPPORTED)
  182304. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  182305. png_handle_oFFs(png_ptr, info_ptr, length);
  182306. #endif
  182307. #if defined(PNG_READ_pCAL_SUPPORTED)
  182308. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  182309. png_handle_pCAL(png_ptr, info_ptr, length);
  182310. #endif
  182311. #if defined(PNG_READ_sCAL_SUPPORTED)
  182312. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  182313. png_handle_sCAL(png_ptr, info_ptr, length);
  182314. #endif
  182315. #if defined(PNG_READ_pHYs_SUPPORTED)
  182316. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  182317. png_handle_pHYs(png_ptr, info_ptr, length);
  182318. #endif
  182319. #if defined(PNG_READ_sBIT_SUPPORTED)
  182320. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  182321. png_handle_sBIT(png_ptr, info_ptr, length);
  182322. #endif
  182323. #if defined(PNG_READ_sRGB_SUPPORTED)
  182324. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  182325. png_handle_sRGB(png_ptr, info_ptr, length);
  182326. #endif
  182327. #if defined(PNG_READ_iCCP_SUPPORTED)
  182328. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  182329. png_handle_iCCP(png_ptr, info_ptr, length);
  182330. #endif
  182331. #if defined(PNG_READ_sPLT_SUPPORTED)
  182332. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  182333. png_handle_sPLT(png_ptr, info_ptr, length);
  182334. #endif
  182335. #if defined(PNG_READ_tEXt_SUPPORTED)
  182336. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  182337. png_handle_tEXt(png_ptr, info_ptr, length);
  182338. #endif
  182339. #if defined(PNG_READ_tIME_SUPPORTED)
  182340. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  182341. png_handle_tIME(png_ptr, info_ptr, length);
  182342. #endif
  182343. #if defined(PNG_READ_tRNS_SUPPORTED)
  182344. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  182345. png_handle_tRNS(png_ptr, info_ptr, length);
  182346. #endif
  182347. #if defined(PNG_READ_zTXt_SUPPORTED)
  182348. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  182349. png_handle_zTXt(png_ptr, info_ptr, length);
  182350. #endif
  182351. #if defined(PNG_READ_iTXt_SUPPORTED)
  182352. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  182353. png_handle_iTXt(png_ptr, info_ptr, length);
  182354. #endif
  182355. else
  182356. png_handle_unknown(png_ptr, info_ptr, length);
  182357. }
  182358. }
  182359. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182360. /* optional call to update the users info_ptr structure */
  182361. void PNGAPI
  182362. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  182363. {
  182364. png_debug(1, "in png_read_update_info\n");
  182365. if(png_ptr == NULL) return;
  182366. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  182367. png_read_start_row(png_ptr);
  182368. else
  182369. png_warning(png_ptr,
  182370. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  182371. png_read_transform_info(png_ptr, info_ptr);
  182372. }
  182373. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182374. /* Initialize palette, background, etc, after transformations
  182375. * are set, but before any reading takes place. This allows
  182376. * the user to obtain a gamma-corrected palette, for example.
  182377. * If the user doesn't call this, we will do it ourselves.
  182378. */
  182379. void PNGAPI
  182380. png_start_read_image(png_structp png_ptr)
  182381. {
  182382. png_debug(1, "in png_start_read_image\n");
  182383. if(png_ptr == NULL) return;
  182384. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  182385. png_read_start_row(png_ptr);
  182386. }
  182387. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182388. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182389. void PNGAPI
  182390. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  182391. {
  182392. #ifdef PNG_USE_LOCAL_ARRAYS
  182393. PNG_CONST PNG_IDAT;
  182394. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  182395. 0xff};
  182396. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  182397. #endif
  182398. int ret;
  182399. if(png_ptr == NULL) return;
  182400. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  182401. png_ptr->row_number, png_ptr->pass);
  182402. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  182403. png_read_start_row(png_ptr);
  182404. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  182405. {
  182406. /* check for transforms that have been set but were defined out */
  182407. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  182408. if (png_ptr->transformations & PNG_INVERT_MONO)
  182409. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  182410. #endif
  182411. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  182412. if (png_ptr->transformations & PNG_FILLER)
  182413. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  182414. #endif
  182415. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  182416. if (png_ptr->transformations & PNG_PACKSWAP)
  182417. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  182418. #endif
  182419. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  182420. if (png_ptr->transformations & PNG_PACK)
  182421. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  182422. #endif
  182423. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  182424. if (png_ptr->transformations & PNG_SHIFT)
  182425. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  182426. #endif
  182427. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  182428. if (png_ptr->transformations & PNG_BGR)
  182429. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  182430. #endif
  182431. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  182432. if (png_ptr->transformations & PNG_SWAP_BYTES)
  182433. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  182434. #endif
  182435. }
  182436. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  182437. /* if interlaced and we do not need a new row, combine row and return */
  182438. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  182439. {
  182440. switch (png_ptr->pass)
  182441. {
  182442. case 0:
  182443. if (png_ptr->row_number & 0x07)
  182444. {
  182445. if (dsp_row != NULL)
  182446. png_combine_row(png_ptr, dsp_row,
  182447. png_pass_dsp_mask[png_ptr->pass]);
  182448. png_read_finish_row(png_ptr);
  182449. return;
  182450. }
  182451. break;
  182452. case 1:
  182453. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  182454. {
  182455. if (dsp_row != NULL)
  182456. png_combine_row(png_ptr, dsp_row,
  182457. png_pass_dsp_mask[png_ptr->pass]);
  182458. png_read_finish_row(png_ptr);
  182459. return;
  182460. }
  182461. break;
  182462. case 2:
  182463. if ((png_ptr->row_number & 0x07) != 4)
  182464. {
  182465. if (dsp_row != NULL && (png_ptr->row_number & 4))
  182466. png_combine_row(png_ptr, dsp_row,
  182467. png_pass_dsp_mask[png_ptr->pass]);
  182468. png_read_finish_row(png_ptr);
  182469. return;
  182470. }
  182471. break;
  182472. case 3:
  182473. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  182474. {
  182475. if (dsp_row != NULL)
  182476. png_combine_row(png_ptr, dsp_row,
  182477. png_pass_dsp_mask[png_ptr->pass]);
  182478. png_read_finish_row(png_ptr);
  182479. return;
  182480. }
  182481. break;
  182482. case 4:
  182483. if ((png_ptr->row_number & 3) != 2)
  182484. {
  182485. if (dsp_row != NULL && (png_ptr->row_number & 2))
  182486. png_combine_row(png_ptr, dsp_row,
  182487. png_pass_dsp_mask[png_ptr->pass]);
  182488. png_read_finish_row(png_ptr);
  182489. return;
  182490. }
  182491. break;
  182492. case 5:
  182493. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  182494. {
  182495. if (dsp_row != NULL)
  182496. png_combine_row(png_ptr, dsp_row,
  182497. png_pass_dsp_mask[png_ptr->pass]);
  182498. png_read_finish_row(png_ptr);
  182499. return;
  182500. }
  182501. break;
  182502. case 6:
  182503. if (!(png_ptr->row_number & 1))
  182504. {
  182505. png_read_finish_row(png_ptr);
  182506. return;
  182507. }
  182508. break;
  182509. }
  182510. }
  182511. #endif
  182512. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  182513. png_error(png_ptr, "Invalid attempt to read row data");
  182514. png_ptr->zstream.next_out = png_ptr->row_buf;
  182515. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  182516. do
  182517. {
  182518. if (!(png_ptr->zstream.avail_in))
  182519. {
  182520. while (!png_ptr->idat_size)
  182521. {
  182522. png_byte chunk_length[4];
  182523. png_crc_finish(png_ptr, 0);
  182524. png_read_data(png_ptr, chunk_length, 4);
  182525. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  182526. png_reset_crc(png_ptr);
  182527. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182528. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182529. png_error(png_ptr, "Not enough image data");
  182530. }
  182531. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  182532. png_ptr->zstream.next_in = png_ptr->zbuf;
  182533. if (png_ptr->zbuf_size > png_ptr->idat_size)
  182534. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  182535. png_crc_read(png_ptr, png_ptr->zbuf,
  182536. (png_size_t)png_ptr->zstream.avail_in);
  182537. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  182538. }
  182539. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  182540. if (ret == Z_STREAM_END)
  182541. {
  182542. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  182543. png_ptr->idat_size)
  182544. png_error(png_ptr, "Extra compressed data");
  182545. png_ptr->mode |= PNG_AFTER_IDAT;
  182546. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  182547. break;
  182548. }
  182549. if (ret != Z_OK)
  182550. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  182551. "Decompression error");
  182552. } while (png_ptr->zstream.avail_out);
  182553. png_ptr->row_info.color_type = png_ptr->color_type;
  182554. png_ptr->row_info.width = png_ptr->iwidth;
  182555. png_ptr->row_info.channels = png_ptr->channels;
  182556. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  182557. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  182558. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  182559. png_ptr->row_info.width);
  182560. if(png_ptr->row_buf[0])
  182561. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  182562. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  182563. (int)(png_ptr->row_buf[0]));
  182564. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  182565. png_ptr->rowbytes + 1);
  182566. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182567. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  182568. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  182569. {
  182570. /* Intrapixel differencing */
  182571. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  182572. }
  182573. #endif
  182574. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  182575. png_do_read_transformations(png_ptr);
  182576. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  182577. /* blow up interlaced rows to full size */
  182578. if (png_ptr->interlaced &&
  182579. (png_ptr->transformations & PNG_INTERLACE))
  182580. {
  182581. if (png_ptr->pass < 6)
  182582. /* old interface (pre-1.0.9):
  182583. png_do_read_interlace(&(png_ptr->row_info),
  182584. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  182585. */
  182586. png_do_read_interlace(png_ptr);
  182587. if (dsp_row != NULL)
  182588. png_combine_row(png_ptr, dsp_row,
  182589. png_pass_dsp_mask[png_ptr->pass]);
  182590. if (row != NULL)
  182591. png_combine_row(png_ptr, row,
  182592. png_pass_mask[png_ptr->pass]);
  182593. }
  182594. else
  182595. #endif
  182596. {
  182597. if (row != NULL)
  182598. png_combine_row(png_ptr, row, 0xff);
  182599. if (dsp_row != NULL)
  182600. png_combine_row(png_ptr, dsp_row, 0xff);
  182601. }
  182602. png_read_finish_row(png_ptr);
  182603. if (png_ptr->read_row_fn != NULL)
  182604. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  182605. }
  182606. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182607. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182608. /* Read one or more rows of image data. If the image is interlaced,
  182609. * and png_set_interlace_handling() has been called, the rows need to
  182610. * contain the contents of the rows from the previous pass. If the
  182611. * image has alpha or transparency, and png_handle_alpha()[*] has been
  182612. * called, the rows contents must be initialized to the contents of the
  182613. * screen.
  182614. *
  182615. * "row" holds the actual image, and pixels are placed in it
  182616. * as they arrive. If the image is displayed after each pass, it will
  182617. * appear to "sparkle" in. "display_row" can be used to display a
  182618. * "chunky" progressive image, with finer detail added as it becomes
  182619. * available. If you do not want this "chunky" display, you may pass
  182620. * NULL for display_row. If you do not want the sparkle display, and
  182621. * you have not called png_handle_alpha(), you may pass NULL for rows.
  182622. * If you have called png_handle_alpha(), and the image has either an
  182623. * alpha channel or a transparency chunk, you must provide a buffer for
  182624. * rows. In this case, you do not have to provide a display_row buffer
  182625. * also, but you may. If the image is not interlaced, or if you have
  182626. * not called png_set_interlace_handling(), the display_row buffer will
  182627. * be ignored, so pass NULL to it.
  182628. *
  182629. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  182630. */
  182631. void PNGAPI
  182632. png_read_rows(png_structp png_ptr, png_bytepp row,
  182633. png_bytepp display_row, png_uint_32 num_rows)
  182634. {
  182635. png_uint_32 i;
  182636. png_bytepp rp;
  182637. png_bytepp dp;
  182638. png_debug(1, "in png_read_rows\n");
  182639. if(png_ptr == NULL) return;
  182640. rp = row;
  182641. dp = display_row;
  182642. if (rp != NULL && dp != NULL)
  182643. for (i = 0; i < num_rows; i++)
  182644. {
  182645. png_bytep rptr = *rp++;
  182646. png_bytep dptr = *dp++;
  182647. png_read_row(png_ptr, rptr, dptr);
  182648. }
  182649. else if(rp != NULL)
  182650. for (i = 0; i < num_rows; i++)
  182651. {
  182652. png_bytep rptr = *rp;
  182653. png_read_row(png_ptr, rptr, png_bytep_NULL);
  182654. rp++;
  182655. }
  182656. else if(dp != NULL)
  182657. for (i = 0; i < num_rows; i++)
  182658. {
  182659. png_bytep dptr = *dp;
  182660. png_read_row(png_ptr, png_bytep_NULL, dptr);
  182661. dp++;
  182662. }
  182663. }
  182664. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182665. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182666. /* Read the entire image. If the image has an alpha channel or a tRNS
  182667. * chunk, and you have called png_handle_alpha()[*], you will need to
  182668. * initialize the image to the current image that PNG will be overlaying.
  182669. * We set the num_rows again here, in case it was incorrectly set in
  182670. * png_read_start_row() by a call to png_read_update_info() or
  182671. * png_start_read_image() if png_set_interlace_handling() wasn't called
  182672. * prior to either of these functions like it should have been. You can
  182673. * only call this function once. If you desire to have an image for
  182674. * each pass of a interlaced image, use png_read_rows() instead.
  182675. *
  182676. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  182677. */
  182678. void PNGAPI
  182679. png_read_image(png_structp png_ptr, png_bytepp image)
  182680. {
  182681. png_uint_32 i,image_height;
  182682. int pass, j;
  182683. png_bytepp rp;
  182684. png_debug(1, "in png_read_image\n");
  182685. if(png_ptr == NULL) return;
  182686. #ifdef PNG_READ_INTERLACING_SUPPORTED
  182687. pass = png_set_interlace_handling(png_ptr);
  182688. #else
  182689. if (png_ptr->interlaced)
  182690. png_error(png_ptr,
  182691. "Cannot read interlaced image -- interlace handler disabled.");
  182692. pass = 1;
  182693. #endif
  182694. image_height=png_ptr->height;
  182695. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  182696. for (j = 0; j < pass; j++)
  182697. {
  182698. rp = image;
  182699. for (i = 0; i < image_height; i++)
  182700. {
  182701. png_read_row(png_ptr, *rp, png_bytep_NULL);
  182702. rp++;
  182703. }
  182704. }
  182705. }
  182706. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182707. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182708. /* Read the end of the PNG file. Will not read past the end of the
  182709. * file, will verify the end is accurate, and will read any comments
  182710. * or time information at the end of the file, if info is not NULL.
  182711. */
  182712. void PNGAPI
  182713. png_read_end(png_structp png_ptr, png_infop info_ptr)
  182714. {
  182715. png_byte chunk_length[4];
  182716. png_uint_32 length;
  182717. png_debug(1, "in png_read_end\n");
  182718. if(png_ptr == NULL) return;
  182719. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  182720. do
  182721. {
  182722. #ifdef PNG_USE_LOCAL_ARRAYS
  182723. PNG_CONST PNG_IHDR;
  182724. PNG_CONST PNG_IDAT;
  182725. PNG_CONST PNG_IEND;
  182726. PNG_CONST PNG_PLTE;
  182727. #if defined(PNG_READ_bKGD_SUPPORTED)
  182728. PNG_CONST PNG_bKGD;
  182729. #endif
  182730. #if defined(PNG_READ_cHRM_SUPPORTED)
  182731. PNG_CONST PNG_cHRM;
  182732. #endif
  182733. #if defined(PNG_READ_gAMA_SUPPORTED)
  182734. PNG_CONST PNG_gAMA;
  182735. #endif
  182736. #if defined(PNG_READ_hIST_SUPPORTED)
  182737. PNG_CONST PNG_hIST;
  182738. #endif
  182739. #if defined(PNG_READ_iCCP_SUPPORTED)
  182740. PNG_CONST PNG_iCCP;
  182741. #endif
  182742. #if defined(PNG_READ_iTXt_SUPPORTED)
  182743. PNG_CONST PNG_iTXt;
  182744. #endif
  182745. #if defined(PNG_READ_oFFs_SUPPORTED)
  182746. PNG_CONST PNG_oFFs;
  182747. #endif
  182748. #if defined(PNG_READ_pCAL_SUPPORTED)
  182749. PNG_CONST PNG_pCAL;
  182750. #endif
  182751. #if defined(PNG_READ_pHYs_SUPPORTED)
  182752. PNG_CONST PNG_pHYs;
  182753. #endif
  182754. #if defined(PNG_READ_sBIT_SUPPORTED)
  182755. PNG_CONST PNG_sBIT;
  182756. #endif
  182757. #if defined(PNG_READ_sCAL_SUPPORTED)
  182758. PNG_CONST PNG_sCAL;
  182759. #endif
  182760. #if defined(PNG_READ_sPLT_SUPPORTED)
  182761. PNG_CONST PNG_sPLT;
  182762. #endif
  182763. #if defined(PNG_READ_sRGB_SUPPORTED)
  182764. PNG_CONST PNG_sRGB;
  182765. #endif
  182766. #if defined(PNG_READ_tEXt_SUPPORTED)
  182767. PNG_CONST PNG_tEXt;
  182768. #endif
  182769. #if defined(PNG_READ_tIME_SUPPORTED)
  182770. PNG_CONST PNG_tIME;
  182771. #endif
  182772. #if defined(PNG_READ_tRNS_SUPPORTED)
  182773. PNG_CONST PNG_tRNS;
  182774. #endif
  182775. #if defined(PNG_READ_zTXt_SUPPORTED)
  182776. PNG_CONST PNG_zTXt;
  182777. #endif
  182778. #endif /* PNG_USE_LOCAL_ARRAYS */
  182779. png_read_data(png_ptr, chunk_length, 4);
  182780. length = png_get_uint_31(png_ptr,chunk_length);
  182781. png_reset_crc(png_ptr);
  182782. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182783. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  182784. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  182785. png_handle_IHDR(png_ptr, info_ptr, length);
  182786. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  182787. png_handle_IEND(png_ptr, info_ptr, length);
  182788. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182789. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  182790. {
  182791. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182792. {
  182793. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  182794. png_error(png_ptr, "Too many IDAT's found");
  182795. }
  182796. png_handle_unknown(png_ptr, info_ptr, length);
  182797. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182798. png_ptr->mode |= PNG_HAVE_PLTE;
  182799. }
  182800. #endif
  182801. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182802. {
  182803. /* Zero length IDATs are legal after the last IDAT has been
  182804. * read, but not after other chunks have been read.
  182805. */
  182806. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  182807. png_error(png_ptr, "Too many IDAT's found");
  182808. png_crc_finish(png_ptr, length);
  182809. }
  182810. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182811. png_handle_PLTE(png_ptr, info_ptr, length);
  182812. #if defined(PNG_READ_bKGD_SUPPORTED)
  182813. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  182814. png_handle_bKGD(png_ptr, info_ptr, length);
  182815. #endif
  182816. #if defined(PNG_READ_cHRM_SUPPORTED)
  182817. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  182818. png_handle_cHRM(png_ptr, info_ptr, length);
  182819. #endif
  182820. #if defined(PNG_READ_gAMA_SUPPORTED)
  182821. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  182822. png_handle_gAMA(png_ptr, info_ptr, length);
  182823. #endif
  182824. #if defined(PNG_READ_hIST_SUPPORTED)
  182825. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  182826. png_handle_hIST(png_ptr, info_ptr, length);
  182827. #endif
  182828. #if defined(PNG_READ_oFFs_SUPPORTED)
  182829. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  182830. png_handle_oFFs(png_ptr, info_ptr, length);
  182831. #endif
  182832. #if defined(PNG_READ_pCAL_SUPPORTED)
  182833. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  182834. png_handle_pCAL(png_ptr, info_ptr, length);
  182835. #endif
  182836. #if defined(PNG_READ_sCAL_SUPPORTED)
  182837. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  182838. png_handle_sCAL(png_ptr, info_ptr, length);
  182839. #endif
  182840. #if defined(PNG_READ_pHYs_SUPPORTED)
  182841. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  182842. png_handle_pHYs(png_ptr, info_ptr, length);
  182843. #endif
  182844. #if defined(PNG_READ_sBIT_SUPPORTED)
  182845. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  182846. png_handle_sBIT(png_ptr, info_ptr, length);
  182847. #endif
  182848. #if defined(PNG_READ_sRGB_SUPPORTED)
  182849. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  182850. png_handle_sRGB(png_ptr, info_ptr, length);
  182851. #endif
  182852. #if defined(PNG_READ_iCCP_SUPPORTED)
  182853. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  182854. png_handle_iCCP(png_ptr, info_ptr, length);
  182855. #endif
  182856. #if defined(PNG_READ_sPLT_SUPPORTED)
  182857. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  182858. png_handle_sPLT(png_ptr, info_ptr, length);
  182859. #endif
  182860. #if defined(PNG_READ_tEXt_SUPPORTED)
  182861. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  182862. png_handle_tEXt(png_ptr, info_ptr, length);
  182863. #endif
  182864. #if defined(PNG_READ_tIME_SUPPORTED)
  182865. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  182866. png_handle_tIME(png_ptr, info_ptr, length);
  182867. #endif
  182868. #if defined(PNG_READ_tRNS_SUPPORTED)
  182869. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  182870. png_handle_tRNS(png_ptr, info_ptr, length);
  182871. #endif
  182872. #if defined(PNG_READ_zTXt_SUPPORTED)
  182873. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  182874. png_handle_zTXt(png_ptr, info_ptr, length);
  182875. #endif
  182876. #if defined(PNG_READ_iTXt_SUPPORTED)
  182877. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  182878. png_handle_iTXt(png_ptr, info_ptr, length);
  182879. #endif
  182880. else
  182881. png_handle_unknown(png_ptr, info_ptr, length);
  182882. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  182883. }
  182884. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182885. /* free all memory used by the read */
  182886. void PNGAPI
  182887. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  182888. png_infopp end_info_ptr_ptr)
  182889. {
  182890. png_structp png_ptr = NULL;
  182891. png_infop info_ptr = NULL, end_info_ptr = NULL;
  182892. #ifdef PNG_USER_MEM_SUPPORTED
  182893. png_free_ptr free_fn;
  182894. png_voidp mem_ptr;
  182895. #endif
  182896. png_debug(1, "in png_destroy_read_struct\n");
  182897. if (png_ptr_ptr != NULL)
  182898. png_ptr = *png_ptr_ptr;
  182899. if (info_ptr_ptr != NULL)
  182900. info_ptr = *info_ptr_ptr;
  182901. if (end_info_ptr_ptr != NULL)
  182902. end_info_ptr = *end_info_ptr_ptr;
  182903. #ifdef PNG_USER_MEM_SUPPORTED
  182904. free_fn = png_ptr->free_fn;
  182905. mem_ptr = png_ptr->mem_ptr;
  182906. #endif
  182907. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  182908. if (info_ptr != NULL)
  182909. {
  182910. #if defined(PNG_TEXT_SUPPORTED)
  182911. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  182912. #endif
  182913. #ifdef PNG_USER_MEM_SUPPORTED
  182914. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  182915. (png_voidp)mem_ptr);
  182916. #else
  182917. png_destroy_struct((png_voidp)info_ptr);
  182918. #endif
  182919. *info_ptr_ptr = NULL;
  182920. }
  182921. if (end_info_ptr != NULL)
  182922. {
  182923. #if defined(PNG_READ_TEXT_SUPPORTED)
  182924. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  182925. #endif
  182926. #ifdef PNG_USER_MEM_SUPPORTED
  182927. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  182928. (png_voidp)mem_ptr);
  182929. #else
  182930. png_destroy_struct((png_voidp)end_info_ptr);
  182931. #endif
  182932. *end_info_ptr_ptr = NULL;
  182933. }
  182934. if (png_ptr != NULL)
  182935. {
  182936. #ifdef PNG_USER_MEM_SUPPORTED
  182937. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  182938. (png_voidp)mem_ptr);
  182939. #else
  182940. png_destroy_struct((png_voidp)png_ptr);
  182941. #endif
  182942. *png_ptr_ptr = NULL;
  182943. }
  182944. }
  182945. /* free all memory used by the read (old method) */
  182946. void /* PRIVATE */
  182947. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  182948. {
  182949. #ifdef PNG_SETJMP_SUPPORTED
  182950. jmp_buf tmp_jmp;
  182951. #endif
  182952. png_error_ptr error_fn;
  182953. png_error_ptr warning_fn;
  182954. png_voidp error_ptr;
  182955. #ifdef PNG_USER_MEM_SUPPORTED
  182956. png_free_ptr free_fn;
  182957. #endif
  182958. png_debug(1, "in png_read_destroy\n");
  182959. if (info_ptr != NULL)
  182960. png_info_destroy(png_ptr, info_ptr);
  182961. if (end_info_ptr != NULL)
  182962. png_info_destroy(png_ptr, end_info_ptr);
  182963. png_free(png_ptr, png_ptr->zbuf);
  182964. png_free(png_ptr, png_ptr->big_row_buf);
  182965. png_free(png_ptr, png_ptr->prev_row);
  182966. #if defined(PNG_READ_DITHER_SUPPORTED)
  182967. png_free(png_ptr, png_ptr->palette_lookup);
  182968. png_free(png_ptr, png_ptr->dither_index);
  182969. #endif
  182970. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182971. png_free(png_ptr, png_ptr->gamma_table);
  182972. #endif
  182973. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182974. png_free(png_ptr, png_ptr->gamma_from_1);
  182975. png_free(png_ptr, png_ptr->gamma_to_1);
  182976. #endif
  182977. #ifdef PNG_FREE_ME_SUPPORTED
  182978. if (png_ptr->free_me & PNG_FREE_PLTE)
  182979. png_zfree(png_ptr, png_ptr->palette);
  182980. png_ptr->free_me &= ~PNG_FREE_PLTE;
  182981. #else
  182982. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  182983. png_zfree(png_ptr, png_ptr->palette);
  182984. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  182985. #endif
  182986. #if defined(PNG_tRNS_SUPPORTED) || \
  182987. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182988. #ifdef PNG_FREE_ME_SUPPORTED
  182989. if (png_ptr->free_me & PNG_FREE_TRNS)
  182990. png_free(png_ptr, png_ptr->trans);
  182991. png_ptr->free_me &= ~PNG_FREE_TRNS;
  182992. #else
  182993. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  182994. png_free(png_ptr, png_ptr->trans);
  182995. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  182996. #endif
  182997. #endif
  182998. #if defined(PNG_READ_hIST_SUPPORTED)
  182999. #ifdef PNG_FREE_ME_SUPPORTED
  183000. if (png_ptr->free_me & PNG_FREE_HIST)
  183001. png_free(png_ptr, png_ptr->hist);
  183002. png_ptr->free_me &= ~PNG_FREE_HIST;
  183003. #else
  183004. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  183005. png_free(png_ptr, png_ptr->hist);
  183006. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  183007. #endif
  183008. #endif
  183009. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183010. if (png_ptr->gamma_16_table != NULL)
  183011. {
  183012. int i;
  183013. int istop = (1 << (8 - png_ptr->gamma_shift));
  183014. for (i = 0; i < istop; i++)
  183015. {
  183016. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  183017. }
  183018. png_free(png_ptr, png_ptr->gamma_16_table);
  183019. }
  183020. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183021. if (png_ptr->gamma_16_from_1 != NULL)
  183022. {
  183023. int i;
  183024. int istop = (1 << (8 - png_ptr->gamma_shift));
  183025. for (i = 0; i < istop; i++)
  183026. {
  183027. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  183028. }
  183029. png_free(png_ptr, png_ptr->gamma_16_from_1);
  183030. }
  183031. if (png_ptr->gamma_16_to_1 != NULL)
  183032. {
  183033. int i;
  183034. int istop = (1 << (8 - png_ptr->gamma_shift));
  183035. for (i = 0; i < istop; i++)
  183036. {
  183037. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  183038. }
  183039. png_free(png_ptr, png_ptr->gamma_16_to_1);
  183040. }
  183041. #endif
  183042. #endif
  183043. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183044. png_free(png_ptr, png_ptr->time_buffer);
  183045. #endif
  183046. inflateEnd(&png_ptr->zstream);
  183047. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183048. png_free(png_ptr, png_ptr->save_buffer);
  183049. #endif
  183050. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183051. #ifdef PNG_TEXT_SUPPORTED
  183052. png_free(png_ptr, png_ptr->current_text);
  183053. #endif /* PNG_TEXT_SUPPORTED */
  183054. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183055. /* Save the important info out of the png_struct, in case it is
  183056. * being used again.
  183057. */
  183058. #ifdef PNG_SETJMP_SUPPORTED
  183059. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  183060. #endif
  183061. error_fn = png_ptr->error_fn;
  183062. warning_fn = png_ptr->warning_fn;
  183063. error_ptr = png_ptr->error_ptr;
  183064. #ifdef PNG_USER_MEM_SUPPORTED
  183065. free_fn = png_ptr->free_fn;
  183066. #endif
  183067. png_memset(png_ptr, 0, png_sizeof (png_struct));
  183068. png_ptr->error_fn = error_fn;
  183069. png_ptr->warning_fn = warning_fn;
  183070. png_ptr->error_ptr = error_ptr;
  183071. #ifdef PNG_USER_MEM_SUPPORTED
  183072. png_ptr->free_fn = free_fn;
  183073. #endif
  183074. #ifdef PNG_SETJMP_SUPPORTED
  183075. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  183076. #endif
  183077. }
  183078. void PNGAPI
  183079. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  183080. {
  183081. if(png_ptr == NULL) return;
  183082. png_ptr->read_row_fn = read_row_fn;
  183083. }
  183084. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183085. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183086. void PNGAPI
  183087. png_read_png(png_structp png_ptr, png_infop info_ptr,
  183088. int transforms,
  183089. voidp params)
  183090. {
  183091. int row;
  183092. if(png_ptr == NULL) return;
  183093. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183094. /* invert the alpha channel from opacity to transparency
  183095. */
  183096. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  183097. png_set_invert_alpha(png_ptr);
  183098. #endif
  183099. /* png_read_info() gives us all of the information from the
  183100. * PNG file before the first IDAT (image data chunk).
  183101. */
  183102. png_read_info(png_ptr, info_ptr);
  183103. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  183104. png_error(png_ptr,"Image is too high to process with png_read_png()");
  183105. /* -------------- image transformations start here ------------------- */
  183106. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183107. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  183108. */
  183109. if (transforms & PNG_TRANSFORM_STRIP_16)
  183110. png_set_strip_16(png_ptr);
  183111. #endif
  183112. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183113. /* Strip alpha bytes from the input data without combining with
  183114. * the background (not recommended).
  183115. */
  183116. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  183117. png_set_strip_alpha(png_ptr);
  183118. #endif
  183119. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  183120. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  183121. * byte into separate bytes (useful for paletted and grayscale images).
  183122. */
  183123. if (transforms & PNG_TRANSFORM_PACKING)
  183124. png_set_packing(png_ptr);
  183125. #endif
  183126. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  183127. /* Change the order of packed pixels to least significant bit first
  183128. * (not useful if you are using png_set_packing).
  183129. */
  183130. if (transforms & PNG_TRANSFORM_PACKSWAP)
  183131. png_set_packswap(png_ptr);
  183132. #endif
  183133. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183134. /* Expand paletted colors into true RGB triplets
  183135. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  183136. * Expand paletted or RGB images with transparency to full alpha
  183137. * channels so the data will be available as RGBA quartets.
  183138. */
  183139. if (transforms & PNG_TRANSFORM_EXPAND)
  183140. if ((png_ptr->bit_depth < 8) ||
  183141. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  183142. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  183143. png_set_expand(png_ptr);
  183144. #endif
  183145. /* We don't handle background color or gamma transformation or dithering.
  183146. */
  183147. #if defined(PNG_READ_INVERT_SUPPORTED)
  183148. /* invert monochrome files to have 0 as white and 1 as black
  183149. */
  183150. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  183151. png_set_invert_mono(png_ptr);
  183152. #endif
  183153. #if defined(PNG_READ_SHIFT_SUPPORTED)
  183154. /* If you want to shift the pixel values from the range [0,255] or
  183155. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  183156. * colors were originally in:
  183157. */
  183158. if ((transforms & PNG_TRANSFORM_SHIFT)
  183159. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  183160. {
  183161. png_color_8p sig_bit;
  183162. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  183163. png_set_shift(png_ptr, sig_bit);
  183164. }
  183165. #endif
  183166. #if defined(PNG_READ_BGR_SUPPORTED)
  183167. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  183168. */
  183169. if (transforms & PNG_TRANSFORM_BGR)
  183170. png_set_bgr(png_ptr);
  183171. #endif
  183172. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  183173. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  183174. */
  183175. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  183176. png_set_swap_alpha(png_ptr);
  183177. #endif
  183178. #if defined(PNG_READ_SWAP_SUPPORTED)
  183179. /* swap bytes of 16 bit files to least significant byte first
  183180. */
  183181. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  183182. png_set_swap(png_ptr);
  183183. #endif
  183184. /* We don't handle adding filler bytes */
  183185. /* Optional call to gamma correct and add the background to the palette
  183186. * and update info structure. REQUIRED if you are expecting libpng to
  183187. * update the palette for you (i.e., you selected such a transform above).
  183188. */
  183189. png_read_update_info(png_ptr, info_ptr);
  183190. /* -------------- image transformations end here ------------------- */
  183191. #ifdef PNG_FREE_ME_SUPPORTED
  183192. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  183193. #endif
  183194. if(info_ptr->row_pointers == NULL)
  183195. {
  183196. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  183197. info_ptr->height * png_sizeof(png_bytep));
  183198. #ifdef PNG_FREE_ME_SUPPORTED
  183199. info_ptr->free_me |= PNG_FREE_ROWS;
  183200. #endif
  183201. for (row = 0; row < (int)info_ptr->height; row++)
  183202. {
  183203. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  183204. png_get_rowbytes(png_ptr, info_ptr));
  183205. }
  183206. }
  183207. png_read_image(png_ptr, info_ptr->row_pointers);
  183208. info_ptr->valid |= PNG_INFO_IDAT;
  183209. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  183210. png_read_end(png_ptr, info_ptr);
  183211. transforms = transforms; /* quiet compiler warnings */
  183212. params = params;
  183213. }
  183214. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  183215. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183216. #endif /* PNG_READ_SUPPORTED */
  183217. /********* End of inlined file: pngread.c *********/
  183218. /********* Start of inlined file: pngpread.c *********/
  183219. /* pngpread.c - read a png file in push mode
  183220. *
  183221. * Last changed in libpng 1.2.21 October 4, 2007
  183222. * For conditions of distribution and use, see copyright notice in png.h
  183223. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183224. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183225. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183226. */
  183227. #define PNG_INTERNAL
  183228. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183229. /* push model modes */
  183230. #define PNG_READ_SIG_MODE 0
  183231. #define PNG_READ_CHUNK_MODE 1
  183232. #define PNG_READ_IDAT_MODE 2
  183233. #define PNG_SKIP_MODE 3
  183234. #define PNG_READ_tEXt_MODE 4
  183235. #define PNG_READ_zTXt_MODE 5
  183236. #define PNG_READ_DONE_MODE 6
  183237. #define PNG_READ_iTXt_MODE 7
  183238. #define PNG_ERROR_MODE 8
  183239. void PNGAPI
  183240. png_process_data(png_structp png_ptr, png_infop info_ptr,
  183241. png_bytep buffer, png_size_t buffer_size)
  183242. {
  183243. if(png_ptr == NULL) return;
  183244. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  183245. while (png_ptr->buffer_size)
  183246. {
  183247. png_process_some_data(png_ptr, info_ptr);
  183248. }
  183249. }
  183250. /* What we do with the incoming data depends on what we were previously
  183251. * doing before we ran out of data...
  183252. */
  183253. void /* PRIVATE */
  183254. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  183255. {
  183256. if(png_ptr == NULL) return;
  183257. switch (png_ptr->process_mode)
  183258. {
  183259. case PNG_READ_SIG_MODE:
  183260. {
  183261. png_push_read_sig(png_ptr, info_ptr);
  183262. break;
  183263. }
  183264. case PNG_READ_CHUNK_MODE:
  183265. {
  183266. png_push_read_chunk(png_ptr, info_ptr);
  183267. break;
  183268. }
  183269. case PNG_READ_IDAT_MODE:
  183270. {
  183271. png_push_read_IDAT(png_ptr);
  183272. break;
  183273. }
  183274. #if defined(PNG_READ_tEXt_SUPPORTED)
  183275. case PNG_READ_tEXt_MODE:
  183276. {
  183277. png_push_read_tEXt(png_ptr, info_ptr);
  183278. break;
  183279. }
  183280. #endif
  183281. #if defined(PNG_READ_zTXt_SUPPORTED)
  183282. case PNG_READ_zTXt_MODE:
  183283. {
  183284. png_push_read_zTXt(png_ptr, info_ptr);
  183285. break;
  183286. }
  183287. #endif
  183288. #if defined(PNG_READ_iTXt_SUPPORTED)
  183289. case PNG_READ_iTXt_MODE:
  183290. {
  183291. png_push_read_iTXt(png_ptr, info_ptr);
  183292. break;
  183293. }
  183294. #endif
  183295. case PNG_SKIP_MODE:
  183296. {
  183297. png_push_crc_finish(png_ptr);
  183298. break;
  183299. }
  183300. default:
  183301. {
  183302. png_ptr->buffer_size = 0;
  183303. break;
  183304. }
  183305. }
  183306. }
  183307. /* Read any remaining signature bytes from the stream and compare them with
  183308. * the correct PNG signature. It is possible that this routine is called
  183309. * with bytes already read from the signature, either because they have been
  183310. * checked by the calling application, or because of multiple calls to this
  183311. * routine.
  183312. */
  183313. void /* PRIVATE */
  183314. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  183315. {
  183316. png_size_t num_checked = png_ptr->sig_bytes,
  183317. num_to_check = 8 - num_checked;
  183318. if (png_ptr->buffer_size < num_to_check)
  183319. {
  183320. num_to_check = png_ptr->buffer_size;
  183321. }
  183322. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  183323. num_to_check);
  183324. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  183325. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  183326. {
  183327. if (num_checked < 4 &&
  183328. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  183329. png_error(png_ptr, "Not a PNG file");
  183330. else
  183331. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  183332. }
  183333. else
  183334. {
  183335. if (png_ptr->sig_bytes >= 8)
  183336. {
  183337. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  183338. }
  183339. }
  183340. }
  183341. void /* PRIVATE */
  183342. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  183343. {
  183344. #ifdef PNG_USE_LOCAL_ARRAYS
  183345. PNG_CONST PNG_IHDR;
  183346. PNG_CONST PNG_IDAT;
  183347. PNG_CONST PNG_IEND;
  183348. PNG_CONST PNG_PLTE;
  183349. #if defined(PNG_READ_bKGD_SUPPORTED)
  183350. PNG_CONST PNG_bKGD;
  183351. #endif
  183352. #if defined(PNG_READ_cHRM_SUPPORTED)
  183353. PNG_CONST PNG_cHRM;
  183354. #endif
  183355. #if defined(PNG_READ_gAMA_SUPPORTED)
  183356. PNG_CONST PNG_gAMA;
  183357. #endif
  183358. #if defined(PNG_READ_hIST_SUPPORTED)
  183359. PNG_CONST PNG_hIST;
  183360. #endif
  183361. #if defined(PNG_READ_iCCP_SUPPORTED)
  183362. PNG_CONST PNG_iCCP;
  183363. #endif
  183364. #if defined(PNG_READ_iTXt_SUPPORTED)
  183365. PNG_CONST PNG_iTXt;
  183366. #endif
  183367. #if defined(PNG_READ_oFFs_SUPPORTED)
  183368. PNG_CONST PNG_oFFs;
  183369. #endif
  183370. #if defined(PNG_READ_pCAL_SUPPORTED)
  183371. PNG_CONST PNG_pCAL;
  183372. #endif
  183373. #if defined(PNG_READ_pHYs_SUPPORTED)
  183374. PNG_CONST PNG_pHYs;
  183375. #endif
  183376. #if defined(PNG_READ_sBIT_SUPPORTED)
  183377. PNG_CONST PNG_sBIT;
  183378. #endif
  183379. #if defined(PNG_READ_sCAL_SUPPORTED)
  183380. PNG_CONST PNG_sCAL;
  183381. #endif
  183382. #if defined(PNG_READ_sRGB_SUPPORTED)
  183383. PNG_CONST PNG_sRGB;
  183384. #endif
  183385. #if defined(PNG_READ_sPLT_SUPPORTED)
  183386. PNG_CONST PNG_sPLT;
  183387. #endif
  183388. #if defined(PNG_READ_tEXt_SUPPORTED)
  183389. PNG_CONST PNG_tEXt;
  183390. #endif
  183391. #if defined(PNG_READ_tIME_SUPPORTED)
  183392. PNG_CONST PNG_tIME;
  183393. #endif
  183394. #if defined(PNG_READ_tRNS_SUPPORTED)
  183395. PNG_CONST PNG_tRNS;
  183396. #endif
  183397. #if defined(PNG_READ_zTXt_SUPPORTED)
  183398. PNG_CONST PNG_zTXt;
  183399. #endif
  183400. #endif /* PNG_USE_LOCAL_ARRAYS */
  183401. /* First we make sure we have enough data for the 4 byte chunk name
  183402. * and the 4 byte chunk length before proceeding with decoding the
  183403. * chunk data. To fully decode each of these chunks, we also make
  183404. * sure we have enough data in the buffer for the 4 byte CRC at the
  183405. * end of every chunk (except IDAT, which is handled separately).
  183406. */
  183407. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  183408. {
  183409. png_byte chunk_length[4];
  183410. if (png_ptr->buffer_size < 8)
  183411. {
  183412. png_push_save_buffer(png_ptr);
  183413. return;
  183414. }
  183415. png_push_fill_buffer(png_ptr, chunk_length, 4);
  183416. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  183417. png_reset_crc(png_ptr);
  183418. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183419. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  183420. }
  183421. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183422. if(png_ptr->mode & PNG_AFTER_IDAT)
  183423. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  183424. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  183425. {
  183426. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183427. {
  183428. png_push_save_buffer(png_ptr);
  183429. return;
  183430. }
  183431. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  183432. }
  183433. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  183434. {
  183435. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183436. {
  183437. png_push_save_buffer(png_ptr);
  183438. return;
  183439. }
  183440. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  183441. png_ptr->process_mode = PNG_READ_DONE_MODE;
  183442. png_push_have_end(png_ptr, info_ptr);
  183443. }
  183444. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183445. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  183446. {
  183447. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183448. {
  183449. png_push_save_buffer(png_ptr);
  183450. return;
  183451. }
  183452. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183453. png_ptr->mode |= PNG_HAVE_IDAT;
  183454. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  183455. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183456. png_ptr->mode |= PNG_HAVE_PLTE;
  183457. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183458. {
  183459. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  183460. png_error(png_ptr, "Missing IHDR before IDAT");
  183461. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  183462. !(png_ptr->mode & PNG_HAVE_PLTE))
  183463. png_error(png_ptr, "Missing PLTE before IDAT");
  183464. }
  183465. }
  183466. #endif
  183467. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183468. {
  183469. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183470. {
  183471. png_push_save_buffer(png_ptr);
  183472. return;
  183473. }
  183474. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  183475. }
  183476. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183477. {
  183478. /* If we reach an IDAT chunk, this means we have read all of the
  183479. * header chunks, and we can start reading the image (or if this
  183480. * is called after the image has been read - we have an error).
  183481. */
  183482. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  183483. png_error(png_ptr, "Missing IHDR before IDAT");
  183484. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  183485. !(png_ptr->mode & PNG_HAVE_PLTE))
  183486. png_error(png_ptr, "Missing PLTE before IDAT");
  183487. if (png_ptr->mode & PNG_HAVE_IDAT)
  183488. {
  183489. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  183490. if (png_ptr->push_length == 0)
  183491. return;
  183492. if (png_ptr->mode & PNG_AFTER_IDAT)
  183493. png_error(png_ptr, "Too many IDAT's found");
  183494. }
  183495. png_ptr->idat_size = png_ptr->push_length;
  183496. png_ptr->mode |= PNG_HAVE_IDAT;
  183497. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  183498. png_push_have_info(png_ptr, info_ptr);
  183499. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  183500. png_ptr->zstream.next_out = png_ptr->row_buf;
  183501. return;
  183502. }
  183503. #if defined(PNG_READ_gAMA_SUPPORTED)
  183504. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  183505. {
  183506. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183507. {
  183508. png_push_save_buffer(png_ptr);
  183509. return;
  183510. }
  183511. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  183512. }
  183513. #endif
  183514. #if defined(PNG_READ_sBIT_SUPPORTED)
  183515. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  183516. {
  183517. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183518. {
  183519. png_push_save_buffer(png_ptr);
  183520. return;
  183521. }
  183522. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  183523. }
  183524. #endif
  183525. #if defined(PNG_READ_cHRM_SUPPORTED)
  183526. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  183527. {
  183528. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183529. {
  183530. png_push_save_buffer(png_ptr);
  183531. return;
  183532. }
  183533. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  183534. }
  183535. #endif
  183536. #if defined(PNG_READ_sRGB_SUPPORTED)
  183537. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  183538. {
  183539. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183540. {
  183541. png_push_save_buffer(png_ptr);
  183542. return;
  183543. }
  183544. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  183545. }
  183546. #endif
  183547. #if defined(PNG_READ_iCCP_SUPPORTED)
  183548. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  183549. {
  183550. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183551. {
  183552. png_push_save_buffer(png_ptr);
  183553. return;
  183554. }
  183555. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  183556. }
  183557. #endif
  183558. #if defined(PNG_READ_sPLT_SUPPORTED)
  183559. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  183560. {
  183561. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183562. {
  183563. png_push_save_buffer(png_ptr);
  183564. return;
  183565. }
  183566. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  183567. }
  183568. #endif
  183569. #if defined(PNG_READ_tRNS_SUPPORTED)
  183570. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  183571. {
  183572. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183573. {
  183574. png_push_save_buffer(png_ptr);
  183575. return;
  183576. }
  183577. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  183578. }
  183579. #endif
  183580. #if defined(PNG_READ_bKGD_SUPPORTED)
  183581. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  183582. {
  183583. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183584. {
  183585. png_push_save_buffer(png_ptr);
  183586. return;
  183587. }
  183588. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  183589. }
  183590. #endif
  183591. #if defined(PNG_READ_hIST_SUPPORTED)
  183592. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  183593. {
  183594. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183595. {
  183596. png_push_save_buffer(png_ptr);
  183597. return;
  183598. }
  183599. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  183600. }
  183601. #endif
  183602. #if defined(PNG_READ_pHYs_SUPPORTED)
  183603. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  183604. {
  183605. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183606. {
  183607. png_push_save_buffer(png_ptr);
  183608. return;
  183609. }
  183610. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  183611. }
  183612. #endif
  183613. #if defined(PNG_READ_oFFs_SUPPORTED)
  183614. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  183615. {
  183616. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183617. {
  183618. png_push_save_buffer(png_ptr);
  183619. return;
  183620. }
  183621. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  183622. }
  183623. #endif
  183624. #if defined(PNG_READ_pCAL_SUPPORTED)
  183625. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  183626. {
  183627. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183628. {
  183629. png_push_save_buffer(png_ptr);
  183630. return;
  183631. }
  183632. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  183633. }
  183634. #endif
  183635. #if defined(PNG_READ_sCAL_SUPPORTED)
  183636. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  183637. {
  183638. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183639. {
  183640. png_push_save_buffer(png_ptr);
  183641. return;
  183642. }
  183643. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  183644. }
  183645. #endif
  183646. #if defined(PNG_READ_tIME_SUPPORTED)
  183647. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  183648. {
  183649. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183650. {
  183651. png_push_save_buffer(png_ptr);
  183652. return;
  183653. }
  183654. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  183655. }
  183656. #endif
  183657. #if defined(PNG_READ_tEXt_SUPPORTED)
  183658. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  183659. {
  183660. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183661. {
  183662. png_push_save_buffer(png_ptr);
  183663. return;
  183664. }
  183665. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  183666. }
  183667. #endif
  183668. #if defined(PNG_READ_zTXt_SUPPORTED)
  183669. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  183670. {
  183671. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183672. {
  183673. png_push_save_buffer(png_ptr);
  183674. return;
  183675. }
  183676. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  183677. }
  183678. #endif
  183679. #if defined(PNG_READ_iTXt_SUPPORTED)
  183680. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  183681. {
  183682. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183683. {
  183684. png_push_save_buffer(png_ptr);
  183685. return;
  183686. }
  183687. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  183688. }
  183689. #endif
  183690. else
  183691. {
  183692. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  183693. {
  183694. png_push_save_buffer(png_ptr);
  183695. return;
  183696. }
  183697. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  183698. }
  183699. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  183700. }
  183701. void /* PRIVATE */
  183702. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  183703. {
  183704. png_ptr->process_mode = PNG_SKIP_MODE;
  183705. png_ptr->skip_length = skip;
  183706. }
  183707. void /* PRIVATE */
  183708. png_push_crc_finish(png_structp png_ptr)
  183709. {
  183710. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  183711. {
  183712. png_size_t save_size;
  183713. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  183714. save_size = (png_size_t)png_ptr->skip_length;
  183715. else
  183716. save_size = png_ptr->save_buffer_size;
  183717. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  183718. png_ptr->skip_length -= save_size;
  183719. png_ptr->buffer_size -= save_size;
  183720. png_ptr->save_buffer_size -= save_size;
  183721. png_ptr->save_buffer_ptr += save_size;
  183722. }
  183723. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  183724. {
  183725. png_size_t save_size;
  183726. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  183727. save_size = (png_size_t)png_ptr->skip_length;
  183728. else
  183729. save_size = png_ptr->current_buffer_size;
  183730. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  183731. png_ptr->skip_length -= save_size;
  183732. png_ptr->buffer_size -= save_size;
  183733. png_ptr->current_buffer_size -= save_size;
  183734. png_ptr->current_buffer_ptr += save_size;
  183735. }
  183736. if (!png_ptr->skip_length)
  183737. {
  183738. if (png_ptr->buffer_size < 4)
  183739. {
  183740. png_push_save_buffer(png_ptr);
  183741. return;
  183742. }
  183743. png_crc_finish(png_ptr, 0);
  183744. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  183745. }
  183746. }
  183747. void PNGAPI
  183748. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  183749. {
  183750. png_bytep ptr;
  183751. if(png_ptr == NULL) return;
  183752. ptr = buffer;
  183753. if (png_ptr->save_buffer_size)
  183754. {
  183755. png_size_t save_size;
  183756. if (length < png_ptr->save_buffer_size)
  183757. save_size = length;
  183758. else
  183759. save_size = png_ptr->save_buffer_size;
  183760. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  183761. length -= save_size;
  183762. ptr += save_size;
  183763. png_ptr->buffer_size -= save_size;
  183764. png_ptr->save_buffer_size -= save_size;
  183765. png_ptr->save_buffer_ptr += save_size;
  183766. }
  183767. if (length && png_ptr->current_buffer_size)
  183768. {
  183769. png_size_t save_size;
  183770. if (length < png_ptr->current_buffer_size)
  183771. save_size = length;
  183772. else
  183773. save_size = png_ptr->current_buffer_size;
  183774. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  183775. png_ptr->buffer_size -= save_size;
  183776. png_ptr->current_buffer_size -= save_size;
  183777. png_ptr->current_buffer_ptr += save_size;
  183778. }
  183779. }
  183780. void /* PRIVATE */
  183781. png_push_save_buffer(png_structp png_ptr)
  183782. {
  183783. if (png_ptr->save_buffer_size)
  183784. {
  183785. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  183786. {
  183787. png_size_t i,istop;
  183788. png_bytep sp;
  183789. png_bytep dp;
  183790. istop = png_ptr->save_buffer_size;
  183791. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  183792. i < istop; i++, sp++, dp++)
  183793. {
  183794. *dp = *sp;
  183795. }
  183796. }
  183797. }
  183798. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  183799. png_ptr->save_buffer_max)
  183800. {
  183801. png_size_t new_max;
  183802. png_bytep old_buffer;
  183803. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  183804. (png_ptr->current_buffer_size + 256))
  183805. {
  183806. png_error(png_ptr, "Potential overflow of save_buffer");
  183807. }
  183808. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  183809. old_buffer = png_ptr->save_buffer;
  183810. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  183811. (png_uint_32)new_max);
  183812. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  183813. png_free(png_ptr, old_buffer);
  183814. png_ptr->save_buffer_max = new_max;
  183815. }
  183816. if (png_ptr->current_buffer_size)
  183817. {
  183818. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  183819. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  183820. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  183821. png_ptr->current_buffer_size = 0;
  183822. }
  183823. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  183824. png_ptr->buffer_size = 0;
  183825. }
  183826. void /* PRIVATE */
  183827. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  183828. png_size_t buffer_length)
  183829. {
  183830. png_ptr->current_buffer = buffer;
  183831. png_ptr->current_buffer_size = buffer_length;
  183832. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  183833. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  183834. }
  183835. void /* PRIVATE */
  183836. png_push_read_IDAT(png_structp png_ptr)
  183837. {
  183838. #ifdef PNG_USE_LOCAL_ARRAYS
  183839. PNG_CONST PNG_IDAT;
  183840. #endif
  183841. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  183842. {
  183843. png_byte chunk_length[4];
  183844. if (png_ptr->buffer_size < 8)
  183845. {
  183846. png_push_save_buffer(png_ptr);
  183847. return;
  183848. }
  183849. png_push_fill_buffer(png_ptr, chunk_length, 4);
  183850. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  183851. png_reset_crc(png_ptr);
  183852. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183853. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  183854. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183855. {
  183856. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  183857. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  183858. png_error(png_ptr, "Not enough compressed data");
  183859. return;
  183860. }
  183861. png_ptr->idat_size = png_ptr->push_length;
  183862. }
  183863. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  183864. {
  183865. png_size_t save_size;
  183866. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  183867. {
  183868. save_size = (png_size_t)png_ptr->idat_size;
  183869. /* check for overflow */
  183870. if((png_uint_32)save_size != png_ptr->idat_size)
  183871. png_error(png_ptr, "save_size overflowed in pngpread");
  183872. }
  183873. else
  183874. save_size = png_ptr->save_buffer_size;
  183875. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  183876. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  183877. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  183878. png_ptr->idat_size -= save_size;
  183879. png_ptr->buffer_size -= save_size;
  183880. png_ptr->save_buffer_size -= save_size;
  183881. png_ptr->save_buffer_ptr += save_size;
  183882. }
  183883. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  183884. {
  183885. png_size_t save_size;
  183886. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  183887. {
  183888. save_size = (png_size_t)png_ptr->idat_size;
  183889. /* check for overflow */
  183890. if((png_uint_32)save_size != png_ptr->idat_size)
  183891. png_error(png_ptr, "save_size overflowed in pngpread");
  183892. }
  183893. else
  183894. save_size = png_ptr->current_buffer_size;
  183895. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  183896. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  183897. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  183898. png_ptr->idat_size -= save_size;
  183899. png_ptr->buffer_size -= save_size;
  183900. png_ptr->current_buffer_size -= save_size;
  183901. png_ptr->current_buffer_ptr += save_size;
  183902. }
  183903. if (!png_ptr->idat_size)
  183904. {
  183905. if (png_ptr->buffer_size < 4)
  183906. {
  183907. png_push_save_buffer(png_ptr);
  183908. return;
  183909. }
  183910. png_crc_finish(png_ptr, 0);
  183911. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  183912. png_ptr->mode |= PNG_AFTER_IDAT;
  183913. }
  183914. }
  183915. void /* PRIVATE */
  183916. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  183917. png_size_t buffer_length)
  183918. {
  183919. int ret;
  183920. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  183921. png_error(png_ptr, "Extra compression data");
  183922. png_ptr->zstream.next_in = buffer;
  183923. png_ptr->zstream.avail_in = (uInt)buffer_length;
  183924. for(;;)
  183925. {
  183926. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  183927. if (ret != Z_OK)
  183928. {
  183929. if (ret == Z_STREAM_END)
  183930. {
  183931. if (png_ptr->zstream.avail_in)
  183932. png_error(png_ptr, "Extra compressed data");
  183933. if (!(png_ptr->zstream.avail_out))
  183934. {
  183935. png_push_process_row(png_ptr);
  183936. }
  183937. png_ptr->mode |= PNG_AFTER_IDAT;
  183938. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  183939. break;
  183940. }
  183941. else if (ret == Z_BUF_ERROR)
  183942. break;
  183943. else
  183944. png_error(png_ptr, "Decompression Error");
  183945. }
  183946. if (!(png_ptr->zstream.avail_out))
  183947. {
  183948. if ((
  183949. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183950. png_ptr->interlaced && png_ptr->pass > 6) ||
  183951. (!png_ptr->interlaced &&
  183952. #endif
  183953. png_ptr->row_number == png_ptr->num_rows))
  183954. {
  183955. if (png_ptr->zstream.avail_in)
  183956. {
  183957. png_warning(png_ptr, "Too much data in IDAT chunks");
  183958. }
  183959. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  183960. break;
  183961. }
  183962. png_push_process_row(png_ptr);
  183963. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  183964. png_ptr->zstream.next_out = png_ptr->row_buf;
  183965. }
  183966. else
  183967. break;
  183968. }
  183969. }
  183970. void /* PRIVATE */
  183971. png_push_process_row(png_structp png_ptr)
  183972. {
  183973. png_ptr->row_info.color_type = png_ptr->color_type;
  183974. png_ptr->row_info.width = png_ptr->iwidth;
  183975. png_ptr->row_info.channels = png_ptr->channels;
  183976. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  183977. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  183978. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  183979. png_ptr->row_info.width);
  183980. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  183981. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  183982. (int)(png_ptr->row_buf[0]));
  183983. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  183984. png_ptr->rowbytes + 1);
  183985. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  183986. png_do_read_transformations(png_ptr);
  183987. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183988. /* blow up interlaced rows to full size */
  183989. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  183990. {
  183991. if (png_ptr->pass < 6)
  183992. /* old interface (pre-1.0.9):
  183993. png_do_read_interlace(&(png_ptr->row_info),
  183994. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  183995. */
  183996. png_do_read_interlace(png_ptr);
  183997. switch (png_ptr->pass)
  183998. {
  183999. case 0:
  184000. {
  184001. int i;
  184002. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  184003. {
  184004. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184005. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  184006. }
  184007. if (png_ptr->pass == 2) /* pass 1 might be empty */
  184008. {
  184009. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184010. {
  184011. png_push_have_row(png_ptr, png_bytep_NULL);
  184012. png_read_push_finish_row(png_ptr);
  184013. }
  184014. }
  184015. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  184016. {
  184017. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184018. {
  184019. png_push_have_row(png_ptr, png_bytep_NULL);
  184020. png_read_push_finish_row(png_ptr);
  184021. }
  184022. }
  184023. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  184024. {
  184025. png_push_have_row(png_ptr, png_bytep_NULL);
  184026. png_read_push_finish_row(png_ptr);
  184027. }
  184028. break;
  184029. }
  184030. case 1:
  184031. {
  184032. int i;
  184033. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  184034. {
  184035. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184036. png_read_push_finish_row(png_ptr);
  184037. }
  184038. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  184039. {
  184040. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184041. {
  184042. png_push_have_row(png_ptr, png_bytep_NULL);
  184043. png_read_push_finish_row(png_ptr);
  184044. }
  184045. }
  184046. break;
  184047. }
  184048. case 2:
  184049. {
  184050. int i;
  184051. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184052. {
  184053. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184054. png_read_push_finish_row(png_ptr);
  184055. }
  184056. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184057. {
  184058. png_push_have_row(png_ptr, png_bytep_NULL);
  184059. png_read_push_finish_row(png_ptr);
  184060. }
  184061. if (png_ptr->pass == 4) /* pass 3 might be empty */
  184062. {
  184063. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184064. {
  184065. png_push_have_row(png_ptr, png_bytep_NULL);
  184066. png_read_push_finish_row(png_ptr);
  184067. }
  184068. }
  184069. break;
  184070. }
  184071. case 3:
  184072. {
  184073. int i;
  184074. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  184075. {
  184076. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184077. png_read_push_finish_row(png_ptr);
  184078. }
  184079. if (png_ptr->pass == 4) /* skip top two generated rows */
  184080. {
  184081. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184082. {
  184083. png_push_have_row(png_ptr, png_bytep_NULL);
  184084. png_read_push_finish_row(png_ptr);
  184085. }
  184086. }
  184087. break;
  184088. }
  184089. case 4:
  184090. {
  184091. int i;
  184092. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184093. {
  184094. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184095. png_read_push_finish_row(png_ptr);
  184096. }
  184097. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184098. {
  184099. png_push_have_row(png_ptr, png_bytep_NULL);
  184100. png_read_push_finish_row(png_ptr);
  184101. }
  184102. if (png_ptr->pass == 6) /* pass 5 might be empty */
  184103. {
  184104. png_push_have_row(png_ptr, png_bytep_NULL);
  184105. png_read_push_finish_row(png_ptr);
  184106. }
  184107. break;
  184108. }
  184109. case 5:
  184110. {
  184111. int i;
  184112. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  184113. {
  184114. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184115. png_read_push_finish_row(png_ptr);
  184116. }
  184117. if (png_ptr->pass == 6) /* skip top generated row */
  184118. {
  184119. png_push_have_row(png_ptr, png_bytep_NULL);
  184120. png_read_push_finish_row(png_ptr);
  184121. }
  184122. break;
  184123. }
  184124. case 6:
  184125. {
  184126. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184127. png_read_push_finish_row(png_ptr);
  184128. if (png_ptr->pass != 6)
  184129. break;
  184130. png_push_have_row(png_ptr, png_bytep_NULL);
  184131. png_read_push_finish_row(png_ptr);
  184132. }
  184133. }
  184134. }
  184135. else
  184136. #endif
  184137. {
  184138. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184139. png_read_push_finish_row(png_ptr);
  184140. }
  184141. }
  184142. void /* PRIVATE */
  184143. png_read_push_finish_row(png_structp png_ptr)
  184144. {
  184145. #ifdef PNG_USE_LOCAL_ARRAYS
  184146. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184147. /* start of interlace block */
  184148. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184149. /* offset to next interlace block */
  184150. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184151. /* start of interlace block in the y direction */
  184152. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184153. /* offset to next interlace block in the y direction */
  184154. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184155. /* Height of interlace block. This is not currently used - if you need
  184156. * it, uncomment it here and in png.h
  184157. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184158. */
  184159. #endif
  184160. png_ptr->row_number++;
  184161. if (png_ptr->row_number < png_ptr->num_rows)
  184162. return;
  184163. if (png_ptr->interlaced)
  184164. {
  184165. png_ptr->row_number = 0;
  184166. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  184167. png_ptr->rowbytes + 1);
  184168. do
  184169. {
  184170. png_ptr->pass++;
  184171. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  184172. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  184173. (png_ptr->pass == 5 && png_ptr->width < 2))
  184174. png_ptr->pass++;
  184175. if (png_ptr->pass > 7)
  184176. png_ptr->pass--;
  184177. if (png_ptr->pass >= 7)
  184178. break;
  184179. png_ptr->iwidth = (png_ptr->width +
  184180. png_pass_inc[png_ptr->pass] - 1 -
  184181. png_pass_start[png_ptr->pass]) /
  184182. png_pass_inc[png_ptr->pass];
  184183. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  184184. png_ptr->iwidth) + 1;
  184185. if (png_ptr->transformations & PNG_INTERLACE)
  184186. break;
  184187. png_ptr->num_rows = (png_ptr->height +
  184188. png_pass_yinc[png_ptr->pass] - 1 -
  184189. png_pass_ystart[png_ptr->pass]) /
  184190. png_pass_yinc[png_ptr->pass];
  184191. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  184192. }
  184193. }
  184194. #if defined(PNG_READ_tEXt_SUPPORTED)
  184195. void /* PRIVATE */
  184196. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  184197. length)
  184198. {
  184199. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  184200. {
  184201. png_error(png_ptr, "Out of place tEXt");
  184202. info_ptr = info_ptr; /* to quiet some compiler warnings */
  184203. }
  184204. #ifdef PNG_MAX_MALLOC_64K
  184205. png_ptr->skip_length = 0; /* This may not be necessary */
  184206. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  184207. {
  184208. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  184209. png_ptr->skip_length = length - (png_uint_32)65535L;
  184210. length = (png_uint_32)65535L;
  184211. }
  184212. #endif
  184213. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  184214. (png_uint_32)(length+1));
  184215. png_ptr->current_text[length] = '\0';
  184216. png_ptr->current_text_ptr = png_ptr->current_text;
  184217. png_ptr->current_text_size = (png_size_t)length;
  184218. png_ptr->current_text_left = (png_size_t)length;
  184219. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  184220. }
  184221. void /* PRIVATE */
  184222. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  184223. {
  184224. if (png_ptr->buffer_size && png_ptr->current_text_left)
  184225. {
  184226. png_size_t text_size;
  184227. if (png_ptr->buffer_size < png_ptr->current_text_left)
  184228. text_size = png_ptr->buffer_size;
  184229. else
  184230. text_size = png_ptr->current_text_left;
  184231. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  184232. png_ptr->current_text_left -= text_size;
  184233. png_ptr->current_text_ptr += text_size;
  184234. }
  184235. if (!(png_ptr->current_text_left))
  184236. {
  184237. png_textp text_ptr;
  184238. png_charp text;
  184239. png_charp key;
  184240. int ret;
  184241. if (png_ptr->buffer_size < 4)
  184242. {
  184243. png_push_save_buffer(png_ptr);
  184244. return;
  184245. }
  184246. png_push_crc_finish(png_ptr);
  184247. #if defined(PNG_MAX_MALLOC_64K)
  184248. if (png_ptr->skip_length)
  184249. return;
  184250. #endif
  184251. key = png_ptr->current_text;
  184252. for (text = key; *text; text++)
  184253. /* empty loop */ ;
  184254. if (text < key + png_ptr->current_text_size)
  184255. text++;
  184256. text_ptr = (png_textp)png_malloc(png_ptr,
  184257. (png_uint_32)png_sizeof(png_text));
  184258. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  184259. text_ptr->key = key;
  184260. #ifdef PNG_iTXt_SUPPORTED
  184261. text_ptr->lang = NULL;
  184262. text_ptr->lang_key = NULL;
  184263. #endif
  184264. text_ptr->text = text;
  184265. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  184266. png_free(png_ptr, key);
  184267. png_free(png_ptr, text_ptr);
  184268. png_ptr->current_text = NULL;
  184269. if (ret)
  184270. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  184271. }
  184272. }
  184273. #endif
  184274. #if defined(PNG_READ_zTXt_SUPPORTED)
  184275. void /* PRIVATE */
  184276. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  184277. length)
  184278. {
  184279. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  184280. {
  184281. png_error(png_ptr, "Out of place zTXt");
  184282. info_ptr = info_ptr; /* to quiet some compiler warnings */
  184283. }
  184284. #ifdef PNG_MAX_MALLOC_64K
  184285. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  184286. * to be able to store the uncompressed data. Actually, the threshold
  184287. * is probably around 32K, but it isn't as definite as 64K is.
  184288. */
  184289. if (length > (png_uint_32)65535L)
  184290. {
  184291. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  184292. png_push_crc_skip(png_ptr, length);
  184293. return;
  184294. }
  184295. #endif
  184296. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  184297. (png_uint_32)(length+1));
  184298. png_ptr->current_text[length] = '\0';
  184299. png_ptr->current_text_ptr = png_ptr->current_text;
  184300. png_ptr->current_text_size = (png_size_t)length;
  184301. png_ptr->current_text_left = (png_size_t)length;
  184302. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  184303. }
  184304. void /* PRIVATE */
  184305. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  184306. {
  184307. if (png_ptr->buffer_size && png_ptr->current_text_left)
  184308. {
  184309. png_size_t text_size;
  184310. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  184311. text_size = png_ptr->buffer_size;
  184312. else
  184313. text_size = png_ptr->current_text_left;
  184314. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  184315. png_ptr->current_text_left -= text_size;
  184316. png_ptr->current_text_ptr += text_size;
  184317. }
  184318. if (!(png_ptr->current_text_left))
  184319. {
  184320. png_textp text_ptr;
  184321. png_charp text;
  184322. png_charp key;
  184323. int ret;
  184324. png_size_t text_size, key_size;
  184325. if (png_ptr->buffer_size < 4)
  184326. {
  184327. png_push_save_buffer(png_ptr);
  184328. return;
  184329. }
  184330. png_push_crc_finish(png_ptr);
  184331. key = png_ptr->current_text;
  184332. for (text = key; *text; text++)
  184333. /* empty loop */ ;
  184334. /* zTXt can't have zero text */
  184335. if (text >= key + png_ptr->current_text_size)
  184336. {
  184337. png_ptr->current_text = NULL;
  184338. png_free(png_ptr, key);
  184339. return;
  184340. }
  184341. text++;
  184342. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  184343. {
  184344. png_ptr->current_text = NULL;
  184345. png_free(png_ptr, key);
  184346. return;
  184347. }
  184348. text++;
  184349. png_ptr->zstream.next_in = (png_bytep )text;
  184350. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  184351. (text - key));
  184352. png_ptr->zstream.next_out = png_ptr->zbuf;
  184353. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  184354. key_size = text - key;
  184355. text_size = 0;
  184356. text = NULL;
  184357. ret = Z_STREAM_END;
  184358. while (png_ptr->zstream.avail_in)
  184359. {
  184360. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  184361. if (ret != Z_OK && ret != Z_STREAM_END)
  184362. {
  184363. inflateReset(&png_ptr->zstream);
  184364. png_ptr->zstream.avail_in = 0;
  184365. png_ptr->current_text = NULL;
  184366. png_free(png_ptr, key);
  184367. png_free(png_ptr, text);
  184368. return;
  184369. }
  184370. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  184371. {
  184372. if (text == NULL)
  184373. {
  184374. text = (png_charp)png_malloc(png_ptr,
  184375. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  184376. + key_size + 1));
  184377. png_memcpy(text + key_size, png_ptr->zbuf,
  184378. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  184379. png_memcpy(text, key, key_size);
  184380. text_size = key_size + png_ptr->zbuf_size -
  184381. png_ptr->zstream.avail_out;
  184382. *(text + text_size) = '\0';
  184383. }
  184384. else
  184385. {
  184386. png_charp tmp;
  184387. tmp = text;
  184388. text = (png_charp)png_malloc(png_ptr, text_size +
  184389. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  184390. + 1));
  184391. png_memcpy(text, tmp, text_size);
  184392. png_free(png_ptr, tmp);
  184393. png_memcpy(text + text_size, png_ptr->zbuf,
  184394. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  184395. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  184396. *(text + text_size) = '\0';
  184397. }
  184398. if (ret != Z_STREAM_END)
  184399. {
  184400. png_ptr->zstream.next_out = png_ptr->zbuf;
  184401. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  184402. }
  184403. }
  184404. else
  184405. {
  184406. break;
  184407. }
  184408. if (ret == Z_STREAM_END)
  184409. break;
  184410. }
  184411. inflateReset(&png_ptr->zstream);
  184412. png_ptr->zstream.avail_in = 0;
  184413. if (ret != Z_STREAM_END)
  184414. {
  184415. png_ptr->current_text = NULL;
  184416. png_free(png_ptr, key);
  184417. png_free(png_ptr, text);
  184418. return;
  184419. }
  184420. png_ptr->current_text = NULL;
  184421. png_free(png_ptr, key);
  184422. key = text;
  184423. text += key_size;
  184424. text_ptr = (png_textp)png_malloc(png_ptr,
  184425. (png_uint_32)png_sizeof(png_text));
  184426. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  184427. text_ptr->key = key;
  184428. #ifdef PNG_iTXt_SUPPORTED
  184429. text_ptr->lang = NULL;
  184430. text_ptr->lang_key = NULL;
  184431. #endif
  184432. text_ptr->text = text;
  184433. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  184434. png_free(png_ptr, key);
  184435. png_free(png_ptr, text_ptr);
  184436. if (ret)
  184437. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  184438. }
  184439. }
  184440. #endif
  184441. #if defined(PNG_READ_iTXt_SUPPORTED)
  184442. void /* PRIVATE */
  184443. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  184444. length)
  184445. {
  184446. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  184447. {
  184448. png_error(png_ptr, "Out of place iTXt");
  184449. info_ptr = info_ptr; /* to quiet some compiler warnings */
  184450. }
  184451. #ifdef PNG_MAX_MALLOC_64K
  184452. png_ptr->skip_length = 0; /* This may not be necessary */
  184453. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  184454. {
  184455. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  184456. png_ptr->skip_length = length - (png_uint_32)65535L;
  184457. length = (png_uint_32)65535L;
  184458. }
  184459. #endif
  184460. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  184461. (png_uint_32)(length+1));
  184462. png_ptr->current_text[length] = '\0';
  184463. png_ptr->current_text_ptr = png_ptr->current_text;
  184464. png_ptr->current_text_size = (png_size_t)length;
  184465. png_ptr->current_text_left = (png_size_t)length;
  184466. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  184467. }
  184468. void /* PRIVATE */
  184469. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  184470. {
  184471. if (png_ptr->buffer_size && png_ptr->current_text_left)
  184472. {
  184473. png_size_t text_size;
  184474. if (png_ptr->buffer_size < png_ptr->current_text_left)
  184475. text_size = png_ptr->buffer_size;
  184476. else
  184477. text_size = png_ptr->current_text_left;
  184478. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  184479. png_ptr->current_text_left -= text_size;
  184480. png_ptr->current_text_ptr += text_size;
  184481. }
  184482. if (!(png_ptr->current_text_left))
  184483. {
  184484. png_textp text_ptr;
  184485. png_charp key;
  184486. int comp_flag;
  184487. png_charp lang;
  184488. png_charp lang_key;
  184489. png_charp text;
  184490. int ret;
  184491. if (png_ptr->buffer_size < 4)
  184492. {
  184493. png_push_save_buffer(png_ptr);
  184494. return;
  184495. }
  184496. png_push_crc_finish(png_ptr);
  184497. #if defined(PNG_MAX_MALLOC_64K)
  184498. if (png_ptr->skip_length)
  184499. return;
  184500. #endif
  184501. key = png_ptr->current_text;
  184502. for (lang = key; *lang; lang++)
  184503. /* empty loop */ ;
  184504. if (lang < key + png_ptr->current_text_size - 3)
  184505. lang++;
  184506. comp_flag = *lang++;
  184507. lang++; /* skip comp_type, always zero */
  184508. for (lang_key = lang; *lang_key; lang_key++)
  184509. /* empty loop */ ;
  184510. lang_key++; /* skip NUL separator */
  184511. text=lang_key;
  184512. if (lang_key < key + png_ptr->current_text_size - 1)
  184513. {
  184514. for (; *text; text++)
  184515. /* empty loop */ ;
  184516. }
  184517. if (text < key + png_ptr->current_text_size)
  184518. text++;
  184519. text_ptr = (png_textp)png_malloc(png_ptr,
  184520. (png_uint_32)png_sizeof(png_text));
  184521. text_ptr->compression = comp_flag + 2;
  184522. text_ptr->key = key;
  184523. text_ptr->lang = lang;
  184524. text_ptr->lang_key = lang_key;
  184525. text_ptr->text = text;
  184526. text_ptr->text_length = 0;
  184527. text_ptr->itxt_length = png_strlen(text);
  184528. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  184529. png_ptr->current_text = NULL;
  184530. png_free(png_ptr, text_ptr);
  184531. if (ret)
  184532. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  184533. }
  184534. }
  184535. #endif
  184536. /* This function is called when we haven't found a handler for this
  184537. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  184538. * name or a critical chunk), the chunk is (currently) silently ignored.
  184539. */
  184540. void /* PRIVATE */
  184541. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  184542. length)
  184543. {
  184544. png_uint_32 skip=0;
  184545. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  184546. if (!(png_ptr->chunk_name[0] & 0x20))
  184547. {
  184548. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  184549. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  184550. PNG_HANDLE_CHUNK_ALWAYS
  184551. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  184552. && png_ptr->read_user_chunk_fn == NULL
  184553. #endif
  184554. )
  184555. #endif
  184556. png_chunk_error(png_ptr, "unknown critical chunk");
  184557. info_ptr = info_ptr; /* to quiet some compiler warnings */
  184558. }
  184559. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  184560. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  184561. {
  184562. #ifdef PNG_MAX_MALLOC_64K
  184563. if (length > (png_uint_32)65535L)
  184564. {
  184565. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  184566. skip = length - (png_uint_32)65535L;
  184567. length = (png_uint_32)65535L;
  184568. }
  184569. #endif
  184570. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  184571. (png_charp)png_ptr->chunk_name, 5);
  184572. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  184573. png_ptr->unknown_chunk.size = (png_size_t)length;
  184574. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  184575. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  184576. if(png_ptr->read_user_chunk_fn != NULL)
  184577. {
  184578. /* callback to user unknown chunk handler */
  184579. int ret;
  184580. ret = (*(png_ptr->read_user_chunk_fn))
  184581. (png_ptr, &png_ptr->unknown_chunk);
  184582. if (ret < 0)
  184583. png_chunk_error(png_ptr, "error in user chunk");
  184584. if (ret == 0)
  184585. {
  184586. if (!(png_ptr->chunk_name[0] & 0x20))
  184587. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  184588. PNG_HANDLE_CHUNK_ALWAYS)
  184589. png_chunk_error(png_ptr, "unknown critical chunk");
  184590. png_set_unknown_chunks(png_ptr, info_ptr,
  184591. &png_ptr->unknown_chunk, 1);
  184592. }
  184593. }
  184594. #else
  184595. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  184596. #endif
  184597. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184598. png_ptr->unknown_chunk.data = NULL;
  184599. }
  184600. else
  184601. #endif
  184602. skip=length;
  184603. png_push_crc_skip(png_ptr, skip);
  184604. }
  184605. void /* PRIVATE */
  184606. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  184607. {
  184608. if (png_ptr->info_fn != NULL)
  184609. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  184610. }
  184611. void /* PRIVATE */
  184612. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  184613. {
  184614. if (png_ptr->end_fn != NULL)
  184615. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  184616. }
  184617. void /* PRIVATE */
  184618. png_push_have_row(png_structp png_ptr, png_bytep row)
  184619. {
  184620. if (png_ptr->row_fn != NULL)
  184621. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  184622. (int)png_ptr->pass);
  184623. }
  184624. void PNGAPI
  184625. png_progressive_combine_row (png_structp png_ptr,
  184626. png_bytep old_row, png_bytep new_row)
  184627. {
  184628. #ifdef PNG_USE_LOCAL_ARRAYS
  184629. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  184630. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184631. #endif
  184632. if(png_ptr == NULL) return;
  184633. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  184634. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  184635. }
  184636. void PNGAPI
  184637. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  184638. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  184639. png_progressive_end_ptr end_fn)
  184640. {
  184641. if(png_ptr == NULL) return;
  184642. png_ptr->info_fn = info_fn;
  184643. png_ptr->row_fn = row_fn;
  184644. png_ptr->end_fn = end_fn;
  184645. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  184646. }
  184647. png_voidp PNGAPI
  184648. png_get_progressive_ptr(png_structp png_ptr)
  184649. {
  184650. if(png_ptr == NULL) return (NULL);
  184651. return png_ptr->io_ptr;
  184652. }
  184653. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184654. /********* End of inlined file: pngpread.c *********/
  184655. /********* Start of inlined file: pngrio.c *********/
  184656. /* pngrio.c - functions for data input
  184657. *
  184658. * Last changed in libpng 1.2.13 November 13, 2006
  184659. * For conditions of distribution and use, see copyright notice in png.h
  184660. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  184661. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184662. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184663. *
  184664. * This file provides a location for all input. Users who need
  184665. * special handling are expected to write a function that has the same
  184666. * arguments as this and performs a similar function, but that possibly
  184667. * has a different input method. Note that you shouldn't change this
  184668. * function, but rather write a replacement function and then make
  184669. * libpng use it at run time with png_set_read_fn(...).
  184670. */
  184671. #define PNG_INTERNAL
  184672. #if defined(PNG_READ_SUPPORTED)
  184673. /* Read the data from whatever input you are using. The default routine
  184674. reads from a file pointer. Note that this routine sometimes gets called
  184675. with very small lengths, so you should implement some kind of simple
  184676. buffering if you are using unbuffered reads. This should never be asked
  184677. to read more then 64K on a 16 bit machine. */
  184678. void /* PRIVATE */
  184679. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  184680. {
  184681. png_debug1(4,"reading %d bytes\n", (int)length);
  184682. if (png_ptr->read_data_fn != NULL)
  184683. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  184684. else
  184685. png_error(png_ptr, "Call to NULL read function");
  184686. }
  184687. #if !defined(PNG_NO_STDIO)
  184688. /* This is the function that does the actual reading of data. If you are
  184689. not reading from a standard C stream, you should create a replacement
  184690. read_data function and use it at run time with png_set_read_fn(), rather
  184691. than changing the library. */
  184692. #ifndef USE_FAR_KEYWORD
  184693. void PNGAPI
  184694. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  184695. {
  184696. png_size_t check;
  184697. if(png_ptr == NULL) return;
  184698. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  184699. * instead of an int, which is what fread() actually returns.
  184700. */
  184701. #if defined(_WIN32_WCE)
  184702. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  184703. check = 0;
  184704. #else
  184705. check = (png_size_t)fread(data, (png_size_t)1, length,
  184706. (png_FILE_p)png_ptr->io_ptr);
  184707. #endif
  184708. if (check != length)
  184709. png_error(png_ptr, "Read Error");
  184710. }
  184711. #else
  184712. /* this is the model-independent version. Since the standard I/O library
  184713. can't handle far buffers in the medium and small models, we have to copy
  184714. the data.
  184715. */
  184716. #define NEAR_BUF_SIZE 1024
  184717. #define MIN(a,b) (a <= b ? a : b)
  184718. static void PNGAPI
  184719. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  184720. {
  184721. int check;
  184722. png_byte *n_data;
  184723. png_FILE_p io_ptr;
  184724. if(png_ptr == NULL) return;
  184725. /* Check if data really is near. If so, use usual code. */
  184726. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  184727. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  184728. if ((png_bytep)n_data == data)
  184729. {
  184730. #if defined(_WIN32_WCE)
  184731. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  184732. check = 0;
  184733. #else
  184734. check = fread(n_data, 1, length, io_ptr);
  184735. #endif
  184736. }
  184737. else
  184738. {
  184739. png_byte buf[NEAR_BUF_SIZE];
  184740. png_size_t read, remaining, err;
  184741. check = 0;
  184742. remaining = length;
  184743. do
  184744. {
  184745. read = MIN(NEAR_BUF_SIZE, remaining);
  184746. #if defined(_WIN32_WCE)
  184747. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  184748. err = 0;
  184749. #else
  184750. err = fread(buf, (png_size_t)1, read, io_ptr);
  184751. #endif
  184752. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  184753. if(err != read)
  184754. break;
  184755. else
  184756. check += err;
  184757. data += read;
  184758. remaining -= read;
  184759. }
  184760. while (remaining != 0);
  184761. }
  184762. if ((png_uint_32)check != (png_uint_32)length)
  184763. png_error(png_ptr, "read Error");
  184764. }
  184765. #endif
  184766. #endif
  184767. /* This function allows the application to supply a new input function
  184768. for libpng if standard C streams aren't being used.
  184769. This function takes as its arguments:
  184770. png_ptr - pointer to a png input data structure
  184771. io_ptr - pointer to user supplied structure containing info about
  184772. the input functions. May be NULL.
  184773. read_data_fn - pointer to a new input function that takes as its
  184774. arguments a pointer to a png_struct, a pointer to
  184775. a location where input data can be stored, and a 32-bit
  184776. unsigned int that is the number of bytes to be read.
  184777. To exit and output any fatal error messages the new write
  184778. function should call png_error(png_ptr, "Error msg"). */
  184779. void PNGAPI
  184780. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  184781. png_rw_ptr read_data_fn)
  184782. {
  184783. if(png_ptr == NULL) return;
  184784. png_ptr->io_ptr = io_ptr;
  184785. #if !defined(PNG_NO_STDIO)
  184786. if (read_data_fn != NULL)
  184787. png_ptr->read_data_fn = read_data_fn;
  184788. else
  184789. png_ptr->read_data_fn = png_default_read_data;
  184790. #else
  184791. png_ptr->read_data_fn = read_data_fn;
  184792. #endif
  184793. /* It is an error to write to a read device */
  184794. if (png_ptr->write_data_fn != NULL)
  184795. {
  184796. png_ptr->write_data_fn = NULL;
  184797. png_warning(png_ptr,
  184798. "It's an error to set both read_data_fn and write_data_fn in the ");
  184799. png_warning(png_ptr,
  184800. "same structure. Resetting write_data_fn to NULL.");
  184801. }
  184802. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184803. png_ptr->output_flush_fn = NULL;
  184804. #endif
  184805. }
  184806. #endif /* PNG_READ_SUPPORTED */
  184807. /********* End of inlined file: pngrio.c *********/
  184808. /********* Start of inlined file: pngrtran.c *********/
  184809. /* pngrtran.c - transforms the data in a row for PNG readers
  184810. *
  184811. * Last changed in libpng 1.2.21 [October 4, 2007]
  184812. * For conditions of distribution and use, see copyright notice in png.h
  184813. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184814. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184815. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184816. *
  184817. * This file contains functions optionally called by an application
  184818. * in order to tell libpng how to handle data when reading a PNG.
  184819. * Transformations that are used in both reading and writing are
  184820. * in pngtrans.c.
  184821. */
  184822. #define PNG_INTERNAL
  184823. #if defined(PNG_READ_SUPPORTED)
  184824. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  184825. void PNGAPI
  184826. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  184827. {
  184828. png_debug(1, "in png_set_crc_action\n");
  184829. /* Tell libpng how we react to CRC errors in critical chunks */
  184830. if(png_ptr == NULL) return;
  184831. switch (crit_action)
  184832. {
  184833. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  184834. break;
  184835. case PNG_CRC_WARN_USE: /* warn/use data */
  184836. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  184837. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  184838. break;
  184839. case PNG_CRC_QUIET_USE: /* quiet/use data */
  184840. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  184841. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  184842. PNG_FLAG_CRC_CRITICAL_IGNORE;
  184843. break;
  184844. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  184845. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  184846. case PNG_CRC_ERROR_QUIT: /* error/quit */
  184847. case PNG_CRC_DEFAULT:
  184848. default:
  184849. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  184850. break;
  184851. }
  184852. switch (ancil_action)
  184853. {
  184854. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  184855. break;
  184856. case PNG_CRC_WARN_USE: /* warn/use data */
  184857. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  184858. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  184859. break;
  184860. case PNG_CRC_QUIET_USE: /* quiet/use data */
  184861. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  184862. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  184863. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  184864. break;
  184865. case PNG_CRC_ERROR_QUIT: /* error/quit */
  184866. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  184867. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  184868. break;
  184869. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  184870. case PNG_CRC_DEFAULT:
  184871. default:
  184872. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  184873. break;
  184874. }
  184875. }
  184876. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  184877. defined(PNG_FLOATING_POINT_SUPPORTED)
  184878. /* handle alpha and tRNS via a background color */
  184879. void PNGAPI
  184880. png_set_background(png_structp png_ptr,
  184881. png_color_16p background_color, int background_gamma_code,
  184882. int need_expand, double background_gamma)
  184883. {
  184884. png_debug(1, "in png_set_background\n");
  184885. if(png_ptr == NULL) return;
  184886. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  184887. {
  184888. png_warning(png_ptr, "Application must supply a known background gamma");
  184889. return;
  184890. }
  184891. png_ptr->transformations |= PNG_BACKGROUND;
  184892. png_memcpy(&(png_ptr->background), background_color,
  184893. png_sizeof(png_color_16));
  184894. png_ptr->background_gamma = (float)background_gamma;
  184895. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  184896. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  184897. }
  184898. #endif
  184899. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184900. /* strip 16 bit depth files to 8 bit depth */
  184901. void PNGAPI
  184902. png_set_strip_16(png_structp png_ptr)
  184903. {
  184904. png_debug(1, "in png_set_strip_16\n");
  184905. if(png_ptr == NULL) return;
  184906. png_ptr->transformations |= PNG_16_TO_8;
  184907. }
  184908. #endif
  184909. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184910. void PNGAPI
  184911. png_set_strip_alpha(png_structp png_ptr)
  184912. {
  184913. png_debug(1, "in png_set_strip_alpha\n");
  184914. if(png_ptr == NULL) return;
  184915. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  184916. }
  184917. #endif
  184918. #if defined(PNG_READ_DITHER_SUPPORTED)
  184919. /* Dither file to 8 bit. Supply a palette, the current number
  184920. * of elements in the palette, the maximum number of elements
  184921. * allowed, and a histogram if possible. If the current number
  184922. * of colors is greater then the maximum number, the palette will be
  184923. * modified to fit in the maximum number. "full_dither" indicates
  184924. * whether we need a dithering cube set up for RGB images, or if we
  184925. * simply are reducing the number of colors in a paletted image.
  184926. */
  184927. typedef struct png_dsort_struct
  184928. {
  184929. struct png_dsort_struct FAR * next;
  184930. png_byte left;
  184931. png_byte right;
  184932. } png_dsort;
  184933. typedef png_dsort FAR * png_dsortp;
  184934. typedef png_dsort FAR * FAR * png_dsortpp;
  184935. void PNGAPI
  184936. png_set_dither(png_structp png_ptr, png_colorp palette,
  184937. int num_palette, int maximum_colors, png_uint_16p histogram,
  184938. int full_dither)
  184939. {
  184940. png_debug(1, "in png_set_dither\n");
  184941. if(png_ptr == NULL) return;
  184942. png_ptr->transformations |= PNG_DITHER;
  184943. if (!full_dither)
  184944. {
  184945. int i;
  184946. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  184947. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  184948. for (i = 0; i < num_palette; i++)
  184949. png_ptr->dither_index[i] = (png_byte)i;
  184950. }
  184951. if (num_palette > maximum_colors)
  184952. {
  184953. if (histogram != NULL)
  184954. {
  184955. /* This is easy enough, just throw out the least used colors.
  184956. Perhaps not the best solution, but good enough. */
  184957. int i;
  184958. /* initialize an array to sort colors */
  184959. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  184960. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  184961. /* initialize the dither_sort array */
  184962. for (i = 0; i < num_palette; i++)
  184963. png_ptr->dither_sort[i] = (png_byte)i;
  184964. /* Find the least used palette entries by starting a
  184965. bubble sort, and running it until we have sorted
  184966. out enough colors. Note that we don't care about
  184967. sorting all the colors, just finding which are
  184968. least used. */
  184969. for (i = num_palette - 1; i >= maximum_colors; i--)
  184970. {
  184971. int done; /* to stop early if the list is pre-sorted */
  184972. int j;
  184973. done = 1;
  184974. for (j = 0; j < i; j++)
  184975. {
  184976. if (histogram[png_ptr->dither_sort[j]]
  184977. < histogram[png_ptr->dither_sort[j + 1]])
  184978. {
  184979. png_byte t;
  184980. t = png_ptr->dither_sort[j];
  184981. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  184982. png_ptr->dither_sort[j + 1] = t;
  184983. done = 0;
  184984. }
  184985. }
  184986. if (done)
  184987. break;
  184988. }
  184989. /* swap the palette around, and set up a table, if necessary */
  184990. if (full_dither)
  184991. {
  184992. int j = num_palette;
  184993. /* put all the useful colors within the max, but don't
  184994. move the others */
  184995. for (i = 0; i < maximum_colors; i++)
  184996. {
  184997. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  184998. {
  184999. do
  185000. j--;
  185001. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  185002. palette[i] = palette[j];
  185003. }
  185004. }
  185005. }
  185006. else
  185007. {
  185008. int j = num_palette;
  185009. /* move all the used colors inside the max limit, and
  185010. develop a translation table */
  185011. for (i = 0; i < maximum_colors; i++)
  185012. {
  185013. /* only move the colors we need to */
  185014. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  185015. {
  185016. png_color tmp_color;
  185017. do
  185018. j--;
  185019. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  185020. tmp_color = palette[j];
  185021. palette[j] = palette[i];
  185022. palette[i] = tmp_color;
  185023. /* indicate where the color went */
  185024. png_ptr->dither_index[j] = (png_byte)i;
  185025. png_ptr->dither_index[i] = (png_byte)j;
  185026. }
  185027. }
  185028. /* find closest color for those colors we are not using */
  185029. for (i = 0; i < num_palette; i++)
  185030. {
  185031. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  185032. {
  185033. int min_d, k, min_k, d_index;
  185034. /* find the closest color to one we threw out */
  185035. d_index = png_ptr->dither_index[i];
  185036. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  185037. for (k = 1, min_k = 0; k < maximum_colors; k++)
  185038. {
  185039. int d;
  185040. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  185041. if (d < min_d)
  185042. {
  185043. min_d = d;
  185044. min_k = k;
  185045. }
  185046. }
  185047. /* point to closest color */
  185048. png_ptr->dither_index[i] = (png_byte)min_k;
  185049. }
  185050. }
  185051. }
  185052. png_free(png_ptr, png_ptr->dither_sort);
  185053. png_ptr->dither_sort=NULL;
  185054. }
  185055. else
  185056. {
  185057. /* This is much harder to do simply (and quickly). Perhaps
  185058. we need to go through a median cut routine, but those
  185059. don't always behave themselves with only a few colors
  185060. as input. So we will just find the closest two colors,
  185061. and throw out one of them (chosen somewhat randomly).
  185062. [We don't understand this at all, so if someone wants to
  185063. work on improving it, be our guest - AED, GRP]
  185064. */
  185065. int i;
  185066. int max_d;
  185067. int num_new_palette;
  185068. png_dsortp t;
  185069. png_dsortpp hash;
  185070. t=NULL;
  185071. /* initialize palette index arrays */
  185072. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  185073. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185074. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  185075. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185076. /* initialize the sort array */
  185077. for (i = 0; i < num_palette; i++)
  185078. {
  185079. png_ptr->index_to_palette[i] = (png_byte)i;
  185080. png_ptr->palette_to_index[i] = (png_byte)i;
  185081. }
  185082. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  185083. png_sizeof (png_dsortp)));
  185084. for (i = 0; i < 769; i++)
  185085. hash[i] = NULL;
  185086. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  185087. num_new_palette = num_palette;
  185088. /* initial wild guess at how far apart the farthest pixel
  185089. pair we will be eliminating will be. Larger
  185090. numbers mean more areas will be allocated, Smaller
  185091. numbers run the risk of not saving enough data, and
  185092. having to do this all over again.
  185093. I have not done extensive checking on this number.
  185094. */
  185095. max_d = 96;
  185096. while (num_new_palette > maximum_colors)
  185097. {
  185098. for (i = 0; i < num_new_palette - 1; i++)
  185099. {
  185100. int j;
  185101. for (j = i + 1; j < num_new_palette; j++)
  185102. {
  185103. int d;
  185104. d = PNG_COLOR_DIST(palette[i], palette[j]);
  185105. if (d <= max_d)
  185106. {
  185107. t = (png_dsortp)png_malloc_warn(png_ptr,
  185108. (png_uint_32)(png_sizeof(png_dsort)));
  185109. if (t == NULL)
  185110. break;
  185111. t->next = hash[d];
  185112. t->left = (png_byte)i;
  185113. t->right = (png_byte)j;
  185114. hash[d] = t;
  185115. }
  185116. }
  185117. if (t == NULL)
  185118. break;
  185119. }
  185120. if (t != NULL)
  185121. for (i = 0; i <= max_d; i++)
  185122. {
  185123. if (hash[i] != NULL)
  185124. {
  185125. png_dsortp p;
  185126. for (p = hash[i]; p; p = p->next)
  185127. {
  185128. if ((int)png_ptr->index_to_palette[p->left]
  185129. < num_new_palette &&
  185130. (int)png_ptr->index_to_palette[p->right]
  185131. < num_new_palette)
  185132. {
  185133. int j, next_j;
  185134. if (num_new_palette & 0x01)
  185135. {
  185136. j = p->left;
  185137. next_j = p->right;
  185138. }
  185139. else
  185140. {
  185141. j = p->right;
  185142. next_j = p->left;
  185143. }
  185144. num_new_palette--;
  185145. palette[png_ptr->index_to_palette[j]]
  185146. = palette[num_new_palette];
  185147. if (!full_dither)
  185148. {
  185149. int k;
  185150. for (k = 0; k < num_palette; k++)
  185151. {
  185152. if (png_ptr->dither_index[k] ==
  185153. png_ptr->index_to_palette[j])
  185154. png_ptr->dither_index[k] =
  185155. png_ptr->index_to_palette[next_j];
  185156. if ((int)png_ptr->dither_index[k] ==
  185157. num_new_palette)
  185158. png_ptr->dither_index[k] =
  185159. png_ptr->index_to_palette[j];
  185160. }
  185161. }
  185162. png_ptr->index_to_palette[png_ptr->palette_to_index
  185163. [num_new_palette]] = png_ptr->index_to_palette[j];
  185164. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  185165. = png_ptr->palette_to_index[num_new_palette];
  185166. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  185167. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  185168. }
  185169. if (num_new_palette <= maximum_colors)
  185170. break;
  185171. }
  185172. if (num_new_palette <= maximum_colors)
  185173. break;
  185174. }
  185175. }
  185176. for (i = 0; i < 769; i++)
  185177. {
  185178. if (hash[i] != NULL)
  185179. {
  185180. png_dsortp p = hash[i];
  185181. while (p)
  185182. {
  185183. t = p->next;
  185184. png_free(png_ptr, p);
  185185. p = t;
  185186. }
  185187. }
  185188. hash[i] = 0;
  185189. }
  185190. max_d += 96;
  185191. }
  185192. png_free(png_ptr, hash);
  185193. png_free(png_ptr, png_ptr->palette_to_index);
  185194. png_free(png_ptr, png_ptr->index_to_palette);
  185195. png_ptr->palette_to_index=NULL;
  185196. png_ptr->index_to_palette=NULL;
  185197. }
  185198. num_palette = maximum_colors;
  185199. }
  185200. if (png_ptr->palette == NULL)
  185201. {
  185202. png_ptr->palette = palette;
  185203. }
  185204. png_ptr->num_palette = (png_uint_16)num_palette;
  185205. if (full_dither)
  185206. {
  185207. int i;
  185208. png_bytep distance;
  185209. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  185210. PNG_DITHER_BLUE_BITS;
  185211. int num_red = (1 << PNG_DITHER_RED_BITS);
  185212. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  185213. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  185214. png_size_t num_entries = ((png_size_t)1 << total_bits);
  185215. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  185216. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  185217. png_memset(png_ptr->palette_lookup, 0, num_entries *
  185218. png_sizeof (png_byte));
  185219. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  185220. png_sizeof(png_byte)));
  185221. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  185222. for (i = 0; i < num_palette; i++)
  185223. {
  185224. int ir, ig, ib;
  185225. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  185226. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  185227. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  185228. for (ir = 0; ir < num_red; ir++)
  185229. {
  185230. /* int dr = abs(ir - r); */
  185231. int dr = ((ir > r) ? ir - r : r - ir);
  185232. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  185233. for (ig = 0; ig < num_green; ig++)
  185234. {
  185235. /* int dg = abs(ig - g); */
  185236. int dg = ((ig > g) ? ig - g : g - ig);
  185237. int dt = dr + dg;
  185238. int dm = ((dr > dg) ? dr : dg);
  185239. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  185240. for (ib = 0; ib < num_blue; ib++)
  185241. {
  185242. int d_index = index_g | ib;
  185243. /* int db = abs(ib - b); */
  185244. int db = ((ib > b) ? ib - b : b - ib);
  185245. int dmax = ((dm > db) ? dm : db);
  185246. int d = dmax + dt + db;
  185247. if (d < (int)distance[d_index])
  185248. {
  185249. distance[d_index] = (png_byte)d;
  185250. png_ptr->palette_lookup[d_index] = (png_byte)i;
  185251. }
  185252. }
  185253. }
  185254. }
  185255. }
  185256. png_free(png_ptr, distance);
  185257. }
  185258. }
  185259. #endif
  185260. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185261. /* Transform the image from the file_gamma to the screen_gamma. We
  185262. * only do transformations on images where the file_gamma and screen_gamma
  185263. * are not close reciprocals, otherwise it slows things down slightly, and
  185264. * also needlessly introduces small errors.
  185265. *
  185266. * We will turn off gamma transformation later if no semitransparent entries
  185267. * are present in the tRNS array for palette images. We can't do it here
  185268. * because we don't necessarily have the tRNS chunk yet.
  185269. */
  185270. void PNGAPI
  185271. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  185272. {
  185273. png_debug(1, "in png_set_gamma\n");
  185274. if(png_ptr == NULL) return;
  185275. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  185276. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  185277. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  185278. png_ptr->transformations |= PNG_GAMMA;
  185279. png_ptr->gamma = (float)file_gamma;
  185280. png_ptr->screen_gamma = (float)scrn_gamma;
  185281. }
  185282. #endif
  185283. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185284. /* Expand paletted images to RGB, expand grayscale images of
  185285. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  185286. * to alpha channels.
  185287. */
  185288. void PNGAPI
  185289. png_set_expand(png_structp png_ptr)
  185290. {
  185291. png_debug(1, "in png_set_expand\n");
  185292. if(png_ptr == NULL) return;
  185293. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  185294. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185295. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  185296. #endif
  185297. }
  185298. /* GRR 19990627: the following three functions currently are identical
  185299. * to png_set_expand(). However, it is entirely reasonable that someone
  185300. * might wish to expand an indexed image to RGB but *not* expand a single,
  185301. * fully transparent palette entry to a full alpha channel--perhaps instead
  185302. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  185303. * the transparent color with a particular RGB value, or drop tRNS entirely.
  185304. * IOW, a future version of the library may make the transformations flag
  185305. * a bit more fine-grained, with separate bits for each of these three
  185306. * functions.
  185307. *
  185308. * More to the point, these functions make it obvious what libpng will be
  185309. * doing, whereas "expand" can (and does) mean any number of things.
  185310. *
  185311. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  185312. * to expand only the sample depth but not to expand the tRNS to alpha.
  185313. */
  185314. /* Expand paletted images to RGB. */
  185315. void PNGAPI
  185316. png_set_palette_to_rgb(png_structp png_ptr)
  185317. {
  185318. png_debug(1, "in png_set_palette_to_rgb\n");
  185319. if(png_ptr == NULL) return;
  185320. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  185321. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185322. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  185323. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  185324. #endif
  185325. }
  185326. #if !defined(PNG_1_0_X)
  185327. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  185328. void PNGAPI
  185329. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  185330. {
  185331. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  185332. if(png_ptr == NULL) return;
  185333. png_ptr->transformations |= PNG_EXPAND;
  185334. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185335. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  185336. #endif
  185337. }
  185338. #endif
  185339. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  185340. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  185341. /* Deprecated as of libpng-1.2.9 */
  185342. void PNGAPI
  185343. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  185344. {
  185345. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  185346. if(png_ptr == NULL) return;
  185347. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  185348. }
  185349. #endif
  185350. /* Expand tRNS chunks to alpha channels. */
  185351. void PNGAPI
  185352. png_set_tRNS_to_alpha(png_structp png_ptr)
  185353. {
  185354. png_debug(1, "in png_set_tRNS_to_alpha\n");
  185355. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  185356. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185357. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  185358. #endif
  185359. }
  185360. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  185361. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185362. void PNGAPI
  185363. png_set_gray_to_rgb(png_structp png_ptr)
  185364. {
  185365. png_debug(1, "in png_set_gray_to_rgb\n");
  185366. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  185367. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185368. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  185369. #endif
  185370. }
  185371. #endif
  185372. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185373. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  185374. /* Convert a RGB image to a grayscale of the same width. This allows us,
  185375. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  185376. */
  185377. void PNGAPI
  185378. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  185379. double green)
  185380. {
  185381. int red_fixed = (int)((float)red*100000.0 + 0.5);
  185382. int green_fixed = (int)((float)green*100000.0 + 0.5);
  185383. if(png_ptr == NULL) return;
  185384. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  185385. }
  185386. #endif
  185387. void PNGAPI
  185388. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  185389. png_fixed_point red, png_fixed_point green)
  185390. {
  185391. png_debug(1, "in png_set_rgb_to_gray\n");
  185392. if(png_ptr == NULL) return;
  185393. switch(error_action)
  185394. {
  185395. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  185396. break;
  185397. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  185398. break;
  185399. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  185400. }
  185401. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185402. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185403. png_ptr->transformations |= PNG_EXPAND;
  185404. #else
  185405. {
  185406. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  185407. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  185408. }
  185409. #endif
  185410. {
  185411. png_uint_16 red_int, green_int;
  185412. if(red < 0 || green < 0)
  185413. {
  185414. red_int = 6968; /* .212671 * 32768 + .5 */
  185415. green_int = 23434; /* .715160 * 32768 + .5 */
  185416. }
  185417. else if(red + green < 100000L)
  185418. {
  185419. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  185420. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  185421. }
  185422. else
  185423. {
  185424. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  185425. red_int = 6968;
  185426. green_int = 23434;
  185427. }
  185428. png_ptr->rgb_to_gray_red_coeff = red_int;
  185429. png_ptr->rgb_to_gray_green_coeff = green_int;
  185430. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  185431. }
  185432. }
  185433. #endif
  185434. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  185435. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  185436. defined(PNG_LEGACY_SUPPORTED)
  185437. void PNGAPI
  185438. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  185439. read_user_transform_fn)
  185440. {
  185441. png_debug(1, "in png_set_read_user_transform_fn\n");
  185442. if(png_ptr == NULL) return;
  185443. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  185444. png_ptr->transformations |= PNG_USER_TRANSFORM;
  185445. png_ptr->read_user_transform_fn = read_user_transform_fn;
  185446. #endif
  185447. #ifdef PNG_LEGACY_SUPPORTED
  185448. if(read_user_transform_fn)
  185449. png_warning(png_ptr,
  185450. "This version of libpng does not support user transforms");
  185451. #endif
  185452. }
  185453. #endif
  185454. /* Initialize everything needed for the read. This includes modifying
  185455. * the palette.
  185456. */
  185457. void /* PRIVATE */
  185458. png_init_read_transformations(png_structp png_ptr)
  185459. {
  185460. png_debug(1, "in png_init_read_transformations\n");
  185461. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185462. if(png_ptr != NULL)
  185463. #endif
  185464. {
  185465. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  185466. || defined(PNG_READ_GAMMA_SUPPORTED)
  185467. int color_type = png_ptr->color_type;
  185468. #endif
  185469. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  185470. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185471. /* Detect gray background and attempt to enable optimization
  185472. * for gray --> RGB case */
  185473. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  185474. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  185475. * background color might actually be gray yet not be flagged as such.
  185476. * This is not a problem for the current code, which uses
  185477. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  185478. * png_do_gray_to_rgb() transformation.
  185479. */
  185480. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  185481. !(color_type & PNG_COLOR_MASK_COLOR))
  185482. {
  185483. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  185484. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  185485. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  185486. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  185487. png_ptr->background.red == png_ptr->background.green &&
  185488. png_ptr->background.red == png_ptr->background.blue)
  185489. {
  185490. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  185491. png_ptr->background.gray = png_ptr->background.red;
  185492. }
  185493. #endif
  185494. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  185495. (png_ptr->transformations & PNG_EXPAND))
  185496. {
  185497. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  185498. {
  185499. /* expand background and tRNS chunks */
  185500. switch (png_ptr->bit_depth)
  185501. {
  185502. case 1:
  185503. png_ptr->background.gray *= (png_uint_16)0xff;
  185504. png_ptr->background.red = png_ptr->background.green
  185505. = png_ptr->background.blue = png_ptr->background.gray;
  185506. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  185507. {
  185508. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  185509. png_ptr->trans_values.red = png_ptr->trans_values.green
  185510. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  185511. }
  185512. break;
  185513. case 2:
  185514. png_ptr->background.gray *= (png_uint_16)0x55;
  185515. png_ptr->background.red = png_ptr->background.green
  185516. = png_ptr->background.blue = png_ptr->background.gray;
  185517. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  185518. {
  185519. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  185520. png_ptr->trans_values.red = png_ptr->trans_values.green
  185521. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  185522. }
  185523. break;
  185524. case 4:
  185525. png_ptr->background.gray *= (png_uint_16)0x11;
  185526. png_ptr->background.red = png_ptr->background.green
  185527. = png_ptr->background.blue = png_ptr->background.gray;
  185528. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  185529. {
  185530. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  185531. png_ptr->trans_values.red = png_ptr->trans_values.green
  185532. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  185533. }
  185534. break;
  185535. case 8:
  185536. case 16:
  185537. png_ptr->background.red = png_ptr->background.green
  185538. = png_ptr->background.blue = png_ptr->background.gray;
  185539. break;
  185540. }
  185541. }
  185542. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  185543. {
  185544. png_ptr->background.red =
  185545. png_ptr->palette[png_ptr->background.index].red;
  185546. png_ptr->background.green =
  185547. png_ptr->palette[png_ptr->background.index].green;
  185548. png_ptr->background.blue =
  185549. png_ptr->palette[png_ptr->background.index].blue;
  185550. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  185551. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  185552. {
  185553. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185554. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  185555. #endif
  185556. {
  185557. /* invert the alpha channel (in tRNS) unless the pixels are
  185558. going to be expanded, in which case leave it for later */
  185559. int i,istop;
  185560. istop=(int)png_ptr->num_trans;
  185561. for (i=0; i<istop; i++)
  185562. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  185563. }
  185564. }
  185565. #endif
  185566. }
  185567. }
  185568. #endif
  185569. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  185570. png_ptr->background_1 = png_ptr->background;
  185571. #endif
  185572. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185573. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  185574. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  185575. < PNG_GAMMA_THRESHOLD))
  185576. {
  185577. int i,k;
  185578. k=0;
  185579. for (i=0; i<png_ptr->num_trans; i++)
  185580. {
  185581. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  185582. k=1; /* partial transparency is present */
  185583. }
  185584. if (k == 0)
  185585. png_ptr->transformations &= (~PNG_GAMMA);
  185586. }
  185587. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  185588. png_ptr->gamma != 0.0)
  185589. {
  185590. png_build_gamma_table(png_ptr);
  185591. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185592. if (png_ptr->transformations & PNG_BACKGROUND)
  185593. {
  185594. if (color_type == PNG_COLOR_TYPE_PALETTE)
  185595. {
  185596. /* could skip if no transparency and
  185597. */
  185598. png_color back, back_1;
  185599. png_colorp palette = png_ptr->palette;
  185600. int num_palette = png_ptr->num_palette;
  185601. int i;
  185602. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  185603. {
  185604. back.red = png_ptr->gamma_table[png_ptr->background.red];
  185605. back.green = png_ptr->gamma_table[png_ptr->background.green];
  185606. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  185607. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  185608. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  185609. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  185610. }
  185611. else
  185612. {
  185613. double g, gs;
  185614. switch (png_ptr->background_gamma_type)
  185615. {
  185616. case PNG_BACKGROUND_GAMMA_SCREEN:
  185617. g = (png_ptr->screen_gamma);
  185618. gs = 1.0;
  185619. break;
  185620. case PNG_BACKGROUND_GAMMA_FILE:
  185621. g = 1.0 / (png_ptr->gamma);
  185622. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  185623. break;
  185624. case PNG_BACKGROUND_GAMMA_UNIQUE:
  185625. g = 1.0 / (png_ptr->background_gamma);
  185626. gs = 1.0 / (png_ptr->background_gamma *
  185627. png_ptr->screen_gamma);
  185628. break;
  185629. default:
  185630. g = 1.0; /* back_1 */
  185631. gs = 1.0; /* back */
  185632. }
  185633. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  185634. {
  185635. back.red = (png_byte)png_ptr->background.red;
  185636. back.green = (png_byte)png_ptr->background.green;
  185637. back.blue = (png_byte)png_ptr->background.blue;
  185638. }
  185639. else
  185640. {
  185641. back.red = (png_byte)(pow(
  185642. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  185643. back.green = (png_byte)(pow(
  185644. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  185645. back.blue = (png_byte)(pow(
  185646. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  185647. }
  185648. back_1.red = (png_byte)(pow(
  185649. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  185650. back_1.green = (png_byte)(pow(
  185651. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  185652. back_1.blue = (png_byte)(pow(
  185653. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  185654. }
  185655. for (i = 0; i < num_palette; i++)
  185656. {
  185657. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  185658. {
  185659. if (png_ptr->trans[i] == 0)
  185660. {
  185661. palette[i] = back;
  185662. }
  185663. else /* if (png_ptr->trans[i] != 0xff) */
  185664. {
  185665. png_byte v, w;
  185666. v = png_ptr->gamma_to_1[palette[i].red];
  185667. png_composite(w, v, png_ptr->trans[i], back_1.red);
  185668. palette[i].red = png_ptr->gamma_from_1[w];
  185669. v = png_ptr->gamma_to_1[palette[i].green];
  185670. png_composite(w, v, png_ptr->trans[i], back_1.green);
  185671. palette[i].green = png_ptr->gamma_from_1[w];
  185672. v = png_ptr->gamma_to_1[palette[i].blue];
  185673. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  185674. palette[i].blue = png_ptr->gamma_from_1[w];
  185675. }
  185676. }
  185677. else
  185678. {
  185679. palette[i].red = png_ptr->gamma_table[palette[i].red];
  185680. palette[i].green = png_ptr->gamma_table[palette[i].green];
  185681. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  185682. }
  185683. }
  185684. }
  185685. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  185686. else
  185687. /* color_type != PNG_COLOR_TYPE_PALETTE */
  185688. {
  185689. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  185690. double g = 1.0;
  185691. double gs = 1.0;
  185692. switch (png_ptr->background_gamma_type)
  185693. {
  185694. case PNG_BACKGROUND_GAMMA_SCREEN:
  185695. g = (png_ptr->screen_gamma);
  185696. gs = 1.0;
  185697. break;
  185698. case PNG_BACKGROUND_GAMMA_FILE:
  185699. g = 1.0 / (png_ptr->gamma);
  185700. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  185701. break;
  185702. case PNG_BACKGROUND_GAMMA_UNIQUE:
  185703. g = 1.0 / (png_ptr->background_gamma);
  185704. gs = 1.0 / (png_ptr->background_gamma *
  185705. png_ptr->screen_gamma);
  185706. break;
  185707. }
  185708. png_ptr->background_1.gray = (png_uint_16)(pow(
  185709. (double)png_ptr->background.gray / m, g) * m + .5);
  185710. png_ptr->background.gray = (png_uint_16)(pow(
  185711. (double)png_ptr->background.gray / m, gs) * m + .5);
  185712. if ((png_ptr->background.red != png_ptr->background.green) ||
  185713. (png_ptr->background.red != png_ptr->background.blue) ||
  185714. (png_ptr->background.red != png_ptr->background.gray))
  185715. {
  185716. /* RGB or RGBA with color background */
  185717. png_ptr->background_1.red = (png_uint_16)(pow(
  185718. (double)png_ptr->background.red / m, g) * m + .5);
  185719. png_ptr->background_1.green = (png_uint_16)(pow(
  185720. (double)png_ptr->background.green / m, g) * m + .5);
  185721. png_ptr->background_1.blue = (png_uint_16)(pow(
  185722. (double)png_ptr->background.blue / m, g) * m + .5);
  185723. png_ptr->background.red = (png_uint_16)(pow(
  185724. (double)png_ptr->background.red / m, gs) * m + .5);
  185725. png_ptr->background.green = (png_uint_16)(pow(
  185726. (double)png_ptr->background.green / m, gs) * m + .5);
  185727. png_ptr->background.blue = (png_uint_16)(pow(
  185728. (double)png_ptr->background.blue / m, gs) * m + .5);
  185729. }
  185730. else
  185731. {
  185732. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  185733. png_ptr->background_1.red = png_ptr->background_1.green
  185734. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  185735. png_ptr->background.red = png_ptr->background.green
  185736. = png_ptr->background.blue = png_ptr->background.gray;
  185737. }
  185738. }
  185739. }
  185740. else
  185741. /* transformation does not include PNG_BACKGROUND */
  185742. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  185743. if (color_type == PNG_COLOR_TYPE_PALETTE)
  185744. {
  185745. png_colorp palette = png_ptr->palette;
  185746. int num_palette = png_ptr->num_palette;
  185747. int i;
  185748. for (i = 0; i < num_palette; i++)
  185749. {
  185750. palette[i].red = png_ptr->gamma_table[palette[i].red];
  185751. palette[i].green = png_ptr->gamma_table[palette[i].green];
  185752. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  185753. }
  185754. }
  185755. }
  185756. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185757. else
  185758. #endif
  185759. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  185760. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185761. /* No GAMMA transformation */
  185762. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  185763. (color_type == PNG_COLOR_TYPE_PALETTE))
  185764. {
  185765. int i;
  185766. int istop = (int)png_ptr->num_trans;
  185767. png_color back;
  185768. png_colorp palette = png_ptr->palette;
  185769. back.red = (png_byte)png_ptr->background.red;
  185770. back.green = (png_byte)png_ptr->background.green;
  185771. back.blue = (png_byte)png_ptr->background.blue;
  185772. for (i = 0; i < istop; i++)
  185773. {
  185774. if (png_ptr->trans[i] == 0)
  185775. {
  185776. palette[i] = back;
  185777. }
  185778. else if (png_ptr->trans[i] != 0xff)
  185779. {
  185780. /* The png_composite() macro is defined in png.h */
  185781. png_composite(palette[i].red, palette[i].red,
  185782. png_ptr->trans[i], back.red);
  185783. png_composite(palette[i].green, palette[i].green,
  185784. png_ptr->trans[i], back.green);
  185785. png_composite(palette[i].blue, palette[i].blue,
  185786. png_ptr->trans[i], back.blue);
  185787. }
  185788. }
  185789. }
  185790. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  185791. #if defined(PNG_READ_SHIFT_SUPPORTED)
  185792. if ((png_ptr->transformations & PNG_SHIFT) &&
  185793. (color_type == PNG_COLOR_TYPE_PALETTE))
  185794. {
  185795. png_uint_16 i;
  185796. png_uint_16 istop = png_ptr->num_palette;
  185797. int sr = 8 - png_ptr->sig_bit.red;
  185798. int sg = 8 - png_ptr->sig_bit.green;
  185799. int sb = 8 - png_ptr->sig_bit.blue;
  185800. if (sr < 0 || sr > 8)
  185801. sr = 0;
  185802. if (sg < 0 || sg > 8)
  185803. sg = 0;
  185804. if (sb < 0 || sb > 8)
  185805. sb = 0;
  185806. for (i = 0; i < istop; i++)
  185807. {
  185808. png_ptr->palette[i].red >>= sr;
  185809. png_ptr->palette[i].green >>= sg;
  185810. png_ptr->palette[i].blue >>= sb;
  185811. }
  185812. }
  185813. #endif /* PNG_READ_SHIFT_SUPPORTED */
  185814. }
  185815. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  185816. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  185817. if(png_ptr)
  185818. return;
  185819. #endif
  185820. }
  185821. /* Modify the info structure to reflect the transformations. The
  185822. * info should be updated so a PNG file could be written with it,
  185823. * assuming the transformations result in valid PNG data.
  185824. */
  185825. void /* PRIVATE */
  185826. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  185827. {
  185828. png_debug(1, "in png_read_transform_info\n");
  185829. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185830. if (png_ptr->transformations & PNG_EXPAND)
  185831. {
  185832. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185833. {
  185834. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  185835. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  185836. else
  185837. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  185838. info_ptr->bit_depth = 8;
  185839. info_ptr->num_trans = 0;
  185840. }
  185841. else
  185842. {
  185843. if (png_ptr->num_trans)
  185844. {
  185845. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  185846. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  185847. else
  185848. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  185849. }
  185850. if (info_ptr->bit_depth < 8)
  185851. info_ptr->bit_depth = 8;
  185852. info_ptr->num_trans = 0;
  185853. }
  185854. }
  185855. #endif
  185856. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185857. if (png_ptr->transformations & PNG_BACKGROUND)
  185858. {
  185859. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  185860. info_ptr->num_trans = 0;
  185861. info_ptr->background = png_ptr->background;
  185862. }
  185863. #endif
  185864. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185865. if (png_ptr->transformations & PNG_GAMMA)
  185866. {
  185867. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185868. info_ptr->gamma = png_ptr->gamma;
  185869. #endif
  185870. #ifdef PNG_FIXED_POINT_SUPPORTED
  185871. info_ptr->int_gamma = png_ptr->int_gamma;
  185872. #endif
  185873. }
  185874. #endif
  185875. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185876. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  185877. info_ptr->bit_depth = 8;
  185878. #endif
  185879. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185880. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  185881. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  185882. #endif
  185883. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185884. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  185885. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  185886. #endif
  185887. #if defined(PNG_READ_DITHER_SUPPORTED)
  185888. if (png_ptr->transformations & PNG_DITHER)
  185889. {
  185890. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  185891. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  185892. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  185893. {
  185894. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  185895. }
  185896. }
  185897. #endif
  185898. #if defined(PNG_READ_PACK_SUPPORTED)
  185899. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  185900. info_ptr->bit_depth = 8;
  185901. #endif
  185902. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185903. info_ptr->channels = 1;
  185904. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  185905. info_ptr->channels = 3;
  185906. else
  185907. info_ptr->channels = 1;
  185908. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185909. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  185910. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  185911. #endif
  185912. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  185913. info_ptr->channels++;
  185914. #if defined(PNG_READ_FILLER_SUPPORTED)
  185915. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  185916. if ((png_ptr->transformations & PNG_FILLER) &&
  185917. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  185918. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  185919. {
  185920. info_ptr->channels++;
  185921. /* if adding a true alpha channel not just filler */
  185922. #if !defined(PNG_1_0_X)
  185923. if (png_ptr->transformations & PNG_ADD_ALPHA)
  185924. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  185925. #endif
  185926. }
  185927. #endif
  185928. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  185929. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  185930. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  185931. {
  185932. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  185933. info_ptr->bit_depth = png_ptr->user_transform_depth;
  185934. if(info_ptr->channels < png_ptr->user_transform_channels)
  185935. info_ptr->channels = png_ptr->user_transform_channels;
  185936. }
  185937. #endif
  185938. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  185939. info_ptr->bit_depth);
  185940. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  185941. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  185942. if(png_ptr)
  185943. return;
  185944. #endif
  185945. }
  185946. /* Transform the row. The order of transformations is significant,
  185947. * and is very touchy. If you add a transformation, take care to
  185948. * decide how it fits in with the other transformations here.
  185949. */
  185950. void /* PRIVATE */
  185951. png_do_read_transformations(png_structp png_ptr)
  185952. {
  185953. png_debug(1, "in png_do_read_transformations\n");
  185954. if (png_ptr->row_buf == NULL)
  185955. {
  185956. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  185957. char msg[50];
  185958. png_snprintf2(msg, 50,
  185959. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  185960. png_ptr->pass);
  185961. png_error(png_ptr, msg);
  185962. #else
  185963. png_error(png_ptr, "NULL row buffer");
  185964. #endif
  185965. }
  185966. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185967. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  185968. /* Application has failed to call either png_read_start_image()
  185969. * or png_read_update_info() after setting transforms that expand
  185970. * pixels. This check added to libpng-1.2.19 */
  185971. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  185972. png_error(png_ptr, "Uninitialized row");
  185973. #else
  185974. png_warning(png_ptr, "Uninitialized row");
  185975. #endif
  185976. #endif
  185977. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185978. if (png_ptr->transformations & PNG_EXPAND)
  185979. {
  185980. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  185981. {
  185982. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185983. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  185984. }
  185985. else
  185986. {
  185987. if (png_ptr->num_trans &&
  185988. (png_ptr->transformations & PNG_EXPAND_tRNS))
  185989. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185990. &(png_ptr->trans_values));
  185991. else
  185992. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185993. NULL);
  185994. }
  185995. }
  185996. #endif
  185997. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185998. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  185999. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186000. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  186001. #endif
  186002. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186003. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  186004. {
  186005. int rgb_error =
  186006. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  186007. if(rgb_error)
  186008. {
  186009. png_ptr->rgb_to_gray_status=1;
  186010. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  186011. PNG_RGB_TO_GRAY_WARN)
  186012. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  186013. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  186014. PNG_RGB_TO_GRAY_ERR)
  186015. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  186016. }
  186017. }
  186018. #endif
  186019. /*
  186020. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  186021. In most cases, the "simple transparency" should be done prior to doing
  186022. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  186023. pixel is transparent. You would also need to make sure that the
  186024. transparency information is upgraded to RGB.
  186025. To summarize, the current flow is:
  186026. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  186027. with background "in place" if transparent,
  186028. convert to RGB if necessary
  186029. - Gray + alpha -> composite with gray background and remove alpha bytes,
  186030. convert to RGB if necessary
  186031. To support RGB backgrounds for gray images we need:
  186032. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  186033. 3 or 6 bytes and composite with background
  186034. "in place" if transparent (3x compare/pixel
  186035. compared to doing composite with gray bkgrnd)
  186036. - Gray + alpha -> convert to RGB + alpha, composite with background and
  186037. remove alpha bytes (3x float operations/pixel
  186038. compared with composite on gray background)
  186039. Greg's change will do this. The reason it wasn't done before is for
  186040. performance, as this increases the per-pixel operations. If we would check
  186041. in advance if the background was gray or RGB, and position the gray-to-RGB
  186042. transform appropriately, then it would save a lot of work/time.
  186043. */
  186044. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186045. /* if gray -> RGB, do so now only if background is non-gray; else do later
  186046. * for performance reasons */
  186047. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186048. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  186049. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186050. #endif
  186051. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186052. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  186053. ((png_ptr->num_trans != 0 ) ||
  186054. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  186055. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186056. &(png_ptr->trans_values), &(png_ptr->background)
  186057. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186058. , &(png_ptr->background_1),
  186059. png_ptr->gamma_table, png_ptr->gamma_from_1,
  186060. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  186061. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  186062. png_ptr->gamma_shift
  186063. #endif
  186064. );
  186065. #endif
  186066. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186067. if ((png_ptr->transformations & PNG_GAMMA) &&
  186068. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186069. !((png_ptr->transformations & PNG_BACKGROUND) &&
  186070. ((png_ptr->num_trans != 0) ||
  186071. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  186072. #endif
  186073. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  186074. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186075. png_ptr->gamma_table, png_ptr->gamma_16_table,
  186076. png_ptr->gamma_shift);
  186077. #endif
  186078. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186079. if (png_ptr->transformations & PNG_16_TO_8)
  186080. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186081. #endif
  186082. #if defined(PNG_READ_DITHER_SUPPORTED)
  186083. if (png_ptr->transformations & PNG_DITHER)
  186084. {
  186085. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  186086. png_ptr->palette_lookup, png_ptr->dither_index);
  186087. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  186088. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  186089. }
  186090. #endif
  186091. #if defined(PNG_READ_INVERT_SUPPORTED)
  186092. if (png_ptr->transformations & PNG_INVERT_MONO)
  186093. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186094. #endif
  186095. #if defined(PNG_READ_SHIFT_SUPPORTED)
  186096. if (png_ptr->transformations & PNG_SHIFT)
  186097. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186098. &(png_ptr->shift));
  186099. #endif
  186100. #if defined(PNG_READ_PACK_SUPPORTED)
  186101. if (png_ptr->transformations & PNG_PACK)
  186102. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186103. #endif
  186104. #if defined(PNG_READ_BGR_SUPPORTED)
  186105. if (png_ptr->transformations & PNG_BGR)
  186106. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186107. #endif
  186108. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  186109. if (png_ptr->transformations & PNG_PACKSWAP)
  186110. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186111. #endif
  186112. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186113. /* if gray -> RGB, do so now only if we did not do so above */
  186114. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186115. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  186116. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186117. #endif
  186118. #if defined(PNG_READ_FILLER_SUPPORTED)
  186119. if (png_ptr->transformations & PNG_FILLER)
  186120. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186121. (png_uint_32)png_ptr->filler, png_ptr->flags);
  186122. #endif
  186123. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  186124. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  186125. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186126. #endif
  186127. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  186128. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  186129. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186130. #endif
  186131. #if defined(PNG_READ_SWAP_SUPPORTED)
  186132. if (png_ptr->transformations & PNG_SWAP_BYTES)
  186133. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186134. #endif
  186135. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  186136. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  186137. {
  186138. if(png_ptr->read_user_transform_fn != NULL)
  186139. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  186140. (png_ptr, /* png_ptr */
  186141. &(png_ptr->row_info), /* row_info: */
  186142. /* png_uint_32 width; width of row */
  186143. /* png_uint_32 rowbytes; number of bytes in row */
  186144. /* png_byte color_type; color type of pixels */
  186145. /* png_byte bit_depth; bit depth of samples */
  186146. /* png_byte channels; number of channels (1-4) */
  186147. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  186148. png_ptr->row_buf + 1); /* start of pixel data for row */
  186149. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  186150. if(png_ptr->user_transform_depth)
  186151. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  186152. if(png_ptr->user_transform_channels)
  186153. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  186154. #endif
  186155. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  186156. png_ptr->row_info.channels);
  186157. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  186158. png_ptr->row_info.width);
  186159. }
  186160. #endif
  186161. }
  186162. #if defined(PNG_READ_PACK_SUPPORTED)
  186163. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  186164. * without changing the actual values. Thus, if you had a row with
  186165. * a bit depth of 1, you would end up with bytes that only contained
  186166. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  186167. * png_do_shift() after this.
  186168. */
  186169. void /* PRIVATE */
  186170. png_do_unpack(png_row_infop row_info, png_bytep row)
  186171. {
  186172. png_debug(1, "in png_do_unpack\n");
  186173. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186174. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  186175. #else
  186176. if (row_info->bit_depth < 8)
  186177. #endif
  186178. {
  186179. png_uint_32 i;
  186180. png_uint_32 row_width=row_info->width;
  186181. switch (row_info->bit_depth)
  186182. {
  186183. case 1:
  186184. {
  186185. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  186186. png_bytep dp = row + (png_size_t)row_width - 1;
  186187. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  186188. for (i = 0; i < row_width; i++)
  186189. {
  186190. *dp = (png_byte)((*sp >> shift) & 0x01);
  186191. if (shift == 7)
  186192. {
  186193. shift = 0;
  186194. sp--;
  186195. }
  186196. else
  186197. shift++;
  186198. dp--;
  186199. }
  186200. break;
  186201. }
  186202. case 2:
  186203. {
  186204. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  186205. png_bytep dp = row + (png_size_t)row_width - 1;
  186206. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  186207. for (i = 0; i < row_width; i++)
  186208. {
  186209. *dp = (png_byte)((*sp >> shift) & 0x03);
  186210. if (shift == 6)
  186211. {
  186212. shift = 0;
  186213. sp--;
  186214. }
  186215. else
  186216. shift += 2;
  186217. dp--;
  186218. }
  186219. break;
  186220. }
  186221. case 4:
  186222. {
  186223. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  186224. png_bytep dp = row + (png_size_t)row_width - 1;
  186225. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  186226. for (i = 0; i < row_width; i++)
  186227. {
  186228. *dp = (png_byte)((*sp >> shift) & 0x0f);
  186229. if (shift == 4)
  186230. {
  186231. shift = 0;
  186232. sp--;
  186233. }
  186234. else
  186235. shift = 4;
  186236. dp--;
  186237. }
  186238. break;
  186239. }
  186240. }
  186241. row_info->bit_depth = 8;
  186242. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  186243. row_info->rowbytes = row_width * row_info->channels;
  186244. }
  186245. }
  186246. #endif
  186247. #if defined(PNG_READ_SHIFT_SUPPORTED)
  186248. /* Reverse the effects of png_do_shift. This routine merely shifts the
  186249. * pixels back to their significant bits values. Thus, if you have
  186250. * a row of bit depth 8, but only 5 are significant, this will shift
  186251. * the values back to 0 through 31.
  186252. */
  186253. void /* PRIVATE */
  186254. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  186255. {
  186256. png_debug(1, "in png_do_unshift\n");
  186257. if (
  186258. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186259. row != NULL && row_info != NULL && sig_bits != NULL &&
  186260. #endif
  186261. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  186262. {
  186263. int shift[4];
  186264. int channels = 0;
  186265. int c;
  186266. png_uint_16 value = 0;
  186267. png_uint_32 row_width = row_info->width;
  186268. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  186269. {
  186270. shift[channels++] = row_info->bit_depth - sig_bits->red;
  186271. shift[channels++] = row_info->bit_depth - sig_bits->green;
  186272. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  186273. }
  186274. else
  186275. {
  186276. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  186277. }
  186278. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  186279. {
  186280. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  186281. }
  186282. for (c = 0; c < channels; c++)
  186283. {
  186284. if (shift[c] <= 0)
  186285. shift[c] = 0;
  186286. else
  186287. value = 1;
  186288. }
  186289. if (!value)
  186290. return;
  186291. switch (row_info->bit_depth)
  186292. {
  186293. case 2:
  186294. {
  186295. png_bytep bp;
  186296. png_uint_32 i;
  186297. png_uint_32 istop = row_info->rowbytes;
  186298. for (bp = row, i = 0; i < istop; i++)
  186299. {
  186300. *bp >>= 1;
  186301. *bp++ &= 0x55;
  186302. }
  186303. break;
  186304. }
  186305. case 4:
  186306. {
  186307. png_bytep bp = row;
  186308. png_uint_32 i;
  186309. png_uint_32 istop = row_info->rowbytes;
  186310. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  186311. (png_byte)((int)0xf >> shift[0]));
  186312. for (i = 0; i < istop; i++)
  186313. {
  186314. *bp >>= shift[0];
  186315. *bp++ &= mask;
  186316. }
  186317. break;
  186318. }
  186319. case 8:
  186320. {
  186321. png_bytep bp = row;
  186322. png_uint_32 i;
  186323. png_uint_32 istop = row_width * channels;
  186324. for (i = 0; i < istop; i++)
  186325. {
  186326. *bp++ >>= shift[i%channels];
  186327. }
  186328. break;
  186329. }
  186330. case 16:
  186331. {
  186332. png_bytep bp = row;
  186333. png_uint_32 i;
  186334. png_uint_32 istop = channels * row_width;
  186335. for (i = 0; i < istop; i++)
  186336. {
  186337. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  186338. value >>= shift[i%channels];
  186339. *bp++ = (png_byte)(value >> 8);
  186340. *bp++ = (png_byte)(value & 0xff);
  186341. }
  186342. break;
  186343. }
  186344. }
  186345. }
  186346. }
  186347. #endif
  186348. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186349. /* chop rows of bit depth 16 down to 8 */
  186350. void /* PRIVATE */
  186351. png_do_chop(png_row_infop row_info, png_bytep row)
  186352. {
  186353. png_debug(1, "in png_do_chop\n");
  186354. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186355. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  186356. #else
  186357. if (row_info->bit_depth == 16)
  186358. #endif
  186359. {
  186360. png_bytep sp = row;
  186361. png_bytep dp = row;
  186362. png_uint_32 i;
  186363. png_uint_32 istop = row_info->width * row_info->channels;
  186364. for (i = 0; i<istop; i++, sp += 2, dp++)
  186365. {
  186366. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  186367. /* This does a more accurate scaling of the 16-bit color
  186368. * value, rather than a simple low-byte truncation.
  186369. *
  186370. * What the ideal calculation should be:
  186371. * *dp = (((((png_uint_32)(*sp) << 8) |
  186372. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  186373. *
  186374. * GRR: no, I think this is what it really should be:
  186375. * *dp = (((((png_uint_32)(*sp) << 8) |
  186376. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  186377. *
  186378. * GRR: here's the exact calculation with shifts:
  186379. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  186380. * *dp = (temp - (temp >> 8)) >> 8;
  186381. *
  186382. * Approximate calculation with shift/add instead of multiply/divide:
  186383. * *dp = ((((png_uint_32)(*sp) << 8) |
  186384. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  186385. *
  186386. * What we actually do to avoid extra shifting and conversion:
  186387. */
  186388. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  186389. #else
  186390. /* Simply discard the low order byte */
  186391. *dp = *sp;
  186392. #endif
  186393. }
  186394. row_info->bit_depth = 8;
  186395. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  186396. row_info->rowbytes = row_info->width * row_info->channels;
  186397. }
  186398. }
  186399. #endif
  186400. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  186401. void /* PRIVATE */
  186402. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  186403. {
  186404. png_debug(1, "in png_do_read_swap_alpha\n");
  186405. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186406. if (row != NULL && row_info != NULL)
  186407. #endif
  186408. {
  186409. png_uint_32 row_width = row_info->width;
  186410. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  186411. {
  186412. /* This converts from RGBA to ARGB */
  186413. if (row_info->bit_depth == 8)
  186414. {
  186415. png_bytep sp = row + row_info->rowbytes;
  186416. png_bytep dp = sp;
  186417. png_byte save;
  186418. png_uint_32 i;
  186419. for (i = 0; i < row_width; i++)
  186420. {
  186421. save = *(--sp);
  186422. *(--dp) = *(--sp);
  186423. *(--dp) = *(--sp);
  186424. *(--dp) = *(--sp);
  186425. *(--dp) = save;
  186426. }
  186427. }
  186428. /* This converts from RRGGBBAA to AARRGGBB */
  186429. else
  186430. {
  186431. png_bytep sp = row + row_info->rowbytes;
  186432. png_bytep dp = sp;
  186433. png_byte save[2];
  186434. png_uint_32 i;
  186435. for (i = 0; i < row_width; i++)
  186436. {
  186437. save[0] = *(--sp);
  186438. save[1] = *(--sp);
  186439. *(--dp) = *(--sp);
  186440. *(--dp) = *(--sp);
  186441. *(--dp) = *(--sp);
  186442. *(--dp) = *(--sp);
  186443. *(--dp) = *(--sp);
  186444. *(--dp) = *(--sp);
  186445. *(--dp) = save[0];
  186446. *(--dp) = save[1];
  186447. }
  186448. }
  186449. }
  186450. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  186451. {
  186452. /* This converts from GA to AG */
  186453. if (row_info->bit_depth == 8)
  186454. {
  186455. png_bytep sp = row + row_info->rowbytes;
  186456. png_bytep dp = sp;
  186457. png_byte save;
  186458. png_uint_32 i;
  186459. for (i = 0; i < row_width; i++)
  186460. {
  186461. save = *(--sp);
  186462. *(--dp) = *(--sp);
  186463. *(--dp) = save;
  186464. }
  186465. }
  186466. /* This converts from GGAA to AAGG */
  186467. else
  186468. {
  186469. png_bytep sp = row + row_info->rowbytes;
  186470. png_bytep dp = sp;
  186471. png_byte save[2];
  186472. png_uint_32 i;
  186473. for (i = 0; i < row_width; i++)
  186474. {
  186475. save[0] = *(--sp);
  186476. save[1] = *(--sp);
  186477. *(--dp) = *(--sp);
  186478. *(--dp) = *(--sp);
  186479. *(--dp) = save[0];
  186480. *(--dp) = save[1];
  186481. }
  186482. }
  186483. }
  186484. }
  186485. }
  186486. #endif
  186487. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  186488. void /* PRIVATE */
  186489. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  186490. {
  186491. png_debug(1, "in png_do_read_invert_alpha\n");
  186492. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186493. if (row != NULL && row_info != NULL)
  186494. #endif
  186495. {
  186496. png_uint_32 row_width = row_info->width;
  186497. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  186498. {
  186499. /* This inverts the alpha channel in RGBA */
  186500. if (row_info->bit_depth == 8)
  186501. {
  186502. png_bytep sp = row + row_info->rowbytes;
  186503. png_bytep dp = sp;
  186504. png_uint_32 i;
  186505. for (i = 0; i < row_width; i++)
  186506. {
  186507. *(--dp) = (png_byte)(255 - *(--sp));
  186508. /* This does nothing:
  186509. *(--dp) = *(--sp);
  186510. *(--dp) = *(--sp);
  186511. *(--dp) = *(--sp);
  186512. We can replace it with:
  186513. */
  186514. sp-=3;
  186515. dp=sp;
  186516. }
  186517. }
  186518. /* This inverts the alpha channel in RRGGBBAA */
  186519. else
  186520. {
  186521. png_bytep sp = row + row_info->rowbytes;
  186522. png_bytep dp = sp;
  186523. png_uint_32 i;
  186524. for (i = 0; i < row_width; i++)
  186525. {
  186526. *(--dp) = (png_byte)(255 - *(--sp));
  186527. *(--dp) = (png_byte)(255 - *(--sp));
  186528. /* This does nothing:
  186529. *(--dp) = *(--sp);
  186530. *(--dp) = *(--sp);
  186531. *(--dp) = *(--sp);
  186532. *(--dp) = *(--sp);
  186533. *(--dp) = *(--sp);
  186534. *(--dp) = *(--sp);
  186535. We can replace it with:
  186536. */
  186537. sp-=6;
  186538. dp=sp;
  186539. }
  186540. }
  186541. }
  186542. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  186543. {
  186544. /* This inverts the alpha channel in GA */
  186545. if (row_info->bit_depth == 8)
  186546. {
  186547. png_bytep sp = row + row_info->rowbytes;
  186548. png_bytep dp = sp;
  186549. png_uint_32 i;
  186550. for (i = 0; i < row_width; i++)
  186551. {
  186552. *(--dp) = (png_byte)(255 - *(--sp));
  186553. *(--dp) = *(--sp);
  186554. }
  186555. }
  186556. /* This inverts the alpha channel in GGAA */
  186557. else
  186558. {
  186559. png_bytep sp = row + row_info->rowbytes;
  186560. png_bytep dp = sp;
  186561. png_uint_32 i;
  186562. for (i = 0; i < row_width; i++)
  186563. {
  186564. *(--dp) = (png_byte)(255 - *(--sp));
  186565. *(--dp) = (png_byte)(255 - *(--sp));
  186566. /*
  186567. *(--dp) = *(--sp);
  186568. *(--dp) = *(--sp);
  186569. */
  186570. sp-=2;
  186571. dp=sp;
  186572. }
  186573. }
  186574. }
  186575. }
  186576. }
  186577. #endif
  186578. #if defined(PNG_READ_FILLER_SUPPORTED)
  186579. /* Add filler channel if we have RGB color */
  186580. void /* PRIVATE */
  186581. png_do_read_filler(png_row_infop row_info, png_bytep row,
  186582. png_uint_32 filler, png_uint_32 flags)
  186583. {
  186584. png_uint_32 i;
  186585. png_uint_32 row_width = row_info->width;
  186586. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  186587. png_byte lo_filler = (png_byte)(filler & 0xff);
  186588. png_debug(1, "in png_do_read_filler\n");
  186589. if (
  186590. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186591. row != NULL && row_info != NULL &&
  186592. #endif
  186593. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  186594. {
  186595. if(row_info->bit_depth == 8)
  186596. {
  186597. /* This changes the data from G to GX */
  186598. if (flags & PNG_FLAG_FILLER_AFTER)
  186599. {
  186600. png_bytep sp = row + (png_size_t)row_width;
  186601. png_bytep dp = sp + (png_size_t)row_width;
  186602. for (i = 1; i < row_width; i++)
  186603. {
  186604. *(--dp) = lo_filler;
  186605. *(--dp) = *(--sp);
  186606. }
  186607. *(--dp) = lo_filler;
  186608. row_info->channels = 2;
  186609. row_info->pixel_depth = 16;
  186610. row_info->rowbytes = row_width * 2;
  186611. }
  186612. /* This changes the data from G to XG */
  186613. else
  186614. {
  186615. png_bytep sp = row + (png_size_t)row_width;
  186616. png_bytep dp = sp + (png_size_t)row_width;
  186617. for (i = 0; i < row_width; i++)
  186618. {
  186619. *(--dp) = *(--sp);
  186620. *(--dp) = lo_filler;
  186621. }
  186622. row_info->channels = 2;
  186623. row_info->pixel_depth = 16;
  186624. row_info->rowbytes = row_width * 2;
  186625. }
  186626. }
  186627. else if(row_info->bit_depth == 16)
  186628. {
  186629. /* This changes the data from GG to GGXX */
  186630. if (flags & PNG_FLAG_FILLER_AFTER)
  186631. {
  186632. png_bytep sp = row + (png_size_t)row_width * 2;
  186633. png_bytep dp = sp + (png_size_t)row_width * 2;
  186634. for (i = 1; i < row_width; i++)
  186635. {
  186636. *(--dp) = hi_filler;
  186637. *(--dp) = lo_filler;
  186638. *(--dp) = *(--sp);
  186639. *(--dp) = *(--sp);
  186640. }
  186641. *(--dp) = hi_filler;
  186642. *(--dp) = lo_filler;
  186643. row_info->channels = 2;
  186644. row_info->pixel_depth = 32;
  186645. row_info->rowbytes = row_width * 4;
  186646. }
  186647. /* This changes the data from GG to XXGG */
  186648. else
  186649. {
  186650. png_bytep sp = row + (png_size_t)row_width * 2;
  186651. png_bytep dp = sp + (png_size_t)row_width * 2;
  186652. for (i = 0; i < row_width; i++)
  186653. {
  186654. *(--dp) = *(--sp);
  186655. *(--dp) = *(--sp);
  186656. *(--dp) = hi_filler;
  186657. *(--dp) = lo_filler;
  186658. }
  186659. row_info->channels = 2;
  186660. row_info->pixel_depth = 32;
  186661. row_info->rowbytes = row_width * 4;
  186662. }
  186663. }
  186664. } /* COLOR_TYPE == GRAY */
  186665. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  186666. {
  186667. if(row_info->bit_depth == 8)
  186668. {
  186669. /* This changes the data from RGB to RGBX */
  186670. if (flags & PNG_FLAG_FILLER_AFTER)
  186671. {
  186672. png_bytep sp = row + (png_size_t)row_width * 3;
  186673. png_bytep dp = sp + (png_size_t)row_width;
  186674. for (i = 1; i < row_width; i++)
  186675. {
  186676. *(--dp) = lo_filler;
  186677. *(--dp) = *(--sp);
  186678. *(--dp) = *(--sp);
  186679. *(--dp) = *(--sp);
  186680. }
  186681. *(--dp) = lo_filler;
  186682. row_info->channels = 4;
  186683. row_info->pixel_depth = 32;
  186684. row_info->rowbytes = row_width * 4;
  186685. }
  186686. /* This changes the data from RGB to XRGB */
  186687. else
  186688. {
  186689. png_bytep sp = row + (png_size_t)row_width * 3;
  186690. png_bytep dp = sp + (png_size_t)row_width;
  186691. for (i = 0; i < row_width; i++)
  186692. {
  186693. *(--dp) = *(--sp);
  186694. *(--dp) = *(--sp);
  186695. *(--dp) = *(--sp);
  186696. *(--dp) = lo_filler;
  186697. }
  186698. row_info->channels = 4;
  186699. row_info->pixel_depth = 32;
  186700. row_info->rowbytes = row_width * 4;
  186701. }
  186702. }
  186703. else if(row_info->bit_depth == 16)
  186704. {
  186705. /* This changes the data from RRGGBB to RRGGBBXX */
  186706. if (flags & PNG_FLAG_FILLER_AFTER)
  186707. {
  186708. png_bytep sp = row + (png_size_t)row_width * 6;
  186709. png_bytep dp = sp + (png_size_t)row_width * 2;
  186710. for (i = 1; i < row_width; i++)
  186711. {
  186712. *(--dp) = hi_filler;
  186713. *(--dp) = lo_filler;
  186714. *(--dp) = *(--sp);
  186715. *(--dp) = *(--sp);
  186716. *(--dp) = *(--sp);
  186717. *(--dp) = *(--sp);
  186718. *(--dp) = *(--sp);
  186719. *(--dp) = *(--sp);
  186720. }
  186721. *(--dp) = hi_filler;
  186722. *(--dp) = lo_filler;
  186723. row_info->channels = 4;
  186724. row_info->pixel_depth = 64;
  186725. row_info->rowbytes = row_width * 8;
  186726. }
  186727. /* This changes the data from RRGGBB to XXRRGGBB */
  186728. else
  186729. {
  186730. png_bytep sp = row + (png_size_t)row_width * 6;
  186731. png_bytep dp = sp + (png_size_t)row_width * 2;
  186732. for (i = 0; i < row_width; i++)
  186733. {
  186734. *(--dp) = *(--sp);
  186735. *(--dp) = *(--sp);
  186736. *(--dp) = *(--sp);
  186737. *(--dp) = *(--sp);
  186738. *(--dp) = *(--sp);
  186739. *(--dp) = *(--sp);
  186740. *(--dp) = hi_filler;
  186741. *(--dp) = lo_filler;
  186742. }
  186743. row_info->channels = 4;
  186744. row_info->pixel_depth = 64;
  186745. row_info->rowbytes = row_width * 8;
  186746. }
  186747. }
  186748. } /* COLOR_TYPE == RGB */
  186749. }
  186750. #endif
  186751. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186752. /* expand grayscale files to RGB, with or without alpha */
  186753. void /* PRIVATE */
  186754. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  186755. {
  186756. png_uint_32 i;
  186757. png_uint_32 row_width = row_info->width;
  186758. png_debug(1, "in png_do_gray_to_rgb\n");
  186759. if (row_info->bit_depth >= 8 &&
  186760. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186761. row != NULL && row_info != NULL &&
  186762. #endif
  186763. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  186764. {
  186765. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  186766. {
  186767. if (row_info->bit_depth == 8)
  186768. {
  186769. png_bytep sp = row + (png_size_t)row_width - 1;
  186770. png_bytep dp = sp + (png_size_t)row_width * 2;
  186771. for (i = 0; i < row_width; i++)
  186772. {
  186773. *(dp--) = *sp;
  186774. *(dp--) = *sp;
  186775. *(dp--) = *(sp--);
  186776. }
  186777. }
  186778. else
  186779. {
  186780. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  186781. png_bytep dp = sp + (png_size_t)row_width * 4;
  186782. for (i = 0; i < row_width; i++)
  186783. {
  186784. *(dp--) = *sp;
  186785. *(dp--) = *(sp - 1);
  186786. *(dp--) = *sp;
  186787. *(dp--) = *(sp - 1);
  186788. *(dp--) = *(sp--);
  186789. *(dp--) = *(sp--);
  186790. }
  186791. }
  186792. }
  186793. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  186794. {
  186795. if (row_info->bit_depth == 8)
  186796. {
  186797. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  186798. png_bytep dp = sp + (png_size_t)row_width * 2;
  186799. for (i = 0; i < row_width; i++)
  186800. {
  186801. *(dp--) = *(sp--);
  186802. *(dp--) = *sp;
  186803. *(dp--) = *sp;
  186804. *(dp--) = *(sp--);
  186805. }
  186806. }
  186807. else
  186808. {
  186809. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  186810. png_bytep dp = sp + (png_size_t)row_width * 4;
  186811. for (i = 0; i < row_width; i++)
  186812. {
  186813. *(dp--) = *(sp--);
  186814. *(dp--) = *(sp--);
  186815. *(dp--) = *sp;
  186816. *(dp--) = *(sp - 1);
  186817. *(dp--) = *sp;
  186818. *(dp--) = *(sp - 1);
  186819. *(dp--) = *(sp--);
  186820. *(dp--) = *(sp--);
  186821. }
  186822. }
  186823. }
  186824. row_info->channels += (png_byte)2;
  186825. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  186826. row_info->pixel_depth = (png_byte)(row_info->channels *
  186827. row_info->bit_depth);
  186828. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  186829. }
  186830. }
  186831. #endif
  186832. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186833. /* reduce RGB files to grayscale, with or without alpha
  186834. * using the equation given in Poynton's ColorFAQ at
  186835. * <http://www.inforamp.net/~poynton/>
  186836. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  186837. *
  186838. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  186839. *
  186840. * We approximate this with
  186841. *
  186842. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  186843. *
  186844. * which can be expressed with integers as
  186845. *
  186846. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  186847. *
  186848. * The calculation is to be done in a linear colorspace.
  186849. *
  186850. * Other integer coefficents can be used via png_set_rgb_to_gray().
  186851. */
  186852. int /* PRIVATE */
  186853. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  186854. {
  186855. png_uint_32 i;
  186856. png_uint_32 row_width = row_info->width;
  186857. int rgb_error = 0;
  186858. png_debug(1, "in png_do_rgb_to_gray\n");
  186859. if (
  186860. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186861. row != NULL && row_info != NULL &&
  186862. #endif
  186863. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  186864. {
  186865. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  186866. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  186867. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  186868. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  186869. {
  186870. if (row_info->bit_depth == 8)
  186871. {
  186872. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186873. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  186874. {
  186875. png_bytep sp = row;
  186876. png_bytep dp = row;
  186877. for (i = 0; i < row_width; i++)
  186878. {
  186879. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  186880. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  186881. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  186882. if(red != green || red != blue)
  186883. {
  186884. rgb_error |= 1;
  186885. *(dp++) = png_ptr->gamma_from_1[
  186886. (rc*red+gc*green+bc*blue)>>15];
  186887. }
  186888. else
  186889. *(dp++) = *(sp-1);
  186890. }
  186891. }
  186892. else
  186893. #endif
  186894. {
  186895. png_bytep sp = row;
  186896. png_bytep dp = row;
  186897. for (i = 0; i < row_width; i++)
  186898. {
  186899. png_byte red = *(sp++);
  186900. png_byte green = *(sp++);
  186901. png_byte blue = *(sp++);
  186902. if(red != green || red != blue)
  186903. {
  186904. rgb_error |= 1;
  186905. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  186906. }
  186907. else
  186908. *(dp++) = *(sp-1);
  186909. }
  186910. }
  186911. }
  186912. else /* RGB bit_depth == 16 */
  186913. {
  186914. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186915. if (png_ptr->gamma_16_to_1 != NULL &&
  186916. png_ptr->gamma_16_from_1 != NULL)
  186917. {
  186918. png_bytep sp = row;
  186919. png_bytep dp = row;
  186920. for (i = 0; i < row_width; i++)
  186921. {
  186922. png_uint_16 red, green, blue, w;
  186923. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186924. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186925. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186926. if(red == green && red == blue)
  186927. w = red;
  186928. else
  186929. {
  186930. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  186931. png_ptr->gamma_shift][red>>8];
  186932. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  186933. png_ptr->gamma_shift][green>>8];
  186934. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  186935. png_ptr->gamma_shift][blue>>8];
  186936. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  186937. + bc*blue_1)>>15);
  186938. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  186939. png_ptr->gamma_shift][gray16 >> 8];
  186940. rgb_error |= 1;
  186941. }
  186942. *(dp++) = (png_byte)((w>>8) & 0xff);
  186943. *(dp++) = (png_byte)(w & 0xff);
  186944. }
  186945. }
  186946. else
  186947. #endif
  186948. {
  186949. png_bytep sp = row;
  186950. png_bytep dp = row;
  186951. for (i = 0; i < row_width; i++)
  186952. {
  186953. png_uint_16 red, green, blue, gray16;
  186954. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186955. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186956. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186957. if(red != green || red != blue)
  186958. rgb_error |= 1;
  186959. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  186960. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  186961. *(dp++) = (png_byte)(gray16 & 0xff);
  186962. }
  186963. }
  186964. }
  186965. }
  186966. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  186967. {
  186968. if (row_info->bit_depth == 8)
  186969. {
  186970. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186971. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  186972. {
  186973. png_bytep sp = row;
  186974. png_bytep dp = row;
  186975. for (i = 0; i < row_width; i++)
  186976. {
  186977. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  186978. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  186979. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  186980. if(red != green || red != blue)
  186981. rgb_error |= 1;
  186982. *(dp++) = png_ptr->gamma_from_1
  186983. [(rc*red + gc*green + bc*blue)>>15];
  186984. *(dp++) = *(sp++); /* alpha */
  186985. }
  186986. }
  186987. else
  186988. #endif
  186989. {
  186990. png_bytep sp = row;
  186991. png_bytep dp = row;
  186992. for (i = 0; i < row_width; i++)
  186993. {
  186994. png_byte red = *(sp++);
  186995. png_byte green = *(sp++);
  186996. png_byte blue = *(sp++);
  186997. if(red != green || red != blue)
  186998. rgb_error |= 1;
  186999. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  187000. *(dp++) = *(sp++); /* alpha */
  187001. }
  187002. }
  187003. }
  187004. else /* RGBA bit_depth == 16 */
  187005. {
  187006. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187007. if (png_ptr->gamma_16_to_1 != NULL &&
  187008. png_ptr->gamma_16_from_1 != NULL)
  187009. {
  187010. png_bytep sp = row;
  187011. png_bytep dp = row;
  187012. for (i = 0; i < row_width; i++)
  187013. {
  187014. png_uint_16 red, green, blue, w;
  187015. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187016. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187017. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187018. if(red == green && red == blue)
  187019. w = red;
  187020. else
  187021. {
  187022. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  187023. png_ptr->gamma_shift][red>>8];
  187024. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  187025. png_ptr->gamma_shift][green>>8];
  187026. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  187027. png_ptr->gamma_shift][blue>>8];
  187028. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  187029. + gc * green_1 + bc * blue_1)>>15);
  187030. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  187031. png_ptr->gamma_shift][gray16 >> 8];
  187032. rgb_error |= 1;
  187033. }
  187034. *(dp++) = (png_byte)((w>>8) & 0xff);
  187035. *(dp++) = (png_byte)(w & 0xff);
  187036. *(dp++) = *(sp++); /* alpha */
  187037. *(dp++) = *(sp++);
  187038. }
  187039. }
  187040. else
  187041. #endif
  187042. {
  187043. png_bytep sp = row;
  187044. png_bytep dp = row;
  187045. for (i = 0; i < row_width; i++)
  187046. {
  187047. png_uint_16 red, green, blue, gray16;
  187048. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187049. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187050. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187051. if(red != green || red != blue)
  187052. rgb_error |= 1;
  187053. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  187054. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  187055. *(dp++) = (png_byte)(gray16 & 0xff);
  187056. *(dp++) = *(sp++); /* alpha */
  187057. *(dp++) = *(sp++);
  187058. }
  187059. }
  187060. }
  187061. }
  187062. row_info->channels -= (png_byte)2;
  187063. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  187064. row_info->pixel_depth = (png_byte)(row_info->channels *
  187065. row_info->bit_depth);
  187066. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187067. }
  187068. return rgb_error;
  187069. }
  187070. #endif
  187071. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  187072. * large of png_color. This lets grayscale images be treated as
  187073. * paletted. Most useful for gamma correction and simplification
  187074. * of code.
  187075. */
  187076. void PNGAPI
  187077. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  187078. {
  187079. int num_palette;
  187080. int color_inc;
  187081. int i;
  187082. int v;
  187083. png_debug(1, "in png_do_build_grayscale_palette\n");
  187084. if (palette == NULL)
  187085. return;
  187086. switch (bit_depth)
  187087. {
  187088. case 1:
  187089. num_palette = 2;
  187090. color_inc = 0xff;
  187091. break;
  187092. case 2:
  187093. num_palette = 4;
  187094. color_inc = 0x55;
  187095. break;
  187096. case 4:
  187097. num_palette = 16;
  187098. color_inc = 0x11;
  187099. break;
  187100. case 8:
  187101. num_palette = 256;
  187102. color_inc = 1;
  187103. break;
  187104. default:
  187105. num_palette = 0;
  187106. color_inc = 0;
  187107. break;
  187108. }
  187109. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  187110. {
  187111. palette[i].red = (png_byte)v;
  187112. palette[i].green = (png_byte)v;
  187113. palette[i].blue = (png_byte)v;
  187114. }
  187115. }
  187116. /* This function is currently unused. Do we really need it? */
  187117. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  187118. void /* PRIVATE */
  187119. png_correct_palette(png_structp png_ptr, png_colorp palette,
  187120. int num_palette)
  187121. {
  187122. png_debug(1, "in png_correct_palette\n");
  187123. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  187124. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  187125. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  187126. {
  187127. png_color back, back_1;
  187128. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  187129. {
  187130. back.red = png_ptr->gamma_table[png_ptr->background.red];
  187131. back.green = png_ptr->gamma_table[png_ptr->background.green];
  187132. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  187133. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  187134. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  187135. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  187136. }
  187137. else
  187138. {
  187139. double g;
  187140. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  187141. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  187142. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  187143. {
  187144. back.red = png_ptr->background.red;
  187145. back.green = png_ptr->background.green;
  187146. back.blue = png_ptr->background.blue;
  187147. }
  187148. else
  187149. {
  187150. back.red =
  187151. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  187152. 255.0 + 0.5);
  187153. back.green =
  187154. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  187155. 255.0 + 0.5);
  187156. back.blue =
  187157. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  187158. 255.0 + 0.5);
  187159. }
  187160. g = 1.0 / png_ptr->background_gamma;
  187161. back_1.red =
  187162. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  187163. 255.0 + 0.5);
  187164. back_1.green =
  187165. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  187166. 255.0 + 0.5);
  187167. back_1.blue =
  187168. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  187169. 255.0 + 0.5);
  187170. }
  187171. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187172. {
  187173. png_uint_32 i;
  187174. for (i = 0; i < (png_uint_32)num_palette; i++)
  187175. {
  187176. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  187177. {
  187178. palette[i] = back;
  187179. }
  187180. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  187181. {
  187182. png_byte v, w;
  187183. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  187184. png_composite(w, v, png_ptr->trans[i], back_1.red);
  187185. palette[i].red = png_ptr->gamma_from_1[w];
  187186. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  187187. png_composite(w, v, png_ptr->trans[i], back_1.green);
  187188. palette[i].green = png_ptr->gamma_from_1[w];
  187189. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  187190. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  187191. palette[i].blue = png_ptr->gamma_from_1[w];
  187192. }
  187193. else
  187194. {
  187195. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187196. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187197. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187198. }
  187199. }
  187200. }
  187201. else
  187202. {
  187203. int i;
  187204. for (i = 0; i < num_palette; i++)
  187205. {
  187206. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  187207. {
  187208. palette[i] = back;
  187209. }
  187210. else
  187211. {
  187212. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187213. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187214. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187215. }
  187216. }
  187217. }
  187218. }
  187219. else
  187220. #endif
  187221. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187222. if (png_ptr->transformations & PNG_GAMMA)
  187223. {
  187224. int i;
  187225. for (i = 0; i < num_palette; i++)
  187226. {
  187227. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187228. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187229. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187230. }
  187231. }
  187232. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187233. else
  187234. #endif
  187235. #endif
  187236. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187237. if (png_ptr->transformations & PNG_BACKGROUND)
  187238. {
  187239. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187240. {
  187241. png_color back;
  187242. back.red = (png_byte)png_ptr->background.red;
  187243. back.green = (png_byte)png_ptr->background.green;
  187244. back.blue = (png_byte)png_ptr->background.blue;
  187245. for (i = 0; i < (int)png_ptr->num_trans; i++)
  187246. {
  187247. if (png_ptr->trans[i] == 0)
  187248. {
  187249. palette[i].red = back.red;
  187250. palette[i].green = back.green;
  187251. palette[i].blue = back.blue;
  187252. }
  187253. else if (png_ptr->trans[i] != 0xff)
  187254. {
  187255. png_composite(palette[i].red, png_ptr->palette[i].red,
  187256. png_ptr->trans[i], back.red);
  187257. png_composite(palette[i].green, png_ptr->palette[i].green,
  187258. png_ptr->trans[i], back.green);
  187259. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  187260. png_ptr->trans[i], back.blue);
  187261. }
  187262. }
  187263. }
  187264. else /* assume grayscale palette (what else could it be?) */
  187265. {
  187266. int i;
  187267. for (i = 0; i < num_palette; i++)
  187268. {
  187269. if (i == (png_byte)png_ptr->trans_values.gray)
  187270. {
  187271. palette[i].red = (png_byte)png_ptr->background.red;
  187272. palette[i].green = (png_byte)png_ptr->background.green;
  187273. palette[i].blue = (png_byte)png_ptr->background.blue;
  187274. }
  187275. }
  187276. }
  187277. }
  187278. #endif
  187279. }
  187280. #endif
  187281. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187282. /* Replace any alpha or transparency with the supplied background color.
  187283. * "background" is already in the screen gamma, while "background_1" is
  187284. * at a gamma of 1.0. Paletted files have already been taken care of.
  187285. */
  187286. void /* PRIVATE */
  187287. png_do_background(png_row_infop row_info, png_bytep row,
  187288. png_color_16p trans_values, png_color_16p background
  187289. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187290. , png_color_16p background_1,
  187291. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  187292. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  187293. png_uint_16pp gamma_16_to_1, int gamma_shift
  187294. #endif
  187295. )
  187296. {
  187297. png_bytep sp, dp;
  187298. png_uint_32 i;
  187299. png_uint_32 row_width=row_info->width;
  187300. int shift;
  187301. png_debug(1, "in png_do_background\n");
  187302. if (background != NULL &&
  187303. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187304. row != NULL && row_info != NULL &&
  187305. #endif
  187306. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  187307. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  187308. {
  187309. switch (row_info->color_type)
  187310. {
  187311. case PNG_COLOR_TYPE_GRAY:
  187312. {
  187313. switch (row_info->bit_depth)
  187314. {
  187315. case 1:
  187316. {
  187317. sp = row;
  187318. shift = 7;
  187319. for (i = 0; i < row_width; i++)
  187320. {
  187321. if ((png_uint_16)((*sp >> shift) & 0x01)
  187322. == trans_values->gray)
  187323. {
  187324. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  187325. *sp |= (png_byte)(background->gray << shift);
  187326. }
  187327. if (!shift)
  187328. {
  187329. shift = 7;
  187330. sp++;
  187331. }
  187332. else
  187333. shift--;
  187334. }
  187335. break;
  187336. }
  187337. case 2:
  187338. {
  187339. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187340. if (gamma_table != NULL)
  187341. {
  187342. sp = row;
  187343. shift = 6;
  187344. for (i = 0; i < row_width; i++)
  187345. {
  187346. if ((png_uint_16)((*sp >> shift) & 0x03)
  187347. == trans_values->gray)
  187348. {
  187349. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  187350. *sp |= (png_byte)(background->gray << shift);
  187351. }
  187352. else
  187353. {
  187354. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  187355. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  187356. (p << 4) | (p << 6)] >> 6) & 0x03);
  187357. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  187358. *sp |= (png_byte)(g << shift);
  187359. }
  187360. if (!shift)
  187361. {
  187362. shift = 6;
  187363. sp++;
  187364. }
  187365. else
  187366. shift -= 2;
  187367. }
  187368. }
  187369. else
  187370. #endif
  187371. {
  187372. sp = row;
  187373. shift = 6;
  187374. for (i = 0; i < row_width; i++)
  187375. {
  187376. if ((png_uint_16)((*sp >> shift) & 0x03)
  187377. == trans_values->gray)
  187378. {
  187379. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  187380. *sp |= (png_byte)(background->gray << shift);
  187381. }
  187382. if (!shift)
  187383. {
  187384. shift = 6;
  187385. sp++;
  187386. }
  187387. else
  187388. shift -= 2;
  187389. }
  187390. }
  187391. break;
  187392. }
  187393. case 4:
  187394. {
  187395. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187396. if (gamma_table != NULL)
  187397. {
  187398. sp = row;
  187399. shift = 4;
  187400. for (i = 0; i < row_width; i++)
  187401. {
  187402. if ((png_uint_16)((*sp >> shift) & 0x0f)
  187403. == trans_values->gray)
  187404. {
  187405. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  187406. *sp |= (png_byte)(background->gray << shift);
  187407. }
  187408. else
  187409. {
  187410. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  187411. png_byte g = (png_byte)((gamma_table[p |
  187412. (p << 4)] >> 4) & 0x0f);
  187413. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  187414. *sp |= (png_byte)(g << shift);
  187415. }
  187416. if (!shift)
  187417. {
  187418. shift = 4;
  187419. sp++;
  187420. }
  187421. else
  187422. shift -= 4;
  187423. }
  187424. }
  187425. else
  187426. #endif
  187427. {
  187428. sp = row;
  187429. shift = 4;
  187430. for (i = 0; i < row_width; i++)
  187431. {
  187432. if ((png_uint_16)((*sp >> shift) & 0x0f)
  187433. == trans_values->gray)
  187434. {
  187435. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  187436. *sp |= (png_byte)(background->gray << shift);
  187437. }
  187438. if (!shift)
  187439. {
  187440. shift = 4;
  187441. sp++;
  187442. }
  187443. else
  187444. shift -= 4;
  187445. }
  187446. }
  187447. break;
  187448. }
  187449. case 8:
  187450. {
  187451. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187452. if (gamma_table != NULL)
  187453. {
  187454. sp = row;
  187455. for (i = 0; i < row_width; i++, sp++)
  187456. {
  187457. if (*sp == trans_values->gray)
  187458. {
  187459. *sp = (png_byte)background->gray;
  187460. }
  187461. else
  187462. {
  187463. *sp = gamma_table[*sp];
  187464. }
  187465. }
  187466. }
  187467. else
  187468. #endif
  187469. {
  187470. sp = row;
  187471. for (i = 0; i < row_width; i++, sp++)
  187472. {
  187473. if (*sp == trans_values->gray)
  187474. {
  187475. *sp = (png_byte)background->gray;
  187476. }
  187477. }
  187478. }
  187479. break;
  187480. }
  187481. case 16:
  187482. {
  187483. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187484. if (gamma_16 != NULL)
  187485. {
  187486. sp = row;
  187487. for (i = 0; i < row_width; i++, sp += 2)
  187488. {
  187489. png_uint_16 v;
  187490. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  187491. if (v == trans_values->gray)
  187492. {
  187493. /* background is already in screen gamma */
  187494. *sp = (png_byte)((background->gray >> 8) & 0xff);
  187495. *(sp + 1) = (png_byte)(background->gray & 0xff);
  187496. }
  187497. else
  187498. {
  187499. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  187500. *sp = (png_byte)((v >> 8) & 0xff);
  187501. *(sp + 1) = (png_byte)(v & 0xff);
  187502. }
  187503. }
  187504. }
  187505. else
  187506. #endif
  187507. {
  187508. sp = row;
  187509. for (i = 0; i < row_width; i++, sp += 2)
  187510. {
  187511. png_uint_16 v;
  187512. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  187513. if (v == trans_values->gray)
  187514. {
  187515. *sp = (png_byte)((background->gray >> 8) & 0xff);
  187516. *(sp + 1) = (png_byte)(background->gray & 0xff);
  187517. }
  187518. }
  187519. }
  187520. break;
  187521. }
  187522. }
  187523. break;
  187524. }
  187525. case PNG_COLOR_TYPE_RGB:
  187526. {
  187527. if (row_info->bit_depth == 8)
  187528. {
  187529. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187530. if (gamma_table != NULL)
  187531. {
  187532. sp = row;
  187533. for (i = 0; i < row_width; i++, sp += 3)
  187534. {
  187535. if (*sp == trans_values->red &&
  187536. *(sp + 1) == trans_values->green &&
  187537. *(sp + 2) == trans_values->blue)
  187538. {
  187539. *sp = (png_byte)background->red;
  187540. *(sp + 1) = (png_byte)background->green;
  187541. *(sp + 2) = (png_byte)background->blue;
  187542. }
  187543. else
  187544. {
  187545. *sp = gamma_table[*sp];
  187546. *(sp + 1) = gamma_table[*(sp + 1)];
  187547. *(sp + 2) = gamma_table[*(sp + 2)];
  187548. }
  187549. }
  187550. }
  187551. else
  187552. #endif
  187553. {
  187554. sp = row;
  187555. for (i = 0; i < row_width; i++, sp += 3)
  187556. {
  187557. if (*sp == trans_values->red &&
  187558. *(sp + 1) == trans_values->green &&
  187559. *(sp + 2) == trans_values->blue)
  187560. {
  187561. *sp = (png_byte)background->red;
  187562. *(sp + 1) = (png_byte)background->green;
  187563. *(sp + 2) = (png_byte)background->blue;
  187564. }
  187565. }
  187566. }
  187567. }
  187568. else /* if (row_info->bit_depth == 16) */
  187569. {
  187570. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187571. if (gamma_16 != NULL)
  187572. {
  187573. sp = row;
  187574. for (i = 0; i < row_width; i++, sp += 6)
  187575. {
  187576. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  187577. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  187578. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  187579. if (r == trans_values->red && g == trans_values->green &&
  187580. b == trans_values->blue)
  187581. {
  187582. /* background is already in screen gamma */
  187583. *sp = (png_byte)((background->red >> 8) & 0xff);
  187584. *(sp + 1) = (png_byte)(background->red & 0xff);
  187585. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  187586. *(sp + 3) = (png_byte)(background->green & 0xff);
  187587. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  187588. *(sp + 5) = (png_byte)(background->blue & 0xff);
  187589. }
  187590. else
  187591. {
  187592. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  187593. *sp = (png_byte)((v >> 8) & 0xff);
  187594. *(sp + 1) = (png_byte)(v & 0xff);
  187595. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  187596. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  187597. *(sp + 3) = (png_byte)(v & 0xff);
  187598. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  187599. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  187600. *(sp + 5) = (png_byte)(v & 0xff);
  187601. }
  187602. }
  187603. }
  187604. else
  187605. #endif
  187606. {
  187607. sp = row;
  187608. for (i = 0; i < row_width; i++, sp += 6)
  187609. {
  187610. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  187611. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  187612. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  187613. if (r == trans_values->red && g == trans_values->green &&
  187614. b == trans_values->blue)
  187615. {
  187616. *sp = (png_byte)((background->red >> 8) & 0xff);
  187617. *(sp + 1) = (png_byte)(background->red & 0xff);
  187618. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  187619. *(sp + 3) = (png_byte)(background->green & 0xff);
  187620. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  187621. *(sp + 5) = (png_byte)(background->blue & 0xff);
  187622. }
  187623. }
  187624. }
  187625. }
  187626. break;
  187627. }
  187628. case PNG_COLOR_TYPE_GRAY_ALPHA:
  187629. {
  187630. if (row_info->bit_depth == 8)
  187631. {
  187632. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187633. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  187634. gamma_table != NULL)
  187635. {
  187636. sp = row;
  187637. dp = row;
  187638. for (i = 0; i < row_width; i++, sp += 2, dp++)
  187639. {
  187640. png_uint_16 a = *(sp + 1);
  187641. if (a == 0xff)
  187642. {
  187643. *dp = gamma_table[*sp];
  187644. }
  187645. else if (a == 0)
  187646. {
  187647. /* background is already in screen gamma */
  187648. *dp = (png_byte)background->gray;
  187649. }
  187650. else
  187651. {
  187652. png_byte v, w;
  187653. v = gamma_to_1[*sp];
  187654. png_composite(w, v, a, background_1->gray);
  187655. *dp = gamma_from_1[w];
  187656. }
  187657. }
  187658. }
  187659. else
  187660. #endif
  187661. {
  187662. sp = row;
  187663. dp = row;
  187664. for (i = 0; i < row_width; i++, sp += 2, dp++)
  187665. {
  187666. png_byte a = *(sp + 1);
  187667. if (a == 0xff)
  187668. {
  187669. *dp = *sp;
  187670. }
  187671. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187672. else if (a == 0)
  187673. {
  187674. *dp = (png_byte)background->gray;
  187675. }
  187676. else
  187677. {
  187678. png_composite(*dp, *sp, a, background_1->gray);
  187679. }
  187680. #else
  187681. *dp = (png_byte)background->gray;
  187682. #endif
  187683. }
  187684. }
  187685. }
  187686. else /* if (png_ptr->bit_depth == 16) */
  187687. {
  187688. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187689. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  187690. gamma_16_to_1 != NULL)
  187691. {
  187692. sp = row;
  187693. dp = row;
  187694. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  187695. {
  187696. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  187697. if (a == (png_uint_16)0xffff)
  187698. {
  187699. png_uint_16 v;
  187700. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  187701. *dp = (png_byte)((v >> 8) & 0xff);
  187702. *(dp + 1) = (png_byte)(v & 0xff);
  187703. }
  187704. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187705. else if (a == 0)
  187706. #else
  187707. else
  187708. #endif
  187709. {
  187710. /* background is already in screen gamma */
  187711. *dp = (png_byte)((background->gray >> 8) & 0xff);
  187712. *(dp + 1) = (png_byte)(background->gray & 0xff);
  187713. }
  187714. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187715. else
  187716. {
  187717. png_uint_16 g, v, w;
  187718. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  187719. png_composite_16(v, g, a, background_1->gray);
  187720. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  187721. *dp = (png_byte)((w >> 8) & 0xff);
  187722. *(dp + 1) = (png_byte)(w & 0xff);
  187723. }
  187724. #endif
  187725. }
  187726. }
  187727. else
  187728. #endif
  187729. {
  187730. sp = row;
  187731. dp = row;
  187732. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  187733. {
  187734. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  187735. if (a == (png_uint_16)0xffff)
  187736. {
  187737. png_memcpy(dp, sp, 2);
  187738. }
  187739. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187740. else if (a == 0)
  187741. #else
  187742. else
  187743. #endif
  187744. {
  187745. *dp = (png_byte)((background->gray >> 8) & 0xff);
  187746. *(dp + 1) = (png_byte)(background->gray & 0xff);
  187747. }
  187748. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187749. else
  187750. {
  187751. png_uint_16 g, v;
  187752. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  187753. png_composite_16(v, g, a, background_1->gray);
  187754. *dp = (png_byte)((v >> 8) & 0xff);
  187755. *(dp + 1) = (png_byte)(v & 0xff);
  187756. }
  187757. #endif
  187758. }
  187759. }
  187760. }
  187761. break;
  187762. }
  187763. case PNG_COLOR_TYPE_RGB_ALPHA:
  187764. {
  187765. if (row_info->bit_depth == 8)
  187766. {
  187767. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187768. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  187769. gamma_table != NULL)
  187770. {
  187771. sp = row;
  187772. dp = row;
  187773. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  187774. {
  187775. png_byte a = *(sp + 3);
  187776. if (a == 0xff)
  187777. {
  187778. *dp = gamma_table[*sp];
  187779. *(dp + 1) = gamma_table[*(sp + 1)];
  187780. *(dp + 2) = gamma_table[*(sp + 2)];
  187781. }
  187782. else if (a == 0)
  187783. {
  187784. /* background is already in screen gamma */
  187785. *dp = (png_byte)background->red;
  187786. *(dp + 1) = (png_byte)background->green;
  187787. *(dp + 2) = (png_byte)background->blue;
  187788. }
  187789. else
  187790. {
  187791. png_byte v, w;
  187792. v = gamma_to_1[*sp];
  187793. png_composite(w, v, a, background_1->red);
  187794. *dp = gamma_from_1[w];
  187795. v = gamma_to_1[*(sp + 1)];
  187796. png_composite(w, v, a, background_1->green);
  187797. *(dp + 1) = gamma_from_1[w];
  187798. v = gamma_to_1[*(sp + 2)];
  187799. png_composite(w, v, a, background_1->blue);
  187800. *(dp + 2) = gamma_from_1[w];
  187801. }
  187802. }
  187803. }
  187804. else
  187805. #endif
  187806. {
  187807. sp = row;
  187808. dp = row;
  187809. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  187810. {
  187811. png_byte a = *(sp + 3);
  187812. if (a == 0xff)
  187813. {
  187814. *dp = *sp;
  187815. *(dp + 1) = *(sp + 1);
  187816. *(dp + 2) = *(sp + 2);
  187817. }
  187818. else if (a == 0)
  187819. {
  187820. *dp = (png_byte)background->red;
  187821. *(dp + 1) = (png_byte)background->green;
  187822. *(dp + 2) = (png_byte)background->blue;
  187823. }
  187824. else
  187825. {
  187826. png_composite(*dp, *sp, a, background->red);
  187827. png_composite(*(dp + 1), *(sp + 1), a,
  187828. background->green);
  187829. png_composite(*(dp + 2), *(sp + 2), a,
  187830. background->blue);
  187831. }
  187832. }
  187833. }
  187834. }
  187835. else /* if (row_info->bit_depth == 16) */
  187836. {
  187837. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187838. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  187839. gamma_16_to_1 != NULL)
  187840. {
  187841. sp = row;
  187842. dp = row;
  187843. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  187844. {
  187845. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  187846. << 8) + (png_uint_16)(*(sp + 7)));
  187847. if (a == (png_uint_16)0xffff)
  187848. {
  187849. png_uint_16 v;
  187850. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  187851. *dp = (png_byte)((v >> 8) & 0xff);
  187852. *(dp + 1) = (png_byte)(v & 0xff);
  187853. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  187854. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  187855. *(dp + 3) = (png_byte)(v & 0xff);
  187856. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  187857. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  187858. *(dp + 5) = (png_byte)(v & 0xff);
  187859. }
  187860. else if (a == 0)
  187861. {
  187862. /* background is already in screen gamma */
  187863. *dp = (png_byte)((background->red >> 8) & 0xff);
  187864. *(dp + 1) = (png_byte)(background->red & 0xff);
  187865. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  187866. *(dp + 3) = (png_byte)(background->green & 0xff);
  187867. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  187868. *(dp + 5) = (png_byte)(background->blue & 0xff);
  187869. }
  187870. else
  187871. {
  187872. png_uint_16 v, w, x;
  187873. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  187874. png_composite_16(w, v, a, background_1->red);
  187875. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  187876. *dp = (png_byte)((x >> 8) & 0xff);
  187877. *(dp + 1) = (png_byte)(x & 0xff);
  187878. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  187879. png_composite_16(w, v, a, background_1->green);
  187880. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  187881. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  187882. *(dp + 3) = (png_byte)(x & 0xff);
  187883. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  187884. png_composite_16(w, v, a, background_1->blue);
  187885. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  187886. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  187887. *(dp + 5) = (png_byte)(x & 0xff);
  187888. }
  187889. }
  187890. }
  187891. else
  187892. #endif
  187893. {
  187894. sp = row;
  187895. dp = row;
  187896. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  187897. {
  187898. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  187899. << 8) + (png_uint_16)(*(sp + 7)));
  187900. if (a == (png_uint_16)0xffff)
  187901. {
  187902. png_memcpy(dp, sp, 6);
  187903. }
  187904. else if (a == 0)
  187905. {
  187906. *dp = (png_byte)((background->red >> 8) & 0xff);
  187907. *(dp + 1) = (png_byte)(background->red & 0xff);
  187908. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  187909. *(dp + 3) = (png_byte)(background->green & 0xff);
  187910. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  187911. *(dp + 5) = (png_byte)(background->blue & 0xff);
  187912. }
  187913. else
  187914. {
  187915. png_uint_16 v;
  187916. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  187917. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  187918. + *(sp + 3));
  187919. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  187920. + *(sp + 5));
  187921. png_composite_16(v, r, a, background->red);
  187922. *dp = (png_byte)((v >> 8) & 0xff);
  187923. *(dp + 1) = (png_byte)(v & 0xff);
  187924. png_composite_16(v, g, a, background->green);
  187925. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  187926. *(dp + 3) = (png_byte)(v & 0xff);
  187927. png_composite_16(v, b, a, background->blue);
  187928. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  187929. *(dp + 5) = (png_byte)(v & 0xff);
  187930. }
  187931. }
  187932. }
  187933. }
  187934. break;
  187935. }
  187936. }
  187937. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  187938. {
  187939. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  187940. row_info->channels--;
  187941. row_info->pixel_depth = (png_byte)(row_info->channels *
  187942. row_info->bit_depth);
  187943. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187944. }
  187945. }
  187946. }
  187947. #endif
  187948. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187949. /* Gamma correct the image, avoiding the alpha channel. Make sure
  187950. * you do this after you deal with the transparency issue on grayscale
  187951. * or RGB images. If your bit depth is 8, use gamma_table, if it
  187952. * is 16, use gamma_16_table and gamma_shift. Build these with
  187953. * build_gamma_table().
  187954. */
  187955. void /* PRIVATE */
  187956. png_do_gamma(png_row_infop row_info, png_bytep row,
  187957. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  187958. int gamma_shift)
  187959. {
  187960. png_bytep sp;
  187961. png_uint_32 i;
  187962. png_uint_32 row_width=row_info->width;
  187963. png_debug(1, "in png_do_gamma\n");
  187964. if (
  187965. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187966. row != NULL && row_info != NULL &&
  187967. #endif
  187968. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  187969. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  187970. {
  187971. switch (row_info->color_type)
  187972. {
  187973. case PNG_COLOR_TYPE_RGB:
  187974. {
  187975. if (row_info->bit_depth == 8)
  187976. {
  187977. sp = row;
  187978. for (i = 0; i < row_width; i++)
  187979. {
  187980. *sp = gamma_table[*sp];
  187981. sp++;
  187982. *sp = gamma_table[*sp];
  187983. sp++;
  187984. *sp = gamma_table[*sp];
  187985. sp++;
  187986. }
  187987. }
  187988. else /* if (row_info->bit_depth == 16) */
  187989. {
  187990. sp = row;
  187991. for (i = 0; i < row_width; i++)
  187992. {
  187993. png_uint_16 v;
  187994. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187995. *sp = (png_byte)((v >> 8) & 0xff);
  187996. *(sp + 1) = (png_byte)(v & 0xff);
  187997. sp += 2;
  187998. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187999. *sp = (png_byte)((v >> 8) & 0xff);
  188000. *(sp + 1) = (png_byte)(v & 0xff);
  188001. sp += 2;
  188002. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188003. *sp = (png_byte)((v >> 8) & 0xff);
  188004. *(sp + 1) = (png_byte)(v & 0xff);
  188005. sp += 2;
  188006. }
  188007. }
  188008. break;
  188009. }
  188010. case PNG_COLOR_TYPE_RGB_ALPHA:
  188011. {
  188012. if (row_info->bit_depth == 8)
  188013. {
  188014. sp = row;
  188015. for (i = 0; i < row_width; i++)
  188016. {
  188017. *sp = gamma_table[*sp];
  188018. sp++;
  188019. *sp = gamma_table[*sp];
  188020. sp++;
  188021. *sp = gamma_table[*sp];
  188022. sp++;
  188023. sp++;
  188024. }
  188025. }
  188026. else /* if (row_info->bit_depth == 16) */
  188027. {
  188028. sp = row;
  188029. for (i = 0; i < row_width; i++)
  188030. {
  188031. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188032. *sp = (png_byte)((v >> 8) & 0xff);
  188033. *(sp + 1) = (png_byte)(v & 0xff);
  188034. sp += 2;
  188035. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188036. *sp = (png_byte)((v >> 8) & 0xff);
  188037. *(sp + 1) = (png_byte)(v & 0xff);
  188038. sp += 2;
  188039. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188040. *sp = (png_byte)((v >> 8) & 0xff);
  188041. *(sp + 1) = (png_byte)(v & 0xff);
  188042. sp += 4;
  188043. }
  188044. }
  188045. break;
  188046. }
  188047. case PNG_COLOR_TYPE_GRAY_ALPHA:
  188048. {
  188049. if (row_info->bit_depth == 8)
  188050. {
  188051. sp = row;
  188052. for (i = 0; i < row_width; i++)
  188053. {
  188054. *sp = gamma_table[*sp];
  188055. sp += 2;
  188056. }
  188057. }
  188058. else /* if (row_info->bit_depth == 16) */
  188059. {
  188060. sp = row;
  188061. for (i = 0; i < row_width; i++)
  188062. {
  188063. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188064. *sp = (png_byte)((v >> 8) & 0xff);
  188065. *(sp + 1) = (png_byte)(v & 0xff);
  188066. sp += 4;
  188067. }
  188068. }
  188069. break;
  188070. }
  188071. case PNG_COLOR_TYPE_GRAY:
  188072. {
  188073. if (row_info->bit_depth == 2)
  188074. {
  188075. sp = row;
  188076. for (i = 0; i < row_width; i += 4)
  188077. {
  188078. int a = *sp & 0xc0;
  188079. int b = *sp & 0x30;
  188080. int c = *sp & 0x0c;
  188081. int d = *sp & 0x03;
  188082. *sp = (png_byte)(
  188083. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  188084. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  188085. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  188086. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  188087. sp++;
  188088. }
  188089. }
  188090. if (row_info->bit_depth == 4)
  188091. {
  188092. sp = row;
  188093. for (i = 0; i < row_width; i += 2)
  188094. {
  188095. int msb = *sp & 0xf0;
  188096. int lsb = *sp & 0x0f;
  188097. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  188098. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  188099. sp++;
  188100. }
  188101. }
  188102. else if (row_info->bit_depth == 8)
  188103. {
  188104. sp = row;
  188105. for (i = 0; i < row_width; i++)
  188106. {
  188107. *sp = gamma_table[*sp];
  188108. sp++;
  188109. }
  188110. }
  188111. else if (row_info->bit_depth == 16)
  188112. {
  188113. sp = row;
  188114. for (i = 0; i < row_width; i++)
  188115. {
  188116. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188117. *sp = (png_byte)((v >> 8) & 0xff);
  188118. *(sp + 1) = (png_byte)(v & 0xff);
  188119. sp += 2;
  188120. }
  188121. }
  188122. break;
  188123. }
  188124. }
  188125. }
  188126. }
  188127. #endif
  188128. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188129. /* Expands a palette row to an RGB or RGBA row depending
  188130. * upon whether you supply trans and num_trans.
  188131. */
  188132. void /* PRIVATE */
  188133. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  188134. png_colorp palette, png_bytep trans, int num_trans)
  188135. {
  188136. int shift, value;
  188137. png_bytep sp, dp;
  188138. png_uint_32 i;
  188139. png_uint_32 row_width=row_info->width;
  188140. png_debug(1, "in png_do_expand_palette\n");
  188141. if (
  188142. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188143. row != NULL && row_info != NULL &&
  188144. #endif
  188145. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  188146. {
  188147. if (row_info->bit_depth < 8)
  188148. {
  188149. switch (row_info->bit_depth)
  188150. {
  188151. case 1:
  188152. {
  188153. sp = row + (png_size_t)((row_width - 1) >> 3);
  188154. dp = row + (png_size_t)row_width - 1;
  188155. shift = 7 - (int)((row_width + 7) & 0x07);
  188156. for (i = 0; i < row_width; i++)
  188157. {
  188158. if ((*sp >> shift) & 0x01)
  188159. *dp = 1;
  188160. else
  188161. *dp = 0;
  188162. if (shift == 7)
  188163. {
  188164. shift = 0;
  188165. sp--;
  188166. }
  188167. else
  188168. shift++;
  188169. dp--;
  188170. }
  188171. break;
  188172. }
  188173. case 2:
  188174. {
  188175. sp = row + (png_size_t)((row_width - 1) >> 2);
  188176. dp = row + (png_size_t)row_width - 1;
  188177. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  188178. for (i = 0; i < row_width; i++)
  188179. {
  188180. value = (*sp >> shift) & 0x03;
  188181. *dp = (png_byte)value;
  188182. if (shift == 6)
  188183. {
  188184. shift = 0;
  188185. sp--;
  188186. }
  188187. else
  188188. shift += 2;
  188189. dp--;
  188190. }
  188191. break;
  188192. }
  188193. case 4:
  188194. {
  188195. sp = row + (png_size_t)((row_width - 1) >> 1);
  188196. dp = row + (png_size_t)row_width - 1;
  188197. shift = (int)((row_width & 0x01) << 2);
  188198. for (i = 0; i < row_width; i++)
  188199. {
  188200. value = (*sp >> shift) & 0x0f;
  188201. *dp = (png_byte)value;
  188202. if (shift == 4)
  188203. {
  188204. shift = 0;
  188205. sp--;
  188206. }
  188207. else
  188208. shift += 4;
  188209. dp--;
  188210. }
  188211. break;
  188212. }
  188213. }
  188214. row_info->bit_depth = 8;
  188215. row_info->pixel_depth = 8;
  188216. row_info->rowbytes = row_width;
  188217. }
  188218. switch (row_info->bit_depth)
  188219. {
  188220. case 8:
  188221. {
  188222. if (trans != NULL)
  188223. {
  188224. sp = row + (png_size_t)row_width - 1;
  188225. dp = row + (png_size_t)(row_width << 2) - 1;
  188226. for (i = 0; i < row_width; i++)
  188227. {
  188228. if ((int)(*sp) >= num_trans)
  188229. *dp-- = 0xff;
  188230. else
  188231. *dp-- = trans[*sp];
  188232. *dp-- = palette[*sp].blue;
  188233. *dp-- = palette[*sp].green;
  188234. *dp-- = palette[*sp].red;
  188235. sp--;
  188236. }
  188237. row_info->bit_depth = 8;
  188238. row_info->pixel_depth = 32;
  188239. row_info->rowbytes = row_width * 4;
  188240. row_info->color_type = 6;
  188241. row_info->channels = 4;
  188242. }
  188243. else
  188244. {
  188245. sp = row + (png_size_t)row_width - 1;
  188246. dp = row + (png_size_t)(row_width * 3) - 1;
  188247. for (i = 0; i < row_width; i++)
  188248. {
  188249. *dp-- = palette[*sp].blue;
  188250. *dp-- = palette[*sp].green;
  188251. *dp-- = palette[*sp].red;
  188252. sp--;
  188253. }
  188254. row_info->bit_depth = 8;
  188255. row_info->pixel_depth = 24;
  188256. row_info->rowbytes = row_width * 3;
  188257. row_info->color_type = 2;
  188258. row_info->channels = 3;
  188259. }
  188260. break;
  188261. }
  188262. }
  188263. }
  188264. }
  188265. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  188266. * expanded transparency value is supplied, an alpha channel is built.
  188267. */
  188268. void /* PRIVATE */
  188269. png_do_expand(png_row_infop row_info, png_bytep row,
  188270. png_color_16p trans_value)
  188271. {
  188272. int shift, value;
  188273. png_bytep sp, dp;
  188274. png_uint_32 i;
  188275. png_uint_32 row_width=row_info->width;
  188276. png_debug(1, "in png_do_expand\n");
  188277. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188278. if (row != NULL && row_info != NULL)
  188279. #endif
  188280. {
  188281. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  188282. {
  188283. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  188284. if (row_info->bit_depth < 8)
  188285. {
  188286. switch (row_info->bit_depth)
  188287. {
  188288. case 1:
  188289. {
  188290. gray = (png_uint_16)((gray&0x01)*0xff);
  188291. sp = row + (png_size_t)((row_width - 1) >> 3);
  188292. dp = row + (png_size_t)row_width - 1;
  188293. shift = 7 - (int)((row_width + 7) & 0x07);
  188294. for (i = 0; i < row_width; i++)
  188295. {
  188296. if ((*sp >> shift) & 0x01)
  188297. *dp = 0xff;
  188298. else
  188299. *dp = 0;
  188300. if (shift == 7)
  188301. {
  188302. shift = 0;
  188303. sp--;
  188304. }
  188305. else
  188306. shift++;
  188307. dp--;
  188308. }
  188309. break;
  188310. }
  188311. case 2:
  188312. {
  188313. gray = (png_uint_16)((gray&0x03)*0x55);
  188314. sp = row + (png_size_t)((row_width - 1) >> 2);
  188315. dp = row + (png_size_t)row_width - 1;
  188316. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  188317. for (i = 0; i < row_width; i++)
  188318. {
  188319. value = (*sp >> shift) & 0x03;
  188320. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  188321. (value << 6));
  188322. if (shift == 6)
  188323. {
  188324. shift = 0;
  188325. sp--;
  188326. }
  188327. else
  188328. shift += 2;
  188329. dp--;
  188330. }
  188331. break;
  188332. }
  188333. case 4:
  188334. {
  188335. gray = (png_uint_16)((gray&0x0f)*0x11);
  188336. sp = row + (png_size_t)((row_width - 1) >> 1);
  188337. dp = row + (png_size_t)row_width - 1;
  188338. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  188339. for (i = 0; i < row_width; i++)
  188340. {
  188341. value = (*sp >> shift) & 0x0f;
  188342. *dp = (png_byte)(value | (value << 4));
  188343. if (shift == 4)
  188344. {
  188345. shift = 0;
  188346. sp--;
  188347. }
  188348. else
  188349. shift = 4;
  188350. dp--;
  188351. }
  188352. break;
  188353. }
  188354. }
  188355. row_info->bit_depth = 8;
  188356. row_info->pixel_depth = 8;
  188357. row_info->rowbytes = row_width;
  188358. }
  188359. if (trans_value != NULL)
  188360. {
  188361. if (row_info->bit_depth == 8)
  188362. {
  188363. gray = gray & 0xff;
  188364. sp = row + (png_size_t)row_width - 1;
  188365. dp = row + (png_size_t)(row_width << 1) - 1;
  188366. for (i = 0; i < row_width; i++)
  188367. {
  188368. if (*sp == gray)
  188369. *dp-- = 0;
  188370. else
  188371. *dp-- = 0xff;
  188372. *dp-- = *sp--;
  188373. }
  188374. }
  188375. else if (row_info->bit_depth == 16)
  188376. {
  188377. png_byte gray_high = (gray >> 8) & 0xff;
  188378. png_byte gray_low = gray & 0xff;
  188379. sp = row + row_info->rowbytes - 1;
  188380. dp = row + (row_info->rowbytes << 1) - 1;
  188381. for (i = 0; i < row_width; i++)
  188382. {
  188383. if (*(sp-1) == gray_high && *(sp) == gray_low)
  188384. {
  188385. *dp-- = 0;
  188386. *dp-- = 0;
  188387. }
  188388. else
  188389. {
  188390. *dp-- = 0xff;
  188391. *dp-- = 0xff;
  188392. }
  188393. *dp-- = *sp--;
  188394. *dp-- = *sp--;
  188395. }
  188396. }
  188397. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  188398. row_info->channels = 2;
  188399. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  188400. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  188401. row_width);
  188402. }
  188403. }
  188404. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  188405. {
  188406. if (row_info->bit_depth == 8)
  188407. {
  188408. png_byte red = trans_value->red & 0xff;
  188409. png_byte green = trans_value->green & 0xff;
  188410. png_byte blue = trans_value->blue & 0xff;
  188411. sp = row + (png_size_t)row_info->rowbytes - 1;
  188412. dp = row + (png_size_t)(row_width << 2) - 1;
  188413. for (i = 0; i < row_width; i++)
  188414. {
  188415. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  188416. *dp-- = 0;
  188417. else
  188418. *dp-- = 0xff;
  188419. *dp-- = *sp--;
  188420. *dp-- = *sp--;
  188421. *dp-- = *sp--;
  188422. }
  188423. }
  188424. else if (row_info->bit_depth == 16)
  188425. {
  188426. png_byte red_high = (trans_value->red >> 8) & 0xff;
  188427. png_byte green_high = (trans_value->green >> 8) & 0xff;
  188428. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  188429. png_byte red_low = trans_value->red & 0xff;
  188430. png_byte green_low = trans_value->green & 0xff;
  188431. png_byte blue_low = trans_value->blue & 0xff;
  188432. sp = row + row_info->rowbytes - 1;
  188433. dp = row + (png_size_t)(row_width << 3) - 1;
  188434. for (i = 0; i < row_width; i++)
  188435. {
  188436. if (*(sp - 5) == red_high &&
  188437. *(sp - 4) == red_low &&
  188438. *(sp - 3) == green_high &&
  188439. *(sp - 2) == green_low &&
  188440. *(sp - 1) == blue_high &&
  188441. *(sp ) == blue_low)
  188442. {
  188443. *dp-- = 0;
  188444. *dp-- = 0;
  188445. }
  188446. else
  188447. {
  188448. *dp-- = 0xff;
  188449. *dp-- = 0xff;
  188450. }
  188451. *dp-- = *sp--;
  188452. *dp-- = *sp--;
  188453. *dp-- = *sp--;
  188454. *dp-- = *sp--;
  188455. *dp-- = *sp--;
  188456. *dp-- = *sp--;
  188457. }
  188458. }
  188459. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  188460. row_info->channels = 4;
  188461. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  188462. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188463. }
  188464. }
  188465. }
  188466. #endif
  188467. #if defined(PNG_READ_DITHER_SUPPORTED)
  188468. void /* PRIVATE */
  188469. png_do_dither(png_row_infop row_info, png_bytep row,
  188470. png_bytep palette_lookup, png_bytep dither_lookup)
  188471. {
  188472. png_bytep sp, dp;
  188473. png_uint_32 i;
  188474. png_uint_32 row_width=row_info->width;
  188475. png_debug(1, "in png_do_dither\n");
  188476. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188477. if (row != NULL && row_info != NULL)
  188478. #endif
  188479. {
  188480. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  188481. palette_lookup && row_info->bit_depth == 8)
  188482. {
  188483. int r, g, b, p;
  188484. sp = row;
  188485. dp = row;
  188486. for (i = 0; i < row_width; i++)
  188487. {
  188488. r = *sp++;
  188489. g = *sp++;
  188490. b = *sp++;
  188491. /* this looks real messy, but the compiler will reduce
  188492. it down to a reasonable formula. For example, with
  188493. 5 bits per color, we get:
  188494. p = (((r >> 3) & 0x1f) << 10) |
  188495. (((g >> 3) & 0x1f) << 5) |
  188496. ((b >> 3) & 0x1f);
  188497. */
  188498. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  188499. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  188500. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  188501. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  188502. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  188503. (PNG_DITHER_BLUE_BITS)) |
  188504. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  188505. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  188506. *dp++ = palette_lookup[p];
  188507. }
  188508. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  188509. row_info->channels = 1;
  188510. row_info->pixel_depth = row_info->bit_depth;
  188511. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188512. }
  188513. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  188514. palette_lookup != NULL && row_info->bit_depth == 8)
  188515. {
  188516. int r, g, b, p;
  188517. sp = row;
  188518. dp = row;
  188519. for (i = 0; i < row_width; i++)
  188520. {
  188521. r = *sp++;
  188522. g = *sp++;
  188523. b = *sp++;
  188524. sp++;
  188525. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  188526. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  188527. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  188528. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  188529. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  188530. (PNG_DITHER_BLUE_BITS)) |
  188531. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  188532. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  188533. *dp++ = palette_lookup[p];
  188534. }
  188535. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  188536. row_info->channels = 1;
  188537. row_info->pixel_depth = row_info->bit_depth;
  188538. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188539. }
  188540. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  188541. dither_lookup && row_info->bit_depth == 8)
  188542. {
  188543. sp = row;
  188544. for (i = 0; i < row_width; i++, sp++)
  188545. {
  188546. *sp = dither_lookup[*sp];
  188547. }
  188548. }
  188549. }
  188550. }
  188551. #endif
  188552. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188553. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188554. static PNG_CONST int png_gamma_shift[] =
  188555. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  188556. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  188557. * tables, we don't make a full table if we are reducing to 8-bit in
  188558. * the future. Note also how the gamma_16 tables are segmented so that
  188559. * we don't need to allocate > 64K chunks for a full 16-bit table.
  188560. */
  188561. void /* PRIVATE */
  188562. png_build_gamma_table(png_structp png_ptr)
  188563. {
  188564. png_debug(1, "in png_build_gamma_table\n");
  188565. if (png_ptr->bit_depth <= 8)
  188566. {
  188567. int i;
  188568. double g;
  188569. if (png_ptr->screen_gamma > .000001)
  188570. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  188571. else
  188572. g = 1.0;
  188573. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  188574. (png_uint_32)256);
  188575. for (i = 0; i < 256; i++)
  188576. {
  188577. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  188578. g) * 255.0 + .5);
  188579. }
  188580. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  188581. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  188582. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  188583. {
  188584. g = 1.0 / (png_ptr->gamma);
  188585. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  188586. (png_uint_32)256);
  188587. for (i = 0; i < 256; i++)
  188588. {
  188589. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  188590. g) * 255.0 + .5);
  188591. }
  188592. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  188593. (png_uint_32)256);
  188594. if(png_ptr->screen_gamma > 0.000001)
  188595. g = 1.0 / png_ptr->screen_gamma;
  188596. else
  188597. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  188598. for (i = 0; i < 256; i++)
  188599. {
  188600. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  188601. g) * 255.0 + .5);
  188602. }
  188603. }
  188604. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  188605. }
  188606. else
  188607. {
  188608. double g;
  188609. int i, j, shift, num;
  188610. int sig_bit;
  188611. png_uint_32 ig;
  188612. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  188613. {
  188614. sig_bit = (int)png_ptr->sig_bit.red;
  188615. if ((int)png_ptr->sig_bit.green > sig_bit)
  188616. sig_bit = png_ptr->sig_bit.green;
  188617. if ((int)png_ptr->sig_bit.blue > sig_bit)
  188618. sig_bit = png_ptr->sig_bit.blue;
  188619. }
  188620. else
  188621. {
  188622. sig_bit = (int)png_ptr->sig_bit.gray;
  188623. }
  188624. if (sig_bit > 0)
  188625. shift = 16 - sig_bit;
  188626. else
  188627. shift = 0;
  188628. if (png_ptr->transformations & PNG_16_TO_8)
  188629. {
  188630. if (shift < (16 - PNG_MAX_GAMMA_8))
  188631. shift = (16 - PNG_MAX_GAMMA_8);
  188632. }
  188633. if (shift > 8)
  188634. shift = 8;
  188635. if (shift < 0)
  188636. shift = 0;
  188637. png_ptr->gamma_shift = (png_byte)shift;
  188638. num = (1 << (8 - shift));
  188639. if (png_ptr->screen_gamma > .000001)
  188640. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  188641. else
  188642. g = 1.0;
  188643. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  188644. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  188645. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  188646. {
  188647. double fin, fout;
  188648. png_uint_32 last, max;
  188649. for (i = 0; i < num; i++)
  188650. {
  188651. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  188652. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  188653. }
  188654. g = 1.0 / g;
  188655. last = 0;
  188656. for (i = 0; i < 256; i++)
  188657. {
  188658. fout = ((double)i + 0.5) / 256.0;
  188659. fin = pow(fout, g);
  188660. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  188661. while (last <= max)
  188662. {
  188663. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  188664. [(int)(last >> (8 - shift))] = (png_uint_16)(
  188665. (png_uint_16)i | ((png_uint_16)i << 8));
  188666. last++;
  188667. }
  188668. }
  188669. while (last < ((png_uint_32)num << 8))
  188670. {
  188671. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  188672. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  188673. last++;
  188674. }
  188675. }
  188676. else
  188677. {
  188678. for (i = 0; i < num; i++)
  188679. {
  188680. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  188681. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  188682. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  188683. for (j = 0; j < 256; j++)
  188684. {
  188685. png_ptr->gamma_16_table[i][j] =
  188686. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  188687. 65535.0, g) * 65535.0 + .5);
  188688. }
  188689. }
  188690. }
  188691. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  188692. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  188693. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  188694. {
  188695. g = 1.0 / (png_ptr->gamma);
  188696. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  188697. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  188698. for (i = 0; i < num; i++)
  188699. {
  188700. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  188701. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  188702. ig = (((png_uint_32)i *
  188703. (png_uint_32)png_gamma_shift[shift]) >> 4);
  188704. for (j = 0; j < 256; j++)
  188705. {
  188706. png_ptr->gamma_16_to_1[i][j] =
  188707. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  188708. 65535.0, g) * 65535.0 + .5);
  188709. }
  188710. }
  188711. if(png_ptr->screen_gamma > 0.000001)
  188712. g = 1.0 / png_ptr->screen_gamma;
  188713. else
  188714. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  188715. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  188716. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  188717. for (i = 0; i < num; i++)
  188718. {
  188719. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  188720. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  188721. ig = (((png_uint_32)i *
  188722. (png_uint_32)png_gamma_shift[shift]) >> 4);
  188723. for (j = 0; j < 256; j++)
  188724. {
  188725. png_ptr->gamma_16_from_1[i][j] =
  188726. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  188727. 65535.0, g) * 65535.0 + .5);
  188728. }
  188729. }
  188730. }
  188731. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  188732. }
  188733. }
  188734. #endif
  188735. /* To do: install integer version of png_build_gamma_table here */
  188736. #endif
  188737. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  188738. /* undoes intrapixel differencing */
  188739. void /* PRIVATE */
  188740. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  188741. {
  188742. png_debug(1, "in png_do_read_intrapixel\n");
  188743. if (
  188744. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188745. row != NULL && row_info != NULL &&
  188746. #endif
  188747. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  188748. {
  188749. int bytes_per_pixel;
  188750. png_uint_32 row_width = row_info->width;
  188751. if (row_info->bit_depth == 8)
  188752. {
  188753. png_bytep rp;
  188754. png_uint_32 i;
  188755. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  188756. bytes_per_pixel = 3;
  188757. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188758. bytes_per_pixel = 4;
  188759. else
  188760. return;
  188761. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  188762. {
  188763. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  188764. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  188765. }
  188766. }
  188767. else if (row_info->bit_depth == 16)
  188768. {
  188769. png_bytep rp;
  188770. png_uint_32 i;
  188771. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  188772. bytes_per_pixel = 6;
  188773. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188774. bytes_per_pixel = 8;
  188775. else
  188776. return;
  188777. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  188778. {
  188779. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  188780. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  188781. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  188782. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  188783. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  188784. *(rp ) = (png_byte)((red >> 8) & 0xff);
  188785. *(rp+1) = (png_byte)(red & 0xff);
  188786. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  188787. *(rp+5) = (png_byte)(blue & 0xff);
  188788. }
  188789. }
  188790. }
  188791. }
  188792. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  188793. #endif /* PNG_READ_SUPPORTED */
  188794. /********* End of inlined file: pngrtran.c *********/
  188795. /********* Start of inlined file: pngrutil.c *********/
  188796. /* pngrutil.c - utilities to read a PNG file
  188797. *
  188798. * Last changed in libpng 1.2.21 [October 4, 2007]
  188799. * For conditions of distribution and use, see copyright notice in png.h
  188800. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188801. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188802. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188803. *
  188804. * This file contains routines that are only called from within
  188805. * libpng itself during the course of reading an image.
  188806. */
  188807. #define PNG_INTERNAL
  188808. #if defined(PNG_READ_SUPPORTED)
  188809. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  188810. # define WIN32_WCE_OLD
  188811. #endif
  188812. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188813. # if defined(WIN32_WCE_OLD)
  188814. /* strtod() function is not supported on WindowsCE */
  188815. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  188816. {
  188817. double result = 0;
  188818. int len;
  188819. wchar_t *str, *end;
  188820. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  188821. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  188822. if ( NULL != str )
  188823. {
  188824. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  188825. result = wcstod(str, &end);
  188826. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  188827. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  188828. png_free(png_ptr, str);
  188829. }
  188830. return result;
  188831. }
  188832. # else
  188833. # define png_strtod(p,a,b) strtod(a,b)
  188834. # endif
  188835. #endif
  188836. png_uint_32 PNGAPI
  188837. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  188838. {
  188839. png_uint_32 i = png_get_uint_32(buf);
  188840. if (i > PNG_UINT_31_MAX)
  188841. png_error(png_ptr, "PNG unsigned integer out of range.");
  188842. return (i);
  188843. }
  188844. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  188845. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  188846. png_uint_32 PNGAPI
  188847. png_get_uint_32(png_bytep buf)
  188848. {
  188849. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  188850. ((png_uint_32)(*(buf + 1)) << 16) +
  188851. ((png_uint_32)(*(buf + 2)) << 8) +
  188852. (png_uint_32)(*(buf + 3));
  188853. return (i);
  188854. }
  188855. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  188856. * data is stored in the PNG file in two's complement format, and it is
  188857. * assumed that the machine format for signed integers is the same. */
  188858. png_int_32 PNGAPI
  188859. png_get_int_32(png_bytep buf)
  188860. {
  188861. png_int_32 i = ((png_int_32)(*buf) << 24) +
  188862. ((png_int_32)(*(buf + 1)) << 16) +
  188863. ((png_int_32)(*(buf + 2)) << 8) +
  188864. (png_int_32)(*(buf + 3));
  188865. return (i);
  188866. }
  188867. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  188868. png_uint_16 PNGAPI
  188869. png_get_uint_16(png_bytep buf)
  188870. {
  188871. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  188872. (png_uint_16)(*(buf + 1)));
  188873. return (i);
  188874. }
  188875. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  188876. /* Read data, and (optionally) run it through the CRC. */
  188877. void /* PRIVATE */
  188878. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  188879. {
  188880. if(png_ptr == NULL) return;
  188881. png_read_data(png_ptr, buf, length);
  188882. png_calculate_crc(png_ptr, buf, length);
  188883. }
  188884. /* Optionally skip data and then check the CRC. Depending on whether we
  188885. are reading a ancillary or critical chunk, and how the program has set
  188886. things up, we may calculate the CRC on the data and print a message.
  188887. Returns '1' if there was a CRC error, '0' otherwise. */
  188888. int /* PRIVATE */
  188889. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  188890. {
  188891. png_size_t i;
  188892. png_size_t istop = png_ptr->zbuf_size;
  188893. for (i = (png_size_t)skip; i > istop; i -= istop)
  188894. {
  188895. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  188896. }
  188897. if (i)
  188898. {
  188899. png_crc_read(png_ptr, png_ptr->zbuf, i);
  188900. }
  188901. if (png_crc_error(png_ptr))
  188902. {
  188903. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  188904. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  188905. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  188906. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  188907. {
  188908. png_chunk_warning(png_ptr, "CRC error");
  188909. }
  188910. else
  188911. {
  188912. png_chunk_error(png_ptr, "CRC error");
  188913. }
  188914. return (1);
  188915. }
  188916. return (0);
  188917. }
  188918. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  188919. the data it has read thus far. */
  188920. int /* PRIVATE */
  188921. png_crc_error(png_structp png_ptr)
  188922. {
  188923. png_byte crc_bytes[4];
  188924. png_uint_32 crc;
  188925. int need_crc = 1;
  188926. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  188927. {
  188928. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  188929. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  188930. need_crc = 0;
  188931. }
  188932. else /* critical */
  188933. {
  188934. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  188935. need_crc = 0;
  188936. }
  188937. png_read_data(png_ptr, crc_bytes, 4);
  188938. if (need_crc)
  188939. {
  188940. crc = png_get_uint_32(crc_bytes);
  188941. return ((int)(crc != png_ptr->crc));
  188942. }
  188943. else
  188944. return (0);
  188945. }
  188946. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  188947. defined(PNG_READ_iCCP_SUPPORTED)
  188948. /*
  188949. * Decompress trailing data in a chunk. The assumption is that chunkdata
  188950. * points at an allocated area holding the contents of a chunk with a
  188951. * trailing compressed part. What we get back is an allocated area
  188952. * holding the original prefix part and an uncompressed version of the
  188953. * trailing part (the malloc area passed in is freed).
  188954. */
  188955. png_charp /* PRIVATE */
  188956. png_decompress_chunk(png_structp png_ptr, int comp_type,
  188957. png_charp chunkdata, png_size_t chunklength,
  188958. png_size_t prefix_size, png_size_t *newlength)
  188959. {
  188960. static PNG_CONST char msg[] = "Error decoding compressed text";
  188961. png_charp text;
  188962. png_size_t text_size;
  188963. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  188964. {
  188965. int ret = Z_OK;
  188966. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  188967. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  188968. png_ptr->zstream.next_out = png_ptr->zbuf;
  188969. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188970. text_size = 0;
  188971. text = NULL;
  188972. while (png_ptr->zstream.avail_in)
  188973. {
  188974. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188975. if (ret != Z_OK && ret != Z_STREAM_END)
  188976. {
  188977. if (png_ptr->zstream.msg != NULL)
  188978. png_warning(png_ptr, png_ptr->zstream.msg);
  188979. else
  188980. png_warning(png_ptr, msg);
  188981. inflateReset(&png_ptr->zstream);
  188982. png_ptr->zstream.avail_in = 0;
  188983. if (text == NULL)
  188984. {
  188985. text_size = prefix_size + png_sizeof(msg) + 1;
  188986. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  188987. if (text == NULL)
  188988. {
  188989. png_free(png_ptr,chunkdata);
  188990. png_error(png_ptr,"Not enough memory to decompress chunk");
  188991. }
  188992. png_memcpy(text, chunkdata, prefix_size);
  188993. }
  188994. text[text_size - 1] = 0x00;
  188995. /* Copy what we can of the error message into the text chunk */
  188996. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  188997. text_size = png_sizeof(msg) > text_size ? text_size :
  188998. png_sizeof(msg);
  188999. png_memcpy(text + prefix_size, msg, text_size + 1);
  189000. break;
  189001. }
  189002. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  189003. {
  189004. if (text == NULL)
  189005. {
  189006. text_size = prefix_size +
  189007. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189008. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  189009. if (text == NULL)
  189010. {
  189011. png_free(png_ptr,chunkdata);
  189012. png_error(png_ptr,"Not enough memory to decompress chunk.");
  189013. }
  189014. png_memcpy(text + prefix_size, png_ptr->zbuf,
  189015. text_size - prefix_size);
  189016. png_memcpy(text, chunkdata, prefix_size);
  189017. *(text + text_size) = 0x00;
  189018. }
  189019. else
  189020. {
  189021. png_charp tmp;
  189022. tmp = text;
  189023. text = (png_charp)png_malloc_warn(png_ptr,
  189024. (png_uint_32)(text_size +
  189025. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  189026. if (text == NULL)
  189027. {
  189028. png_free(png_ptr, tmp);
  189029. png_free(png_ptr, chunkdata);
  189030. png_error(png_ptr,"Not enough memory to decompress chunk..");
  189031. }
  189032. png_memcpy(text, tmp, text_size);
  189033. png_free(png_ptr, tmp);
  189034. png_memcpy(text + text_size, png_ptr->zbuf,
  189035. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  189036. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189037. *(text + text_size) = 0x00;
  189038. }
  189039. if (ret == Z_STREAM_END)
  189040. break;
  189041. else
  189042. {
  189043. png_ptr->zstream.next_out = png_ptr->zbuf;
  189044. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189045. }
  189046. }
  189047. }
  189048. if (ret != Z_STREAM_END)
  189049. {
  189050. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  189051. char umsg[52];
  189052. if (ret == Z_BUF_ERROR)
  189053. png_snprintf(umsg, 52,
  189054. "Buffer error in compressed datastream in %s chunk",
  189055. png_ptr->chunk_name);
  189056. else if (ret == Z_DATA_ERROR)
  189057. png_snprintf(umsg, 52,
  189058. "Data error in compressed datastream in %s chunk",
  189059. png_ptr->chunk_name);
  189060. else
  189061. png_snprintf(umsg, 52,
  189062. "Incomplete compressed datastream in %s chunk",
  189063. png_ptr->chunk_name);
  189064. png_warning(png_ptr, umsg);
  189065. #else
  189066. png_warning(png_ptr,
  189067. "Incomplete compressed datastream in chunk other than IDAT");
  189068. #endif
  189069. text_size=prefix_size;
  189070. if (text == NULL)
  189071. {
  189072. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  189073. if (text == NULL)
  189074. {
  189075. png_free(png_ptr, chunkdata);
  189076. png_error(png_ptr,"Not enough memory for text.");
  189077. }
  189078. png_memcpy(text, chunkdata, prefix_size);
  189079. }
  189080. *(text + text_size) = 0x00;
  189081. }
  189082. inflateReset(&png_ptr->zstream);
  189083. png_ptr->zstream.avail_in = 0;
  189084. png_free(png_ptr, chunkdata);
  189085. chunkdata = text;
  189086. *newlength=text_size;
  189087. }
  189088. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  189089. {
  189090. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  189091. char umsg[50];
  189092. png_snprintf(umsg, 50,
  189093. "Unknown zTXt compression type %d", comp_type);
  189094. png_warning(png_ptr, umsg);
  189095. #else
  189096. png_warning(png_ptr, "Unknown zTXt compression type");
  189097. #endif
  189098. *(chunkdata + prefix_size) = 0x00;
  189099. *newlength=prefix_size;
  189100. }
  189101. return chunkdata;
  189102. }
  189103. #endif
  189104. /* read and check the IDHR chunk */
  189105. void /* PRIVATE */
  189106. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189107. {
  189108. png_byte buf[13];
  189109. png_uint_32 width, height;
  189110. int bit_depth, color_type, compression_type, filter_type;
  189111. int interlace_type;
  189112. png_debug(1, "in png_handle_IHDR\n");
  189113. if (png_ptr->mode & PNG_HAVE_IHDR)
  189114. png_error(png_ptr, "Out of place IHDR");
  189115. /* check the length */
  189116. if (length != 13)
  189117. png_error(png_ptr, "Invalid IHDR chunk");
  189118. png_ptr->mode |= PNG_HAVE_IHDR;
  189119. png_crc_read(png_ptr, buf, 13);
  189120. png_crc_finish(png_ptr, 0);
  189121. width = png_get_uint_31(png_ptr, buf);
  189122. height = png_get_uint_31(png_ptr, buf + 4);
  189123. bit_depth = buf[8];
  189124. color_type = buf[9];
  189125. compression_type = buf[10];
  189126. filter_type = buf[11];
  189127. interlace_type = buf[12];
  189128. /* set internal variables */
  189129. png_ptr->width = width;
  189130. png_ptr->height = height;
  189131. png_ptr->bit_depth = (png_byte)bit_depth;
  189132. png_ptr->interlaced = (png_byte)interlace_type;
  189133. png_ptr->color_type = (png_byte)color_type;
  189134. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  189135. png_ptr->filter_type = (png_byte)filter_type;
  189136. #endif
  189137. png_ptr->compression_type = (png_byte)compression_type;
  189138. /* find number of channels */
  189139. switch (png_ptr->color_type)
  189140. {
  189141. case PNG_COLOR_TYPE_GRAY:
  189142. case PNG_COLOR_TYPE_PALETTE:
  189143. png_ptr->channels = 1;
  189144. break;
  189145. case PNG_COLOR_TYPE_RGB:
  189146. png_ptr->channels = 3;
  189147. break;
  189148. case PNG_COLOR_TYPE_GRAY_ALPHA:
  189149. png_ptr->channels = 2;
  189150. break;
  189151. case PNG_COLOR_TYPE_RGB_ALPHA:
  189152. png_ptr->channels = 4;
  189153. break;
  189154. }
  189155. /* set up other useful info */
  189156. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  189157. png_ptr->channels);
  189158. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  189159. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  189160. png_debug1(3,"channels = %d\n", png_ptr->channels);
  189161. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  189162. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  189163. color_type, interlace_type, compression_type, filter_type);
  189164. }
  189165. /* read and check the palette */
  189166. void /* PRIVATE */
  189167. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189168. {
  189169. png_color palette[PNG_MAX_PALETTE_LENGTH];
  189170. int num, i;
  189171. #ifndef PNG_NO_POINTER_INDEXING
  189172. png_colorp pal_ptr;
  189173. #endif
  189174. png_debug(1, "in png_handle_PLTE\n");
  189175. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189176. png_error(png_ptr, "Missing IHDR before PLTE");
  189177. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189178. {
  189179. png_warning(png_ptr, "Invalid PLTE after IDAT");
  189180. png_crc_finish(png_ptr, length);
  189181. return;
  189182. }
  189183. else if (png_ptr->mode & PNG_HAVE_PLTE)
  189184. png_error(png_ptr, "Duplicate PLTE chunk");
  189185. png_ptr->mode |= PNG_HAVE_PLTE;
  189186. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  189187. {
  189188. png_warning(png_ptr,
  189189. "Ignoring PLTE chunk in grayscale PNG");
  189190. png_crc_finish(png_ptr, length);
  189191. return;
  189192. }
  189193. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  189194. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  189195. {
  189196. png_crc_finish(png_ptr, length);
  189197. return;
  189198. }
  189199. #endif
  189200. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  189201. {
  189202. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  189203. {
  189204. png_warning(png_ptr, "Invalid palette chunk");
  189205. png_crc_finish(png_ptr, length);
  189206. return;
  189207. }
  189208. else
  189209. {
  189210. png_error(png_ptr, "Invalid palette chunk");
  189211. }
  189212. }
  189213. num = (int)length / 3;
  189214. #ifndef PNG_NO_POINTER_INDEXING
  189215. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  189216. {
  189217. png_byte buf[3];
  189218. png_crc_read(png_ptr, buf, 3);
  189219. pal_ptr->red = buf[0];
  189220. pal_ptr->green = buf[1];
  189221. pal_ptr->blue = buf[2];
  189222. }
  189223. #else
  189224. for (i = 0; i < num; i++)
  189225. {
  189226. png_byte buf[3];
  189227. png_crc_read(png_ptr, buf, 3);
  189228. /* don't depend upon png_color being any order */
  189229. palette[i].red = buf[0];
  189230. palette[i].green = buf[1];
  189231. palette[i].blue = buf[2];
  189232. }
  189233. #endif
  189234. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  189235. whatever the normal CRC configuration tells us. However, if we
  189236. have an RGB image, the PLTE can be considered ancillary, so
  189237. we will act as though it is. */
  189238. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  189239. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189240. #endif
  189241. {
  189242. png_crc_finish(png_ptr, 0);
  189243. }
  189244. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  189245. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  189246. {
  189247. /* If we don't want to use the data from an ancillary chunk,
  189248. we have two options: an error abort, or a warning and we
  189249. ignore the data in this chunk (which should be OK, since
  189250. it's considered ancillary for a RGB or RGBA image). */
  189251. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  189252. {
  189253. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  189254. {
  189255. png_chunk_error(png_ptr, "CRC error");
  189256. }
  189257. else
  189258. {
  189259. png_chunk_warning(png_ptr, "CRC error");
  189260. return;
  189261. }
  189262. }
  189263. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  189264. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  189265. {
  189266. png_chunk_warning(png_ptr, "CRC error");
  189267. }
  189268. }
  189269. #endif
  189270. png_set_PLTE(png_ptr, info_ptr, palette, num);
  189271. #if defined(PNG_READ_tRNS_SUPPORTED)
  189272. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189273. {
  189274. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  189275. {
  189276. if (png_ptr->num_trans > (png_uint_16)num)
  189277. {
  189278. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  189279. png_ptr->num_trans = (png_uint_16)num;
  189280. }
  189281. if (info_ptr->num_trans > (png_uint_16)num)
  189282. {
  189283. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  189284. info_ptr->num_trans = (png_uint_16)num;
  189285. }
  189286. }
  189287. }
  189288. #endif
  189289. }
  189290. void /* PRIVATE */
  189291. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189292. {
  189293. png_debug(1, "in png_handle_IEND\n");
  189294. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  189295. {
  189296. png_error(png_ptr, "No image in file");
  189297. }
  189298. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  189299. if (length != 0)
  189300. {
  189301. png_warning(png_ptr, "Incorrect IEND chunk length");
  189302. }
  189303. png_crc_finish(png_ptr, length);
  189304. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  189305. }
  189306. #if defined(PNG_READ_gAMA_SUPPORTED)
  189307. void /* PRIVATE */
  189308. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189309. {
  189310. png_fixed_point igamma;
  189311. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189312. float file_gamma;
  189313. #endif
  189314. png_byte buf[4];
  189315. png_debug(1, "in png_handle_gAMA\n");
  189316. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189317. png_error(png_ptr, "Missing IHDR before gAMA");
  189318. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189319. {
  189320. png_warning(png_ptr, "Invalid gAMA after IDAT");
  189321. png_crc_finish(png_ptr, length);
  189322. return;
  189323. }
  189324. else if (png_ptr->mode & PNG_HAVE_PLTE)
  189325. /* Should be an error, but we can cope with it */
  189326. png_warning(png_ptr, "Out of place gAMA chunk");
  189327. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  189328. #if defined(PNG_READ_sRGB_SUPPORTED)
  189329. && !(info_ptr->valid & PNG_INFO_sRGB)
  189330. #endif
  189331. )
  189332. {
  189333. png_warning(png_ptr, "Duplicate gAMA chunk");
  189334. png_crc_finish(png_ptr, length);
  189335. return;
  189336. }
  189337. if (length != 4)
  189338. {
  189339. png_warning(png_ptr, "Incorrect gAMA chunk length");
  189340. png_crc_finish(png_ptr, length);
  189341. return;
  189342. }
  189343. png_crc_read(png_ptr, buf, 4);
  189344. if (png_crc_finish(png_ptr, 0))
  189345. return;
  189346. igamma = (png_fixed_point)png_get_uint_32(buf);
  189347. /* check for zero gamma */
  189348. if (igamma == 0)
  189349. {
  189350. png_warning(png_ptr,
  189351. "Ignoring gAMA chunk with gamma=0");
  189352. return;
  189353. }
  189354. #if defined(PNG_READ_sRGB_SUPPORTED)
  189355. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  189356. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  189357. {
  189358. png_warning(png_ptr,
  189359. "Ignoring incorrect gAMA value when sRGB is also present");
  189360. #ifndef PNG_NO_CONSOLE_IO
  189361. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  189362. #endif
  189363. return;
  189364. }
  189365. #endif /* PNG_READ_sRGB_SUPPORTED */
  189366. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189367. file_gamma = (float)igamma / (float)100000.0;
  189368. # ifdef PNG_READ_GAMMA_SUPPORTED
  189369. png_ptr->gamma = file_gamma;
  189370. # endif
  189371. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  189372. #endif
  189373. #ifdef PNG_FIXED_POINT_SUPPORTED
  189374. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  189375. #endif
  189376. }
  189377. #endif
  189378. #if defined(PNG_READ_sBIT_SUPPORTED)
  189379. void /* PRIVATE */
  189380. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189381. {
  189382. png_size_t truelen;
  189383. png_byte buf[4];
  189384. png_debug(1, "in png_handle_sBIT\n");
  189385. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  189386. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189387. png_error(png_ptr, "Missing IHDR before sBIT");
  189388. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189389. {
  189390. png_warning(png_ptr, "Invalid sBIT after IDAT");
  189391. png_crc_finish(png_ptr, length);
  189392. return;
  189393. }
  189394. else if (png_ptr->mode & PNG_HAVE_PLTE)
  189395. {
  189396. /* Should be an error, but we can cope with it */
  189397. png_warning(png_ptr, "Out of place sBIT chunk");
  189398. }
  189399. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  189400. {
  189401. png_warning(png_ptr, "Duplicate sBIT chunk");
  189402. png_crc_finish(png_ptr, length);
  189403. return;
  189404. }
  189405. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189406. truelen = 3;
  189407. else
  189408. truelen = (png_size_t)png_ptr->channels;
  189409. if (length != truelen || length > 4)
  189410. {
  189411. png_warning(png_ptr, "Incorrect sBIT chunk length");
  189412. png_crc_finish(png_ptr, length);
  189413. return;
  189414. }
  189415. png_crc_read(png_ptr, buf, truelen);
  189416. if (png_crc_finish(png_ptr, 0))
  189417. return;
  189418. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  189419. {
  189420. png_ptr->sig_bit.red = buf[0];
  189421. png_ptr->sig_bit.green = buf[1];
  189422. png_ptr->sig_bit.blue = buf[2];
  189423. png_ptr->sig_bit.alpha = buf[3];
  189424. }
  189425. else
  189426. {
  189427. png_ptr->sig_bit.gray = buf[0];
  189428. png_ptr->sig_bit.red = buf[0];
  189429. png_ptr->sig_bit.green = buf[0];
  189430. png_ptr->sig_bit.blue = buf[0];
  189431. png_ptr->sig_bit.alpha = buf[1];
  189432. }
  189433. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  189434. }
  189435. #endif
  189436. #if defined(PNG_READ_cHRM_SUPPORTED)
  189437. void /* PRIVATE */
  189438. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189439. {
  189440. png_byte buf[4];
  189441. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189442. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  189443. #endif
  189444. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  189445. int_y_green, int_x_blue, int_y_blue;
  189446. png_uint_32 uint_x, uint_y;
  189447. png_debug(1, "in png_handle_cHRM\n");
  189448. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189449. png_error(png_ptr, "Missing IHDR before cHRM");
  189450. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189451. {
  189452. png_warning(png_ptr, "Invalid cHRM after IDAT");
  189453. png_crc_finish(png_ptr, length);
  189454. return;
  189455. }
  189456. else if (png_ptr->mode & PNG_HAVE_PLTE)
  189457. /* Should be an error, but we can cope with it */
  189458. png_warning(png_ptr, "Missing PLTE before cHRM");
  189459. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  189460. #if defined(PNG_READ_sRGB_SUPPORTED)
  189461. && !(info_ptr->valid & PNG_INFO_sRGB)
  189462. #endif
  189463. )
  189464. {
  189465. png_warning(png_ptr, "Duplicate cHRM chunk");
  189466. png_crc_finish(png_ptr, length);
  189467. return;
  189468. }
  189469. if (length != 32)
  189470. {
  189471. png_warning(png_ptr, "Incorrect cHRM chunk length");
  189472. png_crc_finish(png_ptr, length);
  189473. return;
  189474. }
  189475. png_crc_read(png_ptr, buf, 4);
  189476. uint_x = png_get_uint_32(buf);
  189477. png_crc_read(png_ptr, buf, 4);
  189478. uint_y = png_get_uint_32(buf);
  189479. if (uint_x > 80000L || uint_y > 80000L ||
  189480. uint_x + uint_y > 100000L)
  189481. {
  189482. png_warning(png_ptr, "Invalid cHRM white point");
  189483. png_crc_finish(png_ptr, 24);
  189484. return;
  189485. }
  189486. int_x_white = (png_fixed_point)uint_x;
  189487. int_y_white = (png_fixed_point)uint_y;
  189488. png_crc_read(png_ptr, buf, 4);
  189489. uint_x = png_get_uint_32(buf);
  189490. png_crc_read(png_ptr, buf, 4);
  189491. uint_y = png_get_uint_32(buf);
  189492. if (uint_x + uint_y > 100000L)
  189493. {
  189494. png_warning(png_ptr, "Invalid cHRM red point");
  189495. png_crc_finish(png_ptr, 16);
  189496. return;
  189497. }
  189498. int_x_red = (png_fixed_point)uint_x;
  189499. int_y_red = (png_fixed_point)uint_y;
  189500. png_crc_read(png_ptr, buf, 4);
  189501. uint_x = png_get_uint_32(buf);
  189502. png_crc_read(png_ptr, buf, 4);
  189503. uint_y = png_get_uint_32(buf);
  189504. if (uint_x + uint_y > 100000L)
  189505. {
  189506. png_warning(png_ptr, "Invalid cHRM green point");
  189507. png_crc_finish(png_ptr, 8);
  189508. return;
  189509. }
  189510. int_x_green = (png_fixed_point)uint_x;
  189511. int_y_green = (png_fixed_point)uint_y;
  189512. png_crc_read(png_ptr, buf, 4);
  189513. uint_x = png_get_uint_32(buf);
  189514. png_crc_read(png_ptr, buf, 4);
  189515. uint_y = png_get_uint_32(buf);
  189516. if (uint_x + uint_y > 100000L)
  189517. {
  189518. png_warning(png_ptr, "Invalid cHRM blue point");
  189519. png_crc_finish(png_ptr, 0);
  189520. return;
  189521. }
  189522. int_x_blue = (png_fixed_point)uint_x;
  189523. int_y_blue = (png_fixed_point)uint_y;
  189524. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189525. white_x = (float)int_x_white / (float)100000.0;
  189526. white_y = (float)int_y_white / (float)100000.0;
  189527. red_x = (float)int_x_red / (float)100000.0;
  189528. red_y = (float)int_y_red / (float)100000.0;
  189529. green_x = (float)int_x_green / (float)100000.0;
  189530. green_y = (float)int_y_green / (float)100000.0;
  189531. blue_x = (float)int_x_blue / (float)100000.0;
  189532. blue_y = (float)int_y_blue / (float)100000.0;
  189533. #endif
  189534. #if defined(PNG_READ_sRGB_SUPPORTED)
  189535. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  189536. {
  189537. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  189538. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  189539. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  189540. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  189541. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  189542. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  189543. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  189544. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  189545. {
  189546. png_warning(png_ptr,
  189547. "Ignoring incorrect cHRM value when sRGB is also present");
  189548. #ifndef PNG_NO_CONSOLE_IO
  189549. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189550. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  189551. white_x, white_y, red_x, red_y);
  189552. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  189553. green_x, green_y, blue_x, blue_y);
  189554. #else
  189555. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  189556. int_x_white, int_y_white, int_x_red, int_y_red);
  189557. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  189558. int_x_green, int_y_green, int_x_blue, int_y_blue);
  189559. #endif
  189560. #endif /* PNG_NO_CONSOLE_IO */
  189561. }
  189562. png_crc_finish(png_ptr, 0);
  189563. return;
  189564. }
  189565. #endif /* PNG_READ_sRGB_SUPPORTED */
  189566. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189567. png_set_cHRM(png_ptr, info_ptr,
  189568. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  189569. #endif
  189570. #ifdef PNG_FIXED_POINT_SUPPORTED
  189571. png_set_cHRM_fixed(png_ptr, info_ptr,
  189572. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  189573. int_y_green, int_x_blue, int_y_blue);
  189574. #endif
  189575. if (png_crc_finish(png_ptr, 0))
  189576. return;
  189577. }
  189578. #endif
  189579. #if defined(PNG_READ_sRGB_SUPPORTED)
  189580. void /* PRIVATE */
  189581. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189582. {
  189583. int intent;
  189584. png_byte buf[1];
  189585. png_debug(1, "in png_handle_sRGB\n");
  189586. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189587. png_error(png_ptr, "Missing IHDR before sRGB");
  189588. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189589. {
  189590. png_warning(png_ptr, "Invalid sRGB after IDAT");
  189591. png_crc_finish(png_ptr, length);
  189592. return;
  189593. }
  189594. else if (png_ptr->mode & PNG_HAVE_PLTE)
  189595. /* Should be an error, but we can cope with it */
  189596. png_warning(png_ptr, "Out of place sRGB chunk");
  189597. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  189598. {
  189599. png_warning(png_ptr, "Duplicate sRGB chunk");
  189600. png_crc_finish(png_ptr, length);
  189601. return;
  189602. }
  189603. if (length != 1)
  189604. {
  189605. png_warning(png_ptr, "Incorrect sRGB chunk length");
  189606. png_crc_finish(png_ptr, length);
  189607. return;
  189608. }
  189609. png_crc_read(png_ptr, buf, 1);
  189610. if (png_crc_finish(png_ptr, 0))
  189611. return;
  189612. intent = buf[0];
  189613. /* check for bad intent */
  189614. if (intent >= PNG_sRGB_INTENT_LAST)
  189615. {
  189616. png_warning(png_ptr, "Unknown sRGB intent");
  189617. return;
  189618. }
  189619. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  189620. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  189621. {
  189622. png_fixed_point igamma;
  189623. #ifdef PNG_FIXED_POINT_SUPPORTED
  189624. igamma=info_ptr->int_gamma;
  189625. #else
  189626. # ifdef PNG_FLOATING_POINT_SUPPORTED
  189627. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  189628. # endif
  189629. #endif
  189630. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  189631. {
  189632. png_warning(png_ptr,
  189633. "Ignoring incorrect gAMA value when sRGB is also present");
  189634. #ifndef PNG_NO_CONSOLE_IO
  189635. # ifdef PNG_FIXED_POINT_SUPPORTED
  189636. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  189637. # else
  189638. # ifdef PNG_FLOATING_POINT_SUPPORTED
  189639. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  189640. # endif
  189641. # endif
  189642. #endif
  189643. }
  189644. }
  189645. #endif /* PNG_READ_gAMA_SUPPORTED */
  189646. #ifdef PNG_READ_cHRM_SUPPORTED
  189647. #ifdef PNG_FIXED_POINT_SUPPORTED
  189648. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  189649. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  189650. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  189651. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  189652. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  189653. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  189654. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  189655. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  189656. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  189657. {
  189658. png_warning(png_ptr,
  189659. "Ignoring incorrect cHRM value when sRGB is also present");
  189660. }
  189661. #endif /* PNG_FIXED_POINT_SUPPORTED */
  189662. #endif /* PNG_READ_cHRM_SUPPORTED */
  189663. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  189664. }
  189665. #endif /* PNG_READ_sRGB_SUPPORTED */
  189666. #if defined(PNG_READ_iCCP_SUPPORTED)
  189667. void /* PRIVATE */
  189668. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189669. /* Note: this does not properly handle chunks that are > 64K under DOS */
  189670. {
  189671. png_charp chunkdata;
  189672. png_byte compression_type;
  189673. png_bytep pC;
  189674. png_charp profile;
  189675. png_uint_32 skip = 0;
  189676. png_uint_32 profile_size, profile_length;
  189677. png_size_t slength, prefix_length, data_length;
  189678. png_debug(1, "in png_handle_iCCP\n");
  189679. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189680. png_error(png_ptr, "Missing IHDR before iCCP");
  189681. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189682. {
  189683. png_warning(png_ptr, "Invalid iCCP after IDAT");
  189684. png_crc_finish(png_ptr, length);
  189685. return;
  189686. }
  189687. else if (png_ptr->mode & PNG_HAVE_PLTE)
  189688. /* Should be an error, but we can cope with it */
  189689. png_warning(png_ptr, "Out of place iCCP chunk");
  189690. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  189691. {
  189692. png_warning(png_ptr, "Duplicate iCCP chunk");
  189693. png_crc_finish(png_ptr, length);
  189694. return;
  189695. }
  189696. #ifdef PNG_MAX_MALLOC_64K
  189697. if (length > (png_uint_32)65535L)
  189698. {
  189699. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  189700. skip = length - (png_uint_32)65535L;
  189701. length = (png_uint_32)65535L;
  189702. }
  189703. #endif
  189704. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  189705. slength = (png_size_t)length;
  189706. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  189707. if (png_crc_finish(png_ptr, skip))
  189708. {
  189709. png_free(png_ptr, chunkdata);
  189710. return;
  189711. }
  189712. chunkdata[slength] = 0x00;
  189713. for (profile = chunkdata; *profile; profile++)
  189714. /* empty loop to find end of name */ ;
  189715. ++profile;
  189716. /* there should be at least one zero (the compression type byte)
  189717. following the separator, and we should be on it */
  189718. if ( profile >= chunkdata + slength - 1)
  189719. {
  189720. png_free(png_ptr, chunkdata);
  189721. png_warning(png_ptr, "Malformed iCCP chunk");
  189722. return;
  189723. }
  189724. /* compression_type should always be zero */
  189725. compression_type = *profile++;
  189726. if (compression_type)
  189727. {
  189728. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  189729. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  189730. wrote nonzero) */
  189731. }
  189732. prefix_length = profile - chunkdata;
  189733. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  189734. slength, prefix_length, &data_length);
  189735. profile_length = data_length - prefix_length;
  189736. if ( prefix_length > data_length || profile_length < 4)
  189737. {
  189738. png_free(png_ptr, chunkdata);
  189739. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  189740. return;
  189741. }
  189742. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  189743. pC = (png_bytep)(chunkdata+prefix_length);
  189744. profile_size = ((*(pC ))<<24) |
  189745. ((*(pC+1))<<16) |
  189746. ((*(pC+2))<< 8) |
  189747. ((*(pC+3)) );
  189748. if(profile_size < profile_length)
  189749. profile_length = profile_size;
  189750. if(profile_size > profile_length)
  189751. {
  189752. png_free(png_ptr, chunkdata);
  189753. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  189754. return;
  189755. }
  189756. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  189757. chunkdata + prefix_length, profile_length);
  189758. png_free(png_ptr, chunkdata);
  189759. }
  189760. #endif /* PNG_READ_iCCP_SUPPORTED */
  189761. #if defined(PNG_READ_sPLT_SUPPORTED)
  189762. void /* PRIVATE */
  189763. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189764. /* Note: this does not properly handle chunks that are > 64K under DOS */
  189765. {
  189766. png_bytep chunkdata;
  189767. png_bytep entry_start;
  189768. png_sPLT_t new_palette;
  189769. #ifdef PNG_NO_POINTER_INDEXING
  189770. png_sPLT_entryp pp;
  189771. #endif
  189772. int data_length, entry_size, i;
  189773. png_uint_32 skip = 0;
  189774. png_size_t slength;
  189775. png_debug(1, "in png_handle_sPLT\n");
  189776. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189777. png_error(png_ptr, "Missing IHDR before sPLT");
  189778. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189779. {
  189780. png_warning(png_ptr, "Invalid sPLT after IDAT");
  189781. png_crc_finish(png_ptr, length);
  189782. return;
  189783. }
  189784. #ifdef PNG_MAX_MALLOC_64K
  189785. if (length > (png_uint_32)65535L)
  189786. {
  189787. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  189788. skip = length - (png_uint_32)65535L;
  189789. length = (png_uint_32)65535L;
  189790. }
  189791. #endif
  189792. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  189793. slength = (png_size_t)length;
  189794. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  189795. if (png_crc_finish(png_ptr, skip))
  189796. {
  189797. png_free(png_ptr, chunkdata);
  189798. return;
  189799. }
  189800. chunkdata[slength] = 0x00;
  189801. for (entry_start = chunkdata; *entry_start; entry_start++)
  189802. /* empty loop to find end of name */ ;
  189803. ++entry_start;
  189804. /* a sample depth should follow the separator, and we should be on it */
  189805. if (entry_start > chunkdata + slength - 2)
  189806. {
  189807. png_free(png_ptr, chunkdata);
  189808. png_warning(png_ptr, "malformed sPLT chunk");
  189809. return;
  189810. }
  189811. new_palette.depth = *entry_start++;
  189812. entry_size = (new_palette.depth == 8 ? 6 : 10);
  189813. data_length = (slength - (entry_start - chunkdata));
  189814. /* integrity-check the data length */
  189815. if (data_length % entry_size)
  189816. {
  189817. png_free(png_ptr, chunkdata);
  189818. png_warning(png_ptr, "sPLT chunk has bad length");
  189819. return;
  189820. }
  189821. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  189822. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  189823. png_sizeof(png_sPLT_entry)))
  189824. {
  189825. png_warning(png_ptr, "sPLT chunk too long");
  189826. return;
  189827. }
  189828. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  189829. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  189830. if (new_palette.entries == NULL)
  189831. {
  189832. png_warning(png_ptr, "sPLT chunk requires too much memory");
  189833. return;
  189834. }
  189835. #ifndef PNG_NO_POINTER_INDEXING
  189836. for (i = 0; i < new_palette.nentries; i++)
  189837. {
  189838. png_sPLT_entryp pp = new_palette.entries + i;
  189839. if (new_palette.depth == 8)
  189840. {
  189841. pp->red = *entry_start++;
  189842. pp->green = *entry_start++;
  189843. pp->blue = *entry_start++;
  189844. pp->alpha = *entry_start++;
  189845. }
  189846. else
  189847. {
  189848. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  189849. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  189850. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  189851. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  189852. }
  189853. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  189854. }
  189855. #else
  189856. pp = new_palette.entries;
  189857. for (i = 0; i < new_palette.nentries; i++)
  189858. {
  189859. if (new_palette.depth == 8)
  189860. {
  189861. pp[i].red = *entry_start++;
  189862. pp[i].green = *entry_start++;
  189863. pp[i].blue = *entry_start++;
  189864. pp[i].alpha = *entry_start++;
  189865. }
  189866. else
  189867. {
  189868. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  189869. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  189870. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  189871. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  189872. }
  189873. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  189874. }
  189875. #endif
  189876. /* discard all chunk data except the name and stash that */
  189877. new_palette.name = (png_charp)chunkdata;
  189878. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  189879. png_free(png_ptr, chunkdata);
  189880. png_free(png_ptr, new_palette.entries);
  189881. }
  189882. #endif /* PNG_READ_sPLT_SUPPORTED */
  189883. #if defined(PNG_READ_tRNS_SUPPORTED)
  189884. void /* PRIVATE */
  189885. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189886. {
  189887. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  189888. int bit_mask;
  189889. png_debug(1, "in png_handle_tRNS\n");
  189890. /* For non-indexed color, mask off any bits in the tRNS value that
  189891. * exceed the bit depth. Some creators were writing extra bits there.
  189892. * This is not needed for indexed color. */
  189893. bit_mask = (1 << png_ptr->bit_depth) - 1;
  189894. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189895. png_error(png_ptr, "Missing IHDR before tRNS");
  189896. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189897. {
  189898. png_warning(png_ptr, "Invalid tRNS after IDAT");
  189899. png_crc_finish(png_ptr, length);
  189900. return;
  189901. }
  189902. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  189903. {
  189904. png_warning(png_ptr, "Duplicate tRNS chunk");
  189905. png_crc_finish(png_ptr, length);
  189906. return;
  189907. }
  189908. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  189909. {
  189910. png_byte buf[2];
  189911. if (length != 2)
  189912. {
  189913. png_warning(png_ptr, "Incorrect tRNS chunk length");
  189914. png_crc_finish(png_ptr, length);
  189915. return;
  189916. }
  189917. png_crc_read(png_ptr, buf, 2);
  189918. png_ptr->num_trans = 1;
  189919. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  189920. }
  189921. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  189922. {
  189923. png_byte buf[6];
  189924. if (length != 6)
  189925. {
  189926. png_warning(png_ptr, "Incorrect tRNS chunk length");
  189927. png_crc_finish(png_ptr, length);
  189928. return;
  189929. }
  189930. png_crc_read(png_ptr, buf, (png_size_t)length);
  189931. png_ptr->num_trans = 1;
  189932. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  189933. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  189934. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  189935. }
  189936. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189937. {
  189938. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  189939. {
  189940. /* Should be an error, but we can cope with it. */
  189941. png_warning(png_ptr, "Missing PLTE before tRNS");
  189942. }
  189943. if (length > (png_uint_32)png_ptr->num_palette ||
  189944. length > PNG_MAX_PALETTE_LENGTH)
  189945. {
  189946. png_warning(png_ptr, "Incorrect tRNS chunk length");
  189947. png_crc_finish(png_ptr, length);
  189948. return;
  189949. }
  189950. if (length == 0)
  189951. {
  189952. png_warning(png_ptr, "Zero length tRNS chunk");
  189953. png_crc_finish(png_ptr, length);
  189954. return;
  189955. }
  189956. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  189957. png_ptr->num_trans = (png_uint_16)length;
  189958. }
  189959. else
  189960. {
  189961. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  189962. png_crc_finish(png_ptr, length);
  189963. return;
  189964. }
  189965. if (png_crc_finish(png_ptr, 0))
  189966. {
  189967. png_ptr->num_trans = 0;
  189968. return;
  189969. }
  189970. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  189971. &(png_ptr->trans_values));
  189972. }
  189973. #endif
  189974. #if defined(PNG_READ_bKGD_SUPPORTED)
  189975. void /* PRIVATE */
  189976. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189977. {
  189978. png_size_t truelen;
  189979. png_byte buf[6];
  189980. png_debug(1, "in png_handle_bKGD\n");
  189981. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189982. png_error(png_ptr, "Missing IHDR before bKGD");
  189983. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189984. {
  189985. png_warning(png_ptr, "Invalid bKGD after IDAT");
  189986. png_crc_finish(png_ptr, length);
  189987. return;
  189988. }
  189989. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  189990. !(png_ptr->mode & PNG_HAVE_PLTE))
  189991. {
  189992. png_warning(png_ptr, "Missing PLTE before bKGD");
  189993. png_crc_finish(png_ptr, length);
  189994. return;
  189995. }
  189996. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  189997. {
  189998. png_warning(png_ptr, "Duplicate bKGD chunk");
  189999. png_crc_finish(png_ptr, length);
  190000. return;
  190001. }
  190002. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190003. truelen = 1;
  190004. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190005. truelen = 6;
  190006. else
  190007. truelen = 2;
  190008. if (length != truelen)
  190009. {
  190010. png_warning(png_ptr, "Incorrect bKGD chunk length");
  190011. png_crc_finish(png_ptr, length);
  190012. return;
  190013. }
  190014. png_crc_read(png_ptr, buf, truelen);
  190015. if (png_crc_finish(png_ptr, 0))
  190016. return;
  190017. /* We convert the index value into RGB components so that we can allow
  190018. * arbitrary RGB values for background when we have transparency, and
  190019. * so it is easy to determine the RGB values of the background color
  190020. * from the info_ptr struct. */
  190021. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190022. {
  190023. png_ptr->background.index = buf[0];
  190024. if(info_ptr->num_palette)
  190025. {
  190026. if(buf[0] > info_ptr->num_palette)
  190027. {
  190028. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  190029. return;
  190030. }
  190031. png_ptr->background.red =
  190032. (png_uint_16)png_ptr->palette[buf[0]].red;
  190033. png_ptr->background.green =
  190034. (png_uint_16)png_ptr->palette[buf[0]].green;
  190035. png_ptr->background.blue =
  190036. (png_uint_16)png_ptr->palette[buf[0]].blue;
  190037. }
  190038. }
  190039. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  190040. {
  190041. png_ptr->background.red =
  190042. png_ptr->background.green =
  190043. png_ptr->background.blue =
  190044. png_ptr->background.gray = png_get_uint_16(buf);
  190045. }
  190046. else
  190047. {
  190048. png_ptr->background.red = png_get_uint_16(buf);
  190049. png_ptr->background.green = png_get_uint_16(buf + 2);
  190050. png_ptr->background.blue = png_get_uint_16(buf + 4);
  190051. }
  190052. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  190053. }
  190054. #endif
  190055. #if defined(PNG_READ_hIST_SUPPORTED)
  190056. void /* PRIVATE */
  190057. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190058. {
  190059. unsigned int num, i;
  190060. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  190061. png_debug(1, "in png_handle_hIST\n");
  190062. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190063. png_error(png_ptr, "Missing IHDR before hIST");
  190064. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190065. {
  190066. png_warning(png_ptr, "Invalid hIST after IDAT");
  190067. png_crc_finish(png_ptr, length);
  190068. return;
  190069. }
  190070. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  190071. {
  190072. png_warning(png_ptr, "Missing PLTE before hIST");
  190073. png_crc_finish(png_ptr, length);
  190074. return;
  190075. }
  190076. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  190077. {
  190078. png_warning(png_ptr, "Duplicate hIST chunk");
  190079. png_crc_finish(png_ptr, length);
  190080. return;
  190081. }
  190082. num = length / 2 ;
  190083. if (num != (unsigned int) png_ptr->num_palette || num >
  190084. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  190085. {
  190086. png_warning(png_ptr, "Incorrect hIST chunk length");
  190087. png_crc_finish(png_ptr, length);
  190088. return;
  190089. }
  190090. for (i = 0; i < num; i++)
  190091. {
  190092. png_byte buf[2];
  190093. png_crc_read(png_ptr, buf, 2);
  190094. readbuf[i] = png_get_uint_16(buf);
  190095. }
  190096. if (png_crc_finish(png_ptr, 0))
  190097. return;
  190098. png_set_hIST(png_ptr, info_ptr, readbuf);
  190099. }
  190100. #endif
  190101. #if defined(PNG_READ_pHYs_SUPPORTED)
  190102. void /* PRIVATE */
  190103. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190104. {
  190105. png_byte buf[9];
  190106. png_uint_32 res_x, res_y;
  190107. int unit_type;
  190108. png_debug(1, "in png_handle_pHYs\n");
  190109. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190110. png_error(png_ptr, "Missing IHDR before pHYs");
  190111. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190112. {
  190113. png_warning(png_ptr, "Invalid pHYs after IDAT");
  190114. png_crc_finish(png_ptr, length);
  190115. return;
  190116. }
  190117. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  190118. {
  190119. png_warning(png_ptr, "Duplicate pHYs chunk");
  190120. png_crc_finish(png_ptr, length);
  190121. return;
  190122. }
  190123. if (length != 9)
  190124. {
  190125. png_warning(png_ptr, "Incorrect pHYs chunk length");
  190126. png_crc_finish(png_ptr, length);
  190127. return;
  190128. }
  190129. png_crc_read(png_ptr, buf, 9);
  190130. if (png_crc_finish(png_ptr, 0))
  190131. return;
  190132. res_x = png_get_uint_32(buf);
  190133. res_y = png_get_uint_32(buf + 4);
  190134. unit_type = buf[8];
  190135. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  190136. }
  190137. #endif
  190138. #if defined(PNG_READ_oFFs_SUPPORTED)
  190139. void /* PRIVATE */
  190140. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190141. {
  190142. png_byte buf[9];
  190143. png_int_32 offset_x, offset_y;
  190144. int unit_type;
  190145. png_debug(1, "in png_handle_oFFs\n");
  190146. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190147. png_error(png_ptr, "Missing IHDR before oFFs");
  190148. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190149. {
  190150. png_warning(png_ptr, "Invalid oFFs after IDAT");
  190151. png_crc_finish(png_ptr, length);
  190152. return;
  190153. }
  190154. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  190155. {
  190156. png_warning(png_ptr, "Duplicate oFFs chunk");
  190157. png_crc_finish(png_ptr, length);
  190158. return;
  190159. }
  190160. if (length != 9)
  190161. {
  190162. png_warning(png_ptr, "Incorrect oFFs chunk length");
  190163. png_crc_finish(png_ptr, length);
  190164. return;
  190165. }
  190166. png_crc_read(png_ptr, buf, 9);
  190167. if (png_crc_finish(png_ptr, 0))
  190168. return;
  190169. offset_x = png_get_int_32(buf);
  190170. offset_y = png_get_int_32(buf + 4);
  190171. unit_type = buf[8];
  190172. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  190173. }
  190174. #endif
  190175. #if defined(PNG_READ_pCAL_SUPPORTED)
  190176. /* read the pCAL chunk (described in the PNG Extensions document) */
  190177. void /* PRIVATE */
  190178. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190179. {
  190180. png_charp purpose;
  190181. png_int_32 X0, X1;
  190182. png_byte type, nparams;
  190183. png_charp buf, units, endptr;
  190184. png_charpp params;
  190185. png_size_t slength;
  190186. int i;
  190187. png_debug(1, "in png_handle_pCAL\n");
  190188. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190189. png_error(png_ptr, "Missing IHDR before pCAL");
  190190. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190191. {
  190192. png_warning(png_ptr, "Invalid pCAL after IDAT");
  190193. png_crc_finish(png_ptr, length);
  190194. return;
  190195. }
  190196. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  190197. {
  190198. png_warning(png_ptr, "Duplicate pCAL chunk");
  190199. png_crc_finish(png_ptr, length);
  190200. return;
  190201. }
  190202. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  190203. length + 1);
  190204. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  190205. if (purpose == NULL)
  190206. {
  190207. png_warning(png_ptr, "No memory for pCAL purpose.");
  190208. return;
  190209. }
  190210. slength = (png_size_t)length;
  190211. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  190212. if (png_crc_finish(png_ptr, 0))
  190213. {
  190214. png_free(png_ptr, purpose);
  190215. return;
  190216. }
  190217. purpose[slength] = 0x00; /* null terminate the last string */
  190218. png_debug(3, "Finding end of pCAL purpose string\n");
  190219. for (buf = purpose; *buf; buf++)
  190220. /* empty loop */ ;
  190221. endptr = purpose + slength;
  190222. /* We need to have at least 12 bytes after the purpose string
  190223. in order to get the parameter information. */
  190224. if (endptr <= buf + 12)
  190225. {
  190226. png_warning(png_ptr, "Invalid pCAL data");
  190227. png_free(png_ptr, purpose);
  190228. return;
  190229. }
  190230. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  190231. X0 = png_get_int_32((png_bytep)buf+1);
  190232. X1 = png_get_int_32((png_bytep)buf+5);
  190233. type = buf[9];
  190234. nparams = buf[10];
  190235. units = buf + 11;
  190236. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  190237. /* Check that we have the right number of parameters for known
  190238. equation types. */
  190239. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  190240. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  190241. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  190242. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  190243. {
  190244. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  190245. png_free(png_ptr, purpose);
  190246. return;
  190247. }
  190248. else if (type >= PNG_EQUATION_LAST)
  190249. {
  190250. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  190251. }
  190252. for (buf = units; *buf; buf++)
  190253. /* Empty loop to move past the units string. */ ;
  190254. png_debug(3, "Allocating pCAL parameters array\n");
  190255. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  190256. *png_sizeof(png_charp))) ;
  190257. if (params == NULL)
  190258. {
  190259. png_free(png_ptr, purpose);
  190260. png_warning(png_ptr, "No memory for pCAL params.");
  190261. return;
  190262. }
  190263. /* Get pointers to the start of each parameter string. */
  190264. for (i = 0; i < (int)nparams; i++)
  190265. {
  190266. buf++; /* Skip the null string terminator from previous parameter. */
  190267. png_debug1(3, "Reading pCAL parameter %d\n", i);
  190268. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  190269. /* Empty loop to move past each parameter string */ ;
  190270. /* Make sure we haven't run out of data yet */
  190271. if (buf > endptr)
  190272. {
  190273. png_warning(png_ptr, "Invalid pCAL data");
  190274. png_free(png_ptr, purpose);
  190275. png_free(png_ptr, params);
  190276. return;
  190277. }
  190278. }
  190279. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  190280. units, params);
  190281. png_free(png_ptr, purpose);
  190282. png_free(png_ptr, params);
  190283. }
  190284. #endif
  190285. #if defined(PNG_READ_sCAL_SUPPORTED)
  190286. /* read the sCAL chunk */
  190287. void /* PRIVATE */
  190288. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190289. {
  190290. png_charp buffer, ep;
  190291. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190292. double width, height;
  190293. png_charp vp;
  190294. #else
  190295. #ifdef PNG_FIXED_POINT_SUPPORTED
  190296. png_charp swidth, sheight;
  190297. #endif
  190298. #endif
  190299. png_size_t slength;
  190300. png_debug(1, "in png_handle_sCAL\n");
  190301. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190302. png_error(png_ptr, "Missing IHDR before sCAL");
  190303. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190304. {
  190305. png_warning(png_ptr, "Invalid sCAL after IDAT");
  190306. png_crc_finish(png_ptr, length);
  190307. return;
  190308. }
  190309. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  190310. {
  190311. png_warning(png_ptr, "Duplicate sCAL chunk");
  190312. png_crc_finish(png_ptr, length);
  190313. return;
  190314. }
  190315. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  190316. length + 1);
  190317. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  190318. if (buffer == NULL)
  190319. {
  190320. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  190321. return;
  190322. }
  190323. slength = (png_size_t)length;
  190324. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  190325. if (png_crc_finish(png_ptr, 0))
  190326. {
  190327. png_free(png_ptr, buffer);
  190328. return;
  190329. }
  190330. buffer[slength] = 0x00; /* null terminate the last string */
  190331. ep = buffer + 1; /* skip unit byte */
  190332. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190333. width = png_strtod(png_ptr, ep, &vp);
  190334. if (*vp)
  190335. {
  190336. png_warning(png_ptr, "malformed width string in sCAL chunk");
  190337. return;
  190338. }
  190339. #else
  190340. #ifdef PNG_FIXED_POINT_SUPPORTED
  190341. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  190342. if (swidth == NULL)
  190343. {
  190344. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  190345. return;
  190346. }
  190347. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  190348. #endif
  190349. #endif
  190350. for (ep = buffer; *ep; ep++)
  190351. /* empty loop */ ;
  190352. ep++;
  190353. if (buffer + slength < ep)
  190354. {
  190355. png_warning(png_ptr, "Truncated sCAL chunk");
  190356. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  190357. !defined(PNG_FLOATING_POINT_SUPPORTED)
  190358. png_free(png_ptr, swidth);
  190359. #endif
  190360. png_free(png_ptr, buffer);
  190361. return;
  190362. }
  190363. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190364. height = png_strtod(png_ptr, ep, &vp);
  190365. if (*vp)
  190366. {
  190367. png_warning(png_ptr, "malformed height string in sCAL chunk");
  190368. return;
  190369. }
  190370. #else
  190371. #ifdef PNG_FIXED_POINT_SUPPORTED
  190372. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  190373. if (swidth == NULL)
  190374. {
  190375. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  190376. return;
  190377. }
  190378. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  190379. #endif
  190380. #endif
  190381. if (buffer + slength < ep
  190382. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190383. || width <= 0. || height <= 0.
  190384. #endif
  190385. )
  190386. {
  190387. png_warning(png_ptr, "Invalid sCAL data");
  190388. png_free(png_ptr, buffer);
  190389. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  190390. png_free(png_ptr, swidth);
  190391. png_free(png_ptr, sheight);
  190392. #endif
  190393. return;
  190394. }
  190395. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190396. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  190397. #else
  190398. #ifdef PNG_FIXED_POINT_SUPPORTED
  190399. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  190400. #endif
  190401. #endif
  190402. png_free(png_ptr, buffer);
  190403. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  190404. png_free(png_ptr, swidth);
  190405. png_free(png_ptr, sheight);
  190406. #endif
  190407. }
  190408. #endif
  190409. #if defined(PNG_READ_tIME_SUPPORTED)
  190410. void /* PRIVATE */
  190411. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190412. {
  190413. png_byte buf[7];
  190414. png_time mod_time;
  190415. png_debug(1, "in png_handle_tIME\n");
  190416. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190417. png_error(png_ptr, "Out of place tIME chunk");
  190418. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  190419. {
  190420. png_warning(png_ptr, "Duplicate tIME chunk");
  190421. png_crc_finish(png_ptr, length);
  190422. return;
  190423. }
  190424. if (png_ptr->mode & PNG_HAVE_IDAT)
  190425. png_ptr->mode |= PNG_AFTER_IDAT;
  190426. if (length != 7)
  190427. {
  190428. png_warning(png_ptr, "Incorrect tIME chunk length");
  190429. png_crc_finish(png_ptr, length);
  190430. return;
  190431. }
  190432. png_crc_read(png_ptr, buf, 7);
  190433. if (png_crc_finish(png_ptr, 0))
  190434. return;
  190435. mod_time.second = buf[6];
  190436. mod_time.minute = buf[5];
  190437. mod_time.hour = buf[4];
  190438. mod_time.day = buf[3];
  190439. mod_time.month = buf[2];
  190440. mod_time.year = png_get_uint_16(buf);
  190441. png_set_tIME(png_ptr, info_ptr, &mod_time);
  190442. }
  190443. #endif
  190444. #if defined(PNG_READ_tEXt_SUPPORTED)
  190445. /* Note: this does not properly handle chunks that are > 64K under DOS */
  190446. void /* PRIVATE */
  190447. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190448. {
  190449. png_textp text_ptr;
  190450. png_charp key;
  190451. png_charp text;
  190452. png_uint_32 skip = 0;
  190453. png_size_t slength;
  190454. int ret;
  190455. png_debug(1, "in png_handle_tEXt\n");
  190456. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190457. png_error(png_ptr, "Missing IHDR before tEXt");
  190458. if (png_ptr->mode & PNG_HAVE_IDAT)
  190459. png_ptr->mode |= PNG_AFTER_IDAT;
  190460. #ifdef PNG_MAX_MALLOC_64K
  190461. if (length > (png_uint_32)65535L)
  190462. {
  190463. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  190464. skip = length - (png_uint_32)65535L;
  190465. length = (png_uint_32)65535L;
  190466. }
  190467. #endif
  190468. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  190469. if (key == NULL)
  190470. {
  190471. png_warning(png_ptr, "No memory to process text chunk.");
  190472. return;
  190473. }
  190474. slength = (png_size_t)length;
  190475. png_crc_read(png_ptr, (png_bytep)key, slength);
  190476. if (png_crc_finish(png_ptr, skip))
  190477. {
  190478. png_free(png_ptr, key);
  190479. return;
  190480. }
  190481. key[slength] = 0x00;
  190482. for (text = key; *text; text++)
  190483. /* empty loop to find end of key */ ;
  190484. if (text != key + slength)
  190485. text++;
  190486. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  190487. (png_uint_32)png_sizeof(png_text));
  190488. if (text_ptr == NULL)
  190489. {
  190490. png_warning(png_ptr, "Not enough memory to process text chunk.");
  190491. png_free(png_ptr, key);
  190492. return;
  190493. }
  190494. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  190495. text_ptr->key = key;
  190496. #ifdef PNG_iTXt_SUPPORTED
  190497. text_ptr->lang = NULL;
  190498. text_ptr->lang_key = NULL;
  190499. text_ptr->itxt_length = 0;
  190500. #endif
  190501. text_ptr->text = text;
  190502. text_ptr->text_length = png_strlen(text);
  190503. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  190504. png_free(png_ptr, key);
  190505. png_free(png_ptr, text_ptr);
  190506. if (ret)
  190507. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  190508. }
  190509. #endif
  190510. #if defined(PNG_READ_zTXt_SUPPORTED)
  190511. /* note: this does not correctly handle chunks that are > 64K under DOS */
  190512. void /* PRIVATE */
  190513. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190514. {
  190515. png_textp text_ptr;
  190516. png_charp chunkdata;
  190517. png_charp text;
  190518. int comp_type;
  190519. int ret;
  190520. png_size_t slength, prefix_len, data_len;
  190521. png_debug(1, "in png_handle_zTXt\n");
  190522. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190523. png_error(png_ptr, "Missing IHDR before zTXt");
  190524. if (png_ptr->mode & PNG_HAVE_IDAT)
  190525. png_ptr->mode |= PNG_AFTER_IDAT;
  190526. #ifdef PNG_MAX_MALLOC_64K
  190527. /* We will no doubt have problems with chunks even half this size, but
  190528. there is no hard and fast rule to tell us where to stop. */
  190529. if (length > (png_uint_32)65535L)
  190530. {
  190531. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  190532. png_crc_finish(png_ptr, length);
  190533. return;
  190534. }
  190535. #endif
  190536. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  190537. if (chunkdata == NULL)
  190538. {
  190539. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  190540. return;
  190541. }
  190542. slength = (png_size_t)length;
  190543. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  190544. if (png_crc_finish(png_ptr, 0))
  190545. {
  190546. png_free(png_ptr, chunkdata);
  190547. return;
  190548. }
  190549. chunkdata[slength] = 0x00;
  190550. for (text = chunkdata; *text; text++)
  190551. /* empty loop */ ;
  190552. /* zTXt must have some text after the chunkdataword */
  190553. if (text >= chunkdata + slength - 2)
  190554. {
  190555. png_warning(png_ptr, "Truncated zTXt chunk");
  190556. png_free(png_ptr, chunkdata);
  190557. return;
  190558. }
  190559. else
  190560. {
  190561. comp_type = *(++text);
  190562. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  190563. {
  190564. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  190565. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  190566. }
  190567. text++; /* skip the compression_method byte */
  190568. }
  190569. prefix_len = text - chunkdata;
  190570. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  190571. (png_size_t)length, prefix_len, &data_len);
  190572. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  190573. (png_uint_32)png_sizeof(png_text));
  190574. if (text_ptr == NULL)
  190575. {
  190576. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  190577. png_free(png_ptr, chunkdata);
  190578. return;
  190579. }
  190580. text_ptr->compression = comp_type;
  190581. text_ptr->key = chunkdata;
  190582. #ifdef PNG_iTXt_SUPPORTED
  190583. text_ptr->lang = NULL;
  190584. text_ptr->lang_key = NULL;
  190585. text_ptr->itxt_length = 0;
  190586. #endif
  190587. text_ptr->text = chunkdata + prefix_len;
  190588. text_ptr->text_length = data_len;
  190589. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  190590. png_free(png_ptr, text_ptr);
  190591. png_free(png_ptr, chunkdata);
  190592. if (ret)
  190593. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  190594. }
  190595. #endif
  190596. #if defined(PNG_READ_iTXt_SUPPORTED)
  190597. /* note: this does not correctly handle chunks that are > 64K under DOS */
  190598. void /* PRIVATE */
  190599. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190600. {
  190601. png_textp text_ptr;
  190602. png_charp chunkdata;
  190603. png_charp key, lang, text, lang_key;
  190604. int comp_flag;
  190605. int comp_type = 0;
  190606. int ret;
  190607. png_size_t slength, prefix_len, data_len;
  190608. png_debug(1, "in png_handle_iTXt\n");
  190609. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190610. png_error(png_ptr, "Missing IHDR before iTXt");
  190611. if (png_ptr->mode & PNG_HAVE_IDAT)
  190612. png_ptr->mode |= PNG_AFTER_IDAT;
  190613. #ifdef PNG_MAX_MALLOC_64K
  190614. /* We will no doubt have problems with chunks even half this size, but
  190615. there is no hard and fast rule to tell us where to stop. */
  190616. if (length > (png_uint_32)65535L)
  190617. {
  190618. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  190619. png_crc_finish(png_ptr, length);
  190620. return;
  190621. }
  190622. #endif
  190623. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  190624. if (chunkdata == NULL)
  190625. {
  190626. png_warning(png_ptr, "No memory to process iTXt chunk.");
  190627. return;
  190628. }
  190629. slength = (png_size_t)length;
  190630. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  190631. if (png_crc_finish(png_ptr, 0))
  190632. {
  190633. png_free(png_ptr, chunkdata);
  190634. return;
  190635. }
  190636. chunkdata[slength] = 0x00;
  190637. for (lang = chunkdata; *lang; lang++)
  190638. /* empty loop */ ;
  190639. lang++; /* skip NUL separator */
  190640. /* iTXt must have a language tag (possibly empty), two compression bytes,
  190641. translated keyword (possibly empty), and possibly some text after the
  190642. keyword */
  190643. if (lang >= chunkdata + slength - 3)
  190644. {
  190645. png_warning(png_ptr, "Truncated iTXt chunk");
  190646. png_free(png_ptr, chunkdata);
  190647. return;
  190648. }
  190649. else
  190650. {
  190651. comp_flag = *lang++;
  190652. comp_type = *lang++;
  190653. }
  190654. for (lang_key = lang; *lang_key; lang_key++)
  190655. /* empty loop */ ;
  190656. lang_key++; /* skip NUL separator */
  190657. if (lang_key >= chunkdata + slength)
  190658. {
  190659. png_warning(png_ptr, "Truncated iTXt chunk");
  190660. png_free(png_ptr, chunkdata);
  190661. return;
  190662. }
  190663. for (text = lang_key; *text; text++)
  190664. /* empty loop */ ;
  190665. text++; /* skip NUL separator */
  190666. if (text >= chunkdata + slength)
  190667. {
  190668. png_warning(png_ptr, "Malformed iTXt chunk");
  190669. png_free(png_ptr, chunkdata);
  190670. return;
  190671. }
  190672. prefix_len = text - chunkdata;
  190673. key=chunkdata;
  190674. if (comp_flag)
  190675. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  190676. (size_t)length, prefix_len, &data_len);
  190677. else
  190678. data_len=png_strlen(chunkdata + prefix_len);
  190679. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  190680. (png_uint_32)png_sizeof(png_text));
  190681. if (text_ptr == NULL)
  190682. {
  190683. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  190684. png_free(png_ptr, chunkdata);
  190685. return;
  190686. }
  190687. text_ptr->compression = (int)comp_flag + 1;
  190688. text_ptr->lang_key = chunkdata+(lang_key-key);
  190689. text_ptr->lang = chunkdata+(lang-key);
  190690. text_ptr->itxt_length = data_len;
  190691. text_ptr->text_length = 0;
  190692. text_ptr->key = chunkdata;
  190693. text_ptr->text = chunkdata + prefix_len;
  190694. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  190695. png_free(png_ptr, text_ptr);
  190696. png_free(png_ptr, chunkdata);
  190697. if (ret)
  190698. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  190699. }
  190700. #endif
  190701. /* This function is called when we haven't found a handler for a
  190702. chunk. If there isn't a problem with the chunk itself (ie bad
  190703. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  190704. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  190705. case it will be saved away to be written out later. */
  190706. void /* PRIVATE */
  190707. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190708. {
  190709. png_uint_32 skip = 0;
  190710. png_debug(1, "in png_handle_unknown\n");
  190711. if (png_ptr->mode & PNG_HAVE_IDAT)
  190712. {
  190713. #ifdef PNG_USE_LOCAL_ARRAYS
  190714. PNG_CONST PNG_IDAT;
  190715. #endif
  190716. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  190717. png_ptr->mode |= PNG_AFTER_IDAT;
  190718. }
  190719. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  190720. if (!(png_ptr->chunk_name[0] & 0x20))
  190721. {
  190722. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  190723. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  190724. PNG_HANDLE_CHUNK_ALWAYS
  190725. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  190726. && png_ptr->read_user_chunk_fn == NULL
  190727. #endif
  190728. )
  190729. #endif
  190730. png_chunk_error(png_ptr, "unknown critical chunk");
  190731. }
  190732. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  190733. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  190734. (png_ptr->read_user_chunk_fn != NULL))
  190735. {
  190736. #ifdef PNG_MAX_MALLOC_64K
  190737. if (length > (png_uint_32)65535L)
  190738. {
  190739. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  190740. skip = length - (png_uint_32)65535L;
  190741. length = (png_uint_32)65535L;
  190742. }
  190743. #endif
  190744. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  190745. (png_charp)png_ptr->chunk_name, 5);
  190746. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  190747. png_ptr->unknown_chunk.size = (png_size_t)length;
  190748. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  190749. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  190750. if(png_ptr->read_user_chunk_fn != NULL)
  190751. {
  190752. /* callback to user unknown chunk handler */
  190753. int ret;
  190754. ret = (*(png_ptr->read_user_chunk_fn))
  190755. (png_ptr, &png_ptr->unknown_chunk);
  190756. if (ret < 0)
  190757. png_chunk_error(png_ptr, "error in user chunk");
  190758. if (ret == 0)
  190759. {
  190760. if (!(png_ptr->chunk_name[0] & 0x20))
  190761. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  190762. PNG_HANDLE_CHUNK_ALWAYS)
  190763. png_chunk_error(png_ptr, "unknown critical chunk");
  190764. png_set_unknown_chunks(png_ptr, info_ptr,
  190765. &png_ptr->unknown_chunk, 1);
  190766. }
  190767. }
  190768. #else
  190769. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  190770. #endif
  190771. png_free(png_ptr, png_ptr->unknown_chunk.data);
  190772. png_ptr->unknown_chunk.data = NULL;
  190773. }
  190774. else
  190775. #endif
  190776. skip = length;
  190777. png_crc_finish(png_ptr, skip);
  190778. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  190779. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  190780. #endif
  190781. }
  190782. /* This function is called to verify that a chunk name is valid.
  190783. This function can't have the "critical chunk check" incorporated
  190784. into it, since in the future we will need to be able to call user
  190785. functions to handle unknown critical chunks after we check that
  190786. the chunk name itself is valid. */
  190787. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  190788. void /* PRIVATE */
  190789. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  190790. {
  190791. png_debug(1, "in png_check_chunk_name\n");
  190792. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  190793. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  190794. {
  190795. png_chunk_error(png_ptr, "invalid chunk type");
  190796. }
  190797. }
  190798. /* Combines the row recently read in with the existing pixels in the
  190799. row. This routine takes care of alpha and transparency if requested.
  190800. This routine also handles the two methods of progressive display
  190801. of interlaced images, depending on the mask value.
  190802. The mask value describes which pixels are to be combined with
  190803. the row. The pattern always repeats every 8 pixels, so just 8
  190804. bits are needed. A one indicates the pixel is to be combined,
  190805. a zero indicates the pixel is to be skipped. This is in addition
  190806. to any alpha or transparency value associated with the pixel. If
  190807. you want all pixels to be combined, pass 0xff (255) in mask. */
  190808. void /* PRIVATE */
  190809. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  190810. {
  190811. png_debug(1,"in png_combine_row\n");
  190812. if (mask == 0xff)
  190813. {
  190814. png_memcpy(row, png_ptr->row_buf + 1,
  190815. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  190816. }
  190817. else
  190818. {
  190819. switch (png_ptr->row_info.pixel_depth)
  190820. {
  190821. case 1:
  190822. {
  190823. png_bytep sp = png_ptr->row_buf + 1;
  190824. png_bytep dp = row;
  190825. int s_inc, s_start, s_end;
  190826. int m = 0x80;
  190827. int shift;
  190828. png_uint_32 i;
  190829. png_uint_32 row_width = png_ptr->width;
  190830. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190831. if (png_ptr->transformations & PNG_PACKSWAP)
  190832. {
  190833. s_start = 0;
  190834. s_end = 7;
  190835. s_inc = 1;
  190836. }
  190837. else
  190838. #endif
  190839. {
  190840. s_start = 7;
  190841. s_end = 0;
  190842. s_inc = -1;
  190843. }
  190844. shift = s_start;
  190845. for (i = 0; i < row_width; i++)
  190846. {
  190847. if (m & mask)
  190848. {
  190849. int value;
  190850. value = (*sp >> shift) & 0x01;
  190851. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  190852. *dp |= (png_byte)(value << shift);
  190853. }
  190854. if (shift == s_end)
  190855. {
  190856. shift = s_start;
  190857. sp++;
  190858. dp++;
  190859. }
  190860. else
  190861. shift += s_inc;
  190862. if (m == 1)
  190863. m = 0x80;
  190864. else
  190865. m >>= 1;
  190866. }
  190867. break;
  190868. }
  190869. case 2:
  190870. {
  190871. png_bytep sp = png_ptr->row_buf + 1;
  190872. png_bytep dp = row;
  190873. int s_start, s_end, s_inc;
  190874. int m = 0x80;
  190875. int shift;
  190876. png_uint_32 i;
  190877. png_uint_32 row_width = png_ptr->width;
  190878. int value;
  190879. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190880. if (png_ptr->transformations & PNG_PACKSWAP)
  190881. {
  190882. s_start = 0;
  190883. s_end = 6;
  190884. s_inc = 2;
  190885. }
  190886. else
  190887. #endif
  190888. {
  190889. s_start = 6;
  190890. s_end = 0;
  190891. s_inc = -2;
  190892. }
  190893. shift = s_start;
  190894. for (i = 0; i < row_width; i++)
  190895. {
  190896. if (m & mask)
  190897. {
  190898. value = (*sp >> shift) & 0x03;
  190899. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  190900. *dp |= (png_byte)(value << shift);
  190901. }
  190902. if (shift == s_end)
  190903. {
  190904. shift = s_start;
  190905. sp++;
  190906. dp++;
  190907. }
  190908. else
  190909. shift += s_inc;
  190910. if (m == 1)
  190911. m = 0x80;
  190912. else
  190913. m >>= 1;
  190914. }
  190915. break;
  190916. }
  190917. case 4:
  190918. {
  190919. png_bytep sp = png_ptr->row_buf + 1;
  190920. png_bytep dp = row;
  190921. int s_start, s_end, s_inc;
  190922. int m = 0x80;
  190923. int shift;
  190924. png_uint_32 i;
  190925. png_uint_32 row_width = png_ptr->width;
  190926. int value;
  190927. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190928. if (png_ptr->transformations & PNG_PACKSWAP)
  190929. {
  190930. s_start = 0;
  190931. s_end = 4;
  190932. s_inc = 4;
  190933. }
  190934. else
  190935. #endif
  190936. {
  190937. s_start = 4;
  190938. s_end = 0;
  190939. s_inc = -4;
  190940. }
  190941. shift = s_start;
  190942. for (i = 0; i < row_width; i++)
  190943. {
  190944. if (m & mask)
  190945. {
  190946. value = (*sp >> shift) & 0xf;
  190947. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  190948. *dp |= (png_byte)(value << shift);
  190949. }
  190950. if (shift == s_end)
  190951. {
  190952. shift = s_start;
  190953. sp++;
  190954. dp++;
  190955. }
  190956. else
  190957. shift += s_inc;
  190958. if (m == 1)
  190959. m = 0x80;
  190960. else
  190961. m >>= 1;
  190962. }
  190963. break;
  190964. }
  190965. default:
  190966. {
  190967. png_bytep sp = png_ptr->row_buf + 1;
  190968. png_bytep dp = row;
  190969. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  190970. png_uint_32 i;
  190971. png_uint_32 row_width = png_ptr->width;
  190972. png_byte m = 0x80;
  190973. for (i = 0; i < row_width; i++)
  190974. {
  190975. if (m & mask)
  190976. {
  190977. png_memcpy(dp, sp, pixel_bytes);
  190978. }
  190979. sp += pixel_bytes;
  190980. dp += pixel_bytes;
  190981. if (m == 1)
  190982. m = 0x80;
  190983. else
  190984. m >>= 1;
  190985. }
  190986. break;
  190987. }
  190988. }
  190989. }
  190990. }
  190991. #ifdef PNG_READ_INTERLACING_SUPPORTED
  190992. /* OLD pre-1.0.9 interface:
  190993. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  190994. png_uint_32 transformations)
  190995. */
  190996. void /* PRIVATE */
  190997. png_do_read_interlace(png_structp png_ptr)
  190998. {
  190999. png_row_infop row_info = &(png_ptr->row_info);
  191000. png_bytep row = png_ptr->row_buf + 1;
  191001. int pass = png_ptr->pass;
  191002. png_uint_32 transformations = png_ptr->transformations;
  191003. #ifdef PNG_USE_LOCAL_ARRAYS
  191004. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  191005. /* offset to next interlace block */
  191006. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  191007. #endif
  191008. png_debug(1,"in png_do_read_interlace\n");
  191009. if (row != NULL && row_info != NULL)
  191010. {
  191011. png_uint_32 final_width;
  191012. final_width = row_info->width * png_pass_inc[pass];
  191013. switch (row_info->pixel_depth)
  191014. {
  191015. case 1:
  191016. {
  191017. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  191018. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  191019. int sshift, dshift;
  191020. int s_start, s_end, s_inc;
  191021. int jstop = png_pass_inc[pass];
  191022. png_byte v;
  191023. png_uint_32 i;
  191024. int j;
  191025. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191026. if (transformations & PNG_PACKSWAP)
  191027. {
  191028. sshift = (int)((row_info->width + 7) & 0x07);
  191029. dshift = (int)((final_width + 7) & 0x07);
  191030. s_start = 7;
  191031. s_end = 0;
  191032. s_inc = -1;
  191033. }
  191034. else
  191035. #endif
  191036. {
  191037. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  191038. dshift = 7 - (int)((final_width + 7) & 0x07);
  191039. s_start = 0;
  191040. s_end = 7;
  191041. s_inc = 1;
  191042. }
  191043. for (i = 0; i < row_info->width; i++)
  191044. {
  191045. v = (png_byte)((*sp >> sshift) & 0x01);
  191046. for (j = 0; j < jstop; j++)
  191047. {
  191048. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  191049. *dp |= (png_byte)(v << dshift);
  191050. if (dshift == s_end)
  191051. {
  191052. dshift = s_start;
  191053. dp--;
  191054. }
  191055. else
  191056. dshift += s_inc;
  191057. }
  191058. if (sshift == s_end)
  191059. {
  191060. sshift = s_start;
  191061. sp--;
  191062. }
  191063. else
  191064. sshift += s_inc;
  191065. }
  191066. break;
  191067. }
  191068. case 2:
  191069. {
  191070. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  191071. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  191072. int sshift, dshift;
  191073. int s_start, s_end, s_inc;
  191074. int jstop = png_pass_inc[pass];
  191075. png_uint_32 i;
  191076. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191077. if (transformations & PNG_PACKSWAP)
  191078. {
  191079. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  191080. dshift = (int)(((final_width + 3) & 0x03) << 1);
  191081. s_start = 6;
  191082. s_end = 0;
  191083. s_inc = -2;
  191084. }
  191085. else
  191086. #endif
  191087. {
  191088. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  191089. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  191090. s_start = 0;
  191091. s_end = 6;
  191092. s_inc = 2;
  191093. }
  191094. for (i = 0; i < row_info->width; i++)
  191095. {
  191096. png_byte v;
  191097. int j;
  191098. v = (png_byte)((*sp >> sshift) & 0x03);
  191099. for (j = 0; j < jstop; j++)
  191100. {
  191101. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  191102. *dp |= (png_byte)(v << dshift);
  191103. if (dshift == s_end)
  191104. {
  191105. dshift = s_start;
  191106. dp--;
  191107. }
  191108. else
  191109. dshift += s_inc;
  191110. }
  191111. if (sshift == s_end)
  191112. {
  191113. sshift = s_start;
  191114. sp--;
  191115. }
  191116. else
  191117. sshift += s_inc;
  191118. }
  191119. break;
  191120. }
  191121. case 4:
  191122. {
  191123. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  191124. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  191125. int sshift, dshift;
  191126. int s_start, s_end, s_inc;
  191127. png_uint_32 i;
  191128. int jstop = png_pass_inc[pass];
  191129. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191130. if (transformations & PNG_PACKSWAP)
  191131. {
  191132. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  191133. dshift = (int)(((final_width + 1) & 0x01) << 2);
  191134. s_start = 4;
  191135. s_end = 0;
  191136. s_inc = -4;
  191137. }
  191138. else
  191139. #endif
  191140. {
  191141. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  191142. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  191143. s_start = 0;
  191144. s_end = 4;
  191145. s_inc = 4;
  191146. }
  191147. for (i = 0; i < row_info->width; i++)
  191148. {
  191149. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  191150. int j;
  191151. for (j = 0; j < jstop; j++)
  191152. {
  191153. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  191154. *dp |= (png_byte)(v << dshift);
  191155. if (dshift == s_end)
  191156. {
  191157. dshift = s_start;
  191158. dp--;
  191159. }
  191160. else
  191161. dshift += s_inc;
  191162. }
  191163. if (sshift == s_end)
  191164. {
  191165. sshift = s_start;
  191166. sp--;
  191167. }
  191168. else
  191169. sshift += s_inc;
  191170. }
  191171. break;
  191172. }
  191173. default:
  191174. {
  191175. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  191176. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  191177. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  191178. int jstop = png_pass_inc[pass];
  191179. png_uint_32 i;
  191180. for (i = 0; i < row_info->width; i++)
  191181. {
  191182. png_byte v[8];
  191183. int j;
  191184. png_memcpy(v, sp, pixel_bytes);
  191185. for (j = 0; j < jstop; j++)
  191186. {
  191187. png_memcpy(dp, v, pixel_bytes);
  191188. dp -= pixel_bytes;
  191189. }
  191190. sp -= pixel_bytes;
  191191. }
  191192. break;
  191193. }
  191194. }
  191195. row_info->width = final_width;
  191196. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  191197. }
  191198. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  191199. transformations = transformations; /* silence compiler warning */
  191200. #endif
  191201. }
  191202. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  191203. void /* PRIVATE */
  191204. png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row,
  191205. png_bytep prev_row, int filter)
  191206. {
  191207. png_debug(1, "in png_read_filter_row\n");
  191208. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  191209. switch (filter)
  191210. {
  191211. case PNG_FILTER_VALUE_NONE:
  191212. break;
  191213. case PNG_FILTER_VALUE_SUB:
  191214. {
  191215. png_uint_32 i;
  191216. png_uint_32 istop = row_info->rowbytes;
  191217. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  191218. png_bytep rp = row + bpp;
  191219. png_bytep lp = row;
  191220. for (i = bpp; i < istop; i++)
  191221. {
  191222. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  191223. rp++;
  191224. }
  191225. break;
  191226. }
  191227. case PNG_FILTER_VALUE_UP:
  191228. {
  191229. png_uint_32 i;
  191230. png_uint_32 istop = row_info->rowbytes;
  191231. png_bytep rp = row;
  191232. png_bytep pp = prev_row;
  191233. for (i = 0; i < istop; i++)
  191234. {
  191235. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  191236. rp++;
  191237. }
  191238. break;
  191239. }
  191240. case PNG_FILTER_VALUE_AVG:
  191241. {
  191242. png_uint_32 i;
  191243. png_bytep rp = row;
  191244. png_bytep pp = prev_row;
  191245. png_bytep lp = row;
  191246. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  191247. png_uint_32 istop = row_info->rowbytes - bpp;
  191248. for (i = 0; i < bpp; i++)
  191249. {
  191250. *rp = (png_byte)(((int)(*rp) +
  191251. ((int)(*pp++) / 2 )) & 0xff);
  191252. rp++;
  191253. }
  191254. for (i = 0; i < istop; i++)
  191255. {
  191256. *rp = (png_byte)(((int)(*rp) +
  191257. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  191258. rp++;
  191259. }
  191260. break;
  191261. }
  191262. case PNG_FILTER_VALUE_PAETH:
  191263. {
  191264. png_uint_32 i;
  191265. png_bytep rp = row;
  191266. png_bytep pp = prev_row;
  191267. png_bytep lp = row;
  191268. png_bytep cp = prev_row;
  191269. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  191270. png_uint_32 istop=row_info->rowbytes - bpp;
  191271. for (i = 0; i < bpp; i++)
  191272. {
  191273. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  191274. rp++;
  191275. }
  191276. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  191277. {
  191278. int a, b, c, pa, pb, pc, p;
  191279. a = *lp++;
  191280. b = *pp++;
  191281. c = *cp++;
  191282. p = b - c;
  191283. pc = a - c;
  191284. #ifdef PNG_USE_ABS
  191285. pa = abs(p);
  191286. pb = abs(pc);
  191287. pc = abs(p + pc);
  191288. #else
  191289. pa = p < 0 ? -p : p;
  191290. pb = pc < 0 ? -pc : pc;
  191291. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  191292. #endif
  191293. /*
  191294. if (pa <= pb && pa <= pc)
  191295. p = a;
  191296. else if (pb <= pc)
  191297. p = b;
  191298. else
  191299. p = c;
  191300. */
  191301. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  191302. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  191303. rp++;
  191304. }
  191305. break;
  191306. }
  191307. default:
  191308. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  191309. *row=0;
  191310. break;
  191311. }
  191312. }
  191313. void /* PRIVATE */
  191314. png_read_finish_row(png_structp png_ptr)
  191315. {
  191316. #ifdef PNG_USE_LOCAL_ARRAYS
  191317. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  191318. /* start of interlace block */
  191319. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  191320. /* offset to next interlace block */
  191321. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  191322. /* start of interlace block in the y direction */
  191323. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  191324. /* offset to next interlace block in the y direction */
  191325. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  191326. #endif
  191327. png_debug(1, "in png_read_finish_row\n");
  191328. png_ptr->row_number++;
  191329. if (png_ptr->row_number < png_ptr->num_rows)
  191330. return;
  191331. if (png_ptr->interlaced)
  191332. {
  191333. png_ptr->row_number = 0;
  191334. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  191335. png_ptr->rowbytes + 1);
  191336. do
  191337. {
  191338. png_ptr->pass++;
  191339. if (png_ptr->pass >= 7)
  191340. break;
  191341. png_ptr->iwidth = (png_ptr->width +
  191342. png_pass_inc[png_ptr->pass] - 1 -
  191343. png_pass_start[png_ptr->pass]) /
  191344. png_pass_inc[png_ptr->pass];
  191345. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  191346. png_ptr->iwidth) + 1;
  191347. if (!(png_ptr->transformations & PNG_INTERLACE))
  191348. {
  191349. png_ptr->num_rows = (png_ptr->height +
  191350. png_pass_yinc[png_ptr->pass] - 1 -
  191351. png_pass_ystart[png_ptr->pass]) /
  191352. png_pass_yinc[png_ptr->pass];
  191353. if (!(png_ptr->num_rows))
  191354. continue;
  191355. }
  191356. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  191357. break;
  191358. } while (png_ptr->iwidth == 0);
  191359. if (png_ptr->pass < 7)
  191360. return;
  191361. }
  191362. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  191363. {
  191364. #ifdef PNG_USE_LOCAL_ARRAYS
  191365. PNG_CONST PNG_IDAT;
  191366. #endif
  191367. char extra;
  191368. int ret;
  191369. png_ptr->zstream.next_out = (Bytef *)&extra;
  191370. png_ptr->zstream.avail_out = (uInt)1;
  191371. for(;;)
  191372. {
  191373. if (!(png_ptr->zstream.avail_in))
  191374. {
  191375. while (!png_ptr->idat_size)
  191376. {
  191377. png_byte chunk_length[4];
  191378. png_crc_finish(png_ptr, 0);
  191379. png_read_data(png_ptr, chunk_length, 4);
  191380. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  191381. png_reset_crc(png_ptr);
  191382. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  191383. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  191384. png_error(png_ptr, "Not enough image data");
  191385. }
  191386. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  191387. png_ptr->zstream.next_in = png_ptr->zbuf;
  191388. if (png_ptr->zbuf_size > png_ptr->idat_size)
  191389. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  191390. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  191391. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  191392. }
  191393. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  191394. if (ret == Z_STREAM_END)
  191395. {
  191396. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  191397. png_ptr->idat_size)
  191398. png_warning(png_ptr, "Extra compressed data");
  191399. png_ptr->mode |= PNG_AFTER_IDAT;
  191400. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  191401. break;
  191402. }
  191403. if (ret != Z_OK)
  191404. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  191405. "Decompression Error");
  191406. if (!(png_ptr->zstream.avail_out))
  191407. {
  191408. png_warning(png_ptr, "Extra compressed data.");
  191409. png_ptr->mode |= PNG_AFTER_IDAT;
  191410. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  191411. break;
  191412. }
  191413. }
  191414. png_ptr->zstream.avail_out = 0;
  191415. }
  191416. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  191417. png_warning(png_ptr, "Extra compression data");
  191418. inflateReset(&png_ptr->zstream);
  191419. png_ptr->mode |= PNG_AFTER_IDAT;
  191420. }
  191421. void /* PRIVATE */
  191422. png_read_start_row(png_structp png_ptr)
  191423. {
  191424. #ifdef PNG_USE_LOCAL_ARRAYS
  191425. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  191426. /* start of interlace block */
  191427. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  191428. /* offset to next interlace block */
  191429. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  191430. /* start of interlace block in the y direction */
  191431. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  191432. /* offset to next interlace block in the y direction */
  191433. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  191434. #endif
  191435. int max_pixel_depth;
  191436. png_uint_32 row_bytes;
  191437. png_debug(1, "in png_read_start_row\n");
  191438. png_ptr->zstream.avail_in = 0;
  191439. png_init_read_transformations(png_ptr);
  191440. if (png_ptr->interlaced)
  191441. {
  191442. if (!(png_ptr->transformations & PNG_INTERLACE))
  191443. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  191444. png_pass_ystart[0]) / png_pass_yinc[0];
  191445. else
  191446. png_ptr->num_rows = png_ptr->height;
  191447. png_ptr->iwidth = (png_ptr->width +
  191448. png_pass_inc[png_ptr->pass] - 1 -
  191449. png_pass_start[png_ptr->pass]) /
  191450. png_pass_inc[png_ptr->pass];
  191451. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  191452. png_ptr->irowbytes = (png_size_t)row_bytes;
  191453. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  191454. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  191455. }
  191456. else
  191457. {
  191458. png_ptr->num_rows = png_ptr->height;
  191459. png_ptr->iwidth = png_ptr->width;
  191460. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  191461. }
  191462. max_pixel_depth = png_ptr->pixel_depth;
  191463. #if defined(PNG_READ_PACK_SUPPORTED)
  191464. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  191465. max_pixel_depth = 8;
  191466. #endif
  191467. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191468. if (png_ptr->transformations & PNG_EXPAND)
  191469. {
  191470. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191471. {
  191472. if (png_ptr->num_trans)
  191473. max_pixel_depth = 32;
  191474. else
  191475. max_pixel_depth = 24;
  191476. }
  191477. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  191478. {
  191479. if (max_pixel_depth < 8)
  191480. max_pixel_depth = 8;
  191481. if (png_ptr->num_trans)
  191482. max_pixel_depth *= 2;
  191483. }
  191484. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  191485. {
  191486. if (png_ptr->num_trans)
  191487. {
  191488. max_pixel_depth *= 4;
  191489. max_pixel_depth /= 3;
  191490. }
  191491. }
  191492. }
  191493. #endif
  191494. #if defined(PNG_READ_FILLER_SUPPORTED)
  191495. if (png_ptr->transformations & (PNG_FILLER))
  191496. {
  191497. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191498. max_pixel_depth = 32;
  191499. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  191500. {
  191501. if (max_pixel_depth <= 8)
  191502. max_pixel_depth = 16;
  191503. else
  191504. max_pixel_depth = 32;
  191505. }
  191506. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  191507. {
  191508. if (max_pixel_depth <= 32)
  191509. max_pixel_depth = 32;
  191510. else
  191511. max_pixel_depth = 64;
  191512. }
  191513. }
  191514. #endif
  191515. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191516. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191517. {
  191518. if (
  191519. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191520. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  191521. #endif
  191522. #if defined(PNG_READ_FILLER_SUPPORTED)
  191523. (png_ptr->transformations & (PNG_FILLER)) ||
  191524. #endif
  191525. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191526. {
  191527. if (max_pixel_depth <= 16)
  191528. max_pixel_depth = 32;
  191529. else
  191530. max_pixel_depth = 64;
  191531. }
  191532. else
  191533. {
  191534. if (max_pixel_depth <= 8)
  191535. {
  191536. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191537. max_pixel_depth = 32;
  191538. else
  191539. max_pixel_depth = 24;
  191540. }
  191541. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191542. max_pixel_depth = 64;
  191543. else
  191544. max_pixel_depth = 48;
  191545. }
  191546. }
  191547. #endif
  191548. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  191549. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191550. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191551. {
  191552. int user_pixel_depth=png_ptr->user_transform_depth*
  191553. png_ptr->user_transform_channels;
  191554. if(user_pixel_depth > max_pixel_depth)
  191555. max_pixel_depth=user_pixel_depth;
  191556. }
  191557. #endif
  191558. /* align the width on the next larger 8 pixels. Mainly used
  191559. for interlacing */
  191560. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  191561. /* calculate the maximum bytes needed, adding a byte and a pixel
  191562. for safety's sake */
  191563. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  191564. 1 + ((max_pixel_depth + 7) >> 3);
  191565. #ifdef PNG_MAX_MALLOC_64K
  191566. if (row_bytes > (png_uint_32)65536L)
  191567. png_error(png_ptr, "This image requires a row greater than 64KB");
  191568. #endif
  191569. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  191570. png_ptr->row_buf = png_ptr->big_row_buf+32;
  191571. #ifdef PNG_MAX_MALLOC_64K
  191572. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  191573. png_error(png_ptr, "This image requires a row greater than 64KB");
  191574. #endif
  191575. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  191576. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  191577. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  191578. png_ptr->rowbytes + 1));
  191579. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  191580. png_debug1(3, "width = %lu,\n", png_ptr->width);
  191581. png_debug1(3, "height = %lu,\n", png_ptr->height);
  191582. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  191583. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  191584. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  191585. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  191586. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  191587. }
  191588. #endif /* PNG_READ_SUPPORTED */
  191589. /********* End of inlined file: pngrutil.c *********/
  191590. /********* Start of inlined file: pngset.c *********/
  191591. /* pngset.c - storage of image information into info struct
  191592. *
  191593. * Last changed in libpng 1.2.21 [October 4, 2007]
  191594. * For conditions of distribution and use, see copyright notice in png.h
  191595. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  191596. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  191597. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  191598. *
  191599. * The functions here are used during reads to store data from the file
  191600. * into the info struct, and during writes to store application data
  191601. * into the info struct for writing into the file. This abstracts the
  191602. * info struct and allows us to change the structure in the future.
  191603. */
  191604. #define PNG_INTERNAL
  191605. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  191606. #if defined(PNG_bKGD_SUPPORTED)
  191607. void PNGAPI
  191608. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  191609. {
  191610. png_debug1(1, "in %s storage function\n", "bKGD");
  191611. if (png_ptr == NULL || info_ptr == NULL)
  191612. return;
  191613. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  191614. info_ptr->valid |= PNG_INFO_bKGD;
  191615. }
  191616. #endif
  191617. #if defined(PNG_cHRM_SUPPORTED)
  191618. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191619. void PNGAPI
  191620. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  191621. double white_x, double white_y, double red_x, double red_y,
  191622. double green_x, double green_y, double blue_x, double blue_y)
  191623. {
  191624. png_debug1(1, "in %s storage function\n", "cHRM");
  191625. if (png_ptr == NULL || info_ptr == NULL)
  191626. return;
  191627. if (white_x < 0.0 || white_y < 0.0 ||
  191628. red_x < 0.0 || red_y < 0.0 ||
  191629. green_x < 0.0 || green_y < 0.0 ||
  191630. blue_x < 0.0 || blue_y < 0.0)
  191631. {
  191632. png_warning(png_ptr,
  191633. "Ignoring attempt to set negative chromaticity value");
  191634. return;
  191635. }
  191636. if (white_x > 21474.83 || white_y > 21474.83 ||
  191637. red_x > 21474.83 || red_y > 21474.83 ||
  191638. green_x > 21474.83 || green_y > 21474.83 ||
  191639. blue_x > 21474.83 || blue_y > 21474.83)
  191640. {
  191641. png_warning(png_ptr,
  191642. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  191643. return;
  191644. }
  191645. info_ptr->x_white = (float)white_x;
  191646. info_ptr->y_white = (float)white_y;
  191647. info_ptr->x_red = (float)red_x;
  191648. info_ptr->y_red = (float)red_y;
  191649. info_ptr->x_green = (float)green_x;
  191650. info_ptr->y_green = (float)green_y;
  191651. info_ptr->x_blue = (float)blue_x;
  191652. info_ptr->y_blue = (float)blue_y;
  191653. #ifdef PNG_FIXED_POINT_SUPPORTED
  191654. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  191655. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  191656. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  191657. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  191658. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  191659. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  191660. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  191661. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  191662. #endif
  191663. info_ptr->valid |= PNG_INFO_cHRM;
  191664. }
  191665. #endif
  191666. #ifdef PNG_FIXED_POINT_SUPPORTED
  191667. void PNGAPI
  191668. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  191669. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  191670. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  191671. png_fixed_point blue_x, png_fixed_point blue_y)
  191672. {
  191673. png_debug1(1, "in %s storage function\n", "cHRM");
  191674. if (png_ptr == NULL || info_ptr == NULL)
  191675. return;
  191676. if (white_x < 0 || white_y < 0 ||
  191677. red_x < 0 || red_y < 0 ||
  191678. green_x < 0 || green_y < 0 ||
  191679. blue_x < 0 || blue_y < 0)
  191680. {
  191681. png_warning(png_ptr,
  191682. "Ignoring attempt to set negative chromaticity value");
  191683. return;
  191684. }
  191685. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191686. if (white_x > (double) PNG_UINT_31_MAX ||
  191687. white_y > (double) PNG_UINT_31_MAX ||
  191688. red_x > (double) PNG_UINT_31_MAX ||
  191689. red_y > (double) PNG_UINT_31_MAX ||
  191690. green_x > (double) PNG_UINT_31_MAX ||
  191691. green_y > (double) PNG_UINT_31_MAX ||
  191692. blue_x > (double) PNG_UINT_31_MAX ||
  191693. blue_y > (double) PNG_UINT_31_MAX)
  191694. #else
  191695. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  191696. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  191697. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  191698. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  191699. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  191700. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  191701. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  191702. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  191703. #endif
  191704. {
  191705. png_warning(png_ptr,
  191706. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  191707. return;
  191708. }
  191709. info_ptr->int_x_white = white_x;
  191710. info_ptr->int_y_white = white_y;
  191711. info_ptr->int_x_red = red_x;
  191712. info_ptr->int_y_red = red_y;
  191713. info_ptr->int_x_green = green_x;
  191714. info_ptr->int_y_green = green_y;
  191715. info_ptr->int_x_blue = blue_x;
  191716. info_ptr->int_y_blue = blue_y;
  191717. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191718. info_ptr->x_white = (float)(white_x/100000.);
  191719. info_ptr->y_white = (float)(white_y/100000.);
  191720. info_ptr->x_red = (float)( red_x/100000.);
  191721. info_ptr->y_red = (float)( red_y/100000.);
  191722. info_ptr->x_green = (float)(green_x/100000.);
  191723. info_ptr->y_green = (float)(green_y/100000.);
  191724. info_ptr->x_blue = (float)( blue_x/100000.);
  191725. info_ptr->y_blue = (float)( blue_y/100000.);
  191726. #endif
  191727. info_ptr->valid |= PNG_INFO_cHRM;
  191728. }
  191729. #endif
  191730. #endif
  191731. #if defined(PNG_gAMA_SUPPORTED)
  191732. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191733. void PNGAPI
  191734. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  191735. {
  191736. double gamma;
  191737. png_debug1(1, "in %s storage function\n", "gAMA");
  191738. if (png_ptr == NULL || info_ptr == NULL)
  191739. return;
  191740. /* Check for overflow */
  191741. if (file_gamma > 21474.83)
  191742. {
  191743. png_warning(png_ptr, "Limiting gamma to 21474.83");
  191744. gamma=21474.83;
  191745. }
  191746. else
  191747. gamma=file_gamma;
  191748. info_ptr->gamma = (float)gamma;
  191749. #ifdef PNG_FIXED_POINT_SUPPORTED
  191750. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  191751. #endif
  191752. info_ptr->valid |= PNG_INFO_gAMA;
  191753. if(gamma == 0.0)
  191754. png_warning(png_ptr, "Setting gamma=0");
  191755. }
  191756. #endif
  191757. void PNGAPI
  191758. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  191759. int_gamma)
  191760. {
  191761. png_fixed_point gamma;
  191762. png_debug1(1, "in %s storage function\n", "gAMA");
  191763. if (png_ptr == NULL || info_ptr == NULL)
  191764. return;
  191765. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  191766. {
  191767. png_warning(png_ptr, "Limiting gamma to 21474.83");
  191768. gamma=PNG_UINT_31_MAX;
  191769. }
  191770. else
  191771. {
  191772. if (int_gamma < 0)
  191773. {
  191774. png_warning(png_ptr, "Setting negative gamma to zero");
  191775. gamma=0;
  191776. }
  191777. else
  191778. gamma=int_gamma;
  191779. }
  191780. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191781. info_ptr->gamma = (float)(gamma/100000.);
  191782. #endif
  191783. #ifdef PNG_FIXED_POINT_SUPPORTED
  191784. info_ptr->int_gamma = gamma;
  191785. #endif
  191786. info_ptr->valid |= PNG_INFO_gAMA;
  191787. if(gamma == 0)
  191788. png_warning(png_ptr, "Setting gamma=0");
  191789. }
  191790. #endif
  191791. #if defined(PNG_hIST_SUPPORTED)
  191792. void PNGAPI
  191793. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  191794. {
  191795. int i;
  191796. png_debug1(1, "in %s storage function\n", "hIST");
  191797. if (png_ptr == NULL || info_ptr == NULL)
  191798. return;
  191799. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  191800. > PNG_MAX_PALETTE_LENGTH)
  191801. {
  191802. png_warning(png_ptr,
  191803. "Invalid palette size, hIST allocation skipped.");
  191804. return;
  191805. }
  191806. #ifdef PNG_FREE_ME_SUPPORTED
  191807. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  191808. #endif
  191809. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  191810. 1.2.1 */
  191811. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  191812. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  191813. if (png_ptr->hist == NULL)
  191814. {
  191815. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  191816. return;
  191817. }
  191818. for (i = 0; i < info_ptr->num_palette; i++)
  191819. png_ptr->hist[i] = hist[i];
  191820. info_ptr->hist = png_ptr->hist;
  191821. info_ptr->valid |= PNG_INFO_hIST;
  191822. #ifdef PNG_FREE_ME_SUPPORTED
  191823. info_ptr->free_me |= PNG_FREE_HIST;
  191824. #else
  191825. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  191826. #endif
  191827. }
  191828. #endif
  191829. void PNGAPI
  191830. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  191831. png_uint_32 width, png_uint_32 height, int bit_depth,
  191832. int color_type, int interlace_type, int compression_type,
  191833. int filter_type)
  191834. {
  191835. png_debug1(1, "in %s storage function\n", "IHDR");
  191836. if (png_ptr == NULL || info_ptr == NULL)
  191837. return;
  191838. /* check for width and height valid values */
  191839. if (width == 0 || height == 0)
  191840. png_error(png_ptr, "Image width or height is zero in IHDR");
  191841. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  191842. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  191843. png_error(png_ptr, "image size exceeds user limits in IHDR");
  191844. #else
  191845. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  191846. png_error(png_ptr, "image size exceeds user limits in IHDR");
  191847. #endif
  191848. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  191849. png_error(png_ptr, "Invalid image size in IHDR");
  191850. if ( width > (PNG_UINT_32_MAX
  191851. >> 3) /* 8-byte RGBA pixels */
  191852. - 64 /* bigrowbuf hack */
  191853. - 1 /* filter byte */
  191854. - 7*8 /* rounding of width to multiple of 8 pixels */
  191855. - 8) /* extra max_pixel_depth pad */
  191856. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  191857. /* check other values */
  191858. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  191859. bit_depth != 8 && bit_depth != 16)
  191860. png_error(png_ptr, "Invalid bit depth in IHDR");
  191861. if (color_type < 0 || color_type == 1 ||
  191862. color_type == 5 || color_type > 6)
  191863. png_error(png_ptr, "Invalid color type in IHDR");
  191864. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  191865. ((color_type == PNG_COLOR_TYPE_RGB ||
  191866. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  191867. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  191868. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  191869. if (interlace_type >= PNG_INTERLACE_LAST)
  191870. png_error(png_ptr, "Unknown interlace method in IHDR");
  191871. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  191872. png_error(png_ptr, "Unknown compression method in IHDR");
  191873. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  191874. /* Accept filter_method 64 (intrapixel differencing) only if
  191875. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  191876. * 2. Libpng did not read a PNG signature (this filter_method is only
  191877. * used in PNG datastreams that are embedded in MNG datastreams) and
  191878. * 3. The application called png_permit_mng_features with a mask that
  191879. * included PNG_FLAG_MNG_FILTER_64 and
  191880. * 4. The filter_method is 64 and
  191881. * 5. The color_type is RGB or RGBA
  191882. */
  191883. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  191884. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  191885. if(filter_type != PNG_FILTER_TYPE_BASE)
  191886. {
  191887. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  191888. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  191889. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  191890. (color_type == PNG_COLOR_TYPE_RGB ||
  191891. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  191892. png_error(png_ptr, "Unknown filter method in IHDR");
  191893. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  191894. png_warning(png_ptr, "Invalid filter method in IHDR");
  191895. }
  191896. #else
  191897. if(filter_type != PNG_FILTER_TYPE_BASE)
  191898. png_error(png_ptr, "Unknown filter method in IHDR");
  191899. #endif
  191900. info_ptr->width = width;
  191901. info_ptr->height = height;
  191902. info_ptr->bit_depth = (png_byte)bit_depth;
  191903. info_ptr->color_type =(png_byte) color_type;
  191904. info_ptr->compression_type = (png_byte)compression_type;
  191905. info_ptr->filter_type = (png_byte)filter_type;
  191906. info_ptr->interlace_type = (png_byte)interlace_type;
  191907. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191908. info_ptr->channels = 1;
  191909. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191910. info_ptr->channels = 3;
  191911. else
  191912. info_ptr->channels = 1;
  191913. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191914. info_ptr->channels++;
  191915. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  191916. /* check for potential overflow */
  191917. if (width > (PNG_UINT_32_MAX
  191918. >> 3) /* 8-byte RGBA pixels */
  191919. - 64 /* bigrowbuf hack */
  191920. - 1 /* filter byte */
  191921. - 7*8 /* rounding of width to multiple of 8 pixels */
  191922. - 8) /* extra max_pixel_depth pad */
  191923. info_ptr->rowbytes = (png_size_t)0;
  191924. else
  191925. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  191926. }
  191927. #if defined(PNG_oFFs_SUPPORTED)
  191928. void PNGAPI
  191929. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  191930. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  191931. {
  191932. png_debug1(1, "in %s storage function\n", "oFFs");
  191933. if (png_ptr == NULL || info_ptr == NULL)
  191934. return;
  191935. info_ptr->x_offset = offset_x;
  191936. info_ptr->y_offset = offset_y;
  191937. info_ptr->offset_unit_type = (png_byte)unit_type;
  191938. info_ptr->valid |= PNG_INFO_oFFs;
  191939. }
  191940. #endif
  191941. #if defined(PNG_pCAL_SUPPORTED)
  191942. void PNGAPI
  191943. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  191944. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  191945. png_charp units, png_charpp params)
  191946. {
  191947. png_uint_32 length;
  191948. int i;
  191949. png_debug1(1, "in %s storage function\n", "pCAL");
  191950. if (png_ptr == NULL || info_ptr == NULL)
  191951. return;
  191952. length = png_strlen(purpose) + 1;
  191953. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  191954. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  191955. if (info_ptr->pcal_purpose == NULL)
  191956. {
  191957. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  191958. return;
  191959. }
  191960. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  191961. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  191962. info_ptr->pcal_X0 = X0;
  191963. info_ptr->pcal_X1 = X1;
  191964. info_ptr->pcal_type = (png_byte)type;
  191965. info_ptr->pcal_nparams = (png_byte)nparams;
  191966. length = png_strlen(units) + 1;
  191967. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  191968. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  191969. if (info_ptr->pcal_units == NULL)
  191970. {
  191971. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  191972. return;
  191973. }
  191974. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  191975. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  191976. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  191977. if (info_ptr->pcal_params == NULL)
  191978. {
  191979. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  191980. return;
  191981. }
  191982. info_ptr->pcal_params[nparams] = NULL;
  191983. for (i = 0; i < nparams; i++)
  191984. {
  191985. length = png_strlen(params[i]) + 1;
  191986. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  191987. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  191988. if (info_ptr->pcal_params[i] == NULL)
  191989. {
  191990. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  191991. return;
  191992. }
  191993. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  191994. }
  191995. info_ptr->valid |= PNG_INFO_pCAL;
  191996. #ifdef PNG_FREE_ME_SUPPORTED
  191997. info_ptr->free_me |= PNG_FREE_PCAL;
  191998. #endif
  191999. }
  192000. #endif
  192001. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  192002. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192003. void PNGAPI
  192004. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  192005. int unit, double width, double height)
  192006. {
  192007. png_debug1(1, "in %s storage function\n", "sCAL");
  192008. if (png_ptr == NULL || info_ptr == NULL)
  192009. return;
  192010. info_ptr->scal_unit = (png_byte)unit;
  192011. info_ptr->scal_pixel_width = width;
  192012. info_ptr->scal_pixel_height = height;
  192013. info_ptr->valid |= PNG_INFO_sCAL;
  192014. }
  192015. #else
  192016. #ifdef PNG_FIXED_POINT_SUPPORTED
  192017. void PNGAPI
  192018. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  192019. int unit, png_charp swidth, png_charp sheight)
  192020. {
  192021. png_uint_32 length;
  192022. png_debug1(1, "in %s storage function\n", "sCAL");
  192023. if (png_ptr == NULL || info_ptr == NULL)
  192024. return;
  192025. info_ptr->scal_unit = (png_byte)unit;
  192026. length = png_strlen(swidth) + 1;
  192027. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  192028. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  192029. if (info_ptr->scal_s_width == NULL)
  192030. {
  192031. png_warning(png_ptr,
  192032. "Memory allocation failed while processing sCAL.");
  192033. }
  192034. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  192035. length = png_strlen(sheight) + 1;
  192036. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  192037. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  192038. if (info_ptr->scal_s_height == NULL)
  192039. {
  192040. png_free (png_ptr, info_ptr->scal_s_width);
  192041. png_warning(png_ptr,
  192042. "Memory allocation failed while processing sCAL.");
  192043. }
  192044. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  192045. info_ptr->valid |= PNG_INFO_sCAL;
  192046. #ifdef PNG_FREE_ME_SUPPORTED
  192047. info_ptr->free_me |= PNG_FREE_SCAL;
  192048. #endif
  192049. }
  192050. #endif
  192051. #endif
  192052. #endif
  192053. #if defined(PNG_pHYs_SUPPORTED)
  192054. void PNGAPI
  192055. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  192056. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  192057. {
  192058. png_debug1(1, "in %s storage function\n", "pHYs");
  192059. if (png_ptr == NULL || info_ptr == NULL)
  192060. return;
  192061. info_ptr->x_pixels_per_unit = res_x;
  192062. info_ptr->y_pixels_per_unit = res_y;
  192063. info_ptr->phys_unit_type = (png_byte)unit_type;
  192064. info_ptr->valid |= PNG_INFO_pHYs;
  192065. }
  192066. #endif
  192067. void PNGAPI
  192068. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  192069. png_colorp palette, int num_palette)
  192070. {
  192071. png_debug1(1, "in %s storage function\n", "PLTE");
  192072. if (png_ptr == NULL || info_ptr == NULL)
  192073. return;
  192074. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  192075. {
  192076. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192077. png_error(png_ptr, "Invalid palette length");
  192078. else
  192079. {
  192080. png_warning(png_ptr, "Invalid palette length");
  192081. return;
  192082. }
  192083. }
  192084. /*
  192085. * It may not actually be necessary to set png_ptr->palette here;
  192086. * we do it for backward compatibility with the way the png_handle_tRNS
  192087. * function used to do the allocation.
  192088. */
  192089. #ifdef PNG_FREE_ME_SUPPORTED
  192090. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  192091. #endif
  192092. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  192093. of num_palette entries,
  192094. in case of an invalid PNG file that has too-large sample values. */
  192095. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  192096. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  192097. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  192098. png_sizeof(png_color));
  192099. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  192100. info_ptr->palette = png_ptr->palette;
  192101. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  192102. #ifdef PNG_FREE_ME_SUPPORTED
  192103. info_ptr->free_me |= PNG_FREE_PLTE;
  192104. #else
  192105. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  192106. #endif
  192107. info_ptr->valid |= PNG_INFO_PLTE;
  192108. }
  192109. #if defined(PNG_sBIT_SUPPORTED)
  192110. void PNGAPI
  192111. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  192112. png_color_8p sig_bit)
  192113. {
  192114. png_debug1(1, "in %s storage function\n", "sBIT");
  192115. if (png_ptr == NULL || info_ptr == NULL)
  192116. return;
  192117. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  192118. info_ptr->valid |= PNG_INFO_sBIT;
  192119. }
  192120. #endif
  192121. #if defined(PNG_sRGB_SUPPORTED)
  192122. void PNGAPI
  192123. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  192124. {
  192125. png_debug1(1, "in %s storage function\n", "sRGB");
  192126. if (png_ptr == NULL || info_ptr == NULL)
  192127. return;
  192128. info_ptr->srgb_intent = (png_byte)intent;
  192129. info_ptr->valid |= PNG_INFO_sRGB;
  192130. }
  192131. void PNGAPI
  192132. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  192133. int intent)
  192134. {
  192135. #if defined(PNG_gAMA_SUPPORTED)
  192136. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192137. float file_gamma;
  192138. #endif
  192139. #ifdef PNG_FIXED_POINT_SUPPORTED
  192140. png_fixed_point int_file_gamma;
  192141. #endif
  192142. #endif
  192143. #if defined(PNG_cHRM_SUPPORTED)
  192144. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192145. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  192146. #endif
  192147. #ifdef PNG_FIXED_POINT_SUPPORTED
  192148. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  192149. int_green_y, int_blue_x, int_blue_y;
  192150. #endif
  192151. #endif
  192152. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  192153. if (png_ptr == NULL || info_ptr == NULL)
  192154. return;
  192155. png_set_sRGB(png_ptr, info_ptr, intent);
  192156. #if defined(PNG_gAMA_SUPPORTED)
  192157. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192158. file_gamma = (float).45455;
  192159. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  192160. #endif
  192161. #ifdef PNG_FIXED_POINT_SUPPORTED
  192162. int_file_gamma = 45455L;
  192163. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  192164. #endif
  192165. #endif
  192166. #if defined(PNG_cHRM_SUPPORTED)
  192167. #ifdef PNG_FIXED_POINT_SUPPORTED
  192168. int_white_x = 31270L;
  192169. int_white_y = 32900L;
  192170. int_red_x = 64000L;
  192171. int_red_y = 33000L;
  192172. int_green_x = 30000L;
  192173. int_green_y = 60000L;
  192174. int_blue_x = 15000L;
  192175. int_blue_y = 6000L;
  192176. png_set_cHRM_fixed(png_ptr, info_ptr,
  192177. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  192178. int_blue_x, int_blue_y);
  192179. #endif
  192180. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192181. white_x = (float).3127;
  192182. white_y = (float).3290;
  192183. red_x = (float).64;
  192184. red_y = (float).33;
  192185. green_x = (float).30;
  192186. green_y = (float).60;
  192187. blue_x = (float).15;
  192188. blue_y = (float).06;
  192189. png_set_cHRM(png_ptr, info_ptr,
  192190. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  192191. #endif
  192192. #endif
  192193. }
  192194. #endif
  192195. #if defined(PNG_iCCP_SUPPORTED)
  192196. void PNGAPI
  192197. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  192198. png_charp name, int compression_type,
  192199. png_charp profile, png_uint_32 proflen)
  192200. {
  192201. png_charp new_iccp_name;
  192202. png_charp new_iccp_profile;
  192203. png_debug1(1, "in %s storage function\n", "iCCP");
  192204. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  192205. return;
  192206. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  192207. if (new_iccp_name == NULL)
  192208. {
  192209. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  192210. return;
  192211. }
  192212. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  192213. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  192214. if (new_iccp_profile == NULL)
  192215. {
  192216. png_free (png_ptr, new_iccp_name);
  192217. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  192218. return;
  192219. }
  192220. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  192221. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  192222. info_ptr->iccp_proflen = proflen;
  192223. info_ptr->iccp_name = new_iccp_name;
  192224. info_ptr->iccp_profile = new_iccp_profile;
  192225. /* Compression is always zero but is here so the API and info structure
  192226. * does not have to change if we introduce multiple compression types */
  192227. info_ptr->iccp_compression = (png_byte)compression_type;
  192228. #ifdef PNG_FREE_ME_SUPPORTED
  192229. info_ptr->free_me |= PNG_FREE_ICCP;
  192230. #endif
  192231. info_ptr->valid |= PNG_INFO_iCCP;
  192232. }
  192233. #endif
  192234. #if defined(PNG_TEXT_SUPPORTED)
  192235. void PNGAPI
  192236. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  192237. int num_text)
  192238. {
  192239. int ret;
  192240. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  192241. if (ret)
  192242. png_error(png_ptr, "Insufficient memory to store text");
  192243. }
  192244. int /* PRIVATE */
  192245. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  192246. int num_text)
  192247. {
  192248. int i;
  192249. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  192250. "text" : (png_const_charp)png_ptr->chunk_name));
  192251. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  192252. return(0);
  192253. /* Make sure we have enough space in the "text" array in info_struct
  192254. * to hold all of the incoming text_ptr objects.
  192255. */
  192256. if (info_ptr->num_text + num_text > info_ptr->max_text)
  192257. {
  192258. if (info_ptr->text != NULL)
  192259. {
  192260. png_textp old_text;
  192261. int old_max;
  192262. old_max = info_ptr->max_text;
  192263. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  192264. old_text = info_ptr->text;
  192265. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  192266. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  192267. if (info_ptr->text == NULL)
  192268. {
  192269. png_free(png_ptr, old_text);
  192270. return(1);
  192271. }
  192272. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  192273. png_sizeof(png_text)));
  192274. png_free(png_ptr, old_text);
  192275. }
  192276. else
  192277. {
  192278. info_ptr->max_text = num_text + 8;
  192279. info_ptr->num_text = 0;
  192280. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  192281. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  192282. if (info_ptr->text == NULL)
  192283. return(1);
  192284. #ifdef PNG_FREE_ME_SUPPORTED
  192285. info_ptr->free_me |= PNG_FREE_TEXT;
  192286. #endif
  192287. }
  192288. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  192289. info_ptr->max_text);
  192290. }
  192291. for (i = 0; i < num_text; i++)
  192292. {
  192293. png_size_t text_length,key_len;
  192294. png_size_t lang_len,lang_key_len;
  192295. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  192296. if (text_ptr[i].key == NULL)
  192297. continue;
  192298. key_len = png_strlen(text_ptr[i].key);
  192299. if(text_ptr[i].compression <= 0)
  192300. {
  192301. lang_len = 0;
  192302. lang_key_len = 0;
  192303. }
  192304. else
  192305. #ifdef PNG_iTXt_SUPPORTED
  192306. {
  192307. /* set iTXt data */
  192308. if (text_ptr[i].lang != NULL)
  192309. lang_len = png_strlen(text_ptr[i].lang);
  192310. else
  192311. lang_len = 0;
  192312. if (text_ptr[i].lang_key != NULL)
  192313. lang_key_len = png_strlen(text_ptr[i].lang_key);
  192314. else
  192315. lang_key_len = 0;
  192316. }
  192317. #else
  192318. {
  192319. png_warning(png_ptr, "iTXt chunk not supported.");
  192320. continue;
  192321. }
  192322. #endif
  192323. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  192324. {
  192325. text_length = 0;
  192326. #ifdef PNG_iTXt_SUPPORTED
  192327. if(text_ptr[i].compression > 0)
  192328. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  192329. else
  192330. #endif
  192331. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  192332. }
  192333. else
  192334. {
  192335. text_length = png_strlen(text_ptr[i].text);
  192336. textp->compression = text_ptr[i].compression;
  192337. }
  192338. textp->key = (png_charp)png_malloc_warn(png_ptr,
  192339. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  192340. if (textp->key == NULL)
  192341. return(1);
  192342. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  192343. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  192344. (int)textp->key);
  192345. png_memcpy(textp->key, text_ptr[i].key,
  192346. (png_size_t)(key_len));
  192347. *(textp->key+key_len) = '\0';
  192348. #ifdef PNG_iTXt_SUPPORTED
  192349. if (text_ptr[i].compression > 0)
  192350. {
  192351. textp->lang=textp->key + key_len + 1;
  192352. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  192353. *(textp->lang+lang_len) = '\0';
  192354. textp->lang_key=textp->lang + lang_len + 1;
  192355. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  192356. *(textp->lang_key+lang_key_len) = '\0';
  192357. textp->text=textp->lang_key + lang_key_len + 1;
  192358. }
  192359. else
  192360. #endif
  192361. {
  192362. #ifdef PNG_iTXt_SUPPORTED
  192363. textp->lang=NULL;
  192364. textp->lang_key=NULL;
  192365. #endif
  192366. textp->text=textp->key + key_len + 1;
  192367. }
  192368. if(text_length)
  192369. png_memcpy(textp->text, text_ptr[i].text,
  192370. (png_size_t)(text_length));
  192371. *(textp->text+text_length) = '\0';
  192372. #ifdef PNG_iTXt_SUPPORTED
  192373. if(textp->compression > 0)
  192374. {
  192375. textp->text_length = 0;
  192376. textp->itxt_length = text_length;
  192377. }
  192378. else
  192379. #endif
  192380. {
  192381. textp->text_length = text_length;
  192382. #ifdef PNG_iTXt_SUPPORTED
  192383. textp->itxt_length = 0;
  192384. #endif
  192385. }
  192386. info_ptr->num_text++;
  192387. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  192388. }
  192389. return(0);
  192390. }
  192391. #endif
  192392. #if defined(PNG_tIME_SUPPORTED)
  192393. void PNGAPI
  192394. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  192395. {
  192396. png_debug1(1, "in %s storage function\n", "tIME");
  192397. if (png_ptr == NULL || info_ptr == NULL ||
  192398. (png_ptr->mode & PNG_WROTE_tIME))
  192399. return;
  192400. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  192401. info_ptr->valid |= PNG_INFO_tIME;
  192402. }
  192403. #endif
  192404. #if defined(PNG_tRNS_SUPPORTED)
  192405. void PNGAPI
  192406. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  192407. png_bytep trans, int num_trans, png_color_16p trans_values)
  192408. {
  192409. png_debug1(1, "in %s storage function\n", "tRNS");
  192410. if (png_ptr == NULL || info_ptr == NULL)
  192411. return;
  192412. if (trans != NULL)
  192413. {
  192414. /*
  192415. * It may not actually be necessary to set png_ptr->trans here;
  192416. * we do it for backward compatibility with the way the png_handle_tRNS
  192417. * function used to do the allocation.
  192418. */
  192419. #ifdef PNG_FREE_ME_SUPPORTED
  192420. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  192421. #endif
  192422. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  192423. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  192424. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  192425. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  192426. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  192427. #ifdef PNG_FREE_ME_SUPPORTED
  192428. info_ptr->free_me |= PNG_FREE_TRNS;
  192429. #else
  192430. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  192431. #endif
  192432. }
  192433. if (trans_values != NULL)
  192434. {
  192435. png_memcpy(&(info_ptr->trans_values), trans_values,
  192436. png_sizeof(png_color_16));
  192437. if (num_trans == 0)
  192438. num_trans = 1;
  192439. }
  192440. info_ptr->num_trans = (png_uint_16)num_trans;
  192441. info_ptr->valid |= PNG_INFO_tRNS;
  192442. }
  192443. #endif
  192444. #if defined(PNG_sPLT_SUPPORTED)
  192445. void PNGAPI
  192446. png_set_sPLT(png_structp png_ptr,
  192447. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  192448. {
  192449. png_sPLT_tp np;
  192450. int i;
  192451. if (png_ptr == NULL || info_ptr == NULL)
  192452. return;
  192453. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  192454. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  192455. if (np == NULL)
  192456. {
  192457. png_warning(png_ptr, "No memory for sPLT palettes.");
  192458. return;
  192459. }
  192460. png_memcpy(np, info_ptr->splt_palettes,
  192461. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  192462. png_free(png_ptr, info_ptr->splt_palettes);
  192463. info_ptr->splt_palettes=NULL;
  192464. for (i = 0; i < nentries; i++)
  192465. {
  192466. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  192467. png_sPLT_tp from = entries + i;
  192468. to->name = (png_charp)png_malloc_warn(png_ptr,
  192469. png_strlen(from->name) + 1);
  192470. if (to->name == NULL)
  192471. {
  192472. png_warning(png_ptr,
  192473. "Out of memory while processing sPLT chunk");
  192474. }
  192475. /* TODO: use png_malloc_warn */
  192476. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  192477. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  192478. from->nentries * png_sizeof(png_sPLT_entry));
  192479. /* TODO: use png_malloc_warn */
  192480. png_memcpy(to->entries, from->entries,
  192481. from->nentries * png_sizeof(png_sPLT_entry));
  192482. if (to->entries == NULL)
  192483. {
  192484. png_warning(png_ptr,
  192485. "Out of memory while processing sPLT chunk");
  192486. png_free(png_ptr,to->name);
  192487. to->name = NULL;
  192488. }
  192489. to->nentries = from->nentries;
  192490. to->depth = from->depth;
  192491. }
  192492. info_ptr->splt_palettes = np;
  192493. info_ptr->splt_palettes_num += nentries;
  192494. info_ptr->valid |= PNG_INFO_sPLT;
  192495. #ifdef PNG_FREE_ME_SUPPORTED
  192496. info_ptr->free_me |= PNG_FREE_SPLT;
  192497. #endif
  192498. }
  192499. #endif /* PNG_sPLT_SUPPORTED */
  192500. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  192501. void PNGAPI
  192502. png_set_unknown_chunks(png_structp png_ptr,
  192503. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  192504. {
  192505. png_unknown_chunkp np;
  192506. int i;
  192507. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  192508. return;
  192509. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  192510. (info_ptr->unknown_chunks_num + num_unknowns) *
  192511. png_sizeof(png_unknown_chunk));
  192512. if (np == NULL)
  192513. {
  192514. png_warning(png_ptr,
  192515. "Out of memory while processing unknown chunk.");
  192516. return;
  192517. }
  192518. png_memcpy(np, info_ptr->unknown_chunks,
  192519. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  192520. png_free(png_ptr, info_ptr->unknown_chunks);
  192521. info_ptr->unknown_chunks=NULL;
  192522. for (i = 0; i < num_unknowns; i++)
  192523. {
  192524. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  192525. png_unknown_chunkp from = unknowns + i;
  192526. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  192527. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  192528. if (to->data == NULL)
  192529. {
  192530. png_warning(png_ptr,
  192531. "Out of memory while processing unknown chunk.");
  192532. }
  192533. else
  192534. {
  192535. png_memcpy(to->data, from->data, from->size);
  192536. to->size = from->size;
  192537. /* note our location in the read or write sequence */
  192538. to->location = (png_byte)(png_ptr->mode & 0xff);
  192539. }
  192540. }
  192541. info_ptr->unknown_chunks = np;
  192542. info_ptr->unknown_chunks_num += num_unknowns;
  192543. #ifdef PNG_FREE_ME_SUPPORTED
  192544. info_ptr->free_me |= PNG_FREE_UNKN;
  192545. #endif
  192546. }
  192547. void PNGAPI
  192548. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  192549. int chunk, int location)
  192550. {
  192551. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  192552. (int)info_ptr->unknown_chunks_num)
  192553. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  192554. }
  192555. #endif
  192556. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  192557. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  192558. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  192559. void PNGAPI
  192560. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  192561. {
  192562. /* This function is deprecated in favor of png_permit_mng_features()
  192563. and will be removed from libpng-1.3.0 */
  192564. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  192565. if (png_ptr == NULL)
  192566. return;
  192567. png_ptr->mng_features_permitted = (png_byte)
  192568. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  192569. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  192570. }
  192571. #endif
  192572. #endif
  192573. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192574. png_uint_32 PNGAPI
  192575. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  192576. {
  192577. png_debug(1, "in png_permit_mng_features\n");
  192578. if (png_ptr == NULL)
  192579. return (png_uint_32)0;
  192580. png_ptr->mng_features_permitted =
  192581. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  192582. return (png_uint_32)png_ptr->mng_features_permitted;
  192583. }
  192584. #endif
  192585. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  192586. void PNGAPI
  192587. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  192588. chunk_list, int num_chunks)
  192589. {
  192590. png_bytep new_list, p;
  192591. int i, old_num_chunks;
  192592. if (png_ptr == NULL)
  192593. return;
  192594. if (num_chunks == 0)
  192595. {
  192596. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  192597. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  192598. else
  192599. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  192600. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  192601. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  192602. else
  192603. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  192604. return;
  192605. }
  192606. if (chunk_list == NULL)
  192607. return;
  192608. old_num_chunks=png_ptr->num_chunk_list;
  192609. new_list=(png_bytep)png_malloc(png_ptr,
  192610. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  192611. if(png_ptr->chunk_list != NULL)
  192612. {
  192613. png_memcpy(new_list, png_ptr->chunk_list,
  192614. (png_size_t)(5*old_num_chunks));
  192615. png_free(png_ptr, png_ptr->chunk_list);
  192616. png_ptr->chunk_list=NULL;
  192617. }
  192618. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  192619. (png_size_t)(5*num_chunks));
  192620. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  192621. *p=(png_byte)keep;
  192622. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  192623. png_ptr->chunk_list=new_list;
  192624. #ifdef PNG_FREE_ME_SUPPORTED
  192625. png_ptr->free_me |= PNG_FREE_LIST;
  192626. #endif
  192627. }
  192628. #endif
  192629. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  192630. void PNGAPI
  192631. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  192632. png_user_chunk_ptr read_user_chunk_fn)
  192633. {
  192634. png_debug(1, "in png_set_read_user_chunk_fn\n");
  192635. if (png_ptr == NULL)
  192636. return;
  192637. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  192638. png_ptr->user_chunk_ptr = user_chunk_ptr;
  192639. }
  192640. #endif
  192641. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  192642. void PNGAPI
  192643. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  192644. {
  192645. png_debug1(1, "in %s storage function\n", "rows");
  192646. if (png_ptr == NULL || info_ptr == NULL)
  192647. return;
  192648. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  192649. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  192650. info_ptr->row_pointers = row_pointers;
  192651. if(row_pointers)
  192652. info_ptr->valid |= PNG_INFO_IDAT;
  192653. }
  192654. #endif
  192655. #ifdef PNG_WRITE_SUPPORTED
  192656. void PNGAPI
  192657. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  192658. {
  192659. if (png_ptr == NULL)
  192660. return;
  192661. if(png_ptr->zbuf)
  192662. png_free(png_ptr, png_ptr->zbuf);
  192663. png_ptr->zbuf_size = (png_size_t)size;
  192664. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  192665. png_ptr->zstream.next_out = png_ptr->zbuf;
  192666. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  192667. }
  192668. #endif
  192669. void PNGAPI
  192670. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  192671. {
  192672. if (png_ptr && info_ptr)
  192673. info_ptr->valid &= ~(mask);
  192674. }
  192675. #ifndef PNG_1_0_X
  192676. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  192677. /* function was added to libpng 1.2.0 and should always exist by default */
  192678. void PNGAPI
  192679. png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags)
  192680. {
  192681. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  192682. if (png_ptr != NULL)
  192683. png_ptr->asm_flags = 0;
  192684. }
  192685. /* this function was added to libpng 1.2.0 */
  192686. void PNGAPI
  192687. png_set_mmx_thresholds (png_structp png_ptr,
  192688. png_byte mmx_bitdepth_threshold,
  192689. png_uint_32 mmx_rowbytes_threshold)
  192690. {
  192691. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  192692. if (png_ptr == NULL)
  192693. return;
  192694. }
  192695. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  192696. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  192697. /* this function was added to libpng 1.2.6 */
  192698. void PNGAPI
  192699. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  192700. png_uint_32 user_height_max)
  192701. {
  192702. /* Images with dimensions larger than these limits will be
  192703. * rejected by png_set_IHDR(). To accept any PNG datastream
  192704. * regardless of dimensions, set both limits to 0x7ffffffL.
  192705. */
  192706. if(png_ptr == NULL) return;
  192707. png_ptr->user_width_max = user_width_max;
  192708. png_ptr->user_height_max = user_height_max;
  192709. }
  192710. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  192711. #endif /* ?PNG_1_0_X */
  192712. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  192713. /********* End of inlined file: pngset.c *********/
  192714. /********* Start of inlined file: pngtrans.c *********/
  192715. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  192716. *
  192717. * Last changed in libpng 1.2.17 May 15, 2007
  192718. * For conditions of distribution and use, see copyright notice in png.h
  192719. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  192720. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192721. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192722. */
  192723. #define PNG_INTERNAL
  192724. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  192725. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  192726. /* turn on BGR-to-RGB mapping */
  192727. void PNGAPI
  192728. png_set_bgr(png_structp png_ptr)
  192729. {
  192730. png_debug(1, "in png_set_bgr\n");
  192731. if(png_ptr == NULL) return;
  192732. png_ptr->transformations |= PNG_BGR;
  192733. }
  192734. #endif
  192735. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  192736. /* turn on 16 bit byte swapping */
  192737. void PNGAPI
  192738. png_set_swap(png_structp png_ptr)
  192739. {
  192740. png_debug(1, "in png_set_swap\n");
  192741. if(png_ptr == NULL) return;
  192742. if (png_ptr->bit_depth == 16)
  192743. png_ptr->transformations |= PNG_SWAP_BYTES;
  192744. }
  192745. #endif
  192746. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  192747. /* turn on pixel packing */
  192748. void PNGAPI
  192749. png_set_packing(png_structp png_ptr)
  192750. {
  192751. png_debug(1, "in png_set_packing\n");
  192752. if(png_ptr == NULL) return;
  192753. if (png_ptr->bit_depth < 8)
  192754. {
  192755. png_ptr->transformations |= PNG_PACK;
  192756. png_ptr->usr_bit_depth = 8;
  192757. }
  192758. }
  192759. #endif
  192760. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  192761. /* turn on packed pixel swapping */
  192762. void PNGAPI
  192763. png_set_packswap(png_structp png_ptr)
  192764. {
  192765. png_debug(1, "in png_set_packswap\n");
  192766. if(png_ptr == NULL) return;
  192767. if (png_ptr->bit_depth < 8)
  192768. png_ptr->transformations |= PNG_PACKSWAP;
  192769. }
  192770. #endif
  192771. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  192772. void PNGAPI
  192773. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  192774. {
  192775. png_debug(1, "in png_set_shift\n");
  192776. if(png_ptr == NULL) return;
  192777. png_ptr->transformations |= PNG_SHIFT;
  192778. png_ptr->shift = *true_bits;
  192779. }
  192780. #endif
  192781. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  192782. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  192783. int PNGAPI
  192784. png_set_interlace_handling(png_structp png_ptr)
  192785. {
  192786. png_debug(1, "in png_set_interlace handling\n");
  192787. if (png_ptr && png_ptr->interlaced)
  192788. {
  192789. png_ptr->transformations |= PNG_INTERLACE;
  192790. return (7);
  192791. }
  192792. return (1);
  192793. }
  192794. #endif
  192795. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  192796. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  192797. * The filler type has changed in v0.95 to allow future 2-byte fillers
  192798. * for 48-bit input data, as well as to avoid problems with some compilers
  192799. * that don't like bytes as parameters.
  192800. */
  192801. void PNGAPI
  192802. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  192803. {
  192804. png_debug(1, "in png_set_filler\n");
  192805. if(png_ptr == NULL) return;
  192806. png_ptr->transformations |= PNG_FILLER;
  192807. png_ptr->filler = (png_byte)filler;
  192808. if (filler_loc == PNG_FILLER_AFTER)
  192809. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  192810. else
  192811. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  192812. /* This should probably go in the "do_read_filler" routine.
  192813. * I attempted to do that in libpng-1.0.1a but that caused problems
  192814. * so I restored it in libpng-1.0.2a
  192815. */
  192816. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  192817. {
  192818. png_ptr->usr_channels = 4;
  192819. }
  192820. /* Also I added this in libpng-1.0.2a (what happens when we expand
  192821. * a less-than-8-bit grayscale to GA? */
  192822. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  192823. {
  192824. png_ptr->usr_channels = 2;
  192825. }
  192826. }
  192827. #if !defined(PNG_1_0_X)
  192828. /* Added to libpng-1.2.7 */
  192829. void PNGAPI
  192830. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  192831. {
  192832. png_debug(1, "in png_set_add_alpha\n");
  192833. if(png_ptr == NULL) return;
  192834. png_set_filler(png_ptr, filler, filler_loc);
  192835. png_ptr->transformations |= PNG_ADD_ALPHA;
  192836. }
  192837. #endif
  192838. #endif
  192839. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  192840. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  192841. void PNGAPI
  192842. png_set_swap_alpha(png_structp png_ptr)
  192843. {
  192844. png_debug(1, "in png_set_swap_alpha\n");
  192845. if(png_ptr == NULL) return;
  192846. png_ptr->transformations |= PNG_SWAP_ALPHA;
  192847. }
  192848. #endif
  192849. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  192850. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  192851. void PNGAPI
  192852. png_set_invert_alpha(png_structp png_ptr)
  192853. {
  192854. png_debug(1, "in png_set_invert_alpha\n");
  192855. if(png_ptr == NULL) return;
  192856. png_ptr->transformations |= PNG_INVERT_ALPHA;
  192857. }
  192858. #endif
  192859. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  192860. void PNGAPI
  192861. png_set_invert_mono(png_structp png_ptr)
  192862. {
  192863. png_debug(1, "in png_set_invert_mono\n");
  192864. if(png_ptr == NULL) return;
  192865. png_ptr->transformations |= PNG_INVERT_MONO;
  192866. }
  192867. /* invert monochrome grayscale data */
  192868. void /* PRIVATE */
  192869. png_do_invert(png_row_infop row_info, png_bytep row)
  192870. {
  192871. png_debug(1, "in png_do_invert\n");
  192872. /* This test removed from libpng version 1.0.13 and 1.2.0:
  192873. * if (row_info->bit_depth == 1 &&
  192874. */
  192875. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192876. if (row == NULL || row_info == NULL)
  192877. return;
  192878. #endif
  192879. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192880. {
  192881. png_bytep rp = row;
  192882. png_uint_32 i;
  192883. png_uint_32 istop = row_info->rowbytes;
  192884. for (i = 0; i < istop; i++)
  192885. {
  192886. *rp = (png_byte)(~(*rp));
  192887. rp++;
  192888. }
  192889. }
  192890. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  192891. row_info->bit_depth == 8)
  192892. {
  192893. png_bytep rp = row;
  192894. png_uint_32 i;
  192895. png_uint_32 istop = row_info->rowbytes;
  192896. for (i = 0; i < istop; i+=2)
  192897. {
  192898. *rp = (png_byte)(~(*rp));
  192899. rp+=2;
  192900. }
  192901. }
  192902. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  192903. row_info->bit_depth == 16)
  192904. {
  192905. png_bytep rp = row;
  192906. png_uint_32 i;
  192907. png_uint_32 istop = row_info->rowbytes;
  192908. for (i = 0; i < istop; i+=4)
  192909. {
  192910. *rp = (png_byte)(~(*rp));
  192911. *(rp+1) = (png_byte)(~(*(rp+1)));
  192912. rp+=4;
  192913. }
  192914. }
  192915. }
  192916. #endif
  192917. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  192918. /* swaps byte order on 16 bit depth images */
  192919. void /* PRIVATE */
  192920. png_do_swap(png_row_infop row_info, png_bytep row)
  192921. {
  192922. png_debug(1, "in png_do_swap\n");
  192923. if (
  192924. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192925. row != NULL && row_info != NULL &&
  192926. #endif
  192927. row_info->bit_depth == 16)
  192928. {
  192929. png_bytep rp = row;
  192930. png_uint_32 i;
  192931. png_uint_32 istop= row_info->width * row_info->channels;
  192932. for (i = 0; i < istop; i++, rp += 2)
  192933. {
  192934. png_byte t = *rp;
  192935. *rp = *(rp + 1);
  192936. *(rp + 1) = t;
  192937. }
  192938. }
  192939. }
  192940. #endif
  192941. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  192942. static PNG_CONST png_byte onebppswaptable[256] = {
  192943. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  192944. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  192945. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  192946. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  192947. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  192948. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  192949. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  192950. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  192951. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  192952. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  192953. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  192954. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  192955. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  192956. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  192957. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  192958. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  192959. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  192960. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  192961. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  192962. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  192963. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  192964. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  192965. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  192966. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  192967. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  192968. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  192969. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  192970. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  192971. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  192972. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  192973. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  192974. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  192975. };
  192976. static PNG_CONST png_byte twobppswaptable[256] = {
  192977. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  192978. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  192979. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  192980. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  192981. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  192982. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  192983. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  192984. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  192985. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  192986. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  192987. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  192988. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  192989. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  192990. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  192991. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  192992. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  192993. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  192994. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  192995. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  192996. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  192997. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  192998. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  192999. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  193000. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  193001. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  193002. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  193003. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  193004. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  193005. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  193006. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  193007. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  193008. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  193009. };
  193010. static PNG_CONST png_byte fourbppswaptable[256] = {
  193011. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  193012. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  193013. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  193014. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  193015. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  193016. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  193017. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  193018. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  193019. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  193020. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  193021. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  193022. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  193023. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  193024. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  193025. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  193026. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  193027. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  193028. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  193029. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  193030. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  193031. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  193032. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  193033. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  193034. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  193035. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  193036. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  193037. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  193038. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  193039. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  193040. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  193041. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  193042. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  193043. };
  193044. /* swaps pixel packing order within bytes */
  193045. void /* PRIVATE */
  193046. png_do_packswap(png_row_infop row_info, png_bytep row)
  193047. {
  193048. png_debug(1, "in png_do_packswap\n");
  193049. if (
  193050. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193051. row != NULL && row_info != NULL &&
  193052. #endif
  193053. row_info->bit_depth < 8)
  193054. {
  193055. png_bytep rp, end, table;
  193056. end = row + row_info->rowbytes;
  193057. if (row_info->bit_depth == 1)
  193058. table = (png_bytep)onebppswaptable;
  193059. else if (row_info->bit_depth == 2)
  193060. table = (png_bytep)twobppswaptable;
  193061. else if (row_info->bit_depth == 4)
  193062. table = (png_bytep)fourbppswaptable;
  193063. else
  193064. return;
  193065. for (rp = row; rp < end; rp++)
  193066. *rp = table[*rp];
  193067. }
  193068. }
  193069. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  193070. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  193071. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  193072. /* remove filler or alpha byte(s) */
  193073. void /* PRIVATE */
  193074. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  193075. {
  193076. png_debug(1, "in png_do_strip_filler\n");
  193077. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193078. if (row != NULL && row_info != NULL)
  193079. #endif
  193080. {
  193081. png_bytep sp=row;
  193082. png_bytep dp=row;
  193083. png_uint_32 row_width=row_info->width;
  193084. png_uint_32 i;
  193085. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  193086. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193087. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  193088. row_info->channels == 4)
  193089. {
  193090. if (row_info->bit_depth == 8)
  193091. {
  193092. /* This converts from RGBX or RGBA to RGB */
  193093. if (flags & PNG_FLAG_FILLER_AFTER)
  193094. {
  193095. dp+=3; sp+=4;
  193096. for (i = 1; i < row_width; i++)
  193097. {
  193098. *dp++ = *sp++;
  193099. *dp++ = *sp++;
  193100. *dp++ = *sp++;
  193101. sp++;
  193102. }
  193103. }
  193104. /* This converts from XRGB or ARGB to RGB */
  193105. else
  193106. {
  193107. for (i = 0; i < row_width; i++)
  193108. {
  193109. sp++;
  193110. *dp++ = *sp++;
  193111. *dp++ = *sp++;
  193112. *dp++ = *sp++;
  193113. }
  193114. }
  193115. row_info->pixel_depth = 24;
  193116. row_info->rowbytes = row_width * 3;
  193117. }
  193118. else /* if (row_info->bit_depth == 16) */
  193119. {
  193120. if (flags & PNG_FLAG_FILLER_AFTER)
  193121. {
  193122. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  193123. sp += 8; dp += 6;
  193124. for (i = 1; i < row_width; i++)
  193125. {
  193126. /* This could be (although png_memcpy is probably slower):
  193127. png_memcpy(dp, sp, 6);
  193128. sp += 8;
  193129. dp += 6;
  193130. */
  193131. *dp++ = *sp++;
  193132. *dp++ = *sp++;
  193133. *dp++ = *sp++;
  193134. *dp++ = *sp++;
  193135. *dp++ = *sp++;
  193136. *dp++ = *sp++;
  193137. sp += 2;
  193138. }
  193139. }
  193140. else
  193141. {
  193142. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  193143. for (i = 0; i < row_width; i++)
  193144. {
  193145. /* This could be (although png_memcpy is probably slower):
  193146. png_memcpy(dp, sp, 6);
  193147. sp += 8;
  193148. dp += 6;
  193149. */
  193150. sp+=2;
  193151. *dp++ = *sp++;
  193152. *dp++ = *sp++;
  193153. *dp++ = *sp++;
  193154. *dp++ = *sp++;
  193155. *dp++ = *sp++;
  193156. *dp++ = *sp++;
  193157. }
  193158. }
  193159. row_info->pixel_depth = 48;
  193160. row_info->rowbytes = row_width * 6;
  193161. }
  193162. row_info->channels = 3;
  193163. }
  193164. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  193165. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193166. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  193167. row_info->channels == 2)
  193168. {
  193169. if (row_info->bit_depth == 8)
  193170. {
  193171. /* This converts from GX or GA to G */
  193172. if (flags & PNG_FLAG_FILLER_AFTER)
  193173. {
  193174. for (i = 0; i < row_width; i++)
  193175. {
  193176. *dp++ = *sp++;
  193177. sp++;
  193178. }
  193179. }
  193180. /* This converts from XG or AG to G */
  193181. else
  193182. {
  193183. for (i = 0; i < row_width; i++)
  193184. {
  193185. sp++;
  193186. *dp++ = *sp++;
  193187. }
  193188. }
  193189. row_info->pixel_depth = 8;
  193190. row_info->rowbytes = row_width;
  193191. }
  193192. else /* if (row_info->bit_depth == 16) */
  193193. {
  193194. if (flags & PNG_FLAG_FILLER_AFTER)
  193195. {
  193196. /* This converts from GGXX or GGAA to GG */
  193197. sp += 4; dp += 2;
  193198. for (i = 1; i < row_width; i++)
  193199. {
  193200. *dp++ = *sp++;
  193201. *dp++ = *sp++;
  193202. sp += 2;
  193203. }
  193204. }
  193205. else
  193206. {
  193207. /* This converts from XXGG or AAGG to GG */
  193208. for (i = 0; i < row_width; i++)
  193209. {
  193210. sp += 2;
  193211. *dp++ = *sp++;
  193212. *dp++ = *sp++;
  193213. }
  193214. }
  193215. row_info->pixel_depth = 16;
  193216. row_info->rowbytes = row_width * 2;
  193217. }
  193218. row_info->channels = 1;
  193219. }
  193220. if (flags & PNG_FLAG_STRIP_ALPHA)
  193221. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193222. }
  193223. }
  193224. #endif
  193225. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  193226. /* swaps red and blue bytes within a pixel */
  193227. void /* PRIVATE */
  193228. png_do_bgr(png_row_infop row_info, png_bytep row)
  193229. {
  193230. png_debug(1, "in png_do_bgr\n");
  193231. if (
  193232. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193233. row != NULL && row_info != NULL &&
  193234. #endif
  193235. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193236. {
  193237. png_uint_32 row_width = row_info->width;
  193238. if (row_info->bit_depth == 8)
  193239. {
  193240. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193241. {
  193242. png_bytep rp;
  193243. png_uint_32 i;
  193244. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  193245. {
  193246. png_byte save = *rp;
  193247. *rp = *(rp + 2);
  193248. *(rp + 2) = save;
  193249. }
  193250. }
  193251. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193252. {
  193253. png_bytep rp;
  193254. png_uint_32 i;
  193255. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  193256. {
  193257. png_byte save = *rp;
  193258. *rp = *(rp + 2);
  193259. *(rp + 2) = save;
  193260. }
  193261. }
  193262. }
  193263. else if (row_info->bit_depth == 16)
  193264. {
  193265. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193266. {
  193267. png_bytep rp;
  193268. png_uint_32 i;
  193269. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  193270. {
  193271. png_byte save = *rp;
  193272. *rp = *(rp + 4);
  193273. *(rp + 4) = save;
  193274. save = *(rp + 1);
  193275. *(rp + 1) = *(rp + 5);
  193276. *(rp + 5) = save;
  193277. }
  193278. }
  193279. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193280. {
  193281. png_bytep rp;
  193282. png_uint_32 i;
  193283. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  193284. {
  193285. png_byte save = *rp;
  193286. *rp = *(rp + 4);
  193287. *(rp + 4) = save;
  193288. save = *(rp + 1);
  193289. *(rp + 1) = *(rp + 5);
  193290. *(rp + 5) = save;
  193291. }
  193292. }
  193293. }
  193294. }
  193295. }
  193296. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  193297. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  193298. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  193299. defined(PNG_LEGACY_SUPPORTED)
  193300. void PNGAPI
  193301. png_set_user_transform_info(png_structp png_ptr, png_voidp
  193302. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  193303. {
  193304. png_debug(1, "in png_set_user_transform_info\n");
  193305. if(png_ptr == NULL) return;
  193306. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  193307. png_ptr->user_transform_ptr = user_transform_ptr;
  193308. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  193309. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  193310. #else
  193311. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  193312. png_warning(png_ptr,
  193313. "This version of libpng does not support user transform info");
  193314. #endif
  193315. }
  193316. #endif
  193317. /* This function returns a pointer to the user_transform_ptr associated with
  193318. * the user transform functions. The application should free any memory
  193319. * associated with this pointer before png_write_destroy and png_read_destroy
  193320. * are called.
  193321. */
  193322. png_voidp PNGAPI
  193323. png_get_user_transform_ptr(png_structp png_ptr)
  193324. {
  193325. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  193326. if (png_ptr == NULL) return (NULL);
  193327. return ((png_voidp)png_ptr->user_transform_ptr);
  193328. #else
  193329. return (NULL);
  193330. #endif
  193331. }
  193332. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  193333. /********* End of inlined file: pngtrans.c *********/
  193334. /********* Start of inlined file: pngwio.c *********/
  193335. /* pngwio.c - functions for data output
  193336. *
  193337. * Last changed in libpng 1.2.13 November 13, 2006
  193338. * For conditions of distribution and use, see copyright notice in png.h
  193339. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  193340. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193341. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193342. *
  193343. * This file provides a location for all output. Users who need
  193344. * special handling are expected to write functions that have the same
  193345. * arguments as these and perform similar functions, but that possibly
  193346. * use different output methods. Note that you shouldn't change these
  193347. * functions, but rather write replacement functions and then change
  193348. * them at run time with png_set_write_fn(...).
  193349. */
  193350. #define PNG_INTERNAL
  193351. #ifdef PNG_WRITE_SUPPORTED
  193352. /* Write the data to whatever output you are using. The default routine
  193353. writes to a file pointer. Note that this routine sometimes gets called
  193354. with very small lengths, so you should implement some kind of simple
  193355. buffering if you are using unbuffered writes. This should never be asked
  193356. to write more than 64K on a 16 bit machine. */
  193357. void /* PRIVATE */
  193358. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  193359. {
  193360. if (png_ptr->write_data_fn != NULL )
  193361. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  193362. else
  193363. png_error(png_ptr, "Call to NULL write function");
  193364. }
  193365. #if !defined(PNG_NO_STDIO)
  193366. /* This is the function that does the actual writing of data. If you are
  193367. not writing to a standard C stream, you should create a replacement
  193368. write_data function and use it at run time with png_set_write_fn(), rather
  193369. than changing the library. */
  193370. #ifndef USE_FAR_KEYWORD
  193371. void PNGAPI
  193372. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  193373. {
  193374. png_uint_32 check;
  193375. if(png_ptr == NULL) return;
  193376. #if defined(_WIN32_WCE)
  193377. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  193378. check = 0;
  193379. #else
  193380. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  193381. #endif
  193382. if (check != length)
  193383. png_error(png_ptr, "Write Error");
  193384. }
  193385. #else
  193386. /* this is the model-independent version. Since the standard I/O library
  193387. can't handle far buffers in the medium and small models, we have to copy
  193388. the data.
  193389. */
  193390. #define NEAR_BUF_SIZE 1024
  193391. #define MIN(a,b) (a <= b ? a : b)
  193392. void PNGAPI
  193393. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  193394. {
  193395. png_uint_32 check;
  193396. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  193397. png_FILE_p io_ptr;
  193398. if(png_ptr == NULL) return;
  193399. /* Check if data really is near. If so, use usual code. */
  193400. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  193401. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  193402. if ((png_bytep)near_data == data)
  193403. {
  193404. #if defined(_WIN32_WCE)
  193405. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  193406. check = 0;
  193407. #else
  193408. check = fwrite(near_data, 1, length, io_ptr);
  193409. #endif
  193410. }
  193411. else
  193412. {
  193413. png_byte buf[NEAR_BUF_SIZE];
  193414. png_size_t written, remaining, err;
  193415. check = 0;
  193416. remaining = length;
  193417. do
  193418. {
  193419. written = MIN(NEAR_BUF_SIZE, remaining);
  193420. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  193421. #if defined(_WIN32_WCE)
  193422. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  193423. err = 0;
  193424. #else
  193425. err = fwrite(buf, 1, written, io_ptr);
  193426. #endif
  193427. if (err != written)
  193428. break;
  193429. else
  193430. check += err;
  193431. data += written;
  193432. remaining -= written;
  193433. }
  193434. while (remaining != 0);
  193435. }
  193436. if (check != length)
  193437. png_error(png_ptr, "Write Error");
  193438. }
  193439. #endif
  193440. #endif
  193441. /* This function is called to output any data pending writing (normally
  193442. to disk). After png_flush is called, there should be no data pending
  193443. writing in any buffers. */
  193444. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  193445. void /* PRIVATE */
  193446. png_flush(png_structp png_ptr)
  193447. {
  193448. if (png_ptr->output_flush_fn != NULL)
  193449. (*(png_ptr->output_flush_fn))(png_ptr);
  193450. }
  193451. #if !defined(PNG_NO_STDIO)
  193452. void PNGAPI
  193453. png_default_flush(png_structp png_ptr)
  193454. {
  193455. #if !defined(_WIN32_WCE)
  193456. png_FILE_p io_ptr;
  193457. #endif
  193458. if(png_ptr == NULL) return;
  193459. #if !defined(_WIN32_WCE)
  193460. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  193461. if (io_ptr != NULL)
  193462. fflush(io_ptr);
  193463. #endif
  193464. }
  193465. #endif
  193466. #endif
  193467. /* This function allows the application to supply new output functions for
  193468. libpng if standard C streams aren't being used.
  193469. This function takes as its arguments:
  193470. png_ptr - pointer to a png output data structure
  193471. io_ptr - pointer to user supplied structure containing info about
  193472. the output functions. May be NULL.
  193473. write_data_fn - pointer to a new output function that takes as its
  193474. arguments a pointer to a png_struct, a pointer to
  193475. data to be written, and a 32-bit unsigned int that is
  193476. the number of bytes to be written. The new write
  193477. function should call png_error(png_ptr, "Error msg")
  193478. to exit and output any fatal error messages.
  193479. flush_data_fn - pointer to a new flush function that takes as its
  193480. arguments a pointer to a png_struct. After a call to
  193481. the flush function, there should be no data in any buffers
  193482. or pending transmission. If the output method doesn't do
  193483. any buffering of ouput, a function prototype must still be
  193484. supplied although it doesn't have to do anything. If
  193485. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  193486. time, output_flush_fn will be ignored, although it must be
  193487. supplied for compatibility. */
  193488. void PNGAPI
  193489. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  193490. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  193491. {
  193492. if(png_ptr == NULL) return;
  193493. png_ptr->io_ptr = io_ptr;
  193494. #if !defined(PNG_NO_STDIO)
  193495. if (write_data_fn != NULL)
  193496. png_ptr->write_data_fn = write_data_fn;
  193497. else
  193498. png_ptr->write_data_fn = png_default_write_data;
  193499. #else
  193500. png_ptr->write_data_fn = write_data_fn;
  193501. #endif
  193502. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  193503. #if !defined(PNG_NO_STDIO)
  193504. if (output_flush_fn != NULL)
  193505. png_ptr->output_flush_fn = output_flush_fn;
  193506. else
  193507. png_ptr->output_flush_fn = png_default_flush;
  193508. #else
  193509. png_ptr->output_flush_fn = output_flush_fn;
  193510. #endif
  193511. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  193512. /* It is an error to read while writing a png file */
  193513. if (png_ptr->read_data_fn != NULL)
  193514. {
  193515. png_ptr->read_data_fn = NULL;
  193516. png_warning(png_ptr,
  193517. "Attempted to set both read_data_fn and write_data_fn in");
  193518. png_warning(png_ptr,
  193519. "the same structure. Resetting read_data_fn to NULL.");
  193520. }
  193521. }
  193522. #if defined(USE_FAR_KEYWORD)
  193523. #if defined(_MSC_VER)
  193524. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  193525. {
  193526. void *near_ptr;
  193527. void FAR *far_ptr;
  193528. FP_OFF(near_ptr) = FP_OFF(ptr);
  193529. far_ptr = (void FAR *)near_ptr;
  193530. if(check != 0)
  193531. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  193532. png_error(png_ptr,"segment lost in conversion");
  193533. return(near_ptr);
  193534. }
  193535. # else
  193536. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  193537. {
  193538. void *near_ptr;
  193539. void FAR *far_ptr;
  193540. near_ptr = (void FAR *)ptr;
  193541. far_ptr = (void FAR *)near_ptr;
  193542. if(check != 0)
  193543. if(far_ptr != ptr)
  193544. png_error(png_ptr,"segment lost in conversion");
  193545. return(near_ptr);
  193546. }
  193547. # endif
  193548. # endif
  193549. #endif /* PNG_WRITE_SUPPORTED */
  193550. /********* End of inlined file: pngwio.c *********/
  193551. /********* Start of inlined file: pngwrite.c *********/
  193552. /* pngwrite.c - general routines to write a PNG file
  193553. *
  193554. * Last changed in libpng 1.2.15 January 5, 2007
  193555. * For conditions of distribution and use, see copyright notice in png.h
  193556. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193557. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193558. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193559. */
  193560. /* get internal access to png.h */
  193561. #define PNG_INTERNAL
  193562. #ifdef PNG_WRITE_SUPPORTED
  193563. /* Writes all the PNG information. This is the suggested way to use the
  193564. * library. If you have a new chunk to add, make a function to write it,
  193565. * and put it in the correct location here. If you want the chunk written
  193566. * after the image data, put it in png_write_end(). I strongly encourage
  193567. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  193568. * the chunk, as that will keep the code from breaking if you want to just
  193569. * write a plain PNG file. If you have long comments, I suggest writing
  193570. * them in png_write_end(), and compressing them.
  193571. */
  193572. void PNGAPI
  193573. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  193574. {
  193575. png_debug(1, "in png_write_info_before_PLTE\n");
  193576. if (png_ptr == NULL || info_ptr == NULL)
  193577. return;
  193578. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  193579. {
  193580. png_write_sig(png_ptr); /* write PNG signature */
  193581. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193582. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  193583. {
  193584. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  193585. png_ptr->mng_features_permitted=0;
  193586. }
  193587. #endif
  193588. /* write IHDR information. */
  193589. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  193590. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  193591. info_ptr->filter_type,
  193592. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193593. info_ptr->interlace_type);
  193594. #else
  193595. 0);
  193596. #endif
  193597. /* the rest of these check to see if the valid field has the appropriate
  193598. flag set, and if it does, writes the chunk. */
  193599. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  193600. if (info_ptr->valid & PNG_INFO_gAMA)
  193601. {
  193602. # ifdef PNG_FLOATING_POINT_SUPPORTED
  193603. png_write_gAMA(png_ptr, info_ptr->gamma);
  193604. #else
  193605. #ifdef PNG_FIXED_POINT_SUPPORTED
  193606. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  193607. # endif
  193608. #endif
  193609. }
  193610. #endif
  193611. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  193612. if (info_ptr->valid & PNG_INFO_sRGB)
  193613. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  193614. #endif
  193615. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  193616. if (info_ptr->valid & PNG_INFO_iCCP)
  193617. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  193618. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  193619. #endif
  193620. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  193621. if (info_ptr->valid & PNG_INFO_sBIT)
  193622. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  193623. #endif
  193624. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  193625. if (info_ptr->valid & PNG_INFO_cHRM)
  193626. {
  193627. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193628. png_write_cHRM(png_ptr,
  193629. info_ptr->x_white, info_ptr->y_white,
  193630. info_ptr->x_red, info_ptr->y_red,
  193631. info_ptr->x_green, info_ptr->y_green,
  193632. info_ptr->x_blue, info_ptr->y_blue);
  193633. #else
  193634. # ifdef PNG_FIXED_POINT_SUPPORTED
  193635. png_write_cHRM_fixed(png_ptr,
  193636. info_ptr->int_x_white, info_ptr->int_y_white,
  193637. info_ptr->int_x_red, info_ptr->int_y_red,
  193638. info_ptr->int_x_green, info_ptr->int_y_green,
  193639. info_ptr->int_x_blue, info_ptr->int_y_blue);
  193640. # endif
  193641. #endif
  193642. }
  193643. #endif
  193644. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  193645. if (info_ptr->unknown_chunks_num)
  193646. {
  193647. png_unknown_chunk *up;
  193648. png_debug(5, "writing extra chunks\n");
  193649. for (up = info_ptr->unknown_chunks;
  193650. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  193651. up++)
  193652. {
  193653. int keep=png_handle_as_unknown(png_ptr, up->name);
  193654. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  193655. up->location && !(up->location & PNG_HAVE_PLTE) &&
  193656. !(up->location & PNG_HAVE_IDAT) &&
  193657. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  193658. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  193659. {
  193660. png_write_chunk(png_ptr, up->name, up->data, up->size);
  193661. }
  193662. }
  193663. }
  193664. #endif
  193665. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  193666. }
  193667. }
  193668. void PNGAPI
  193669. png_write_info(png_structp png_ptr, png_infop info_ptr)
  193670. {
  193671. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  193672. int i;
  193673. #endif
  193674. png_debug(1, "in png_write_info\n");
  193675. if (png_ptr == NULL || info_ptr == NULL)
  193676. return;
  193677. png_write_info_before_PLTE(png_ptr, info_ptr);
  193678. if (info_ptr->valid & PNG_INFO_PLTE)
  193679. png_write_PLTE(png_ptr, info_ptr->palette,
  193680. (png_uint_32)info_ptr->num_palette);
  193681. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193682. png_error(png_ptr, "Valid palette required for paletted images");
  193683. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  193684. if (info_ptr->valid & PNG_INFO_tRNS)
  193685. {
  193686. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  193687. /* invert the alpha channel (in tRNS) */
  193688. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  193689. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193690. {
  193691. int j;
  193692. for (j=0; j<(int)info_ptr->num_trans; j++)
  193693. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  193694. }
  193695. #endif
  193696. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  193697. info_ptr->num_trans, info_ptr->color_type);
  193698. }
  193699. #endif
  193700. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  193701. if (info_ptr->valid & PNG_INFO_bKGD)
  193702. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  193703. #endif
  193704. #if defined(PNG_WRITE_hIST_SUPPORTED)
  193705. if (info_ptr->valid & PNG_INFO_hIST)
  193706. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  193707. #endif
  193708. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  193709. if (info_ptr->valid & PNG_INFO_oFFs)
  193710. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  193711. info_ptr->offset_unit_type);
  193712. #endif
  193713. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  193714. if (info_ptr->valid & PNG_INFO_pCAL)
  193715. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  193716. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  193717. info_ptr->pcal_units, info_ptr->pcal_params);
  193718. #endif
  193719. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  193720. if (info_ptr->valid & PNG_INFO_sCAL)
  193721. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  193722. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  193723. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  193724. #else
  193725. #ifdef PNG_FIXED_POINT_SUPPORTED
  193726. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  193727. info_ptr->scal_s_width, info_ptr->scal_s_height);
  193728. #else
  193729. png_warning(png_ptr,
  193730. "png_write_sCAL not supported; sCAL chunk not written.");
  193731. #endif
  193732. #endif
  193733. #endif
  193734. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  193735. if (info_ptr->valid & PNG_INFO_pHYs)
  193736. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  193737. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  193738. #endif
  193739. #if defined(PNG_WRITE_tIME_SUPPORTED)
  193740. if (info_ptr->valid & PNG_INFO_tIME)
  193741. {
  193742. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  193743. png_ptr->mode |= PNG_WROTE_tIME;
  193744. }
  193745. #endif
  193746. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  193747. if (info_ptr->valid & PNG_INFO_sPLT)
  193748. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  193749. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  193750. #endif
  193751. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  193752. /* Check to see if we need to write text chunks */
  193753. for (i = 0; i < info_ptr->num_text; i++)
  193754. {
  193755. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  193756. info_ptr->text[i].compression);
  193757. /* an internationalized chunk? */
  193758. if (info_ptr->text[i].compression > 0)
  193759. {
  193760. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  193761. /* write international chunk */
  193762. png_write_iTXt(png_ptr,
  193763. info_ptr->text[i].compression,
  193764. info_ptr->text[i].key,
  193765. info_ptr->text[i].lang,
  193766. info_ptr->text[i].lang_key,
  193767. info_ptr->text[i].text);
  193768. #else
  193769. png_warning(png_ptr, "Unable to write international text");
  193770. #endif
  193771. /* Mark this chunk as written */
  193772. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  193773. }
  193774. /* If we want a compressed text chunk */
  193775. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  193776. {
  193777. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  193778. /* write compressed chunk */
  193779. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  193780. info_ptr->text[i].text, 0,
  193781. info_ptr->text[i].compression);
  193782. #else
  193783. png_warning(png_ptr, "Unable to write compressed text");
  193784. #endif
  193785. /* Mark this chunk as written */
  193786. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  193787. }
  193788. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  193789. {
  193790. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  193791. /* write uncompressed chunk */
  193792. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  193793. info_ptr->text[i].text,
  193794. 0);
  193795. #else
  193796. png_warning(png_ptr, "Unable to write uncompressed text");
  193797. #endif
  193798. /* Mark this chunk as written */
  193799. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  193800. }
  193801. }
  193802. #endif
  193803. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  193804. if (info_ptr->unknown_chunks_num)
  193805. {
  193806. png_unknown_chunk *up;
  193807. png_debug(5, "writing extra chunks\n");
  193808. for (up = info_ptr->unknown_chunks;
  193809. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  193810. up++)
  193811. {
  193812. int keep=png_handle_as_unknown(png_ptr, up->name);
  193813. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  193814. up->location && (up->location & PNG_HAVE_PLTE) &&
  193815. !(up->location & PNG_HAVE_IDAT) &&
  193816. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  193817. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  193818. {
  193819. png_write_chunk(png_ptr, up->name, up->data, up->size);
  193820. }
  193821. }
  193822. }
  193823. #endif
  193824. }
  193825. /* Writes the end of the PNG file. If you don't want to write comments or
  193826. * time information, you can pass NULL for info. If you already wrote these
  193827. * in png_write_info(), do not write them again here. If you have long
  193828. * comments, I suggest writing them here, and compressing them.
  193829. */
  193830. void PNGAPI
  193831. png_write_end(png_structp png_ptr, png_infop info_ptr)
  193832. {
  193833. png_debug(1, "in png_write_end\n");
  193834. if (png_ptr == NULL)
  193835. return;
  193836. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  193837. png_error(png_ptr, "No IDATs written into file");
  193838. /* see if user wants us to write information chunks */
  193839. if (info_ptr != NULL)
  193840. {
  193841. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  193842. int i; /* local index variable */
  193843. #endif
  193844. #if defined(PNG_WRITE_tIME_SUPPORTED)
  193845. /* check to see if user has supplied a time chunk */
  193846. if ((info_ptr->valid & PNG_INFO_tIME) &&
  193847. !(png_ptr->mode & PNG_WROTE_tIME))
  193848. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  193849. #endif
  193850. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  193851. /* loop through comment chunks */
  193852. for (i = 0; i < info_ptr->num_text; i++)
  193853. {
  193854. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  193855. info_ptr->text[i].compression);
  193856. /* an internationalized chunk? */
  193857. if (info_ptr->text[i].compression > 0)
  193858. {
  193859. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  193860. /* write international chunk */
  193861. png_write_iTXt(png_ptr,
  193862. info_ptr->text[i].compression,
  193863. info_ptr->text[i].key,
  193864. info_ptr->text[i].lang,
  193865. info_ptr->text[i].lang_key,
  193866. info_ptr->text[i].text);
  193867. #else
  193868. png_warning(png_ptr, "Unable to write international text");
  193869. #endif
  193870. /* Mark this chunk as written */
  193871. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  193872. }
  193873. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  193874. {
  193875. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  193876. /* write compressed chunk */
  193877. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  193878. info_ptr->text[i].text, 0,
  193879. info_ptr->text[i].compression);
  193880. #else
  193881. png_warning(png_ptr, "Unable to write compressed text");
  193882. #endif
  193883. /* Mark this chunk as written */
  193884. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  193885. }
  193886. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  193887. {
  193888. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  193889. /* write uncompressed chunk */
  193890. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  193891. info_ptr->text[i].text, 0);
  193892. #else
  193893. png_warning(png_ptr, "Unable to write uncompressed text");
  193894. #endif
  193895. /* Mark this chunk as written */
  193896. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  193897. }
  193898. }
  193899. #endif
  193900. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  193901. if (info_ptr->unknown_chunks_num)
  193902. {
  193903. png_unknown_chunk *up;
  193904. png_debug(5, "writing extra chunks\n");
  193905. for (up = info_ptr->unknown_chunks;
  193906. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  193907. up++)
  193908. {
  193909. int keep=png_handle_as_unknown(png_ptr, up->name);
  193910. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  193911. up->location && (up->location & PNG_AFTER_IDAT) &&
  193912. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  193913. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  193914. {
  193915. png_write_chunk(png_ptr, up->name, up->data, up->size);
  193916. }
  193917. }
  193918. }
  193919. #endif
  193920. }
  193921. png_ptr->mode |= PNG_AFTER_IDAT;
  193922. /* write end of PNG file */
  193923. png_write_IEND(png_ptr);
  193924. }
  193925. #if defined(PNG_WRITE_tIME_SUPPORTED)
  193926. #if !defined(_WIN32_WCE)
  193927. /* "time.h" functions are not supported on WindowsCE */
  193928. void PNGAPI
  193929. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  193930. {
  193931. png_debug(1, "in png_convert_from_struct_tm\n");
  193932. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  193933. ptime->month = (png_byte)(ttime->tm_mon + 1);
  193934. ptime->day = (png_byte)ttime->tm_mday;
  193935. ptime->hour = (png_byte)ttime->tm_hour;
  193936. ptime->minute = (png_byte)ttime->tm_min;
  193937. ptime->second = (png_byte)ttime->tm_sec;
  193938. }
  193939. void PNGAPI
  193940. png_convert_from_time_t(png_timep ptime, time_t ttime)
  193941. {
  193942. struct tm *tbuf;
  193943. png_debug(1, "in png_convert_from_time_t\n");
  193944. tbuf = gmtime(&ttime);
  193945. png_convert_from_struct_tm(ptime, tbuf);
  193946. }
  193947. #endif
  193948. #endif
  193949. /* Initialize png_ptr structure, and allocate any memory needed */
  193950. png_structp PNGAPI
  193951. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  193952. png_error_ptr error_fn, png_error_ptr warn_fn)
  193953. {
  193954. #ifdef PNG_USER_MEM_SUPPORTED
  193955. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  193956. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  193957. }
  193958. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  193959. png_structp PNGAPI
  193960. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  193961. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  193962. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  193963. {
  193964. #endif /* PNG_USER_MEM_SUPPORTED */
  193965. png_structp png_ptr;
  193966. #ifdef PNG_SETJMP_SUPPORTED
  193967. #ifdef USE_FAR_KEYWORD
  193968. jmp_buf jmpbuf;
  193969. #endif
  193970. #endif
  193971. int i;
  193972. png_debug(1, "in png_create_write_struct\n");
  193973. #ifdef PNG_USER_MEM_SUPPORTED
  193974. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  193975. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  193976. #else
  193977. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  193978. #endif /* PNG_USER_MEM_SUPPORTED */
  193979. if (png_ptr == NULL)
  193980. return (NULL);
  193981. /* added at libpng-1.2.6 */
  193982. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  193983. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  193984. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  193985. #endif
  193986. #ifdef PNG_SETJMP_SUPPORTED
  193987. #ifdef USE_FAR_KEYWORD
  193988. if (setjmp(jmpbuf))
  193989. #else
  193990. if (setjmp(png_ptr->jmpbuf))
  193991. #endif
  193992. {
  193993. png_free(png_ptr, png_ptr->zbuf);
  193994. png_ptr->zbuf=NULL;
  193995. png_destroy_struct(png_ptr);
  193996. return (NULL);
  193997. }
  193998. #ifdef USE_FAR_KEYWORD
  193999. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  194000. #endif
  194001. #endif
  194002. #ifdef PNG_USER_MEM_SUPPORTED
  194003. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  194004. #endif /* PNG_USER_MEM_SUPPORTED */
  194005. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  194006. i=0;
  194007. do
  194008. {
  194009. if(user_png_ver[i] != png_libpng_ver[i])
  194010. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  194011. } while (png_libpng_ver[i++]);
  194012. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  194013. {
  194014. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  194015. * we must recompile any applications that use any older library version.
  194016. * For versions after libpng 1.0, we will be compatible, so we need
  194017. * only check the first digit.
  194018. */
  194019. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  194020. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  194021. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  194022. {
  194023. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194024. char msg[80];
  194025. if (user_png_ver)
  194026. {
  194027. png_snprintf(msg, 80,
  194028. "Application was compiled with png.h from libpng-%.20s",
  194029. user_png_ver);
  194030. png_warning(png_ptr, msg);
  194031. }
  194032. png_snprintf(msg, 80,
  194033. "Application is running with png.c from libpng-%.20s",
  194034. png_libpng_ver);
  194035. png_warning(png_ptr, msg);
  194036. #endif
  194037. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194038. png_ptr->flags=0;
  194039. #endif
  194040. png_error(png_ptr,
  194041. "Incompatible libpng version in application and library");
  194042. }
  194043. }
  194044. /* initialize zbuf - compression buffer */
  194045. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  194046. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  194047. (png_uint_32)png_ptr->zbuf_size);
  194048. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  194049. png_flush_ptr_NULL);
  194050. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  194051. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  194052. 1, png_doublep_NULL, png_doublep_NULL);
  194053. #endif
  194054. #ifdef PNG_SETJMP_SUPPORTED
  194055. /* Applications that neglect to set up their own setjmp() and then encounter
  194056. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  194057. abort instead of returning. */
  194058. #ifdef USE_FAR_KEYWORD
  194059. if (setjmp(jmpbuf))
  194060. PNG_ABORT();
  194061. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  194062. #else
  194063. if (setjmp(png_ptr->jmpbuf))
  194064. PNG_ABORT();
  194065. #endif
  194066. #endif
  194067. return (png_ptr);
  194068. }
  194069. /* Initialize png_ptr structure, and allocate any memory needed */
  194070. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  194071. /* Deprecated. */
  194072. #undef png_write_init
  194073. void PNGAPI
  194074. png_write_init(png_structp png_ptr)
  194075. {
  194076. /* We only come here via pre-1.0.7-compiled applications */
  194077. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  194078. }
  194079. void PNGAPI
  194080. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  194081. png_size_t png_struct_size, png_size_t png_info_size)
  194082. {
  194083. /* We only come here via pre-1.0.12-compiled applications */
  194084. if(png_ptr == NULL) return;
  194085. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194086. if(png_sizeof(png_struct) > png_struct_size ||
  194087. png_sizeof(png_info) > png_info_size)
  194088. {
  194089. char msg[80];
  194090. png_ptr->warning_fn=NULL;
  194091. if (user_png_ver)
  194092. {
  194093. png_snprintf(msg, 80,
  194094. "Application was compiled with png.h from libpng-%.20s",
  194095. user_png_ver);
  194096. png_warning(png_ptr, msg);
  194097. }
  194098. png_snprintf(msg, 80,
  194099. "Application is running with png.c from libpng-%.20s",
  194100. png_libpng_ver);
  194101. png_warning(png_ptr, msg);
  194102. }
  194103. #endif
  194104. if(png_sizeof(png_struct) > png_struct_size)
  194105. {
  194106. png_ptr->error_fn=NULL;
  194107. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194108. png_ptr->flags=0;
  194109. #endif
  194110. png_error(png_ptr,
  194111. "The png struct allocated by the application for writing is too small.");
  194112. }
  194113. if(png_sizeof(png_info) > png_info_size)
  194114. {
  194115. png_ptr->error_fn=NULL;
  194116. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194117. png_ptr->flags=0;
  194118. #endif
  194119. png_error(png_ptr,
  194120. "The info struct allocated by the application for writing is too small.");
  194121. }
  194122. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  194123. }
  194124. #endif /* PNG_1_0_X || PNG_1_2_X */
  194125. void PNGAPI
  194126. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  194127. png_size_t png_struct_size)
  194128. {
  194129. png_structp png_ptr=*ptr_ptr;
  194130. #ifdef PNG_SETJMP_SUPPORTED
  194131. jmp_buf tmp_jmp; /* to save current jump buffer */
  194132. #endif
  194133. int i = 0;
  194134. if (png_ptr == NULL)
  194135. return;
  194136. do
  194137. {
  194138. if (user_png_ver[i] != png_libpng_ver[i])
  194139. {
  194140. #ifdef PNG_LEGACY_SUPPORTED
  194141. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  194142. #else
  194143. png_ptr->warning_fn=NULL;
  194144. png_warning(png_ptr,
  194145. "Application uses deprecated png_write_init() and should be recompiled.");
  194146. break;
  194147. #endif
  194148. }
  194149. } while (png_libpng_ver[i++]);
  194150. png_debug(1, "in png_write_init_3\n");
  194151. #ifdef PNG_SETJMP_SUPPORTED
  194152. /* save jump buffer and error functions */
  194153. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  194154. #endif
  194155. if (png_sizeof(png_struct) > png_struct_size)
  194156. {
  194157. png_destroy_struct(png_ptr);
  194158. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  194159. *ptr_ptr = png_ptr;
  194160. }
  194161. /* reset all variables to 0 */
  194162. png_memset(png_ptr, 0, png_sizeof (png_struct));
  194163. /* added at libpng-1.2.6 */
  194164. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194165. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  194166. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  194167. #endif
  194168. #ifdef PNG_SETJMP_SUPPORTED
  194169. /* restore jump buffer */
  194170. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  194171. #endif
  194172. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  194173. png_flush_ptr_NULL);
  194174. /* initialize zbuf - compression buffer */
  194175. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  194176. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  194177. (png_uint_32)png_ptr->zbuf_size);
  194178. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  194179. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  194180. 1, png_doublep_NULL, png_doublep_NULL);
  194181. #endif
  194182. }
  194183. /* Write a few rows of image data. If the image is interlaced,
  194184. * either you will have to write the 7 sub images, or, if you
  194185. * have called png_set_interlace_handling(), you will have to
  194186. * "write" the image seven times.
  194187. */
  194188. void PNGAPI
  194189. png_write_rows(png_structp png_ptr, png_bytepp row,
  194190. png_uint_32 num_rows)
  194191. {
  194192. png_uint_32 i; /* row counter */
  194193. png_bytepp rp; /* row pointer */
  194194. png_debug(1, "in png_write_rows\n");
  194195. if (png_ptr == NULL)
  194196. return;
  194197. /* loop through the rows */
  194198. for (i = 0, rp = row; i < num_rows; i++, rp++)
  194199. {
  194200. png_write_row(png_ptr, *rp);
  194201. }
  194202. }
  194203. /* Write the image. You only need to call this function once, even
  194204. * if you are writing an interlaced image.
  194205. */
  194206. void PNGAPI
  194207. png_write_image(png_structp png_ptr, png_bytepp image)
  194208. {
  194209. png_uint_32 i; /* row index */
  194210. int pass, num_pass; /* pass variables */
  194211. png_bytepp rp; /* points to current row */
  194212. if (png_ptr == NULL)
  194213. return;
  194214. png_debug(1, "in png_write_image\n");
  194215. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194216. /* intialize interlace handling. If image is not interlaced,
  194217. this will set pass to 1 */
  194218. num_pass = png_set_interlace_handling(png_ptr);
  194219. #else
  194220. num_pass = 1;
  194221. #endif
  194222. /* loop through passes */
  194223. for (pass = 0; pass < num_pass; pass++)
  194224. {
  194225. /* loop through image */
  194226. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  194227. {
  194228. png_write_row(png_ptr, *rp);
  194229. }
  194230. }
  194231. }
  194232. /* called by user to write a row of image data */
  194233. void PNGAPI
  194234. png_write_row(png_structp png_ptr, png_bytep row)
  194235. {
  194236. if (png_ptr == NULL)
  194237. return;
  194238. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  194239. png_ptr->row_number, png_ptr->pass);
  194240. /* initialize transformations and other stuff if first time */
  194241. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  194242. {
  194243. /* make sure we wrote the header info */
  194244. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  194245. png_error(png_ptr,
  194246. "png_write_info was never called before png_write_row.");
  194247. /* check for transforms that have been set but were defined out */
  194248. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  194249. if (png_ptr->transformations & PNG_INVERT_MONO)
  194250. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  194251. #endif
  194252. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  194253. if (png_ptr->transformations & PNG_FILLER)
  194254. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  194255. #endif
  194256. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  194257. if (png_ptr->transformations & PNG_PACKSWAP)
  194258. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  194259. #endif
  194260. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  194261. if (png_ptr->transformations & PNG_PACK)
  194262. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  194263. #endif
  194264. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  194265. if (png_ptr->transformations & PNG_SHIFT)
  194266. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  194267. #endif
  194268. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  194269. if (png_ptr->transformations & PNG_BGR)
  194270. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  194271. #endif
  194272. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  194273. if (png_ptr->transformations & PNG_SWAP_BYTES)
  194274. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  194275. #endif
  194276. png_write_start_row(png_ptr);
  194277. }
  194278. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194279. /* if interlaced and not interested in row, return */
  194280. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  194281. {
  194282. switch (png_ptr->pass)
  194283. {
  194284. case 0:
  194285. if (png_ptr->row_number & 0x07)
  194286. {
  194287. png_write_finish_row(png_ptr);
  194288. return;
  194289. }
  194290. break;
  194291. case 1:
  194292. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  194293. {
  194294. png_write_finish_row(png_ptr);
  194295. return;
  194296. }
  194297. break;
  194298. case 2:
  194299. if ((png_ptr->row_number & 0x07) != 4)
  194300. {
  194301. png_write_finish_row(png_ptr);
  194302. return;
  194303. }
  194304. break;
  194305. case 3:
  194306. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  194307. {
  194308. png_write_finish_row(png_ptr);
  194309. return;
  194310. }
  194311. break;
  194312. case 4:
  194313. if ((png_ptr->row_number & 0x03) != 2)
  194314. {
  194315. png_write_finish_row(png_ptr);
  194316. return;
  194317. }
  194318. break;
  194319. case 5:
  194320. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  194321. {
  194322. png_write_finish_row(png_ptr);
  194323. return;
  194324. }
  194325. break;
  194326. case 6:
  194327. if (!(png_ptr->row_number & 0x01))
  194328. {
  194329. png_write_finish_row(png_ptr);
  194330. return;
  194331. }
  194332. break;
  194333. }
  194334. }
  194335. #endif
  194336. /* set up row info for transformations */
  194337. png_ptr->row_info.color_type = png_ptr->color_type;
  194338. png_ptr->row_info.width = png_ptr->usr_width;
  194339. png_ptr->row_info.channels = png_ptr->usr_channels;
  194340. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  194341. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  194342. png_ptr->row_info.channels);
  194343. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  194344. png_ptr->row_info.width);
  194345. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  194346. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  194347. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  194348. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  194349. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  194350. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  194351. /* Copy user's row into buffer, leaving room for filter byte. */
  194352. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  194353. png_ptr->row_info.rowbytes);
  194354. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194355. /* handle interlacing */
  194356. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  194357. (png_ptr->transformations & PNG_INTERLACE))
  194358. {
  194359. png_do_write_interlace(&(png_ptr->row_info),
  194360. png_ptr->row_buf + 1, png_ptr->pass);
  194361. /* this should always get caught above, but still ... */
  194362. if (!(png_ptr->row_info.width))
  194363. {
  194364. png_write_finish_row(png_ptr);
  194365. return;
  194366. }
  194367. }
  194368. #endif
  194369. /* handle other transformations */
  194370. if (png_ptr->transformations)
  194371. png_do_write_transformations(png_ptr);
  194372. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194373. /* Write filter_method 64 (intrapixel differencing) only if
  194374. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  194375. * 2. Libpng did not write a PNG signature (this filter_method is only
  194376. * used in PNG datastreams that are embedded in MNG datastreams) and
  194377. * 3. The application called png_permit_mng_features with a mask that
  194378. * included PNG_FLAG_MNG_FILTER_64 and
  194379. * 4. The filter_method is 64 and
  194380. * 5. The color_type is RGB or RGBA
  194381. */
  194382. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  194383. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  194384. {
  194385. /* Intrapixel differencing */
  194386. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194387. }
  194388. #endif
  194389. /* Find a filter if necessary, filter the row and write it out. */
  194390. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  194391. if (png_ptr->write_row_fn != NULL)
  194392. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  194393. }
  194394. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  194395. /* Set the automatic flush interval or 0 to turn flushing off */
  194396. void PNGAPI
  194397. png_set_flush(png_structp png_ptr, int nrows)
  194398. {
  194399. png_debug(1, "in png_set_flush\n");
  194400. if (png_ptr == NULL)
  194401. return;
  194402. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  194403. }
  194404. /* flush the current output buffers now */
  194405. void PNGAPI
  194406. png_write_flush(png_structp png_ptr)
  194407. {
  194408. int wrote_IDAT;
  194409. png_debug(1, "in png_write_flush\n");
  194410. if (png_ptr == NULL)
  194411. return;
  194412. /* We have already written out all of the data */
  194413. if (png_ptr->row_number >= png_ptr->num_rows)
  194414. return;
  194415. do
  194416. {
  194417. int ret;
  194418. /* compress the data */
  194419. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  194420. wrote_IDAT = 0;
  194421. /* check for compression errors */
  194422. if (ret != Z_OK)
  194423. {
  194424. if (png_ptr->zstream.msg != NULL)
  194425. png_error(png_ptr, png_ptr->zstream.msg);
  194426. else
  194427. png_error(png_ptr, "zlib error");
  194428. }
  194429. if (!(png_ptr->zstream.avail_out))
  194430. {
  194431. /* write the IDAT and reset the zlib output buffer */
  194432. png_write_IDAT(png_ptr, png_ptr->zbuf,
  194433. png_ptr->zbuf_size);
  194434. png_ptr->zstream.next_out = png_ptr->zbuf;
  194435. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194436. wrote_IDAT = 1;
  194437. }
  194438. } while(wrote_IDAT == 1);
  194439. /* If there is any data left to be output, write it into a new IDAT */
  194440. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  194441. {
  194442. /* write the IDAT and reset the zlib output buffer */
  194443. png_write_IDAT(png_ptr, png_ptr->zbuf,
  194444. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  194445. png_ptr->zstream.next_out = png_ptr->zbuf;
  194446. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194447. }
  194448. png_ptr->flush_rows = 0;
  194449. png_flush(png_ptr);
  194450. }
  194451. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  194452. /* free all memory used by the write */
  194453. void PNGAPI
  194454. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  194455. {
  194456. png_structp png_ptr = NULL;
  194457. png_infop info_ptr = NULL;
  194458. #ifdef PNG_USER_MEM_SUPPORTED
  194459. png_free_ptr free_fn = NULL;
  194460. png_voidp mem_ptr = NULL;
  194461. #endif
  194462. png_debug(1, "in png_destroy_write_struct\n");
  194463. if (png_ptr_ptr != NULL)
  194464. {
  194465. png_ptr = *png_ptr_ptr;
  194466. #ifdef PNG_USER_MEM_SUPPORTED
  194467. free_fn = png_ptr->free_fn;
  194468. mem_ptr = png_ptr->mem_ptr;
  194469. #endif
  194470. }
  194471. if (info_ptr_ptr != NULL)
  194472. info_ptr = *info_ptr_ptr;
  194473. if (info_ptr != NULL)
  194474. {
  194475. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  194476. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  194477. if (png_ptr->num_chunk_list)
  194478. {
  194479. png_free(png_ptr, png_ptr->chunk_list);
  194480. png_ptr->chunk_list=NULL;
  194481. png_ptr->num_chunk_list=0;
  194482. }
  194483. #endif
  194484. #ifdef PNG_USER_MEM_SUPPORTED
  194485. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  194486. (png_voidp)mem_ptr);
  194487. #else
  194488. png_destroy_struct((png_voidp)info_ptr);
  194489. #endif
  194490. *info_ptr_ptr = NULL;
  194491. }
  194492. if (png_ptr != NULL)
  194493. {
  194494. png_write_destroy(png_ptr);
  194495. #ifdef PNG_USER_MEM_SUPPORTED
  194496. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  194497. (png_voidp)mem_ptr);
  194498. #else
  194499. png_destroy_struct((png_voidp)png_ptr);
  194500. #endif
  194501. *png_ptr_ptr = NULL;
  194502. }
  194503. }
  194504. /* Free any memory used in png_ptr struct (old method) */
  194505. void /* PRIVATE */
  194506. png_write_destroy(png_structp png_ptr)
  194507. {
  194508. #ifdef PNG_SETJMP_SUPPORTED
  194509. jmp_buf tmp_jmp; /* save jump buffer */
  194510. #endif
  194511. png_error_ptr error_fn;
  194512. png_error_ptr warning_fn;
  194513. png_voidp error_ptr;
  194514. #ifdef PNG_USER_MEM_SUPPORTED
  194515. png_free_ptr free_fn;
  194516. #endif
  194517. png_debug(1, "in png_write_destroy\n");
  194518. /* free any memory zlib uses */
  194519. deflateEnd(&png_ptr->zstream);
  194520. /* free our memory. png_free checks NULL for us. */
  194521. png_free(png_ptr, png_ptr->zbuf);
  194522. png_free(png_ptr, png_ptr->row_buf);
  194523. png_free(png_ptr, png_ptr->prev_row);
  194524. png_free(png_ptr, png_ptr->sub_row);
  194525. png_free(png_ptr, png_ptr->up_row);
  194526. png_free(png_ptr, png_ptr->avg_row);
  194527. png_free(png_ptr, png_ptr->paeth_row);
  194528. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  194529. png_free(png_ptr, png_ptr->time_buffer);
  194530. #endif
  194531. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  194532. png_free(png_ptr, png_ptr->prev_filters);
  194533. png_free(png_ptr, png_ptr->filter_weights);
  194534. png_free(png_ptr, png_ptr->inv_filter_weights);
  194535. png_free(png_ptr, png_ptr->filter_costs);
  194536. png_free(png_ptr, png_ptr->inv_filter_costs);
  194537. #endif
  194538. #ifdef PNG_SETJMP_SUPPORTED
  194539. /* reset structure */
  194540. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  194541. #endif
  194542. error_fn = png_ptr->error_fn;
  194543. warning_fn = png_ptr->warning_fn;
  194544. error_ptr = png_ptr->error_ptr;
  194545. #ifdef PNG_USER_MEM_SUPPORTED
  194546. free_fn = png_ptr->free_fn;
  194547. #endif
  194548. png_memset(png_ptr, 0, png_sizeof (png_struct));
  194549. png_ptr->error_fn = error_fn;
  194550. png_ptr->warning_fn = warning_fn;
  194551. png_ptr->error_ptr = error_ptr;
  194552. #ifdef PNG_USER_MEM_SUPPORTED
  194553. png_ptr->free_fn = free_fn;
  194554. #endif
  194555. #ifdef PNG_SETJMP_SUPPORTED
  194556. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  194557. #endif
  194558. }
  194559. /* Allow the application to select one or more row filters to use. */
  194560. void PNGAPI
  194561. png_set_filter(png_structp png_ptr, int method, int filters)
  194562. {
  194563. png_debug(1, "in png_set_filter\n");
  194564. if (png_ptr == NULL)
  194565. return;
  194566. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194567. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  194568. (method == PNG_INTRAPIXEL_DIFFERENCING))
  194569. method = PNG_FILTER_TYPE_BASE;
  194570. #endif
  194571. if (method == PNG_FILTER_TYPE_BASE)
  194572. {
  194573. switch (filters & (PNG_ALL_FILTERS | 0x07))
  194574. {
  194575. #ifndef PNG_NO_WRITE_FILTER
  194576. case 5:
  194577. case 6:
  194578. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  194579. #endif /* PNG_NO_WRITE_FILTER */
  194580. case PNG_FILTER_VALUE_NONE:
  194581. png_ptr->do_filter=PNG_FILTER_NONE; break;
  194582. #ifndef PNG_NO_WRITE_FILTER
  194583. case PNG_FILTER_VALUE_SUB:
  194584. png_ptr->do_filter=PNG_FILTER_SUB; break;
  194585. case PNG_FILTER_VALUE_UP:
  194586. png_ptr->do_filter=PNG_FILTER_UP; break;
  194587. case PNG_FILTER_VALUE_AVG:
  194588. png_ptr->do_filter=PNG_FILTER_AVG; break;
  194589. case PNG_FILTER_VALUE_PAETH:
  194590. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  194591. default: png_ptr->do_filter = (png_byte)filters; break;
  194592. #else
  194593. default: png_warning(png_ptr, "Unknown row filter for method 0");
  194594. #endif /* PNG_NO_WRITE_FILTER */
  194595. }
  194596. /* If we have allocated the row_buf, this means we have already started
  194597. * with the image and we should have allocated all of the filter buffers
  194598. * that have been selected. If prev_row isn't already allocated, then
  194599. * it is too late to start using the filters that need it, since we
  194600. * will be missing the data in the previous row. If an application
  194601. * wants to start and stop using particular filters during compression,
  194602. * it should start out with all of the filters, and then add and
  194603. * remove them after the start of compression.
  194604. */
  194605. if (png_ptr->row_buf != NULL)
  194606. {
  194607. #ifndef PNG_NO_WRITE_FILTER
  194608. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  194609. {
  194610. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  194611. (png_ptr->rowbytes + 1));
  194612. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  194613. }
  194614. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  194615. {
  194616. if (png_ptr->prev_row == NULL)
  194617. {
  194618. png_warning(png_ptr, "Can't add Up filter after starting");
  194619. png_ptr->do_filter &= ~PNG_FILTER_UP;
  194620. }
  194621. else
  194622. {
  194623. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  194624. (png_ptr->rowbytes + 1));
  194625. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  194626. }
  194627. }
  194628. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  194629. {
  194630. if (png_ptr->prev_row == NULL)
  194631. {
  194632. png_warning(png_ptr, "Can't add Average filter after starting");
  194633. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  194634. }
  194635. else
  194636. {
  194637. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  194638. (png_ptr->rowbytes + 1));
  194639. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  194640. }
  194641. }
  194642. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  194643. png_ptr->paeth_row == NULL)
  194644. {
  194645. if (png_ptr->prev_row == NULL)
  194646. {
  194647. png_warning(png_ptr, "Can't add Paeth filter after starting");
  194648. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  194649. }
  194650. else
  194651. {
  194652. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  194653. (png_ptr->rowbytes + 1));
  194654. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  194655. }
  194656. }
  194657. if (png_ptr->do_filter == PNG_NO_FILTERS)
  194658. #endif /* PNG_NO_WRITE_FILTER */
  194659. png_ptr->do_filter = PNG_FILTER_NONE;
  194660. }
  194661. }
  194662. else
  194663. png_error(png_ptr, "Unknown custom filter method");
  194664. }
  194665. /* This allows us to influence the way in which libpng chooses the "best"
  194666. * filter for the current scanline. While the "minimum-sum-of-absolute-
  194667. * differences metric is relatively fast and effective, there is some
  194668. * question as to whether it can be improved upon by trying to keep the
  194669. * filtered data going to zlib more consistent, hopefully resulting in
  194670. * better compression.
  194671. */
  194672. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  194673. void PNGAPI
  194674. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  194675. int num_weights, png_doublep filter_weights,
  194676. png_doublep filter_costs)
  194677. {
  194678. int i;
  194679. png_debug(1, "in png_set_filter_heuristics\n");
  194680. if (png_ptr == NULL)
  194681. return;
  194682. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  194683. {
  194684. png_warning(png_ptr, "Unknown filter heuristic method");
  194685. return;
  194686. }
  194687. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  194688. {
  194689. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  194690. }
  194691. if (num_weights < 0 || filter_weights == NULL ||
  194692. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  194693. {
  194694. num_weights = 0;
  194695. }
  194696. png_ptr->num_prev_filters = (png_byte)num_weights;
  194697. png_ptr->heuristic_method = (png_byte)heuristic_method;
  194698. if (num_weights > 0)
  194699. {
  194700. if (png_ptr->prev_filters == NULL)
  194701. {
  194702. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  194703. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  194704. /* To make sure that the weighting starts out fairly */
  194705. for (i = 0; i < num_weights; i++)
  194706. {
  194707. png_ptr->prev_filters[i] = 255;
  194708. }
  194709. }
  194710. if (png_ptr->filter_weights == NULL)
  194711. {
  194712. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  194713. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  194714. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  194715. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  194716. for (i = 0; i < num_weights; i++)
  194717. {
  194718. png_ptr->inv_filter_weights[i] =
  194719. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  194720. }
  194721. }
  194722. for (i = 0; i < num_weights; i++)
  194723. {
  194724. if (filter_weights[i] < 0.0)
  194725. {
  194726. png_ptr->inv_filter_weights[i] =
  194727. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  194728. }
  194729. else
  194730. {
  194731. png_ptr->inv_filter_weights[i] =
  194732. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  194733. png_ptr->filter_weights[i] =
  194734. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  194735. }
  194736. }
  194737. }
  194738. /* If, in the future, there are other filter methods, this would
  194739. * need to be based on png_ptr->filter.
  194740. */
  194741. if (png_ptr->filter_costs == NULL)
  194742. {
  194743. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  194744. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  194745. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  194746. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  194747. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  194748. {
  194749. png_ptr->inv_filter_costs[i] =
  194750. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  194751. }
  194752. }
  194753. /* Here is where we set the relative costs of the different filters. We
  194754. * should take the desired compression level into account when setting
  194755. * the costs, so that Paeth, for instance, has a high relative cost at low
  194756. * compression levels, while it has a lower relative cost at higher
  194757. * compression settings. The filter types are in order of increasing
  194758. * relative cost, so it would be possible to do this with an algorithm.
  194759. */
  194760. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  194761. {
  194762. if (filter_costs == NULL || filter_costs[i] < 0.0)
  194763. {
  194764. png_ptr->inv_filter_costs[i] =
  194765. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  194766. }
  194767. else if (filter_costs[i] >= 1.0)
  194768. {
  194769. png_ptr->inv_filter_costs[i] =
  194770. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  194771. png_ptr->filter_costs[i] =
  194772. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  194773. }
  194774. }
  194775. }
  194776. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  194777. void PNGAPI
  194778. png_set_compression_level(png_structp png_ptr, int level)
  194779. {
  194780. png_debug(1, "in png_set_compression_level\n");
  194781. if (png_ptr == NULL)
  194782. return;
  194783. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  194784. png_ptr->zlib_level = level;
  194785. }
  194786. void PNGAPI
  194787. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  194788. {
  194789. png_debug(1, "in png_set_compression_mem_level\n");
  194790. if (png_ptr == NULL)
  194791. return;
  194792. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  194793. png_ptr->zlib_mem_level = mem_level;
  194794. }
  194795. void PNGAPI
  194796. png_set_compression_strategy(png_structp png_ptr, int strategy)
  194797. {
  194798. png_debug(1, "in png_set_compression_strategy\n");
  194799. if (png_ptr == NULL)
  194800. return;
  194801. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  194802. png_ptr->zlib_strategy = strategy;
  194803. }
  194804. void PNGAPI
  194805. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  194806. {
  194807. if (png_ptr == NULL)
  194808. return;
  194809. if (window_bits > 15)
  194810. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  194811. else if (window_bits < 8)
  194812. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  194813. #ifndef WBITS_8_OK
  194814. /* avoid libpng bug with 256-byte windows */
  194815. if (window_bits == 8)
  194816. {
  194817. png_warning(png_ptr, "Compression window is being reset to 512");
  194818. window_bits=9;
  194819. }
  194820. #endif
  194821. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  194822. png_ptr->zlib_window_bits = window_bits;
  194823. }
  194824. void PNGAPI
  194825. png_set_compression_method(png_structp png_ptr, int method)
  194826. {
  194827. png_debug(1, "in png_set_compression_method\n");
  194828. if (png_ptr == NULL)
  194829. return;
  194830. if (method != 8)
  194831. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  194832. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  194833. png_ptr->zlib_method = method;
  194834. }
  194835. void PNGAPI
  194836. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  194837. {
  194838. if (png_ptr == NULL)
  194839. return;
  194840. png_ptr->write_row_fn = write_row_fn;
  194841. }
  194842. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  194843. void PNGAPI
  194844. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  194845. write_user_transform_fn)
  194846. {
  194847. png_debug(1, "in png_set_write_user_transform_fn\n");
  194848. if (png_ptr == NULL)
  194849. return;
  194850. png_ptr->transformations |= PNG_USER_TRANSFORM;
  194851. png_ptr->write_user_transform_fn = write_user_transform_fn;
  194852. }
  194853. #endif
  194854. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  194855. void PNGAPI
  194856. png_write_png(png_structp png_ptr, png_infop info_ptr,
  194857. int transforms, voidp params)
  194858. {
  194859. if (png_ptr == NULL || info_ptr == NULL)
  194860. return;
  194861. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194862. /* invert the alpha channel from opacity to transparency */
  194863. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  194864. png_set_invert_alpha(png_ptr);
  194865. #endif
  194866. /* Write the file header information. */
  194867. png_write_info(png_ptr, info_ptr);
  194868. /* ------ these transformations don't touch the info structure ------- */
  194869. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  194870. /* invert monochrome pixels */
  194871. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  194872. png_set_invert_mono(png_ptr);
  194873. #endif
  194874. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  194875. /* Shift the pixels up to a legal bit depth and fill in
  194876. * as appropriate to correctly scale the image.
  194877. */
  194878. if ((transforms & PNG_TRANSFORM_SHIFT)
  194879. && (info_ptr->valid & PNG_INFO_sBIT))
  194880. png_set_shift(png_ptr, &info_ptr->sig_bit);
  194881. #endif
  194882. #if defined(PNG_WRITE_PACK_SUPPORTED)
  194883. /* pack pixels into bytes */
  194884. if (transforms & PNG_TRANSFORM_PACKING)
  194885. png_set_packing(png_ptr);
  194886. #endif
  194887. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  194888. /* swap location of alpha bytes from ARGB to RGBA */
  194889. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  194890. png_set_swap_alpha(png_ptr);
  194891. #endif
  194892. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  194893. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  194894. * RGB (4 channels -> 3 channels). The second parameter is not used.
  194895. */
  194896. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  194897. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  194898. #endif
  194899. #if defined(PNG_WRITE_BGR_SUPPORTED)
  194900. /* flip BGR pixels to RGB */
  194901. if (transforms & PNG_TRANSFORM_BGR)
  194902. png_set_bgr(png_ptr);
  194903. #endif
  194904. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  194905. /* swap bytes of 16-bit files to most significant byte first */
  194906. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  194907. png_set_swap(png_ptr);
  194908. #endif
  194909. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  194910. /* swap bits of 1, 2, 4 bit packed pixel formats */
  194911. if (transforms & PNG_TRANSFORM_PACKSWAP)
  194912. png_set_packswap(png_ptr);
  194913. #endif
  194914. /* ----------------------- end of transformations ------------------- */
  194915. /* write the bits */
  194916. if (info_ptr->valid & PNG_INFO_IDAT)
  194917. png_write_image(png_ptr, info_ptr->row_pointers);
  194918. /* It is REQUIRED to call this to finish writing the rest of the file */
  194919. png_write_end(png_ptr, info_ptr);
  194920. transforms = transforms; /* quiet compiler warnings */
  194921. params = params;
  194922. }
  194923. #endif
  194924. #endif /* PNG_WRITE_SUPPORTED */
  194925. /********* End of inlined file: pngwrite.c *********/
  194926. /********* Start of inlined file: pngwtran.c *********/
  194927. /* pngwtran.c - transforms the data in a row for PNG writers
  194928. *
  194929. * Last changed in libpng 1.2.9 April 14, 2006
  194930. * For conditions of distribution and use, see copyright notice in png.h
  194931. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  194932. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194933. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194934. */
  194935. #define PNG_INTERNAL
  194936. #ifdef PNG_WRITE_SUPPORTED
  194937. /* Transform the data according to the user's wishes. The order of
  194938. * transformations is significant.
  194939. */
  194940. void /* PRIVATE */
  194941. png_do_write_transformations(png_structp png_ptr)
  194942. {
  194943. png_debug(1, "in png_do_write_transformations\n");
  194944. if (png_ptr == NULL)
  194945. return;
  194946. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  194947. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  194948. if(png_ptr->write_user_transform_fn != NULL)
  194949. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  194950. (png_ptr, /* png_ptr */
  194951. &(png_ptr->row_info), /* row_info: */
  194952. /* png_uint_32 width; width of row */
  194953. /* png_uint_32 rowbytes; number of bytes in row */
  194954. /* png_byte color_type; color type of pixels */
  194955. /* png_byte bit_depth; bit depth of samples */
  194956. /* png_byte channels; number of channels (1-4) */
  194957. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  194958. png_ptr->row_buf + 1); /* start of pixel data for row */
  194959. #endif
  194960. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  194961. if (png_ptr->transformations & PNG_FILLER)
  194962. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  194963. png_ptr->flags);
  194964. #endif
  194965. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  194966. if (png_ptr->transformations & PNG_PACKSWAP)
  194967. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194968. #endif
  194969. #if defined(PNG_WRITE_PACK_SUPPORTED)
  194970. if (png_ptr->transformations & PNG_PACK)
  194971. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  194972. (png_uint_32)png_ptr->bit_depth);
  194973. #endif
  194974. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  194975. if (png_ptr->transformations & PNG_SWAP_BYTES)
  194976. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194977. #endif
  194978. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  194979. if (png_ptr->transformations & PNG_SHIFT)
  194980. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  194981. &(png_ptr->shift));
  194982. #endif
  194983. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  194984. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  194985. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194986. #endif
  194987. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194988. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  194989. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194990. #endif
  194991. #if defined(PNG_WRITE_BGR_SUPPORTED)
  194992. if (png_ptr->transformations & PNG_BGR)
  194993. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194994. #endif
  194995. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  194996. if (png_ptr->transformations & PNG_INVERT_MONO)
  194997. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194998. #endif
  194999. }
  195000. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195001. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  195002. * row_info bit depth should be 8 (one pixel per byte). The channels
  195003. * should be 1 (this only happens on grayscale and paletted images).
  195004. */
  195005. void /* PRIVATE */
  195006. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  195007. {
  195008. png_debug(1, "in png_do_pack\n");
  195009. if (row_info->bit_depth == 8 &&
  195010. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195011. row != NULL && row_info != NULL &&
  195012. #endif
  195013. row_info->channels == 1)
  195014. {
  195015. switch ((int)bit_depth)
  195016. {
  195017. case 1:
  195018. {
  195019. png_bytep sp, dp;
  195020. int mask, v;
  195021. png_uint_32 i;
  195022. png_uint_32 row_width = row_info->width;
  195023. sp = row;
  195024. dp = row;
  195025. mask = 0x80;
  195026. v = 0;
  195027. for (i = 0; i < row_width; i++)
  195028. {
  195029. if (*sp != 0)
  195030. v |= mask;
  195031. sp++;
  195032. if (mask > 1)
  195033. mask >>= 1;
  195034. else
  195035. {
  195036. mask = 0x80;
  195037. *dp = (png_byte)v;
  195038. dp++;
  195039. v = 0;
  195040. }
  195041. }
  195042. if (mask != 0x80)
  195043. *dp = (png_byte)v;
  195044. break;
  195045. }
  195046. case 2:
  195047. {
  195048. png_bytep sp, dp;
  195049. int shift, v;
  195050. png_uint_32 i;
  195051. png_uint_32 row_width = row_info->width;
  195052. sp = row;
  195053. dp = row;
  195054. shift = 6;
  195055. v = 0;
  195056. for (i = 0; i < row_width; i++)
  195057. {
  195058. png_byte value;
  195059. value = (png_byte)(*sp & 0x03);
  195060. v |= (value << shift);
  195061. if (shift == 0)
  195062. {
  195063. shift = 6;
  195064. *dp = (png_byte)v;
  195065. dp++;
  195066. v = 0;
  195067. }
  195068. else
  195069. shift -= 2;
  195070. sp++;
  195071. }
  195072. if (shift != 6)
  195073. *dp = (png_byte)v;
  195074. break;
  195075. }
  195076. case 4:
  195077. {
  195078. png_bytep sp, dp;
  195079. int shift, v;
  195080. png_uint_32 i;
  195081. png_uint_32 row_width = row_info->width;
  195082. sp = row;
  195083. dp = row;
  195084. shift = 4;
  195085. v = 0;
  195086. for (i = 0; i < row_width; i++)
  195087. {
  195088. png_byte value;
  195089. value = (png_byte)(*sp & 0x0f);
  195090. v |= (value << shift);
  195091. if (shift == 0)
  195092. {
  195093. shift = 4;
  195094. *dp = (png_byte)v;
  195095. dp++;
  195096. v = 0;
  195097. }
  195098. else
  195099. shift -= 4;
  195100. sp++;
  195101. }
  195102. if (shift != 4)
  195103. *dp = (png_byte)v;
  195104. break;
  195105. }
  195106. }
  195107. row_info->bit_depth = (png_byte)bit_depth;
  195108. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  195109. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  195110. row_info->width);
  195111. }
  195112. }
  195113. #endif
  195114. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195115. /* Shift pixel values to take advantage of whole range. Pass the
  195116. * true number of bits in bit_depth. The row should be packed
  195117. * according to row_info->bit_depth. Thus, if you had a row of
  195118. * bit depth 4, but the pixels only had values from 0 to 7, you
  195119. * would pass 3 as bit_depth, and this routine would translate the
  195120. * data to 0 to 15.
  195121. */
  195122. void /* PRIVATE */
  195123. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  195124. {
  195125. png_debug(1, "in png_do_shift\n");
  195126. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195127. if (row != NULL && row_info != NULL &&
  195128. #else
  195129. if (
  195130. #endif
  195131. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  195132. {
  195133. int shift_start[4], shift_dec[4];
  195134. int channels = 0;
  195135. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  195136. {
  195137. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  195138. shift_dec[channels] = bit_depth->red;
  195139. channels++;
  195140. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  195141. shift_dec[channels] = bit_depth->green;
  195142. channels++;
  195143. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  195144. shift_dec[channels] = bit_depth->blue;
  195145. channels++;
  195146. }
  195147. else
  195148. {
  195149. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  195150. shift_dec[channels] = bit_depth->gray;
  195151. channels++;
  195152. }
  195153. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  195154. {
  195155. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  195156. shift_dec[channels] = bit_depth->alpha;
  195157. channels++;
  195158. }
  195159. /* with low row depths, could only be grayscale, so one channel */
  195160. if (row_info->bit_depth < 8)
  195161. {
  195162. png_bytep bp = row;
  195163. png_uint_32 i;
  195164. png_byte mask;
  195165. png_uint_32 row_bytes = row_info->rowbytes;
  195166. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  195167. mask = 0x55;
  195168. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  195169. mask = 0x11;
  195170. else
  195171. mask = 0xff;
  195172. for (i = 0; i < row_bytes; i++, bp++)
  195173. {
  195174. png_uint_16 v;
  195175. int j;
  195176. v = *bp;
  195177. *bp = 0;
  195178. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  195179. {
  195180. if (j > 0)
  195181. *bp |= (png_byte)((v << j) & 0xff);
  195182. else
  195183. *bp |= (png_byte)((v >> (-j)) & mask);
  195184. }
  195185. }
  195186. }
  195187. else if (row_info->bit_depth == 8)
  195188. {
  195189. png_bytep bp = row;
  195190. png_uint_32 i;
  195191. png_uint_32 istop = channels * row_info->width;
  195192. for (i = 0; i < istop; i++, bp++)
  195193. {
  195194. png_uint_16 v;
  195195. int j;
  195196. int c = (int)(i%channels);
  195197. v = *bp;
  195198. *bp = 0;
  195199. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  195200. {
  195201. if (j > 0)
  195202. *bp |= (png_byte)((v << j) & 0xff);
  195203. else
  195204. *bp |= (png_byte)((v >> (-j)) & 0xff);
  195205. }
  195206. }
  195207. }
  195208. else
  195209. {
  195210. png_bytep bp;
  195211. png_uint_32 i;
  195212. png_uint_32 istop = channels * row_info->width;
  195213. for (bp = row, i = 0; i < istop; i++)
  195214. {
  195215. int c = (int)(i%channels);
  195216. png_uint_16 value, v;
  195217. int j;
  195218. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  195219. value = 0;
  195220. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  195221. {
  195222. if (j > 0)
  195223. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  195224. else
  195225. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  195226. }
  195227. *bp++ = (png_byte)(value >> 8);
  195228. *bp++ = (png_byte)(value & 0xff);
  195229. }
  195230. }
  195231. }
  195232. }
  195233. #endif
  195234. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195235. void /* PRIVATE */
  195236. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  195237. {
  195238. png_debug(1, "in png_do_write_swap_alpha\n");
  195239. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195240. if (row != NULL && row_info != NULL)
  195241. #endif
  195242. {
  195243. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195244. {
  195245. /* This converts from ARGB to RGBA */
  195246. if (row_info->bit_depth == 8)
  195247. {
  195248. png_bytep sp, dp;
  195249. png_uint_32 i;
  195250. png_uint_32 row_width = row_info->width;
  195251. for (i = 0, sp = dp = row; i < row_width; i++)
  195252. {
  195253. png_byte save = *(sp++);
  195254. *(dp++) = *(sp++);
  195255. *(dp++) = *(sp++);
  195256. *(dp++) = *(sp++);
  195257. *(dp++) = save;
  195258. }
  195259. }
  195260. /* This converts from AARRGGBB to RRGGBBAA */
  195261. else
  195262. {
  195263. png_bytep sp, dp;
  195264. png_uint_32 i;
  195265. png_uint_32 row_width = row_info->width;
  195266. for (i = 0, sp = dp = row; i < row_width; i++)
  195267. {
  195268. png_byte save[2];
  195269. save[0] = *(sp++);
  195270. save[1] = *(sp++);
  195271. *(dp++) = *(sp++);
  195272. *(dp++) = *(sp++);
  195273. *(dp++) = *(sp++);
  195274. *(dp++) = *(sp++);
  195275. *(dp++) = *(sp++);
  195276. *(dp++) = *(sp++);
  195277. *(dp++) = save[0];
  195278. *(dp++) = save[1];
  195279. }
  195280. }
  195281. }
  195282. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  195283. {
  195284. /* This converts from AG to GA */
  195285. if (row_info->bit_depth == 8)
  195286. {
  195287. png_bytep sp, dp;
  195288. png_uint_32 i;
  195289. png_uint_32 row_width = row_info->width;
  195290. for (i = 0, sp = dp = row; i < row_width; i++)
  195291. {
  195292. png_byte save = *(sp++);
  195293. *(dp++) = *(sp++);
  195294. *(dp++) = save;
  195295. }
  195296. }
  195297. /* This converts from AAGG to GGAA */
  195298. else
  195299. {
  195300. png_bytep sp, dp;
  195301. png_uint_32 i;
  195302. png_uint_32 row_width = row_info->width;
  195303. for (i = 0, sp = dp = row; i < row_width; i++)
  195304. {
  195305. png_byte save[2];
  195306. save[0] = *(sp++);
  195307. save[1] = *(sp++);
  195308. *(dp++) = *(sp++);
  195309. *(dp++) = *(sp++);
  195310. *(dp++) = save[0];
  195311. *(dp++) = save[1];
  195312. }
  195313. }
  195314. }
  195315. }
  195316. }
  195317. #endif
  195318. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195319. void /* PRIVATE */
  195320. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  195321. {
  195322. png_debug(1, "in png_do_write_invert_alpha\n");
  195323. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195324. if (row != NULL && row_info != NULL)
  195325. #endif
  195326. {
  195327. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195328. {
  195329. /* This inverts the alpha channel in RGBA */
  195330. if (row_info->bit_depth == 8)
  195331. {
  195332. png_bytep sp, dp;
  195333. png_uint_32 i;
  195334. png_uint_32 row_width = row_info->width;
  195335. for (i = 0, sp = dp = row; i < row_width; i++)
  195336. {
  195337. /* does nothing
  195338. *(dp++) = *(sp++);
  195339. *(dp++) = *(sp++);
  195340. *(dp++) = *(sp++);
  195341. */
  195342. sp+=3; dp = sp;
  195343. *(dp++) = (png_byte)(255 - *(sp++));
  195344. }
  195345. }
  195346. /* This inverts the alpha channel in RRGGBBAA */
  195347. else
  195348. {
  195349. png_bytep sp, dp;
  195350. png_uint_32 i;
  195351. png_uint_32 row_width = row_info->width;
  195352. for (i = 0, sp = dp = row; i < row_width; i++)
  195353. {
  195354. /* does nothing
  195355. *(dp++) = *(sp++);
  195356. *(dp++) = *(sp++);
  195357. *(dp++) = *(sp++);
  195358. *(dp++) = *(sp++);
  195359. *(dp++) = *(sp++);
  195360. *(dp++) = *(sp++);
  195361. */
  195362. sp+=6; dp = sp;
  195363. *(dp++) = (png_byte)(255 - *(sp++));
  195364. *(dp++) = (png_byte)(255 - *(sp++));
  195365. }
  195366. }
  195367. }
  195368. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  195369. {
  195370. /* This inverts the alpha channel in GA */
  195371. if (row_info->bit_depth == 8)
  195372. {
  195373. png_bytep sp, dp;
  195374. png_uint_32 i;
  195375. png_uint_32 row_width = row_info->width;
  195376. for (i = 0, sp = dp = row; i < row_width; i++)
  195377. {
  195378. *(dp++) = *(sp++);
  195379. *(dp++) = (png_byte)(255 - *(sp++));
  195380. }
  195381. }
  195382. /* This inverts the alpha channel in GGAA */
  195383. else
  195384. {
  195385. png_bytep sp, dp;
  195386. png_uint_32 i;
  195387. png_uint_32 row_width = row_info->width;
  195388. for (i = 0, sp = dp = row; i < row_width; i++)
  195389. {
  195390. /* does nothing
  195391. *(dp++) = *(sp++);
  195392. *(dp++) = *(sp++);
  195393. */
  195394. sp+=2; dp = sp;
  195395. *(dp++) = (png_byte)(255 - *(sp++));
  195396. *(dp++) = (png_byte)(255 - *(sp++));
  195397. }
  195398. }
  195399. }
  195400. }
  195401. }
  195402. #endif
  195403. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195404. /* undoes intrapixel differencing */
  195405. void /* PRIVATE */
  195406. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  195407. {
  195408. png_debug(1, "in png_do_write_intrapixel\n");
  195409. if (
  195410. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195411. row != NULL && row_info != NULL &&
  195412. #endif
  195413. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  195414. {
  195415. int bytes_per_pixel;
  195416. png_uint_32 row_width = row_info->width;
  195417. if (row_info->bit_depth == 8)
  195418. {
  195419. png_bytep rp;
  195420. png_uint_32 i;
  195421. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  195422. bytes_per_pixel = 3;
  195423. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195424. bytes_per_pixel = 4;
  195425. else
  195426. return;
  195427. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  195428. {
  195429. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  195430. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  195431. }
  195432. }
  195433. else if (row_info->bit_depth == 16)
  195434. {
  195435. png_bytep rp;
  195436. png_uint_32 i;
  195437. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  195438. bytes_per_pixel = 6;
  195439. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195440. bytes_per_pixel = 8;
  195441. else
  195442. return;
  195443. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  195444. {
  195445. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  195446. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  195447. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  195448. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  195449. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  195450. *(rp ) = (png_byte)((red >> 8) & 0xff);
  195451. *(rp+1) = (png_byte)(red & 0xff);
  195452. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  195453. *(rp+5) = (png_byte)(blue & 0xff);
  195454. }
  195455. }
  195456. }
  195457. }
  195458. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  195459. #endif /* PNG_WRITE_SUPPORTED */
  195460. /********* End of inlined file: pngwtran.c *********/
  195461. /********* Start of inlined file: pngwutil.c *********/
  195462. /* pngwutil.c - utilities to write a PNG file
  195463. *
  195464. * Last changed in libpng 1.2.20 Septhember 3, 2007
  195465. * For conditions of distribution and use, see copyright notice in png.h
  195466. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  195467. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195468. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195469. */
  195470. #define PNG_INTERNAL
  195471. #ifdef PNG_WRITE_SUPPORTED
  195472. /* Place a 32-bit number into a buffer in PNG byte order. We work
  195473. * with unsigned numbers for convenience, although one supported
  195474. * ancillary chunk uses signed (two's complement) numbers.
  195475. */
  195476. void PNGAPI
  195477. png_save_uint_32(png_bytep buf, png_uint_32 i)
  195478. {
  195479. buf[0] = (png_byte)((i >> 24) & 0xff);
  195480. buf[1] = (png_byte)((i >> 16) & 0xff);
  195481. buf[2] = (png_byte)((i >> 8) & 0xff);
  195482. buf[3] = (png_byte)(i & 0xff);
  195483. }
  195484. /* The png_save_int_32 function assumes integers are stored in two's
  195485. * complement format. If this isn't the case, then this routine needs to
  195486. * be modified to write data in two's complement format.
  195487. */
  195488. void PNGAPI
  195489. png_save_int_32(png_bytep buf, png_int_32 i)
  195490. {
  195491. buf[0] = (png_byte)((i >> 24) & 0xff);
  195492. buf[1] = (png_byte)((i >> 16) & 0xff);
  195493. buf[2] = (png_byte)((i >> 8) & 0xff);
  195494. buf[3] = (png_byte)(i & 0xff);
  195495. }
  195496. /* Place a 16-bit number into a buffer in PNG byte order.
  195497. * The parameter is declared unsigned int, not png_uint_16,
  195498. * just to avoid potential problems on pre-ANSI C compilers.
  195499. */
  195500. void PNGAPI
  195501. png_save_uint_16(png_bytep buf, unsigned int i)
  195502. {
  195503. buf[0] = (png_byte)((i >> 8) & 0xff);
  195504. buf[1] = (png_byte)(i & 0xff);
  195505. }
  195506. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  195507. * representing the chunk name. The array must be at least 4 bytes in
  195508. * length, and does not need to be null terminated. To be safe, pass the
  195509. * pre-defined chunk names here, and if you need a new one, define it
  195510. * where the others are defined. The length is the length of the data.
  195511. * All the data must be present. If that is not possible, use the
  195512. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  195513. * functions instead.
  195514. */
  195515. void PNGAPI
  195516. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  195517. png_bytep data, png_size_t length)
  195518. {
  195519. if(png_ptr == NULL) return;
  195520. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  195521. png_write_chunk_data(png_ptr, data, length);
  195522. png_write_chunk_end(png_ptr);
  195523. }
  195524. /* Write the start of a PNG chunk. The type is the chunk type.
  195525. * The total_length is the sum of the lengths of all the data you will be
  195526. * passing in png_write_chunk_data().
  195527. */
  195528. void PNGAPI
  195529. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  195530. png_uint_32 length)
  195531. {
  195532. png_byte buf[4];
  195533. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  195534. if(png_ptr == NULL) return;
  195535. /* write the length */
  195536. png_save_uint_32(buf, length);
  195537. png_write_data(png_ptr, buf, (png_size_t)4);
  195538. /* write the chunk name */
  195539. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  195540. /* reset the crc and run it over the chunk name */
  195541. png_reset_crc(png_ptr);
  195542. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  195543. }
  195544. /* Write the data of a PNG chunk started with png_write_chunk_start().
  195545. * Note that multiple calls to this function are allowed, and that the
  195546. * sum of the lengths from these calls *must* add up to the total_length
  195547. * given to png_write_chunk_start().
  195548. */
  195549. void PNGAPI
  195550. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  195551. {
  195552. /* write the data, and run the CRC over it */
  195553. if(png_ptr == NULL) return;
  195554. if (data != NULL && length > 0)
  195555. {
  195556. png_calculate_crc(png_ptr, data, length);
  195557. png_write_data(png_ptr, data, length);
  195558. }
  195559. }
  195560. /* Finish a chunk started with png_write_chunk_start(). */
  195561. void PNGAPI
  195562. png_write_chunk_end(png_structp png_ptr)
  195563. {
  195564. png_byte buf[4];
  195565. if(png_ptr == NULL) return;
  195566. /* write the crc */
  195567. png_save_uint_32(buf, png_ptr->crc);
  195568. png_write_data(png_ptr, buf, (png_size_t)4);
  195569. }
  195570. /* Simple function to write the signature. If we have already written
  195571. * the magic bytes of the signature, or more likely, the PNG stream is
  195572. * being embedded into another stream and doesn't need its own signature,
  195573. * we should call png_set_sig_bytes() to tell libpng how many of the
  195574. * bytes have already been written.
  195575. */
  195576. void /* PRIVATE */
  195577. png_write_sig(png_structp png_ptr)
  195578. {
  195579. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  195580. /* write the rest of the 8 byte signature */
  195581. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  195582. (png_size_t)8 - png_ptr->sig_bytes);
  195583. if(png_ptr->sig_bytes < 3)
  195584. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  195585. }
  195586. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  195587. /*
  195588. * This pair of functions encapsulates the operation of (a) compressing a
  195589. * text string, and (b) issuing it later as a series of chunk data writes.
  195590. * The compression_state structure is shared context for these functions
  195591. * set up by the caller in order to make the whole mess thread-safe.
  195592. */
  195593. typedef struct
  195594. {
  195595. char *input; /* the uncompressed input data */
  195596. int input_len; /* its length */
  195597. int num_output_ptr; /* number of output pointers used */
  195598. int max_output_ptr; /* size of output_ptr */
  195599. png_charpp output_ptr; /* array of pointers to output */
  195600. } compression_state;
  195601. /* compress given text into storage in the png_ptr structure */
  195602. static int /* PRIVATE */
  195603. png_text_compress(png_structp png_ptr,
  195604. png_charp text, png_size_t text_len, int compression,
  195605. compression_state *comp)
  195606. {
  195607. int ret;
  195608. comp->num_output_ptr = 0;
  195609. comp->max_output_ptr = 0;
  195610. comp->output_ptr = NULL;
  195611. comp->input = NULL;
  195612. comp->input_len = 0;
  195613. /* we may just want to pass the text right through */
  195614. if (compression == PNG_TEXT_COMPRESSION_NONE)
  195615. {
  195616. comp->input = text;
  195617. comp->input_len = text_len;
  195618. return((int)text_len);
  195619. }
  195620. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  195621. {
  195622. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  195623. char msg[50];
  195624. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  195625. png_warning(png_ptr, msg);
  195626. #else
  195627. png_warning(png_ptr, "Unknown compression type");
  195628. #endif
  195629. }
  195630. /* We can't write the chunk until we find out how much data we have,
  195631. * which means we need to run the compressor first and save the
  195632. * output. This shouldn't be a problem, as the vast majority of
  195633. * comments should be reasonable, but we will set up an array of
  195634. * malloc'd pointers to be sure.
  195635. *
  195636. * If we knew the application was well behaved, we could simplify this
  195637. * greatly by assuming we can always malloc an output buffer large
  195638. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  195639. * and malloc this directly. The only time this would be a bad idea is
  195640. * if we can't malloc more than 64K and we have 64K of random input
  195641. * data, or if the input string is incredibly large (although this
  195642. * wouldn't cause a failure, just a slowdown due to swapping).
  195643. */
  195644. /* set up the compression buffers */
  195645. png_ptr->zstream.avail_in = (uInt)text_len;
  195646. png_ptr->zstream.next_in = (Bytef *)text;
  195647. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195648. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  195649. /* this is the same compression loop as in png_write_row() */
  195650. do
  195651. {
  195652. /* compress the data */
  195653. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  195654. if (ret != Z_OK)
  195655. {
  195656. /* error */
  195657. if (png_ptr->zstream.msg != NULL)
  195658. png_error(png_ptr, png_ptr->zstream.msg);
  195659. else
  195660. png_error(png_ptr, "zlib error");
  195661. }
  195662. /* check to see if we need more room */
  195663. if (!(png_ptr->zstream.avail_out))
  195664. {
  195665. /* make sure the output array has room */
  195666. if (comp->num_output_ptr >= comp->max_output_ptr)
  195667. {
  195668. int old_max;
  195669. old_max = comp->max_output_ptr;
  195670. comp->max_output_ptr = comp->num_output_ptr + 4;
  195671. if (comp->output_ptr != NULL)
  195672. {
  195673. png_charpp old_ptr;
  195674. old_ptr = comp->output_ptr;
  195675. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  195676. (png_uint_32)(comp->max_output_ptr *
  195677. png_sizeof (png_charpp)));
  195678. png_memcpy(comp->output_ptr, old_ptr, old_max
  195679. * png_sizeof (png_charp));
  195680. png_free(png_ptr, old_ptr);
  195681. }
  195682. else
  195683. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  195684. (png_uint_32)(comp->max_output_ptr *
  195685. png_sizeof (png_charp)));
  195686. }
  195687. /* save the data */
  195688. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  195689. (png_uint_32)png_ptr->zbuf_size);
  195690. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  195691. png_ptr->zbuf_size);
  195692. comp->num_output_ptr++;
  195693. /* and reset the buffer */
  195694. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195695. png_ptr->zstream.next_out = png_ptr->zbuf;
  195696. }
  195697. /* continue until we don't have any more to compress */
  195698. } while (png_ptr->zstream.avail_in);
  195699. /* finish the compression */
  195700. do
  195701. {
  195702. /* tell zlib we are finished */
  195703. ret = deflate(&png_ptr->zstream, Z_FINISH);
  195704. if (ret == Z_OK)
  195705. {
  195706. /* check to see if we need more room */
  195707. if (!(png_ptr->zstream.avail_out))
  195708. {
  195709. /* check to make sure our output array has room */
  195710. if (comp->num_output_ptr >= comp->max_output_ptr)
  195711. {
  195712. int old_max;
  195713. old_max = comp->max_output_ptr;
  195714. comp->max_output_ptr = comp->num_output_ptr + 4;
  195715. if (comp->output_ptr != NULL)
  195716. {
  195717. png_charpp old_ptr;
  195718. old_ptr = comp->output_ptr;
  195719. /* This could be optimized to realloc() */
  195720. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  195721. (png_uint_32)(comp->max_output_ptr *
  195722. png_sizeof (png_charpp)));
  195723. png_memcpy(comp->output_ptr, old_ptr,
  195724. old_max * png_sizeof (png_charp));
  195725. png_free(png_ptr, old_ptr);
  195726. }
  195727. else
  195728. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  195729. (png_uint_32)(comp->max_output_ptr *
  195730. png_sizeof (png_charp)));
  195731. }
  195732. /* save off the data */
  195733. comp->output_ptr[comp->num_output_ptr] =
  195734. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  195735. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  195736. png_ptr->zbuf_size);
  195737. comp->num_output_ptr++;
  195738. /* and reset the buffer pointers */
  195739. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195740. png_ptr->zstream.next_out = png_ptr->zbuf;
  195741. }
  195742. }
  195743. else if (ret != Z_STREAM_END)
  195744. {
  195745. /* we got an error */
  195746. if (png_ptr->zstream.msg != NULL)
  195747. png_error(png_ptr, png_ptr->zstream.msg);
  195748. else
  195749. png_error(png_ptr, "zlib error");
  195750. }
  195751. } while (ret != Z_STREAM_END);
  195752. /* text length is number of buffers plus last buffer */
  195753. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  195754. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  195755. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  195756. return((int)text_len);
  195757. }
  195758. /* ship the compressed text out via chunk writes */
  195759. static void /* PRIVATE */
  195760. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  195761. {
  195762. int i;
  195763. /* handle the no-compression case */
  195764. if (comp->input)
  195765. {
  195766. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  195767. (png_size_t)comp->input_len);
  195768. return;
  195769. }
  195770. /* write saved output buffers, if any */
  195771. for (i = 0; i < comp->num_output_ptr; i++)
  195772. {
  195773. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  195774. png_ptr->zbuf_size);
  195775. png_free(png_ptr, comp->output_ptr[i]);
  195776. comp->output_ptr[i]=NULL;
  195777. }
  195778. if (comp->max_output_ptr != 0)
  195779. png_free(png_ptr, comp->output_ptr);
  195780. comp->output_ptr=NULL;
  195781. /* write anything left in zbuf */
  195782. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  195783. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  195784. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  195785. /* reset zlib for another zTXt/iTXt or image data */
  195786. deflateReset(&png_ptr->zstream);
  195787. png_ptr->zstream.data_type = Z_BINARY;
  195788. }
  195789. #endif
  195790. /* Write the IHDR chunk, and update the png_struct with the necessary
  195791. * information. Note that the rest of this code depends upon this
  195792. * information being correct.
  195793. */
  195794. void /* PRIVATE */
  195795. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  195796. int bit_depth, int color_type, int compression_type, int filter_type,
  195797. int interlace_type)
  195798. {
  195799. #ifdef PNG_USE_LOCAL_ARRAYS
  195800. PNG_IHDR;
  195801. #endif
  195802. png_byte buf[13]; /* buffer to store the IHDR info */
  195803. png_debug(1, "in png_write_IHDR\n");
  195804. /* Check that we have valid input data from the application info */
  195805. switch (color_type)
  195806. {
  195807. case PNG_COLOR_TYPE_GRAY:
  195808. switch (bit_depth)
  195809. {
  195810. case 1:
  195811. case 2:
  195812. case 4:
  195813. case 8:
  195814. case 16: png_ptr->channels = 1; break;
  195815. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  195816. }
  195817. break;
  195818. case PNG_COLOR_TYPE_RGB:
  195819. if (bit_depth != 8 && bit_depth != 16)
  195820. png_error(png_ptr, "Invalid bit depth for RGB image");
  195821. png_ptr->channels = 3;
  195822. break;
  195823. case PNG_COLOR_TYPE_PALETTE:
  195824. switch (bit_depth)
  195825. {
  195826. case 1:
  195827. case 2:
  195828. case 4:
  195829. case 8: png_ptr->channels = 1; break;
  195830. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  195831. }
  195832. break;
  195833. case PNG_COLOR_TYPE_GRAY_ALPHA:
  195834. if (bit_depth != 8 && bit_depth != 16)
  195835. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  195836. png_ptr->channels = 2;
  195837. break;
  195838. case PNG_COLOR_TYPE_RGB_ALPHA:
  195839. if (bit_depth != 8 && bit_depth != 16)
  195840. png_error(png_ptr, "Invalid bit depth for RGBA image");
  195841. png_ptr->channels = 4;
  195842. break;
  195843. default:
  195844. png_error(png_ptr, "Invalid image color type specified");
  195845. }
  195846. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  195847. {
  195848. png_warning(png_ptr, "Invalid compression type specified");
  195849. compression_type = PNG_COMPRESSION_TYPE_BASE;
  195850. }
  195851. /* Write filter_method 64 (intrapixel differencing) only if
  195852. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  195853. * 2. Libpng did not write a PNG signature (this filter_method is only
  195854. * used in PNG datastreams that are embedded in MNG datastreams) and
  195855. * 3. The application called png_permit_mng_features with a mask that
  195856. * included PNG_FLAG_MNG_FILTER_64 and
  195857. * 4. The filter_method is 64 and
  195858. * 5. The color_type is RGB or RGBA
  195859. */
  195860. if (
  195861. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195862. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  195863. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  195864. (color_type == PNG_COLOR_TYPE_RGB ||
  195865. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  195866. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  195867. #endif
  195868. filter_type != PNG_FILTER_TYPE_BASE)
  195869. {
  195870. png_warning(png_ptr, "Invalid filter type specified");
  195871. filter_type = PNG_FILTER_TYPE_BASE;
  195872. }
  195873. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  195874. if (interlace_type != PNG_INTERLACE_NONE &&
  195875. interlace_type != PNG_INTERLACE_ADAM7)
  195876. {
  195877. png_warning(png_ptr, "Invalid interlace type specified");
  195878. interlace_type = PNG_INTERLACE_ADAM7;
  195879. }
  195880. #else
  195881. interlace_type=PNG_INTERLACE_NONE;
  195882. #endif
  195883. /* save off the relevent information */
  195884. png_ptr->bit_depth = (png_byte)bit_depth;
  195885. png_ptr->color_type = (png_byte)color_type;
  195886. png_ptr->interlaced = (png_byte)interlace_type;
  195887. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195888. png_ptr->filter_type = (png_byte)filter_type;
  195889. #endif
  195890. png_ptr->compression_type = (png_byte)compression_type;
  195891. png_ptr->width = width;
  195892. png_ptr->height = height;
  195893. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  195894. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  195895. /* set the usr info, so any transformations can modify it */
  195896. png_ptr->usr_width = png_ptr->width;
  195897. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  195898. png_ptr->usr_channels = png_ptr->channels;
  195899. /* pack the header information into the buffer */
  195900. png_save_uint_32(buf, width);
  195901. png_save_uint_32(buf + 4, height);
  195902. buf[8] = (png_byte)bit_depth;
  195903. buf[9] = (png_byte)color_type;
  195904. buf[10] = (png_byte)compression_type;
  195905. buf[11] = (png_byte)filter_type;
  195906. buf[12] = (png_byte)interlace_type;
  195907. /* write the chunk */
  195908. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  195909. /* initialize zlib with PNG info */
  195910. png_ptr->zstream.zalloc = png_zalloc;
  195911. png_ptr->zstream.zfree = png_zfree;
  195912. png_ptr->zstream.opaque = (voidpf)png_ptr;
  195913. if (!(png_ptr->do_filter))
  195914. {
  195915. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  195916. png_ptr->bit_depth < 8)
  195917. png_ptr->do_filter = PNG_FILTER_NONE;
  195918. else
  195919. png_ptr->do_filter = PNG_ALL_FILTERS;
  195920. }
  195921. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  195922. {
  195923. if (png_ptr->do_filter != PNG_FILTER_NONE)
  195924. png_ptr->zlib_strategy = Z_FILTERED;
  195925. else
  195926. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  195927. }
  195928. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  195929. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  195930. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  195931. png_ptr->zlib_mem_level = 8;
  195932. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  195933. png_ptr->zlib_window_bits = 15;
  195934. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  195935. png_ptr->zlib_method = 8;
  195936. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  195937. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  195938. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  195939. png_error(png_ptr, "zlib failed to initialize compressor");
  195940. png_ptr->zstream.next_out = png_ptr->zbuf;
  195941. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195942. /* libpng is not interested in zstream.data_type */
  195943. /* set it to a predefined value, to avoid its evaluation inside zlib */
  195944. png_ptr->zstream.data_type = Z_BINARY;
  195945. png_ptr->mode = PNG_HAVE_IHDR;
  195946. }
  195947. /* write the palette. We are careful not to trust png_color to be in the
  195948. * correct order for PNG, so people can redefine it to any convenient
  195949. * structure.
  195950. */
  195951. void /* PRIVATE */
  195952. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  195953. {
  195954. #ifdef PNG_USE_LOCAL_ARRAYS
  195955. PNG_PLTE;
  195956. #endif
  195957. png_uint_32 i;
  195958. png_colorp pal_ptr;
  195959. png_byte buf[3];
  195960. png_debug(1, "in png_write_PLTE\n");
  195961. if ((
  195962. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195963. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  195964. #endif
  195965. num_pal == 0) || num_pal > 256)
  195966. {
  195967. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195968. {
  195969. png_error(png_ptr, "Invalid number of colors in palette");
  195970. }
  195971. else
  195972. {
  195973. png_warning(png_ptr, "Invalid number of colors in palette");
  195974. return;
  195975. }
  195976. }
  195977. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  195978. {
  195979. png_warning(png_ptr,
  195980. "Ignoring request to write a PLTE chunk in grayscale PNG");
  195981. return;
  195982. }
  195983. png_ptr->num_palette = (png_uint_16)num_pal;
  195984. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  195985. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  195986. #ifndef PNG_NO_POINTER_INDEXING
  195987. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  195988. {
  195989. buf[0] = pal_ptr->red;
  195990. buf[1] = pal_ptr->green;
  195991. buf[2] = pal_ptr->blue;
  195992. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  195993. }
  195994. #else
  195995. /* This is a little slower but some buggy compilers need to do this instead */
  195996. pal_ptr=palette;
  195997. for (i = 0; i < num_pal; i++)
  195998. {
  195999. buf[0] = pal_ptr[i].red;
  196000. buf[1] = pal_ptr[i].green;
  196001. buf[2] = pal_ptr[i].blue;
  196002. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  196003. }
  196004. #endif
  196005. png_write_chunk_end(png_ptr);
  196006. png_ptr->mode |= PNG_HAVE_PLTE;
  196007. }
  196008. /* write an IDAT chunk */
  196009. void /* PRIVATE */
  196010. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  196011. {
  196012. #ifdef PNG_USE_LOCAL_ARRAYS
  196013. PNG_IDAT;
  196014. #endif
  196015. png_debug(1, "in png_write_IDAT\n");
  196016. /* Optimize the CMF field in the zlib stream. */
  196017. /* This hack of the zlib stream is compliant to the stream specification. */
  196018. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  196019. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  196020. {
  196021. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  196022. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  196023. {
  196024. /* Avoid memory underflows and multiplication overflows. */
  196025. /* The conditions below are practically always satisfied;
  196026. however, they still must be checked. */
  196027. if (length >= 2 &&
  196028. png_ptr->height < 16384 && png_ptr->width < 16384)
  196029. {
  196030. png_uint_32 uncompressed_idat_size = png_ptr->height *
  196031. ((png_ptr->width *
  196032. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  196033. unsigned int z_cinfo = z_cmf >> 4;
  196034. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  196035. while (uncompressed_idat_size <= half_z_window_size &&
  196036. half_z_window_size >= 256)
  196037. {
  196038. z_cinfo--;
  196039. half_z_window_size >>= 1;
  196040. }
  196041. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  196042. if (data[0] != (png_byte)z_cmf)
  196043. {
  196044. data[0] = (png_byte)z_cmf;
  196045. data[1] &= 0xe0;
  196046. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  196047. }
  196048. }
  196049. }
  196050. else
  196051. png_error(png_ptr,
  196052. "Invalid zlib compression method or flags in IDAT");
  196053. }
  196054. png_write_chunk(png_ptr, png_IDAT, data, length);
  196055. png_ptr->mode |= PNG_HAVE_IDAT;
  196056. }
  196057. /* write an IEND chunk */
  196058. void /* PRIVATE */
  196059. png_write_IEND(png_structp png_ptr)
  196060. {
  196061. #ifdef PNG_USE_LOCAL_ARRAYS
  196062. PNG_IEND;
  196063. #endif
  196064. png_debug(1, "in png_write_IEND\n");
  196065. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  196066. (png_size_t)0);
  196067. png_ptr->mode |= PNG_HAVE_IEND;
  196068. }
  196069. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  196070. /* write a gAMA chunk */
  196071. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196072. void /* PRIVATE */
  196073. png_write_gAMA(png_structp png_ptr, double file_gamma)
  196074. {
  196075. #ifdef PNG_USE_LOCAL_ARRAYS
  196076. PNG_gAMA;
  196077. #endif
  196078. png_uint_32 igamma;
  196079. png_byte buf[4];
  196080. png_debug(1, "in png_write_gAMA\n");
  196081. /* file_gamma is saved in 1/100,000ths */
  196082. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  196083. png_save_uint_32(buf, igamma);
  196084. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  196085. }
  196086. #endif
  196087. #ifdef PNG_FIXED_POINT_SUPPORTED
  196088. void /* PRIVATE */
  196089. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  196090. {
  196091. #ifdef PNG_USE_LOCAL_ARRAYS
  196092. PNG_gAMA;
  196093. #endif
  196094. png_byte buf[4];
  196095. png_debug(1, "in png_write_gAMA\n");
  196096. /* file_gamma is saved in 1/100,000ths */
  196097. png_save_uint_32(buf, (png_uint_32)file_gamma);
  196098. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  196099. }
  196100. #endif
  196101. #endif
  196102. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  196103. /* write a sRGB chunk */
  196104. void /* PRIVATE */
  196105. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  196106. {
  196107. #ifdef PNG_USE_LOCAL_ARRAYS
  196108. PNG_sRGB;
  196109. #endif
  196110. png_byte buf[1];
  196111. png_debug(1, "in png_write_sRGB\n");
  196112. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  196113. png_warning(png_ptr,
  196114. "Invalid sRGB rendering intent specified");
  196115. buf[0]=(png_byte)srgb_intent;
  196116. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  196117. }
  196118. #endif
  196119. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  196120. /* write an iCCP chunk */
  196121. void /* PRIVATE */
  196122. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  196123. png_charp profile, int profile_len)
  196124. {
  196125. #ifdef PNG_USE_LOCAL_ARRAYS
  196126. PNG_iCCP;
  196127. #endif
  196128. png_size_t name_len;
  196129. png_charp new_name;
  196130. compression_state comp;
  196131. int embedded_profile_len = 0;
  196132. png_debug(1, "in png_write_iCCP\n");
  196133. comp.num_output_ptr = 0;
  196134. comp.max_output_ptr = 0;
  196135. comp.output_ptr = NULL;
  196136. comp.input = NULL;
  196137. comp.input_len = 0;
  196138. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  196139. &new_name)) == 0)
  196140. {
  196141. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  196142. return;
  196143. }
  196144. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196145. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  196146. if (profile == NULL)
  196147. profile_len = 0;
  196148. if (profile_len > 3)
  196149. embedded_profile_len =
  196150. ((*( (png_bytep)profile ))<<24) |
  196151. ((*( (png_bytep)profile+1))<<16) |
  196152. ((*( (png_bytep)profile+2))<< 8) |
  196153. ((*( (png_bytep)profile+3)) );
  196154. if (profile_len < embedded_profile_len)
  196155. {
  196156. png_warning(png_ptr,
  196157. "Embedded profile length too large in iCCP chunk");
  196158. return;
  196159. }
  196160. if (profile_len > embedded_profile_len)
  196161. {
  196162. png_warning(png_ptr,
  196163. "Truncating profile to actual length in iCCP chunk");
  196164. profile_len = embedded_profile_len;
  196165. }
  196166. if (profile_len)
  196167. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  196168. PNG_COMPRESSION_TYPE_BASE, &comp);
  196169. /* make sure we include the NULL after the name and the compression type */
  196170. png_write_chunk_start(png_ptr, png_iCCP,
  196171. (png_uint_32)name_len+profile_len+2);
  196172. new_name[name_len+1]=0x00;
  196173. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  196174. if (profile_len)
  196175. png_write_compressed_data_out(png_ptr, &comp);
  196176. png_write_chunk_end(png_ptr);
  196177. png_free(png_ptr, new_name);
  196178. }
  196179. #endif
  196180. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  196181. /* write a sPLT chunk */
  196182. void /* PRIVATE */
  196183. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  196184. {
  196185. #ifdef PNG_USE_LOCAL_ARRAYS
  196186. PNG_sPLT;
  196187. #endif
  196188. png_size_t name_len;
  196189. png_charp new_name;
  196190. png_byte entrybuf[10];
  196191. int entry_size = (spalette->depth == 8 ? 6 : 10);
  196192. int palette_size = entry_size * spalette->nentries;
  196193. png_sPLT_entryp ep;
  196194. #ifdef PNG_NO_POINTER_INDEXING
  196195. int i;
  196196. #endif
  196197. png_debug(1, "in png_write_sPLT\n");
  196198. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  196199. spalette->name, &new_name))==0)
  196200. {
  196201. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  196202. return;
  196203. }
  196204. /* make sure we include the NULL after the name */
  196205. png_write_chunk_start(png_ptr, png_sPLT,
  196206. (png_uint_32)(name_len + 2 + palette_size));
  196207. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  196208. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  196209. /* loop through each palette entry, writing appropriately */
  196210. #ifndef PNG_NO_POINTER_INDEXING
  196211. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  196212. {
  196213. if (spalette->depth == 8)
  196214. {
  196215. entrybuf[0] = (png_byte)ep->red;
  196216. entrybuf[1] = (png_byte)ep->green;
  196217. entrybuf[2] = (png_byte)ep->blue;
  196218. entrybuf[3] = (png_byte)ep->alpha;
  196219. png_save_uint_16(entrybuf + 4, ep->frequency);
  196220. }
  196221. else
  196222. {
  196223. png_save_uint_16(entrybuf + 0, ep->red);
  196224. png_save_uint_16(entrybuf + 2, ep->green);
  196225. png_save_uint_16(entrybuf + 4, ep->blue);
  196226. png_save_uint_16(entrybuf + 6, ep->alpha);
  196227. png_save_uint_16(entrybuf + 8, ep->frequency);
  196228. }
  196229. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  196230. }
  196231. #else
  196232. ep=spalette->entries;
  196233. for (i=0; i>spalette->nentries; i++)
  196234. {
  196235. if (spalette->depth == 8)
  196236. {
  196237. entrybuf[0] = (png_byte)ep[i].red;
  196238. entrybuf[1] = (png_byte)ep[i].green;
  196239. entrybuf[2] = (png_byte)ep[i].blue;
  196240. entrybuf[3] = (png_byte)ep[i].alpha;
  196241. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  196242. }
  196243. else
  196244. {
  196245. png_save_uint_16(entrybuf + 0, ep[i].red);
  196246. png_save_uint_16(entrybuf + 2, ep[i].green);
  196247. png_save_uint_16(entrybuf + 4, ep[i].blue);
  196248. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  196249. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  196250. }
  196251. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  196252. }
  196253. #endif
  196254. png_write_chunk_end(png_ptr);
  196255. png_free(png_ptr, new_name);
  196256. }
  196257. #endif
  196258. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  196259. /* write the sBIT chunk */
  196260. void /* PRIVATE */
  196261. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  196262. {
  196263. #ifdef PNG_USE_LOCAL_ARRAYS
  196264. PNG_sBIT;
  196265. #endif
  196266. png_byte buf[4];
  196267. png_size_t size;
  196268. png_debug(1, "in png_write_sBIT\n");
  196269. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  196270. if (color_type & PNG_COLOR_MASK_COLOR)
  196271. {
  196272. png_byte maxbits;
  196273. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  196274. png_ptr->usr_bit_depth);
  196275. if (sbit->red == 0 || sbit->red > maxbits ||
  196276. sbit->green == 0 || sbit->green > maxbits ||
  196277. sbit->blue == 0 || sbit->blue > maxbits)
  196278. {
  196279. png_warning(png_ptr, "Invalid sBIT depth specified");
  196280. return;
  196281. }
  196282. buf[0] = sbit->red;
  196283. buf[1] = sbit->green;
  196284. buf[2] = sbit->blue;
  196285. size = 3;
  196286. }
  196287. else
  196288. {
  196289. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  196290. {
  196291. png_warning(png_ptr, "Invalid sBIT depth specified");
  196292. return;
  196293. }
  196294. buf[0] = sbit->gray;
  196295. size = 1;
  196296. }
  196297. if (color_type & PNG_COLOR_MASK_ALPHA)
  196298. {
  196299. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  196300. {
  196301. png_warning(png_ptr, "Invalid sBIT depth specified");
  196302. return;
  196303. }
  196304. buf[size++] = sbit->alpha;
  196305. }
  196306. png_write_chunk(png_ptr, png_sBIT, buf, size);
  196307. }
  196308. #endif
  196309. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  196310. /* write the cHRM chunk */
  196311. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196312. void /* PRIVATE */
  196313. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  196314. double red_x, double red_y, double green_x, double green_y,
  196315. double blue_x, double blue_y)
  196316. {
  196317. #ifdef PNG_USE_LOCAL_ARRAYS
  196318. PNG_cHRM;
  196319. #endif
  196320. png_byte buf[32];
  196321. png_uint_32 itemp;
  196322. png_debug(1, "in png_write_cHRM\n");
  196323. /* each value is saved in 1/100,000ths */
  196324. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  196325. white_x + white_y > 1.0)
  196326. {
  196327. png_warning(png_ptr, "Invalid cHRM white point specified");
  196328. #if !defined(PNG_NO_CONSOLE_IO)
  196329. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  196330. #endif
  196331. return;
  196332. }
  196333. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  196334. png_save_uint_32(buf, itemp);
  196335. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  196336. png_save_uint_32(buf + 4, itemp);
  196337. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  196338. {
  196339. png_warning(png_ptr, "Invalid cHRM red point specified");
  196340. return;
  196341. }
  196342. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  196343. png_save_uint_32(buf + 8, itemp);
  196344. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  196345. png_save_uint_32(buf + 12, itemp);
  196346. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  196347. {
  196348. png_warning(png_ptr, "Invalid cHRM green point specified");
  196349. return;
  196350. }
  196351. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  196352. png_save_uint_32(buf + 16, itemp);
  196353. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  196354. png_save_uint_32(buf + 20, itemp);
  196355. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  196356. {
  196357. png_warning(png_ptr, "Invalid cHRM blue point specified");
  196358. return;
  196359. }
  196360. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  196361. png_save_uint_32(buf + 24, itemp);
  196362. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  196363. png_save_uint_32(buf + 28, itemp);
  196364. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  196365. }
  196366. #endif
  196367. #ifdef PNG_FIXED_POINT_SUPPORTED
  196368. void /* PRIVATE */
  196369. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  196370. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  196371. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  196372. png_fixed_point blue_y)
  196373. {
  196374. #ifdef PNG_USE_LOCAL_ARRAYS
  196375. PNG_cHRM;
  196376. #endif
  196377. png_byte buf[32];
  196378. png_debug(1, "in png_write_cHRM\n");
  196379. /* each value is saved in 1/100,000ths */
  196380. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  196381. {
  196382. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  196383. #if !defined(PNG_NO_CONSOLE_IO)
  196384. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  196385. #endif
  196386. return;
  196387. }
  196388. png_save_uint_32(buf, (png_uint_32)white_x);
  196389. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  196390. if (red_x + red_y > 100000L)
  196391. {
  196392. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  196393. return;
  196394. }
  196395. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  196396. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  196397. if (green_x + green_y > 100000L)
  196398. {
  196399. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  196400. return;
  196401. }
  196402. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  196403. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  196404. if (blue_x + blue_y > 100000L)
  196405. {
  196406. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  196407. return;
  196408. }
  196409. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  196410. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  196411. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  196412. }
  196413. #endif
  196414. #endif
  196415. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  196416. /* write the tRNS chunk */
  196417. void /* PRIVATE */
  196418. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  196419. int num_trans, int color_type)
  196420. {
  196421. #ifdef PNG_USE_LOCAL_ARRAYS
  196422. PNG_tRNS;
  196423. #endif
  196424. png_byte buf[6];
  196425. png_debug(1, "in png_write_tRNS\n");
  196426. if (color_type == PNG_COLOR_TYPE_PALETTE)
  196427. {
  196428. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  196429. {
  196430. png_warning(png_ptr,"Invalid number of transparent colors specified");
  196431. return;
  196432. }
  196433. /* write the chunk out as it is */
  196434. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  196435. }
  196436. else if (color_type == PNG_COLOR_TYPE_GRAY)
  196437. {
  196438. /* one 16 bit value */
  196439. if(tran->gray >= (1 << png_ptr->bit_depth))
  196440. {
  196441. png_warning(png_ptr,
  196442. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  196443. return;
  196444. }
  196445. png_save_uint_16(buf, tran->gray);
  196446. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  196447. }
  196448. else if (color_type == PNG_COLOR_TYPE_RGB)
  196449. {
  196450. /* three 16 bit values */
  196451. png_save_uint_16(buf, tran->red);
  196452. png_save_uint_16(buf + 2, tran->green);
  196453. png_save_uint_16(buf + 4, tran->blue);
  196454. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  196455. {
  196456. png_warning(png_ptr,
  196457. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  196458. return;
  196459. }
  196460. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  196461. }
  196462. else
  196463. {
  196464. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  196465. }
  196466. }
  196467. #endif
  196468. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  196469. /* write the background chunk */
  196470. void /* PRIVATE */
  196471. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  196472. {
  196473. #ifdef PNG_USE_LOCAL_ARRAYS
  196474. PNG_bKGD;
  196475. #endif
  196476. png_byte buf[6];
  196477. png_debug(1, "in png_write_bKGD\n");
  196478. if (color_type == PNG_COLOR_TYPE_PALETTE)
  196479. {
  196480. if (
  196481. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196482. (png_ptr->num_palette ||
  196483. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  196484. #endif
  196485. back->index > png_ptr->num_palette)
  196486. {
  196487. png_warning(png_ptr, "Invalid background palette index");
  196488. return;
  196489. }
  196490. buf[0] = back->index;
  196491. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  196492. }
  196493. else if (color_type & PNG_COLOR_MASK_COLOR)
  196494. {
  196495. png_save_uint_16(buf, back->red);
  196496. png_save_uint_16(buf + 2, back->green);
  196497. png_save_uint_16(buf + 4, back->blue);
  196498. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  196499. {
  196500. png_warning(png_ptr,
  196501. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  196502. return;
  196503. }
  196504. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  196505. }
  196506. else
  196507. {
  196508. if(back->gray >= (1 << png_ptr->bit_depth))
  196509. {
  196510. png_warning(png_ptr,
  196511. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  196512. return;
  196513. }
  196514. png_save_uint_16(buf, back->gray);
  196515. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  196516. }
  196517. }
  196518. #endif
  196519. #if defined(PNG_WRITE_hIST_SUPPORTED)
  196520. /* write the histogram */
  196521. void /* PRIVATE */
  196522. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  196523. {
  196524. #ifdef PNG_USE_LOCAL_ARRAYS
  196525. PNG_hIST;
  196526. #endif
  196527. int i;
  196528. png_byte buf[3];
  196529. png_debug(1, "in png_write_hIST\n");
  196530. if (num_hist > (int)png_ptr->num_palette)
  196531. {
  196532. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  196533. png_ptr->num_palette);
  196534. png_warning(png_ptr, "Invalid number of histogram entries specified");
  196535. return;
  196536. }
  196537. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  196538. for (i = 0; i < num_hist; i++)
  196539. {
  196540. png_save_uint_16(buf, hist[i]);
  196541. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  196542. }
  196543. png_write_chunk_end(png_ptr);
  196544. }
  196545. #endif
  196546. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  196547. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  196548. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  196549. * and if invalid, correct the keyword rather than discarding the entire
  196550. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  196551. * length, forbids leading or trailing whitespace, multiple internal spaces,
  196552. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  196553. *
  196554. * The new_key is allocated to hold the corrected keyword and must be freed
  196555. * by the calling routine. This avoids problems with trying to write to
  196556. * static keywords without having to have duplicate copies of the strings.
  196557. */
  196558. png_size_t /* PRIVATE */
  196559. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  196560. {
  196561. png_size_t key_len;
  196562. png_charp kp, dp;
  196563. int kflag;
  196564. int kwarn=0;
  196565. png_debug(1, "in png_check_keyword\n");
  196566. *new_key = NULL;
  196567. if (key == NULL || (key_len = png_strlen(key)) == 0)
  196568. {
  196569. png_warning(png_ptr, "zero length keyword");
  196570. return ((png_size_t)0);
  196571. }
  196572. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  196573. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  196574. if (*new_key == NULL)
  196575. {
  196576. png_warning(png_ptr, "Out of memory while procesing keyword");
  196577. return ((png_size_t)0);
  196578. }
  196579. /* Replace non-printing characters with a blank and print a warning */
  196580. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  196581. {
  196582. if ((png_byte)*kp < 0x20 ||
  196583. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  196584. {
  196585. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  196586. char msg[40];
  196587. png_snprintf(msg, 40,
  196588. "invalid keyword character 0x%02X", (png_byte)*kp);
  196589. png_warning(png_ptr, msg);
  196590. #else
  196591. png_warning(png_ptr, "invalid character in keyword");
  196592. #endif
  196593. *dp = ' ';
  196594. }
  196595. else
  196596. {
  196597. *dp = *kp;
  196598. }
  196599. }
  196600. *dp = '\0';
  196601. /* Remove any trailing white space. */
  196602. kp = *new_key + key_len - 1;
  196603. if (*kp == ' ')
  196604. {
  196605. png_warning(png_ptr, "trailing spaces removed from keyword");
  196606. while (*kp == ' ')
  196607. {
  196608. *(kp--) = '\0';
  196609. key_len--;
  196610. }
  196611. }
  196612. /* Remove any leading white space. */
  196613. kp = *new_key;
  196614. if (*kp == ' ')
  196615. {
  196616. png_warning(png_ptr, "leading spaces removed from keyword");
  196617. while (*kp == ' ')
  196618. {
  196619. kp++;
  196620. key_len--;
  196621. }
  196622. }
  196623. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  196624. /* Remove multiple internal spaces. */
  196625. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  196626. {
  196627. if (*kp == ' ' && kflag == 0)
  196628. {
  196629. *(dp++) = *kp;
  196630. kflag = 1;
  196631. }
  196632. else if (*kp == ' ')
  196633. {
  196634. key_len--;
  196635. kwarn=1;
  196636. }
  196637. else
  196638. {
  196639. *(dp++) = *kp;
  196640. kflag = 0;
  196641. }
  196642. }
  196643. *dp = '\0';
  196644. if(kwarn)
  196645. png_warning(png_ptr, "extra interior spaces removed from keyword");
  196646. if (key_len == 0)
  196647. {
  196648. png_free(png_ptr, *new_key);
  196649. *new_key=NULL;
  196650. png_warning(png_ptr, "Zero length keyword");
  196651. }
  196652. if (key_len > 79)
  196653. {
  196654. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  196655. new_key[79] = '\0';
  196656. key_len = 79;
  196657. }
  196658. return (key_len);
  196659. }
  196660. #endif
  196661. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  196662. /* write a tEXt chunk */
  196663. void /* PRIVATE */
  196664. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  196665. png_size_t text_len)
  196666. {
  196667. #ifdef PNG_USE_LOCAL_ARRAYS
  196668. PNG_tEXt;
  196669. #endif
  196670. png_size_t key_len;
  196671. png_charp new_key;
  196672. png_debug(1, "in png_write_tEXt\n");
  196673. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  196674. {
  196675. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  196676. return;
  196677. }
  196678. if (text == NULL || *text == '\0')
  196679. text_len = 0;
  196680. else
  196681. text_len = png_strlen(text);
  196682. /* make sure we include the 0 after the key */
  196683. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  196684. /*
  196685. * We leave it to the application to meet PNG-1.0 requirements on the
  196686. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  196687. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  196688. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  196689. */
  196690. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  196691. if (text_len)
  196692. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  196693. png_write_chunk_end(png_ptr);
  196694. png_free(png_ptr, new_key);
  196695. }
  196696. #endif
  196697. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  196698. /* write a compressed text chunk */
  196699. void /* PRIVATE */
  196700. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  196701. png_size_t text_len, int compression)
  196702. {
  196703. #ifdef PNG_USE_LOCAL_ARRAYS
  196704. PNG_zTXt;
  196705. #endif
  196706. png_size_t key_len;
  196707. char buf[1];
  196708. png_charp new_key;
  196709. compression_state comp;
  196710. png_debug(1, "in png_write_zTXt\n");
  196711. comp.num_output_ptr = 0;
  196712. comp.max_output_ptr = 0;
  196713. comp.output_ptr = NULL;
  196714. comp.input = NULL;
  196715. comp.input_len = 0;
  196716. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  196717. {
  196718. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  196719. return;
  196720. }
  196721. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  196722. {
  196723. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  196724. png_free(png_ptr, new_key);
  196725. return;
  196726. }
  196727. text_len = png_strlen(text);
  196728. /* compute the compressed data; do it now for the length */
  196729. text_len = png_text_compress(png_ptr, text, text_len, compression,
  196730. &comp);
  196731. /* write start of chunk */
  196732. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  196733. (key_len+text_len+2));
  196734. /* write key */
  196735. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  196736. png_free(png_ptr, new_key);
  196737. buf[0] = (png_byte)compression;
  196738. /* write compression */
  196739. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  196740. /* write the compressed data */
  196741. png_write_compressed_data_out(png_ptr, &comp);
  196742. /* close the chunk */
  196743. png_write_chunk_end(png_ptr);
  196744. }
  196745. #endif
  196746. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  196747. /* write an iTXt chunk */
  196748. void /* PRIVATE */
  196749. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  196750. png_charp lang, png_charp lang_key, png_charp text)
  196751. {
  196752. #ifdef PNG_USE_LOCAL_ARRAYS
  196753. PNG_iTXt;
  196754. #endif
  196755. png_size_t lang_len, key_len, lang_key_len, text_len;
  196756. png_charp new_lang, new_key;
  196757. png_byte cbuf[2];
  196758. compression_state comp;
  196759. png_debug(1, "in png_write_iTXt\n");
  196760. comp.num_output_ptr = 0;
  196761. comp.max_output_ptr = 0;
  196762. comp.output_ptr = NULL;
  196763. comp.input = NULL;
  196764. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  196765. {
  196766. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  196767. return;
  196768. }
  196769. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  196770. {
  196771. png_warning(png_ptr, "Empty language field in iTXt chunk");
  196772. new_lang = NULL;
  196773. lang_len = 0;
  196774. }
  196775. if (lang_key == NULL)
  196776. lang_key_len = 0;
  196777. else
  196778. lang_key_len = png_strlen(lang_key);
  196779. if (text == NULL)
  196780. text_len = 0;
  196781. else
  196782. text_len = png_strlen(text);
  196783. /* compute the compressed data; do it now for the length */
  196784. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  196785. &comp);
  196786. /* make sure we include the compression flag, the compression byte,
  196787. * and the NULs after the key, lang, and lang_key parts */
  196788. png_write_chunk_start(png_ptr, png_iTXt,
  196789. (png_uint_32)(
  196790. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  196791. + key_len
  196792. + lang_len
  196793. + lang_key_len
  196794. + text_len));
  196795. /*
  196796. * We leave it to the application to meet PNG-1.0 requirements on the
  196797. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  196798. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  196799. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  196800. */
  196801. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  196802. /* set the compression flag */
  196803. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  196804. compression == PNG_TEXT_COMPRESSION_NONE)
  196805. cbuf[0] = 0;
  196806. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  196807. cbuf[0] = 1;
  196808. /* set the compression method */
  196809. cbuf[1] = 0;
  196810. png_write_chunk_data(png_ptr, cbuf, 2);
  196811. cbuf[0] = 0;
  196812. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  196813. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  196814. png_write_compressed_data_out(png_ptr, &comp);
  196815. png_write_chunk_end(png_ptr);
  196816. png_free(png_ptr, new_key);
  196817. if (new_lang)
  196818. png_free(png_ptr, new_lang);
  196819. }
  196820. #endif
  196821. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  196822. /* write the oFFs chunk */
  196823. void /* PRIVATE */
  196824. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  196825. int unit_type)
  196826. {
  196827. #ifdef PNG_USE_LOCAL_ARRAYS
  196828. PNG_oFFs;
  196829. #endif
  196830. png_byte buf[9];
  196831. png_debug(1, "in png_write_oFFs\n");
  196832. if (unit_type >= PNG_OFFSET_LAST)
  196833. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  196834. png_save_int_32(buf, x_offset);
  196835. png_save_int_32(buf + 4, y_offset);
  196836. buf[8] = (png_byte)unit_type;
  196837. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  196838. }
  196839. #endif
  196840. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  196841. /* write the pCAL chunk (described in the PNG extensions document) */
  196842. void /* PRIVATE */
  196843. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  196844. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  196845. {
  196846. #ifdef PNG_USE_LOCAL_ARRAYS
  196847. PNG_pCAL;
  196848. #endif
  196849. png_size_t purpose_len, units_len, total_len;
  196850. png_uint_32p params_len;
  196851. png_byte buf[10];
  196852. png_charp new_purpose;
  196853. int i;
  196854. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  196855. if (type >= PNG_EQUATION_LAST)
  196856. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  196857. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  196858. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  196859. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  196860. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  196861. total_len = purpose_len + units_len + 10;
  196862. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  196863. *png_sizeof(png_uint_32)));
  196864. /* Find the length of each parameter, making sure we don't count the
  196865. null terminator for the last parameter. */
  196866. for (i = 0; i < nparams; i++)
  196867. {
  196868. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  196869. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  196870. total_len += (png_size_t)params_len[i];
  196871. }
  196872. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  196873. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  196874. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  196875. png_save_int_32(buf, X0);
  196876. png_save_int_32(buf + 4, X1);
  196877. buf[8] = (png_byte)type;
  196878. buf[9] = (png_byte)nparams;
  196879. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  196880. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  196881. png_free(png_ptr, new_purpose);
  196882. for (i = 0; i < nparams; i++)
  196883. {
  196884. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  196885. (png_size_t)params_len[i]);
  196886. }
  196887. png_free(png_ptr, params_len);
  196888. png_write_chunk_end(png_ptr);
  196889. }
  196890. #endif
  196891. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  196892. /* write the sCAL chunk */
  196893. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  196894. void /* PRIVATE */
  196895. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  196896. {
  196897. #ifdef PNG_USE_LOCAL_ARRAYS
  196898. PNG_sCAL;
  196899. #endif
  196900. char buf[64];
  196901. png_size_t total_len;
  196902. png_debug(1, "in png_write_sCAL\n");
  196903. buf[0] = (char)unit;
  196904. #if defined(_WIN32_WCE)
  196905. /* sprintf() function is not supported on WindowsCE */
  196906. {
  196907. wchar_t wc_buf[32];
  196908. size_t wc_len;
  196909. swprintf(wc_buf, TEXT("%12.12e"), width);
  196910. wc_len = wcslen(wc_buf);
  196911. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  196912. total_len = wc_len + 2;
  196913. swprintf(wc_buf, TEXT("%12.12e"), height);
  196914. wc_len = wcslen(wc_buf);
  196915. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  196916. NULL, NULL);
  196917. total_len += wc_len;
  196918. }
  196919. #else
  196920. png_snprintf(buf + 1, 63, "%12.12e", width);
  196921. total_len = 1 + png_strlen(buf + 1) + 1;
  196922. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  196923. total_len += png_strlen(buf + total_len);
  196924. #endif
  196925. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  196926. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  196927. }
  196928. #else
  196929. #ifdef PNG_FIXED_POINT_SUPPORTED
  196930. void /* PRIVATE */
  196931. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  196932. png_charp height)
  196933. {
  196934. #ifdef PNG_USE_LOCAL_ARRAYS
  196935. PNG_sCAL;
  196936. #endif
  196937. png_byte buf[64];
  196938. png_size_t wlen, hlen, total_len;
  196939. png_debug(1, "in png_write_sCAL_s\n");
  196940. wlen = png_strlen(width);
  196941. hlen = png_strlen(height);
  196942. total_len = wlen + hlen + 2;
  196943. if (total_len > 64)
  196944. {
  196945. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  196946. return;
  196947. }
  196948. buf[0] = (png_byte)unit;
  196949. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  196950. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  196951. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  196952. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  196953. }
  196954. #endif
  196955. #endif
  196956. #endif
  196957. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  196958. /* write the pHYs chunk */
  196959. void /* PRIVATE */
  196960. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  196961. png_uint_32 y_pixels_per_unit,
  196962. int unit_type)
  196963. {
  196964. #ifdef PNG_USE_LOCAL_ARRAYS
  196965. PNG_pHYs;
  196966. #endif
  196967. png_byte buf[9];
  196968. png_debug(1, "in png_write_pHYs\n");
  196969. if (unit_type >= PNG_RESOLUTION_LAST)
  196970. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  196971. png_save_uint_32(buf, x_pixels_per_unit);
  196972. png_save_uint_32(buf + 4, y_pixels_per_unit);
  196973. buf[8] = (png_byte)unit_type;
  196974. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  196975. }
  196976. #endif
  196977. #if defined(PNG_WRITE_tIME_SUPPORTED)
  196978. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  196979. * or png_convert_from_time_t(), or fill in the structure yourself.
  196980. */
  196981. void /* PRIVATE */
  196982. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  196983. {
  196984. #ifdef PNG_USE_LOCAL_ARRAYS
  196985. PNG_tIME;
  196986. #endif
  196987. png_byte buf[7];
  196988. png_debug(1, "in png_write_tIME\n");
  196989. if (mod_time->month > 12 || mod_time->month < 1 ||
  196990. mod_time->day > 31 || mod_time->day < 1 ||
  196991. mod_time->hour > 23 || mod_time->second > 60)
  196992. {
  196993. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  196994. return;
  196995. }
  196996. png_save_uint_16(buf, mod_time->year);
  196997. buf[2] = mod_time->month;
  196998. buf[3] = mod_time->day;
  196999. buf[4] = mod_time->hour;
  197000. buf[5] = mod_time->minute;
  197001. buf[6] = mod_time->second;
  197002. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  197003. }
  197004. #endif
  197005. /* initializes the row writing capability of libpng */
  197006. void /* PRIVATE */
  197007. png_write_start_row(png_structp png_ptr)
  197008. {
  197009. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197010. #ifdef PNG_USE_LOCAL_ARRAYS
  197011. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197012. /* start of interlace block */
  197013. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197014. /* offset to next interlace block */
  197015. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197016. /* start of interlace block in the y direction */
  197017. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  197018. /* offset to next interlace block in the y direction */
  197019. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  197020. #endif
  197021. #endif
  197022. png_size_t buf_size;
  197023. png_debug(1, "in png_write_start_row\n");
  197024. buf_size = (png_size_t)(PNG_ROWBYTES(
  197025. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  197026. /* set up row buffer */
  197027. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  197028. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  197029. #ifndef PNG_NO_WRITE_FILTERING
  197030. /* set up filtering buffer, if using this filter */
  197031. if (png_ptr->do_filter & PNG_FILTER_SUB)
  197032. {
  197033. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  197034. (png_ptr->rowbytes + 1));
  197035. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  197036. }
  197037. /* We only need to keep the previous row if we are using one of these. */
  197038. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  197039. {
  197040. /* set up previous row buffer */
  197041. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  197042. png_memset(png_ptr->prev_row, 0, buf_size);
  197043. if (png_ptr->do_filter & PNG_FILTER_UP)
  197044. {
  197045. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  197046. (png_ptr->rowbytes + 1));
  197047. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  197048. }
  197049. if (png_ptr->do_filter & PNG_FILTER_AVG)
  197050. {
  197051. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  197052. (png_ptr->rowbytes + 1));
  197053. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  197054. }
  197055. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  197056. {
  197057. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  197058. (png_ptr->rowbytes + 1));
  197059. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  197060. }
  197061. #endif /* PNG_NO_WRITE_FILTERING */
  197062. }
  197063. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197064. /* if interlaced, we need to set up width and height of pass */
  197065. if (png_ptr->interlaced)
  197066. {
  197067. if (!(png_ptr->transformations & PNG_INTERLACE))
  197068. {
  197069. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  197070. png_pass_ystart[0]) / png_pass_yinc[0];
  197071. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  197072. png_pass_start[0]) / png_pass_inc[0];
  197073. }
  197074. else
  197075. {
  197076. png_ptr->num_rows = png_ptr->height;
  197077. png_ptr->usr_width = png_ptr->width;
  197078. }
  197079. }
  197080. else
  197081. #endif
  197082. {
  197083. png_ptr->num_rows = png_ptr->height;
  197084. png_ptr->usr_width = png_ptr->width;
  197085. }
  197086. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197087. png_ptr->zstream.next_out = png_ptr->zbuf;
  197088. }
  197089. /* Internal use only. Called when finished processing a row of data. */
  197090. void /* PRIVATE */
  197091. png_write_finish_row(png_structp png_ptr)
  197092. {
  197093. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197094. #ifdef PNG_USE_LOCAL_ARRAYS
  197095. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197096. /* start of interlace block */
  197097. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197098. /* offset to next interlace block */
  197099. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197100. /* start of interlace block in the y direction */
  197101. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  197102. /* offset to next interlace block in the y direction */
  197103. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  197104. #endif
  197105. #endif
  197106. int ret;
  197107. png_debug(1, "in png_write_finish_row\n");
  197108. /* next row */
  197109. png_ptr->row_number++;
  197110. /* see if we are done */
  197111. if (png_ptr->row_number < png_ptr->num_rows)
  197112. return;
  197113. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197114. /* if interlaced, go to next pass */
  197115. if (png_ptr->interlaced)
  197116. {
  197117. png_ptr->row_number = 0;
  197118. if (png_ptr->transformations & PNG_INTERLACE)
  197119. {
  197120. png_ptr->pass++;
  197121. }
  197122. else
  197123. {
  197124. /* loop until we find a non-zero width or height pass */
  197125. do
  197126. {
  197127. png_ptr->pass++;
  197128. if (png_ptr->pass >= 7)
  197129. break;
  197130. png_ptr->usr_width = (png_ptr->width +
  197131. png_pass_inc[png_ptr->pass] - 1 -
  197132. png_pass_start[png_ptr->pass]) /
  197133. png_pass_inc[png_ptr->pass];
  197134. png_ptr->num_rows = (png_ptr->height +
  197135. png_pass_yinc[png_ptr->pass] - 1 -
  197136. png_pass_ystart[png_ptr->pass]) /
  197137. png_pass_yinc[png_ptr->pass];
  197138. if (png_ptr->transformations & PNG_INTERLACE)
  197139. break;
  197140. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  197141. }
  197142. /* reset the row above the image for the next pass */
  197143. if (png_ptr->pass < 7)
  197144. {
  197145. if (png_ptr->prev_row != NULL)
  197146. png_memset(png_ptr->prev_row, 0,
  197147. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  197148. png_ptr->usr_bit_depth,png_ptr->width))+1);
  197149. return;
  197150. }
  197151. }
  197152. #endif
  197153. /* if we get here, we've just written the last row, so we need
  197154. to flush the compressor */
  197155. do
  197156. {
  197157. /* tell the compressor we are done */
  197158. ret = deflate(&png_ptr->zstream, Z_FINISH);
  197159. /* check for an error */
  197160. if (ret == Z_OK)
  197161. {
  197162. /* check to see if we need more room */
  197163. if (!(png_ptr->zstream.avail_out))
  197164. {
  197165. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  197166. png_ptr->zstream.next_out = png_ptr->zbuf;
  197167. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197168. }
  197169. }
  197170. else if (ret != Z_STREAM_END)
  197171. {
  197172. if (png_ptr->zstream.msg != NULL)
  197173. png_error(png_ptr, png_ptr->zstream.msg);
  197174. else
  197175. png_error(png_ptr, "zlib error");
  197176. }
  197177. } while (ret != Z_STREAM_END);
  197178. /* write any extra space */
  197179. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  197180. {
  197181. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  197182. png_ptr->zstream.avail_out);
  197183. }
  197184. deflateReset(&png_ptr->zstream);
  197185. png_ptr->zstream.data_type = Z_BINARY;
  197186. }
  197187. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197188. /* Pick out the correct pixels for the interlace pass.
  197189. * The basic idea here is to go through the row with a source
  197190. * pointer and a destination pointer (sp and dp), and copy the
  197191. * correct pixels for the pass. As the row gets compacted,
  197192. * sp will always be >= dp, so we should never overwrite anything.
  197193. * See the default: case for the easiest code to understand.
  197194. */
  197195. void /* PRIVATE */
  197196. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  197197. {
  197198. #ifdef PNG_USE_LOCAL_ARRAYS
  197199. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197200. /* start of interlace block */
  197201. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197202. /* offset to next interlace block */
  197203. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197204. #endif
  197205. png_debug(1, "in png_do_write_interlace\n");
  197206. /* we don't have to do anything on the last pass (6) */
  197207. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197208. if (row != NULL && row_info != NULL && pass < 6)
  197209. #else
  197210. if (pass < 6)
  197211. #endif
  197212. {
  197213. /* each pixel depth is handled separately */
  197214. switch (row_info->pixel_depth)
  197215. {
  197216. case 1:
  197217. {
  197218. png_bytep sp;
  197219. png_bytep dp;
  197220. int shift;
  197221. int d;
  197222. int value;
  197223. png_uint_32 i;
  197224. png_uint_32 row_width = row_info->width;
  197225. dp = row;
  197226. d = 0;
  197227. shift = 7;
  197228. for (i = png_pass_start[pass]; i < row_width;
  197229. i += png_pass_inc[pass])
  197230. {
  197231. sp = row + (png_size_t)(i >> 3);
  197232. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  197233. d |= (value << shift);
  197234. if (shift == 0)
  197235. {
  197236. shift = 7;
  197237. *dp++ = (png_byte)d;
  197238. d = 0;
  197239. }
  197240. else
  197241. shift--;
  197242. }
  197243. if (shift != 7)
  197244. *dp = (png_byte)d;
  197245. break;
  197246. }
  197247. case 2:
  197248. {
  197249. png_bytep sp;
  197250. png_bytep dp;
  197251. int shift;
  197252. int d;
  197253. int value;
  197254. png_uint_32 i;
  197255. png_uint_32 row_width = row_info->width;
  197256. dp = row;
  197257. shift = 6;
  197258. d = 0;
  197259. for (i = png_pass_start[pass]; i < row_width;
  197260. i += png_pass_inc[pass])
  197261. {
  197262. sp = row + (png_size_t)(i >> 2);
  197263. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  197264. d |= (value << shift);
  197265. if (shift == 0)
  197266. {
  197267. shift = 6;
  197268. *dp++ = (png_byte)d;
  197269. d = 0;
  197270. }
  197271. else
  197272. shift -= 2;
  197273. }
  197274. if (shift != 6)
  197275. *dp = (png_byte)d;
  197276. break;
  197277. }
  197278. case 4:
  197279. {
  197280. png_bytep sp;
  197281. png_bytep dp;
  197282. int shift;
  197283. int d;
  197284. int value;
  197285. png_uint_32 i;
  197286. png_uint_32 row_width = row_info->width;
  197287. dp = row;
  197288. shift = 4;
  197289. d = 0;
  197290. for (i = png_pass_start[pass]; i < row_width;
  197291. i += png_pass_inc[pass])
  197292. {
  197293. sp = row + (png_size_t)(i >> 1);
  197294. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  197295. d |= (value << shift);
  197296. if (shift == 0)
  197297. {
  197298. shift = 4;
  197299. *dp++ = (png_byte)d;
  197300. d = 0;
  197301. }
  197302. else
  197303. shift -= 4;
  197304. }
  197305. if (shift != 4)
  197306. *dp = (png_byte)d;
  197307. break;
  197308. }
  197309. default:
  197310. {
  197311. png_bytep sp;
  197312. png_bytep dp;
  197313. png_uint_32 i;
  197314. png_uint_32 row_width = row_info->width;
  197315. png_size_t pixel_bytes;
  197316. /* start at the beginning */
  197317. dp = row;
  197318. /* find out how many bytes each pixel takes up */
  197319. pixel_bytes = (row_info->pixel_depth >> 3);
  197320. /* loop through the row, only looking at the pixels that
  197321. matter */
  197322. for (i = png_pass_start[pass]; i < row_width;
  197323. i += png_pass_inc[pass])
  197324. {
  197325. /* find out where the original pixel is */
  197326. sp = row + (png_size_t)i * pixel_bytes;
  197327. /* move the pixel */
  197328. if (dp != sp)
  197329. png_memcpy(dp, sp, pixel_bytes);
  197330. /* next pixel */
  197331. dp += pixel_bytes;
  197332. }
  197333. break;
  197334. }
  197335. }
  197336. /* set new row width */
  197337. row_info->width = (row_info->width +
  197338. png_pass_inc[pass] - 1 -
  197339. png_pass_start[pass]) /
  197340. png_pass_inc[pass];
  197341. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  197342. row_info->width);
  197343. }
  197344. }
  197345. #endif
  197346. /* This filters the row, chooses which filter to use, if it has not already
  197347. * been specified by the application, and then writes the row out with the
  197348. * chosen filter.
  197349. */
  197350. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  197351. #define PNG_HISHIFT 10
  197352. #define PNG_LOMASK ((png_uint_32)0xffffL)
  197353. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  197354. void /* PRIVATE */
  197355. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  197356. {
  197357. png_bytep best_row;
  197358. #ifndef PNG_NO_WRITE_FILTER
  197359. png_bytep prev_row, row_buf;
  197360. png_uint_32 mins, bpp;
  197361. png_byte filter_to_do = png_ptr->do_filter;
  197362. png_uint_32 row_bytes = row_info->rowbytes;
  197363. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197364. int num_p_filters = (int)png_ptr->num_prev_filters;
  197365. #endif
  197366. png_debug(1, "in png_write_find_filter\n");
  197367. /* find out how many bytes offset each pixel is */
  197368. bpp = (row_info->pixel_depth + 7) >> 3;
  197369. prev_row = png_ptr->prev_row;
  197370. #endif
  197371. best_row = png_ptr->row_buf;
  197372. #ifndef PNG_NO_WRITE_FILTER
  197373. row_buf = best_row;
  197374. mins = PNG_MAXSUM;
  197375. /* The prediction method we use is to find which method provides the
  197376. * smallest value when summing the absolute values of the distances
  197377. * from zero, using anything >= 128 as negative numbers. This is known
  197378. * as the "minimum sum of absolute differences" heuristic. Other
  197379. * heuristics are the "weighted minimum sum of absolute differences"
  197380. * (experimental and can in theory improve compression), and the "zlib
  197381. * predictive" method (not implemented yet), which does test compressions
  197382. * of lines using different filter methods, and then chooses the
  197383. * (series of) filter(s) that give minimum compressed data size (VERY
  197384. * computationally expensive).
  197385. *
  197386. * GRR 980525: consider also
  197387. * (1) minimum sum of absolute differences from running average (i.e.,
  197388. * keep running sum of non-absolute differences & count of bytes)
  197389. * [track dispersion, too? restart average if dispersion too large?]
  197390. * (1b) minimum sum of absolute differences from sliding average, probably
  197391. * with window size <= deflate window (usually 32K)
  197392. * (2) minimum sum of squared differences from zero or running average
  197393. * (i.e., ~ root-mean-square approach)
  197394. */
  197395. /* We don't need to test the 'no filter' case if this is the only filter
  197396. * that has been chosen, as it doesn't actually do anything to the data.
  197397. */
  197398. if ((filter_to_do & PNG_FILTER_NONE) &&
  197399. filter_to_do != PNG_FILTER_NONE)
  197400. {
  197401. png_bytep rp;
  197402. png_uint_32 sum = 0;
  197403. png_uint_32 i;
  197404. int v;
  197405. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  197406. {
  197407. v = *rp;
  197408. sum += (v < 128) ? v : 256 - v;
  197409. }
  197410. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197411. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197412. {
  197413. png_uint_32 sumhi, sumlo;
  197414. int j;
  197415. sumlo = sum & PNG_LOMASK;
  197416. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  197417. /* Reduce the sum if we match any of the previous rows */
  197418. for (j = 0; j < num_p_filters; j++)
  197419. {
  197420. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  197421. {
  197422. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  197423. PNG_WEIGHT_SHIFT;
  197424. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  197425. PNG_WEIGHT_SHIFT;
  197426. }
  197427. }
  197428. /* Factor in the cost of this filter (this is here for completeness,
  197429. * but it makes no sense to have a "cost" for the NONE filter, as
  197430. * it has the minimum possible computational cost - none).
  197431. */
  197432. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  197433. PNG_COST_SHIFT;
  197434. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  197435. PNG_COST_SHIFT;
  197436. if (sumhi > PNG_HIMASK)
  197437. sum = PNG_MAXSUM;
  197438. else
  197439. sum = (sumhi << PNG_HISHIFT) + sumlo;
  197440. }
  197441. #endif
  197442. mins = sum;
  197443. }
  197444. /* sub filter */
  197445. if (filter_to_do == PNG_FILTER_SUB)
  197446. /* it's the only filter so no testing is needed */
  197447. {
  197448. png_bytep rp, lp, dp;
  197449. png_uint_32 i;
  197450. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  197451. i++, rp++, dp++)
  197452. {
  197453. *dp = *rp;
  197454. }
  197455. for (lp = row_buf + 1; i < row_bytes;
  197456. i++, rp++, lp++, dp++)
  197457. {
  197458. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  197459. }
  197460. best_row = png_ptr->sub_row;
  197461. }
  197462. else if (filter_to_do & PNG_FILTER_SUB)
  197463. {
  197464. png_bytep rp, dp, lp;
  197465. png_uint_32 sum = 0, lmins = mins;
  197466. png_uint_32 i;
  197467. int v;
  197468. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197469. /* We temporarily increase the "minimum sum" by the factor we
  197470. * would reduce the sum of this filter, so that we can do the
  197471. * early exit comparison without scaling the sum each time.
  197472. */
  197473. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197474. {
  197475. int j;
  197476. png_uint_32 lmhi, lmlo;
  197477. lmlo = lmins & PNG_LOMASK;
  197478. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  197479. for (j = 0; j < num_p_filters; j++)
  197480. {
  197481. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  197482. {
  197483. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  197484. PNG_WEIGHT_SHIFT;
  197485. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  197486. PNG_WEIGHT_SHIFT;
  197487. }
  197488. }
  197489. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  197490. PNG_COST_SHIFT;
  197491. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  197492. PNG_COST_SHIFT;
  197493. if (lmhi > PNG_HIMASK)
  197494. lmins = PNG_MAXSUM;
  197495. else
  197496. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  197497. }
  197498. #endif
  197499. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  197500. i++, rp++, dp++)
  197501. {
  197502. v = *dp = *rp;
  197503. sum += (v < 128) ? v : 256 - v;
  197504. }
  197505. for (lp = row_buf + 1; i < row_bytes;
  197506. i++, rp++, lp++, dp++)
  197507. {
  197508. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  197509. sum += (v < 128) ? v : 256 - v;
  197510. if (sum > lmins) /* We are already worse, don't continue. */
  197511. break;
  197512. }
  197513. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197514. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197515. {
  197516. int j;
  197517. png_uint_32 sumhi, sumlo;
  197518. sumlo = sum & PNG_LOMASK;
  197519. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  197520. for (j = 0; j < num_p_filters; j++)
  197521. {
  197522. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  197523. {
  197524. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  197525. PNG_WEIGHT_SHIFT;
  197526. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  197527. PNG_WEIGHT_SHIFT;
  197528. }
  197529. }
  197530. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  197531. PNG_COST_SHIFT;
  197532. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  197533. PNG_COST_SHIFT;
  197534. if (sumhi > PNG_HIMASK)
  197535. sum = PNG_MAXSUM;
  197536. else
  197537. sum = (sumhi << PNG_HISHIFT) + sumlo;
  197538. }
  197539. #endif
  197540. if (sum < mins)
  197541. {
  197542. mins = sum;
  197543. best_row = png_ptr->sub_row;
  197544. }
  197545. }
  197546. /* up filter */
  197547. if (filter_to_do == PNG_FILTER_UP)
  197548. {
  197549. png_bytep rp, dp, pp;
  197550. png_uint_32 i;
  197551. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  197552. pp = prev_row + 1; i < row_bytes;
  197553. i++, rp++, pp++, dp++)
  197554. {
  197555. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  197556. }
  197557. best_row = png_ptr->up_row;
  197558. }
  197559. else if (filter_to_do & PNG_FILTER_UP)
  197560. {
  197561. png_bytep rp, dp, pp;
  197562. png_uint_32 sum = 0, lmins = mins;
  197563. png_uint_32 i;
  197564. int v;
  197565. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197566. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197567. {
  197568. int j;
  197569. png_uint_32 lmhi, lmlo;
  197570. lmlo = lmins & PNG_LOMASK;
  197571. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  197572. for (j = 0; j < num_p_filters; j++)
  197573. {
  197574. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  197575. {
  197576. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  197577. PNG_WEIGHT_SHIFT;
  197578. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  197579. PNG_WEIGHT_SHIFT;
  197580. }
  197581. }
  197582. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  197583. PNG_COST_SHIFT;
  197584. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  197585. PNG_COST_SHIFT;
  197586. if (lmhi > PNG_HIMASK)
  197587. lmins = PNG_MAXSUM;
  197588. else
  197589. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  197590. }
  197591. #endif
  197592. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  197593. pp = prev_row + 1; i < row_bytes; i++)
  197594. {
  197595. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  197596. sum += (v < 128) ? v : 256 - v;
  197597. if (sum > lmins) /* We are already worse, don't continue. */
  197598. break;
  197599. }
  197600. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197601. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197602. {
  197603. int j;
  197604. png_uint_32 sumhi, sumlo;
  197605. sumlo = sum & PNG_LOMASK;
  197606. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  197607. for (j = 0; j < num_p_filters; j++)
  197608. {
  197609. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  197610. {
  197611. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  197612. PNG_WEIGHT_SHIFT;
  197613. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  197614. PNG_WEIGHT_SHIFT;
  197615. }
  197616. }
  197617. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  197618. PNG_COST_SHIFT;
  197619. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  197620. PNG_COST_SHIFT;
  197621. if (sumhi > PNG_HIMASK)
  197622. sum = PNG_MAXSUM;
  197623. else
  197624. sum = (sumhi << PNG_HISHIFT) + sumlo;
  197625. }
  197626. #endif
  197627. if (sum < mins)
  197628. {
  197629. mins = sum;
  197630. best_row = png_ptr->up_row;
  197631. }
  197632. }
  197633. /* avg filter */
  197634. if (filter_to_do == PNG_FILTER_AVG)
  197635. {
  197636. png_bytep rp, dp, pp, lp;
  197637. png_uint_32 i;
  197638. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  197639. pp = prev_row + 1; i < bpp; i++)
  197640. {
  197641. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  197642. }
  197643. for (lp = row_buf + 1; i < row_bytes; i++)
  197644. {
  197645. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  197646. & 0xff);
  197647. }
  197648. best_row = png_ptr->avg_row;
  197649. }
  197650. else if (filter_to_do & PNG_FILTER_AVG)
  197651. {
  197652. png_bytep rp, dp, pp, lp;
  197653. png_uint_32 sum = 0, lmins = mins;
  197654. png_uint_32 i;
  197655. int v;
  197656. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197657. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197658. {
  197659. int j;
  197660. png_uint_32 lmhi, lmlo;
  197661. lmlo = lmins & PNG_LOMASK;
  197662. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  197663. for (j = 0; j < num_p_filters; j++)
  197664. {
  197665. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  197666. {
  197667. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  197668. PNG_WEIGHT_SHIFT;
  197669. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  197670. PNG_WEIGHT_SHIFT;
  197671. }
  197672. }
  197673. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  197674. PNG_COST_SHIFT;
  197675. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  197676. PNG_COST_SHIFT;
  197677. if (lmhi > PNG_HIMASK)
  197678. lmins = PNG_MAXSUM;
  197679. else
  197680. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  197681. }
  197682. #endif
  197683. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  197684. pp = prev_row + 1; i < bpp; i++)
  197685. {
  197686. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  197687. sum += (v < 128) ? v : 256 - v;
  197688. }
  197689. for (lp = row_buf + 1; i < row_bytes; i++)
  197690. {
  197691. v = *dp++ =
  197692. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  197693. sum += (v < 128) ? v : 256 - v;
  197694. if (sum > lmins) /* We are already worse, don't continue. */
  197695. break;
  197696. }
  197697. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197698. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197699. {
  197700. int j;
  197701. png_uint_32 sumhi, sumlo;
  197702. sumlo = sum & PNG_LOMASK;
  197703. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  197704. for (j = 0; j < num_p_filters; j++)
  197705. {
  197706. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  197707. {
  197708. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  197709. PNG_WEIGHT_SHIFT;
  197710. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  197711. PNG_WEIGHT_SHIFT;
  197712. }
  197713. }
  197714. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  197715. PNG_COST_SHIFT;
  197716. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  197717. PNG_COST_SHIFT;
  197718. if (sumhi > PNG_HIMASK)
  197719. sum = PNG_MAXSUM;
  197720. else
  197721. sum = (sumhi << PNG_HISHIFT) + sumlo;
  197722. }
  197723. #endif
  197724. if (sum < mins)
  197725. {
  197726. mins = sum;
  197727. best_row = png_ptr->avg_row;
  197728. }
  197729. }
  197730. /* Paeth filter */
  197731. if (filter_to_do == PNG_FILTER_PAETH)
  197732. {
  197733. png_bytep rp, dp, pp, cp, lp;
  197734. png_uint_32 i;
  197735. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  197736. pp = prev_row + 1; i < bpp; i++)
  197737. {
  197738. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  197739. }
  197740. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  197741. {
  197742. int a, b, c, pa, pb, pc, p;
  197743. b = *pp++;
  197744. c = *cp++;
  197745. a = *lp++;
  197746. p = b - c;
  197747. pc = a - c;
  197748. #ifdef PNG_USE_ABS
  197749. pa = abs(p);
  197750. pb = abs(pc);
  197751. pc = abs(p + pc);
  197752. #else
  197753. pa = p < 0 ? -p : p;
  197754. pb = pc < 0 ? -pc : pc;
  197755. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  197756. #endif
  197757. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  197758. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  197759. }
  197760. best_row = png_ptr->paeth_row;
  197761. }
  197762. else if (filter_to_do & PNG_FILTER_PAETH)
  197763. {
  197764. png_bytep rp, dp, pp, cp, lp;
  197765. png_uint_32 sum = 0, lmins = mins;
  197766. png_uint_32 i;
  197767. int v;
  197768. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197769. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197770. {
  197771. int j;
  197772. png_uint_32 lmhi, lmlo;
  197773. lmlo = lmins & PNG_LOMASK;
  197774. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  197775. for (j = 0; j < num_p_filters; j++)
  197776. {
  197777. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  197778. {
  197779. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  197780. PNG_WEIGHT_SHIFT;
  197781. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  197782. PNG_WEIGHT_SHIFT;
  197783. }
  197784. }
  197785. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  197786. PNG_COST_SHIFT;
  197787. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  197788. PNG_COST_SHIFT;
  197789. if (lmhi > PNG_HIMASK)
  197790. lmins = PNG_MAXSUM;
  197791. else
  197792. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  197793. }
  197794. #endif
  197795. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  197796. pp = prev_row + 1; i < bpp; i++)
  197797. {
  197798. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  197799. sum += (v < 128) ? v : 256 - v;
  197800. }
  197801. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  197802. {
  197803. int a, b, c, pa, pb, pc, p;
  197804. b = *pp++;
  197805. c = *cp++;
  197806. a = *lp++;
  197807. #ifndef PNG_SLOW_PAETH
  197808. p = b - c;
  197809. pc = a - c;
  197810. #ifdef PNG_USE_ABS
  197811. pa = abs(p);
  197812. pb = abs(pc);
  197813. pc = abs(p + pc);
  197814. #else
  197815. pa = p < 0 ? -p : p;
  197816. pb = pc < 0 ? -pc : pc;
  197817. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  197818. #endif
  197819. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  197820. #else /* PNG_SLOW_PAETH */
  197821. p = a + b - c;
  197822. pa = abs(p - a);
  197823. pb = abs(p - b);
  197824. pc = abs(p - c);
  197825. if (pa <= pb && pa <= pc)
  197826. p = a;
  197827. else if (pb <= pc)
  197828. p = b;
  197829. else
  197830. p = c;
  197831. #endif /* PNG_SLOW_PAETH */
  197832. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  197833. sum += (v < 128) ? v : 256 - v;
  197834. if (sum > lmins) /* We are already worse, don't continue. */
  197835. break;
  197836. }
  197837. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197838. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197839. {
  197840. int j;
  197841. png_uint_32 sumhi, sumlo;
  197842. sumlo = sum & PNG_LOMASK;
  197843. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  197844. for (j = 0; j < num_p_filters; j++)
  197845. {
  197846. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  197847. {
  197848. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  197849. PNG_WEIGHT_SHIFT;
  197850. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  197851. PNG_WEIGHT_SHIFT;
  197852. }
  197853. }
  197854. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  197855. PNG_COST_SHIFT;
  197856. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  197857. PNG_COST_SHIFT;
  197858. if (sumhi > PNG_HIMASK)
  197859. sum = PNG_MAXSUM;
  197860. else
  197861. sum = (sumhi << PNG_HISHIFT) + sumlo;
  197862. }
  197863. #endif
  197864. if (sum < mins)
  197865. {
  197866. best_row = png_ptr->paeth_row;
  197867. }
  197868. }
  197869. #endif /* PNG_NO_WRITE_FILTER */
  197870. /* Do the actual writing of the filtered row data from the chosen filter. */
  197871. png_write_filtered_row(png_ptr, best_row);
  197872. #ifndef PNG_NO_WRITE_FILTER
  197873. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197874. /* Save the type of filter we picked this time for future calculations */
  197875. if (png_ptr->num_prev_filters > 0)
  197876. {
  197877. int j;
  197878. for (j = 1; j < num_p_filters; j++)
  197879. {
  197880. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  197881. }
  197882. png_ptr->prev_filters[j] = best_row[0];
  197883. }
  197884. #endif
  197885. #endif /* PNG_NO_WRITE_FILTER */
  197886. }
  197887. /* Do the actual writing of a previously filtered row. */
  197888. void /* PRIVATE */
  197889. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  197890. {
  197891. png_debug(1, "in png_write_filtered_row\n");
  197892. png_debug1(2, "filter = %d\n", filtered_row[0]);
  197893. /* set up the zlib input buffer */
  197894. png_ptr->zstream.next_in = filtered_row;
  197895. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  197896. /* repeat until we have compressed all the data */
  197897. do
  197898. {
  197899. int ret; /* return of zlib */
  197900. /* compress the data */
  197901. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  197902. /* check for compression errors */
  197903. if (ret != Z_OK)
  197904. {
  197905. if (png_ptr->zstream.msg != NULL)
  197906. png_error(png_ptr, png_ptr->zstream.msg);
  197907. else
  197908. png_error(png_ptr, "zlib error");
  197909. }
  197910. /* see if it is time to write another IDAT */
  197911. if (!(png_ptr->zstream.avail_out))
  197912. {
  197913. /* write the IDAT and reset the zlib output buffer */
  197914. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  197915. png_ptr->zstream.next_out = png_ptr->zbuf;
  197916. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197917. }
  197918. /* repeat until all data has been compressed */
  197919. } while (png_ptr->zstream.avail_in);
  197920. /* swap the current and previous rows */
  197921. if (png_ptr->prev_row != NULL)
  197922. {
  197923. png_bytep tptr;
  197924. tptr = png_ptr->prev_row;
  197925. png_ptr->prev_row = png_ptr->row_buf;
  197926. png_ptr->row_buf = tptr;
  197927. }
  197928. /* finish row - updates counters and flushes zlib if last row */
  197929. png_write_finish_row(png_ptr);
  197930. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  197931. png_ptr->flush_rows++;
  197932. if (png_ptr->flush_dist > 0 &&
  197933. png_ptr->flush_rows >= png_ptr->flush_dist)
  197934. {
  197935. png_write_flush(png_ptr);
  197936. }
  197937. #endif
  197938. }
  197939. #endif /* PNG_WRITE_SUPPORTED */
  197940. /********* End of inlined file: pngwutil.c *********/
  197941. }
  197942. #else
  197943. #define PNG_INTERNAL
  197944. #define PNG_SETJMP_NOT_SUPPORTED
  197945. #include <png.h>
  197946. #include <pngconf.h>
  197947. #endif
  197948. }
  197949. #ifdef _MSC_VER
  197950. #pragma warning (pop)
  197951. #endif
  197952. BEGIN_JUCE_NAMESPACE
  197953. using namespace pnglibNamespace;
  197954. using ::calloc;
  197955. using ::malloc;
  197956. using ::free;
  197957. static void pngReadCallback (png_structp pngReadStruct, png_bytep data, png_size_t length) throw()
  197958. {
  197959. InputStream* const in = (InputStream*) png_get_io_ptr (pngReadStruct);
  197960. in->read (data, (int) length);
  197961. }
  197962. struct PNGErrorStruct {};
  197963. static void pngErrorCallback (png_structp, png_const_charp)
  197964. {
  197965. throw PNGErrorStruct();
  197966. }
  197967. Image* juce_loadPNGImageFromStream (InputStream& in) throw()
  197968. {
  197969. Image* image = 0;
  197970. png_structp pngReadStruct;
  197971. png_infop pngInfoStruct;
  197972. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  197973. if (pngReadStruct != 0)
  197974. {
  197975. pngInfoStruct = png_create_info_struct (pngReadStruct);
  197976. if (pngInfoStruct == 0)
  197977. {
  197978. png_destroy_read_struct (&pngReadStruct, 0, 0);
  197979. return 0;
  197980. }
  197981. png_set_error_fn (pngReadStruct, 0, pngErrorCallback, pngErrorCallback);
  197982. // read the header..
  197983. png_set_read_fn (pngReadStruct, &in, pngReadCallback);
  197984. png_uint_32 width, height;
  197985. int bitDepth, colorType, interlaceType;
  197986. png_read_info (pngReadStruct, pngInfoStruct);
  197987. png_get_IHDR (pngReadStruct, pngInfoStruct,
  197988. &width, &height,
  197989. &bitDepth, &colorType,
  197990. &interlaceType, 0, 0);
  197991. if (bitDepth == 16)
  197992. png_set_strip_16 (pngReadStruct);
  197993. if (colorType == PNG_COLOR_TYPE_PALETTE)
  197994. png_set_expand (pngReadStruct);
  197995. if (bitDepth < 8)
  197996. png_set_expand (pngReadStruct);
  197997. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  197998. png_set_expand (pngReadStruct);
  197999. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  198000. png_set_gray_to_rgb (pngReadStruct);
  198001. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  198002. const bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  198003. || pngInfoStruct->num_trans > 0;
  198004. // Load the image into a temp buffer in the pnglib format..
  198005. uint8* const tempBuffer = (uint8*) juce_malloc (height * (width << 2));
  198006. png_bytepp rows = (png_bytepp) juce_malloc (sizeof (png_bytep) * height);
  198007. int y;
  198008. for (y = (int) height; --y >= 0;)
  198009. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  198010. png_read_image (pngReadStruct, rows);
  198011. png_read_end (pngReadStruct, pngInfoStruct);
  198012. juce_free (rows);
  198013. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  198014. // now convert the data to a juce image format..
  198015. image = new Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  198016. width, height, hasAlphaChan);
  198017. int stride, pixelStride;
  198018. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  198019. uint8* srcRow = tempBuffer;
  198020. uint8* destRow = pixels;
  198021. for (y = 0; y < (int) height; ++y)
  198022. {
  198023. const uint8* src = srcRow;
  198024. srcRow += (width << 2);
  198025. uint8* dest = destRow;
  198026. destRow += stride;
  198027. if (hasAlphaChan)
  198028. {
  198029. for (int i = width; --i >= 0;)
  198030. {
  198031. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  198032. ((PixelARGB*) dest)->premultiply();
  198033. dest += pixelStride;
  198034. src += 4;
  198035. }
  198036. }
  198037. else
  198038. {
  198039. for (int i = width; --i >= 0;)
  198040. {
  198041. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  198042. dest += pixelStride;
  198043. src += 4;
  198044. }
  198045. }
  198046. }
  198047. image->releasePixelDataReadWrite (pixels);
  198048. juce_free (tempBuffer);
  198049. }
  198050. return image;
  198051. }
  198052. static void pngWriteDataCallback (png_structp png_ptr, png_bytep data, png_size_t length) throw()
  198053. {
  198054. OutputStream* const out = (OutputStream*) png_ptr->io_ptr;
  198055. const bool ok = out->write (data, length);
  198056. (void) ok;
  198057. jassert (ok);
  198058. }
  198059. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw()
  198060. {
  198061. const int width = image.getWidth();
  198062. const int height = image.getHeight();
  198063. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  198064. if (pngWriteStruct == 0)
  198065. return false;
  198066. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  198067. if (pngInfoStruct == 0)
  198068. {
  198069. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  198070. return false;
  198071. }
  198072. png_set_write_fn (pngWriteStruct, &out, pngWriteDataCallback, 0);
  198073. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  198074. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  198075. : PNG_COLOR_TYPE_RGB,
  198076. PNG_INTERLACE_NONE,
  198077. PNG_COMPRESSION_TYPE_BASE,
  198078. PNG_FILTER_TYPE_BASE);
  198079. png_bytep rowData = (png_bytep) juce_malloc (width * 4 * sizeof (png_byte));
  198080. png_color_8 sig_bit;
  198081. sig_bit.red = 8;
  198082. sig_bit.green = 8;
  198083. sig_bit.blue = 8;
  198084. sig_bit.alpha = 8;
  198085. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  198086. png_write_info (pngWriteStruct, pngInfoStruct);
  198087. png_set_shift (pngWriteStruct, &sig_bit);
  198088. png_set_packing (pngWriteStruct);
  198089. for (int y = 0; y < height; ++y)
  198090. {
  198091. uint8* dst = (uint8*) rowData;
  198092. int stride, pixelStride;
  198093. const uint8* pixels = image.lockPixelDataReadOnly (0, y, width, 1, stride, pixelStride);
  198094. const uint8* src = pixels;
  198095. if (image.hasAlphaChannel())
  198096. {
  198097. for (int i = width; --i >= 0;)
  198098. {
  198099. PixelARGB p (*(const PixelARGB*) src);
  198100. p.unpremultiply();
  198101. *dst++ = p.getRed();
  198102. *dst++ = p.getGreen();
  198103. *dst++ = p.getBlue();
  198104. *dst++ = p.getAlpha();
  198105. src += pixelStride;
  198106. }
  198107. }
  198108. else
  198109. {
  198110. for (int i = width; --i >= 0;)
  198111. {
  198112. *dst++ = ((const PixelRGB*) src)->getRed();
  198113. *dst++ = ((const PixelRGB*) src)->getGreen();
  198114. *dst++ = ((const PixelRGB*) src)->getBlue();
  198115. src += pixelStride;
  198116. }
  198117. }
  198118. png_write_rows (pngWriteStruct, &rowData, 1);
  198119. image.releasePixelDataReadOnly (pixels);
  198120. }
  198121. juce_free (rowData);
  198122. png_write_end (pngWriteStruct, pngInfoStruct);
  198123. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  198124. out.flush();
  198125. return true;
  198126. }
  198127. END_JUCE_NAMESPACE
  198128. /********* End of inlined file: juce_PNGLoader.cpp *********/
  198129. #endif
  198130. //==============================================================================
  198131. #if JUCE_WIN32
  198132. /********* Start of inlined file: juce_win32_NativeCode.cpp *********/
  198133. /*
  198134. This file wraps together all the win32-specific code, so that
  198135. we can include all the native headers just once, and compile all our
  198136. platform-specific stuff in one big lump, keeping it out of the way of
  198137. the rest of the codebase.
  198138. */
  198139. BEGIN_JUCE_NAMESPACE
  198140. #define JUCE_INCLUDED_FILE 1
  198141. // Now include the actual code files..
  198142. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  198143. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  198144. // compiled on its own).
  198145. #if JUCE_INCLUDED_FILE
  198146. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  198147. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198148. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198149. #ifndef DOXYGEN
  198150. // use with DynamicLibraryLoader to simplify importing functions
  198151. //
  198152. // functionName: function to import
  198153. // localFunctionName: name you want to use to actually call it (must be different)
  198154. // returnType: the return type
  198155. // object: the DynamicLibraryLoader to use
  198156. // params: list of params (bracketed)
  198157. //
  198158. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  198159. typedef returnType (WINAPI *type##localFunctionName) params; \
  198160. type##localFunctionName localFunctionName \
  198161. = (type##localFunctionName)object.findProcAddress (#functionName);
  198162. // loads and unloads a DLL automatically
  198163. class JUCE_API DynamicLibraryLoader
  198164. {
  198165. public:
  198166. DynamicLibraryLoader (const String& name);
  198167. ~DynamicLibraryLoader();
  198168. void* findProcAddress (const String& functionName);
  198169. private:
  198170. void* libHandle;
  198171. };
  198172. #endif
  198173. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198174. /********* End of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  198175. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  198176. {
  198177. libHandle = LoadLibrary (name);
  198178. }
  198179. DynamicLibraryLoader::~DynamicLibraryLoader()
  198180. {
  198181. FreeLibrary ((HMODULE) libHandle);
  198182. }
  198183. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  198184. {
  198185. return (void*) GetProcAddress ((HMODULE) libHandle, functionName);
  198186. }
  198187. #endif
  198188. /********* End of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  198189. /********* Start of inlined file: juce_win32_SystemStats.cpp *********/
  198190. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  198191. // compiled on its own).
  198192. #if JUCE_INCLUDED_FILE
  198193. extern void juce_updateMultiMonitorInfo() throw();
  198194. extern void juce_initialiseThreadEvents() throw();
  198195. void Logger::outputDebugString (const String& text) throw()
  198196. {
  198197. OutputDebugString (text + T("\n"));
  198198. }
  198199. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  198200. {
  198201. String text;
  198202. va_list args;
  198203. va_start (args, format);
  198204. text.vprintf(format, args);
  198205. outputDebugString (text);
  198206. }
  198207. static int64 hiResTicksPerSecond;
  198208. static double hiResTicksScaleFactor;
  198209. #if JUCE_USE_INTRINSICS
  198210. // CPU info functions using intrinsics...
  198211. #pragma intrinsic (__cpuid)
  198212. #pragma intrinsic (__rdtsc)
  198213. /*static unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0) throw()
  198214. {
  198215. int info [4];
  198216. __cpuid (info, 1);
  198217. if (familyModel != 0)
  198218. *familyModel = info [0];
  198219. if (extFeatures != 0)
  198220. *extFeatures = info[1];
  198221. return info[3];
  198222. }*/
  198223. const String SystemStats::getCpuVendor() throw()
  198224. {
  198225. int info [4];
  198226. __cpuid (info, 0);
  198227. char v [12];
  198228. memcpy (v, info + 1, 4);
  198229. memcpy (v + 4, info + 3, 4);
  198230. memcpy (v + 8, info + 2, 4);
  198231. return String (v, 12);
  198232. }
  198233. #else
  198234. // CPU info functions using old fashioned inline asm...
  198235. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0)
  198236. {
  198237. unsigned int cpu = 0;
  198238. unsigned int ext = 0;
  198239. unsigned int family = 0;
  198240. #if JUCE_GCC
  198241. unsigned int dummy = 0;
  198242. #endif
  198243. #ifndef __MINGW32__
  198244. __try
  198245. #endif
  198246. {
  198247. #if JUCE_GCC
  198248. __asm__ ("cpuid" : "=a" (family), "=b" (ext), "=c" (dummy),"=d" (cpu) : "a" (1));
  198249. #else
  198250. __asm
  198251. {
  198252. mov eax, 1
  198253. cpuid
  198254. mov cpu, edx
  198255. mov family, eax
  198256. mov ext, ebx
  198257. }
  198258. #endif
  198259. }
  198260. #ifndef __MINGW32__
  198261. __except (EXCEPTION_EXECUTE_HANDLER)
  198262. {
  198263. return 0;
  198264. }
  198265. #endif
  198266. if (familyModel != 0)
  198267. *familyModel = family;
  198268. if (extFeatures != 0)
  198269. *extFeatures = ext;
  198270. return cpu;
  198271. }*/
  198272. static void juce_getCpuVendor (char* const v)
  198273. {
  198274. int vendor[4];
  198275. zeromem (vendor, 16);
  198276. #ifdef JUCE_64BIT
  198277. #else
  198278. #ifndef __MINGW32__
  198279. __try
  198280. #endif
  198281. {
  198282. #if JUCE_GCC
  198283. unsigned int dummy = 0;
  198284. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  198285. #else
  198286. __asm
  198287. {
  198288. mov eax, 0
  198289. cpuid
  198290. mov [vendor], ebx
  198291. mov [vendor + 4], edx
  198292. mov [vendor + 8], ecx
  198293. }
  198294. #endif
  198295. }
  198296. #ifndef __MINGW32__
  198297. __except (EXCEPTION_EXECUTE_HANDLER)
  198298. {
  198299. *v = 0;
  198300. }
  198301. #endif
  198302. #endif
  198303. memcpy (v, vendor, 16);
  198304. }
  198305. const String SystemStats::getCpuVendor() throw()
  198306. {
  198307. char v [16];
  198308. juce_getCpuVendor (v);
  198309. return String (v, 16);
  198310. }
  198311. #endif
  198312. struct CPUFlags
  198313. {
  198314. bool hasMMX : 1;
  198315. bool hasSSE : 1;
  198316. bool hasSSE2 : 1;
  198317. bool has3DNow : 1;
  198318. };
  198319. static CPUFlags cpuFlags;
  198320. bool SystemStats::hasMMX() throw()
  198321. {
  198322. return cpuFlags.hasMMX;
  198323. }
  198324. bool SystemStats::hasSSE() throw()
  198325. {
  198326. return cpuFlags.hasSSE;
  198327. }
  198328. bool SystemStats::hasSSE2() throw()
  198329. {
  198330. return cpuFlags.hasSSE2;
  198331. }
  198332. bool SystemStats::has3DNow() throw()
  198333. {
  198334. return cpuFlags.has3DNow;
  198335. }
  198336. void SystemStats::initialiseStats() throw()
  198337. {
  198338. juce_initialiseThreadEvents();
  198339. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  198340. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  198341. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  198342. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  198343. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  198344. #else
  198345. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  198346. #endif
  198347. LARGE_INTEGER f;
  198348. QueryPerformanceFrequency (&f);
  198349. hiResTicksPerSecond = f.QuadPart;
  198350. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  198351. String s (SystemStats::getJUCEVersion());
  198352. #ifdef JUCE_DEBUG
  198353. const MMRESULT res = timeBeginPeriod (1);
  198354. jassert (res == TIMERR_NOERROR);
  198355. #else
  198356. timeBeginPeriod (1);
  198357. #endif
  198358. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  198359. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  198360. #endif
  198361. }
  198362. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  198363. {
  198364. OSVERSIONINFO info;
  198365. info.dwOSVersionInfoSize = sizeof (info);
  198366. GetVersionEx (&info);
  198367. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  198368. {
  198369. switch (info.dwMajorVersion)
  198370. {
  198371. case 5:
  198372. return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  198373. case 6:
  198374. return WinVista;
  198375. default:
  198376. jassertfalse // !! not a supported OS!
  198377. break;
  198378. }
  198379. }
  198380. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  198381. {
  198382. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  198383. return Win98;
  198384. }
  198385. return UnknownOS;
  198386. }
  198387. const String SystemStats::getOperatingSystemName() throw()
  198388. {
  198389. const char* name = "Unknown OS";
  198390. switch (getOperatingSystemType())
  198391. {
  198392. case WinVista:
  198393. name = "Windows Vista";
  198394. break;
  198395. case WinXP:
  198396. name = "Windows XP";
  198397. break;
  198398. case Win2000:
  198399. name = "Windows 2000";
  198400. break;
  198401. case Win98:
  198402. name = "Windows 98";
  198403. break;
  198404. default:
  198405. jassertfalse // !! new type of OS?
  198406. break;
  198407. }
  198408. return name;
  198409. }
  198410. bool SystemStats::isOperatingSystem64Bit() throw()
  198411. {
  198412. #ifdef _WIN64
  198413. return true;
  198414. #else
  198415. typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  198416. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  198417. BOOL isWow64 = FALSE;
  198418. return (fnIsWow64Process != 0)
  198419. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  198420. && (isWow64 != FALSE);
  198421. #endif
  198422. }
  198423. int SystemStats::getMemorySizeInMegabytes() throw()
  198424. {
  198425. MEMORYSTATUS mem;
  198426. GlobalMemoryStatus (&mem);
  198427. return (int) (mem.dwTotalPhys / (1024 * 1024)) + 1;
  198428. }
  198429. int SystemStats::getNumCpus() throw()
  198430. {
  198431. SYSTEM_INFO systemInfo;
  198432. GetSystemInfo (&systemInfo);
  198433. return systemInfo.dwNumberOfProcessors;
  198434. }
  198435. uint32 juce_millisecondsSinceStartup() throw()
  198436. {
  198437. return (uint32) GetTickCount();
  198438. }
  198439. int64 Time::getHighResolutionTicks() throw()
  198440. {
  198441. LARGE_INTEGER ticks;
  198442. QueryPerformanceCounter (&ticks);
  198443. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  198444. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  198445. // fix for a very obscure PCI hardware bug that can make the counter
  198446. // sometimes jump forwards by a few seconds..
  198447. static int64 hiResTicksOffset = 0;
  198448. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  198449. if (offsetDrift > (hiResTicksPerSecond >> 1))
  198450. hiResTicksOffset = newOffset;
  198451. return ticks.QuadPart + hiResTicksOffset;
  198452. }
  198453. double Time::getMillisecondCounterHiRes() throw()
  198454. {
  198455. return getHighResolutionTicks() * hiResTicksScaleFactor;
  198456. }
  198457. int64 Time::getHighResolutionTicksPerSecond() throw()
  198458. {
  198459. return hiResTicksPerSecond;
  198460. }
  198461. int64 SystemStats::getClockCycleCounter() throw()
  198462. {
  198463. #if JUCE_USE_INTRINSICS
  198464. // MS intrinsics version...
  198465. return __rdtsc();
  198466. #elif JUCE_GCC
  198467. // GNU inline asm version...
  198468. unsigned int hi = 0, lo = 0;
  198469. __asm__ __volatile__ (
  198470. "xor %%eax, %%eax \n\
  198471. xor %%edx, %%edx \n\
  198472. rdtsc \n\
  198473. movl %%eax, %[lo] \n\
  198474. movl %%edx, %[hi]"
  198475. :
  198476. : [hi] "m" (hi),
  198477. [lo] "m" (lo)
  198478. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  198479. return (int64) ((((uint64) hi) << 32) | lo);
  198480. #else
  198481. // MSVC inline asm version...
  198482. unsigned int hi = 0, lo = 0;
  198483. __asm
  198484. {
  198485. xor eax, eax
  198486. xor edx, edx
  198487. rdtsc
  198488. mov lo, eax
  198489. mov hi, edx
  198490. }
  198491. return (int64) ((((uint64) hi) << 32) | lo);
  198492. #endif
  198493. }
  198494. int SystemStats::getCpuSpeedInMegaherz() throw()
  198495. {
  198496. const int64 cycles = SystemStats::getClockCycleCounter();
  198497. const uint32 millis = Time::getMillisecondCounter();
  198498. int lastResult = 0;
  198499. for (;;)
  198500. {
  198501. int n = 1000000;
  198502. while (--n > 0) {}
  198503. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  198504. const int64 cyclesNow = SystemStats::getClockCycleCounter();
  198505. if (millisElapsed > 80)
  198506. {
  198507. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  198508. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  198509. return newResult;
  198510. lastResult = newResult;
  198511. }
  198512. }
  198513. }
  198514. bool Time::setSystemTimeToThisTime() const throw()
  198515. {
  198516. SYSTEMTIME st;
  198517. st.wDayOfWeek = 0;
  198518. st.wYear = (WORD) getYear();
  198519. st.wMonth = (WORD) (getMonth() + 1);
  198520. st.wDay = (WORD) getDayOfMonth();
  198521. st.wHour = (WORD) getHours();
  198522. st.wMinute = (WORD) getMinutes();
  198523. st.wSecond = (WORD) getSeconds();
  198524. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  198525. // do this twice because of daylight saving conversion problems - the
  198526. // first one sets it up, the second one kicks it in.
  198527. return SetLocalTime (&st) != 0
  198528. && SetLocalTime (&st) != 0;
  198529. }
  198530. int SystemStats::getPageSize() throw()
  198531. {
  198532. SYSTEM_INFO systemInfo;
  198533. GetSystemInfo (&systemInfo);
  198534. return systemInfo.dwPageSize;
  198535. }
  198536. #endif
  198537. /********* End of inlined file: juce_win32_SystemStats.cpp *********/
  198538. /********* Start of inlined file: juce_win32_Threads.cpp *********/
  198539. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  198540. // compiled on its own).
  198541. #if JUCE_INCLUDED_FILE
  198542. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198543. extern HWND juce_messageWindowHandle;
  198544. #endif
  198545. CriticalSection::CriticalSection() throw()
  198546. {
  198547. // (just to check the MS haven't changed this structure and broken things...)
  198548. #if _MSC_VER >= 1400
  198549. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  198550. #else
  198551. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  198552. #endif
  198553. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  198554. }
  198555. CriticalSection::~CriticalSection() throw()
  198556. {
  198557. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  198558. }
  198559. void CriticalSection::enter() const throw()
  198560. {
  198561. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  198562. }
  198563. bool CriticalSection::tryEnter() const throw()
  198564. {
  198565. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  198566. }
  198567. void CriticalSection::exit() const throw()
  198568. {
  198569. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  198570. }
  198571. WaitableEvent::WaitableEvent() throw()
  198572. : internal (CreateEvent (0, FALSE, FALSE, 0))
  198573. {
  198574. }
  198575. WaitableEvent::~WaitableEvent() throw()
  198576. {
  198577. CloseHandle (internal);
  198578. }
  198579. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  198580. {
  198581. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  198582. }
  198583. void WaitableEvent::signal() const throw()
  198584. {
  198585. SetEvent (internal);
  198586. }
  198587. void WaitableEvent::reset() const throw()
  198588. {
  198589. ResetEvent (internal);
  198590. }
  198591. void JUCE_API juce_threadEntryPoint (void*);
  198592. static unsigned int __stdcall threadEntryProc (void* userData) throw()
  198593. {
  198594. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198595. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  198596. GetCurrentThreadId(), TRUE);
  198597. #endif
  198598. juce_threadEntryPoint (userData);
  198599. _endthreadex (0);
  198600. return 0;
  198601. }
  198602. void juce_CloseThreadHandle (void* handle) throw()
  198603. {
  198604. CloseHandle ((HANDLE) handle);
  198605. }
  198606. void* juce_createThread (void* userData) throw()
  198607. {
  198608. unsigned int threadId;
  198609. return (void*) _beginthreadex (0, 0,
  198610. &threadEntryProc,
  198611. userData,
  198612. 0, &threadId);
  198613. }
  198614. void juce_killThread (void* handle) throw()
  198615. {
  198616. if (handle != 0)
  198617. {
  198618. #ifdef JUCE_DEBUG
  198619. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  198620. #endif
  198621. TerminateThread (handle, 0);
  198622. }
  198623. }
  198624. void juce_setCurrentThreadName (const String& name) throw()
  198625. {
  198626. #if defined (JUCE_DEBUG) && JUCE_MSVC
  198627. struct
  198628. {
  198629. DWORD dwType;
  198630. LPCSTR szName;
  198631. DWORD dwThreadID;
  198632. DWORD dwFlags;
  198633. } info;
  198634. info.dwType = 0x1000;
  198635. info.szName = name;
  198636. info.dwThreadID = GetCurrentThreadId();
  198637. info.dwFlags = 0;
  198638. #define MS_VC_EXCEPTION 0x406d1388
  198639. __try
  198640. {
  198641. RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  198642. }
  198643. __except (EXCEPTION_CONTINUE_EXECUTION)
  198644. {}
  198645. #else
  198646. (void) name;
  198647. #endif
  198648. }
  198649. Thread::ThreadID Thread::getCurrentThreadId() throw()
  198650. {
  198651. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  198652. }
  198653. // priority 1 to 10 where 5=normal, 1=low
  198654. bool juce_setThreadPriority (void* threadHandle, int priority) throw()
  198655. {
  198656. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  198657. if (priority < 1)
  198658. pri = THREAD_PRIORITY_IDLE;
  198659. else if (priority < 2)
  198660. pri = THREAD_PRIORITY_LOWEST;
  198661. else if (priority < 5)
  198662. pri = THREAD_PRIORITY_BELOW_NORMAL;
  198663. else if (priority < 7)
  198664. pri = THREAD_PRIORITY_NORMAL;
  198665. else if (priority < 9)
  198666. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  198667. else if (priority < 10)
  198668. pri = THREAD_PRIORITY_HIGHEST;
  198669. if (threadHandle == 0)
  198670. threadHandle = GetCurrentThread();
  198671. return SetThreadPriority (threadHandle, pri) != FALSE;
  198672. }
  198673. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  198674. {
  198675. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  198676. }
  198677. static HANDLE sleepEvent = 0;
  198678. void juce_initialiseThreadEvents() throw()
  198679. {
  198680. if (sleepEvent == 0)
  198681. #ifdef JUCE_DEBUG
  198682. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  198683. #else
  198684. sleepEvent = CreateEvent (0, 0, 0, 0);
  198685. #endif
  198686. }
  198687. void Thread::yield() throw()
  198688. {
  198689. Sleep (0);
  198690. }
  198691. void JUCE_CALLTYPE Thread::sleep (const int millisecs) throw()
  198692. {
  198693. if (millisecs >= 10)
  198694. {
  198695. Sleep (millisecs);
  198696. }
  198697. else
  198698. {
  198699. jassert (sleepEvent != 0);
  198700. // unlike Sleep() this is guaranteed to return to the current thread after
  198701. // the time expires, so we'll use this for short waits, which are more likely
  198702. // to need to be accurate
  198703. WaitForSingleObject (sleepEvent, millisecs);
  198704. }
  198705. }
  198706. static int lastProcessPriority = -1;
  198707. // called by WindowDriver because Windows does wierd things to process priority
  198708. // when you swap apps, and this forces an update when the app is brought to the front.
  198709. void juce_repeatLastProcessPriority() throw()
  198710. {
  198711. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  198712. {
  198713. DWORD p;
  198714. switch (lastProcessPriority)
  198715. {
  198716. case Process::LowPriority:
  198717. p = IDLE_PRIORITY_CLASS;
  198718. break;
  198719. case Process::NormalPriority:
  198720. p = NORMAL_PRIORITY_CLASS;
  198721. break;
  198722. case Process::HighPriority:
  198723. p = HIGH_PRIORITY_CLASS;
  198724. break;
  198725. case Process::RealtimePriority:
  198726. p = REALTIME_PRIORITY_CLASS;
  198727. break;
  198728. default:
  198729. jassertfalse // bad priority value
  198730. return;
  198731. }
  198732. SetPriorityClass (GetCurrentProcess(), p);
  198733. }
  198734. }
  198735. void Process::setPriority (ProcessPriority prior)
  198736. {
  198737. if (lastProcessPriority != (int) prior)
  198738. {
  198739. lastProcessPriority = (int) prior;
  198740. juce_repeatLastProcessPriority();
  198741. }
  198742. }
  198743. bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  198744. {
  198745. return IsDebuggerPresent() != FALSE;
  198746. }
  198747. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  198748. {
  198749. return juce_isRunningUnderDebugger();
  198750. }
  198751. void Process::raisePrivilege()
  198752. {
  198753. jassertfalse // xxx not implemented
  198754. }
  198755. void Process::lowerPrivilege()
  198756. {
  198757. jassertfalse // xxx not implemented
  198758. }
  198759. void Process::terminate()
  198760. {
  198761. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  198762. _CrtDumpMemoryLeaks();
  198763. #endif
  198764. // bullet in the head in case there's a problem shutting down..
  198765. ExitProcess (0);
  198766. }
  198767. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  198768. {
  198769. void* result = 0;
  198770. JUCE_TRY
  198771. {
  198772. result = (void*) LoadLibrary (name);
  198773. }
  198774. JUCE_CATCH_ALL
  198775. return result;
  198776. }
  198777. void PlatformUtilities::freeDynamicLibrary (void* h)
  198778. {
  198779. JUCE_TRY
  198780. {
  198781. if (h != 0)
  198782. FreeLibrary ((HMODULE) h);
  198783. }
  198784. JUCE_CATCH_ALL
  198785. }
  198786. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  198787. {
  198788. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name)
  198789. : 0;
  198790. }
  198791. InterProcessLock::InterProcessLock (const String& name_) throw()
  198792. : internal (0),
  198793. name (name_),
  198794. reentrancyLevel (0)
  198795. {
  198796. }
  198797. InterProcessLock::~InterProcessLock() throw()
  198798. {
  198799. exit();
  198800. }
  198801. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  198802. {
  198803. if (reentrancyLevel++ == 0)
  198804. {
  198805. internal = CreateMutex (0, TRUE, name);
  198806. if (internal != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  198807. {
  198808. if (timeOutMillisecs == 0
  198809. || WaitForSingleObject (internal, (timeOutMillisecs < 0) ? INFINITE : timeOutMillisecs)
  198810. == WAIT_TIMEOUT)
  198811. {
  198812. ReleaseMutex (internal);
  198813. CloseHandle (internal);
  198814. internal = 0;
  198815. }
  198816. }
  198817. }
  198818. return (internal != 0);
  198819. }
  198820. void InterProcessLock::exit() throw()
  198821. {
  198822. if (--reentrancyLevel == 0 && internal != 0)
  198823. {
  198824. ReleaseMutex (internal);
  198825. CloseHandle (internal);
  198826. internal = 0;
  198827. }
  198828. }
  198829. #endif
  198830. /********* End of inlined file: juce_win32_Threads.cpp *********/
  198831. /********* Start of inlined file: juce_win32_Files.cpp *********/
  198832. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  198833. // compiled on its own).
  198834. #if JUCE_INCLUDED_FILE
  198835. #ifndef CSIDL_MYMUSIC
  198836. #define CSIDL_MYMUSIC 0x000d
  198837. #endif
  198838. #ifndef CSIDL_MYVIDEO
  198839. #define CSIDL_MYVIDEO 0x000e
  198840. #endif
  198841. const tchar File::separator = T('\\');
  198842. const tchar* File::separatorString = T("\\");
  198843. bool juce_fileExists (const String& fileName,
  198844. const bool dontCountDirectories) throw()
  198845. {
  198846. if (fileName.isEmpty())
  198847. return false;
  198848. const DWORD attr = GetFileAttributes (fileName);
  198849. return dontCountDirectories ? ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
  198850. : (attr != 0xffffffff);
  198851. }
  198852. bool juce_isDirectory (const String& fileName) throw()
  198853. {
  198854. const DWORD attr = GetFileAttributes (fileName);
  198855. return (attr != 0xffffffff)
  198856. && ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
  198857. }
  198858. bool juce_canWriteToFile (const String& fileName) throw()
  198859. {
  198860. const DWORD attr = GetFileAttributes (fileName);
  198861. return ((attr & FILE_ATTRIBUTE_READONLY) == 0);
  198862. }
  198863. bool juce_setFileReadOnly (const String& fileName,
  198864. bool isReadOnly) throw()
  198865. {
  198866. DWORD attr = GetFileAttributes (fileName);
  198867. if (attr == 0xffffffff)
  198868. return false;
  198869. if (isReadOnly != juce_canWriteToFile (fileName))
  198870. return true;
  198871. if (isReadOnly)
  198872. attr |= FILE_ATTRIBUTE_READONLY;
  198873. else
  198874. attr &= ~FILE_ATTRIBUTE_READONLY;
  198875. return SetFileAttributes (fileName, attr) != FALSE;
  198876. }
  198877. bool File::isHidden() const throw()
  198878. {
  198879. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  198880. }
  198881. bool juce_deleteFile (const String& fileName) throw()
  198882. {
  198883. if (juce_isDirectory (fileName))
  198884. return RemoveDirectory (fileName) != 0;
  198885. return DeleteFile (fileName) != 0;
  198886. }
  198887. bool File::moveToTrash() const throw()
  198888. {
  198889. if (! exists())
  198890. return true;
  198891. SHFILEOPSTRUCT fos;
  198892. zerostruct (fos);
  198893. // The string we pass in must be double null terminated..
  198894. String doubleNullTermPath (getFullPathName() + " ");
  198895. TCHAR* p = (TCHAR*) (const TCHAR*) doubleNullTermPath;
  198896. p [getFullPathName().length()] = 0;
  198897. fos.wFunc = FO_DELETE;
  198898. fos.hwnd = (HWND) 0;
  198899. fos.pFrom = p;
  198900. fos.pTo = NULL;
  198901. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  198902. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  198903. return SHFileOperation (&fos) == 0;
  198904. }
  198905. bool juce_moveFile (const String& source, const String& dest) throw()
  198906. {
  198907. return MoveFile (source, dest) != 0;
  198908. }
  198909. bool juce_copyFile (const String& source, const String& dest) throw()
  198910. {
  198911. return CopyFile (source, dest, false) != 0;
  198912. }
  198913. void juce_createDirectory (const String& fileName) throw()
  198914. {
  198915. if (! juce_fileExists (fileName, true))
  198916. {
  198917. CreateDirectory (fileName, 0);
  198918. }
  198919. }
  198920. // return 0 if not possible
  198921. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  198922. {
  198923. HANDLE h;
  198924. if (forWriting)
  198925. {
  198926. h = CreateFile (fileName, GENERIC_WRITE, FILE_SHARE_READ, 0,
  198927. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  198928. if (h != INVALID_HANDLE_VALUE)
  198929. SetFilePointer (h, 0, 0, FILE_END);
  198930. else
  198931. h = 0;
  198932. }
  198933. else
  198934. {
  198935. h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  198936. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  198937. if (h == INVALID_HANDLE_VALUE)
  198938. h = 0;
  198939. }
  198940. return (void*) h;
  198941. }
  198942. void juce_fileClose (void* handle) throw()
  198943. {
  198944. CloseHandle (handle);
  198945. }
  198946. int juce_fileRead (void* handle, void* buffer, int size) throw()
  198947. {
  198948. DWORD num = 0;
  198949. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  198950. return num;
  198951. }
  198952. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  198953. {
  198954. DWORD num;
  198955. WriteFile ((HANDLE) handle,
  198956. buffer, size,
  198957. &num, 0);
  198958. return num;
  198959. }
  198960. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  198961. {
  198962. LARGE_INTEGER li;
  198963. li.QuadPart = pos;
  198964. li.LowPart = SetFilePointer ((HANDLE) handle,
  198965. li.LowPart,
  198966. &li.HighPart,
  198967. FILE_BEGIN); // (returns -1 if it fails)
  198968. return li.QuadPart;
  198969. }
  198970. int64 juce_fileGetPosition (void* handle) throw()
  198971. {
  198972. LARGE_INTEGER li;
  198973. li.QuadPart = 0;
  198974. li.LowPart = SetFilePointer ((HANDLE) handle,
  198975. 0, &li.HighPart,
  198976. FILE_CURRENT); // (returns -1 if it fails)
  198977. return jmax ((int64) 0, li.QuadPart);
  198978. }
  198979. void juce_fileFlush (void* handle) throw()
  198980. {
  198981. FlushFileBuffers ((HANDLE) handle);
  198982. }
  198983. int64 juce_getFileSize (const String& fileName) throw()
  198984. {
  198985. WIN32_FILE_ATTRIBUTE_DATA attributes;
  198986. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  198987. {
  198988. return (((int64) attributes.nFileSizeHigh) << 32)
  198989. | attributes.nFileSizeLow;
  198990. }
  198991. return 0;
  198992. }
  198993. static int64 fileTimeToTime (const FILETIME* const ft) throw()
  198994. {
  198995. // tell me if this fails!
  198996. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME));
  198997. #if JUCE_GCC
  198998. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000LL) / 10000;
  198999. #else
  199000. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000) / 10000;
  199001. #endif
  199002. }
  199003. static void timeToFileTime (const int64 time, FILETIME* const ft) throw()
  199004. {
  199005. #if JUCE_GCC
  199006. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000LL;
  199007. #else
  199008. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000;
  199009. #endif
  199010. }
  199011. void juce_getFileTimes (const String& fileName,
  199012. int64& modificationTime,
  199013. int64& accessTime,
  199014. int64& creationTime) throw()
  199015. {
  199016. WIN32_FILE_ATTRIBUTE_DATA attributes;
  199017. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  199018. {
  199019. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  199020. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  199021. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  199022. }
  199023. else
  199024. {
  199025. creationTime = accessTime = modificationTime = 0;
  199026. }
  199027. }
  199028. bool juce_setFileTimes (const String& fileName,
  199029. int64 modificationTime,
  199030. int64 accessTime,
  199031. int64 creationTime) throw()
  199032. {
  199033. FILETIME m, a, c;
  199034. if (modificationTime > 0)
  199035. timeToFileTime (modificationTime, &m);
  199036. if (accessTime > 0)
  199037. timeToFileTime (accessTime, &a);
  199038. if (creationTime > 0)
  199039. timeToFileTime (creationTime, &c);
  199040. void* const h = juce_fileOpen (fileName, true);
  199041. bool ok = false;
  199042. if (h != 0)
  199043. {
  199044. ok = SetFileTime ((HANDLE) h,
  199045. (creationTime > 0) ? &c : 0,
  199046. (accessTime > 0) ? &a : 0,
  199047. (modificationTime > 0) ? &m : 0) != 0;
  199048. juce_fileClose (h);
  199049. }
  199050. return ok;
  199051. }
  199052. // return '\0' separated list of strings
  199053. const StringArray juce_getFileSystemRoots() throw()
  199054. {
  199055. TCHAR buffer [2048];
  199056. buffer[0] = 0;
  199057. buffer[1] = 0;
  199058. GetLogicalDriveStrings (2048, buffer);
  199059. TCHAR* n = buffer;
  199060. StringArray roots;
  199061. while (*n != 0)
  199062. {
  199063. roots.add (String (n));
  199064. while (*n++ != 0)
  199065. {
  199066. }
  199067. }
  199068. roots.sort (true);
  199069. return roots;
  199070. }
  199071. const String juce_getVolumeLabel (const String& filenameOnVolume,
  199072. int& volumeSerialNumber) throw()
  199073. {
  199074. TCHAR n [4];
  199075. n[0] = *(const TCHAR*) filenameOnVolume;
  199076. n[1] = L':';
  199077. n[2] = L'\\';
  199078. n[3] = 0;
  199079. TCHAR dest [64];
  199080. DWORD serialNum;
  199081. if (! GetVolumeInformation (n, dest, 64, (DWORD*) &serialNum, 0, 0, 0, 0))
  199082. {
  199083. dest[0] = 0;
  199084. serialNum = 0;
  199085. }
  199086. volumeSerialNumber = serialNum;
  199087. return String (dest);
  199088. }
  199089. static int64 getDiskSpaceInfo (String fn, const bool total) throw()
  199090. {
  199091. if (fn[1] == T(':'))
  199092. fn = fn.substring (0, 2) + T("\\");
  199093. ULARGE_INTEGER spc, tot, totFree;
  199094. if (GetDiskFreeSpaceEx (fn, &spc, &tot, &totFree))
  199095. return (int64) (total ? tot.QuadPart
  199096. : spc.QuadPart);
  199097. return 0;
  199098. }
  199099. int64 File::getBytesFreeOnVolume() const throw()
  199100. {
  199101. return getDiskSpaceInfo (getFullPathName(), false);
  199102. }
  199103. int64 File::getVolumeTotalSize() const throw()
  199104. {
  199105. return getDiskSpaceInfo (getFullPathName(), true);
  199106. }
  199107. static unsigned int getWindowsDriveType (const String& fileName) throw()
  199108. {
  199109. TCHAR n[4];
  199110. n[0] = *(const TCHAR*) fileName;
  199111. n[1] = L':';
  199112. n[2] = L'\\';
  199113. n[3] = 0;
  199114. return GetDriveType (n);
  199115. }
  199116. bool File::isOnCDRomDrive() const throw()
  199117. {
  199118. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  199119. }
  199120. bool File::isOnHardDisk() const throw()
  199121. {
  199122. if (fullPath.isEmpty())
  199123. return false;
  199124. const unsigned int n = getWindowsDriveType (getFullPathName());
  199125. if (fullPath.toLowerCase()[0] <= 'b'
  199126. && fullPath[1] == T(':'))
  199127. {
  199128. return n != DRIVE_REMOVABLE;
  199129. }
  199130. else
  199131. {
  199132. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  199133. }
  199134. }
  199135. bool File::isOnRemovableDrive() const throw()
  199136. {
  199137. if (fullPath.isEmpty())
  199138. return false;
  199139. const unsigned int n = getWindowsDriveType (getFullPathName());
  199140. return n == DRIVE_CDROM
  199141. || n == DRIVE_REMOTE
  199142. || n == DRIVE_REMOVABLE
  199143. || n == DRIVE_RAMDISK;
  199144. }
  199145. #define MAX_PATH_CHARS (MAX_PATH + 256)
  199146. static const File juce_getSpecialFolderPath (int type) throw()
  199147. {
  199148. WCHAR path [MAX_PATH_CHARS];
  199149. if (SHGetSpecialFolderPath (0, path, type, 0))
  199150. return File (String (path));
  199151. return File::nonexistent;
  199152. }
  199153. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  199154. {
  199155. int csidlType = 0;
  199156. switch (type)
  199157. {
  199158. case userHomeDirectory:
  199159. case userDocumentsDirectory:
  199160. csidlType = CSIDL_PERSONAL;
  199161. break;
  199162. case userDesktopDirectory:
  199163. csidlType = CSIDL_DESKTOP;
  199164. break;
  199165. case userApplicationDataDirectory:
  199166. csidlType = CSIDL_APPDATA;
  199167. break;
  199168. case commonApplicationDataDirectory:
  199169. csidlType = CSIDL_COMMON_APPDATA;
  199170. break;
  199171. case globalApplicationsDirectory:
  199172. csidlType = CSIDL_PROGRAM_FILES;
  199173. break;
  199174. case userMusicDirectory:
  199175. csidlType = CSIDL_MYMUSIC;
  199176. break;
  199177. case userMoviesDirectory:
  199178. csidlType = CSIDL_MYVIDEO;
  199179. break;
  199180. case tempDirectory:
  199181. {
  199182. WCHAR dest [2048];
  199183. dest[0] = 0;
  199184. GetTempPath (2048, dest);
  199185. return File (String (dest));
  199186. }
  199187. case currentExecutableFile:
  199188. case currentApplicationFile:
  199189. {
  199190. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  199191. WCHAR dest [MAX_PATH_CHARS];
  199192. dest[0] = 0;
  199193. GetModuleFileName (moduleHandle, dest, MAX_PATH_CHARS);
  199194. return File (String (dest));
  199195. }
  199196. break;
  199197. default:
  199198. jassertfalse // unknown type?
  199199. return File::nonexistent;
  199200. }
  199201. return juce_getSpecialFolderPath (csidlType);
  199202. }
  199203. const File File::getCurrentWorkingDirectory() throw()
  199204. {
  199205. WCHAR dest [MAX_PATH_CHARS];
  199206. dest[0] = 0;
  199207. GetCurrentDirectory (MAX_PATH_CHARS, dest);
  199208. return File (String (dest));
  199209. }
  199210. bool File::setAsCurrentWorkingDirectory() const throw()
  199211. {
  199212. return SetCurrentDirectory (getFullPathName()) != FALSE;
  199213. }
  199214. const String File::getVersion() const throw()
  199215. {
  199216. String result;
  199217. DWORD handle = 0;
  199218. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  199219. void* buffer = juce_calloc (bufferSize);
  199220. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  199221. {
  199222. VS_FIXEDFILEINFO* vffi;
  199223. UINT len = 0;
  199224. if (VerQueryValue (buffer, _T("\\"), (LPVOID*) &vffi, &len))
  199225. {
  199226. result.printf (T("%d.%d.%d.%d"),
  199227. HIWORD (vffi->dwFileVersionMS),
  199228. LOWORD (vffi->dwFileVersionMS),
  199229. HIWORD (vffi->dwFileVersionLS),
  199230. LOWORD (vffi->dwFileVersionLS));
  199231. }
  199232. }
  199233. juce_free (buffer);
  199234. return result;
  199235. }
  199236. const File File::getLinkedTarget() const throw()
  199237. {
  199238. File result (*this);
  199239. String p (getFullPathName());
  199240. if (! exists())
  199241. p += T(".lnk");
  199242. else if (getFileExtension() != T(".lnk"))
  199243. return result;
  199244. ComSmartPtr <IShellLink> shellLink;
  199245. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink, CLSCTX_INPROC_SERVER)))
  199246. {
  199247. ComSmartPtr <IPersistFile> persistFile;
  199248. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  199249. {
  199250. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  199251. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  199252. {
  199253. WIN32_FIND_DATA winFindData;
  199254. WCHAR resolvedPath [MAX_PATH];
  199255. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  199256. result = File (resolvedPath);
  199257. }
  199258. }
  199259. }
  199260. return result;
  199261. }
  199262. template <class FindDataType>
  199263. static void getFindFileInfo (FindDataType& findData,
  199264. String& filename, bool* const isDir, bool* const isHidden,
  199265. int64* const fileSize, Time* const modTime, Time* const creationTime,
  199266. bool* const isReadOnly) throw()
  199267. {
  199268. filename = findData.cFileName;
  199269. if (isDir != 0)
  199270. *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  199271. if (isHidden != 0)
  199272. *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  199273. if (fileSize != 0)
  199274. *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  199275. if (modTime != 0)
  199276. *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  199277. if (creationTime != 0)
  199278. *creationTime = fileTimeToTime (&findData.ftCreationTime);
  199279. if (isReadOnly != 0)
  199280. *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  199281. }
  199282. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResult,
  199283. bool* isDir, bool* isHidden, int64* fileSize,
  199284. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  199285. {
  199286. String wc (directory);
  199287. if (! wc.endsWithChar (File::separator))
  199288. wc += File::separator;
  199289. wc += wildCard;
  199290. WIN32_FIND_DATA findData;
  199291. HANDLE h = FindFirstFile (wc, &findData);
  199292. if (h != INVALID_HANDLE_VALUE)
  199293. {
  199294. getFindFileInfo (findData, firstResult, isDir, isHidden, fileSize,
  199295. modTime, creationTime, isReadOnly);
  199296. return h;
  199297. }
  199298. firstResult = String::empty;
  199299. return 0;
  199300. }
  199301. bool juce_findFileNext (void* handle, String& resultFile,
  199302. bool* isDir, bool* isHidden, int64* fileSize,
  199303. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  199304. {
  199305. WIN32_FIND_DATA findData;
  199306. if (handle != 0 && FindNextFile ((HANDLE) handle, &findData) != 0)
  199307. {
  199308. getFindFileInfo (findData, resultFile, isDir, isHidden, fileSize,
  199309. modTime, creationTime, isReadOnly);
  199310. return true;
  199311. }
  199312. resultFile = String::empty;
  199313. return false;
  199314. }
  199315. void juce_findFileClose (void* handle) throw()
  199316. {
  199317. FindClose (handle);
  199318. }
  199319. bool juce_launchFile (const String& fileName,
  199320. const String& parameters) throw()
  199321. {
  199322. HINSTANCE hInstance = 0;
  199323. JUCE_TRY
  199324. {
  199325. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  199326. }
  199327. JUCE_CATCH_ALL
  199328. return hInstance > (HINSTANCE) 32;
  199329. }
  199330. struct NamedPipeInternal
  199331. {
  199332. HANDLE pipeH;
  199333. HANDLE cancelEvent;
  199334. bool connected, createdPipe;
  199335. NamedPipeInternal()
  199336. : pipeH (0),
  199337. cancelEvent (0),
  199338. connected (false),
  199339. createdPipe (false)
  199340. {
  199341. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  199342. }
  199343. ~NamedPipeInternal()
  199344. {
  199345. disconnect();
  199346. if (pipeH != 0)
  199347. CloseHandle (pipeH);
  199348. CloseHandle (cancelEvent);
  199349. }
  199350. bool connect (const int timeOutMs)
  199351. {
  199352. if (! createdPipe)
  199353. return true;
  199354. if (! connected)
  199355. {
  199356. OVERLAPPED over;
  199357. zerostruct (over);
  199358. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  199359. if (ConnectNamedPipe (pipeH, &over))
  199360. {
  199361. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  199362. }
  199363. else
  199364. {
  199365. const int err = GetLastError();
  199366. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  199367. {
  199368. HANDLE handles[] = { over.hEvent, cancelEvent };
  199369. if (WaitForMultipleObjects (2, handles, FALSE,
  199370. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  199371. connected = true;
  199372. }
  199373. else if (err == ERROR_PIPE_CONNECTED)
  199374. {
  199375. connected = true;
  199376. }
  199377. }
  199378. CloseHandle (over.hEvent);
  199379. }
  199380. return connected;
  199381. }
  199382. void disconnect()
  199383. {
  199384. if (connected)
  199385. {
  199386. DisconnectNamedPipe (pipeH);
  199387. connected = false;
  199388. }
  199389. }
  199390. };
  199391. void NamedPipe::close()
  199392. {
  199393. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  199394. delete intern;
  199395. internal = 0;
  199396. }
  199397. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  199398. {
  199399. close();
  199400. NamedPipeInternal* const intern = new NamedPipeInternal();
  199401. String file ("\\\\.\\pipe\\");
  199402. file += pipeName;
  199403. intern->createdPipe = createPipe;
  199404. if (createPipe)
  199405. {
  199406. intern->pipeH = CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  199407. PIPE_UNLIMITED_INSTANCES,
  199408. 4096, 4096, 0, NULL);
  199409. }
  199410. else
  199411. {
  199412. intern->pipeH = CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
  199413. FILE_FLAG_OVERLAPPED, 0);
  199414. }
  199415. if (intern->pipeH != INVALID_HANDLE_VALUE)
  199416. {
  199417. internal = intern;
  199418. return true;
  199419. }
  199420. delete intern;
  199421. return false;
  199422. }
  199423. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  199424. {
  199425. int bytesRead = -1;
  199426. bool waitAgain = true;
  199427. while (waitAgain && internal != 0)
  199428. {
  199429. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  199430. waitAgain = false;
  199431. if (! intern->connect (timeOutMilliseconds))
  199432. break;
  199433. if (maxBytesToRead <= 0)
  199434. return 0;
  199435. OVERLAPPED over;
  199436. zerostruct (over);
  199437. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  199438. unsigned long numRead;
  199439. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  199440. {
  199441. bytesRead = (int) numRead;
  199442. }
  199443. else if (GetLastError() == ERROR_IO_PENDING)
  199444. {
  199445. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  199446. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  199447. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  199448. : INFINITE);
  199449. if (waitResult != WAIT_OBJECT_0)
  199450. {
  199451. // if the operation timed out, let's cancel it...
  199452. CancelIo (intern->pipeH);
  199453. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  199454. }
  199455. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  199456. {
  199457. bytesRead = (int) numRead;
  199458. }
  199459. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  199460. {
  199461. intern->disconnect();
  199462. waitAgain = true;
  199463. }
  199464. }
  199465. else
  199466. {
  199467. waitAgain = internal != 0;
  199468. Sleep (5);
  199469. }
  199470. CloseHandle (over.hEvent);
  199471. }
  199472. return bytesRead;
  199473. }
  199474. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  199475. {
  199476. int bytesWritten = -1;
  199477. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  199478. if (intern != 0 && intern->connect (timeOutMilliseconds))
  199479. {
  199480. if (numBytesToWrite <= 0)
  199481. return 0;
  199482. OVERLAPPED over;
  199483. zerostruct (over);
  199484. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  199485. unsigned long numWritten;
  199486. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  199487. {
  199488. bytesWritten = (int) numWritten;
  199489. }
  199490. else if (GetLastError() == ERROR_IO_PENDING)
  199491. {
  199492. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  199493. DWORD waitResult;
  199494. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  199495. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  199496. : INFINITE);
  199497. if (waitResult != WAIT_OBJECT_0)
  199498. {
  199499. CancelIo (intern->pipeH);
  199500. WaitForSingleObject (over.hEvent, INFINITE);
  199501. }
  199502. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  199503. {
  199504. bytesWritten = (int) numWritten;
  199505. }
  199506. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  199507. {
  199508. intern->disconnect();
  199509. }
  199510. }
  199511. CloseHandle (over.hEvent);
  199512. }
  199513. return bytesWritten;
  199514. }
  199515. void NamedPipe::cancelPendingReads()
  199516. {
  199517. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  199518. if (intern != 0)
  199519. SetEvent (intern->cancelEvent);
  199520. }
  199521. #endif
  199522. /********* End of inlined file: juce_win32_Files.cpp *********/
  199523. /********* Start of inlined file: juce_win32_Network.cpp *********/
  199524. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199525. // compiled on its own).
  199526. #if JUCE_INCLUDED_FILE
  199527. #ifndef INTERNET_FLAG_NEED_FILE
  199528. #define INTERNET_FLAG_NEED_FILE 0x00000010
  199529. #endif
  199530. bool juce_isOnLine()
  199531. {
  199532. DWORD connectionType;
  199533. return InternetGetConnectedState (&connectionType, 0) != 0
  199534. || (connectionType & (INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_PROXY)) != 0;
  199535. }
  199536. struct ConnectionAndRequestStruct
  199537. {
  199538. HINTERNET connection, request;
  199539. };
  199540. static HINTERNET sessionHandle = 0;
  199541. void* juce_openInternetFile (const String& url,
  199542. const String& headers,
  199543. const MemoryBlock& postData,
  199544. const bool isPost,
  199545. URL::OpenStreamProgressCallback* callback,
  199546. void* callbackContext,
  199547. int timeOutMs)
  199548. {
  199549. if (sessionHandle == 0)
  199550. sessionHandle = InternetOpen (_T("juce"),
  199551. INTERNET_OPEN_TYPE_PRECONFIG,
  199552. 0, 0, 0);
  199553. if (sessionHandle != 0)
  199554. {
  199555. // break up the url..
  199556. TCHAR file[1024], server[1024];
  199557. URL_COMPONENTS uc;
  199558. zerostruct (uc);
  199559. uc.dwStructSize = sizeof (uc);
  199560. uc.dwUrlPathLength = sizeof (file);
  199561. uc.dwHostNameLength = sizeof (server);
  199562. uc.lpszUrlPath = file;
  199563. uc.lpszHostName = server;
  199564. if (InternetCrackUrl (url, 0, 0, &uc))
  199565. {
  199566. if (timeOutMs == 0)
  199567. timeOutMs = 30000;
  199568. else if (timeOutMs < 0)
  199569. timeOutMs = -1;
  199570. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  199571. const bool isFtp = url.startsWithIgnoreCase (T("ftp:"));
  199572. HINTERNET connection = InternetConnect (sessionHandle,
  199573. uc.lpszHostName,
  199574. uc.nPort,
  199575. _T(""), _T(""),
  199576. isFtp ? INTERNET_SERVICE_FTP
  199577. : INTERNET_SERVICE_HTTP,
  199578. 0, 0);
  199579. if (connection != 0)
  199580. {
  199581. if (isFtp)
  199582. {
  199583. HINTERNET request = FtpOpenFile (connection,
  199584. uc.lpszUrlPath,
  199585. GENERIC_READ,
  199586. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  199587. 0);
  199588. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  199589. result->connection = connection;
  199590. result->request = request;
  199591. return result;
  199592. }
  199593. else
  199594. {
  199595. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  199596. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;
  199597. if (url.startsWithIgnoreCase (T("https:")))
  199598. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  199599. // IE7 seems to automatically work out when it's https)
  199600. HINTERNET request = HttpOpenRequest (connection,
  199601. isPost ? _T("POST")
  199602. : _T("GET"),
  199603. uc.lpszUrlPath,
  199604. 0, 0, mimeTypes, flags, 0);
  199605. if (request != 0)
  199606. {
  199607. INTERNET_BUFFERS buffers;
  199608. zerostruct (buffers);
  199609. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  199610. buffers.lpcszHeader = (LPCTSTR) headers;
  199611. buffers.dwHeadersLength = headers.length();
  199612. buffers.dwBufferTotal = (DWORD) postData.getSize();
  199613. ConnectionAndRequestStruct* result = 0;
  199614. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  199615. {
  199616. int bytesSent = 0;
  199617. for (;;)
  199618. {
  199619. const int bytesToDo = jmin (1024, postData.getSize() - bytesSent);
  199620. DWORD bytesDone = 0;
  199621. if (bytesToDo > 0
  199622. && ! InternetWriteFile (request,
  199623. ((const char*) postData.getData()) + bytesSent,
  199624. bytesToDo, &bytesDone))
  199625. {
  199626. break;
  199627. }
  199628. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  199629. {
  199630. result = new ConnectionAndRequestStruct();
  199631. result->connection = connection;
  199632. result->request = request;
  199633. HttpEndRequest (request, 0, 0, 0);
  199634. return result;
  199635. }
  199636. bytesSent += bytesDone;
  199637. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  199638. break;
  199639. }
  199640. }
  199641. InternetCloseHandle (request);
  199642. }
  199643. InternetCloseHandle (connection);
  199644. }
  199645. }
  199646. }
  199647. }
  199648. return 0;
  199649. }
  199650. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  199651. {
  199652. DWORD bytesRead = 0;
  199653. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  199654. if (crs != 0)
  199655. InternetReadFile (crs->request,
  199656. buffer, bytesToRead,
  199657. &bytesRead);
  199658. return bytesRead;
  199659. }
  199660. int juce_seekInInternetFile (void* handle, int newPosition)
  199661. {
  199662. if (handle != 0)
  199663. {
  199664. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  199665. return InternetSetFilePointer (crs->request,
  199666. newPosition, 0,
  199667. FILE_BEGIN, 0);
  199668. }
  199669. else
  199670. {
  199671. return -1;
  199672. }
  199673. }
  199674. int64 juce_getInternetFileContentLength (void* handle)
  199675. {
  199676. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  199677. if (crs != 0)
  199678. {
  199679. DWORD index = 0;
  199680. DWORD result = 0;
  199681. DWORD size = sizeof (result);
  199682. if (HttpQueryInfo (crs->request,
  199683. HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
  199684. &result,
  199685. &size,
  199686. &index))
  199687. {
  199688. return (int64) result;
  199689. }
  199690. }
  199691. return -1;
  199692. }
  199693. void juce_closeInternetFile (void* handle)
  199694. {
  199695. if (handle != 0)
  199696. {
  199697. ConnectionAndRequestStruct* const crs = (ConnectionAndRequestStruct*) handle;
  199698. InternetCloseHandle (crs->request);
  199699. InternetCloseHandle (crs->connection);
  199700. delete crs;
  199701. }
  199702. }
  199703. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  199704. {
  199705. int numFound = 0;
  199706. DynamicLibraryLoader dll ("iphlpapi.dll");
  199707. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  199708. if (getAdaptersInfo != 0)
  199709. {
  199710. ULONG len = sizeof (IP_ADAPTER_INFO);
  199711. MemoryBlock mb;
  199712. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  199713. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  199714. {
  199715. mb.setSize (len);
  199716. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  199717. }
  199718. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  199719. {
  199720. PIP_ADAPTER_INFO adapter = adapterInfo;
  199721. while (adapter != 0)
  199722. {
  199723. int64 mac = 0;
  199724. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  199725. mac = (mac << 8) | adapter->Address[i];
  199726. if (littleEndian)
  199727. mac = (int64) swapByteOrder ((uint64) mac);
  199728. if (numFound < maxNum && mac != 0)
  199729. addresses [numFound++] = mac;
  199730. adapter = adapter->Next;
  199731. }
  199732. }
  199733. }
  199734. return numFound;
  199735. }
  199736. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  199737. {
  199738. int numFound = 0;
  199739. DynamicLibraryLoader dll ("netapi32.dll");
  199740. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  199741. if (NetbiosCall != 0)
  199742. {
  199743. NCB ncb;
  199744. zerostruct (ncb);
  199745. typedef struct _ASTAT_
  199746. {
  199747. ADAPTER_STATUS adapt;
  199748. NAME_BUFFER NameBuff [30];
  199749. } ASTAT;
  199750. ASTAT astat;
  199751. zerostruct (astat);
  199752. LANA_ENUM enums;
  199753. zerostruct (enums);
  199754. ncb.ncb_command = NCBENUM;
  199755. ncb.ncb_buffer = (unsigned char*) &enums;
  199756. ncb.ncb_length = sizeof (LANA_ENUM);
  199757. NetbiosCall (&ncb);
  199758. for (int i = 0; i < enums.length; ++i)
  199759. {
  199760. zerostruct (ncb);
  199761. ncb.ncb_command = NCBRESET;
  199762. ncb.ncb_lana_num = enums.lana[i];
  199763. if (NetbiosCall (&ncb) == 0)
  199764. {
  199765. zerostruct (ncb);
  199766. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  199767. ncb.ncb_command = NCBASTAT;
  199768. ncb.ncb_lana_num = enums.lana[i];
  199769. ncb.ncb_buffer = (unsigned char*) &astat;
  199770. ncb.ncb_length = sizeof (ASTAT);
  199771. if (NetbiosCall (&ncb) == 0)
  199772. {
  199773. if (astat.adapt.adapter_type == 0xfe)
  199774. {
  199775. int64 mac = 0;
  199776. for (unsigned int i = 0; i < 6; ++i)
  199777. mac = (mac << 8) | astat.adapt.adapter_address[i];
  199778. if (littleEndian)
  199779. mac = (int64) swapByteOrder ((uint64) mac);
  199780. if (numFound < maxNum && mac != 0)
  199781. addresses [numFound++] = mac;
  199782. }
  199783. }
  199784. }
  199785. }
  199786. }
  199787. return numFound;
  199788. }
  199789. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  199790. {
  199791. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  199792. if (numFound == 0)
  199793. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  199794. return numFound;
  199795. }
  199796. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  199797. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  199798. const String& emailSubject,
  199799. const String& bodyText,
  199800. const StringArray& filesToAttach)
  199801. {
  199802. HMODULE h = LoadLibraryA ("MAPI32.dll");
  199803. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  199804. bool ok = false;
  199805. if (mapiSendMail != 0)
  199806. {
  199807. MapiMessage message;
  199808. zerostruct (message);
  199809. message.lpszSubject = (LPSTR) (LPCSTR) emailSubject;
  199810. message.lpszNoteText = (LPSTR) (LPCSTR) bodyText;
  199811. MapiRecipDesc recip;
  199812. zerostruct (recip);
  199813. recip.ulRecipClass = MAPI_TO;
  199814. String targetEmailAddress_ (targetEmailAddress);
  199815. if (targetEmailAddress_.isEmpty())
  199816. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  199817. recip.lpszName = (LPSTR) (LPCSTR) targetEmailAddress_;
  199818. message.nRecipCount = 1;
  199819. message.lpRecips = &recip;
  199820. MemoryBlock mb (sizeof (MapiFileDesc) * filesToAttach.size());
  199821. mb.fillWith (0);
  199822. MapiFileDesc* files = (MapiFileDesc*) mb.getData();
  199823. message.nFileCount = filesToAttach.size();
  199824. message.lpFiles = files;
  199825. for (int i = 0; i < filesToAttach.size(); ++i)
  199826. {
  199827. files[i].nPosition = (ULONG) -1;
  199828. files[i].lpszPathName = (LPSTR) (LPCSTR) filesToAttach [i];
  199829. }
  199830. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  199831. }
  199832. FreeLibrary (h);
  199833. return ok;
  199834. }
  199835. #endif
  199836. /********* End of inlined file: juce_win32_Network.cpp *********/
  199837. /********* Start of inlined file: juce_win32_PlatformUtils.cpp *********/
  199838. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199839. // compiled on its own).
  199840. #if JUCE_INCLUDED_FILE
  199841. static HKEY findKeyForPath (String name,
  199842. const bool createForWriting,
  199843. String& valueName) throw()
  199844. {
  199845. HKEY rootKey = 0;
  199846. if (name.startsWithIgnoreCase (T("HKEY_CURRENT_USER\\")))
  199847. rootKey = HKEY_CURRENT_USER;
  199848. else if (name.startsWithIgnoreCase (T("HKEY_LOCAL_MACHINE\\")))
  199849. rootKey = HKEY_LOCAL_MACHINE;
  199850. else if (name.startsWithIgnoreCase (T("HKEY_CLASSES_ROOT\\")))
  199851. rootKey = HKEY_CLASSES_ROOT;
  199852. if (rootKey != 0)
  199853. {
  199854. name = name.substring (name.indexOfChar (T('\\')) + 1);
  199855. const int lastSlash = name.lastIndexOfChar (T('\\'));
  199856. valueName = name.substring (lastSlash + 1);
  199857. name = name.substring (0, lastSlash);
  199858. HKEY key;
  199859. DWORD result;
  199860. if (createForWriting)
  199861. {
  199862. if (RegCreateKeyEx (rootKey, name, 0, L"", REG_OPTION_NON_VOLATILE,
  199863. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  199864. return key;
  199865. }
  199866. else
  199867. {
  199868. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  199869. return key;
  199870. }
  199871. }
  199872. return 0;
  199873. }
  199874. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  199875. const String& defaultValue)
  199876. {
  199877. String valueName, s;
  199878. HKEY k = findKeyForPath (regValuePath, false, valueName);
  199879. if (k != 0)
  199880. {
  199881. WCHAR buffer [2048];
  199882. unsigned long bufferSize = sizeof (buffer);
  199883. DWORD type = REG_SZ;
  199884. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  199885. s = buffer;
  199886. else
  199887. s = defaultValue;
  199888. RegCloseKey (k);
  199889. }
  199890. return s;
  199891. }
  199892. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  199893. const String& value)
  199894. {
  199895. String valueName;
  199896. HKEY k = findKeyForPath (regValuePath, true, valueName);
  199897. if (k != 0)
  199898. {
  199899. RegSetValueEx (k, valueName, 0, REG_SZ,
  199900. (const BYTE*) (const WCHAR*) value,
  199901. sizeof (WCHAR) * (value.length() + 1));
  199902. RegCloseKey (k);
  199903. }
  199904. }
  199905. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  199906. {
  199907. bool exists = false;
  199908. String valueName;
  199909. HKEY k = findKeyForPath (regValuePath, false, valueName);
  199910. if (k != 0)
  199911. {
  199912. unsigned char buffer [2048];
  199913. unsigned long bufferSize = sizeof (buffer);
  199914. DWORD type = 0;
  199915. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  199916. exists = true;
  199917. RegCloseKey (k);
  199918. }
  199919. return exists;
  199920. }
  199921. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  199922. {
  199923. String valueName;
  199924. HKEY k = findKeyForPath (regValuePath, true, valueName);
  199925. if (k != 0)
  199926. {
  199927. RegDeleteValue (k, valueName);
  199928. RegCloseKey (k);
  199929. }
  199930. }
  199931. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  199932. {
  199933. String valueName;
  199934. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  199935. if (k != 0)
  199936. {
  199937. RegDeleteKey (k, valueName);
  199938. RegCloseKey (k);
  199939. }
  199940. }
  199941. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  199942. const String& symbolicDescription,
  199943. const String& fullDescription,
  199944. const File& targetExecutable,
  199945. int iconResourceNumber)
  199946. {
  199947. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  199948. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  199949. if (iconResourceNumber != 0)
  199950. setRegistryValue (key + "\\DefaultIcon\\",
  199951. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  199952. setRegistryValue (key + "\\", fullDescription);
  199953. setRegistryValue (key + "\\shell\\open\\command\\",
  199954. targetExecutable.getFullPathName() + " %1");
  199955. }
  199956. bool juce_IsRunningInWine() throw()
  199957. {
  199958. HKEY key;
  199959. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  199960. {
  199961. RegCloseKey (key);
  199962. return true;
  199963. }
  199964. return false;
  199965. }
  199966. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams() throw()
  199967. {
  199968. String s (::GetCommandLineW());
  199969. StringArray tokens;
  199970. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  199971. return tokens.joinIntoString (T(" "), 1);
  199972. }
  199973. static void* currentModuleHandle = 0;
  199974. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  199975. {
  199976. if (currentModuleHandle == 0)
  199977. currentModuleHandle = GetModuleHandle (0);
  199978. return currentModuleHandle;
  199979. }
  199980. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  199981. {
  199982. currentModuleHandle = newHandle;
  199983. }
  199984. void PlatformUtilities::fpuReset()
  199985. {
  199986. #if JUCE_MSVC
  199987. _clearfp();
  199988. #endif
  199989. }
  199990. void PlatformUtilities::beep()
  199991. {
  199992. MessageBeep (MB_OK);
  199993. }
  199994. #endif
  199995. /********* End of inlined file: juce_win32_PlatformUtils.cpp *********/
  199996. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  199997. /********* Start of inlined file: juce_win32_Messaging.cpp *********/
  199998. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199999. // compiled on its own).
  200000. #if JUCE_INCLUDED_FILE
  200001. static const unsigned int specialId = WM_APP + 0x4400;
  200002. static const unsigned int broadcastId = WM_APP + 0x4403;
  200003. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  200004. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  200005. HWND juce_messageWindowHandle = 0;
  200006. extern long improbableWindowNumber; // defined in windowing.cpp
  200007. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  200008. const UINT message,
  200009. const WPARAM wParam,
  200010. const LPARAM lParam) throw()
  200011. {
  200012. JUCE_TRY
  200013. {
  200014. if (h == juce_messageWindowHandle)
  200015. {
  200016. if (message == specialCallbackId)
  200017. {
  200018. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  200019. return (LRESULT) (*func) ((void*) lParam);
  200020. }
  200021. else if (message == specialId)
  200022. {
  200023. // these are trapped early in the dispatch call, but must also be checked
  200024. // here in case there are windows modal dialog boxes doing their own
  200025. // dispatch loop and not calling our version
  200026. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  200027. return 0;
  200028. }
  200029. else if (message == broadcastId)
  200030. {
  200031. String* const messageString = (String*) lParam;
  200032. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  200033. delete messageString;
  200034. return 0;
  200035. }
  200036. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  200037. {
  200038. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  200039. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  200040. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  200041. return 0;
  200042. }
  200043. }
  200044. }
  200045. JUCE_CATCH_EXCEPTION
  200046. return DefWindowProc (h, message, wParam, lParam);
  200047. }
  200048. static bool isEventBlockedByModalComps (MSG& m)
  200049. {
  200050. if (Component::getNumCurrentlyModalComponents() == 0
  200051. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  200052. return false;
  200053. switch (m.message)
  200054. {
  200055. case WM_MOUSEMOVE:
  200056. case WM_NCMOUSEMOVE:
  200057. case 0x020A: /* WM_MOUSEWHEEL */
  200058. case 0x020E: /* WM_MOUSEHWHEEL */
  200059. case WM_KEYUP:
  200060. case WM_SYSKEYUP:
  200061. case WM_CHAR:
  200062. case WM_APPCOMMAND:
  200063. case WM_LBUTTONUP:
  200064. case WM_MBUTTONUP:
  200065. case WM_RBUTTONUP:
  200066. case WM_MOUSEACTIVATE:
  200067. case WM_NCMOUSEHOVER:
  200068. case WM_MOUSEHOVER:
  200069. return true;
  200070. case WM_NCLBUTTONDOWN:
  200071. case WM_NCLBUTTONDBLCLK:
  200072. case WM_NCRBUTTONDOWN:
  200073. case WM_NCRBUTTONDBLCLK:
  200074. case WM_NCMBUTTONDOWN:
  200075. case WM_NCMBUTTONDBLCLK:
  200076. case WM_LBUTTONDOWN:
  200077. case WM_LBUTTONDBLCLK:
  200078. case WM_MBUTTONDOWN:
  200079. case WM_MBUTTONDBLCLK:
  200080. case WM_RBUTTONDOWN:
  200081. case WM_RBUTTONDBLCLK:
  200082. case WM_KEYDOWN:
  200083. case WM_SYSKEYDOWN:
  200084. {
  200085. Component* const modal = Component::getCurrentlyModalComponent (0);
  200086. if (modal != 0)
  200087. modal->inputAttemptWhenModal();
  200088. return true;
  200089. }
  200090. default:
  200091. break;
  200092. }
  200093. return false;
  200094. }
  200095. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  200096. {
  200097. MSG m;
  200098. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  200099. return false;
  200100. if (GetMessage (&m, (HWND) 0, 0, 0) > 0)
  200101. {
  200102. if (m.message == specialId
  200103. && m.hwnd == juce_messageWindowHandle)
  200104. {
  200105. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  200106. }
  200107. else if (! isEventBlockedByModalComps (m))
  200108. {
  200109. if (GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber
  200110. && (m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN))
  200111. {
  200112. // if it's someone else's window being clicked on, and the focus is
  200113. // currently on a juce window, pass the kb focus over..
  200114. HWND currentFocus = GetFocus();
  200115. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  200116. SetFocus (m.hwnd);
  200117. }
  200118. TranslateMessage (&m);
  200119. DispatchMessage (&m);
  200120. }
  200121. }
  200122. return true;
  200123. }
  200124. bool juce_postMessageToSystemQueue (void* message)
  200125. {
  200126. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  200127. }
  200128. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  200129. void* userData)
  200130. {
  200131. if (MessageManager::getInstance()->isThisTheMessageThread())
  200132. {
  200133. return (*callback) (userData);
  200134. }
  200135. else
  200136. {
  200137. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  200138. // deadlock because the message manager is blocked from running, and can't
  200139. // call your function..
  200140. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  200141. return (void*) SendMessage (juce_messageWindowHandle,
  200142. specialCallbackId,
  200143. (WPARAM) callback,
  200144. (LPARAM) userData);
  200145. }
  200146. }
  200147. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  200148. {
  200149. if (hwnd != juce_messageWindowHandle)
  200150. (reinterpret_cast <VoidArray*> (lParam))->add ((void*) hwnd);
  200151. return TRUE;
  200152. }
  200153. void MessageManager::broadcastMessage (const String& value) throw()
  200154. {
  200155. VoidArray windows;
  200156. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  200157. const String localCopy (value);
  200158. COPYDATASTRUCT data;
  200159. data.dwData = broadcastId;
  200160. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  200161. data.lpData = (void*) (const juce_wchar*) localCopy;
  200162. for (int i = windows.size(); --i >= 0;)
  200163. {
  200164. HWND hwnd = (HWND) windows.getUnchecked(i);
  200165. TCHAR windowName [64]; // no need to read longer strings than this
  200166. GetWindowText (hwnd, windowName, 64);
  200167. windowName [63] = 0;
  200168. if (String (windowName) == String (messageWindowName))
  200169. {
  200170. DWORD_PTR result;
  200171. SendMessageTimeout (hwnd, WM_COPYDATA,
  200172. (WPARAM) juce_messageWindowHandle,
  200173. (LPARAM) &data,
  200174. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  200175. 8000,
  200176. &result);
  200177. }
  200178. }
  200179. }
  200180. static const String getMessageWindowClassName()
  200181. {
  200182. // this name has to be different for each app/dll instance because otherwise
  200183. // poor old Win32 can get a bit confused (even despite it not being a process-global
  200184. // window class).
  200185. static int number = 0;
  200186. if (number == 0)
  200187. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  200188. return T("JUCEcs_") + String (number);
  200189. }
  200190. void MessageManager::doPlatformSpecificInitialisation()
  200191. {
  200192. OleInitialize (0);
  200193. const String className (getMessageWindowClassName());
  200194. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  200195. WNDCLASSEX wc;
  200196. zerostruct (wc);
  200197. wc.cbSize = sizeof (wc);
  200198. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  200199. wc.cbWndExtra = 4;
  200200. wc.hInstance = hmod;
  200201. wc.lpszClassName = className;
  200202. RegisterClassEx (&wc);
  200203. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  200204. messageWindowName,
  200205. 0, 0, 0, 0, 0, 0, 0,
  200206. hmod, 0);
  200207. }
  200208. void MessageManager::doPlatformSpecificShutdown()
  200209. {
  200210. DestroyWindow (juce_messageWindowHandle);
  200211. UnregisterClass (getMessageWindowClassName(), 0);
  200212. OleUninitialize();
  200213. }
  200214. #endif
  200215. /********* End of inlined file: juce_win32_Messaging.cpp *********/
  200216. /********* Start of inlined file: juce_win32_Windowing.cpp *********/
  200217. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200218. // compiled on its own).
  200219. #if JUCE_INCLUDED_FILE
  200220. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  200221. // these are in the windows SDK, but need to be repeated here for GCC..
  200222. #ifndef GET_APPCOMMAND_LPARAM
  200223. #define FAPPCOMMAND_MASK 0xF000
  200224. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  200225. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  200226. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  200227. #define APPCOMMAND_MEDIA_STOP 13
  200228. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  200229. #define WM_APPCOMMAND 0x0319
  200230. #endif
  200231. extern void juce_repeatLastProcessPriority() throw(); // in juce_win32_Threads.cpp
  200232. extern void juce_CheckCurrentlyFocusedTopLevelWindow() throw(); // in juce_TopLevelWindow.cpp
  200233. extern bool juce_IsRunningInWine() throw();
  200234. #ifndef ULW_ALPHA
  200235. #define ULW_ALPHA 0x00000002
  200236. #endif
  200237. #ifndef AC_SRC_ALPHA
  200238. #define AC_SRC_ALPHA 0x01
  200239. #endif
  200240. #define DEBUG_REPAINT_TIMES 0
  200241. static HPALETTE palette = 0;
  200242. static bool createPaletteIfNeeded = true;
  200243. static bool shouldDeactivateTitleBar = true;
  200244. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  200245. #define WM_TRAYNOTIFY WM_USER + 100
  200246. using ::abs;
  200247. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  200248. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  200249. bool Desktop::canUseSemiTransparentWindows() throw()
  200250. {
  200251. if (updateLayeredWindow == 0)
  200252. {
  200253. if (! juce_IsRunningInWine())
  200254. {
  200255. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  200256. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  200257. }
  200258. }
  200259. return updateLayeredWindow != 0;
  200260. }
  200261. #undef DefWindowProc
  200262. #define DefWindowProc DefWindowProcW
  200263. const int extendedKeyModifier = 0x10000;
  200264. const int KeyPress::spaceKey = VK_SPACE;
  200265. const int KeyPress::returnKey = VK_RETURN;
  200266. const int KeyPress::escapeKey = VK_ESCAPE;
  200267. const int KeyPress::backspaceKey = VK_BACK;
  200268. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  200269. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  200270. const int KeyPress::tabKey = VK_TAB;
  200271. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  200272. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  200273. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  200274. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  200275. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  200276. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  200277. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  200278. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  200279. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  200280. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  200281. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  200282. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  200283. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  200284. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  200285. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  200286. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  200287. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  200288. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  200289. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  200290. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  200291. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  200292. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  200293. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  200294. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  200295. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  200296. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  200297. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  200298. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  200299. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  200300. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  200301. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  200302. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  200303. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  200304. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  200305. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  200306. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  200307. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  200308. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  200309. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  200310. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  200311. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  200312. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  200313. const int KeyPress::playKey = 0x30000;
  200314. const int KeyPress::stopKey = 0x30001;
  200315. const int KeyPress::fastForwardKey = 0x30002;
  200316. const int KeyPress::rewindKey = 0x30003;
  200317. class WindowsBitmapImage : public Image
  200318. {
  200319. public:
  200320. HBITMAP hBitmap;
  200321. BITMAPV4HEADER bitmapInfo;
  200322. HDC hdc;
  200323. unsigned char* bitmapData;
  200324. WindowsBitmapImage (const PixelFormat format_,
  200325. const int w, const int h, const bool clearImage)
  200326. : Image (format_, w, h)
  200327. {
  200328. jassert (format_ == RGB || format_ == ARGB);
  200329. pixelStride = (format_ == RGB) ? 3 : 4;
  200330. zerostruct (bitmapInfo);
  200331. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  200332. bitmapInfo.bV4Width = w;
  200333. bitmapInfo.bV4Height = h;
  200334. bitmapInfo.bV4Planes = 1;
  200335. bitmapInfo.bV4CSType = 1;
  200336. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  200337. if (format_ == ARGB)
  200338. {
  200339. bitmapInfo.bV4AlphaMask = 0xff000000;
  200340. bitmapInfo.bV4RedMask = 0xff0000;
  200341. bitmapInfo.bV4GreenMask = 0xff00;
  200342. bitmapInfo.bV4BlueMask = 0xff;
  200343. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  200344. }
  200345. else
  200346. {
  200347. bitmapInfo.bV4V4Compression = BI_RGB;
  200348. }
  200349. lineStride = -((w * pixelStride + 3) & ~3);
  200350. HDC dc = GetDC (0);
  200351. hdc = CreateCompatibleDC (dc);
  200352. ReleaseDC (0, dc);
  200353. SetMapMode (hdc, MM_TEXT);
  200354. hBitmap = CreateDIBSection (hdc,
  200355. (BITMAPINFO*) &(bitmapInfo),
  200356. DIB_RGB_COLORS,
  200357. (void**) &bitmapData,
  200358. 0, 0);
  200359. SelectObject (hdc, hBitmap);
  200360. if (format_ == ARGB && clearImage)
  200361. zeromem (bitmapData, abs (h * lineStride));
  200362. imageData = bitmapData - (lineStride * (h - 1));
  200363. }
  200364. ~WindowsBitmapImage()
  200365. {
  200366. DeleteDC (hdc);
  200367. DeleteObject (hBitmap);
  200368. imageData = 0; // to stop the base class freeing this
  200369. }
  200370. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  200371. const int x, const int y,
  200372. const RectangleList& maskedRegion) throw()
  200373. {
  200374. static HDRAWDIB hdd = 0;
  200375. static bool needToCreateDrawDib = true;
  200376. if (needToCreateDrawDib)
  200377. {
  200378. needToCreateDrawDib = false;
  200379. HDC dc = GetDC (0);
  200380. const int n = GetDeviceCaps (dc, BITSPIXEL);
  200381. ReleaseDC (0, dc);
  200382. // only open if we're not palettised
  200383. if (n > 8)
  200384. hdd = DrawDibOpen();
  200385. }
  200386. if (createPaletteIfNeeded)
  200387. {
  200388. HDC dc = GetDC (0);
  200389. const int n = GetDeviceCaps (dc, BITSPIXEL);
  200390. ReleaseDC (0, dc);
  200391. if (n <= 8)
  200392. palette = CreateHalftonePalette (dc);
  200393. createPaletteIfNeeded = false;
  200394. }
  200395. if (palette != 0)
  200396. {
  200397. SelectPalette (dc, palette, FALSE);
  200398. RealizePalette (dc);
  200399. SetStretchBltMode (dc, HALFTONE);
  200400. }
  200401. SetMapMode (dc, MM_TEXT);
  200402. if (transparent)
  200403. {
  200404. POINT p, pos;
  200405. SIZE size;
  200406. RECT windowBounds;
  200407. GetWindowRect (hwnd, &windowBounds);
  200408. p.x = -x;
  200409. p.y = -y;
  200410. pos.x = windowBounds.left;
  200411. pos.y = windowBounds.top;
  200412. size.cx = windowBounds.right - windowBounds.left;
  200413. size.cy = windowBounds.bottom - windowBounds.top;
  200414. BLENDFUNCTION bf;
  200415. bf.AlphaFormat = AC_SRC_ALPHA;
  200416. bf.BlendFlags = 0;
  200417. bf.BlendOp = AC_SRC_OVER;
  200418. bf.SourceConstantAlpha = 0xff;
  200419. if (! maskedRegion.isEmpty())
  200420. {
  200421. for (RectangleList::Iterator i (maskedRegion); i.next();)
  200422. {
  200423. const Rectangle& r = *i.getRectangle();
  200424. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  200425. }
  200426. }
  200427. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  200428. }
  200429. else
  200430. {
  200431. int savedDC = 0;
  200432. if (! maskedRegion.isEmpty())
  200433. {
  200434. savedDC = SaveDC (dc);
  200435. for (RectangleList::Iterator i (maskedRegion); i.next();)
  200436. {
  200437. const Rectangle& r = *i.getRectangle();
  200438. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  200439. }
  200440. }
  200441. const int w = getWidth();
  200442. const int h = getHeight();
  200443. if (hdd == 0)
  200444. {
  200445. StretchDIBits (dc,
  200446. x, y, w, h,
  200447. 0, 0, w, h,
  200448. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  200449. DIB_RGB_COLORS, SRCCOPY);
  200450. }
  200451. else
  200452. {
  200453. DrawDibDraw (hdd, dc, x, y, -1, -1,
  200454. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  200455. 0, 0, w, h, 0);
  200456. }
  200457. if (! maskedRegion.isEmpty())
  200458. RestoreDC (dc, savedDC);
  200459. }
  200460. }
  200461. juce_UseDebuggingNewOperator
  200462. private:
  200463. WindowsBitmapImage (const WindowsBitmapImage&);
  200464. const WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  200465. };
  200466. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  200467. static int currentModifiers = 0;
  200468. static int modifiersAtLastCallback = 0;
  200469. static void updateKeyModifiers() throw()
  200470. {
  200471. currentModifiers &= ~(ModifierKeys::shiftModifier
  200472. | ModifierKeys::ctrlModifier
  200473. | ModifierKeys::altModifier);
  200474. if ((GetKeyState (VK_SHIFT) & 0x8000) != 0)
  200475. currentModifiers |= ModifierKeys::shiftModifier;
  200476. if ((GetKeyState (VK_CONTROL) & 0x8000) != 0)
  200477. currentModifiers |= ModifierKeys::ctrlModifier;
  200478. if ((GetKeyState (VK_MENU) & 0x8000) != 0)
  200479. currentModifiers |= ModifierKeys::altModifier;
  200480. if ((GetKeyState (VK_RMENU) & 0x8000) != 0)
  200481. currentModifiers &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  200482. }
  200483. void ModifierKeys::updateCurrentModifiers() throw()
  200484. {
  200485. currentModifierFlags = currentModifiers;
  200486. }
  200487. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  200488. {
  200489. SHORT k = (SHORT) keyCode;
  200490. if ((keyCode & extendedKeyModifier) == 0
  200491. && (k >= (SHORT) T('a') && k <= (SHORT) T('z')))
  200492. k += (SHORT) T('A') - (SHORT) T('a');
  200493. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  200494. (SHORT) '+', VK_OEM_PLUS,
  200495. (SHORT) '-', VK_OEM_MINUS,
  200496. (SHORT) '.', VK_OEM_PERIOD,
  200497. (SHORT) ';', VK_OEM_1,
  200498. (SHORT) ':', VK_OEM_1,
  200499. (SHORT) '/', VK_OEM_2,
  200500. (SHORT) '?', VK_OEM_2,
  200501. (SHORT) '[', VK_OEM_4,
  200502. (SHORT) ']', VK_OEM_6 };
  200503. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  200504. if (k == translatedValues [i])
  200505. k = translatedValues [i + 1];
  200506. return (GetKeyState (k) & 0x8000) != 0;
  200507. }
  200508. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  200509. {
  200510. updateKeyModifiers();
  200511. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  200512. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0)
  200513. currentModifiers |= ModifierKeys::leftButtonModifier;
  200514. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0)
  200515. currentModifiers |= ModifierKeys::rightButtonModifier;
  200516. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0)
  200517. currentModifiers |= ModifierKeys::middleButtonModifier;
  200518. return ModifierKeys (currentModifiers);
  200519. }
  200520. static int64 getMouseEventTime() throw()
  200521. {
  200522. static int64 eventTimeOffset = 0;
  200523. static DWORD lastMessageTime = 0;
  200524. const DWORD thisMessageTime = GetMessageTime();
  200525. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  200526. {
  200527. lastMessageTime = thisMessageTime;
  200528. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  200529. }
  200530. return eventTimeOffset + thisMessageTime;
  200531. }
  200532. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  200533. {
  200534. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  200535. return callback (userData);
  200536. else
  200537. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  200538. }
  200539. class Win32ComponentPeer : public ComponentPeer
  200540. {
  200541. public:
  200542. Win32ComponentPeer (Component* const component,
  200543. const int windowStyleFlags)
  200544. : ComponentPeer (component, windowStyleFlags),
  200545. dontRepaint (false),
  200546. fullScreen (false),
  200547. isDragging (false),
  200548. isMouseOver (false),
  200549. hasCreatedCaret (false),
  200550. currentWindowIcon (0),
  200551. taskBarIcon (0),
  200552. dropTarget (0)
  200553. {
  200554. callFunctionIfNotLocked (&createWindowCallback, (void*) this);
  200555. setTitle (component->getName());
  200556. if ((windowStyleFlags & windowHasDropShadow) != 0
  200557. && Desktop::canUseSemiTransparentWindows())
  200558. {
  200559. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  200560. if (shadower != 0)
  200561. shadower->setOwner (component);
  200562. }
  200563. else
  200564. {
  200565. shadower = 0;
  200566. }
  200567. }
  200568. ~Win32ComponentPeer()
  200569. {
  200570. setTaskBarIcon (0);
  200571. deleteAndZero (shadower);
  200572. // do this before the next bit to avoid messages arriving for this window
  200573. // before it's destroyed
  200574. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  200575. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  200576. if (currentWindowIcon != 0)
  200577. DestroyIcon (currentWindowIcon);
  200578. if (dropTarget != 0)
  200579. {
  200580. dropTarget->Release();
  200581. dropTarget = 0;
  200582. }
  200583. }
  200584. void* getNativeHandle() const
  200585. {
  200586. return (void*) hwnd;
  200587. }
  200588. void setVisible (bool shouldBeVisible)
  200589. {
  200590. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  200591. if (shouldBeVisible)
  200592. InvalidateRect (hwnd, 0, 0);
  200593. else
  200594. lastPaintTime = 0;
  200595. }
  200596. void setTitle (const String& title)
  200597. {
  200598. SetWindowText (hwnd, title);
  200599. }
  200600. void setPosition (int x, int y)
  200601. {
  200602. offsetWithinParent (x, y);
  200603. SetWindowPos (hwnd, 0,
  200604. x - windowBorder.getLeft(),
  200605. y - windowBorder.getTop(),
  200606. 0, 0,
  200607. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  200608. }
  200609. void repaintNowIfTransparent()
  200610. {
  200611. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  200612. handlePaintMessage();
  200613. }
  200614. void updateBorderSize()
  200615. {
  200616. WINDOWINFO info;
  200617. info.cbSize = sizeof (info);
  200618. if (GetWindowInfo (hwnd, &info))
  200619. {
  200620. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  200621. info.rcClient.left - info.rcWindow.left,
  200622. info.rcWindow.bottom - info.rcClient.bottom,
  200623. info.rcWindow.right - info.rcClient.right);
  200624. }
  200625. }
  200626. void setSize (int w, int h)
  200627. {
  200628. SetWindowPos (hwnd, 0, 0, 0,
  200629. w + windowBorder.getLeftAndRight(),
  200630. h + windowBorder.getTopAndBottom(),
  200631. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  200632. updateBorderSize();
  200633. repaintNowIfTransparent();
  200634. }
  200635. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  200636. {
  200637. fullScreen = isNowFullScreen;
  200638. offsetWithinParent (x, y);
  200639. SetWindowPos (hwnd, 0,
  200640. x - windowBorder.getLeft(),
  200641. y - windowBorder.getTop(),
  200642. w + windowBorder.getLeftAndRight(),
  200643. h + windowBorder.getTopAndBottom(),
  200644. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  200645. updateBorderSize();
  200646. repaintNowIfTransparent();
  200647. }
  200648. void getBounds (int& x, int& y, int& w, int& h) const
  200649. {
  200650. RECT r;
  200651. GetWindowRect (hwnd, &r);
  200652. x = r.left;
  200653. y = r.top;
  200654. w = r.right - x;
  200655. h = r.bottom - y;
  200656. HWND parentH = GetParent (hwnd);
  200657. if (parentH != 0)
  200658. {
  200659. GetWindowRect (parentH, &r);
  200660. x -= r.left;
  200661. y -= r.top;
  200662. }
  200663. x += windowBorder.getLeft();
  200664. y += windowBorder.getTop();
  200665. w -= windowBorder.getLeftAndRight();
  200666. h -= windowBorder.getTopAndBottom();
  200667. }
  200668. int getScreenX() const
  200669. {
  200670. RECT r;
  200671. GetWindowRect (hwnd, &r);
  200672. return r.left + windowBorder.getLeft();
  200673. }
  200674. int getScreenY() const
  200675. {
  200676. RECT r;
  200677. GetWindowRect (hwnd, &r);
  200678. return r.top + windowBorder.getTop();
  200679. }
  200680. void relativePositionToGlobal (int& x, int& y)
  200681. {
  200682. RECT r;
  200683. GetWindowRect (hwnd, &r);
  200684. x += r.left + windowBorder.getLeft();
  200685. y += r.top + windowBorder.getTop();
  200686. }
  200687. void globalPositionToRelative (int& x, int& y)
  200688. {
  200689. RECT r;
  200690. GetWindowRect (hwnd, &r);
  200691. x -= r.left + windowBorder.getLeft();
  200692. y -= r.top + windowBorder.getTop();
  200693. }
  200694. void setMinimised (bool shouldBeMinimised)
  200695. {
  200696. if (shouldBeMinimised != isMinimised())
  200697. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  200698. }
  200699. bool isMinimised() const
  200700. {
  200701. WINDOWPLACEMENT wp;
  200702. wp.length = sizeof (WINDOWPLACEMENT);
  200703. GetWindowPlacement (hwnd, &wp);
  200704. return wp.showCmd == SW_SHOWMINIMIZED;
  200705. }
  200706. void setFullScreen (bool shouldBeFullScreen)
  200707. {
  200708. setMinimised (false);
  200709. if (fullScreen != shouldBeFullScreen)
  200710. {
  200711. fullScreen = shouldBeFullScreen;
  200712. const ComponentDeletionWatcher deletionChecker (component);
  200713. if (! fullScreen)
  200714. {
  200715. const Rectangle boundsCopy (lastNonFullscreenBounds);
  200716. if (hasTitleBar())
  200717. ShowWindow (hwnd, SW_SHOWNORMAL);
  200718. if (! boundsCopy.isEmpty())
  200719. {
  200720. setBounds (boundsCopy.getX(),
  200721. boundsCopy.getY(),
  200722. boundsCopy.getWidth(),
  200723. boundsCopy.getHeight(),
  200724. false);
  200725. }
  200726. }
  200727. else
  200728. {
  200729. if (hasTitleBar())
  200730. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  200731. else
  200732. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  200733. }
  200734. if (! deletionChecker.hasBeenDeleted())
  200735. handleMovedOrResized();
  200736. }
  200737. }
  200738. bool isFullScreen() const
  200739. {
  200740. if (! hasTitleBar())
  200741. return fullScreen;
  200742. WINDOWPLACEMENT wp;
  200743. wp.length = sizeof (wp);
  200744. GetWindowPlacement (hwnd, &wp);
  200745. return wp.showCmd == SW_SHOWMAXIMIZED;
  200746. }
  200747. bool contains (int x, int y, bool trueIfInAChildWindow) const
  200748. {
  200749. RECT r;
  200750. GetWindowRect (hwnd, &r);
  200751. POINT p;
  200752. p.x = x + r.left + windowBorder.getLeft();
  200753. p.y = y + r.top + windowBorder.getTop();
  200754. HWND w = WindowFromPoint (p);
  200755. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  200756. }
  200757. const BorderSize getFrameSize() const
  200758. {
  200759. return windowBorder;
  200760. }
  200761. bool setAlwaysOnTop (bool alwaysOnTop)
  200762. {
  200763. const bool oldDeactivate = shouldDeactivateTitleBar;
  200764. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  200765. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  200766. 0, 0, 0, 0,
  200767. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  200768. shouldDeactivateTitleBar = oldDeactivate;
  200769. if (shadower != 0)
  200770. shadower->componentBroughtToFront (*component);
  200771. return true;
  200772. }
  200773. void toFront (bool makeActive)
  200774. {
  200775. setMinimised (false);
  200776. const bool oldDeactivate = shouldDeactivateTitleBar;
  200777. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  200778. callFunctionIfNotLocked (makeActive ? &toFrontCallback1
  200779. : &toFrontCallback2,
  200780. (void*) hwnd);
  200781. shouldDeactivateTitleBar = oldDeactivate;
  200782. if (! makeActive)
  200783. {
  200784. // in this case a broughttofront call won't have occured, so do it now..
  200785. handleBroughtToFront();
  200786. }
  200787. }
  200788. void toBehind (ComponentPeer* other)
  200789. {
  200790. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  200791. jassert (otherPeer != 0); // wrong type of window?
  200792. if (otherPeer != 0)
  200793. {
  200794. setMinimised (false);
  200795. // must be careful not to try to put a topmost window behind a normal one, or win32
  200796. // promotes the normal one to be topmost!
  200797. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  200798. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  200799. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  200800. else if (otherPeer->getComponent()->isAlwaysOnTop())
  200801. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  200802. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  200803. }
  200804. }
  200805. bool isFocused() const
  200806. {
  200807. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  200808. }
  200809. void grabFocus()
  200810. {
  200811. const bool oldDeactivate = shouldDeactivateTitleBar;
  200812. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  200813. callFunctionIfNotLocked (&setFocusCallback, (void*) hwnd);
  200814. shouldDeactivateTitleBar = oldDeactivate;
  200815. }
  200816. void textInputRequired (int /*x*/, int /*y*/)
  200817. {
  200818. if (! hasCreatedCaret)
  200819. {
  200820. hasCreatedCaret = true;
  200821. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  200822. }
  200823. ShowCaret (hwnd);
  200824. SetCaretPos (0, 0);
  200825. }
  200826. void repaint (int x, int y, int w, int h)
  200827. {
  200828. const RECT r = { x, y, x + w, y + h };
  200829. InvalidateRect (hwnd, &r, FALSE);
  200830. }
  200831. void performAnyPendingRepaintsNow()
  200832. {
  200833. MSG m;
  200834. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  200835. DispatchMessage (&m);
  200836. }
  200837. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  200838. {
  200839. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  200840. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  200841. return 0;
  200842. }
  200843. void setTaskBarIcon (const Image* const image)
  200844. {
  200845. if (image != 0)
  200846. {
  200847. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  200848. if (taskBarIcon == 0)
  200849. {
  200850. taskBarIcon = new NOTIFYICONDATA();
  200851. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  200852. taskBarIcon->hWnd = (HWND) hwnd;
  200853. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  200854. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  200855. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  200856. taskBarIcon->hIcon = hicon;
  200857. taskBarIcon->szTip[0] = 0;
  200858. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  200859. }
  200860. else
  200861. {
  200862. HICON oldIcon = taskBarIcon->hIcon;
  200863. taskBarIcon->hIcon = hicon;
  200864. taskBarIcon->uFlags = NIF_ICON;
  200865. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  200866. DestroyIcon (oldIcon);
  200867. }
  200868. DestroyIcon (hicon);
  200869. }
  200870. else if (taskBarIcon != 0)
  200871. {
  200872. taskBarIcon->uFlags = 0;
  200873. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  200874. DestroyIcon (taskBarIcon->hIcon);
  200875. deleteAndZero (taskBarIcon);
  200876. }
  200877. }
  200878. void setTaskBarIconToolTip (const String& toolTip) const
  200879. {
  200880. if (taskBarIcon != 0)
  200881. {
  200882. taskBarIcon->uFlags = NIF_TIP;
  200883. toolTip.copyToBuffer (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  200884. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  200885. }
  200886. }
  200887. bool isInside (HWND h) const
  200888. {
  200889. return GetAncestor (hwnd, GA_ROOT) == h;
  200890. }
  200891. juce_UseDebuggingNewOperator
  200892. bool dontRepaint;
  200893. private:
  200894. HWND hwnd;
  200895. DropShadower* shadower;
  200896. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  200897. BorderSize windowBorder;
  200898. HICON currentWindowIcon;
  200899. NOTIFYICONDATA* taskBarIcon;
  200900. IDropTarget* dropTarget;
  200901. class TemporaryImage : public Timer
  200902. {
  200903. public:
  200904. TemporaryImage()
  200905. : image (0)
  200906. {
  200907. }
  200908. ~TemporaryImage()
  200909. {
  200910. delete image;
  200911. }
  200912. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  200913. {
  200914. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  200915. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  200916. {
  200917. delete image;
  200918. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  200919. }
  200920. startTimer (3000);
  200921. return image;
  200922. }
  200923. void timerCallback()
  200924. {
  200925. stopTimer();
  200926. deleteAndZero (image);
  200927. }
  200928. private:
  200929. WindowsBitmapImage* image;
  200930. TemporaryImage (const TemporaryImage&);
  200931. const TemporaryImage& operator= (const TemporaryImage&);
  200932. };
  200933. TemporaryImage offscreenImageGenerator;
  200934. class WindowClassHolder : public DeletedAtShutdown
  200935. {
  200936. public:
  200937. WindowClassHolder()
  200938. : windowClassName ("JUCE_")
  200939. {
  200940. // this name has to be different for each app/dll instance because otherwise
  200941. // poor old Win32 can get a bit confused (even despite it not being a process-global
  200942. // window class).
  200943. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  200944. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  200945. TCHAR moduleFile [1024];
  200946. moduleFile[0] = 0;
  200947. GetModuleFileName (moduleHandle, moduleFile, 1024);
  200948. WORD iconNum = 0;
  200949. WNDCLASSEX wcex;
  200950. wcex.cbSize = sizeof (wcex);
  200951. wcex.style = CS_OWNDC;
  200952. wcex.lpfnWndProc = (WNDPROC) windowProc;
  200953. wcex.lpszClassName = windowClassName;
  200954. wcex.cbClsExtra = 0;
  200955. wcex.cbWndExtra = 32;
  200956. wcex.hInstance = moduleHandle;
  200957. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  200958. iconNum = 1;
  200959. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  200960. wcex.hCursor = 0;
  200961. wcex.hbrBackground = 0;
  200962. wcex.lpszMenuName = 0;
  200963. RegisterClassEx (&wcex);
  200964. }
  200965. ~WindowClassHolder()
  200966. {
  200967. if (ComponentPeer::getNumPeers() == 0)
  200968. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  200969. clearSingletonInstance();
  200970. }
  200971. String windowClassName;
  200972. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  200973. };
  200974. static void* createWindowCallback (void* userData)
  200975. {
  200976. ((Win32ComponentPeer*) userData)->createWindow();
  200977. return 0;
  200978. }
  200979. void createWindow()
  200980. {
  200981. DWORD exstyle = WS_EX_ACCEPTFILES;
  200982. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  200983. if (hasTitleBar())
  200984. {
  200985. type |= WS_OVERLAPPED;
  200986. exstyle |= WS_EX_APPWINDOW;
  200987. if ((styleFlags & windowHasCloseButton) != 0)
  200988. {
  200989. type |= WS_SYSMENU;
  200990. }
  200991. else
  200992. {
  200993. // annoyingly, windows won't let you have a min/max button without a close button
  200994. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  200995. }
  200996. if ((styleFlags & windowIsResizable) != 0)
  200997. type |= WS_THICKFRAME;
  200998. }
  200999. else
  201000. {
  201001. type |= WS_POPUP | WS_SYSMENU;
  201002. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  201003. exstyle |= WS_EX_TOOLWINDOW;
  201004. else
  201005. exstyle |= WS_EX_APPWINDOW;
  201006. }
  201007. if ((styleFlags & windowHasMinimiseButton) != 0)
  201008. type |= WS_MINIMIZEBOX;
  201009. if ((styleFlags & windowHasMaximiseButton) != 0)
  201010. type |= WS_MAXIMIZEBOX;
  201011. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  201012. exstyle |= WS_EX_TRANSPARENT;
  201013. if ((styleFlags & windowIsSemiTransparent) != 0
  201014. && Desktop::canUseSemiTransparentWindows())
  201015. exstyle |= WS_EX_LAYERED;
  201016. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  201017. if (hwnd != 0)
  201018. {
  201019. SetWindowLongPtr (hwnd, 0, 0);
  201020. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  201021. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  201022. if (dropTarget == 0)
  201023. dropTarget = new JuceDropTarget (this);
  201024. RegisterDragDrop (hwnd, dropTarget);
  201025. updateBorderSize();
  201026. // Calling this function here is (for some reason) necessary to make Windows
  201027. // correctly enable the menu items that we specify in the wm_initmenu message.
  201028. GetSystemMenu (hwnd, false);
  201029. }
  201030. else
  201031. {
  201032. jassertfalse
  201033. }
  201034. }
  201035. static void* destroyWindowCallback (void* handle)
  201036. {
  201037. RevokeDragDrop ((HWND) handle);
  201038. DestroyWindow ((HWND) handle);
  201039. return 0;
  201040. }
  201041. static void* toFrontCallback1 (void* h)
  201042. {
  201043. SetForegroundWindow ((HWND) h);
  201044. return 0;
  201045. }
  201046. static void* toFrontCallback2 (void* h)
  201047. {
  201048. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201049. return 0;
  201050. }
  201051. static void* setFocusCallback (void* h)
  201052. {
  201053. SetFocus ((HWND) h);
  201054. return 0;
  201055. }
  201056. static void* getFocusCallback (void*)
  201057. {
  201058. return (void*) GetFocus();
  201059. }
  201060. void offsetWithinParent (int& x, int& y) const
  201061. {
  201062. if (isTransparent())
  201063. {
  201064. HWND parentHwnd = GetParent (hwnd);
  201065. if (parentHwnd != 0)
  201066. {
  201067. RECT parentRect;
  201068. GetWindowRect (parentHwnd, &parentRect);
  201069. x += parentRect.left;
  201070. y += parentRect.top;
  201071. }
  201072. }
  201073. }
  201074. bool isTransparent() const
  201075. {
  201076. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  201077. }
  201078. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  201079. void setIcon (const Image& newIcon)
  201080. {
  201081. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  201082. if (hicon != 0)
  201083. {
  201084. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  201085. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  201086. if (currentWindowIcon != 0)
  201087. DestroyIcon (currentWindowIcon);
  201088. currentWindowIcon = hicon;
  201089. }
  201090. }
  201091. void handlePaintMessage()
  201092. {
  201093. #if DEBUG_REPAINT_TIMES
  201094. const double paintStart = Time::getMillisecondCounterHiRes();
  201095. #endif
  201096. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  201097. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  201098. PAINTSTRUCT paintStruct;
  201099. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  201100. // message and become re-entrant, but that's OK
  201101. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  201102. // corrupt the image it's using to paint into, so do a check here.
  201103. static bool reentrant = false;
  201104. if (reentrant)
  201105. {
  201106. DeleteObject (rgn);
  201107. EndPaint (hwnd, &paintStruct);
  201108. return;
  201109. }
  201110. reentrant = true;
  201111. // this is the rectangle to update..
  201112. int x = paintStruct.rcPaint.left;
  201113. int y = paintStruct.rcPaint.top;
  201114. int w = paintStruct.rcPaint.right - x;
  201115. int h = paintStruct.rcPaint.bottom - y;
  201116. const bool transparent = isTransparent();
  201117. if (transparent)
  201118. {
  201119. // it's not possible to have a transparent window with a title bar at the moment!
  201120. jassert (! hasTitleBar());
  201121. RECT r;
  201122. GetWindowRect (hwnd, &r);
  201123. x = y = 0;
  201124. w = r.right - r.left;
  201125. h = r.bottom - r.top;
  201126. }
  201127. if (w > 0 && h > 0)
  201128. {
  201129. clearMaskedRegion();
  201130. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  201131. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  201132. RectangleList* const contextClip = context.getRawClipRegion();
  201133. contextClip->clear();
  201134. context.setOrigin (-x, -y);
  201135. bool needToPaintAll = true;
  201136. if (regionType == COMPLEXREGION && ! transparent)
  201137. {
  201138. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  201139. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  201140. DeleteObject (clipRgn);
  201141. char rgnData [8192];
  201142. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  201143. if (res > 0 && res <= sizeof (rgnData))
  201144. {
  201145. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  201146. if (hdr->iType == RDH_RECTANGLES
  201147. && hdr->rcBound.right - hdr->rcBound.left >= w
  201148. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  201149. {
  201150. needToPaintAll = false;
  201151. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  201152. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  201153. while (--num >= 0)
  201154. {
  201155. // (need to move this one pixel to the left because of a win32 bug)
  201156. const int cx = jmax (x, rects->left - 1);
  201157. const int cy = rects->top;
  201158. const int cw = rects->right - cx;
  201159. const int ch = rects->bottom - rects->top;
  201160. if (cx + cw - x <= w && cy + ch - y <= h)
  201161. {
  201162. contextClip->addWithoutMerging (Rectangle (cx - x, cy - y, cw, ch));
  201163. }
  201164. else
  201165. {
  201166. needToPaintAll = true;
  201167. break;
  201168. }
  201169. ++rects;
  201170. }
  201171. }
  201172. }
  201173. }
  201174. if (needToPaintAll)
  201175. {
  201176. contextClip->clear();
  201177. contextClip->addWithoutMerging (Rectangle (0, 0, w, h));
  201178. }
  201179. if (transparent)
  201180. {
  201181. RectangleList::Iterator i (*contextClip);
  201182. while (i.next())
  201183. {
  201184. const Rectangle& r = *i.getRectangle();
  201185. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  201186. }
  201187. }
  201188. // if the component's not opaque, this won't draw properly unless the platform can support this
  201189. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  201190. updateCurrentModifiers();
  201191. handlePaint (context);
  201192. if (! dontRepaint)
  201193. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  201194. }
  201195. DeleteObject (rgn);
  201196. EndPaint (hwnd, &paintStruct);
  201197. reentrant = false;
  201198. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  201199. _fpreset(); // because some graphics cards can unmask FP exceptions
  201200. #endif
  201201. lastPaintTime = Time::getMillisecondCounter();
  201202. #if DEBUG_REPAINT_TIMES
  201203. const double elapsed = Time::getMillisecondCounterHiRes() - paintStart;
  201204. Logger::outputDebugString (T("repaint time: ") + String (elapsed, 2));
  201205. #endif
  201206. }
  201207. void doMouseMove (const int x, const int y)
  201208. {
  201209. static uint32 lastMouseTime = 0;
  201210. // this can be set to throttle the mouse-messages to less than a
  201211. // certain number per second, as things can get unresponsive
  201212. // if each drag or move callback has to do a lot of work.
  201213. const int maxMouseMovesPerSecond = 60;
  201214. const int64 mouseEventTime = getMouseEventTime();
  201215. if (! isMouseOver)
  201216. {
  201217. isMouseOver = true;
  201218. TRACKMOUSEEVENT tme;
  201219. tme.cbSize = sizeof (tme);
  201220. tme.dwFlags = TME_LEAVE;
  201221. tme.hwndTrack = hwnd;
  201222. tme.dwHoverTime = 0;
  201223. if (! TrackMouseEvent (&tme))
  201224. {
  201225. jassertfalse;
  201226. }
  201227. updateKeyModifiers();
  201228. handleMouseEnter (x, y, mouseEventTime);
  201229. }
  201230. else if (! isDragging)
  201231. {
  201232. if (((unsigned int) x) < (unsigned int) component->getWidth()
  201233. && ((unsigned int) y) < (unsigned int) component->getHeight())
  201234. {
  201235. RECT r;
  201236. GetWindowRect (hwnd, &r);
  201237. POINT p;
  201238. p.x = x + r.left + windowBorder.getLeft();
  201239. p.y = y + r.top + windowBorder.getTop();
  201240. if (WindowFromPoint (p) == hwnd)
  201241. {
  201242. const uint32 now = Time::getMillisecondCounter();
  201243. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  201244. {
  201245. lastMouseTime = now;
  201246. handleMouseMove (x, y, mouseEventTime);
  201247. }
  201248. }
  201249. }
  201250. }
  201251. else
  201252. {
  201253. const uint32 now = Time::getMillisecondCounter();
  201254. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  201255. {
  201256. lastMouseTime = now;
  201257. handleMouseDrag (x, y, mouseEventTime);
  201258. }
  201259. }
  201260. }
  201261. void doMouseDown (const int x, const int y, const WPARAM wParam)
  201262. {
  201263. if (GetCapture() != hwnd)
  201264. SetCapture (hwnd);
  201265. doMouseMove (x, y);
  201266. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  201267. if ((wParam & MK_LBUTTON) != 0)
  201268. currentModifiers |= ModifierKeys::leftButtonModifier;
  201269. if ((wParam & MK_RBUTTON) != 0)
  201270. currentModifiers |= ModifierKeys::rightButtonModifier;
  201271. if ((wParam & MK_MBUTTON) != 0)
  201272. currentModifiers |= ModifierKeys::middleButtonModifier;
  201273. updateKeyModifiers();
  201274. isDragging = true;
  201275. handleMouseDown (x, y, getMouseEventTime());
  201276. }
  201277. void doMouseUp (const int x, const int y, const WPARAM wParam)
  201278. {
  201279. int numButtons = 0;
  201280. if ((wParam & MK_LBUTTON) != 0)
  201281. ++numButtons;
  201282. if ((wParam & MK_RBUTTON) != 0)
  201283. ++numButtons;
  201284. if ((wParam & MK_MBUTTON) != 0)
  201285. ++numButtons;
  201286. const int oldModifiers = currentModifiers;
  201287. // update the currentmodifiers only after the callback, so the callback
  201288. // knows which button was released.
  201289. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  201290. if ((wParam & MK_LBUTTON) != 0)
  201291. currentModifiers |= ModifierKeys::leftButtonModifier;
  201292. if ((wParam & MK_RBUTTON) != 0)
  201293. currentModifiers |= ModifierKeys::rightButtonModifier;
  201294. if ((wParam & MK_MBUTTON) != 0)
  201295. currentModifiers |= ModifierKeys::middleButtonModifier;
  201296. updateKeyModifiers();
  201297. isDragging = false;
  201298. // release the mouse capture if the user's not still got a button down
  201299. if (numButtons == 0 && hwnd == GetCapture())
  201300. ReleaseCapture();
  201301. handleMouseUp (oldModifiers, x, y, getMouseEventTime());
  201302. }
  201303. void doCaptureChanged()
  201304. {
  201305. if (isDragging)
  201306. {
  201307. RECT wr;
  201308. GetWindowRect (hwnd, &wr);
  201309. const DWORD mp = GetMessagePos();
  201310. doMouseUp (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  201311. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  201312. (WPARAM) getMouseEventTime());
  201313. }
  201314. }
  201315. void doMouseExit()
  201316. {
  201317. if (isMouseOver)
  201318. {
  201319. isMouseOver = false;
  201320. RECT wr;
  201321. GetWindowRect (hwnd, &wr);
  201322. const DWORD mp = GetMessagePos();
  201323. handleMouseExit (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  201324. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  201325. getMouseEventTime());
  201326. }
  201327. }
  201328. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  201329. {
  201330. updateKeyModifiers();
  201331. const int amount = jlimit (-1000, 1000, (int) (0.75f * (short) HIWORD (wParam)));
  201332. handleMouseWheel (isVertical ? 0 : amount,
  201333. isVertical ? amount : 0,
  201334. getMouseEventTime());
  201335. }
  201336. void sendModifierKeyChangeIfNeeded()
  201337. {
  201338. if (modifiersAtLastCallback != currentModifiers)
  201339. {
  201340. modifiersAtLastCallback = currentModifiers;
  201341. handleModifierKeysChange();
  201342. }
  201343. }
  201344. bool doKeyUp (const WPARAM key)
  201345. {
  201346. updateKeyModifiers();
  201347. switch (key)
  201348. {
  201349. case VK_SHIFT:
  201350. case VK_CONTROL:
  201351. case VK_MENU:
  201352. case VK_CAPITAL:
  201353. case VK_LWIN:
  201354. case VK_RWIN:
  201355. case VK_APPS:
  201356. case VK_NUMLOCK:
  201357. case VK_SCROLL:
  201358. case VK_LSHIFT:
  201359. case VK_RSHIFT:
  201360. case VK_LCONTROL:
  201361. case VK_LMENU:
  201362. case VK_RCONTROL:
  201363. case VK_RMENU:
  201364. sendModifierKeyChangeIfNeeded();
  201365. }
  201366. return handleKeyUpOrDown (false)
  201367. || Component::getCurrentlyModalComponent() != 0;
  201368. }
  201369. bool doKeyDown (const WPARAM key)
  201370. {
  201371. updateKeyModifiers();
  201372. bool used = false;
  201373. switch (key)
  201374. {
  201375. case VK_SHIFT:
  201376. case VK_LSHIFT:
  201377. case VK_RSHIFT:
  201378. case VK_CONTROL:
  201379. case VK_LCONTROL:
  201380. case VK_RCONTROL:
  201381. case VK_MENU:
  201382. case VK_LMENU:
  201383. case VK_RMENU:
  201384. case VK_LWIN:
  201385. case VK_RWIN:
  201386. case VK_CAPITAL:
  201387. case VK_NUMLOCK:
  201388. case VK_SCROLL:
  201389. case VK_APPS:
  201390. sendModifierKeyChangeIfNeeded();
  201391. break;
  201392. case VK_LEFT:
  201393. case VK_RIGHT:
  201394. case VK_UP:
  201395. case VK_DOWN:
  201396. case VK_PRIOR:
  201397. case VK_NEXT:
  201398. case VK_HOME:
  201399. case VK_END:
  201400. case VK_DELETE:
  201401. case VK_INSERT:
  201402. case VK_F1:
  201403. case VK_F2:
  201404. case VK_F3:
  201405. case VK_F4:
  201406. case VK_F5:
  201407. case VK_F6:
  201408. case VK_F7:
  201409. case VK_F8:
  201410. case VK_F9:
  201411. case VK_F10:
  201412. case VK_F11:
  201413. case VK_F12:
  201414. case VK_F13:
  201415. case VK_F14:
  201416. case VK_F15:
  201417. case VK_F16:
  201418. used = handleKeyUpOrDown (true);
  201419. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  201420. break;
  201421. case VK_ADD:
  201422. case VK_SUBTRACT:
  201423. case VK_MULTIPLY:
  201424. case VK_DIVIDE:
  201425. case VK_SEPARATOR:
  201426. case VK_DECIMAL:
  201427. used = handleKeyUpOrDown (true);
  201428. break;
  201429. default:
  201430. used = handleKeyUpOrDown (true);
  201431. {
  201432. MSG msg;
  201433. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  201434. {
  201435. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  201436. // manually generate the key-press event that matches this key-down.
  201437. const UINT keyChar = MapVirtualKey (key, 2);
  201438. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  201439. }
  201440. }
  201441. break;
  201442. }
  201443. if (Component::getCurrentlyModalComponent() != 0)
  201444. used = true;
  201445. return used;
  201446. }
  201447. bool doKeyChar (int key, const LPARAM flags)
  201448. {
  201449. updateKeyModifiers();
  201450. juce_wchar textChar = (juce_wchar) key;
  201451. const int virtualScanCode = (flags >> 16) & 0xff;
  201452. if (key >= '0' && key <= '9')
  201453. {
  201454. switch (virtualScanCode) // check for a numeric keypad scan-code
  201455. {
  201456. case 0x52:
  201457. case 0x4f:
  201458. case 0x50:
  201459. case 0x51:
  201460. case 0x4b:
  201461. case 0x4c:
  201462. case 0x4d:
  201463. case 0x47:
  201464. case 0x48:
  201465. case 0x49:
  201466. key = (key - '0') + KeyPress::numberPad0;
  201467. break;
  201468. default:
  201469. break;
  201470. }
  201471. }
  201472. else
  201473. {
  201474. // convert the scan code to an unmodified character code..
  201475. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  201476. UINT keyChar = MapVirtualKey (virtualKey, 2);
  201477. keyChar = LOWORD (keyChar);
  201478. if (keyChar != 0)
  201479. key = (int) keyChar;
  201480. // avoid sending junk text characters for some control-key combinations
  201481. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  201482. textChar = 0;
  201483. }
  201484. return handleKeyPress (key, textChar);
  201485. }
  201486. bool doAppCommand (const LPARAM lParam)
  201487. {
  201488. int key = 0;
  201489. switch (GET_APPCOMMAND_LPARAM (lParam))
  201490. {
  201491. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  201492. key = KeyPress::playKey;
  201493. break;
  201494. case APPCOMMAND_MEDIA_STOP:
  201495. key = KeyPress::stopKey;
  201496. break;
  201497. case APPCOMMAND_MEDIA_NEXTTRACK:
  201498. key = KeyPress::fastForwardKey;
  201499. break;
  201500. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  201501. key = KeyPress::rewindKey;
  201502. break;
  201503. }
  201504. if (key != 0)
  201505. {
  201506. updateKeyModifiers();
  201507. if (hwnd == GetActiveWindow())
  201508. {
  201509. handleKeyPress (key, 0);
  201510. return true;
  201511. }
  201512. }
  201513. return false;
  201514. }
  201515. class JuceDropTarget : public IDropTarget
  201516. {
  201517. public:
  201518. JuceDropTarget (Win32ComponentPeer* const owner_)
  201519. : owner (owner_),
  201520. refCount (1)
  201521. {
  201522. }
  201523. virtual ~JuceDropTarget()
  201524. {
  201525. jassert (refCount == 0);
  201526. }
  201527. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  201528. {
  201529. if (id == IID_IUnknown || id == IID_IDropTarget)
  201530. {
  201531. AddRef();
  201532. *result = this;
  201533. return S_OK;
  201534. }
  201535. *result = 0;
  201536. return E_NOINTERFACE;
  201537. }
  201538. ULONG __stdcall AddRef() { return ++refCount; }
  201539. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  201540. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  201541. {
  201542. updateFileList (pDataObject);
  201543. int x = mousePos.x, y = mousePos.y;
  201544. owner->globalPositionToRelative (x, y);
  201545. owner->handleFileDragMove (files, x, y);
  201546. *pdwEffect = DROPEFFECT_COPY;
  201547. return S_OK;
  201548. }
  201549. HRESULT __stdcall DragLeave()
  201550. {
  201551. owner->handleFileDragExit (files);
  201552. return S_OK;
  201553. }
  201554. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  201555. {
  201556. int x = mousePos.x, y = mousePos.y;
  201557. owner->globalPositionToRelative (x, y);
  201558. owner->handleFileDragMove (files, x, y);
  201559. *pdwEffect = DROPEFFECT_COPY;
  201560. return S_OK;
  201561. }
  201562. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  201563. {
  201564. updateFileList (pDataObject);
  201565. int x = mousePos.x, y = mousePos.y;
  201566. owner->globalPositionToRelative (x, y);
  201567. owner->handleFileDragDrop (files, x, y);
  201568. *pdwEffect = DROPEFFECT_COPY;
  201569. return S_OK;
  201570. }
  201571. private:
  201572. Win32ComponentPeer* const owner;
  201573. int refCount;
  201574. StringArray files;
  201575. void updateFileList (IDataObject* const pDataObject)
  201576. {
  201577. files.clear();
  201578. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  201579. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  201580. if (pDataObject->GetData (&format, &medium) == S_OK)
  201581. {
  201582. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  201583. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  201584. unsigned int i = 0;
  201585. if (pDropFiles->fWide)
  201586. {
  201587. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  201588. for (;;)
  201589. {
  201590. unsigned int len = 0;
  201591. while (i + len < totalLen && fname [i + len] != 0)
  201592. ++len;
  201593. if (len == 0)
  201594. break;
  201595. files.add (String (fname + i, len));
  201596. i += len + 1;
  201597. }
  201598. }
  201599. else
  201600. {
  201601. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  201602. for (;;)
  201603. {
  201604. unsigned int len = 0;
  201605. while (i + len < totalLen && fname [i + len] != 0)
  201606. ++len;
  201607. if (len == 0)
  201608. break;
  201609. files.add (String (fname + i, len));
  201610. i += len + 1;
  201611. }
  201612. }
  201613. GlobalUnlock (medium.hGlobal);
  201614. }
  201615. }
  201616. JuceDropTarget (const JuceDropTarget&);
  201617. const JuceDropTarget& operator= (const JuceDropTarget&);
  201618. };
  201619. void doSettingChange()
  201620. {
  201621. Desktop::getInstance().refreshMonitorSizes();
  201622. if (fullScreen && ! isMinimised())
  201623. {
  201624. const Rectangle r (component->getParentMonitorArea());
  201625. SetWindowPos (hwnd, 0,
  201626. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  201627. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  201628. }
  201629. }
  201630. public:
  201631. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  201632. {
  201633. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  201634. if (peer != 0)
  201635. return peer->peerWindowProc (h, message, wParam, lParam);
  201636. return DefWindowProc (h, message, wParam, lParam);
  201637. }
  201638. private:
  201639. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  201640. {
  201641. {
  201642. if (isValidPeer (this))
  201643. {
  201644. switch (message)
  201645. {
  201646. case WM_NCHITTEST:
  201647. if (hasTitleBar())
  201648. break;
  201649. return HTCLIENT;
  201650. case WM_PAINT:
  201651. handlePaintMessage();
  201652. return 0;
  201653. case WM_NCPAINT:
  201654. if (wParam != 1)
  201655. handlePaintMessage();
  201656. if (hasTitleBar())
  201657. break;
  201658. return 0;
  201659. case WM_ERASEBKGND:
  201660. case WM_NCCALCSIZE:
  201661. if (hasTitleBar())
  201662. break;
  201663. return 1;
  201664. case WM_MOUSEMOVE:
  201665. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  201666. return 0;
  201667. case WM_MOUSELEAVE:
  201668. doMouseExit();
  201669. return 0;
  201670. case WM_LBUTTONDOWN:
  201671. case WM_MBUTTONDOWN:
  201672. case WM_RBUTTONDOWN:
  201673. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  201674. return 0;
  201675. case WM_LBUTTONUP:
  201676. case WM_MBUTTONUP:
  201677. case WM_RBUTTONUP:
  201678. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  201679. return 0;
  201680. case WM_CAPTURECHANGED:
  201681. doCaptureChanged();
  201682. return 0;
  201683. case WM_NCMOUSEMOVE:
  201684. if (hasTitleBar())
  201685. break;
  201686. return 0;
  201687. case 0x020A: /* WM_MOUSEWHEEL */
  201688. doMouseWheel (wParam, true);
  201689. return 0;
  201690. case 0x020E: /* WM_MOUSEHWHEEL */
  201691. doMouseWheel (wParam, false);
  201692. return 0;
  201693. case WM_WINDOWPOSCHANGING:
  201694. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  201695. {
  201696. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  201697. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  201698. {
  201699. if (constrainer != 0)
  201700. {
  201701. const Rectangle current (component->getX() - windowBorder.getLeft(),
  201702. component->getY() - windowBorder.getTop(),
  201703. component->getWidth() + windowBorder.getLeftAndRight(),
  201704. component->getHeight() + windowBorder.getTopAndBottom());
  201705. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  201706. current,
  201707. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  201708. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  201709. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  201710. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  201711. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  201712. }
  201713. }
  201714. }
  201715. return 0;
  201716. case WM_WINDOWPOSCHANGED:
  201717. handleMovedOrResized();
  201718. if (dontRepaint)
  201719. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  201720. else
  201721. return 0;
  201722. case WM_KEYDOWN:
  201723. case WM_SYSKEYDOWN:
  201724. if (doKeyDown (wParam))
  201725. return 0;
  201726. break;
  201727. case WM_KEYUP:
  201728. case WM_SYSKEYUP:
  201729. if (doKeyUp (wParam))
  201730. return 0;
  201731. break;
  201732. case WM_CHAR:
  201733. if (doKeyChar ((int) wParam, lParam))
  201734. return 0;
  201735. break;
  201736. case WM_APPCOMMAND:
  201737. if (doAppCommand (lParam))
  201738. return TRUE;
  201739. break;
  201740. case WM_SETFOCUS:
  201741. updateKeyModifiers();
  201742. handleFocusGain();
  201743. break;
  201744. case WM_KILLFOCUS:
  201745. if (hasCreatedCaret)
  201746. {
  201747. hasCreatedCaret = false;
  201748. DestroyCaret();
  201749. }
  201750. handleFocusLoss();
  201751. break;
  201752. case WM_ACTIVATEAPP:
  201753. // Windows does weird things to process priority when you swap apps,
  201754. // so this forces an update when the app is brought to the front
  201755. if (wParam != FALSE)
  201756. juce_repeatLastProcessPriority();
  201757. else
  201758. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  201759. juce_CheckCurrentlyFocusedTopLevelWindow();
  201760. modifiersAtLastCallback = -1;
  201761. return 0;
  201762. case WM_ACTIVATE:
  201763. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  201764. {
  201765. modifiersAtLastCallback = -1;
  201766. updateKeyModifiers();
  201767. if (isMinimised())
  201768. {
  201769. component->repaint();
  201770. handleMovedOrResized();
  201771. if (! isValidMessageListener())
  201772. return 0;
  201773. }
  201774. if (LOWORD (wParam) == WA_CLICKACTIVE
  201775. && component->isCurrentlyBlockedByAnotherModalComponent())
  201776. {
  201777. int mx, my;
  201778. component->getMouseXYRelative (mx, my);
  201779. Component* const underMouse = component->getComponentAt (mx, my);
  201780. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  201781. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  201782. return 0;
  201783. }
  201784. handleBroughtToFront();
  201785. if (component->isCurrentlyBlockedByAnotherModalComponent())
  201786. Component::getCurrentlyModalComponent()->toFront (true);
  201787. return 0;
  201788. }
  201789. break;
  201790. case WM_NCACTIVATE:
  201791. // while a temporary window is being shown, prevent Windows from deactivating the
  201792. // title bars of our main windows.
  201793. if (wParam == 0 && ! shouldDeactivateTitleBar)
  201794. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  201795. break;
  201796. case WM_MOUSEACTIVATE:
  201797. if (! component->getMouseClickGrabsKeyboardFocus())
  201798. return MA_NOACTIVATE;
  201799. break;
  201800. case WM_SHOWWINDOW:
  201801. if (wParam != 0)
  201802. handleBroughtToFront();
  201803. break;
  201804. case WM_CLOSE:
  201805. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  201806. handleUserClosingWindow();
  201807. return 0;
  201808. case WM_QUIT:
  201809. if (JUCEApplication::getInstance() != 0)
  201810. JUCEApplication::getInstance()->systemRequestedQuit();
  201811. return 0;
  201812. case WM_QUERYENDSESSION:
  201813. if (JUCEApplication::getInstance() != 0)
  201814. {
  201815. JUCEApplication::getInstance()->systemRequestedQuit();
  201816. return MessageManager::getInstance()->hasStopMessageBeenSent();
  201817. }
  201818. return TRUE;
  201819. case WM_TRAYNOTIFY:
  201820. if (component->isCurrentlyBlockedByAnotherModalComponent())
  201821. {
  201822. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  201823. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  201824. {
  201825. Component* const current = Component::getCurrentlyModalComponent();
  201826. if (current != 0)
  201827. current->inputAttemptWhenModal();
  201828. }
  201829. }
  201830. else
  201831. {
  201832. const int oldModifiers = currentModifiers;
  201833. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  201834. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  201835. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  201836. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  201837. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  201838. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  201839. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  201840. {
  201841. SetFocus (hwnd);
  201842. SetForegroundWindow (hwnd);
  201843. component->mouseDown (e);
  201844. }
  201845. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  201846. {
  201847. e.mods = ModifierKeys (oldModifiers);
  201848. component->mouseUp (e);
  201849. }
  201850. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  201851. {
  201852. e.mods = ModifierKeys (oldModifiers);
  201853. component->mouseDoubleClick (e);
  201854. }
  201855. else if (lParam == WM_MOUSEMOVE)
  201856. {
  201857. component->mouseMove (e);
  201858. }
  201859. }
  201860. break;
  201861. case WM_SYNCPAINT:
  201862. return 0;
  201863. case WM_PALETTECHANGED:
  201864. InvalidateRect (h, 0, 0);
  201865. break;
  201866. case WM_DISPLAYCHANGE:
  201867. InvalidateRect (h, 0, 0);
  201868. createPaletteIfNeeded = true;
  201869. // intentional fall-through...
  201870. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  201871. doSettingChange();
  201872. break;
  201873. case WM_INITMENU:
  201874. if (! hasTitleBar())
  201875. {
  201876. if (isFullScreen())
  201877. {
  201878. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  201879. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  201880. }
  201881. else if (! isMinimised())
  201882. {
  201883. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  201884. }
  201885. }
  201886. break;
  201887. case WM_SYSCOMMAND:
  201888. switch (wParam & 0xfff0)
  201889. {
  201890. case SC_CLOSE:
  201891. if (sendInputAttemptWhenModalMessage())
  201892. return 0;
  201893. if (hasTitleBar())
  201894. {
  201895. PostMessage (h, WM_CLOSE, 0, 0);
  201896. return 0;
  201897. }
  201898. break;
  201899. case SC_KEYMENU:
  201900. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  201901. // obscure situations that can arise if a modal loop is started from an alt-key
  201902. // keypress).
  201903. if (hasTitleBar() && h == GetCapture())
  201904. ReleaseCapture();
  201905. break;
  201906. case SC_MAXIMIZE:
  201907. if (sendInputAttemptWhenModalMessage())
  201908. return 0;
  201909. setFullScreen (true);
  201910. return 0;
  201911. case SC_MINIMIZE:
  201912. if (sendInputAttemptWhenModalMessage())
  201913. return 0;
  201914. if (! hasTitleBar())
  201915. {
  201916. setMinimised (true);
  201917. return 0;
  201918. }
  201919. break;
  201920. case SC_RESTORE:
  201921. if (sendInputAttemptWhenModalMessage())
  201922. return 0;
  201923. if (hasTitleBar())
  201924. {
  201925. if (isFullScreen())
  201926. {
  201927. setFullScreen (false);
  201928. return 0;
  201929. }
  201930. }
  201931. else
  201932. {
  201933. if (isMinimised())
  201934. setMinimised (false);
  201935. else if (isFullScreen())
  201936. setFullScreen (false);
  201937. return 0;
  201938. }
  201939. break;
  201940. }
  201941. break;
  201942. case WM_NCLBUTTONDOWN:
  201943. case WM_NCRBUTTONDOWN:
  201944. case WM_NCMBUTTONDOWN:
  201945. sendInputAttemptWhenModalMessage();
  201946. break;
  201947. //case WM_IME_STARTCOMPOSITION;
  201948. // return 0;
  201949. case WM_GETDLGCODE:
  201950. return DLGC_WANTALLKEYS;
  201951. default:
  201952. break;
  201953. }
  201954. }
  201955. }
  201956. // (the message manager lock exits before calling this, to avoid deadlocks if
  201957. // this calls into non-juce windows)
  201958. return DefWindowProc (h, message, wParam, lParam);
  201959. }
  201960. bool sendInputAttemptWhenModalMessage()
  201961. {
  201962. if (component->isCurrentlyBlockedByAnotherModalComponent())
  201963. {
  201964. Component* const current = Component::getCurrentlyModalComponent();
  201965. if (current != 0)
  201966. current->inputAttemptWhenModal();
  201967. return true;
  201968. }
  201969. return false;
  201970. }
  201971. Win32ComponentPeer (const Win32ComponentPeer&);
  201972. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  201973. };
  201974. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  201975. {
  201976. return new Win32ComponentPeer (this, styleFlags);
  201977. }
  201978. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  201979. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  201980. {
  201981. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  201982. if (wp != 0)
  201983. wp->setTaskBarIcon (&newImage);
  201984. }
  201985. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  201986. {
  201987. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  201988. if (wp != 0)
  201989. wp->setTaskBarIconToolTip (tooltip);
  201990. }
  201991. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  201992. {
  201993. DWORD val = GetWindowLong (h, styleType);
  201994. if (bitIsSet)
  201995. val |= feature;
  201996. else
  201997. val &= ~feature;
  201998. SetWindowLongPtr (h, styleType, val);
  201999. SetWindowPos (h, 0, 0, 0, 0, 0,
  202000. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  202001. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  202002. }
  202003. bool Process::isForegroundProcess() throw()
  202004. {
  202005. HWND fg = GetForegroundWindow();
  202006. if (fg == 0)
  202007. return true;
  202008. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  202009. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  202010. // have to see if any of our windows are children of the foreground window
  202011. fg = GetAncestor (fg, GA_ROOT);
  202012. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  202013. {
  202014. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  202015. if (wp != 0 && wp->isInside (fg))
  202016. return true;
  202017. }
  202018. return false;
  202019. }
  202020. bool AlertWindow::showNativeDialogBox (const String& title,
  202021. const String& bodyText,
  202022. bool isOkCancel)
  202023. {
  202024. return MessageBox (0, bodyText, title,
  202025. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  202026. : MB_OK)) == IDOK;
  202027. }
  202028. void Desktop::getMousePosition (int& x, int& y) throw()
  202029. {
  202030. POINT mousePos;
  202031. GetCursorPos (&mousePos);
  202032. x = mousePos.x;
  202033. y = mousePos.y;
  202034. }
  202035. void Desktop::setMousePosition (int x, int y) throw()
  202036. {
  202037. SetCursorPos (x, y);
  202038. }
  202039. class ScreenSaverDefeater : public Timer,
  202040. public DeletedAtShutdown
  202041. {
  202042. public:
  202043. ScreenSaverDefeater() throw()
  202044. {
  202045. startTimer (10000);
  202046. timerCallback();
  202047. }
  202048. ~ScreenSaverDefeater() {}
  202049. void timerCallback()
  202050. {
  202051. if (Process::isForegroundProcess())
  202052. {
  202053. // simulate a shift key getting pressed..
  202054. INPUT input[2];
  202055. input[0].type = INPUT_KEYBOARD;
  202056. input[0].ki.wVk = VK_SHIFT;
  202057. input[0].ki.dwFlags = 0;
  202058. input[0].ki.dwExtraInfo = 0;
  202059. input[1].type = INPUT_KEYBOARD;
  202060. input[1].ki.wVk = VK_SHIFT;
  202061. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  202062. input[1].ki.dwExtraInfo = 0;
  202063. SendInput (2, input, sizeof (INPUT));
  202064. }
  202065. }
  202066. };
  202067. static ScreenSaverDefeater* screenSaverDefeater = 0;
  202068. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  202069. {
  202070. if (isEnabled)
  202071. {
  202072. deleteAndZero (screenSaverDefeater);
  202073. }
  202074. else if (screenSaverDefeater == 0)
  202075. {
  202076. screenSaverDefeater = new ScreenSaverDefeater();
  202077. }
  202078. }
  202079. bool Desktop::isScreenSaverEnabled() throw()
  202080. {
  202081. return screenSaverDefeater == 0;
  202082. }
  202083. /* (The code below is the "correct" way to disable the screen saver, but it
  202084. completely fails on winXP when the saver is password-protected...)
  202085. static bool juce_screenSaverEnabled = true;
  202086. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  202087. {
  202088. juce_screenSaverEnabled = isEnabled;
  202089. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  202090. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  202091. }
  202092. bool Desktop::isScreenSaverEnabled() throw()
  202093. {
  202094. return juce_screenSaverEnabled;
  202095. }
  202096. */
  202097. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  202098. {
  202099. if (enableOrDisable)
  202100. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  202101. }
  202102. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  202103. {
  202104. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  202105. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  202106. return TRUE;
  202107. }
  202108. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  202109. {
  202110. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  202111. // make sure the first in the list is the main monitor
  202112. for (int i = 1; i < monitorCoords.size(); ++i)
  202113. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  202114. monitorCoords.swap (i, 0);
  202115. if (monitorCoords.size() == 0)
  202116. {
  202117. RECT r;
  202118. GetWindowRect (GetDesktopWindow(), &r);
  202119. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  202120. }
  202121. if (clipToWorkArea)
  202122. {
  202123. // clip the main monitor to the active non-taskbar area
  202124. RECT r;
  202125. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  202126. Rectangle& screen = monitorCoords.getReference (0);
  202127. screen.setPosition (jmax (screen.getX(), r.left),
  202128. jmax (screen.getY(), r.top));
  202129. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  202130. jmin (screen.getBottom(), r.bottom) - screen.getY());
  202131. }
  202132. }
  202133. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  202134. {
  202135. Image* im = 0;
  202136. if (bitmap != 0)
  202137. {
  202138. BITMAP bm;
  202139. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  202140. && bm.bmWidth > 0 && bm.bmHeight > 0)
  202141. {
  202142. HDC tempDC = GetDC (0);
  202143. HDC dc = CreateCompatibleDC (tempDC);
  202144. ReleaseDC (0, tempDC);
  202145. SelectObject (dc, bitmap);
  202146. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  202147. for (int y = bm.bmHeight; --y >= 0;)
  202148. {
  202149. for (int x = bm.bmWidth; --x >= 0;)
  202150. {
  202151. COLORREF col = GetPixel (dc, x, y);
  202152. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  202153. (uint8) GetGValue (col),
  202154. (uint8) GetBValue (col)));
  202155. }
  202156. }
  202157. DeleteDC (dc);
  202158. }
  202159. }
  202160. return im;
  202161. }
  202162. static Image* createImageFromHICON (HICON icon) throw()
  202163. {
  202164. ICONINFO info;
  202165. if (GetIconInfo (icon, &info))
  202166. {
  202167. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  202168. if (mask == 0)
  202169. return 0;
  202170. Image* const image = createImageFromHBITMAP (info.hbmColor);
  202171. if (image == 0)
  202172. return mask;
  202173. for (int y = image->getHeight(); --y >= 0;)
  202174. {
  202175. for (int x = image->getWidth(); --x >= 0;)
  202176. {
  202177. const float brightness = mask->getPixelAt (x, y).getBrightness();
  202178. if (brightness > 0.0f)
  202179. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  202180. }
  202181. }
  202182. delete mask;
  202183. return image;
  202184. }
  202185. return 0;
  202186. }
  202187. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  202188. {
  202189. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  202190. ICONINFO info;
  202191. info.fIcon = isIcon;
  202192. info.xHotspot = hotspotX;
  202193. info.yHotspot = hotspotY;
  202194. info.hbmMask = mask;
  202195. HICON hi = 0;
  202196. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  202197. {
  202198. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  202199. Graphics g (bitmap);
  202200. g.drawImageAt (&image, 0, 0);
  202201. info.hbmColor = bitmap.hBitmap;
  202202. hi = CreateIconIndirect (&info);
  202203. }
  202204. else
  202205. {
  202206. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  202207. HDC colDC = CreateCompatibleDC (GetDC (0));
  202208. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  202209. SelectObject (colDC, colour);
  202210. SelectObject (alphaDC, mask);
  202211. for (int y = image.getHeight(); --y >= 0;)
  202212. {
  202213. for (int x = image.getWidth(); --x >= 0;)
  202214. {
  202215. const Colour c (image.getPixelAt (x, y));
  202216. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  202217. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  202218. }
  202219. }
  202220. DeleteDC (colDC);
  202221. DeleteDC (alphaDC);
  202222. info.hbmColor = colour;
  202223. hi = CreateIconIndirect (&info);
  202224. DeleteObject (colour);
  202225. }
  202226. DeleteObject (mask);
  202227. return hi;
  202228. }
  202229. Image* juce_createIconForFile (const File& file)
  202230. {
  202231. Image* image = 0;
  202232. TCHAR filename [1024];
  202233. file.getFullPathName().copyToBuffer (filename, 1023);
  202234. WORD iconNum = 0;
  202235. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  202236. filename, &iconNum);
  202237. if (icon != 0)
  202238. {
  202239. image = createImageFromHICON (icon);
  202240. DestroyIcon (icon);
  202241. }
  202242. return image;
  202243. }
  202244. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  202245. {
  202246. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  202247. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  202248. const Image* im = &image;
  202249. Image* newIm = 0;
  202250. if (image.getWidth() > maxW || image.getHeight() > maxH)
  202251. {
  202252. im = newIm = image.createCopy (maxW, maxH);
  202253. hotspotX = (hotspotX * maxW) / image.getWidth();
  202254. hotspotY = (hotspotY * maxH) / image.getHeight();
  202255. }
  202256. void* cursorH = 0;
  202257. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  202258. if (os == SystemStats::WinXP)
  202259. {
  202260. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  202261. }
  202262. else
  202263. {
  202264. const int stride = (maxW + 7) >> 3;
  202265. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  202266. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  202267. int index = 0;
  202268. for (int y = 0; y < maxH; ++y)
  202269. {
  202270. for (int x = 0; x < maxW; ++x)
  202271. {
  202272. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  202273. const Colour pixelColour (im->getPixelAt (x, y));
  202274. if (pixelColour.getAlpha() < 127)
  202275. andPlane [index + (x >> 3)] |= bit;
  202276. else if (pixelColour.getBrightness() >= 0.5f)
  202277. xorPlane [index + (x >> 3)] |= bit;
  202278. }
  202279. index += stride;
  202280. }
  202281. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  202282. juce_free (andPlane);
  202283. juce_free (xorPlane);
  202284. }
  202285. delete newIm;
  202286. return cursorH;
  202287. }
  202288. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  202289. {
  202290. if (cursorHandle != 0 && ! isStandard)
  202291. DestroyCursor ((HCURSOR) cursorHandle);
  202292. }
  202293. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  202294. {
  202295. LPCTSTR cursorName = IDC_ARROW;
  202296. switch (type)
  202297. {
  202298. case MouseCursor::NormalCursor:
  202299. cursorName = IDC_ARROW;
  202300. break;
  202301. case MouseCursor::NoCursor:
  202302. return 0;
  202303. case MouseCursor::DraggingHandCursor:
  202304. {
  202305. static void* dragHandCursor = 0;
  202306. if (dragHandCursor == 0)
  202307. {
  202308. static const unsigned char dragHandData[] =
  202309. { 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,
  202310. 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,
  202311. 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 };
  202312. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  202313. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  202314. delete image;
  202315. }
  202316. return dragHandCursor;
  202317. }
  202318. case MouseCursor::WaitCursor:
  202319. cursorName = IDC_WAIT;
  202320. break;
  202321. case MouseCursor::IBeamCursor:
  202322. cursorName = IDC_IBEAM;
  202323. break;
  202324. case MouseCursor::PointingHandCursor:
  202325. cursorName = MAKEINTRESOURCE(32649);
  202326. break;
  202327. case MouseCursor::LeftRightResizeCursor:
  202328. case MouseCursor::LeftEdgeResizeCursor:
  202329. case MouseCursor::RightEdgeResizeCursor:
  202330. cursorName = IDC_SIZEWE;
  202331. break;
  202332. case MouseCursor::UpDownResizeCursor:
  202333. case MouseCursor::TopEdgeResizeCursor:
  202334. case MouseCursor::BottomEdgeResizeCursor:
  202335. cursorName = IDC_SIZENS;
  202336. break;
  202337. case MouseCursor::TopLeftCornerResizeCursor:
  202338. case MouseCursor::BottomRightCornerResizeCursor:
  202339. cursorName = IDC_SIZENWSE;
  202340. break;
  202341. case MouseCursor::TopRightCornerResizeCursor:
  202342. case MouseCursor::BottomLeftCornerResizeCursor:
  202343. cursorName = IDC_SIZENESW;
  202344. break;
  202345. case MouseCursor::UpDownLeftRightResizeCursor:
  202346. cursorName = IDC_SIZEALL;
  202347. break;
  202348. case MouseCursor::CrosshairCursor:
  202349. cursorName = IDC_CROSS;
  202350. break;
  202351. case MouseCursor::CopyingCursor:
  202352. // can't seem to find one of these in the win32 list..
  202353. break;
  202354. }
  202355. HCURSOR cursorH = LoadCursor (0, cursorName);
  202356. if (cursorH == 0)
  202357. cursorH = LoadCursor (0, IDC_ARROW);
  202358. return (void*) cursorH;
  202359. }
  202360. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  202361. {
  202362. SetCursor ((HCURSOR) getHandle());
  202363. }
  202364. void MouseCursor::showInAllWindows() const throw()
  202365. {
  202366. showInWindow (0);
  202367. }
  202368. class JuceDropSource : public IDropSource
  202369. {
  202370. int refCount;
  202371. public:
  202372. JuceDropSource()
  202373. : refCount (1)
  202374. {
  202375. }
  202376. virtual ~JuceDropSource()
  202377. {
  202378. jassert (refCount == 0);
  202379. }
  202380. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  202381. {
  202382. if (id == IID_IUnknown || id == IID_IDropSource)
  202383. {
  202384. AddRef();
  202385. *result = this;
  202386. return S_OK;
  202387. }
  202388. *result = 0;
  202389. return E_NOINTERFACE;
  202390. }
  202391. ULONG __stdcall AddRef() { return ++refCount; }
  202392. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  202393. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  202394. {
  202395. if (escapePressed)
  202396. return DRAGDROP_S_CANCEL;
  202397. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  202398. return DRAGDROP_S_DROP;
  202399. return S_OK;
  202400. }
  202401. HRESULT __stdcall GiveFeedback (DWORD)
  202402. {
  202403. return DRAGDROP_S_USEDEFAULTCURSORS;
  202404. }
  202405. };
  202406. class JuceEnumFormatEtc : public IEnumFORMATETC
  202407. {
  202408. public:
  202409. JuceEnumFormatEtc (const FORMATETC* const format_)
  202410. : refCount (1),
  202411. format (format_),
  202412. index (0)
  202413. {
  202414. }
  202415. virtual ~JuceEnumFormatEtc()
  202416. {
  202417. jassert (refCount == 0);
  202418. }
  202419. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  202420. {
  202421. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  202422. {
  202423. AddRef();
  202424. *result = this;
  202425. return S_OK;
  202426. }
  202427. *result = 0;
  202428. return E_NOINTERFACE;
  202429. }
  202430. ULONG __stdcall AddRef() { return ++refCount; }
  202431. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  202432. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  202433. {
  202434. if (result == 0)
  202435. return E_POINTER;
  202436. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  202437. newOne->index = index;
  202438. *result = newOne;
  202439. return S_OK;
  202440. }
  202441. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  202442. {
  202443. if (pceltFetched != 0)
  202444. *pceltFetched = 0;
  202445. else if (celt != 1)
  202446. return S_FALSE;
  202447. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  202448. {
  202449. copyFormatEtc (lpFormatEtc [0], *format);
  202450. ++index;
  202451. if (pceltFetched != 0)
  202452. *pceltFetched = 1;
  202453. return S_OK;
  202454. }
  202455. return S_FALSE;
  202456. }
  202457. HRESULT __stdcall Skip (ULONG celt)
  202458. {
  202459. if (index + (int) celt >= 1)
  202460. return S_FALSE;
  202461. index += celt;
  202462. return S_OK;
  202463. }
  202464. HRESULT __stdcall Reset()
  202465. {
  202466. index = 0;
  202467. return S_OK;
  202468. }
  202469. private:
  202470. int refCount;
  202471. const FORMATETC* const format;
  202472. int index;
  202473. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  202474. {
  202475. dest = source;
  202476. if (source.ptd != 0)
  202477. {
  202478. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  202479. *(dest.ptd) = *(source.ptd);
  202480. }
  202481. }
  202482. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  202483. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  202484. };
  202485. class JuceDataObject : public IDataObject
  202486. {
  202487. JuceDropSource* const dropSource;
  202488. const FORMATETC* const format;
  202489. const STGMEDIUM* const medium;
  202490. int refCount;
  202491. JuceDataObject (const JuceDataObject&);
  202492. const JuceDataObject& operator= (const JuceDataObject&);
  202493. public:
  202494. JuceDataObject (JuceDropSource* const dropSource_,
  202495. const FORMATETC* const format_,
  202496. const STGMEDIUM* const medium_)
  202497. : dropSource (dropSource_),
  202498. format (format_),
  202499. medium (medium_),
  202500. refCount (1)
  202501. {
  202502. }
  202503. virtual ~JuceDataObject()
  202504. {
  202505. jassert (refCount == 0);
  202506. }
  202507. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  202508. {
  202509. if (id == IID_IUnknown || id == IID_IDataObject)
  202510. {
  202511. AddRef();
  202512. *result = this;
  202513. return S_OK;
  202514. }
  202515. *result = 0;
  202516. return E_NOINTERFACE;
  202517. }
  202518. ULONG __stdcall AddRef() { return ++refCount; }
  202519. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  202520. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  202521. {
  202522. if (pFormatEtc->tymed == format->tymed
  202523. && pFormatEtc->cfFormat == format->cfFormat
  202524. && pFormatEtc->dwAspect == format->dwAspect)
  202525. {
  202526. pMedium->tymed = format->tymed;
  202527. pMedium->pUnkForRelease = 0;
  202528. if (format->tymed == TYMED_HGLOBAL)
  202529. {
  202530. const SIZE_T len = GlobalSize (medium->hGlobal);
  202531. void* const src = GlobalLock (medium->hGlobal);
  202532. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  202533. memcpy (dst, src, len);
  202534. GlobalUnlock (medium->hGlobal);
  202535. pMedium->hGlobal = dst;
  202536. return S_OK;
  202537. }
  202538. }
  202539. return DV_E_FORMATETC;
  202540. }
  202541. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  202542. {
  202543. if (f == 0)
  202544. return E_INVALIDARG;
  202545. if (f->tymed == format->tymed
  202546. && f->cfFormat == format->cfFormat
  202547. && f->dwAspect == format->dwAspect)
  202548. return S_OK;
  202549. return DV_E_FORMATETC;
  202550. }
  202551. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  202552. {
  202553. pFormatEtcOut->ptd = 0;
  202554. return E_NOTIMPL;
  202555. }
  202556. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  202557. {
  202558. if (result == 0)
  202559. return E_POINTER;
  202560. if (direction == DATADIR_GET)
  202561. {
  202562. *result = new JuceEnumFormatEtc (format);
  202563. return S_OK;
  202564. }
  202565. *result = 0;
  202566. return E_NOTIMPL;
  202567. }
  202568. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  202569. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  202570. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  202571. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  202572. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  202573. };
  202574. static HDROP createHDrop (const StringArray& fileNames) throw()
  202575. {
  202576. int totalChars = 0;
  202577. for (int i = fileNames.size(); --i >= 0;)
  202578. totalChars += fileNames[i].length() + 1;
  202579. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  202580. sizeof (DROPFILES)
  202581. + sizeof (WCHAR) * (totalChars + 2));
  202582. if (hDrop != 0)
  202583. {
  202584. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  202585. pDropFiles->pFiles = sizeof (DROPFILES);
  202586. pDropFiles->fWide = true;
  202587. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  202588. for (int i = 0; i < fileNames.size(); ++i)
  202589. {
  202590. fileNames[i].copyToBuffer (fname, 2048);
  202591. fname += fileNames[i].length() + 1;
  202592. }
  202593. *fname = 0;
  202594. GlobalUnlock (hDrop);
  202595. }
  202596. return hDrop;
  202597. }
  202598. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  202599. {
  202600. JuceDropSource* const source = new JuceDropSource();
  202601. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  202602. DWORD effect;
  202603. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  202604. data->Release();
  202605. source->Release();
  202606. return res == DRAGDROP_S_DROP;
  202607. }
  202608. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  202609. {
  202610. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  202611. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  202612. medium.hGlobal = createHDrop (files);
  202613. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  202614. : DROPEFFECT_COPY);
  202615. }
  202616. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  202617. {
  202618. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  202619. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  202620. const int numChars = text.length();
  202621. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  202622. char* d = (char*) GlobalLock (medium.hGlobal);
  202623. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  202624. format.cfFormat = CF_UNICODETEXT;
  202625. GlobalUnlock (medium.hGlobal);
  202626. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  202627. }
  202628. #endif
  202629. /********* End of inlined file: juce_win32_Windowing.cpp *********/
  202630. /********* Start of inlined file: juce_win32_Fonts.cpp *********/
  202631. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202632. // compiled on its own).
  202633. #if JUCE_INCLUDED_FILE
  202634. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  202635. NEWTEXTMETRICEXW*,
  202636. int type,
  202637. LPARAM lParam)
  202638. {
  202639. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  202640. {
  202641. const String fontName (lpelfe->elfLogFont.lfFaceName);
  202642. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters (T("@")));
  202643. }
  202644. return 1;
  202645. }
  202646. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  202647. NEWTEXTMETRICEXW*,
  202648. int type,
  202649. LPARAM lParam)
  202650. {
  202651. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  202652. {
  202653. LOGFONTW lf;
  202654. zerostruct (lf);
  202655. lf.lfWeight = FW_DONTCARE;
  202656. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  202657. lf.lfQuality = DEFAULT_QUALITY;
  202658. lf.lfCharSet = DEFAULT_CHARSET;
  202659. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  202660. lf.lfPitchAndFamily = FF_DONTCARE;
  202661. const String fontName (lpelfe->elfLogFont.lfFaceName);
  202662. fontName.copyToBuffer (lf.lfFaceName, LF_FACESIZE - 1);
  202663. HDC dc = CreateCompatibleDC (0);
  202664. EnumFontFamiliesEx (dc, &lf,
  202665. (FONTENUMPROCW) &wfontEnum2,
  202666. lParam, 0);
  202667. DeleteDC (dc);
  202668. }
  202669. return 1;
  202670. }
  202671. const StringArray Font::findAllTypefaceNames() throw()
  202672. {
  202673. StringArray results;
  202674. HDC dc = CreateCompatibleDC (0);
  202675. {
  202676. LOGFONTW lf;
  202677. zerostruct (lf);
  202678. lf.lfWeight = FW_DONTCARE;
  202679. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  202680. lf.lfQuality = DEFAULT_QUALITY;
  202681. lf.lfCharSet = DEFAULT_CHARSET;
  202682. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  202683. lf.lfPitchAndFamily = FF_DONTCARE;
  202684. lf.lfFaceName[0] = 0;
  202685. EnumFontFamiliesEx (dc, &lf,
  202686. (FONTENUMPROCW) &wfontEnum1,
  202687. (LPARAM) &results, 0);
  202688. }
  202689. DeleteDC (dc);
  202690. results.sort (true);
  202691. return results;
  202692. }
  202693. extern bool juce_IsRunningInWine() throw();
  202694. void Typeface::getDefaultFontNames (String& defaultSans,
  202695. String& defaultSerif,
  202696. String& defaultFixed) throw()
  202697. {
  202698. if (juce_IsRunningInWine())
  202699. {
  202700. // If we're running in Wine, then use fonts that might be available on Linux..
  202701. defaultSans = "Bitstream Vera Sans";
  202702. defaultSerif = "Bitstream Vera Serif";
  202703. defaultFixed = "Bitstream Vera Sans Mono";
  202704. }
  202705. else
  202706. {
  202707. defaultSans = "Verdana";
  202708. defaultSerif = "Times";
  202709. defaultFixed = "Lucida Console";
  202710. }
  202711. }
  202712. class FontDCHolder : private DeletedAtShutdown
  202713. {
  202714. HDC dc;
  202715. String fontName;
  202716. KERNINGPAIR* kps;
  202717. int numKPs;
  202718. bool bold, italic;
  202719. int size;
  202720. FontDCHolder (const FontDCHolder&);
  202721. const FontDCHolder& operator= (const FontDCHolder&);
  202722. public:
  202723. HFONT fontH;
  202724. FontDCHolder() throw()
  202725. : dc (0),
  202726. kps (0),
  202727. numKPs (0),
  202728. bold (false),
  202729. italic (false),
  202730. size (0)
  202731. {
  202732. }
  202733. ~FontDCHolder() throw()
  202734. {
  202735. if (dc != 0)
  202736. {
  202737. DeleteDC (dc);
  202738. DeleteObject (fontH);
  202739. juce_free (kps);
  202740. }
  202741. clearSingletonInstance();
  202742. }
  202743. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  202744. HDC loadFont (const String& fontName_,
  202745. const bool bold_,
  202746. const bool italic_,
  202747. const int size_) throw()
  202748. {
  202749. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  202750. {
  202751. fontName = fontName_;
  202752. bold = bold_;
  202753. italic = italic_;
  202754. size = size_;
  202755. if (dc != 0)
  202756. {
  202757. DeleteDC (dc);
  202758. DeleteObject (fontH);
  202759. juce_free (kps);
  202760. kps = 0;
  202761. }
  202762. fontH = 0;
  202763. dc = CreateCompatibleDC (0);
  202764. SetMapperFlags (dc, 0);
  202765. SetMapMode (dc, MM_TEXT);
  202766. LOGFONTW lfw;
  202767. zerostruct (lfw);
  202768. lfw.lfCharSet = DEFAULT_CHARSET;
  202769. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  202770. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  202771. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  202772. lfw.lfQuality = PROOF_QUALITY;
  202773. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  202774. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  202775. fontName.copyToBuffer (lfw.lfFaceName, LF_FACESIZE - 1);
  202776. lfw.lfHeight = size > 0 ? size : -256;
  202777. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  202778. if (standardSizedFont != 0)
  202779. {
  202780. if (SelectObject (dc, standardSizedFont) != 0)
  202781. {
  202782. fontH = standardSizedFont;
  202783. if (size == 0)
  202784. {
  202785. OUTLINETEXTMETRIC otm;
  202786. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  202787. {
  202788. lfw.lfHeight = -(int) otm.otmEMSquare;
  202789. fontH = CreateFontIndirect (&lfw);
  202790. SelectObject (dc, fontH);
  202791. DeleteObject (standardSizedFont);
  202792. }
  202793. }
  202794. }
  202795. else
  202796. {
  202797. jassertfalse
  202798. }
  202799. }
  202800. else
  202801. {
  202802. jassertfalse
  202803. }
  202804. }
  202805. return dc;
  202806. }
  202807. KERNINGPAIR* getKerningPairs (int& numKPs_) throw()
  202808. {
  202809. if (kps == 0)
  202810. {
  202811. numKPs = GetKerningPairs (dc, 0, 0);
  202812. kps = (KERNINGPAIR*) juce_calloc (sizeof (KERNINGPAIR) * numKPs);
  202813. GetKerningPairs (dc, numKPs, kps);
  202814. }
  202815. numKPs_ = numKPs;
  202816. return kps;
  202817. }
  202818. };
  202819. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  202820. static bool addGlyphToTypeface (HDC dc,
  202821. juce_wchar character,
  202822. Typeface& dest,
  202823. bool addKerning)
  202824. {
  202825. Path destShape;
  202826. GLYPHMETRICS gm;
  202827. float height;
  202828. BOOL ok = false;
  202829. {
  202830. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  202831. WORD index = 0;
  202832. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  202833. && index == 0xffff)
  202834. {
  202835. return false;
  202836. }
  202837. }
  202838. TEXTMETRIC tm;
  202839. ok = GetTextMetrics (dc, &tm);
  202840. height = (float) tm.tmHeight;
  202841. if (! ok)
  202842. {
  202843. dest.addGlyph (character, destShape, 0);
  202844. return true;
  202845. }
  202846. const float scaleX = 1.0f / height;
  202847. const float scaleY = -1.0f / height;
  202848. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  202849. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  202850. &gm, 0, 0, &identityMatrix);
  202851. if (bufSize > 0)
  202852. {
  202853. char* const data = (char*) juce_malloc (bufSize);
  202854. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  202855. bufSize, data, &identityMatrix);
  202856. const TTPOLYGONHEADER* pheader = (TTPOLYGONHEADER*) data;
  202857. while ((char*) pheader < data + bufSize)
  202858. {
  202859. #define remapX(v) (scaleX * (v).x.value)
  202860. #define remapY(v) (scaleY * (v).y.value)
  202861. float x = remapX (pheader->pfxStart);
  202862. float y = remapY (pheader->pfxStart);
  202863. destShape.startNewSubPath (x, y);
  202864. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  202865. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  202866. while ((const char*) curve < curveEnd)
  202867. {
  202868. if (curve->wType == TT_PRIM_LINE)
  202869. {
  202870. for (int i = 0; i < curve->cpfx; ++i)
  202871. {
  202872. x = remapX (curve->apfx [i]);
  202873. y = remapY (curve->apfx [i]);
  202874. destShape.lineTo (x, y);
  202875. }
  202876. }
  202877. else if (curve->wType == TT_PRIM_QSPLINE)
  202878. {
  202879. for (int i = 0; i < curve->cpfx - 1; ++i)
  202880. {
  202881. const float x2 = remapX (curve->apfx [i]);
  202882. const float y2 = remapY (curve->apfx [i]);
  202883. float x3, y3;
  202884. if (i < curve->cpfx - 2)
  202885. {
  202886. x3 = 0.5f * (x2 + remapX (curve->apfx [i + 1]));
  202887. y3 = 0.5f * (y2 + remapY (curve->apfx [i + 1]));
  202888. }
  202889. else
  202890. {
  202891. x3 = remapX (curve->apfx [i + 1]);
  202892. y3 = remapY (curve->apfx [i + 1]);
  202893. }
  202894. destShape.quadraticTo (x2, y2, x3, y3);
  202895. x = x3;
  202896. y = y3;
  202897. }
  202898. }
  202899. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  202900. }
  202901. pheader = (const TTPOLYGONHEADER*) curve;
  202902. destShape.closeSubPath();
  202903. }
  202904. juce_free (data);
  202905. }
  202906. dest.addGlyph (character, destShape, gm.gmCellIncX / height);
  202907. if (addKerning)
  202908. {
  202909. int numKPs;
  202910. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  202911. for (int i = 0; i < numKPs; ++i)
  202912. {
  202913. if (kps[i].wFirst == character)
  202914. {
  202915. dest.addKerningPair (kps[i].wFirst,
  202916. kps[i].wSecond,
  202917. kps[i].iKernAmount / height);
  202918. }
  202919. }
  202920. }
  202921. return true;
  202922. }
  202923. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  202924. {
  202925. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), 0);
  202926. return addGlyphToTypeface (dc, character, *this, true);
  202927. }
  202928. /*Image* Typeface::renderGlyphToImage (juce_wchar character, float& topLeftX, float& topLeftY)
  202929. {
  202930. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), hintingSize);
  202931. int bufSize;
  202932. GLYPHMETRICS gm;
  202933. const UINT format = GGO_GRAY2_BITMAP;
  202934. const int shift = 6;
  202935. if (wGetGlyphOutlineW != 0)
  202936. bufSize = wGetGlyphOutlineW (dc, character, format, &gm, 0, 0, &identityMatrix);
  202937. else
  202938. bufSize = GetGlyphOutline (dc, character, format, &gm, 0, 0, &identityMatrix);
  202939. Image* im = new Image (Image::SingleChannel, jmax (1, gm.gmBlackBoxX), jmax (1, gm.gmBlackBoxY), true);
  202940. if (bufSize > 0)
  202941. {
  202942. topLeftX = (float) gm.gmptGlyphOrigin.x;
  202943. topLeftY = (float) -gm.gmptGlyphOrigin.y;
  202944. uint8* const data = (uint8*) juce_calloc (bufSize);
  202945. if (wGetGlyphOutlineW != 0)
  202946. wGetGlyphOutlineW (dc, character, format, &gm, bufSize, data, &identityMatrix);
  202947. else
  202948. GetGlyphOutline (dc, character, format, &gm, bufSize, data, &identityMatrix);
  202949. const int stride = ((gm.gmBlackBoxX + 3) & ~3);
  202950. for (int y = gm.gmBlackBoxY; --y >= 0;)
  202951. {
  202952. for (int x = gm.gmBlackBoxX; --x >= 0;)
  202953. {
  202954. const int level = data [x + y * stride] << shift;
  202955. if (level > 0)
  202956. im->setPixelAt (x, y, Colour ((uint8) 0xff, (uint8) 0xff, (uint8) 0xff, (uint8) jmin (0xff, level)));
  202957. }
  202958. }
  202959. juce_free (data);
  202960. }
  202961. return im;
  202962. }*/
  202963. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  202964. bool bold,
  202965. bool italic,
  202966. bool addAllGlyphsToFont) throw()
  202967. {
  202968. clear();
  202969. HDC dc = FontDCHolder::getInstance()->loadFont (fontName, bold, italic, 0);
  202970. float height;
  202971. int firstChar, lastChar;
  202972. {
  202973. TEXTMETRIC tm;
  202974. GetTextMetrics (dc, &tm);
  202975. height = (float) tm.tmHeight;
  202976. firstChar = tm.tmFirstChar;
  202977. lastChar = tm.tmLastChar;
  202978. setAscent (tm.tmAscent / height);
  202979. setDefaultCharacter (tm.tmDefaultChar);
  202980. }
  202981. setName (fontName);
  202982. setBold (bold);
  202983. setItalic (italic);
  202984. if (addAllGlyphsToFont)
  202985. {
  202986. for (int character = firstChar; character <= lastChar; ++character)
  202987. addGlyphToTypeface (dc, (juce_wchar) character, *this, false);
  202988. int numKPs;
  202989. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  202990. for (int i = 0; i < numKPs; ++i)
  202991. {
  202992. addKerningPair (kps[i].wFirst,
  202993. kps[i].wSecond,
  202994. kps[i].iKernAmount / height);
  202995. }
  202996. }
  202997. }
  202998. #endif
  202999. /********* End of inlined file: juce_win32_Fonts.cpp *********/
  203000. /********* Start of inlined file: juce_win32_FileChooser.cpp *********/
  203001. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203002. // compiled on its own).
  203003. #if JUCE_INCLUDED_FILE
  203004. static const void* defaultDirPath = 0;
  203005. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  203006. static Component* currentExtraFileWin = 0;
  203007. static bool areThereAnyAlwaysOnTopWindows()
  203008. {
  203009. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  203010. {
  203011. Component* c = Desktop::getInstance().getComponent (i);
  203012. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  203013. return true;
  203014. }
  203015. return false;
  203016. }
  203017. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  203018. {
  203019. if (msg == BFFM_INITIALIZED)
  203020. {
  203021. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  203022. }
  203023. else if (msg == BFFM_VALIDATEFAILEDW)
  203024. {
  203025. returnedString = (LPCWSTR) lParam;
  203026. }
  203027. else if (msg == BFFM_VALIDATEFAILEDA)
  203028. {
  203029. returnedString = (const char*) lParam;
  203030. }
  203031. return 0;
  203032. }
  203033. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  203034. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  203035. {
  203036. if (currentExtraFileWin != 0)
  203037. {
  203038. if (uiMsg == WM_INITDIALOG)
  203039. {
  203040. HWND dialogH = GetParent (hdlg);
  203041. jassert (dialogH != 0);
  203042. if (dialogH == 0)
  203043. dialogH = hdlg;
  203044. RECT r, cr;
  203045. GetWindowRect (dialogH, &r);
  203046. GetClientRect (dialogH, &cr);
  203047. SetWindowPos (dialogH, 0,
  203048. r.left, r.top,
  203049. currentExtraFileWin->getWidth() + jmax (150, r.right - r.left),
  203050. jmax (150, r.bottom - r.top),
  203051. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  203052. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  203053. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  203054. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  203055. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  203056. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  203057. }
  203058. else if (uiMsg == WM_NOTIFY)
  203059. {
  203060. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  203061. if (ofn->hdr.code == CDN_SELCHANGE)
  203062. {
  203063. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  203064. if (comp != 0)
  203065. {
  203066. TCHAR path [MAX_PATH * 2];
  203067. path[0] = 0;
  203068. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  203069. const String fn ((const WCHAR*) path);
  203070. comp->selectedFileChanged (File (fn));
  203071. }
  203072. }
  203073. }
  203074. }
  203075. return 0;
  203076. }
  203077. class FPComponentHolder : public Component
  203078. {
  203079. public:
  203080. FPComponentHolder()
  203081. {
  203082. setVisible (true);
  203083. setOpaque (true);
  203084. }
  203085. ~FPComponentHolder()
  203086. {
  203087. }
  203088. void paint (Graphics& g)
  203089. {
  203090. g.fillAll (Colours::lightgrey);
  203091. }
  203092. private:
  203093. FPComponentHolder (const FPComponentHolder&);
  203094. const FPComponentHolder& operator= (const FPComponentHolder&);
  203095. };
  203096. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  203097. const String& title,
  203098. const File& currentFileOrDirectory,
  203099. const String& filter,
  203100. bool selectsDirectory,
  203101. bool isSaveDialogue,
  203102. bool warnAboutOverwritingExistingFiles,
  203103. bool selectMultipleFiles,
  203104. FilePreviewComponent* extraInfoComponent)
  203105. {
  203106. const int numCharsAvailable = 32768;
  203107. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  203108. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  203109. int fnameIdx = 0;
  203110. JUCE_TRY
  203111. {
  203112. // use a modal window as the parent for this dialog box
  203113. // to block input from other app windows
  203114. const Rectangle mainMon (Desktop::getInstance().getMainMonitorArea());
  203115. Component w (String::empty);
  203116. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  203117. mainMon.getY() + mainMon.getHeight() / 4,
  203118. 0, 0);
  203119. w.setOpaque (true);
  203120. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  203121. w.addToDesktop (0);
  203122. if (extraInfoComponent == 0)
  203123. w.enterModalState();
  203124. String initialDir;
  203125. if (currentFileOrDirectory.isDirectory())
  203126. {
  203127. initialDir = currentFileOrDirectory.getFullPathName();
  203128. }
  203129. else
  203130. {
  203131. currentFileOrDirectory.getFileName().copyToBuffer (fname, numCharsAvailable);
  203132. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  203133. }
  203134. if (currentExtraFileWin->isValidComponent())
  203135. {
  203136. jassertfalse
  203137. return;
  203138. }
  203139. if (selectsDirectory)
  203140. {
  203141. LPITEMIDLIST list = 0;
  203142. filenameSpace.fillWith (0);
  203143. {
  203144. BROWSEINFO bi;
  203145. zerostruct (bi);
  203146. bi.hwndOwner = (HWND) w.getWindowHandle();
  203147. bi.pszDisplayName = fname;
  203148. bi.lpszTitle = title;
  203149. bi.lpfn = browseCallbackProc;
  203150. #ifdef BIF_USENEWUI
  203151. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  203152. #else
  203153. bi.ulFlags = 0x50;
  203154. #endif
  203155. defaultDirPath = (const WCHAR*) initialDir;
  203156. list = SHBrowseForFolder (&bi);
  203157. if (! SHGetPathFromIDListW (list, fname))
  203158. {
  203159. fname[0] = 0;
  203160. returnedString = String::empty;
  203161. }
  203162. }
  203163. LPMALLOC al;
  203164. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  203165. al->Free (list);
  203166. defaultDirPath = 0;
  203167. if (returnedString.isNotEmpty())
  203168. {
  203169. const String stringFName (fname);
  203170. results.add (new File (File (stringFName).getSiblingFile (returnedString)));
  203171. returnedString = String::empty;
  203172. return;
  203173. }
  203174. }
  203175. else
  203176. {
  203177. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  203178. if (warnAboutOverwritingExistingFiles)
  203179. flags |= OFN_OVERWRITEPROMPT;
  203180. if (selectMultipleFiles)
  203181. flags |= OFN_ALLOWMULTISELECT;
  203182. if (extraInfoComponent != 0)
  203183. {
  203184. flags |= OFN_ENABLEHOOK;
  203185. currentExtraFileWin = new FPComponentHolder();
  203186. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  203187. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  203188. extraInfoComponent->getHeight());
  203189. currentExtraFileWin->addToDesktop (0);
  203190. currentExtraFileWin->enterModalState();
  203191. }
  203192. {
  203193. WCHAR filters [1024];
  203194. zeromem (filters, sizeof (filters));
  203195. filter.copyToBuffer (filters, 1024);
  203196. filter.copyToBuffer (filters + filter.length() + 1,
  203197. 1022 - filter.length());
  203198. OPENFILENAMEW of;
  203199. zerostruct (of);
  203200. #ifdef OPENFILENAME_SIZE_VERSION_400W
  203201. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  203202. #else
  203203. of.lStructSize = sizeof (of);
  203204. #endif
  203205. of.hwndOwner = (HWND) w.getWindowHandle();
  203206. of.lpstrFilter = filters;
  203207. of.nFilterIndex = 1;
  203208. of.lpstrFile = fname;
  203209. of.nMaxFile = numCharsAvailable;
  203210. of.lpstrInitialDir = initialDir;
  203211. of.lpstrTitle = title;
  203212. of.Flags = flags;
  203213. if (extraInfoComponent != 0)
  203214. of.lpfnHook = &openCallback;
  203215. if (isSaveDialogue)
  203216. {
  203217. if (! GetSaveFileName (&of))
  203218. fname[0] = 0;
  203219. else
  203220. fnameIdx = of.nFileOffset;
  203221. }
  203222. else
  203223. {
  203224. if (! GetOpenFileName (&of))
  203225. fname[0] = 0;
  203226. else
  203227. fnameIdx = of.nFileOffset;
  203228. }
  203229. }
  203230. }
  203231. }
  203232. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  203233. catch (...)
  203234. {
  203235. fname[0] = 0;
  203236. }
  203237. #endif
  203238. deleteAndZero (currentExtraFileWin);
  203239. const WCHAR* const files = fname;
  203240. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  203241. {
  203242. const WCHAR* filename = files + fnameIdx;
  203243. while (*filename != 0)
  203244. {
  203245. const String filepath (String (files) + T("\\") + String (filename));
  203246. results.add (new File (filepath));
  203247. filename += CharacterFunctions::length (filename) + 1;
  203248. }
  203249. }
  203250. else if (files[0] != 0)
  203251. {
  203252. results.add (new File (files));
  203253. }
  203254. }
  203255. #endif
  203256. /********* End of inlined file: juce_win32_FileChooser.cpp *********/
  203257. /********* Start of inlined file: juce_win32_Misc.cpp *********/
  203258. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203259. // compiled on its own).
  203260. #if JUCE_INCLUDED_FILE
  203261. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  203262. {
  203263. if (OpenClipboard (0) != 0)
  203264. {
  203265. if (EmptyClipboard() != 0)
  203266. {
  203267. const int len = text.length();
  203268. if (len > 0)
  203269. {
  203270. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  203271. (len + 1) * sizeof (wchar_t));
  203272. if (bufH != 0)
  203273. {
  203274. wchar_t* const data = (wchar_t*) GlobalLock (bufH);
  203275. text.copyToBuffer (data, len);
  203276. GlobalUnlock (bufH);
  203277. SetClipboardData (CF_UNICODETEXT, bufH);
  203278. }
  203279. }
  203280. }
  203281. CloseClipboard();
  203282. }
  203283. }
  203284. const String SystemClipboard::getTextFromClipboard() throw()
  203285. {
  203286. String result;
  203287. if (OpenClipboard (0) != 0)
  203288. {
  203289. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  203290. if (bufH != 0)
  203291. {
  203292. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  203293. if (data != 0)
  203294. {
  203295. result = String (data, (int) (GlobalSize (bufH) / sizeof (tchar)));
  203296. GlobalUnlock (bufH);
  203297. }
  203298. }
  203299. CloseClipboard();
  203300. }
  203301. return result;
  203302. }
  203303. #endif
  203304. /********* End of inlined file: juce_win32_Misc.cpp *********/
  203305. /********* Start of inlined file: juce_win32_ActiveXComponent.cpp *********/
  203306. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203307. // compiled on its own).
  203308. #if JUCE_INCLUDED_FILE
  203309. class JuceIStorage : public IStorage
  203310. {
  203311. int refCount;
  203312. public:
  203313. JuceIStorage() : refCount (1) {}
  203314. virtual ~JuceIStorage()
  203315. {
  203316. jassert (refCount == 0);
  203317. }
  203318. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203319. {
  203320. if (id == IID_IUnknown || id == IID_IStorage)
  203321. {
  203322. AddRef();
  203323. *result = this;
  203324. return S_OK;
  203325. }
  203326. *result = 0;
  203327. return E_NOINTERFACE;
  203328. }
  203329. ULONG __stdcall AddRef() { return ++refCount; }
  203330. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  203331. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  203332. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  203333. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  203334. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  203335. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  203336. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  203337. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  203338. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  203339. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  203340. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  203341. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  203342. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  203343. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  203344. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  203345. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  203346. juce_UseDebuggingNewOperator
  203347. };
  203348. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  203349. {
  203350. int refCount;
  203351. HWND window;
  203352. public:
  203353. JuceOleInPlaceFrame (HWND window_)
  203354. : refCount (1),
  203355. window (window_)
  203356. {
  203357. }
  203358. virtual ~JuceOleInPlaceFrame()
  203359. {
  203360. jassert (refCount == 0);
  203361. }
  203362. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203363. {
  203364. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  203365. {
  203366. AddRef();
  203367. *result = this;
  203368. return S_OK;
  203369. }
  203370. *result = 0;
  203371. return E_NOINTERFACE;
  203372. }
  203373. ULONG __stdcall AddRef() { return ++refCount; }
  203374. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  203375. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  203376. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  203377. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  203378. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  203379. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  203380. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  203381. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  203382. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  203383. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  203384. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  203385. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  203386. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  203387. juce_UseDebuggingNewOperator
  203388. };
  203389. class JuceIOleInPlaceSite : public IOleInPlaceSite
  203390. {
  203391. int refCount;
  203392. HWND window;
  203393. JuceOleInPlaceFrame* frame;
  203394. public:
  203395. JuceIOleInPlaceSite (HWND window_)
  203396. : refCount (1),
  203397. window (window_)
  203398. {
  203399. frame = new JuceOleInPlaceFrame (window);
  203400. }
  203401. virtual ~JuceIOleInPlaceSite()
  203402. {
  203403. jassert (refCount == 0);
  203404. frame->Release();
  203405. }
  203406. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203407. {
  203408. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  203409. {
  203410. AddRef();
  203411. *result = this;
  203412. return S_OK;
  203413. }
  203414. *result = 0;
  203415. return E_NOINTERFACE;
  203416. }
  203417. ULONG __stdcall AddRef() { return ++refCount; }
  203418. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  203419. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  203420. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  203421. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  203422. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  203423. HRESULT __stdcall OnUIActivate() { return S_OK; }
  203424. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  203425. {
  203426. frame->AddRef();
  203427. *lplpFrame = frame;
  203428. *lplpDoc = 0;
  203429. lpFrameInfo->fMDIApp = FALSE;
  203430. lpFrameInfo->hwndFrame = window;
  203431. lpFrameInfo->haccel = 0;
  203432. lpFrameInfo->cAccelEntries = 0;
  203433. return S_OK;
  203434. }
  203435. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  203436. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  203437. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  203438. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  203439. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  203440. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  203441. juce_UseDebuggingNewOperator
  203442. };
  203443. class JuceIOleClientSite : public IOleClientSite
  203444. {
  203445. int refCount;
  203446. JuceIOleInPlaceSite* inplaceSite;
  203447. public:
  203448. JuceIOleClientSite (HWND window)
  203449. : refCount (1)
  203450. {
  203451. inplaceSite = new JuceIOleInPlaceSite (window);
  203452. }
  203453. virtual ~JuceIOleClientSite()
  203454. {
  203455. jassert (refCount == 0);
  203456. inplaceSite->Release();
  203457. }
  203458. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203459. {
  203460. if (id == IID_IUnknown || id == IID_IOleClientSite)
  203461. {
  203462. AddRef();
  203463. *result = this;
  203464. return S_OK;
  203465. }
  203466. else if (id == IID_IOleInPlaceSite)
  203467. {
  203468. inplaceSite->AddRef();
  203469. *result = inplaceSite;
  203470. return S_OK;
  203471. }
  203472. *result = 0;
  203473. return E_NOINTERFACE;
  203474. }
  203475. ULONG __stdcall AddRef() { return ++refCount; }
  203476. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  203477. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  203478. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  203479. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  203480. HRESULT __stdcall ShowObject() { return S_OK; }
  203481. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  203482. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  203483. juce_UseDebuggingNewOperator
  203484. };
  203485. class ActiveXControlData : public ComponentMovementWatcher
  203486. {
  203487. ActiveXControlComponent* const owner;
  203488. bool wasShowing;
  203489. public:
  203490. HWND controlHWND;
  203491. IStorage* storage;
  203492. IOleClientSite* clientSite;
  203493. IOleObject* control;
  203494. ActiveXControlData (HWND hwnd,
  203495. ActiveXControlComponent* const owner_)
  203496. : ComponentMovementWatcher (owner_),
  203497. owner (owner_),
  203498. wasShowing (owner_ != 0 && owner_->isShowing()),
  203499. controlHWND (0),
  203500. storage (new JuceIStorage()),
  203501. clientSite (new JuceIOleClientSite (hwnd)),
  203502. control (0)
  203503. {
  203504. }
  203505. ~ActiveXControlData()
  203506. {
  203507. if (control != 0)
  203508. {
  203509. control->Close (OLECLOSE_NOSAVE);
  203510. control->Release();
  203511. }
  203512. clientSite->Release();
  203513. storage->Release();
  203514. }
  203515. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  203516. {
  203517. Component* const topComp = owner->getTopLevelComponent();
  203518. if (topComp->getPeer() != 0)
  203519. {
  203520. int x = 0, y = 0;
  203521. owner->relativePositionToOtherComponent (topComp, x, y);
  203522. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  203523. }
  203524. }
  203525. void componentPeerChanged()
  203526. {
  203527. const bool isShowingNow = owner->isShowing();
  203528. if (wasShowing != isShowingNow)
  203529. {
  203530. wasShowing = isShowingNow;
  203531. owner->setControlVisible (isShowingNow);
  203532. }
  203533. componentMovedOrResized (true, true);
  203534. }
  203535. void componentVisibilityChanged (Component&)
  203536. {
  203537. componentPeerChanged();
  203538. }
  203539. static bool doesWindowMatch (const ActiveXControlComponent* const ax, HWND hwnd)
  203540. {
  203541. return ((ActiveXControlData*) ax->control) != 0
  203542. && ((ActiveXControlData*) ax->control)->controlHWND == hwnd;
  203543. }
  203544. };
  203545. static VoidArray activeXComps;
  203546. static HWND getHWND (const ActiveXControlComponent* const component)
  203547. {
  203548. HWND hwnd = 0;
  203549. const IID iid = IID_IOleWindow;
  203550. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  203551. if (window != 0)
  203552. {
  203553. window->GetWindow (&hwnd);
  203554. window->Release();
  203555. }
  203556. return hwnd;
  203557. }
  203558. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  203559. {
  203560. RECT activeXRect, peerRect;
  203561. GetWindowRect (hwnd, &activeXRect);
  203562. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  203563. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  203564. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  203565. const int64 mouseEventTime = getMouseEventTime();
  203566. const int oldModifiers = currentModifiers;
  203567. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  203568. switch (message)
  203569. {
  203570. case WM_MOUSEMOVE:
  203571. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  203572. peer->handleMouseDrag (mx, my, mouseEventTime);
  203573. else
  203574. peer->handleMouseMove (mx, my, mouseEventTime);
  203575. break;
  203576. case WM_LBUTTONDOWN:
  203577. case WM_MBUTTONDOWN:
  203578. case WM_RBUTTONDOWN:
  203579. peer->handleMouseDown (mx, my, mouseEventTime);
  203580. break;
  203581. case WM_LBUTTONUP:
  203582. case WM_MBUTTONUP:
  203583. case WM_RBUTTONUP:
  203584. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  203585. break;
  203586. default:
  203587. break;
  203588. }
  203589. }
  203590. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  203591. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  203592. {
  203593. for (int i = activeXComps.size(); --i >= 0;)
  203594. {
  203595. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  203596. if (ActiveXControlData::doesWindowMatch (ax, hwnd))
  203597. {
  203598. switch (message)
  203599. {
  203600. case WM_MOUSEMOVE:
  203601. case WM_LBUTTONDOWN:
  203602. case WM_MBUTTONDOWN:
  203603. case WM_RBUTTONDOWN:
  203604. case WM_LBUTTONUP:
  203605. case WM_MBUTTONUP:
  203606. case WM_RBUTTONUP:
  203607. case WM_LBUTTONDBLCLK:
  203608. case WM_MBUTTONDBLCLK:
  203609. case WM_RBUTTONDBLCLK:
  203610. if (ax->isShowing())
  203611. {
  203612. ComponentPeer* const peer = ax->getPeer();
  203613. if (peer != 0)
  203614. {
  203615. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  203616. if (! ax->areMouseEventsAllowed())
  203617. return 0;
  203618. }
  203619. }
  203620. break;
  203621. default:
  203622. break;
  203623. }
  203624. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  203625. }
  203626. }
  203627. return DefWindowProc (hwnd, message, wParam, lParam);
  203628. }
  203629. ActiveXControlComponent::ActiveXControlComponent()
  203630. : originalWndProc (0),
  203631. control (0),
  203632. mouseEventsAllowed (true)
  203633. {
  203634. activeXComps.add (this);
  203635. }
  203636. ActiveXControlComponent::~ActiveXControlComponent()
  203637. {
  203638. deleteControl();
  203639. activeXComps.removeValue (this);
  203640. }
  203641. void ActiveXControlComponent::paint (Graphics& g)
  203642. {
  203643. if (control == 0)
  203644. g.fillAll (Colours::lightgrey);
  203645. }
  203646. bool ActiveXControlComponent::createControl (const void* controlIID)
  203647. {
  203648. deleteControl();
  203649. ComponentPeer* const peer = getPeer();
  203650. // the component must have already been added to a real window when you call this!
  203651. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  203652. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  203653. {
  203654. int x = 0, y = 0;
  203655. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  203656. HWND hwnd = (HWND) peer->getNativeHandle();
  203657. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  203658. HRESULT hr;
  203659. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  203660. info->clientSite, info->storage,
  203661. (void**) &(info->control))) == S_OK)
  203662. {
  203663. info->control->SetHostNames (L"Juce", 0);
  203664. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  203665. {
  203666. RECT rect;
  203667. rect.left = x;
  203668. rect.top = y;
  203669. rect.right = x + getWidth();
  203670. rect.bottom = y + getHeight();
  203671. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  203672. {
  203673. control = info;
  203674. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  203675. info->controlHWND = getHWND (this);
  203676. if (info->controlHWND != 0)
  203677. {
  203678. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC);
  203679. SetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  203680. }
  203681. return true;
  203682. }
  203683. }
  203684. }
  203685. delete info;
  203686. }
  203687. return false;
  203688. }
  203689. void ActiveXControlComponent::deleteControl()
  203690. {
  203691. ActiveXControlData* const info = (ActiveXControlData*) control;
  203692. if (info != 0)
  203693. {
  203694. delete info;
  203695. control = 0;
  203696. originalWndProc = 0;
  203697. }
  203698. }
  203699. void* ActiveXControlComponent::queryInterface (const void* iid) const
  203700. {
  203701. ActiveXControlData* const info = (ActiveXControlData*) control;
  203702. void* result = 0;
  203703. if (info != 0 && info->control != 0
  203704. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  203705. return result;
  203706. return 0;
  203707. }
  203708. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  203709. {
  203710. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  203711. if (hwnd != 0)
  203712. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  203713. }
  203714. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  203715. {
  203716. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  203717. if (hwnd != 0)
  203718. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  203719. }
  203720. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  203721. {
  203722. mouseEventsAllowed = eventsCanReachControl;
  203723. }
  203724. #endif
  203725. /********* End of inlined file: juce_win32_ActiveXComponent.cpp *********/
  203726. /********* Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp *********/
  203727. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203728. // compiled on its own).
  203729. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  203730. using namespace QTOLibrary;
  203731. using namespace QTOControlLib;
  203732. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  203733. static bool isQTAvailable = false;
  203734. struct QTMovieCompInternal
  203735. {
  203736. QTMovieCompInternal()
  203737. : dataHandle (0)
  203738. {
  203739. }
  203740. ~QTMovieCompInternal()
  203741. {
  203742. clearHandle();
  203743. }
  203744. IQTControlPtr qtControlInternal;
  203745. IQTMoviePtr qtMovieInternal;
  203746. Handle dataHandle;
  203747. void clearHandle()
  203748. {
  203749. if (dataHandle != 0)
  203750. {
  203751. DisposeHandle (dataHandle);
  203752. dataHandle = 0;
  203753. }
  203754. }
  203755. };
  203756. #define qtControl (((QTMovieCompInternal*) internal)->qtControlInternal)
  203757. #define qtMovie (((QTMovieCompInternal*) internal)->qtMovieInternal)
  203758. QuickTimeMovieComponent::QuickTimeMovieComponent()
  203759. : movieLoaded (false),
  203760. controllerVisible (true)
  203761. {
  203762. internal = new QTMovieCompInternal();
  203763. setMouseEventsAllowed (false);
  203764. }
  203765. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  203766. {
  203767. closeMovie();
  203768. qtControl = 0;
  203769. deleteControl();
  203770. delete internal;
  203771. internal = 0;
  203772. }
  203773. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  203774. {
  203775. if (! isQTAvailable)
  203776. {
  203777. isQTAvailable = (InitializeQTML (0) == noErr)
  203778. && (EnterMovies() == noErr);
  203779. }
  203780. return isQTAvailable;
  203781. }
  203782. void QuickTimeMovieComponent::createControlIfNeeded()
  203783. {
  203784. if (isShowing() && ! isControlCreated())
  203785. {
  203786. const IID qtIID = __uuidof (QTControl);
  203787. if (createControl (&qtIID))
  203788. {
  203789. const IID qtInterfaceIID = __uuidof (IQTControl);
  203790. qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  203791. if (qtControl != 0)
  203792. {
  203793. qtControl->Release(); // it has one ref too many at this point
  203794. qtControl->QuickTimeInitialize();
  203795. qtControl->PutSizing (qtMovieFitsControl);
  203796. if (movieFile != File::nonexistent)
  203797. loadMovie (movieFile, controllerVisible);
  203798. }
  203799. }
  203800. }
  203801. }
  203802. bool QuickTimeMovieComponent::isControlCreated() const
  203803. {
  203804. return isControlOpen();
  203805. }
  203806. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  203807. const bool isControllerVisible)
  203808. {
  203809. movieFile = File::nonexistent;
  203810. movieLoaded = false;
  203811. qtMovie = 0;
  203812. controllerVisible = isControllerVisible;
  203813. createControlIfNeeded();
  203814. if (isControlCreated())
  203815. {
  203816. if (qtControl != 0)
  203817. {
  203818. qtControl->Put_MovieHandle (0);
  203819. ((QTMovieCompInternal*) internal)->clearHandle();
  203820. Movie movie;
  203821. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, ((QTMovieCompInternal*) internal)->dataHandle))
  203822. {
  203823. qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  203824. qtMovie = qtControl->GetMovie();
  203825. if (qtMovie != 0)
  203826. qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  203827. : qtMovieControllerTypeNone);
  203828. }
  203829. if (movie == 0)
  203830. ((QTMovieCompInternal*) internal)->clearHandle();
  203831. }
  203832. movieLoaded = (qtMovie != 0);
  203833. }
  203834. else
  203835. {
  203836. // You're trying to open a movie when the control hasn't yet been created, probably because
  203837. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  203838. jassertfalse
  203839. }
  203840. delete movieStream;
  203841. return movieLoaded;
  203842. }
  203843. void QuickTimeMovieComponent::closeMovie()
  203844. {
  203845. stop();
  203846. movieFile = File::nonexistent;
  203847. movieLoaded = false;
  203848. qtMovie = 0;
  203849. if (qtControl != 0)
  203850. qtControl->Put_MovieHandle (0);
  203851. ((QTMovieCompInternal*) internal)->clearHandle();
  203852. }
  203853. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  203854. {
  203855. return movieFile;
  203856. }
  203857. bool QuickTimeMovieComponent::isMovieOpen() const
  203858. {
  203859. return movieLoaded;
  203860. }
  203861. double QuickTimeMovieComponent::getMovieDuration() const
  203862. {
  203863. if (qtMovie != 0)
  203864. return qtMovie->GetDuration() / (double) qtMovie->GetTimeScale();
  203865. return 0.0;
  203866. }
  203867. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  203868. {
  203869. if (qtMovie != 0)
  203870. {
  203871. struct QTRECT r = qtMovie->GetNaturalRect();
  203872. width = r.right - r.left;
  203873. height = r.bottom - r.top;
  203874. }
  203875. else
  203876. {
  203877. width = height = 0;
  203878. }
  203879. }
  203880. void QuickTimeMovieComponent::play()
  203881. {
  203882. if (qtMovie != 0)
  203883. qtMovie->Play();
  203884. }
  203885. void QuickTimeMovieComponent::stop()
  203886. {
  203887. if (qtMovie != 0)
  203888. qtMovie->Stop();
  203889. }
  203890. bool QuickTimeMovieComponent::isPlaying() const
  203891. {
  203892. return qtMovie != 0 && qtMovie->GetRate() != 0.0f;
  203893. }
  203894. void QuickTimeMovieComponent::setPosition (const double seconds)
  203895. {
  203896. if (qtMovie != 0)
  203897. qtMovie->PutTime ((long) (seconds * qtMovie->GetTimeScale()));
  203898. }
  203899. double QuickTimeMovieComponent::getPosition() const
  203900. {
  203901. if (qtMovie != 0)
  203902. return qtMovie->GetTime() / (double) qtMovie->GetTimeScale();
  203903. return 0.0;
  203904. }
  203905. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  203906. {
  203907. if (qtMovie != 0)
  203908. qtMovie->PutRate (newSpeed);
  203909. }
  203910. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  203911. {
  203912. if (qtMovie != 0)
  203913. {
  203914. qtMovie->PutAudioVolume (newVolume);
  203915. qtMovie->PutAudioMute (newVolume <= 0);
  203916. }
  203917. }
  203918. float QuickTimeMovieComponent::getMovieVolume() const
  203919. {
  203920. if (qtMovie != 0)
  203921. return qtMovie->GetAudioVolume();
  203922. return 0.0f;
  203923. }
  203924. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  203925. {
  203926. if (qtMovie != 0)
  203927. qtMovie->PutLoop (shouldLoop);
  203928. }
  203929. bool QuickTimeMovieComponent::isLooping() const
  203930. {
  203931. return qtMovie != 0 && qtMovie->GetLoop();
  203932. }
  203933. bool QuickTimeMovieComponent::isControllerVisible() const
  203934. {
  203935. return controllerVisible;
  203936. }
  203937. void QuickTimeMovieComponent::parentHierarchyChanged()
  203938. {
  203939. createControlIfNeeded();
  203940. QTCompBaseClass::parentHierarchyChanged();
  203941. }
  203942. void QuickTimeMovieComponent::visibilityChanged()
  203943. {
  203944. createControlIfNeeded();
  203945. QTCompBaseClass::visibilityChanged();
  203946. }
  203947. void QuickTimeMovieComponent::paint (Graphics& g)
  203948. {
  203949. if (! isControlCreated())
  203950. g.fillAll (Colours::black);
  203951. }
  203952. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  203953. {
  203954. Handle dataRef = 0;
  203955. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  203956. if (err == noErr)
  203957. {
  203958. Str255 suffix;
  203959. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  203960. StringPtr name = suffix;
  203961. err = PtrAndHand (name, dataRef, name[0] + 1);
  203962. if (err == noErr)
  203963. {
  203964. long atoms[3];
  203965. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  203966. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  203967. atoms[2] = EndianU32_NtoB (MovieFileType);
  203968. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  203969. if (err == noErr)
  203970. return dataRef;
  203971. }
  203972. DisposeHandle (dataRef);
  203973. }
  203974. return 0;
  203975. }
  203976. static CFStringRef juceStringToCFString (const String& s)
  203977. {
  203978. const int len = s.length();
  203979. const juce_wchar* const t = (const juce_wchar*) s;
  203980. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  203981. for (int i = 0; i <= len; ++i)
  203982. temp[i] = t[i];
  203983. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  203984. juce_free (temp);
  203985. return result;
  203986. }
  203987. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  203988. {
  203989. Boolean trueBool = true;
  203990. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  203991. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  203992. props[prop].propValueSize = sizeof (trueBool);
  203993. props[prop].propValueAddress = &trueBool;
  203994. ++prop;
  203995. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  203996. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  203997. props[prop].propValueSize = sizeof (trueBool);
  203998. props[prop].propValueAddress = &trueBool;
  203999. ++prop;
  204000. Boolean isActive = true;
  204001. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  204002. props[prop].propID = kQTNewMoviePropertyID_Active;
  204003. props[prop].propValueSize = sizeof (isActive);
  204004. props[prop].propValueAddress = &isActive;
  204005. ++prop;
  204006. MacSetPort (0);
  204007. jassert (prop <= 5);
  204008. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  204009. return err == noErr;
  204010. }
  204011. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  204012. {
  204013. if (input == 0)
  204014. return false;
  204015. dataHandle = 0;
  204016. bool ok = false;
  204017. QTNewMoviePropertyElement props[5];
  204018. zeromem (props, sizeof (props));
  204019. int prop = 0;
  204020. DataReferenceRecord dr;
  204021. props[prop].propClass = kQTPropertyClass_DataLocation;
  204022. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  204023. props[prop].propValueSize = sizeof (dr);
  204024. props[prop].propValueAddress = (void*) &dr;
  204025. ++prop;
  204026. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  204027. if (fin != 0)
  204028. {
  204029. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  204030. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  204031. &dr.dataRef, &dr.dataRefType);
  204032. ok = openMovie (props, prop, movie);
  204033. DisposeHandle (dr.dataRef);
  204034. CFRelease (filePath);
  204035. }
  204036. else
  204037. {
  204038. // sanity-check because this currently needs to load the whole stream into memory..
  204039. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  204040. dataHandle = NewHandle ((Size) input->getTotalLength());
  204041. HLock (dataHandle);
  204042. // read the entire stream into memory - this is a pain, but can't get it to work
  204043. // properly using a custom callback to supply the data.
  204044. input->read (*dataHandle, (int) input->getTotalLength());
  204045. HUnlock (dataHandle);
  204046. // different types to get QT to try. (We should really be a bit smarter here by
  204047. // working out in advance which one the stream contains, rather than just trying
  204048. // each one)
  204049. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  204050. "\04.avi", "\04.m4a" };
  204051. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  204052. {
  204053. /* // this fails for some bizarre reason - it can be bodged to work with
  204054. // movies, but can't seem to do it for other file types..
  204055. QTNewMovieUserProcRecord procInfo;
  204056. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  204057. procInfo.getMovieUserProcRefcon = this;
  204058. procInfo.defaultDataRef.dataRef = dataRef;
  204059. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  204060. props[prop].propClass = kQTPropertyClass_DataLocation;
  204061. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  204062. props[prop].propValueSize = sizeof (procInfo);
  204063. props[prop].propValueAddress = (void*) &procInfo;
  204064. ++prop; */
  204065. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  204066. dr.dataRefType = HandleDataHandlerSubType;
  204067. ok = openMovie (props, prop, movie);
  204068. DisposeHandle (dr.dataRef);
  204069. }
  204070. }
  204071. return ok;
  204072. }
  204073. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  204074. const bool isControllerVisible)
  204075. {
  204076. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  204077. movieFile = movieFile_;
  204078. return ok;
  204079. }
  204080. void QuickTimeMovieComponent::goToStart()
  204081. {
  204082. setPosition (0.0);
  204083. }
  204084. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  204085. const RectanglePlacement& placement)
  204086. {
  204087. int normalWidth, normalHeight;
  204088. getMovieNormalSize (normalWidth, normalHeight);
  204089. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  204090. {
  204091. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  204092. placement.applyTo (x, y, w, h,
  204093. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  204094. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  204095. if (w > 0 && h > 0)
  204096. {
  204097. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  204098. roundDoubleToInt (w), roundDoubleToInt (h));
  204099. }
  204100. }
  204101. else
  204102. {
  204103. setBounds (spaceToFitWithin);
  204104. }
  204105. }
  204106. #endif
  204107. /********* End of inlined file: juce_win32_QuickTimeMovieComponent.cpp *********/
  204108. /********* Start of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  204109. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204110. // compiled on its own).
  204111. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  204112. class WebBrowserComponentInternal : public ActiveXControlComponent
  204113. {
  204114. public:
  204115. WebBrowserComponentInternal()
  204116. : browser (0),
  204117. connectionPoint (0),
  204118. adviseCookie (0)
  204119. {
  204120. }
  204121. ~WebBrowserComponentInternal()
  204122. {
  204123. if (connectionPoint != 0)
  204124. connectionPoint->Unadvise (adviseCookie);
  204125. if (browser != 0)
  204126. browser->Release();
  204127. }
  204128. void createBrowser()
  204129. {
  204130. createControl (&CLSID_WebBrowser);
  204131. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  204132. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  204133. if (connectionPointContainer != 0)
  204134. {
  204135. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  204136. &connectionPoint);
  204137. if (connectionPoint != 0)
  204138. {
  204139. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  204140. jassert (owner != 0);
  204141. EventHandler* handler = new EventHandler (owner);
  204142. connectionPoint->Advise (handler, &adviseCookie);
  204143. }
  204144. }
  204145. }
  204146. void goToURL (const String& url,
  204147. const StringArray* headers,
  204148. const MemoryBlock* postData)
  204149. {
  204150. if (browser != 0)
  204151. {
  204152. LPSAFEARRAY sa = 0;
  204153. _variant_t flags, frame, postDataVar, headersVar;
  204154. if (headers != 0)
  204155. headersVar = (const tchar*) headers->joinIntoString ("\r\n");
  204156. if (postData != 0 && postData->getSize() > 0)
  204157. {
  204158. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  204159. if (sa != 0)
  204160. {
  204161. void* data = 0;
  204162. SafeArrayAccessData (sa, &data);
  204163. jassert (data != 0);
  204164. if (data != 0)
  204165. {
  204166. postData->copyTo (data, 0, postData->getSize());
  204167. SafeArrayUnaccessData (sa);
  204168. VARIANT postDataVar2;
  204169. VariantInit (&postDataVar2);
  204170. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  204171. V_ARRAY (&postDataVar2) = sa;
  204172. postDataVar = postDataVar2;
  204173. }
  204174. }
  204175. }
  204176. browser->Navigate ((BSTR) (const OLECHAR*) url,
  204177. &flags, &frame,
  204178. &postDataVar, &headersVar);
  204179. if (sa != 0)
  204180. SafeArrayDestroy (sa);
  204181. }
  204182. }
  204183. IWebBrowser2* browser;
  204184. juce_UseDebuggingNewOperator
  204185. private:
  204186. IConnectionPoint* connectionPoint;
  204187. DWORD adviseCookie;
  204188. class EventHandler : public IDispatch
  204189. {
  204190. public:
  204191. EventHandler (WebBrowserComponent* owner_)
  204192. : owner (owner_),
  204193. refCount (0)
  204194. {
  204195. }
  204196. ~EventHandler()
  204197. {
  204198. }
  204199. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204200. {
  204201. if (id == IID_IUnknown || id == IID_IDispatch || id == DIID_DWebBrowserEvents2)
  204202. {
  204203. AddRef();
  204204. *result = this;
  204205. return S_OK;
  204206. }
  204207. *result = 0;
  204208. return E_NOINTERFACE;
  204209. }
  204210. ULONG __stdcall AddRef() { return ++refCount; }
  204211. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  204212. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  204213. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  204214. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  204215. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  204216. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  204217. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  204218. UINT __RPC_FAR* /*puArgErr*/)
  204219. {
  204220. switch (dispIdMember)
  204221. {
  204222. case DISPID_BEFORENAVIGATE2:
  204223. {
  204224. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  204225. String url;
  204226. if ((vurl->vt & VT_BYREF) != 0)
  204227. url = *vurl->pbstrVal;
  204228. else
  204229. url = vurl->bstrVal;
  204230. *pDispParams->rgvarg->pboolVal
  204231. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  204232. : VARIANT_TRUE;
  204233. return S_OK;
  204234. }
  204235. default:
  204236. break;
  204237. }
  204238. return E_NOTIMPL;
  204239. }
  204240. juce_UseDebuggingNewOperator
  204241. private:
  204242. WebBrowserComponent* const owner;
  204243. int refCount;
  204244. EventHandler (const EventHandler&);
  204245. const EventHandler& operator= (const EventHandler&);
  204246. };
  204247. };
  204248. WebBrowserComponent::WebBrowserComponent()
  204249. : browser (0),
  204250. blankPageShown (false)
  204251. {
  204252. setOpaque (true);
  204253. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  204254. }
  204255. WebBrowserComponent::~WebBrowserComponent()
  204256. {
  204257. delete browser;
  204258. }
  204259. void WebBrowserComponent::goToURL (const String& url,
  204260. const StringArray* headers,
  204261. const MemoryBlock* postData)
  204262. {
  204263. lastURL = url;
  204264. lastHeaders.clear();
  204265. if (headers != 0)
  204266. lastHeaders = *headers;
  204267. lastPostData.setSize (0);
  204268. if (postData != 0)
  204269. lastPostData = *postData;
  204270. blankPageShown = false;
  204271. browser->goToURL (url, headers, postData);
  204272. }
  204273. void WebBrowserComponent::stop()
  204274. {
  204275. if (browser->browser != 0)
  204276. browser->browser->Stop();
  204277. }
  204278. void WebBrowserComponent::goBack()
  204279. {
  204280. lastURL = String::empty;
  204281. blankPageShown = false;
  204282. if (browser->browser != 0)
  204283. browser->browser->GoBack();
  204284. }
  204285. void WebBrowserComponent::goForward()
  204286. {
  204287. lastURL = String::empty;
  204288. if (browser->browser != 0)
  204289. browser->browser->GoForward();
  204290. }
  204291. void WebBrowserComponent::refresh()
  204292. {
  204293. if (browser->browser != 0)
  204294. browser->browser->Refresh();
  204295. }
  204296. void WebBrowserComponent::paint (Graphics& g)
  204297. {
  204298. if (browser->browser == 0)
  204299. g.fillAll (Colours::white);
  204300. }
  204301. void WebBrowserComponent::checkWindowAssociation()
  204302. {
  204303. if (isShowing())
  204304. {
  204305. if (browser->browser == 0 && getPeer() != 0)
  204306. {
  204307. browser->createBrowser();
  204308. reloadLastURL();
  204309. }
  204310. else
  204311. {
  204312. if (blankPageShown)
  204313. goBack();
  204314. }
  204315. }
  204316. else
  204317. {
  204318. if (browser != 0 && ! blankPageShown)
  204319. {
  204320. // when the component becomes invisible, some stuff like flash
  204321. // carries on playing audio, so we need to force it onto a blank
  204322. // page to avoid this..
  204323. blankPageShown = true;
  204324. browser->goToURL ("about:blank", 0, 0);
  204325. }
  204326. }
  204327. }
  204328. void WebBrowserComponent::reloadLastURL()
  204329. {
  204330. if (lastURL.isNotEmpty())
  204331. {
  204332. goToURL (lastURL, &lastHeaders, &lastPostData);
  204333. lastURL = String::empty;
  204334. }
  204335. }
  204336. void WebBrowserComponent::parentHierarchyChanged()
  204337. {
  204338. checkWindowAssociation();
  204339. }
  204340. void WebBrowserComponent::resized()
  204341. {
  204342. browser->setSize (getWidth(), getHeight());
  204343. }
  204344. void WebBrowserComponent::visibilityChanged()
  204345. {
  204346. checkWindowAssociation();
  204347. }
  204348. bool WebBrowserComponent::pageAboutToLoad (const String&)
  204349. {
  204350. return true;
  204351. }
  204352. #endif
  204353. /********* End of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  204354. /********* Start of inlined file: juce_win32_OpenGLComponent.cpp *********/
  204355. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204356. // compiled on its own).
  204357. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  204358. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  204359. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  204360. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  204361. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  204362. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  204363. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  204364. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  204365. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  204366. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  204367. #define WGL_ACCELERATION_ARB 0x2003
  204368. #define WGL_SWAP_METHOD_ARB 0x2007
  204369. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  204370. #define WGL_PIXEL_TYPE_ARB 0x2013
  204371. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  204372. #define WGL_COLOR_BITS_ARB 0x2014
  204373. #define WGL_RED_BITS_ARB 0x2015
  204374. #define WGL_GREEN_BITS_ARB 0x2017
  204375. #define WGL_BLUE_BITS_ARB 0x2019
  204376. #define WGL_ALPHA_BITS_ARB 0x201B
  204377. #define WGL_DEPTH_BITS_ARB 0x2022
  204378. #define WGL_STENCIL_BITS_ARB 0x2023
  204379. #define WGL_FULL_ACCELERATION_ARB 0x2027
  204380. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  204381. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  204382. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  204383. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  204384. #define WGL_STEREO_ARB 0x2012
  204385. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  204386. #define WGL_SAMPLES_ARB 0x2042
  204387. #define WGL_TYPE_RGBA_ARB 0x202B
  204388. static void getWglExtensions (HDC dc, StringArray& result) throw()
  204389. {
  204390. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  204391. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  204392. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  204393. else
  204394. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  204395. }
  204396. class WindowedGLContext : public OpenGLContext
  204397. {
  204398. public:
  204399. WindowedGLContext (Component* const component_,
  204400. HGLRC contextToShareWith,
  204401. const OpenGLPixelFormat& pixelFormat)
  204402. : renderContext (0),
  204403. nativeWindow (0),
  204404. dc (0),
  204405. component (component_)
  204406. {
  204407. jassert (component != 0);
  204408. createNativeWindow();
  204409. // Use a default pixel format that should be supported everywhere
  204410. PIXELFORMATDESCRIPTOR pfd;
  204411. zerostruct (pfd);
  204412. pfd.nSize = sizeof (pfd);
  204413. pfd.nVersion = 1;
  204414. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  204415. pfd.iPixelType = PFD_TYPE_RGBA;
  204416. pfd.cColorBits = 24;
  204417. pfd.cDepthBits = 16;
  204418. const int format = ChoosePixelFormat (dc, &pfd);
  204419. if (format != 0)
  204420. SetPixelFormat (dc, format, &pfd);
  204421. renderContext = wglCreateContext (dc);
  204422. makeActive();
  204423. setPixelFormat (pixelFormat);
  204424. if (contextToShareWith != 0 && renderContext != 0)
  204425. wglShareLists (contextToShareWith, renderContext);
  204426. }
  204427. ~WindowedGLContext()
  204428. {
  204429. makeInactive();
  204430. wglDeleteContext (renderContext);
  204431. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  204432. delete nativeWindow;
  204433. }
  204434. bool makeActive() const throw()
  204435. {
  204436. jassert (renderContext != 0);
  204437. return wglMakeCurrent (dc, renderContext) != 0;
  204438. }
  204439. bool makeInactive() const throw()
  204440. {
  204441. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  204442. }
  204443. bool isActive() const throw()
  204444. {
  204445. return wglGetCurrentContext() == renderContext;
  204446. }
  204447. const OpenGLPixelFormat getPixelFormat() const
  204448. {
  204449. OpenGLPixelFormat pf;
  204450. makeActive();
  204451. StringArray availableExtensions;
  204452. getWglExtensions (dc, availableExtensions);
  204453. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  204454. return pf;
  204455. }
  204456. void* getRawContext() const throw()
  204457. {
  204458. return renderContext;
  204459. }
  204460. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  204461. {
  204462. makeActive();
  204463. PIXELFORMATDESCRIPTOR pfd;
  204464. zerostruct (pfd);
  204465. pfd.nSize = sizeof (pfd);
  204466. pfd.nVersion = 1;
  204467. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  204468. pfd.iPixelType = PFD_TYPE_RGBA;
  204469. pfd.iLayerType = PFD_MAIN_PLANE;
  204470. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  204471. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  204472. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  204473. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  204474. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  204475. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  204476. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  204477. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  204478. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  204479. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  204480. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  204481. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  204482. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  204483. int format = 0;
  204484. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  204485. StringArray availableExtensions;
  204486. getWglExtensions (dc, availableExtensions);
  204487. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  204488. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  204489. {
  204490. int attributes[64];
  204491. int n = 0;
  204492. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  204493. attributes[n++] = GL_TRUE;
  204494. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  204495. attributes[n++] = GL_TRUE;
  204496. attributes[n++] = WGL_ACCELERATION_ARB;
  204497. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  204498. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  204499. attributes[n++] = GL_TRUE;
  204500. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  204501. attributes[n++] = WGL_TYPE_RGBA_ARB;
  204502. attributes[n++] = WGL_COLOR_BITS_ARB;
  204503. attributes[n++] = pfd.cColorBits;
  204504. attributes[n++] = WGL_RED_BITS_ARB;
  204505. attributes[n++] = pixelFormat.redBits;
  204506. attributes[n++] = WGL_GREEN_BITS_ARB;
  204507. attributes[n++] = pixelFormat.greenBits;
  204508. attributes[n++] = WGL_BLUE_BITS_ARB;
  204509. attributes[n++] = pixelFormat.blueBits;
  204510. attributes[n++] = WGL_ALPHA_BITS_ARB;
  204511. attributes[n++] = pixelFormat.alphaBits;
  204512. attributes[n++] = WGL_DEPTH_BITS_ARB;
  204513. attributes[n++] = pixelFormat.depthBufferBits;
  204514. if (pixelFormat.stencilBufferBits > 0)
  204515. {
  204516. attributes[n++] = WGL_STENCIL_BITS_ARB;
  204517. attributes[n++] = pixelFormat.stencilBufferBits;
  204518. }
  204519. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  204520. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  204521. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  204522. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  204523. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  204524. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  204525. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  204526. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  204527. if (availableExtensions.contains ("WGL_ARB_multisample")
  204528. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  204529. {
  204530. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  204531. attributes[n++] = 1;
  204532. attributes[n++] = WGL_SAMPLES_ARB;
  204533. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  204534. }
  204535. attributes[n++] = 0;
  204536. UINT formatsCount;
  204537. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  204538. (void) ok;
  204539. jassert (ok);
  204540. }
  204541. else
  204542. {
  204543. format = ChoosePixelFormat (dc, &pfd);
  204544. }
  204545. if (format != 0)
  204546. {
  204547. makeInactive();
  204548. // win32 can't change the pixel format of a window, so need to delete the
  204549. // old one and create a new one..
  204550. jassert (nativeWindow != 0);
  204551. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  204552. delete nativeWindow;
  204553. createNativeWindow();
  204554. if (SetPixelFormat (dc, format, &pfd))
  204555. {
  204556. wglDeleteContext (renderContext);
  204557. renderContext = wglCreateContext (dc);
  204558. jassert (renderContext != 0);
  204559. return renderContext != 0;
  204560. }
  204561. }
  204562. return false;
  204563. }
  204564. void updateWindowPosition (int x, int y, int w, int h, int)
  204565. {
  204566. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  204567. x, y, w, h,
  204568. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204569. }
  204570. void repaint()
  204571. {
  204572. int x, y, w, h;
  204573. nativeWindow->getBounds (x, y, w, h);
  204574. nativeWindow->repaint (0, 0, w, h);
  204575. }
  204576. void swapBuffers()
  204577. {
  204578. SwapBuffers (dc);
  204579. }
  204580. bool setSwapInterval (const int numFramesPerSwap)
  204581. {
  204582. makeActive();
  204583. StringArray availableExtensions;
  204584. getWglExtensions (dc, availableExtensions);
  204585. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  204586. return availableExtensions.contains ("WGL_EXT_swap_control")
  204587. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  204588. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  204589. }
  204590. int getSwapInterval() const
  204591. {
  204592. makeActive();
  204593. StringArray availableExtensions;
  204594. getWglExtensions (dc, availableExtensions);
  204595. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  204596. if (availableExtensions.contains ("WGL_EXT_swap_control")
  204597. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  204598. return wglGetSwapIntervalEXT();
  204599. return 0;
  204600. }
  204601. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  204602. {
  204603. jassert (isActive());
  204604. StringArray availableExtensions;
  204605. getWglExtensions (dc, availableExtensions);
  204606. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  204607. int numTypes = 0;
  204608. if (availableExtensions.contains("WGL_ARB_pixel_format")
  204609. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  204610. {
  204611. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  204612. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  204613. jassertfalse
  204614. }
  204615. else
  204616. {
  204617. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  204618. }
  204619. OpenGLPixelFormat pf;
  204620. for (int i = 0; i < numTypes; ++i)
  204621. {
  204622. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  204623. {
  204624. bool alreadyListed = false;
  204625. for (int j = results.size(); --j >= 0;)
  204626. if (pf == *results.getUnchecked(j))
  204627. alreadyListed = true;
  204628. if (! alreadyListed)
  204629. results.add (new OpenGLPixelFormat (pf));
  204630. }
  204631. }
  204632. }
  204633. void* getNativeWindowHandle() const
  204634. {
  204635. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  204636. }
  204637. juce_UseDebuggingNewOperator
  204638. HGLRC renderContext;
  204639. private:
  204640. Win32ComponentPeer* nativeWindow;
  204641. Component* const component;
  204642. HDC dc;
  204643. void createNativeWindow()
  204644. {
  204645. nativeWindow = new Win32ComponentPeer (component, 0);
  204646. nativeWindow->dontRepaint = true;
  204647. nativeWindow->setVisible (true);
  204648. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  204649. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  204650. if (peer != 0)
  204651. {
  204652. SetParent (hwnd, (HWND) peer->getNativeHandle());
  204653. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  204654. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  204655. }
  204656. dc = GetDC (hwnd);
  204657. }
  204658. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  204659. OpenGLPixelFormat& result,
  204660. const StringArray& availableExtensions) const throw()
  204661. {
  204662. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  204663. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  204664. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  204665. {
  204666. int attributes[32];
  204667. int numAttributes = 0;
  204668. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  204669. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  204670. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  204671. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  204672. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  204673. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  204674. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  204675. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  204676. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  204677. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  204678. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  204679. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  204680. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  204681. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  204682. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  204683. if (availableExtensions.contains ("WGL_ARB_multisample"))
  204684. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  204685. int values[32];
  204686. zeromem (values, sizeof (values));
  204687. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  204688. {
  204689. int n = 0;
  204690. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  204691. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  204692. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  204693. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  204694. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  204695. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  204696. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  204697. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  204698. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  204699. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  204700. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  204701. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  204702. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  204703. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  204704. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  204705. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  204706. return isValidFormat;
  204707. }
  204708. else
  204709. {
  204710. jassertfalse
  204711. }
  204712. }
  204713. else
  204714. {
  204715. PIXELFORMATDESCRIPTOR pfd;
  204716. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  204717. {
  204718. result.redBits = pfd.cRedBits;
  204719. result.greenBits = pfd.cGreenBits;
  204720. result.blueBits = pfd.cBlueBits;
  204721. result.alphaBits = pfd.cAlphaBits;
  204722. result.depthBufferBits = pfd.cDepthBits;
  204723. result.stencilBufferBits = pfd.cStencilBits;
  204724. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  204725. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  204726. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  204727. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  204728. result.fullSceneAntiAliasingNumSamples = 0;
  204729. return true;
  204730. }
  204731. else
  204732. {
  204733. jassertfalse
  204734. }
  204735. }
  204736. return false;
  204737. }
  204738. WindowedGLContext (const WindowedGLContext&);
  204739. const WindowedGLContext& operator= (const WindowedGLContext&);
  204740. };
  204741. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  204742. const OpenGLPixelFormat& pixelFormat,
  204743. const OpenGLContext* const contextToShareWith)
  204744. {
  204745. WindowedGLContext* c = new WindowedGLContext (component,
  204746. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  204747. pixelFormat);
  204748. if (c->renderContext == 0)
  204749. deleteAndZero (c);
  204750. return c;
  204751. }
  204752. void* OpenGLComponent::getNativeWindowHandle() const
  204753. {
  204754. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle() : 0;
  204755. }
  204756. void juce_glViewport (const int w, const int h)
  204757. {
  204758. glViewport (0, 0, w, h);
  204759. }
  204760. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  204761. OwnedArray <OpenGLPixelFormat>& results)
  204762. {
  204763. Component tempComp;
  204764. {
  204765. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  204766. wc.makeActive();
  204767. wc.findAlternativeOpenGLPixelFormats (results);
  204768. }
  204769. }
  204770. #endif
  204771. /********* End of inlined file: juce_win32_OpenGLComponent.cpp *********/
  204772. /********* Start of inlined file: juce_win32_AudioCDReader.cpp *********/
  204773. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204774. // compiled on its own).
  204775. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  204776. //***************************************************************************
  204777. // %%% TARGET STATUS VALUES %%%
  204778. //***************************************************************************
  204779. #define STATUS_GOOD 0x00 // Status Good
  204780. #define STATUS_CHKCOND 0x02 // Check Condition
  204781. #define STATUS_CONDMET 0x04 // Condition Met
  204782. #define STATUS_BUSY 0x08 // Busy
  204783. #define STATUS_INTERM 0x10 // Intermediate
  204784. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  204785. #define STATUS_RESCONF 0x18 // Reservation conflict
  204786. #define STATUS_COMTERM 0x22 // Command Terminated
  204787. #define STATUS_QFULL 0x28 // Queue full
  204788. //***************************************************************************
  204789. // %%% SCSI MISCELLANEOUS EQUATES %%%
  204790. //***************************************************************************
  204791. #define MAXLUN 7 // Maximum Logical Unit Id
  204792. #define MAXTARG 7 // Maximum Target Id
  204793. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  204794. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  204795. //***************************************************************************
  204796. // %%% Commands for all Device Types %%%
  204797. //***************************************************************************
  204798. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  204799. #define SCSI_COMPARE 0x39 // Compare (O)
  204800. #define SCSI_COPY 0x18 // Copy (O)
  204801. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  204802. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  204803. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  204804. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  204805. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  204806. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  204807. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  204808. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  204809. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  204810. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  204811. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  204812. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  204813. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  204814. //***************************************************************************
  204815. // %%% Commands Unique to Direct Access Devices %%%
  204816. //***************************************************************************
  204817. #define SCSI_COMPARE 0x39 // Compare (O)
  204818. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  204819. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  204820. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  204821. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  204822. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  204823. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  204824. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  204825. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  204826. #define SCSI_READ_LONG 0x3E // Read Long (O)
  204827. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  204828. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  204829. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  204830. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  204831. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  204832. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  204833. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  204834. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  204835. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  204836. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  204837. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  204838. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  204839. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  204840. #define SCSI_VERIFY 0x2F // Verify (O)
  204841. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  204842. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  204843. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  204844. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  204845. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  204846. //***************************************************************************
  204847. // %%% Commands Unique to Sequential Access Devices %%%
  204848. //***************************************************************************
  204849. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  204850. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  204851. #define SCSI_LOCATE 0x2B // Locate (O)
  204852. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  204853. #define SCSI_READ_POS 0x34 // Read Position (O)
  204854. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  204855. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  204856. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  204857. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  204858. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  204859. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  204860. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  204861. //***************************************************************************
  204862. // %%% Commands Unique to Printer Devices %%%
  204863. //***************************************************************************
  204864. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  204865. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  204866. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  204867. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  204868. //***************************************************************************
  204869. // %%% Commands Unique to Processor Devices %%%
  204870. //***************************************************************************
  204871. #define SCSI_RECEIVE 0x08 // Receive (O)
  204872. #define SCSI_SEND 0x0A // Send (O)
  204873. //***************************************************************************
  204874. // %%% Commands Unique to Write-Once Devices %%%
  204875. //***************************************************************************
  204876. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  204877. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  204878. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  204879. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  204880. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  204881. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  204882. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  204883. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  204884. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  204885. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  204886. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  204887. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  204888. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  204889. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  204890. //***************************************************************************
  204891. // %%% Commands Unique to CD-ROM Devices %%%
  204892. //***************************************************************************
  204893. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  204894. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  204895. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  204896. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  204897. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  204898. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  204899. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  204900. #define SCSI_READHEADER 0x44 // Read Header (O)
  204901. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  204902. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  204903. //***************************************************************************
  204904. // %%% Commands Unique to Scanner Devices %%%
  204905. //***************************************************************************
  204906. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  204907. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  204908. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  204909. #define SCSI_SCAN 0x1B // Scan (O)
  204910. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  204911. //***************************************************************************
  204912. // %%% Commands Unique to Optical Memory Devices %%%
  204913. //***************************************************************************
  204914. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  204915. //***************************************************************************
  204916. // %%% Commands Unique to Medium Changer Devices %%%
  204917. //***************************************************************************
  204918. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  204919. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  204920. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  204921. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  204922. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  204923. //***************************************************************************
  204924. // %%% Commands Unique to Communication Devices %%%
  204925. //***************************************************************************
  204926. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  204927. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  204928. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  204929. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  204930. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  204931. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  204932. //***************************************************************************
  204933. // %%% Request Sense Data Format %%%
  204934. //***************************************************************************
  204935. typedef struct {
  204936. BYTE ErrorCode; // Error Code (70H or 71H)
  204937. BYTE SegmentNum; // Number of current segment descriptor
  204938. BYTE SenseKey; // Sense Key(See bit definitions too)
  204939. BYTE InfoByte0; // Information MSB
  204940. BYTE InfoByte1; // Information MID
  204941. BYTE InfoByte2; // Information MID
  204942. BYTE InfoByte3; // Information LSB
  204943. BYTE AddSenLen; // Additional Sense Length
  204944. BYTE ComSpecInf0; // Command Specific Information MSB
  204945. BYTE ComSpecInf1; // Command Specific Information MID
  204946. BYTE ComSpecInf2; // Command Specific Information MID
  204947. BYTE ComSpecInf3; // Command Specific Information LSB
  204948. BYTE AddSenseCode; // Additional Sense Code
  204949. BYTE AddSenQual; // Additional Sense Code Qualifier
  204950. BYTE FieldRepUCode; // Field Replaceable Unit Code
  204951. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  204952. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  204953. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  204954. BYTE AddSenseBytes; // Additional Sense Bytes
  204955. } SENSE_DATA_FMT;
  204956. //***************************************************************************
  204957. // %%% REQUEST SENSE ERROR CODE %%%
  204958. //***************************************************************************
  204959. #define SERROR_CURRENT 0x70 // Current Errors
  204960. #define SERROR_DEFERED 0x71 // Deferred Errors
  204961. //***************************************************************************
  204962. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  204963. //***************************************************************************
  204964. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  204965. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  204966. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  204967. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  204968. //***************************************************************************
  204969. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  204970. //***************************************************************************
  204971. #define KEY_NOSENSE 0x00 // No Sense
  204972. #define KEY_RECERROR 0x01 // Recovered Error
  204973. #define KEY_NOTREADY 0x02 // Not Ready
  204974. #define KEY_MEDIUMERR 0x03 // Medium Error
  204975. #define KEY_HARDERROR 0x04 // Hardware Error
  204976. #define KEY_ILLGLREQ 0x05 // Illegal Request
  204977. #define KEY_UNITATT 0x06 // Unit Attention
  204978. #define KEY_DATAPROT 0x07 // Data Protect
  204979. #define KEY_BLANKCHK 0x08 // Blank Check
  204980. #define KEY_VENDSPEC 0x09 // Vendor Specific
  204981. #define KEY_COPYABORT 0x0A // Copy Abort
  204982. #define KEY_EQUAL 0x0C // Equal (Search)
  204983. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  204984. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  204985. #define KEY_RESERVED 0x0F // Reserved
  204986. //***************************************************************************
  204987. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  204988. //***************************************************************************
  204989. #define DTYPE_DASD 0x00 // Disk Device
  204990. #define DTYPE_SEQD 0x01 // Tape Device
  204991. #define DTYPE_PRNT 0x02 // Printer
  204992. #define DTYPE_PROC 0x03 // Processor
  204993. #define DTYPE_WORM 0x04 // Write-once read-multiple
  204994. #define DTYPE_CROM 0x05 // CD-ROM device
  204995. #define DTYPE_SCAN 0x06 // Scanner device
  204996. #define DTYPE_OPTI 0x07 // Optical memory device
  204997. #define DTYPE_JUKE 0x08 // Medium Changer device
  204998. #define DTYPE_COMM 0x09 // Communications device
  204999. #define DTYPE_RESL 0x0A // Reserved (low)
  205000. #define DTYPE_RESH 0x1E // Reserved (high)
  205001. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  205002. //***************************************************************************
  205003. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  205004. //***************************************************************************
  205005. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  205006. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  205007. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  205008. #define ANSI_RESLO 0x3 // Reserved (low)
  205009. #define ANSI_RESHI 0x7 // Reserved (high)
  205010. typedef struct
  205011. {
  205012. USHORT Length;
  205013. UCHAR ScsiStatus;
  205014. UCHAR PathId;
  205015. UCHAR TargetId;
  205016. UCHAR Lun;
  205017. UCHAR CdbLength;
  205018. UCHAR SenseInfoLength;
  205019. UCHAR DataIn;
  205020. ULONG DataTransferLength;
  205021. ULONG TimeOutValue;
  205022. ULONG DataBufferOffset;
  205023. ULONG SenseInfoOffset;
  205024. UCHAR Cdb[16];
  205025. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  205026. typedef struct
  205027. {
  205028. USHORT Length;
  205029. UCHAR ScsiStatus;
  205030. UCHAR PathId;
  205031. UCHAR TargetId;
  205032. UCHAR Lun;
  205033. UCHAR CdbLength;
  205034. UCHAR SenseInfoLength;
  205035. UCHAR DataIn;
  205036. ULONG DataTransferLength;
  205037. ULONG TimeOutValue;
  205038. PVOID DataBuffer;
  205039. ULONG SenseInfoOffset;
  205040. UCHAR Cdb[16];
  205041. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  205042. typedef struct
  205043. {
  205044. SCSI_PASS_THROUGH_DIRECT spt;
  205045. ULONG Filler;
  205046. UCHAR ucSenseBuf[32];
  205047. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  205048. typedef struct
  205049. {
  205050. ULONG Length;
  205051. UCHAR PortNumber;
  205052. UCHAR PathId;
  205053. UCHAR TargetId;
  205054. UCHAR Lun;
  205055. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  205056. #define METHOD_BUFFERED 0
  205057. #define METHOD_IN_DIRECT 1
  205058. #define METHOD_OUT_DIRECT 2
  205059. #define METHOD_NEITHER 3
  205060. #define FILE_ANY_ACCESS 0
  205061. #ifndef FILE_READ_ACCESS
  205062. #define FILE_READ_ACCESS (0x0001)
  205063. #endif
  205064. #ifndef FILE_WRITE_ACCESS
  205065. #define FILE_WRITE_ACCESS (0x0002)
  205066. #endif
  205067. #define IOCTL_SCSI_BASE 0x00000004
  205068. #define SCSI_IOCTL_DATA_OUT 0
  205069. #define SCSI_IOCTL_DATA_IN 1
  205070. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  205071. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  205072. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  205073. )
  205074. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  205075. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  205076. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  205077. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  205078. #define SENSE_LEN 14
  205079. #define SRB_DIR_SCSI 0x00
  205080. #define SRB_POSTING 0x01
  205081. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  205082. #define SRB_DIR_IN 0x08
  205083. #define SRB_DIR_OUT 0x10
  205084. #define SRB_EVENT_NOTIFY 0x40
  205085. #define RESIDUAL_COUNT_SUPPORTED 0x02
  205086. #define MAX_SRB_TIMEOUT 1080001u
  205087. #define DEFAULT_SRB_TIMEOUT 1080001u
  205088. #define SC_HA_INQUIRY 0x00
  205089. #define SC_GET_DEV_TYPE 0x01
  205090. #define SC_EXEC_SCSI_CMD 0x02
  205091. #define SC_ABORT_SRB 0x03
  205092. #define SC_RESET_DEV 0x04
  205093. #define SC_SET_HA_PARMS 0x05
  205094. #define SC_GET_DISK_INFO 0x06
  205095. #define SC_RESCAN_SCSI_BUS 0x07
  205096. #define SC_GETSET_TIMEOUTS 0x08
  205097. #define SS_PENDING 0x00
  205098. #define SS_COMP 0x01
  205099. #define SS_ABORTED 0x02
  205100. #define SS_ABORT_FAIL 0x03
  205101. #define SS_ERR 0x04
  205102. #define SS_INVALID_CMD 0x80
  205103. #define SS_INVALID_HA 0x81
  205104. #define SS_NO_DEVICE 0x82
  205105. #define SS_INVALID_SRB 0xE0
  205106. #define SS_OLD_MANAGER 0xE1
  205107. #define SS_BUFFER_ALIGN 0xE1
  205108. #define SS_ILLEGAL_MODE 0xE2
  205109. #define SS_NO_ASPI 0xE3
  205110. #define SS_FAILED_INIT 0xE4
  205111. #define SS_ASPI_IS_BUSY 0xE5
  205112. #define SS_BUFFER_TO_BIG 0xE6
  205113. #define SS_BUFFER_TOO_BIG 0xE6
  205114. #define SS_MISMATCHED_COMPONENTS 0xE7
  205115. #define SS_NO_ADAPTERS 0xE8
  205116. #define SS_INSUFFICIENT_RESOURCES 0xE9
  205117. #define SS_ASPI_IS_SHUTDOWN 0xEA
  205118. #define SS_BAD_INSTALL 0xEB
  205119. #define HASTAT_OK 0x00
  205120. #define HASTAT_SEL_TO 0x11
  205121. #define HASTAT_DO_DU 0x12
  205122. #define HASTAT_BUS_FREE 0x13
  205123. #define HASTAT_PHASE_ERR 0x14
  205124. #define HASTAT_TIMEOUT 0x09
  205125. #define HASTAT_COMMAND_TIMEOUT 0x0B
  205126. #define HASTAT_MESSAGE_REJECT 0x0D
  205127. #define HASTAT_BUS_RESET 0x0E
  205128. #define HASTAT_PARITY_ERROR 0x0F
  205129. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  205130. #define PACKED
  205131. #pragma pack(1)
  205132. typedef struct
  205133. {
  205134. BYTE SRB_Cmd;
  205135. BYTE SRB_Status;
  205136. BYTE SRB_HaID;
  205137. BYTE SRB_Flags;
  205138. DWORD SRB_Hdr_Rsvd;
  205139. BYTE HA_Count;
  205140. BYTE HA_SCSI_ID;
  205141. BYTE HA_ManagerId[16];
  205142. BYTE HA_Identifier[16];
  205143. BYTE HA_Unique[16];
  205144. WORD HA_Rsvd1;
  205145. BYTE pad[20];
  205146. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  205147. typedef struct
  205148. {
  205149. BYTE SRB_Cmd;
  205150. BYTE SRB_Status;
  205151. BYTE SRB_HaID;
  205152. BYTE SRB_Flags;
  205153. DWORD SRB_Hdr_Rsvd;
  205154. BYTE SRB_Target;
  205155. BYTE SRB_Lun;
  205156. BYTE SRB_DeviceType;
  205157. BYTE SRB_Rsvd1;
  205158. BYTE pad[68];
  205159. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  205160. typedef struct
  205161. {
  205162. BYTE SRB_Cmd;
  205163. BYTE SRB_Status;
  205164. BYTE SRB_HaID;
  205165. BYTE SRB_Flags;
  205166. DWORD SRB_Hdr_Rsvd;
  205167. BYTE SRB_Target;
  205168. BYTE SRB_Lun;
  205169. WORD SRB_Rsvd1;
  205170. DWORD SRB_BufLen;
  205171. BYTE FAR *SRB_BufPointer;
  205172. BYTE SRB_SenseLen;
  205173. BYTE SRB_CDBLen;
  205174. BYTE SRB_HaStat;
  205175. BYTE SRB_TargStat;
  205176. VOID FAR *SRB_PostProc;
  205177. BYTE SRB_Rsvd2[20];
  205178. BYTE CDBByte[16];
  205179. BYTE SenseArea[SENSE_LEN+2];
  205180. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  205181. typedef struct
  205182. {
  205183. BYTE SRB_Cmd;
  205184. BYTE SRB_Status;
  205185. BYTE SRB_HaId;
  205186. BYTE SRB_Flags;
  205187. DWORD SRB_Hdr_Rsvd;
  205188. } PACKED SRB, *PSRB, FAR *LPSRB;
  205189. #pragma pack()
  205190. struct CDDeviceInfo
  205191. {
  205192. char vendor[9];
  205193. char productId[17];
  205194. char rev[5];
  205195. char vendorSpec[21];
  205196. BYTE ha;
  205197. BYTE tgt;
  205198. BYTE lun;
  205199. char scsiDriveLetter; // will be 0 if not using scsi
  205200. };
  205201. class CDReadBuffer
  205202. {
  205203. public:
  205204. int startFrame;
  205205. int numFrames;
  205206. int dataStartOffset;
  205207. int dataLength;
  205208. BYTE* buffer;
  205209. int bufferSize;
  205210. int index;
  205211. bool wantsIndex;
  205212. CDReadBuffer (const int numberOfFrames)
  205213. : startFrame (0),
  205214. numFrames (0),
  205215. dataStartOffset (0),
  205216. dataLength (0),
  205217. index (0),
  205218. wantsIndex (false)
  205219. {
  205220. bufferSize = 2352 * numberOfFrames;
  205221. buffer = (BYTE*) malloc (bufferSize);
  205222. }
  205223. ~CDReadBuffer()
  205224. {
  205225. free (buffer);
  205226. }
  205227. bool isZero() const
  205228. {
  205229. BYTE* p = buffer + dataStartOffset;
  205230. for (int i = dataLength; --i >= 0;)
  205231. if (*p++ != 0)
  205232. return false;
  205233. return true;
  205234. }
  205235. };
  205236. class CDDeviceHandle;
  205237. class CDController
  205238. {
  205239. public:
  205240. CDController();
  205241. virtual ~CDController();
  205242. virtual bool read (CDReadBuffer* t) = 0;
  205243. virtual void shutDown();
  205244. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  205245. int getLastIndex();
  205246. public:
  205247. bool initialised;
  205248. CDDeviceHandle* deviceInfo;
  205249. int framesToCheck, framesOverlap;
  205250. void prepare (SRB_ExecSCSICmd& s);
  205251. void perform (SRB_ExecSCSICmd& s);
  205252. void setPaused (bool paused);
  205253. };
  205254. #pragma pack(1)
  205255. struct TOCTRACK
  205256. {
  205257. BYTE rsvd;
  205258. BYTE ADR;
  205259. BYTE trackNumber;
  205260. BYTE rsvd2;
  205261. BYTE addr[4];
  205262. };
  205263. struct TOC
  205264. {
  205265. WORD tocLen;
  205266. BYTE firstTrack;
  205267. BYTE lastTrack;
  205268. TOCTRACK tracks[100];
  205269. };
  205270. #pragma pack()
  205271. enum
  205272. {
  205273. READTYPE_ANY = 0,
  205274. READTYPE_ATAPI1 = 1,
  205275. READTYPE_ATAPI2 = 2,
  205276. READTYPE_READ6 = 3,
  205277. READTYPE_READ10 = 4,
  205278. READTYPE_READ_D8 = 5,
  205279. READTYPE_READ_D4 = 6,
  205280. READTYPE_READ_D4_1 = 7,
  205281. READTYPE_READ10_2 = 8
  205282. };
  205283. class CDDeviceHandle
  205284. {
  205285. public:
  205286. CDDeviceHandle (const CDDeviceInfo* const device)
  205287. : scsiHandle (0),
  205288. readType (READTYPE_ANY),
  205289. controller (0)
  205290. {
  205291. memcpy (&info, device, sizeof (info));
  205292. }
  205293. ~CDDeviceHandle()
  205294. {
  205295. if (controller != 0)
  205296. {
  205297. controller->shutDown();
  205298. delete controller;
  205299. }
  205300. if (scsiHandle != 0)
  205301. CloseHandle (scsiHandle);
  205302. }
  205303. bool readTOC (TOC* lpToc, bool useMSF);
  205304. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  205305. void openDrawer (bool shouldBeOpen);
  205306. CDDeviceInfo info;
  205307. HANDLE scsiHandle;
  205308. BYTE readType;
  205309. private:
  205310. CDController* controller;
  205311. bool testController (const int readType,
  205312. CDController* const newController,
  205313. CDReadBuffer* const bufferToUse);
  205314. };
  205315. DWORD (*fGetASPI32SupportInfo)(void);
  205316. DWORD (*fSendASPI32Command)(LPSRB);
  205317. static HINSTANCE winAspiLib = 0;
  205318. static bool usingScsi = false;
  205319. static bool initialised = false;
  205320. static bool InitialiseCDRipper()
  205321. {
  205322. if (! initialised)
  205323. {
  205324. initialised = true;
  205325. OSVERSIONINFO info;
  205326. info.dwOSVersionInfoSize = sizeof (info);
  205327. GetVersionEx (&info);
  205328. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  205329. if (! usingScsi)
  205330. {
  205331. fGetASPI32SupportInfo = 0;
  205332. fSendASPI32Command = 0;
  205333. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  205334. if (winAspiLib != 0)
  205335. {
  205336. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  205337. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  205338. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  205339. return false;
  205340. }
  205341. else
  205342. {
  205343. usingScsi = true;
  205344. }
  205345. }
  205346. }
  205347. return true;
  205348. }
  205349. static void DeinitialiseCDRipper()
  205350. {
  205351. if (winAspiLib != 0)
  205352. {
  205353. fGetASPI32SupportInfo = 0;
  205354. fSendASPI32Command = 0;
  205355. FreeLibrary (winAspiLib);
  205356. winAspiLib = 0;
  205357. }
  205358. initialised = false;
  205359. }
  205360. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  205361. {
  205362. TCHAR devicePath[8];
  205363. devicePath[0] = '\\';
  205364. devicePath[1] = '\\';
  205365. devicePath[2] = '.';
  205366. devicePath[3] = '\\';
  205367. devicePath[4] = driveLetter;
  205368. devicePath[5] = ':';
  205369. devicePath[6] = 0;
  205370. OSVERSIONINFO info;
  205371. info.dwOSVersionInfoSize = sizeof (info);
  205372. GetVersionEx (&info);
  205373. DWORD flags = GENERIC_READ;
  205374. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  205375. flags = GENERIC_READ | GENERIC_WRITE;
  205376. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  205377. if (h == INVALID_HANDLE_VALUE)
  205378. {
  205379. flags ^= GENERIC_WRITE;
  205380. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  205381. }
  205382. return h;
  205383. }
  205384. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  205385. const char driveLetter,
  205386. HANDLE& deviceHandle,
  205387. const bool retryOnFailure = true)
  205388. {
  205389. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  205390. zerostruct (s);
  205391. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  205392. s.spt.CdbLength = srb->SRB_CDBLen;
  205393. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  205394. ? SCSI_IOCTL_DATA_IN
  205395. : ((srb->SRB_Flags & SRB_DIR_OUT)
  205396. ? SCSI_IOCTL_DATA_OUT
  205397. : SCSI_IOCTL_DATA_UNSPECIFIED));
  205398. s.spt.DataTransferLength = srb->SRB_BufLen;
  205399. s.spt.TimeOutValue = 5;
  205400. s.spt.DataBuffer = srb->SRB_BufPointer;
  205401. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  205402. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  205403. srb->SRB_Status = SS_ERR;
  205404. srb->SRB_TargStat = 0x0004;
  205405. DWORD bytesReturned = 0;
  205406. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  205407. &s, sizeof (s),
  205408. &s, sizeof (s),
  205409. &bytesReturned, 0) != 0)
  205410. {
  205411. srb->SRB_Status = SS_COMP;
  205412. }
  205413. else if (retryOnFailure)
  205414. {
  205415. const DWORD error = GetLastError();
  205416. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  205417. {
  205418. if (error != ERROR_INVALID_HANDLE)
  205419. CloseHandle (deviceHandle);
  205420. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  205421. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  205422. }
  205423. }
  205424. return srb->SRB_Status;
  205425. }
  205426. // Controller types..
  205427. class ControllerType1 : public CDController
  205428. {
  205429. public:
  205430. ControllerType1() {}
  205431. ~ControllerType1() {}
  205432. bool read (CDReadBuffer* rb)
  205433. {
  205434. if (rb->numFrames * 2352 > rb->bufferSize)
  205435. return false;
  205436. SRB_ExecSCSICmd s;
  205437. prepare (s);
  205438. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  205439. s.SRB_BufLen = rb->bufferSize;
  205440. s.SRB_BufPointer = rb->buffer;
  205441. s.SRB_CDBLen = 12;
  205442. s.CDBByte[0] = 0xBE;
  205443. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  205444. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  205445. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  205446. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  205447. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  205448. perform (s);
  205449. if (s.SRB_Status != SS_COMP)
  205450. return false;
  205451. rb->dataLength = rb->numFrames * 2352;
  205452. rb->dataStartOffset = 0;
  205453. return true;
  205454. }
  205455. };
  205456. class ControllerType2 : public CDController
  205457. {
  205458. public:
  205459. ControllerType2() {}
  205460. ~ControllerType2() {}
  205461. void shutDown()
  205462. {
  205463. if (initialised)
  205464. {
  205465. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  205466. SRB_ExecSCSICmd s;
  205467. prepare (s);
  205468. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  205469. s.SRB_BufLen = 0x0C;
  205470. s.SRB_BufPointer = bufPointer;
  205471. s.SRB_CDBLen = 6;
  205472. s.CDBByte[0] = 0x15;
  205473. s.CDBByte[4] = 0x0C;
  205474. perform (s);
  205475. }
  205476. }
  205477. bool init()
  205478. {
  205479. SRB_ExecSCSICmd s;
  205480. s.SRB_Status = SS_ERR;
  205481. if (deviceInfo->readType == READTYPE_READ10_2)
  205482. {
  205483. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  205484. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  205485. for (int i = 0; i < 2; ++i)
  205486. {
  205487. prepare (s);
  205488. s.SRB_Flags = SRB_EVENT_NOTIFY;
  205489. s.SRB_BufLen = 0x14;
  205490. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  205491. s.SRB_CDBLen = 6;
  205492. s.CDBByte[0] = 0x15;
  205493. s.CDBByte[1] = 0x10;
  205494. s.CDBByte[4] = 0x14;
  205495. perform (s);
  205496. if (s.SRB_Status != SS_COMP)
  205497. return false;
  205498. }
  205499. }
  205500. else
  205501. {
  205502. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  205503. prepare (s);
  205504. s.SRB_Flags = SRB_EVENT_NOTIFY;
  205505. s.SRB_BufLen = 0x0C;
  205506. s.SRB_BufPointer = bufPointer;
  205507. s.SRB_CDBLen = 6;
  205508. s.CDBByte[0] = 0x15;
  205509. s.CDBByte[4] = 0x0C;
  205510. perform (s);
  205511. }
  205512. return s.SRB_Status == SS_COMP;
  205513. }
  205514. bool read (CDReadBuffer* rb)
  205515. {
  205516. if (rb->numFrames * 2352 > rb->bufferSize)
  205517. return false;
  205518. if (!initialised)
  205519. {
  205520. initialised = init();
  205521. if (!initialised)
  205522. return false;
  205523. }
  205524. SRB_ExecSCSICmd s;
  205525. prepare (s);
  205526. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  205527. s.SRB_BufLen = rb->bufferSize;
  205528. s.SRB_BufPointer = rb->buffer;
  205529. s.SRB_CDBLen = 10;
  205530. s.CDBByte[0] = 0x28;
  205531. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  205532. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  205533. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  205534. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  205535. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  205536. perform (s);
  205537. if (s.SRB_Status != SS_COMP)
  205538. return false;
  205539. rb->dataLength = rb->numFrames * 2352;
  205540. rb->dataStartOffset = 0;
  205541. return true;
  205542. }
  205543. };
  205544. class ControllerType3 : public CDController
  205545. {
  205546. public:
  205547. ControllerType3() {}
  205548. ~ControllerType3() {}
  205549. bool read (CDReadBuffer* rb)
  205550. {
  205551. if (rb->numFrames * 2352 > rb->bufferSize)
  205552. return false;
  205553. if (!initialised)
  205554. {
  205555. setPaused (false);
  205556. initialised = true;
  205557. }
  205558. SRB_ExecSCSICmd s;
  205559. prepare (s);
  205560. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  205561. s.SRB_BufLen = rb->numFrames * 2352;
  205562. s.SRB_BufPointer = rb->buffer;
  205563. s.SRB_CDBLen = 12;
  205564. s.CDBByte[0] = 0xD8;
  205565. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  205566. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  205567. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  205568. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  205569. perform (s);
  205570. if (s.SRB_Status != SS_COMP)
  205571. return false;
  205572. rb->dataLength = rb->numFrames * 2352;
  205573. rb->dataStartOffset = 0;
  205574. return true;
  205575. }
  205576. };
  205577. class ControllerType4 : public CDController
  205578. {
  205579. public:
  205580. ControllerType4() {}
  205581. ~ControllerType4() {}
  205582. bool selectD4Mode()
  205583. {
  205584. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  205585. SRB_ExecSCSICmd s;
  205586. prepare (s);
  205587. s.SRB_Flags = SRB_EVENT_NOTIFY;
  205588. s.SRB_CDBLen = 6;
  205589. s.SRB_BufLen = 12;
  205590. s.SRB_BufPointer = bufPointer;
  205591. s.CDBByte[0] = 0x15;
  205592. s.CDBByte[1] = 0x10;
  205593. s.CDBByte[4] = 0x08;
  205594. perform (s);
  205595. return s.SRB_Status == SS_COMP;
  205596. }
  205597. bool read (CDReadBuffer* rb)
  205598. {
  205599. if (rb->numFrames * 2352 > rb->bufferSize)
  205600. return false;
  205601. if (!initialised)
  205602. {
  205603. setPaused (true);
  205604. if (deviceInfo->readType == READTYPE_READ_D4_1)
  205605. selectD4Mode();
  205606. initialised = true;
  205607. }
  205608. SRB_ExecSCSICmd s;
  205609. prepare (s);
  205610. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  205611. s.SRB_BufLen = rb->bufferSize;
  205612. s.SRB_BufPointer = rb->buffer;
  205613. s.SRB_CDBLen = 10;
  205614. s.CDBByte[0] = 0xD4;
  205615. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  205616. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  205617. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  205618. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  205619. perform (s);
  205620. if (s.SRB_Status != SS_COMP)
  205621. return false;
  205622. rb->dataLength = rb->numFrames * 2352;
  205623. rb->dataStartOffset = 0;
  205624. return true;
  205625. }
  205626. };
  205627. CDController::CDController() : initialised (false)
  205628. {
  205629. }
  205630. CDController::~CDController()
  205631. {
  205632. }
  205633. void CDController::prepare (SRB_ExecSCSICmd& s)
  205634. {
  205635. zerostruct (s);
  205636. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  205637. s.SRB_HaID = deviceInfo->info.ha;
  205638. s.SRB_Target = deviceInfo->info.tgt;
  205639. s.SRB_Lun = deviceInfo->info.lun;
  205640. s.SRB_SenseLen = SENSE_LEN;
  205641. }
  205642. void CDController::perform (SRB_ExecSCSICmd& s)
  205643. {
  205644. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  205645. s.SRB_PostProc = (void*)event;
  205646. ResetEvent (event);
  205647. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  205648. deviceInfo->info.scsiDriveLetter,
  205649. deviceInfo->scsiHandle)
  205650. : fSendASPI32Command ((LPSRB)&s);
  205651. if (status == SS_PENDING)
  205652. WaitForSingleObject (event, 4000);
  205653. CloseHandle (event);
  205654. }
  205655. void CDController::setPaused (bool paused)
  205656. {
  205657. SRB_ExecSCSICmd s;
  205658. prepare (s);
  205659. s.SRB_Flags = SRB_EVENT_NOTIFY;
  205660. s.SRB_CDBLen = 10;
  205661. s.CDBByte[0] = 0x4B;
  205662. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  205663. perform (s);
  205664. }
  205665. void CDController::shutDown()
  205666. {
  205667. }
  205668. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  205669. {
  205670. if (overlapBuffer != 0)
  205671. {
  205672. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  205673. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  205674. if (doJitter
  205675. && overlapBuffer->startFrame > 0
  205676. && overlapBuffer->numFrames > 0
  205677. && overlapBuffer->dataLength > 0)
  205678. {
  205679. const int numFrames = rb->numFrames;
  205680. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  205681. {
  205682. rb->startFrame -= framesOverlap;
  205683. if (framesToCheck < framesOverlap
  205684. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  205685. rb->numFrames += framesOverlap;
  205686. }
  205687. else
  205688. {
  205689. overlapBuffer->dataLength = 0;
  205690. overlapBuffer->startFrame = 0;
  205691. overlapBuffer->numFrames = 0;
  205692. }
  205693. }
  205694. if (! read (rb))
  205695. return false;
  205696. if (doJitter)
  205697. {
  205698. const int checkLen = framesToCheck * 2352;
  205699. const int maxToCheck = rb->dataLength - checkLen;
  205700. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  205701. return true;
  205702. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  205703. bool found = false;
  205704. for (int i = 0; i < maxToCheck; ++i)
  205705. {
  205706. if (!memcmp (p, rb->buffer + i, checkLen))
  205707. {
  205708. i += checkLen;
  205709. rb->dataStartOffset = i;
  205710. rb->dataLength -= i;
  205711. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  205712. found = true;
  205713. break;
  205714. }
  205715. }
  205716. rb->numFrames = rb->dataLength / 2352;
  205717. rb->dataLength = 2352 * rb->numFrames;
  205718. if (!found)
  205719. return false;
  205720. }
  205721. if (canDoJitter)
  205722. {
  205723. memcpy (overlapBuffer->buffer,
  205724. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  205725. 2352 * framesToCheck);
  205726. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  205727. overlapBuffer->numFrames = framesToCheck;
  205728. overlapBuffer->dataLength = 2352 * framesToCheck;
  205729. overlapBuffer->dataStartOffset = 0;
  205730. }
  205731. else
  205732. {
  205733. overlapBuffer->startFrame = 0;
  205734. overlapBuffer->numFrames = 0;
  205735. overlapBuffer->dataLength = 0;
  205736. }
  205737. return true;
  205738. }
  205739. else
  205740. {
  205741. return read (rb);
  205742. }
  205743. }
  205744. int CDController::getLastIndex()
  205745. {
  205746. char qdata[100];
  205747. SRB_ExecSCSICmd s;
  205748. prepare (s);
  205749. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  205750. s.SRB_BufLen = sizeof (qdata);
  205751. s.SRB_BufPointer = (BYTE*)qdata;
  205752. s.SRB_CDBLen = 12;
  205753. s.CDBByte[0] = 0x42;
  205754. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  205755. s.CDBByte[2] = 64;
  205756. s.CDBByte[3] = 1; // get current position
  205757. s.CDBByte[7] = 0;
  205758. s.CDBByte[8] = (BYTE)sizeof (qdata);
  205759. perform (s);
  205760. if (s.SRB_Status == SS_COMP)
  205761. return qdata[7];
  205762. return 0;
  205763. }
  205764. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  205765. {
  205766. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  205767. SRB_ExecSCSICmd s;
  205768. zerostruct (s);
  205769. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  205770. s.SRB_HaID = info.ha;
  205771. s.SRB_Target = info.tgt;
  205772. s.SRB_Lun = info.lun;
  205773. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  205774. s.SRB_BufLen = 0x324;
  205775. s.SRB_BufPointer = (BYTE*)lpToc;
  205776. s.SRB_SenseLen = 0x0E;
  205777. s.SRB_CDBLen = 0x0A;
  205778. s.SRB_PostProc = (void*)event;
  205779. s.CDBByte[0] = 0x43;
  205780. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  205781. s.CDBByte[7] = 0x03;
  205782. s.CDBByte[8] = 0x24;
  205783. ResetEvent (event);
  205784. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  205785. : fSendASPI32Command ((LPSRB)&s);
  205786. if (status == SS_PENDING)
  205787. WaitForSingleObject (event, 4000);
  205788. CloseHandle (event);
  205789. return (s.SRB_Status == SS_COMP);
  205790. }
  205791. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  205792. CDReadBuffer* const overlapBuffer)
  205793. {
  205794. if (controller == 0)
  205795. {
  205796. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  205797. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  205798. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  205799. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  205800. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  205801. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  205802. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  205803. }
  205804. buffer->index = 0;
  205805. if ((controller != 0)
  205806. && controller->readAudio (buffer, overlapBuffer))
  205807. {
  205808. if (buffer->wantsIndex)
  205809. buffer->index = controller->getLastIndex();
  205810. return true;
  205811. }
  205812. return false;
  205813. }
  205814. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  205815. {
  205816. if (shouldBeOpen)
  205817. {
  205818. if (controller != 0)
  205819. {
  205820. controller->shutDown();
  205821. delete controller;
  205822. controller = 0;
  205823. }
  205824. if (scsiHandle != 0)
  205825. {
  205826. CloseHandle (scsiHandle);
  205827. scsiHandle = 0;
  205828. }
  205829. }
  205830. SRB_ExecSCSICmd s;
  205831. zerostruct (s);
  205832. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  205833. s.SRB_HaID = info.ha;
  205834. s.SRB_Target = info.tgt;
  205835. s.SRB_Lun = info.lun;
  205836. s.SRB_SenseLen = SENSE_LEN;
  205837. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  205838. s.SRB_BufLen = 0;
  205839. s.SRB_BufPointer = 0;
  205840. s.SRB_CDBLen = 12;
  205841. s.CDBByte[0] = 0x1b;
  205842. s.CDBByte[1] = (BYTE)(info.lun << 5);
  205843. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  205844. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  205845. s.SRB_PostProc = (void*)event;
  205846. ResetEvent (event);
  205847. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  205848. : fSendASPI32Command ((LPSRB)&s);
  205849. if (status == SS_PENDING)
  205850. WaitForSingleObject (event, 4000);
  205851. CloseHandle (event);
  205852. }
  205853. bool CDDeviceHandle::testController (const int type,
  205854. CDController* const newController,
  205855. CDReadBuffer* const rb)
  205856. {
  205857. controller = newController;
  205858. readType = (BYTE)type;
  205859. controller->deviceInfo = this;
  205860. controller->framesToCheck = 1;
  205861. controller->framesOverlap = 3;
  205862. bool passed = false;
  205863. memset (rb->buffer, 0xcd, rb->bufferSize);
  205864. if (controller->read (rb))
  205865. {
  205866. passed = true;
  205867. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  205868. int wrong = 0;
  205869. for (int i = rb->dataLength / 4; --i >= 0;)
  205870. {
  205871. if (*p++ == (int) 0xcdcdcdcd)
  205872. {
  205873. if (++wrong == 4)
  205874. {
  205875. passed = false;
  205876. break;
  205877. }
  205878. }
  205879. else
  205880. {
  205881. wrong = 0;
  205882. }
  205883. }
  205884. }
  205885. if (! passed)
  205886. {
  205887. controller->shutDown();
  205888. delete controller;
  205889. controller = 0;
  205890. }
  205891. return passed;
  205892. }
  205893. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  205894. {
  205895. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  205896. const int bufSize = 128;
  205897. BYTE buffer[bufSize];
  205898. zeromem (buffer, bufSize);
  205899. SRB_ExecSCSICmd s;
  205900. zerostruct (s);
  205901. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  205902. s.SRB_HaID = ha;
  205903. s.SRB_Target = tgt;
  205904. s.SRB_Lun = lun;
  205905. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  205906. s.SRB_BufLen = bufSize;
  205907. s.SRB_BufPointer = buffer;
  205908. s.SRB_SenseLen = SENSE_LEN;
  205909. s.SRB_CDBLen = 6;
  205910. s.SRB_PostProc = (void*)event;
  205911. s.CDBByte[0] = SCSI_INQUIRY;
  205912. s.CDBByte[4] = 100;
  205913. ResetEvent (event);
  205914. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  205915. WaitForSingleObject (event, 4000);
  205916. CloseHandle (event);
  205917. if (s.SRB_Status == SS_COMP)
  205918. {
  205919. memcpy (dev->vendor, &buffer[8], 8);
  205920. memcpy (dev->productId, &buffer[16], 16);
  205921. memcpy (dev->rev, &buffer[32], 4);
  205922. memcpy (dev->vendorSpec, &buffer[36], 20);
  205923. }
  205924. }
  205925. static int FindCDDevices (CDDeviceInfo* const list,
  205926. int maxItems)
  205927. {
  205928. int count = 0;
  205929. if (usingScsi)
  205930. {
  205931. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  205932. {
  205933. TCHAR drivePath[8];
  205934. drivePath[0] = driveLetter;
  205935. drivePath[1] = ':';
  205936. drivePath[2] = '\\';
  205937. drivePath[3] = 0;
  205938. if (GetDriveType (drivePath) == DRIVE_CDROM)
  205939. {
  205940. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  205941. if (h != INVALID_HANDLE_VALUE)
  205942. {
  205943. BYTE buffer[100], passThroughStruct[1024];
  205944. zeromem (buffer, sizeof (buffer));
  205945. zeromem (passThroughStruct, sizeof (passThroughStruct));
  205946. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  205947. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  205948. p->spt.CdbLength = 6;
  205949. p->spt.SenseInfoLength = 24;
  205950. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  205951. p->spt.DataTransferLength = 100;
  205952. p->spt.TimeOutValue = 2;
  205953. p->spt.DataBuffer = buffer;
  205954. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  205955. p->spt.Cdb[0] = 0x12;
  205956. p->spt.Cdb[4] = 100;
  205957. DWORD bytesReturned = 0;
  205958. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  205959. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  205960. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  205961. &bytesReturned, 0) != 0)
  205962. {
  205963. zeromem (&list[count], sizeof (CDDeviceInfo));
  205964. list[count].scsiDriveLetter = driveLetter;
  205965. memcpy (list[count].vendor, &buffer[8], 8);
  205966. memcpy (list[count].productId, &buffer[16], 16);
  205967. memcpy (list[count].rev, &buffer[32], 4);
  205968. memcpy (list[count].vendorSpec, &buffer[36], 20);
  205969. zeromem (passThroughStruct, sizeof (passThroughStruct));
  205970. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  205971. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  205972. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  205973. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  205974. &bytesReturned, 0) != 0)
  205975. {
  205976. list[count].ha = scsiAddr->PortNumber;
  205977. list[count].tgt = scsiAddr->TargetId;
  205978. list[count].lun = scsiAddr->Lun;
  205979. ++count;
  205980. }
  205981. }
  205982. CloseHandle (h);
  205983. }
  205984. }
  205985. }
  205986. }
  205987. else
  205988. {
  205989. const DWORD d = fGetASPI32SupportInfo();
  205990. BYTE status = HIBYTE (LOWORD (d));
  205991. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  205992. return 0;
  205993. const int numAdapters = LOBYTE (LOWORD (d));
  205994. for (BYTE ha = 0; ha < numAdapters; ++ha)
  205995. {
  205996. SRB_HAInquiry s;
  205997. zerostruct (s);
  205998. s.SRB_Cmd = SC_HA_INQUIRY;
  205999. s.SRB_HaID = ha;
  206000. fSendASPI32Command ((LPSRB)&s);
  206001. if (s.SRB_Status == SS_COMP)
  206002. {
  206003. maxItems = (int)s.HA_Unique[3];
  206004. if (maxItems == 0)
  206005. maxItems = 8;
  206006. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  206007. {
  206008. for (BYTE lun = 0; lun < 8; ++lun)
  206009. {
  206010. SRB_GDEVBlock sb;
  206011. zerostruct (sb);
  206012. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  206013. sb.SRB_HaID = ha;
  206014. sb.SRB_Target = tgt;
  206015. sb.SRB_Lun = lun;
  206016. fSendASPI32Command ((LPSRB) &sb);
  206017. if (sb.SRB_Status == SS_COMP
  206018. && sb.SRB_DeviceType == DTYPE_CROM)
  206019. {
  206020. zeromem (&list[count], sizeof (CDDeviceInfo));
  206021. list[count].ha = ha;
  206022. list[count].tgt = tgt;
  206023. list[count].lun = lun;
  206024. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  206025. ++count;
  206026. }
  206027. }
  206028. }
  206029. }
  206030. }
  206031. }
  206032. return count;
  206033. }
  206034. static int ripperUsers = 0;
  206035. static bool initialisedOk = false;
  206036. class DeinitialiseTimer : private Timer,
  206037. private DeletedAtShutdown
  206038. {
  206039. DeinitialiseTimer (const DeinitialiseTimer&);
  206040. const DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  206041. public:
  206042. DeinitialiseTimer()
  206043. {
  206044. startTimer (4000);
  206045. }
  206046. ~DeinitialiseTimer()
  206047. {
  206048. if (--ripperUsers == 0)
  206049. DeinitialiseCDRipper();
  206050. }
  206051. void timerCallback()
  206052. {
  206053. delete this;
  206054. }
  206055. juce_UseDebuggingNewOperator
  206056. };
  206057. static void incUserCount()
  206058. {
  206059. if (ripperUsers++ == 0)
  206060. initialisedOk = InitialiseCDRipper();
  206061. }
  206062. static void decUserCount()
  206063. {
  206064. new DeinitialiseTimer();
  206065. }
  206066. struct CDDeviceWrapper
  206067. {
  206068. CDDeviceHandle* cdH;
  206069. CDReadBuffer* overlapBuffer;
  206070. bool jitter;
  206071. };
  206072. static int getAddressOf (const TOCTRACK* const t)
  206073. {
  206074. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  206075. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  206076. }
  206077. static int getMSFAddressOf (const TOCTRACK* const t)
  206078. {
  206079. return 60 * t->addr[1] + t->addr[2];
  206080. }
  206081. static const int samplesPerFrame = 44100 / 75;
  206082. static const int bytesPerFrame = samplesPerFrame * 4;
  206083. const StringArray AudioCDReader::getAvailableCDNames()
  206084. {
  206085. StringArray results;
  206086. incUserCount();
  206087. if (initialisedOk)
  206088. {
  206089. CDDeviceInfo list[8];
  206090. const int num = FindCDDevices (list, 8);
  206091. decUserCount();
  206092. for (int i = 0; i < num; ++i)
  206093. {
  206094. String s;
  206095. if (list[i].scsiDriveLetter > 0)
  206096. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << T(": ");
  206097. s << String (list[i].vendor).trim()
  206098. << T(" ") << String (list[i].productId).trim()
  206099. << T(" ") << String (list[i].rev).trim();
  206100. results.add (s);
  206101. }
  206102. }
  206103. return results;
  206104. }
  206105. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  206106. {
  206107. SRB_GDEVBlock s;
  206108. zerostruct (s);
  206109. s.SRB_Cmd = SC_GET_DEV_TYPE;
  206110. s.SRB_HaID = device->ha;
  206111. s.SRB_Target = device->tgt;
  206112. s.SRB_Lun = device->lun;
  206113. if (usingScsi)
  206114. {
  206115. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  206116. if (h != INVALID_HANDLE_VALUE)
  206117. {
  206118. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  206119. cdh->scsiHandle = h;
  206120. return cdh;
  206121. }
  206122. }
  206123. else
  206124. {
  206125. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  206126. && s.SRB_DeviceType == DTYPE_CROM)
  206127. {
  206128. return new CDDeviceHandle (device);
  206129. }
  206130. }
  206131. return 0;
  206132. }
  206133. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  206134. {
  206135. incUserCount();
  206136. if (initialisedOk)
  206137. {
  206138. CDDeviceInfo list[8];
  206139. const int num = FindCDDevices (list, 8);
  206140. if (((unsigned int) deviceIndex) < (unsigned int) num)
  206141. {
  206142. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  206143. if (handle != 0)
  206144. {
  206145. CDDeviceWrapper* const d = new CDDeviceWrapper();
  206146. d->cdH = handle;
  206147. d->overlapBuffer = new CDReadBuffer(3);
  206148. return new AudioCDReader (d);
  206149. }
  206150. }
  206151. }
  206152. decUserCount();
  206153. return 0;
  206154. }
  206155. AudioCDReader::AudioCDReader (void* handle_)
  206156. : AudioFormatReader (0, T("CD Audio")),
  206157. handle (handle_),
  206158. indexingEnabled (false),
  206159. lastIndex (0),
  206160. firstFrameInBuffer (0),
  206161. samplesInBuffer (0)
  206162. {
  206163. jassert (handle_ != 0);
  206164. refreshTrackLengths();
  206165. sampleRate = 44100.0;
  206166. bitsPerSample = 16;
  206167. lengthInSamples = getPositionOfTrackStart (numTracks);
  206168. numChannels = 2;
  206169. usesFloatingPointData = false;
  206170. buffer.setSize (4 * bytesPerFrame, true);
  206171. }
  206172. AudioCDReader::~AudioCDReader()
  206173. {
  206174. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  206175. delete device->cdH;
  206176. delete device->overlapBuffer;
  206177. delete device;
  206178. decUserCount();
  206179. }
  206180. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  206181. int64 startSampleInFile, int numSamples)
  206182. {
  206183. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  206184. bool ok = true;
  206185. while (numSamples > 0)
  206186. {
  206187. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  206188. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  206189. if (startSampleInFile >= bufferStartSample
  206190. && startSampleInFile < bufferEndSample)
  206191. {
  206192. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  206193. int* const l = destSamples[0] + startOffsetInDestBuffer;
  206194. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  206195. const short* src = (const short*) buffer.getData();
  206196. src += 2 * (startSampleInFile - bufferStartSample);
  206197. for (int i = 0; i < toDo; ++i)
  206198. {
  206199. l[i] = src [i << 1] << 16;
  206200. if (r != 0)
  206201. r[i] = src [(i << 1) + 1] << 16;
  206202. }
  206203. startOffsetInDestBuffer += toDo;
  206204. startSampleInFile += toDo;
  206205. numSamples -= toDo;
  206206. }
  206207. else
  206208. {
  206209. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  206210. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  206211. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  206212. {
  206213. device->overlapBuffer->dataLength = 0;
  206214. device->overlapBuffer->startFrame = 0;
  206215. device->overlapBuffer->numFrames = 0;
  206216. device->jitter = false;
  206217. }
  206218. firstFrameInBuffer = frameNeeded;
  206219. lastIndex = 0;
  206220. CDReadBuffer readBuffer (framesInBuffer + 4);
  206221. readBuffer.wantsIndex = indexingEnabled;
  206222. int i;
  206223. for (i = 5; --i >= 0;)
  206224. {
  206225. readBuffer.startFrame = frameNeeded;
  206226. readBuffer.numFrames = framesInBuffer;
  206227. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  206228. break;
  206229. else
  206230. device->overlapBuffer->dataLength = 0;
  206231. }
  206232. if (i >= 0)
  206233. {
  206234. memcpy ((char*) buffer.getData(),
  206235. readBuffer.buffer + readBuffer.dataStartOffset,
  206236. readBuffer.dataLength);
  206237. samplesInBuffer = readBuffer.dataLength >> 2;
  206238. lastIndex = readBuffer.index;
  206239. }
  206240. else
  206241. {
  206242. int* l = destSamples[0] + startOffsetInDestBuffer;
  206243. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  206244. while (--numSamples >= 0)
  206245. {
  206246. *l++ = 0;
  206247. if (r != 0)
  206248. *r++ = 0;
  206249. }
  206250. // sometimes the read fails for just the very last couple of blocks, so
  206251. // we'll ignore and errors in the last half-second of the disk..
  206252. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  206253. break;
  206254. }
  206255. }
  206256. }
  206257. return ok;
  206258. }
  206259. bool AudioCDReader::isCDStillPresent() const
  206260. {
  206261. TOC toc;
  206262. zerostruct (toc);
  206263. return ((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false);
  206264. }
  206265. int AudioCDReader::getNumTracks() const
  206266. {
  206267. return numTracks;
  206268. }
  206269. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  206270. {
  206271. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  206272. : 0;
  206273. }
  206274. void AudioCDReader::refreshTrackLengths()
  206275. {
  206276. zeromem (trackStarts, sizeof (trackStarts));
  206277. zeromem (audioTracks, sizeof (audioTracks));
  206278. TOC toc;
  206279. zerostruct (toc);
  206280. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  206281. {
  206282. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  206283. for (int i = 0; i <= numTracks; ++i)
  206284. {
  206285. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  206286. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  206287. }
  206288. }
  206289. else
  206290. {
  206291. numTracks = 0;
  206292. }
  206293. }
  206294. bool AudioCDReader::isTrackAudio (int trackNum) const
  206295. {
  206296. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  206297. : false;
  206298. }
  206299. void AudioCDReader::enableIndexScanning (bool b)
  206300. {
  206301. indexingEnabled = b;
  206302. }
  206303. int AudioCDReader::getLastIndex() const
  206304. {
  206305. return lastIndex;
  206306. }
  206307. const int framesPerIndexRead = 4;
  206308. int AudioCDReader::getIndexAt (int samplePos)
  206309. {
  206310. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  206311. const int frameNeeded = samplePos / samplesPerFrame;
  206312. device->overlapBuffer->dataLength = 0;
  206313. device->overlapBuffer->startFrame = 0;
  206314. device->overlapBuffer->numFrames = 0;
  206315. device->jitter = false;
  206316. firstFrameInBuffer = 0;
  206317. lastIndex = 0;
  206318. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  206319. readBuffer.wantsIndex = true;
  206320. int i;
  206321. for (i = 5; --i >= 0;)
  206322. {
  206323. readBuffer.startFrame = frameNeeded;
  206324. readBuffer.numFrames = framesPerIndexRead;
  206325. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  206326. break;
  206327. }
  206328. if (i >= 0)
  206329. return readBuffer.index;
  206330. return -1;
  206331. }
  206332. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  206333. {
  206334. Array <int> indexes;
  206335. const int trackStart = getPositionOfTrackStart (trackNumber);
  206336. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  206337. bool needToScan = true;
  206338. if (trackEnd - trackStart > 20 * 44100)
  206339. {
  206340. // check the end of the track for indexes before scanning the whole thing
  206341. needToScan = false;
  206342. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  206343. bool seenAnIndex = false;
  206344. while (pos <= trackEnd - samplesPerFrame)
  206345. {
  206346. const int index = getIndexAt (pos);
  206347. if (index == 0)
  206348. {
  206349. // lead-out, so skip back a bit if we've not found any indexes yet..
  206350. if (seenAnIndex)
  206351. break;
  206352. pos -= 44100 * 5;
  206353. if (pos < trackStart)
  206354. break;
  206355. }
  206356. else
  206357. {
  206358. if (index > 0)
  206359. seenAnIndex = true;
  206360. if (index > 1)
  206361. {
  206362. needToScan = true;
  206363. break;
  206364. }
  206365. pos += samplesPerFrame * framesPerIndexRead;
  206366. }
  206367. }
  206368. }
  206369. if (needToScan)
  206370. {
  206371. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  206372. int pos = trackStart;
  206373. int last = -1;
  206374. while (pos < trackEnd - samplesPerFrame * 10)
  206375. {
  206376. const int frameNeeded = pos / samplesPerFrame;
  206377. device->overlapBuffer->dataLength = 0;
  206378. device->overlapBuffer->startFrame = 0;
  206379. device->overlapBuffer->numFrames = 0;
  206380. device->jitter = false;
  206381. firstFrameInBuffer = 0;
  206382. CDReadBuffer readBuffer (4);
  206383. readBuffer.wantsIndex = true;
  206384. int i;
  206385. for (i = 5; --i >= 0;)
  206386. {
  206387. readBuffer.startFrame = frameNeeded;
  206388. readBuffer.numFrames = framesPerIndexRead;
  206389. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  206390. break;
  206391. }
  206392. if (i < 0)
  206393. break;
  206394. if (readBuffer.index > last && readBuffer.index > 1)
  206395. {
  206396. last = readBuffer.index;
  206397. indexes.add (pos);
  206398. }
  206399. pos += samplesPerFrame * framesPerIndexRead;
  206400. }
  206401. indexes.removeValue (trackStart);
  206402. }
  206403. return indexes;
  206404. }
  206405. int AudioCDReader::getCDDBId()
  206406. {
  206407. refreshTrackLengths();
  206408. if (numTracks > 0)
  206409. {
  206410. TOC toc;
  206411. zerostruct (toc);
  206412. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  206413. {
  206414. int n = 0;
  206415. for (int i = numTracks; --i >= 0;)
  206416. {
  206417. int j = getMSFAddressOf (&toc.tracks[i]);
  206418. while (j > 0)
  206419. {
  206420. n += (j % 10);
  206421. j /= 10;
  206422. }
  206423. }
  206424. if (n != 0)
  206425. {
  206426. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  206427. - getMSFAddressOf (&toc.tracks[0]);
  206428. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  206429. }
  206430. }
  206431. }
  206432. return 0;
  206433. }
  206434. void AudioCDReader::ejectDisk()
  206435. {
  206436. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  206437. }
  206438. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  206439. {
  206440. CoInitialize (0);
  206441. IDiscMaster* dm;
  206442. IDiscRecorder* result = 0;
  206443. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  206444. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  206445. IID_IDiscMaster,
  206446. (void**) &dm)))
  206447. {
  206448. if (SUCCEEDED (dm->Open()))
  206449. {
  206450. IEnumDiscRecorders* drEnum = 0;
  206451. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  206452. {
  206453. IDiscRecorder* dr = 0;
  206454. DWORD dummy;
  206455. int index = 0;
  206456. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  206457. {
  206458. if (indexToOpen == index)
  206459. {
  206460. result = dr;
  206461. break;
  206462. }
  206463. else if (list != 0)
  206464. {
  206465. BSTR path;
  206466. if (SUCCEEDED (dr->GetPath (&path)))
  206467. list->add ((const WCHAR*) path);
  206468. }
  206469. ++index;
  206470. dr->Release();
  206471. }
  206472. drEnum->Release();
  206473. }
  206474. /*if (redbookFormat != 0)
  206475. {
  206476. IEnumDiscMasterFormats* mfEnum;
  206477. if (SUCCEEDED (dm->EnumDiscMasterFormats (&mfEnum)))
  206478. {
  206479. IID formatIID;
  206480. DWORD dummy;
  206481. while (mfEnum->Next (1, &formatIID, &dummy) == S_OK)
  206482. {
  206483. }
  206484. mfEnum->Release();
  206485. }
  206486. redbookFormat
  206487. }*/
  206488. if (master == 0)
  206489. dm->Close();
  206490. }
  206491. if (master != 0)
  206492. *master = dm;
  206493. else
  206494. dm->Release();
  206495. }
  206496. return result;
  206497. }
  206498. const StringArray AudioCDBurner::findAvailableDevices()
  206499. {
  206500. StringArray devs;
  206501. enumCDBurners (&devs, -1, 0);
  206502. return devs;
  206503. }
  206504. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  206505. {
  206506. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  206507. if (b->internal == 0)
  206508. deleteAndZero (b);
  206509. return b;
  206510. }
  206511. class CDBurnerInfo : public IDiscMasterProgressEvents
  206512. {
  206513. public:
  206514. CDBurnerInfo()
  206515. : refCount (1),
  206516. progress (0),
  206517. shouldCancel (false),
  206518. listener (0)
  206519. {
  206520. }
  206521. ~CDBurnerInfo()
  206522. {
  206523. }
  206524. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  206525. {
  206526. if (result == 0)
  206527. return E_POINTER;
  206528. if (id == IID_IUnknown || id == IID_IDiscMasterProgressEvents)
  206529. {
  206530. AddRef();
  206531. *result = this;
  206532. return S_OK;
  206533. }
  206534. *result = 0;
  206535. return E_NOINTERFACE;
  206536. }
  206537. ULONG __stdcall AddRef() { return ++refCount; }
  206538. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  206539. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  206540. {
  206541. if (listener != 0 && ! shouldCancel)
  206542. shouldCancel = listener->audioCDBurnProgress (progress);
  206543. *pbCancel = shouldCancel;
  206544. return S_OK;
  206545. }
  206546. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  206547. {
  206548. progress = nCompleted / (float) nTotal;
  206549. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  206550. return E_NOTIMPL;
  206551. }
  206552. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  206553. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  206554. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  206555. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  206556. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  206557. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  206558. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  206559. IDiscMaster* discMaster;
  206560. IDiscRecorder* discRecorder;
  206561. IRedbookDiscMaster* redbook;
  206562. AudioCDBurner::BurnProgressListener* listener;
  206563. float progress;
  206564. bool shouldCancel;
  206565. private:
  206566. int refCount;
  206567. };
  206568. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  206569. : internal (0)
  206570. {
  206571. IDiscMaster* discMaster;
  206572. IDiscRecorder* dr = enumCDBurners (0, deviceIndex, &discMaster);
  206573. if (dr != 0)
  206574. {
  206575. IRedbookDiscMaster* redbook;
  206576. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  206577. hr = discMaster->SetActiveDiscRecorder (dr);
  206578. CDBurnerInfo* const info = new CDBurnerInfo();
  206579. internal = info;
  206580. info->discMaster = discMaster;
  206581. info->discRecorder = dr;
  206582. info->redbook = redbook;
  206583. }
  206584. }
  206585. AudioCDBurner::~AudioCDBurner()
  206586. {
  206587. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  206588. if (info != 0)
  206589. {
  206590. info->discRecorder->Close();
  206591. info->redbook->Release();
  206592. info->discRecorder->Release();
  206593. info->discMaster->Release();
  206594. info->Release();
  206595. }
  206596. }
  206597. bool AudioCDBurner::isDiskPresent() const
  206598. {
  206599. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  206600. HRESULT hr = info->discRecorder->OpenExclusive();
  206601. long type, flags;
  206602. hr = info->discRecorder->QueryMediaType (&type, &flags);
  206603. info->discRecorder->Close();
  206604. return hr == S_OK && type != 0 && (flags & MEDIA_WRITABLE) != 0;
  206605. }
  206606. int AudioCDBurner::getNumAvailableAudioBlocks() const
  206607. {
  206608. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  206609. long blocksFree = 0;
  206610. info->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  206611. return blocksFree;
  206612. }
  206613. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener,
  206614. const bool ejectDiscAfterwards,
  206615. const bool performFakeBurnForTesting)
  206616. {
  206617. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  206618. info->listener = listener;
  206619. info->progress = 0;
  206620. info->shouldCancel = false;
  206621. UINT_PTR cookie;
  206622. HRESULT hr = info->discMaster->ProgressAdvise (info, &cookie);
  206623. hr = info->discMaster->RecordDisc (performFakeBurnForTesting,
  206624. ejectDiscAfterwards);
  206625. String error;
  206626. if (hr != S_OK)
  206627. {
  206628. const char* e = "Couldn't open or write to the CD device";
  206629. if (hr == IMAPI_E_USERABORT)
  206630. e = "User cancelled the write operation";
  206631. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  206632. e = "No Disk present";
  206633. error = e;
  206634. }
  206635. info->discMaster->ProgressUnadvise (cookie);
  206636. info->listener = 0;
  206637. return error;
  206638. }
  206639. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamples)
  206640. {
  206641. if (source == 0)
  206642. return false;
  206643. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  206644. long bytesPerBlock;
  206645. HRESULT hr = info->redbook->GetAudioBlockSize (&bytesPerBlock);
  206646. const int samplesPerBlock = bytesPerBlock / 4;
  206647. bool ok = true;
  206648. hr = info->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  206649. byte* const buffer = (byte*) juce_malloc (bytesPerBlock);
  206650. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  206651. int samplesDone = 0;
  206652. source->prepareToPlay (samplesPerBlock, 44100.0);
  206653. while (ok)
  206654. {
  206655. {
  206656. AudioSourceChannelInfo info;
  206657. info.buffer = &sourceBuffer;
  206658. info.numSamples = samplesPerBlock;
  206659. info.startSample = 0;
  206660. sourceBuffer.clear();
  206661. source->getNextAudioBlock (info);
  206662. }
  206663. zeromem (buffer, bytesPerBlock);
  206664. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  206665. buffer, samplesPerBlock, 4);
  206666. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  206667. buffer + 2, samplesPerBlock, 4);
  206668. hr = info->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  206669. if (hr != S_OK)
  206670. ok = false;
  206671. samplesDone += samplesPerBlock;
  206672. if (samplesDone >= numSamples)
  206673. break;
  206674. }
  206675. juce_free (buffer);
  206676. hr = info->redbook->CloseAudioTrack();
  206677. delete source;
  206678. return ok && hr == S_OK;
  206679. }
  206680. #endif
  206681. /********* End of inlined file: juce_win32_AudioCDReader.cpp *********/
  206682. /********* Start of inlined file: juce_win32_Midi.cpp *********/
  206683. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206684. // compiled on its own).
  206685. #if JUCE_INCLUDED_FILE
  206686. static const int midiBufferSize = 1024 * 10;
  206687. static const int numInHeaders = 32;
  206688. static const int inBufferSize = 256;
  206689. static Array <void*, CriticalSection> activeMidiThreads;
  206690. using ::free;
  206691. class MidiInThread : public Thread
  206692. {
  206693. public:
  206694. MidiInThread (MidiInput* const input_,
  206695. MidiInputCallback* const callback_)
  206696. : Thread ("Juce Midi"),
  206697. hIn (0),
  206698. input (input_),
  206699. callback (callback_),
  206700. isStarted (false),
  206701. startTime (0),
  206702. pendingLength(0)
  206703. {
  206704. for (int i = numInHeaders; --i >= 0;)
  206705. {
  206706. zeromem (&hdr[i], sizeof (MIDIHDR));
  206707. hdr[i].lpData = inData[i];
  206708. hdr[i].dwBufferLength = inBufferSize;
  206709. }
  206710. };
  206711. ~MidiInThread()
  206712. {
  206713. stop();
  206714. if (hIn != 0)
  206715. {
  206716. int count = 5;
  206717. while (--count >= 0)
  206718. {
  206719. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  206720. break;
  206721. Sleep (20);
  206722. }
  206723. }
  206724. }
  206725. void handle (const uint32 message, const uint32 timeStamp) throw()
  206726. {
  206727. const int byte = message & 0xff;
  206728. if (byte < 0x80)
  206729. return;
  206730. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  206731. const double time = timeStampToTime (timeStamp);
  206732. lock.enter();
  206733. if (pendingLength < midiBufferSize - 12)
  206734. {
  206735. char* const p = pending + pendingLength;
  206736. *(double*) p = time;
  206737. *(uint32*) (p + 8) = numBytes;
  206738. *(uint32*) (p + 12) = message;
  206739. pendingLength += 12 + numBytes;
  206740. }
  206741. else
  206742. {
  206743. jassertfalse // midi buffer overflow! You might need to increase the size..
  206744. }
  206745. lock.exit();
  206746. notify();
  206747. }
  206748. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp) throw()
  206749. {
  206750. const int num = hdr->dwBytesRecorded;
  206751. if (num > 0)
  206752. {
  206753. const double time = timeStampToTime (timeStamp);
  206754. lock.enter();
  206755. if (pendingLength < midiBufferSize - (8 + num))
  206756. {
  206757. char* const p = pending + pendingLength;
  206758. *(double*) p = time;
  206759. *(uint32*) (p + 8) = num;
  206760. memcpy (p + 12, hdr->lpData, num);
  206761. pendingLength += 12 + num;
  206762. }
  206763. else
  206764. {
  206765. jassertfalse // midi buffer overflow! You might need to increase the size..
  206766. }
  206767. lock.exit();
  206768. notify();
  206769. }
  206770. }
  206771. void writeBlock (const int i) throw()
  206772. {
  206773. hdr[i].dwBytesRecorded = 0;
  206774. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  206775. jassert (res == MMSYSERR_NOERROR);
  206776. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  206777. jassert (res == MMSYSERR_NOERROR);
  206778. }
  206779. void run()
  206780. {
  206781. MemoryBlock pendingCopy (64);
  206782. while (! threadShouldExit())
  206783. {
  206784. for (int i = 0; i < numInHeaders; ++i)
  206785. {
  206786. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  206787. {
  206788. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  206789. (void) res;
  206790. jassert (res == MMSYSERR_NOERROR);
  206791. writeBlock (i);
  206792. }
  206793. }
  206794. lock.enter();
  206795. int len = pendingLength;
  206796. if (len > 0)
  206797. {
  206798. pendingCopy.ensureSize (len);
  206799. pendingCopy.copyFrom (pending, 0, len);
  206800. pendingLength = 0;
  206801. }
  206802. lock.exit();
  206803. //xxx needs to figure out if blocks are broken up or not
  206804. if (len == 0)
  206805. {
  206806. wait (500);
  206807. }
  206808. else
  206809. {
  206810. const char* p = (const char*) pendingCopy.getData();
  206811. while (len > 0)
  206812. {
  206813. const double time = *(const double*) p;
  206814. const int messageLen = *(const int*) (p + 8);
  206815. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  206816. callback->handleIncomingMidiMessage (input, message);
  206817. p += 12 + messageLen;
  206818. len -= 12 + messageLen;
  206819. }
  206820. }
  206821. }
  206822. }
  206823. void start() throw()
  206824. {
  206825. jassert (hIn != 0);
  206826. if (hIn != 0 && ! isStarted)
  206827. {
  206828. stop();
  206829. activeMidiThreads.addIfNotAlreadyThere (this);
  206830. int i;
  206831. for (i = 0; i < numInHeaders; ++i)
  206832. writeBlock (i);
  206833. startTime = Time::getMillisecondCounter();
  206834. MMRESULT res = midiInStart (hIn);
  206835. jassert (res == MMSYSERR_NOERROR);
  206836. if (res == MMSYSERR_NOERROR)
  206837. {
  206838. isStarted = true;
  206839. pendingLength = 0;
  206840. startThread (6);
  206841. }
  206842. }
  206843. }
  206844. void stop() throw()
  206845. {
  206846. if (isStarted)
  206847. {
  206848. stopThread (5000);
  206849. midiInReset (hIn);
  206850. midiInStop (hIn);
  206851. activeMidiThreads.removeValue (this);
  206852. lock.enter();
  206853. lock.exit();
  206854. for (int i = numInHeaders; --i >= 0;)
  206855. {
  206856. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  206857. {
  206858. int c = 10;
  206859. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  206860. Sleep (20);
  206861. jassert (c >= 0);
  206862. }
  206863. }
  206864. isStarted = false;
  206865. pendingLength = 0;
  206866. }
  206867. }
  206868. juce_UseDebuggingNewOperator
  206869. HMIDIIN hIn;
  206870. private:
  206871. MidiInput* input;
  206872. MidiInputCallback* callback;
  206873. bool isStarted;
  206874. uint32 startTime;
  206875. CriticalSection lock;
  206876. MIDIHDR hdr [numInHeaders];
  206877. char inData [numInHeaders] [inBufferSize];
  206878. int pendingLength;
  206879. char pending [midiBufferSize];
  206880. double timeStampToTime (uint32 timeStamp) throw()
  206881. {
  206882. timeStamp += startTime;
  206883. const uint32 now = Time::getMillisecondCounter();
  206884. if (timeStamp > now)
  206885. {
  206886. if (timeStamp > now + 2)
  206887. --startTime;
  206888. timeStamp = now;
  206889. }
  206890. return 0.001 * timeStamp;
  206891. }
  206892. MidiInThread (const MidiInThread&);
  206893. const MidiInThread& operator= (const MidiInThread&);
  206894. };
  206895. static void CALLBACK midiInCallback (HMIDIIN,
  206896. UINT uMsg,
  206897. DWORD_PTR dwInstance,
  206898. DWORD_PTR midiMessage,
  206899. DWORD_PTR timeStamp)
  206900. {
  206901. MidiInThread* const thread = (MidiInThread*) dwInstance;
  206902. if (thread != 0 && activeMidiThreads.contains (thread))
  206903. {
  206904. if (uMsg == MIM_DATA)
  206905. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  206906. else if (uMsg == MIM_LONGDATA)
  206907. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  206908. }
  206909. }
  206910. const StringArray MidiInput::getDevices()
  206911. {
  206912. StringArray s;
  206913. const int num = midiInGetNumDevs();
  206914. for (int i = 0; i < num; ++i)
  206915. {
  206916. MIDIINCAPS mc;
  206917. zerostruct (mc);
  206918. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  206919. s.add (String (mc.szPname, sizeof (mc.szPname)));
  206920. }
  206921. return s;
  206922. }
  206923. int MidiInput::getDefaultDeviceIndex()
  206924. {
  206925. return 0;
  206926. }
  206927. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  206928. {
  206929. if (callback == 0)
  206930. return 0;
  206931. UINT deviceId = MIDI_MAPPER;
  206932. int n = 0;
  206933. String name;
  206934. const int num = midiInGetNumDevs();
  206935. for (int i = 0; i < num; ++i)
  206936. {
  206937. MIDIINCAPS mc;
  206938. zerostruct (mc);
  206939. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  206940. {
  206941. if (index == n)
  206942. {
  206943. deviceId = i;
  206944. name = String (mc.szPname, sizeof (mc.szPname));
  206945. break;
  206946. }
  206947. ++n;
  206948. }
  206949. }
  206950. MidiInput* const in = new MidiInput (name);
  206951. MidiInThread* const thread = new MidiInThread (in, callback);
  206952. HMIDIIN h;
  206953. HRESULT err = midiInOpen (&h, deviceId,
  206954. (DWORD_PTR) &midiInCallback,
  206955. (DWORD_PTR) thread,
  206956. CALLBACK_FUNCTION);
  206957. if (err == MMSYSERR_NOERROR)
  206958. {
  206959. thread->hIn = h;
  206960. in->internal = (void*) thread;
  206961. return in;
  206962. }
  206963. else
  206964. {
  206965. delete in;
  206966. delete thread;
  206967. return 0;
  206968. }
  206969. }
  206970. MidiInput::MidiInput (const String& name_)
  206971. : name (name_),
  206972. internal (0)
  206973. {
  206974. }
  206975. MidiInput::~MidiInput()
  206976. {
  206977. if (internal != 0)
  206978. {
  206979. MidiInThread* const thread = (MidiInThread*) internal;
  206980. delete thread;
  206981. }
  206982. }
  206983. void MidiInput::start()
  206984. {
  206985. ((MidiInThread*) internal)->start();
  206986. }
  206987. void MidiInput::stop()
  206988. {
  206989. ((MidiInThread*) internal)->stop();
  206990. }
  206991. struct MidiOutHandle
  206992. {
  206993. int refCount;
  206994. UINT deviceId;
  206995. HMIDIOUT handle;
  206996. juce_UseDebuggingNewOperator
  206997. };
  206998. static VoidArray handles (4);
  206999. const StringArray MidiOutput::getDevices()
  207000. {
  207001. StringArray s;
  207002. const int num = midiOutGetNumDevs();
  207003. for (int i = 0; i < num; ++i)
  207004. {
  207005. MIDIOUTCAPS mc;
  207006. zerostruct (mc);
  207007. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207008. s.add (String (mc.szPname, sizeof (mc.szPname)));
  207009. }
  207010. return s;
  207011. }
  207012. int MidiOutput::getDefaultDeviceIndex()
  207013. {
  207014. const int num = midiOutGetNumDevs();
  207015. int n = 0;
  207016. for (int i = 0; i < num; ++i)
  207017. {
  207018. MIDIOUTCAPS mc;
  207019. zerostruct (mc);
  207020. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207021. {
  207022. if ((mc.wTechnology & MOD_MAPPER) != 0)
  207023. return n;
  207024. ++n;
  207025. }
  207026. }
  207027. return 0;
  207028. }
  207029. MidiOutput* MidiOutput::openDevice (int index)
  207030. {
  207031. UINT deviceId = MIDI_MAPPER;
  207032. const int num = midiOutGetNumDevs();
  207033. int i, n = 0;
  207034. for (i = 0; i < num; ++i)
  207035. {
  207036. MIDIOUTCAPS mc;
  207037. zerostruct (mc);
  207038. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207039. {
  207040. // use the microsoft sw synth as a default - best not to allow deviceId
  207041. // to be MIDI_MAPPER, or else device sharing breaks
  207042. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase (T("microsoft")))
  207043. deviceId = i;
  207044. if (index == n)
  207045. {
  207046. deviceId = i;
  207047. break;
  207048. }
  207049. ++n;
  207050. }
  207051. }
  207052. for (i = handles.size(); --i >= 0;)
  207053. {
  207054. MidiOutHandle* const han = (MidiOutHandle*) handles.getUnchecked(i);
  207055. if (han != 0 && han->deviceId == deviceId)
  207056. {
  207057. han->refCount++;
  207058. MidiOutput* const out = new MidiOutput();
  207059. out->internal = (void*) han;
  207060. return out;
  207061. }
  207062. }
  207063. for (i = 4; --i >= 0;)
  207064. {
  207065. HMIDIOUT h = 0;
  207066. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  207067. if (res == MMSYSERR_NOERROR)
  207068. {
  207069. MidiOutHandle* const han = new MidiOutHandle();
  207070. han->deviceId = deviceId;
  207071. han->refCount = 1;
  207072. han->handle = h;
  207073. handles.add (han);
  207074. MidiOutput* const out = new MidiOutput();
  207075. out->internal = (void*) han;
  207076. return out;
  207077. }
  207078. else if (res == MMSYSERR_ALLOCATED)
  207079. {
  207080. Sleep (100);
  207081. }
  207082. else
  207083. {
  207084. break;
  207085. }
  207086. }
  207087. return 0;
  207088. }
  207089. MidiOutput::~MidiOutput()
  207090. {
  207091. MidiOutHandle* const h = (MidiOutHandle*) internal;
  207092. if (handles.contains ((void*) h) && --(h->refCount) == 0)
  207093. {
  207094. midiOutClose (h->handle);
  207095. handles.removeValue ((void*) h);
  207096. delete h;
  207097. }
  207098. }
  207099. void MidiOutput::reset()
  207100. {
  207101. const MidiOutHandle* const h = (MidiOutHandle*) internal;
  207102. midiOutReset (h->handle);
  207103. }
  207104. bool MidiOutput::getVolume (float& leftVol,
  207105. float& rightVol)
  207106. {
  207107. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  207108. DWORD n;
  207109. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  207110. {
  207111. const unsigned short* const nn = (const unsigned short*) &n;
  207112. rightVol = nn[0] / (float) 0xffff;
  207113. leftVol = nn[1] / (float) 0xffff;
  207114. return true;
  207115. }
  207116. else
  207117. {
  207118. rightVol = leftVol = 1.0f;
  207119. return false;
  207120. }
  207121. }
  207122. void MidiOutput::setVolume (float leftVol,
  207123. float rightVol)
  207124. {
  207125. const MidiOutHandle* const handle = (MidiOutHandle*) internal;
  207126. DWORD n;
  207127. unsigned short* const nn = (unsigned short*) &n;
  207128. nn[0] = (unsigned short) jlimit (0, 0xffff, (int)(rightVol * 0xffff));
  207129. nn[1] = (unsigned short) jlimit (0, 0xffff, (int)(leftVol * 0xffff));
  207130. midiOutSetVolume (handle->handle, n);
  207131. }
  207132. void MidiOutput::sendMessageNow (const MidiMessage& message)
  207133. {
  207134. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  207135. if (message.getRawDataSize() > 3
  207136. || message.isSysEx())
  207137. {
  207138. MIDIHDR h;
  207139. zerostruct (h);
  207140. h.lpData = (char*) message.getRawData();
  207141. h.dwBufferLength = message.getRawDataSize();
  207142. h.dwBytesRecorded = message.getRawDataSize();
  207143. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  207144. {
  207145. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  207146. if (res == MMSYSERR_NOERROR)
  207147. {
  207148. while ((h.dwFlags & MHDR_DONE) == 0)
  207149. Sleep (1);
  207150. int count = 500; // 1 sec timeout
  207151. while (--count >= 0)
  207152. {
  207153. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  207154. if (res == MIDIERR_STILLPLAYING)
  207155. Sleep (2);
  207156. else
  207157. break;
  207158. }
  207159. }
  207160. }
  207161. }
  207162. else
  207163. {
  207164. midiOutShortMsg (handle->handle,
  207165. *(unsigned int*) message.getRawData());
  207166. }
  207167. }
  207168. #endif
  207169. /********* End of inlined file: juce_win32_Midi.cpp *********/
  207170. /********* Start of inlined file: juce_win32_ASIO.cpp *********/
  207171. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207172. // compiled on its own).
  207173. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  207174. #undef WINDOWS
  207175. // #define ASIO_DEBUGGING
  207176. #ifdef ASIO_DEBUGGING
  207177. #define log(a) { Logger::writeToLog (a); DBG (a) }
  207178. #else
  207179. #define log(a) {}
  207180. #endif
  207181. #ifdef ASIO_DEBUGGING
  207182. static void logError (const String& context, long error)
  207183. {
  207184. String err ("unknown error");
  207185. if (error == ASE_NotPresent)
  207186. err = "Not Present";
  207187. else if (error == ASE_HWMalfunction)
  207188. err = "Hardware Malfunction";
  207189. else if (error == ASE_InvalidParameter)
  207190. err = "Invalid Parameter";
  207191. else if (error == ASE_InvalidMode)
  207192. err = "Invalid Mode";
  207193. else if (error == ASE_SPNotAdvancing)
  207194. err = "Sample position not advancing";
  207195. else if (error == ASE_NoClock)
  207196. err = "No Clock";
  207197. else if (error == ASE_NoMemory)
  207198. err = "Out of memory";
  207199. log (T("!!error: ") + context + T(" - ") + err);
  207200. }
  207201. #else
  207202. #define logError(a, b) {}
  207203. #endif
  207204. class ASIOAudioIODevice;
  207205. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  207206. static const int maxASIOChannels = 160;
  207207. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  207208. private Timer
  207209. {
  207210. public:
  207211. Component ourWindow;
  207212. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  207213. const String& optionalDllForDirectLoading_)
  207214. : AudioIODevice (name_, T("ASIO")),
  207215. asioObject (0),
  207216. classId (classId_),
  207217. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  207218. currentBitDepth (16),
  207219. currentSampleRate (0),
  207220. tempBuffer (0),
  207221. isOpen_ (false),
  207222. isStarted (false),
  207223. postOutput (true),
  207224. insideControlPanelModalLoop (false),
  207225. shouldUsePreferredSize (false)
  207226. {
  207227. name = name_;
  207228. ourWindow.addToDesktop (0);
  207229. windowHandle = ourWindow.getWindowHandle();
  207230. jassert (currentASIODev [slotNumber] == 0);
  207231. currentASIODev [slotNumber] = this;
  207232. openDevice();
  207233. }
  207234. ~ASIOAudioIODevice()
  207235. {
  207236. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  207237. if (currentASIODev[i] == this)
  207238. currentASIODev[i] = 0;
  207239. close();
  207240. log ("ASIO - exiting");
  207241. removeCurrentDriver();
  207242. juce_free (tempBuffer);
  207243. }
  207244. void updateSampleRates()
  207245. {
  207246. // find a list of sample rates..
  207247. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  207248. sampleRates.clear();
  207249. if (asioObject != 0)
  207250. {
  207251. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  207252. {
  207253. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  207254. if (err == 0)
  207255. {
  207256. sampleRates.add ((int) possibleSampleRates[index]);
  207257. log (T("rate: ") + String ((int) possibleSampleRates[index]));
  207258. }
  207259. else if (err != ASE_NoClock)
  207260. {
  207261. logError (T("CanSampleRate"), err);
  207262. }
  207263. }
  207264. if (sampleRates.size() == 0)
  207265. {
  207266. double cr = 0;
  207267. const long err = asioObject->getSampleRate (&cr);
  207268. log (T("No sample rates supported - current rate: ") + String ((int) cr));
  207269. if (err == 0)
  207270. sampleRates.add ((int) cr);
  207271. }
  207272. }
  207273. }
  207274. const StringArray getOutputChannelNames()
  207275. {
  207276. return outputChannelNames;
  207277. }
  207278. const StringArray getInputChannelNames()
  207279. {
  207280. return inputChannelNames;
  207281. }
  207282. int getNumSampleRates()
  207283. {
  207284. return sampleRates.size();
  207285. }
  207286. double getSampleRate (int index)
  207287. {
  207288. return sampleRates [index];
  207289. }
  207290. int getNumBufferSizesAvailable()
  207291. {
  207292. return bufferSizes.size();
  207293. }
  207294. int getBufferSizeSamples (int index)
  207295. {
  207296. return bufferSizes [index];
  207297. }
  207298. int getDefaultBufferSize()
  207299. {
  207300. return preferredSize;
  207301. }
  207302. const String open (const BitArray& inputChannels,
  207303. const BitArray& outputChannels,
  207304. double sr,
  207305. int bufferSizeSamples)
  207306. {
  207307. close();
  207308. currentCallback = 0;
  207309. if (bufferSizeSamples <= 0)
  207310. shouldUsePreferredSize = true;
  207311. if (asioObject == 0 || ! isASIOOpen)
  207312. {
  207313. log ("Warning: device not open");
  207314. const String err (openDevice());
  207315. if (asioObject == 0 || ! isASIOOpen)
  207316. return err;
  207317. }
  207318. isStarted = false;
  207319. bufferIndex = -1;
  207320. long err = 0;
  207321. long newPreferredSize = 0;
  207322. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  207323. minSize = 0;
  207324. maxSize = 0;
  207325. newPreferredSize = 0;
  207326. granularity = 0;
  207327. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  207328. {
  207329. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  207330. shouldUsePreferredSize = true;
  207331. preferredSize = newPreferredSize;
  207332. }
  207333. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  207334. // dynamic changes to the buffer size...
  207335. shouldUsePreferredSize = shouldUsePreferredSize
  207336. || getName().containsIgnoreCase (T("Digidesign"));
  207337. if (shouldUsePreferredSize)
  207338. {
  207339. log ("Using preferred size for buffer..");
  207340. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  207341. {
  207342. bufferSizeSamples = preferredSize;
  207343. }
  207344. else
  207345. {
  207346. bufferSizeSamples = 1024;
  207347. logError ("GetBufferSize1", err);
  207348. }
  207349. shouldUsePreferredSize = false;
  207350. }
  207351. int sampleRate = roundDoubleToInt (sr);
  207352. currentSampleRate = sampleRate;
  207353. currentBlockSizeSamples = bufferSizeSamples;
  207354. currentChansOut.clear();
  207355. currentChansIn.clear();
  207356. zeromem (inBuffers, sizeof (inBuffers));
  207357. zeromem (outBuffers, sizeof (outBuffers));
  207358. updateSampleRates();
  207359. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  207360. sampleRate = sampleRates[0];
  207361. jassert (sampleRate != 0);
  207362. if (sampleRate == 0)
  207363. sampleRate = 44100;
  207364. long numSources = 32;
  207365. ASIOClockSource clocks[32];
  207366. zeromem (clocks, sizeof (clocks));
  207367. asioObject->getClockSources (clocks, &numSources);
  207368. bool isSourceSet = false;
  207369. // careful not to remove this loop because it does more than just logging!
  207370. int i;
  207371. for (i = 0; i < numSources; ++i)
  207372. {
  207373. String s ("clock: ");
  207374. s += clocks[i].name;
  207375. if (clocks[i].isCurrentSource)
  207376. {
  207377. isSourceSet = true;
  207378. s << " (cur)";
  207379. }
  207380. log (s);
  207381. }
  207382. if (numSources > 1 && ! isSourceSet)
  207383. {
  207384. log ("setting clock source");
  207385. asioObject->setClockSource (clocks[0].index);
  207386. Thread::sleep (20);
  207387. }
  207388. else
  207389. {
  207390. if (numSources == 0)
  207391. {
  207392. log ("ASIO - no clock sources!");
  207393. }
  207394. }
  207395. double cr = 0;
  207396. err = asioObject->getSampleRate (&cr);
  207397. if (err == 0)
  207398. {
  207399. currentSampleRate = cr;
  207400. }
  207401. else
  207402. {
  207403. logError ("GetSampleRate", err);
  207404. currentSampleRate = 0;
  207405. }
  207406. error = String::empty;
  207407. needToReset = false;
  207408. isReSync = false;
  207409. err = 0;
  207410. bool buffersCreated = false;
  207411. if (currentSampleRate != sampleRate)
  207412. {
  207413. log (T("ASIO samplerate: ") + String (currentSampleRate) + T(" to ") + String (sampleRate));
  207414. err = asioObject->setSampleRate (sampleRate);
  207415. if (err == ASE_NoClock && numSources > 0)
  207416. {
  207417. log ("trying to set a clock source..");
  207418. Thread::sleep (10);
  207419. err = asioObject->setClockSource (clocks[0].index);
  207420. if (err != 0)
  207421. {
  207422. logError ("SetClock", err);
  207423. }
  207424. Thread::sleep (10);
  207425. err = asioObject->setSampleRate (sampleRate);
  207426. }
  207427. }
  207428. if (err == 0)
  207429. {
  207430. currentSampleRate = sampleRate;
  207431. if (needToReset)
  207432. {
  207433. if (isReSync)
  207434. {
  207435. log ("Resync request");
  207436. }
  207437. log ("! Resetting ASIO after sample rate change");
  207438. removeCurrentDriver();
  207439. loadDriver();
  207440. const String error (initDriver());
  207441. if (error.isNotEmpty())
  207442. {
  207443. log (T("ASIOInit: ") + error);
  207444. }
  207445. needToReset = false;
  207446. isReSync = false;
  207447. }
  207448. numActiveInputChans = 0;
  207449. numActiveOutputChans = 0;
  207450. ASIOBufferInfo* info = bufferInfos;
  207451. int i;
  207452. for (i = 0; i < totalNumInputChans; ++i)
  207453. {
  207454. if (inputChannels[i])
  207455. {
  207456. currentChansIn.setBit (i);
  207457. info->isInput = 1;
  207458. info->channelNum = i;
  207459. info->buffers[0] = info->buffers[1] = 0;
  207460. ++info;
  207461. ++numActiveInputChans;
  207462. }
  207463. }
  207464. for (i = 0; i < totalNumOutputChans; ++i)
  207465. {
  207466. if (outputChannels[i])
  207467. {
  207468. currentChansOut.setBit (i);
  207469. info->isInput = 0;
  207470. info->channelNum = i;
  207471. info->buffers[0] = info->buffers[1] = 0;
  207472. ++info;
  207473. ++numActiveOutputChans;
  207474. }
  207475. }
  207476. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  207477. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  207478. if (currentASIODev[0] == this)
  207479. {
  207480. callbacks.bufferSwitch = &bufferSwitchCallback0;
  207481. callbacks.asioMessage = &asioMessagesCallback0;
  207482. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  207483. }
  207484. else if (currentASIODev[1] == this)
  207485. {
  207486. callbacks.bufferSwitch = &bufferSwitchCallback1;
  207487. callbacks.asioMessage = &asioMessagesCallback1;
  207488. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  207489. }
  207490. else if (currentASIODev[2] == this)
  207491. {
  207492. callbacks.bufferSwitch = &bufferSwitchCallback2;
  207493. callbacks.asioMessage = &asioMessagesCallback2;
  207494. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  207495. }
  207496. else
  207497. {
  207498. jassertfalse
  207499. }
  207500. log ("disposing buffers");
  207501. err = asioObject->disposeBuffers();
  207502. log (T("creating buffers: ") + String (totalBuffers) + T(", ") + String (currentBlockSizeSamples));
  207503. err = asioObject->createBuffers (bufferInfos,
  207504. totalBuffers,
  207505. currentBlockSizeSamples,
  207506. &callbacks);
  207507. if (err != 0)
  207508. {
  207509. currentBlockSizeSamples = preferredSize;
  207510. logError ("create buffers 2", err);
  207511. asioObject->disposeBuffers();
  207512. err = asioObject->createBuffers (bufferInfos,
  207513. totalBuffers,
  207514. currentBlockSizeSamples,
  207515. &callbacks);
  207516. }
  207517. if (err == 0)
  207518. {
  207519. buffersCreated = true;
  207520. juce_free (tempBuffer);
  207521. tempBuffer = (float*) juce_calloc (totalBuffers * currentBlockSizeSamples * sizeof (float) + 128);
  207522. int n = 0;
  207523. Array <int> types;
  207524. currentBitDepth = 16;
  207525. for (i = 0; i < jmin (totalNumInputChans, maxASIOChannels); ++i)
  207526. {
  207527. if (inputChannels[i])
  207528. {
  207529. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  207530. ASIOChannelInfo channelInfo;
  207531. zerostruct (channelInfo);
  207532. channelInfo.channel = i;
  207533. channelInfo.isInput = 1;
  207534. asioObject->getChannelInfo (&channelInfo);
  207535. types.addIfNotAlreadyThere (channelInfo.type);
  207536. typeToFormatParameters (channelInfo.type,
  207537. inputChannelBitDepths[n],
  207538. inputChannelBytesPerSample[n],
  207539. inputChannelIsFloat[n],
  207540. inputChannelLittleEndian[n]);
  207541. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  207542. ++n;
  207543. }
  207544. }
  207545. jassert (numActiveInputChans == n);
  207546. n = 0;
  207547. for (i = 0; i < jmin (totalNumOutputChans, maxASIOChannels); ++i)
  207548. {
  207549. if (outputChannels[i])
  207550. {
  207551. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  207552. ASIOChannelInfo channelInfo;
  207553. zerostruct (channelInfo);
  207554. channelInfo.channel = i;
  207555. channelInfo.isInput = 0;
  207556. asioObject->getChannelInfo (&channelInfo);
  207557. types.addIfNotAlreadyThere (channelInfo.type);
  207558. typeToFormatParameters (channelInfo.type,
  207559. outputChannelBitDepths[n],
  207560. outputChannelBytesPerSample[n],
  207561. outputChannelIsFloat[n],
  207562. outputChannelLittleEndian[n]);
  207563. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  207564. ++n;
  207565. }
  207566. }
  207567. jassert (numActiveOutputChans == n);
  207568. for (i = types.size(); --i >= 0;)
  207569. {
  207570. log (T("channel format: ") + String (types[i]));
  207571. }
  207572. jassert (n <= totalBuffers);
  207573. for (i = 0; i < numActiveOutputChans; ++i)
  207574. {
  207575. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  207576. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  207577. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  207578. {
  207579. log ("!! Null buffers");
  207580. }
  207581. else
  207582. {
  207583. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  207584. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  207585. }
  207586. }
  207587. inputLatency = outputLatency = 0;
  207588. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  207589. {
  207590. log ("ASIO - no latencies");
  207591. }
  207592. else
  207593. {
  207594. log (T("ASIO latencies: ")
  207595. + String ((int) outputLatency)
  207596. + T(", ")
  207597. + String ((int) inputLatency));
  207598. }
  207599. isOpen_ = true;
  207600. log ("starting ASIO");
  207601. calledback = false;
  207602. err = asioObject->start();
  207603. if (err != 0)
  207604. {
  207605. isOpen_ = false;
  207606. log ("ASIO - stop on failure");
  207607. Thread::sleep (10);
  207608. asioObject->stop();
  207609. error = "Can't start device";
  207610. Thread::sleep (10);
  207611. }
  207612. else
  207613. {
  207614. int count = 300;
  207615. while (--count > 0 && ! calledback)
  207616. Thread::sleep (10);
  207617. isStarted = true;
  207618. if (! calledback)
  207619. {
  207620. error = "Device didn't start correctly";
  207621. log ("ASIO didn't callback - stopping..");
  207622. asioObject->stop();
  207623. }
  207624. }
  207625. }
  207626. else
  207627. {
  207628. error = "Can't create i/o buffers";
  207629. }
  207630. }
  207631. else
  207632. {
  207633. error = "Can't set sample rate: ";
  207634. error << sampleRate;
  207635. }
  207636. if (error.isNotEmpty())
  207637. {
  207638. logError (error, err);
  207639. if (asioObject != 0 && buffersCreated)
  207640. asioObject->disposeBuffers();
  207641. Thread::sleep (20);
  207642. isStarted = false;
  207643. isOpen_ = false;
  207644. close();
  207645. }
  207646. needToReset = false;
  207647. isReSync = false;
  207648. return error;
  207649. }
  207650. void close()
  207651. {
  207652. error = String::empty;
  207653. stopTimer();
  207654. stop();
  207655. if (isASIOOpen && isOpen_)
  207656. {
  207657. const ScopedLock sl (callbackLock);
  207658. isOpen_ = false;
  207659. isStarted = false;
  207660. needToReset = false;
  207661. isReSync = false;
  207662. log ("ASIO - stopping");
  207663. if (asioObject != 0)
  207664. {
  207665. Thread::sleep (20);
  207666. asioObject->stop();
  207667. Thread::sleep (10);
  207668. asioObject->disposeBuffers();
  207669. }
  207670. Thread::sleep (10);
  207671. }
  207672. }
  207673. bool isOpen()
  207674. {
  207675. return isOpen_ || insideControlPanelModalLoop;
  207676. }
  207677. int getCurrentBufferSizeSamples()
  207678. {
  207679. return currentBlockSizeSamples;
  207680. }
  207681. double getCurrentSampleRate()
  207682. {
  207683. return currentSampleRate;
  207684. }
  207685. const BitArray getActiveOutputChannels() const
  207686. {
  207687. return currentChansOut;
  207688. }
  207689. const BitArray getActiveInputChannels() const
  207690. {
  207691. return currentChansIn;
  207692. }
  207693. int getCurrentBitDepth()
  207694. {
  207695. return currentBitDepth;
  207696. }
  207697. int getOutputLatencyInSamples()
  207698. {
  207699. return outputLatency + currentBlockSizeSamples / 4;
  207700. }
  207701. int getInputLatencyInSamples()
  207702. {
  207703. return inputLatency + currentBlockSizeSamples / 4;
  207704. }
  207705. void start (AudioIODeviceCallback* callback)
  207706. {
  207707. if (callback != 0)
  207708. {
  207709. callback->audioDeviceAboutToStart (this);
  207710. const ScopedLock sl (callbackLock);
  207711. currentCallback = callback;
  207712. }
  207713. }
  207714. void stop()
  207715. {
  207716. AudioIODeviceCallback* const lastCallback = currentCallback;
  207717. {
  207718. const ScopedLock sl (callbackLock);
  207719. currentCallback = 0;
  207720. }
  207721. if (lastCallback != 0)
  207722. lastCallback->audioDeviceStopped();
  207723. }
  207724. bool isPlaying()
  207725. {
  207726. return isASIOOpen && (currentCallback != 0);
  207727. }
  207728. const String getLastError()
  207729. {
  207730. return error;
  207731. }
  207732. bool hasControlPanel() const
  207733. {
  207734. return true;
  207735. }
  207736. bool showControlPanel()
  207737. {
  207738. log ("ASIO - showing control panel");
  207739. Component modalWindow (String::empty);
  207740. modalWindow.setOpaque (true);
  207741. modalWindow.addToDesktop (0);
  207742. modalWindow.enterModalState();
  207743. bool done = false;
  207744. JUCE_TRY
  207745. {
  207746. // are there are devices that need to be closed before showing their control panel?
  207747. // close();
  207748. insideControlPanelModalLoop = true;
  207749. const uint32 started = Time::getMillisecondCounter();
  207750. if (asioObject != 0)
  207751. {
  207752. asioObject->controlPanel();
  207753. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  207754. log (T("spent: ") + String (spent));
  207755. if (spent > 300)
  207756. {
  207757. shouldUsePreferredSize = true;
  207758. done = true;
  207759. }
  207760. }
  207761. }
  207762. JUCE_CATCH_ALL
  207763. insideControlPanelModalLoop = false;
  207764. return done;
  207765. }
  207766. void resetRequest() throw()
  207767. {
  207768. needToReset = true;
  207769. }
  207770. void resyncRequest() throw()
  207771. {
  207772. needToReset = true;
  207773. isReSync = true;
  207774. }
  207775. void timerCallback()
  207776. {
  207777. if (! insideControlPanelModalLoop)
  207778. {
  207779. stopTimer();
  207780. // used to cause a reset
  207781. log ("! ASIO restart request!");
  207782. if (isOpen_)
  207783. {
  207784. AudioIODeviceCallback* const oldCallback = currentCallback;
  207785. close();
  207786. open (BitArray (currentChansIn), BitArray (currentChansOut),
  207787. currentSampleRate, currentBlockSizeSamples);
  207788. if (oldCallback != 0)
  207789. start (oldCallback);
  207790. }
  207791. }
  207792. else
  207793. {
  207794. startTimer (100);
  207795. }
  207796. }
  207797. juce_UseDebuggingNewOperator
  207798. private:
  207799. IASIO* volatile asioObject;
  207800. ASIOCallbacks callbacks;
  207801. void* windowHandle;
  207802. CLSID classId;
  207803. const String optionalDllForDirectLoading;
  207804. String error;
  207805. long totalNumInputChans, totalNumOutputChans;
  207806. StringArray inputChannelNames, outputChannelNames;
  207807. Array<int> sampleRates, bufferSizes;
  207808. long inputLatency, outputLatency;
  207809. long minSize, maxSize, preferredSize, granularity;
  207810. int volatile currentBlockSizeSamples;
  207811. int volatile currentBitDepth;
  207812. double volatile currentSampleRate;
  207813. BitArray currentChansOut, currentChansIn;
  207814. AudioIODeviceCallback* volatile currentCallback;
  207815. CriticalSection callbackLock;
  207816. ASIOBufferInfo bufferInfos [maxASIOChannels];
  207817. float* inBuffers [maxASIOChannels];
  207818. float* outBuffers [maxASIOChannels];
  207819. int inputChannelBitDepths [maxASIOChannels];
  207820. int outputChannelBitDepths [maxASIOChannels];
  207821. int inputChannelBytesPerSample [maxASIOChannels];
  207822. int outputChannelBytesPerSample [maxASIOChannels];
  207823. bool inputChannelIsFloat [maxASIOChannels];
  207824. bool outputChannelIsFloat [maxASIOChannels];
  207825. bool inputChannelLittleEndian [maxASIOChannels];
  207826. bool outputChannelLittleEndian [maxASIOChannels];
  207827. WaitableEvent event1;
  207828. float* tempBuffer;
  207829. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  207830. bool isOpen_, isStarted;
  207831. bool volatile isASIOOpen;
  207832. bool volatile calledback;
  207833. bool volatile littleEndian, postOutput, needToReset, isReSync;
  207834. bool volatile insideControlPanelModalLoop;
  207835. bool volatile shouldUsePreferredSize;
  207836. void removeCurrentDriver()
  207837. {
  207838. if (asioObject != 0)
  207839. {
  207840. asioObject->Release();
  207841. asioObject = 0;
  207842. }
  207843. }
  207844. bool loadDriver()
  207845. {
  207846. removeCurrentDriver();
  207847. JUCE_TRY
  207848. {
  207849. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  207850. classId, (void**) &asioObject) == S_OK)
  207851. {
  207852. return true;
  207853. }
  207854. // If a class isn't registered but we have a path for it, we can fallback to
  207855. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  207856. if (optionalDllForDirectLoading.isNotEmpty())
  207857. {
  207858. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  207859. if (h != 0)
  207860. {
  207861. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  207862. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  207863. if (dllGetClassObject != 0)
  207864. {
  207865. IClassFactory* classFactory = 0;
  207866. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  207867. if (classFactory != 0)
  207868. {
  207869. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  207870. classFactory->Release();
  207871. }
  207872. return asioObject != 0;
  207873. }
  207874. }
  207875. }
  207876. }
  207877. JUCE_CATCH_ALL
  207878. asioObject = 0;
  207879. return false;
  207880. }
  207881. const String initDriver()
  207882. {
  207883. if (asioObject != 0)
  207884. {
  207885. char buffer [256];
  207886. zeromem (buffer, sizeof (buffer));
  207887. if (! asioObject->init (windowHandle))
  207888. {
  207889. asioObject->getErrorMessage (buffer);
  207890. return String (buffer, sizeof (buffer) - 1);
  207891. }
  207892. // just in case any daft drivers expect this to be called..
  207893. asioObject->getDriverName (buffer);
  207894. return String::empty;
  207895. }
  207896. return "No Driver";
  207897. }
  207898. const String openDevice()
  207899. {
  207900. // use this in case the driver starts opening dialog boxes..
  207901. Component modalWindow (String::empty);
  207902. modalWindow.setOpaque (true);
  207903. modalWindow.addToDesktop (0);
  207904. modalWindow.enterModalState();
  207905. // open the device and get its info..
  207906. log (T("opening ASIO device: ") + getName());
  207907. needToReset = false;
  207908. isReSync = false;
  207909. outputChannelNames.clear();
  207910. inputChannelNames.clear();
  207911. bufferSizes.clear();
  207912. sampleRates.clear();
  207913. isASIOOpen = false;
  207914. isOpen_ = false;
  207915. totalNumInputChans = 0;
  207916. totalNumOutputChans = 0;
  207917. numActiveInputChans = 0;
  207918. numActiveOutputChans = 0;
  207919. currentCallback = 0;
  207920. error = String::empty;
  207921. if (getName().isEmpty())
  207922. return error;
  207923. long err = 0;
  207924. if (loadDriver())
  207925. {
  207926. if ((error = initDriver()).isEmpty())
  207927. {
  207928. numActiveInputChans = 0;
  207929. numActiveOutputChans = 0;
  207930. totalNumInputChans = 0;
  207931. totalNumOutputChans = 0;
  207932. if (asioObject != 0
  207933. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  207934. {
  207935. log (String ((int) totalNumInputChans) + T(" in, ") + String ((int) totalNumOutputChans) + T(" out"));
  207936. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  207937. {
  207938. // find a list of buffer sizes..
  207939. log (String ((int) minSize) + T(" ") + String ((int) maxSize) + T(" ") + String ((int)preferredSize) + T(" ") + String ((int)granularity));
  207940. if (granularity >= 0)
  207941. {
  207942. granularity = jmax (1, (int) granularity);
  207943. for (int i = jmax (minSize, (int) granularity); i < jmin (6400, maxSize); i += granularity)
  207944. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  207945. }
  207946. else if (granularity < 0)
  207947. {
  207948. for (int i = 0; i < 18; ++i)
  207949. {
  207950. const int s = (1 << i);
  207951. if (s >= minSize && s <= maxSize)
  207952. bufferSizes.add (s);
  207953. }
  207954. }
  207955. if (! bufferSizes.contains (preferredSize))
  207956. bufferSizes.insert (0, preferredSize);
  207957. double currentRate = 0;
  207958. asioObject->getSampleRate (&currentRate);
  207959. if (currentRate <= 0.0 || currentRate > 192001.0)
  207960. {
  207961. log ("setting sample rate");
  207962. err = asioObject->setSampleRate (44100.0);
  207963. if (err != 0)
  207964. {
  207965. logError ("setting sample rate", err);
  207966. }
  207967. asioObject->getSampleRate (&currentRate);
  207968. }
  207969. currentSampleRate = currentRate;
  207970. postOutput = (asioObject->outputReady() == 0);
  207971. if (postOutput)
  207972. {
  207973. log ("ASIO outputReady = ok");
  207974. }
  207975. updateSampleRates();
  207976. // ..because cubase does it at this point
  207977. inputLatency = outputLatency = 0;
  207978. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  207979. {
  207980. log ("ASIO - no latencies");
  207981. }
  207982. log (String ("latencies: ")
  207983. + String ((int) inputLatency)
  207984. + T(", ") + String ((int) outputLatency));
  207985. // create some dummy buffers now.. because cubase does..
  207986. numActiveInputChans = 0;
  207987. numActiveOutputChans = 0;
  207988. ASIOBufferInfo* info = bufferInfos;
  207989. int i, numChans = 0;
  207990. for (i = 0; i < jmin (2, totalNumInputChans); ++i)
  207991. {
  207992. info->isInput = 1;
  207993. info->channelNum = i;
  207994. info->buffers[0] = info->buffers[1] = 0;
  207995. ++info;
  207996. ++numChans;
  207997. }
  207998. const int outputBufferIndex = numChans;
  207999. for (i = 0; i < jmin (2, totalNumOutputChans); ++i)
  208000. {
  208001. info->isInput = 0;
  208002. info->channelNum = i;
  208003. info->buffers[0] = info->buffers[1] = 0;
  208004. ++info;
  208005. ++numChans;
  208006. }
  208007. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  208008. if (currentASIODev[0] == this)
  208009. {
  208010. callbacks.bufferSwitch = &bufferSwitchCallback0;
  208011. callbacks.asioMessage = &asioMessagesCallback0;
  208012. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  208013. }
  208014. else if (currentASIODev[1] == this)
  208015. {
  208016. callbacks.bufferSwitch = &bufferSwitchCallback1;
  208017. callbacks.asioMessage = &asioMessagesCallback1;
  208018. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  208019. }
  208020. else if (currentASIODev[2] == this)
  208021. {
  208022. callbacks.bufferSwitch = &bufferSwitchCallback2;
  208023. callbacks.asioMessage = &asioMessagesCallback2;
  208024. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  208025. }
  208026. else
  208027. {
  208028. jassertfalse
  208029. }
  208030. log (T("creating buffers (dummy): ") + String (numChans)
  208031. + T(", ") + String ((int) preferredSize));
  208032. if (preferredSize > 0)
  208033. {
  208034. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  208035. if (err != 0)
  208036. {
  208037. logError ("dummy buffers", err);
  208038. }
  208039. }
  208040. long newInps = 0, newOuts = 0;
  208041. asioObject->getChannels (&newInps, &newOuts);
  208042. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  208043. {
  208044. totalNumInputChans = newInps;
  208045. totalNumOutputChans = newOuts;
  208046. log (String ((int) totalNumInputChans) + T(" in; ")
  208047. + String ((int) totalNumOutputChans) + T(" out"));
  208048. }
  208049. updateSampleRates();
  208050. ASIOChannelInfo channelInfo;
  208051. channelInfo.type = 0;
  208052. for (i = 0; i < totalNumInputChans; ++i)
  208053. {
  208054. zerostruct (channelInfo);
  208055. channelInfo.channel = i;
  208056. channelInfo.isInput = 1;
  208057. asioObject->getChannelInfo (&channelInfo);
  208058. inputChannelNames.add (String (channelInfo.name));
  208059. }
  208060. for (i = 0; i < totalNumOutputChans; ++i)
  208061. {
  208062. zerostruct (channelInfo);
  208063. channelInfo.channel = i;
  208064. channelInfo.isInput = 0;
  208065. asioObject->getChannelInfo (&channelInfo);
  208066. outputChannelNames.add (String (channelInfo.name));
  208067. typeToFormatParameters (channelInfo.type,
  208068. outputChannelBitDepths[i],
  208069. outputChannelBytesPerSample[i],
  208070. outputChannelIsFloat[i],
  208071. outputChannelLittleEndian[i]);
  208072. if (i < 2)
  208073. {
  208074. // clear the channels that are used with the dummy stuff
  208075. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  208076. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  208077. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  208078. }
  208079. }
  208080. outputChannelNames.trim();
  208081. inputChannelNames.trim();
  208082. outputChannelNames.appendNumbersToDuplicates (false, true);
  208083. inputChannelNames.appendNumbersToDuplicates (false, true);
  208084. // start and stop because cubase does it..
  208085. asioObject->getLatencies (&inputLatency, &outputLatency);
  208086. if ((err = asioObject->start()) != 0)
  208087. {
  208088. // ignore an error here, as it might start later after setting other stuff up
  208089. logError ("ASIO start", err);
  208090. }
  208091. Thread::sleep (100);
  208092. asioObject->stop();
  208093. }
  208094. else
  208095. {
  208096. error = "Can't detect buffer sizes";
  208097. }
  208098. }
  208099. else
  208100. {
  208101. error = "Can't detect asio channels";
  208102. }
  208103. }
  208104. }
  208105. else
  208106. {
  208107. error = "No such device";
  208108. }
  208109. if (error.isNotEmpty())
  208110. {
  208111. logError (error, err);
  208112. if (asioObject != 0)
  208113. asioObject->disposeBuffers();
  208114. removeCurrentDriver();
  208115. isASIOOpen = false;
  208116. }
  208117. else
  208118. {
  208119. isASIOOpen = true;
  208120. log ("ASIO device open");
  208121. }
  208122. isOpen_ = false;
  208123. needToReset = false;
  208124. isReSync = false;
  208125. return error;
  208126. }
  208127. void callback (const long index) throw()
  208128. {
  208129. if (isStarted)
  208130. {
  208131. bufferIndex = index;
  208132. processBuffer();
  208133. }
  208134. else
  208135. {
  208136. if (postOutput && (asioObject != 0))
  208137. asioObject->outputReady();
  208138. }
  208139. calledback = true;
  208140. }
  208141. void processBuffer() throw()
  208142. {
  208143. const ASIOBufferInfo* const infos = bufferInfos;
  208144. const int bi = bufferIndex;
  208145. const ScopedLock sl (callbackLock);
  208146. if (needToReset)
  208147. {
  208148. needToReset = false;
  208149. if (isReSync)
  208150. {
  208151. log ("! ASIO resync");
  208152. isReSync = false;
  208153. }
  208154. else
  208155. {
  208156. startTimer (20);
  208157. }
  208158. }
  208159. if (bi >= 0)
  208160. {
  208161. const int samps = currentBlockSizeSamples;
  208162. if (currentCallback != 0)
  208163. {
  208164. int i;
  208165. for (i = 0; i < numActiveInputChans; ++i)
  208166. {
  208167. float* const dst = inBuffers[i];
  208168. jassert (dst != 0);
  208169. const char* const src = (const char*) (infos[i].buffers[bi]);
  208170. if (inputChannelIsFloat[i])
  208171. {
  208172. memcpy (dst, src, samps * sizeof (float));
  208173. }
  208174. else
  208175. {
  208176. jassert (dst == tempBuffer + (samps * i));
  208177. switch (inputChannelBitDepths[i])
  208178. {
  208179. case 16:
  208180. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  208181. samps, inputChannelLittleEndian[i]);
  208182. break;
  208183. case 24:
  208184. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  208185. samps, inputChannelLittleEndian[i]);
  208186. break;
  208187. case 32:
  208188. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  208189. samps, inputChannelLittleEndian[i]);
  208190. break;
  208191. case 64:
  208192. jassertfalse
  208193. break;
  208194. }
  208195. }
  208196. }
  208197. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  208198. numActiveInputChans,
  208199. outBuffers,
  208200. numActiveOutputChans,
  208201. samps);
  208202. for (i = 0; i < numActiveOutputChans; ++i)
  208203. {
  208204. float* const src = outBuffers[i];
  208205. jassert (src != 0);
  208206. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  208207. if (outputChannelIsFloat[i])
  208208. {
  208209. memcpy (dst, src, samps * sizeof (float));
  208210. }
  208211. else
  208212. {
  208213. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  208214. switch (outputChannelBitDepths[i])
  208215. {
  208216. case 16:
  208217. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  208218. samps, outputChannelLittleEndian[i]);
  208219. break;
  208220. case 24:
  208221. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  208222. samps, outputChannelLittleEndian[i]);
  208223. break;
  208224. case 32:
  208225. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  208226. samps, outputChannelLittleEndian[i]);
  208227. break;
  208228. case 64:
  208229. jassertfalse
  208230. break;
  208231. }
  208232. }
  208233. }
  208234. }
  208235. else
  208236. {
  208237. for (int i = 0; i < numActiveOutputChans; ++i)
  208238. {
  208239. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  208240. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  208241. }
  208242. }
  208243. }
  208244. if (postOutput)
  208245. asioObject->outputReady();
  208246. }
  208247. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long) throw()
  208248. {
  208249. if (currentASIODev[0] != 0)
  208250. currentASIODev[0]->callback (index);
  208251. return 0;
  208252. }
  208253. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long) throw()
  208254. {
  208255. if (currentASIODev[1] != 0)
  208256. currentASIODev[1]->callback (index);
  208257. return 0;
  208258. }
  208259. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long) throw()
  208260. {
  208261. if (currentASIODev[2] != 0)
  208262. currentASIODev[2]->callback (index);
  208263. return 0;
  208264. }
  208265. static void bufferSwitchCallback0 (long index, long) throw()
  208266. {
  208267. if (currentASIODev[0] != 0)
  208268. currentASIODev[0]->callback (index);
  208269. }
  208270. static void bufferSwitchCallback1 (long index, long) throw()
  208271. {
  208272. if (currentASIODev[1] != 0)
  208273. currentASIODev[1]->callback (index);
  208274. }
  208275. static void bufferSwitchCallback2 (long index, long) throw()
  208276. {
  208277. if (currentASIODev[2] != 0)
  208278. currentASIODev[2]->callback (index);
  208279. }
  208280. static long asioMessagesCallback0 (long selector, long value, void*, double*) throw()
  208281. {
  208282. return asioMessagesCallback (selector, value, 0);
  208283. }
  208284. static long asioMessagesCallback1 (long selector, long value, void*, double*) throw()
  208285. {
  208286. return asioMessagesCallback (selector, value, 1);
  208287. }
  208288. static long asioMessagesCallback2 (long selector, long value, void*, double*) throw()
  208289. {
  208290. return asioMessagesCallback (selector, value, 2);
  208291. }
  208292. static long asioMessagesCallback (long selector, long value, const int deviceIndex) throw()
  208293. {
  208294. switch (selector)
  208295. {
  208296. case kAsioSelectorSupported:
  208297. if (value == kAsioResetRequest
  208298. || value == kAsioEngineVersion
  208299. || value == kAsioResyncRequest
  208300. || value == kAsioLatenciesChanged
  208301. || value == kAsioSupportsInputMonitor)
  208302. return 1;
  208303. break;
  208304. case kAsioBufferSizeChange:
  208305. break;
  208306. case kAsioResetRequest:
  208307. if (currentASIODev[deviceIndex] != 0)
  208308. currentASIODev[deviceIndex]->resetRequest();
  208309. return 1;
  208310. case kAsioResyncRequest:
  208311. if (currentASIODev[deviceIndex] != 0)
  208312. currentASIODev[deviceIndex]->resyncRequest();
  208313. return 1;
  208314. case kAsioLatenciesChanged:
  208315. return 1;
  208316. case kAsioEngineVersion:
  208317. return 2;
  208318. case kAsioSupportsTimeInfo:
  208319. case kAsioSupportsTimeCode:
  208320. return 0;
  208321. }
  208322. return 0;
  208323. }
  208324. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  208325. {
  208326. }
  208327. static void convertInt16ToFloat (const char* src,
  208328. float* dest,
  208329. const int srcStrideBytes,
  208330. int numSamples,
  208331. const bool littleEndian) throw()
  208332. {
  208333. const double g = 1.0 / 32768.0;
  208334. if (littleEndian)
  208335. {
  208336. while (--numSamples >= 0)
  208337. {
  208338. *dest++ = (float) (g * (short) littleEndianShort (src));
  208339. src += srcStrideBytes;
  208340. }
  208341. }
  208342. else
  208343. {
  208344. while (--numSamples >= 0)
  208345. {
  208346. *dest++ = (float) (g * (short) bigEndianShort (src));
  208347. src += srcStrideBytes;
  208348. }
  208349. }
  208350. }
  208351. static void convertFloatToInt16 (const float* src,
  208352. char* dest,
  208353. const int dstStrideBytes,
  208354. int numSamples,
  208355. const bool littleEndian) throw()
  208356. {
  208357. const double maxVal = (double) 0x7fff;
  208358. if (littleEndian)
  208359. {
  208360. while (--numSamples >= 0)
  208361. {
  208362. *(uint16*) dest = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  208363. dest += dstStrideBytes;
  208364. }
  208365. }
  208366. else
  208367. {
  208368. while (--numSamples >= 0)
  208369. {
  208370. *(uint16*) dest = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  208371. dest += dstStrideBytes;
  208372. }
  208373. }
  208374. }
  208375. static void convertInt24ToFloat (const char* src,
  208376. float* dest,
  208377. const int srcStrideBytes,
  208378. int numSamples,
  208379. const bool littleEndian) throw()
  208380. {
  208381. const double g = 1.0 / 0x7fffff;
  208382. if (littleEndian)
  208383. {
  208384. while (--numSamples >= 0)
  208385. {
  208386. *dest++ = (float) (g * littleEndian24Bit (src));
  208387. src += srcStrideBytes;
  208388. }
  208389. }
  208390. else
  208391. {
  208392. while (--numSamples >= 0)
  208393. {
  208394. *dest++ = (float) (g * bigEndian24Bit (src));
  208395. src += srcStrideBytes;
  208396. }
  208397. }
  208398. }
  208399. static void convertFloatToInt24 (const float* src,
  208400. char* dest,
  208401. const int dstStrideBytes,
  208402. int numSamples,
  208403. const bool littleEndian) throw()
  208404. {
  208405. const double maxVal = (double) 0x7fffff;
  208406. if (littleEndian)
  208407. {
  208408. while (--numSamples >= 0)
  208409. {
  208410. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  208411. dest += dstStrideBytes;
  208412. }
  208413. }
  208414. else
  208415. {
  208416. while (--numSamples >= 0)
  208417. {
  208418. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  208419. dest += dstStrideBytes;
  208420. }
  208421. }
  208422. }
  208423. static void convertInt32ToFloat (const char* src,
  208424. float* dest,
  208425. const int srcStrideBytes,
  208426. int numSamples,
  208427. const bool littleEndian) throw()
  208428. {
  208429. const double g = 1.0 / 0x7fffffff;
  208430. if (littleEndian)
  208431. {
  208432. while (--numSamples >= 0)
  208433. {
  208434. *dest++ = (float) (g * (int) littleEndianInt (src));
  208435. src += srcStrideBytes;
  208436. }
  208437. }
  208438. else
  208439. {
  208440. while (--numSamples >= 0)
  208441. {
  208442. *dest++ = (float) (g * (int) bigEndianInt (src));
  208443. src += srcStrideBytes;
  208444. }
  208445. }
  208446. }
  208447. static void convertFloatToInt32 (const float* src,
  208448. char* dest,
  208449. const int dstStrideBytes,
  208450. int numSamples,
  208451. const bool littleEndian) throw()
  208452. {
  208453. const double maxVal = (double) 0x7fffffff;
  208454. if (littleEndian)
  208455. {
  208456. while (--numSamples >= 0)
  208457. {
  208458. *(uint32*) dest = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  208459. dest += dstStrideBytes;
  208460. }
  208461. }
  208462. else
  208463. {
  208464. while (--numSamples >= 0)
  208465. {
  208466. *(uint32*) dest = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  208467. dest += dstStrideBytes;
  208468. }
  208469. }
  208470. }
  208471. static void typeToFormatParameters (const long type,
  208472. int& bitDepth,
  208473. int& byteStride,
  208474. bool& formatIsFloat,
  208475. bool& littleEndian) throw()
  208476. {
  208477. bitDepth = 0;
  208478. littleEndian = false;
  208479. formatIsFloat = false;
  208480. switch (type)
  208481. {
  208482. case ASIOSTInt16MSB:
  208483. case ASIOSTInt16LSB:
  208484. case ASIOSTInt32MSB16:
  208485. case ASIOSTInt32LSB16:
  208486. bitDepth = 16; break;
  208487. case ASIOSTFloat32MSB:
  208488. case ASIOSTFloat32LSB:
  208489. formatIsFloat = true;
  208490. bitDepth = 32; break;
  208491. case ASIOSTInt32MSB:
  208492. case ASIOSTInt32LSB:
  208493. bitDepth = 32; break;
  208494. case ASIOSTInt24MSB:
  208495. case ASIOSTInt24LSB:
  208496. case ASIOSTInt32MSB24:
  208497. case ASIOSTInt32LSB24:
  208498. case ASIOSTInt32MSB18:
  208499. case ASIOSTInt32MSB20:
  208500. case ASIOSTInt32LSB18:
  208501. case ASIOSTInt32LSB20:
  208502. bitDepth = 24; break;
  208503. case ASIOSTFloat64MSB:
  208504. case ASIOSTFloat64LSB:
  208505. default:
  208506. bitDepth = 64;
  208507. break;
  208508. }
  208509. switch (type)
  208510. {
  208511. case ASIOSTInt16MSB:
  208512. case ASIOSTInt32MSB16:
  208513. case ASIOSTFloat32MSB:
  208514. case ASIOSTFloat64MSB:
  208515. case ASIOSTInt32MSB:
  208516. case ASIOSTInt32MSB18:
  208517. case ASIOSTInt32MSB20:
  208518. case ASIOSTInt32MSB24:
  208519. case ASIOSTInt24MSB:
  208520. littleEndian = false; break;
  208521. case ASIOSTInt16LSB:
  208522. case ASIOSTInt32LSB16:
  208523. case ASIOSTFloat32LSB:
  208524. case ASIOSTFloat64LSB:
  208525. case ASIOSTInt32LSB:
  208526. case ASIOSTInt32LSB18:
  208527. case ASIOSTInt32LSB20:
  208528. case ASIOSTInt32LSB24:
  208529. case ASIOSTInt24LSB:
  208530. littleEndian = true; break;
  208531. default:
  208532. break;
  208533. }
  208534. switch (type)
  208535. {
  208536. case ASIOSTInt16LSB:
  208537. case ASIOSTInt16MSB:
  208538. byteStride = 2; break;
  208539. case ASIOSTInt24LSB:
  208540. case ASIOSTInt24MSB:
  208541. byteStride = 3; break;
  208542. case ASIOSTInt32MSB16:
  208543. case ASIOSTInt32LSB16:
  208544. case ASIOSTInt32MSB:
  208545. case ASIOSTInt32MSB18:
  208546. case ASIOSTInt32MSB20:
  208547. case ASIOSTInt32MSB24:
  208548. case ASIOSTInt32LSB:
  208549. case ASIOSTInt32LSB18:
  208550. case ASIOSTInt32LSB20:
  208551. case ASIOSTInt32LSB24:
  208552. case ASIOSTFloat32LSB:
  208553. case ASIOSTFloat32MSB:
  208554. byteStride = 4; break;
  208555. case ASIOSTFloat64MSB:
  208556. case ASIOSTFloat64LSB:
  208557. byteStride = 8; break;
  208558. default:
  208559. break;
  208560. }
  208561. }
  208562. };
  208563. class ASIOAudioIODeviceType : public AudioIODeviceType
  208564. {
  208565. public:
  208566. ASIOAudioIODeviceType()
  208567. : AudioIODeviceType (T("ASIO")),
  208568. classIds (2),
  208569. hasScanned (false)
  208570. {
  208571. CoInitialize (0);
  208572. }
  208573. ~ASIOAudioIODeviceType()
  208574. {
  208575. }
  208576. void scanForDevices()
  208577. {
  208578. hasScanned = true;
  208579. deviceNames.clear();
  208580. classIds.clear();
  208581. HKEY hk = 0;
  208582. int index = 0;
  208583. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  208584. {
  208585. for (;;)
  208586. {
  208587. char name [256];
  208588. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  208589. {
  208590. addDriverInfo (name, hk);
  208591. }
  208592. else
  208593. {
  208594. break;
  208595. }
  208596. }
  208597. RegCloseKey (hk);
  208598. }
  208599. }
  208600. const StringArray getDeviceNames (const bool /*wantInputNames*/) const
  208601. {
  208602. jassert (hasScanned); // need to call scanForDevices() before doing this
  208603. return deviceNames;
  208604. }
  208605. int getDefaultDeviceIndex (const bool) const
  208606. {
  208607. jassert (hasScanned); // need to call scanForDevices() before doing this
  208608. for (int i = deviceNames.size(); --i >= 0;)
  208609. if (deviceNames[i].containsIgnoreCase (T("asio4all")))
  208610. return i; // asio4all is a safe choice for a default..
  208611. #if JUCE_DEBUG
  208612. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase (T("digidesign")))
  208613. return 1; // (the digi m-box driver crashes the app when you run
  208614. // it in the debugger, which can be a bit annoying)
  208615. #endif
  208616. return 0;
  208617. }
  208618. static int findFreeSlot()
  208619. {
  208620. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  208621. if (currentASIODev[i] == 0)
  208622. return i;
  208623. jassertfalse; // unfortunately you can only have a finite number
  208624. // of ASIO devices open at the same time..
  208625. return -1;
  208626. }
  208627. int getIndexOfDevice (AudioIODevice* d, const bool /*asInput*/) const
  208628. {
  208629. jassert (hasScanned); // need to call scanForDevices() before doing this
  208630. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  208631. }
  208632. bool hasSeparateInputsAndOutputs() const { return false; }
  208633. AudioIODevice* createDevice (const String& outputDeviceName,
  208634. const String& inputDeviceName)
  208635. {
  208636. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  208637. (void) inputDeviceName;
  208638. jassert (hasScanned); // need to call scanForDevices() before doing this
  208639. const int index = deviceNames.indexOf (outputDeviceName);
  208640. if (index >= 0)
  208641. {
  208642. const int freeSlot = findFreeSlot();
  208643. if (freeSlot >= 0)
  208644. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  208645. }
  208646. return 0;
  208647. }
  208648. juce_UseDebuggingNewOperator
  208649. private:
  208650. StringArray deviceNames;
  208651. OwnedArray <CLSID> classIds;
  208652. bool hasScanned;
  208653. static bool checkClassIsOk (const String& classId)
  208654. {
  208655. HKEY hk = 0;
  208656. bool ok = false;
  208657. if (RegOpenKeyA (HKEY_CLASSES_ROOT, "clsid", &hk) == ERROR_SUCCESS)
  208658. {
  208659. int index = 0;
  208660. for (;;)
  208661. {
  208662. char buf [512];
  208663. if (RegEnumKeyA (hk, index++, buf, 512) == ERROR_SUCCESS)
  208664. {
  208665. if (classId.equalsIgnoreCase (buf))
  208666. {
  208667. HKEY subKey, pathKey;
  208668. if (RegOpenKeyExA (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  208669. {
  208670. if (RegOpenKeyExA (subKey, "InprocServer32", 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  208671. {
  208672. char pathName [600];
  208673. DWORD dtype = REG_SZ;
  208674. DWORD dsize = sizeof (pathName);
  208675. if (RegQueryValueExA (pathKey, 0, 0, &dtype,
  208676. (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  208677. {
  208678. OFSTRUCT of;
  208679. zerostruct (of);
  208680. of.cBytes = sizeof (of);
  208681. ok = (OpenFile (String (pathName), &of, OF_EXIST) != 0);
  208682. }
  208683. RegCloseKey (pathKey);
  208684. }
  208685. RegCloseKey (subKey);
  208686. }
  208687. break;
  208688. }
  208689. }
  208690. else
  208691. {
  208692. break;
  208693. }
  208694. }
  208695. RegCloseKey (hk);
  208696. }
  208697. return ok;
  208698. }
  208699. void addDriverInfo (const String& keyName, HKEY hk)
  208700. {
  208701. HKEY subKey;
  208702. if (RegOpenKeyExA (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  208703. {
  208704. char buf [256];
  208705. DWORD dtype = REG_SZ;
  208706. DWORD dsize = sizeof (buf);
  208707. zeromem (buf, dsize);
  208708. if (RegQueryValueExA (subKey, "clsid", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  208709. {
  208710. if (dsize > 0 && checkClassIsOk (buf))
  208711. {
  208712. wchar_t classIdStr [130];
  208713. MultiByteToWideChar (CP_ACP, 0, buf, -1, classIdStr, 128);
  208714. String deviceName;
  208715. CLSID classId;
  208716. if (CLSIDFromString ((LPOLESTR) classIdStr, &classId) == S_OK)
  208717. {
  208718. dtype = REG_SZ;
  208719. dsize = sizeof (buf);
  208720. if (RegQueryValueExA (subKey, "description", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  208721. deviceName = buf;
  208722. else
  208723. deviceName = keyName;
  208724. log (T("found ") + deviceName);
  208725. deviceNames.add (deviceName);
  208726. classIds.add (new CLSID (classId));
  208727. }
  208728. }
  208729. RegCloseKey (subKey);
  208730. }
  208731. }
  208732. }
  208733. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  208734. const ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  208735. };
  208736. AudioIODeviceType* juce_createASIOAudioIODeviceType()
  208737. {
  208738. return new ASIOAudioIODeviceType();
  208739. }
  208740. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  208741. void* guid,
  208742. const String& optionalDllForDirectLoading)
  208743. {
  208744. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  208745. if (freeSlot < 0)
  208746. return 0;
  208747. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  208748. }
  208749. #undef log
  208750. #endif
  208751. /********* End of inlined file: juce_win32_ASIO.cpp *********/
  208752. /********* Start of inlined file: juce_win32_DirectSound.cpp *********/
  208753. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208754. // compiled on its own).
  208755. #if JUCE_INCLUDED_FILE
  208756. END_JUCE_NAMESPACE
  208757. extern "C"
  208758. {
  208759. // Declare just the minimum number of interfaces for the DSound objects that we need..
  208760. typedef struct typeDSBUFFERDESC
  208761. {
  208762. DWORD dwSize;
  208763. DWORD dwFlags;
  208764. DWORD dwBufferBytes;
  208765. DWORD dwReserved;
  208766. LPWAVEFORMATEX lpwfxFormat;
  208767. GUID guid3DAlgorithm;
  208768. } DSBUFFERDESC;
  208769. struct IDirectSoundBuffer;
  208770. #undef INTERFACE
  208771. #define INTERFACE IDirectSound
  208772. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  208773. {
  208774. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  208775. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  208776. STDMETHOD_(ULONG,Release) (THIS) PURE;
  208777. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  208778. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  208779. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  208780. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  208781. STDMETHOD(Compact) (THIS) PURE;
  208782. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  208783. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  208784. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  208785. };
  208786. #undef INTERFACE
  208787. #define INTERFACE IDirectSoundBuffer
  208788. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  208789. {
  208790. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  208791. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  208792. STDMETHOD_(ULONG,Release) (THIS) PURE;
  208793. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  208794. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  208795. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  208796. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  208797. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  208798. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  208799. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  208800. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  208801. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  208802. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  208803. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  208804. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  208805. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  208806. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  208807. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  208808. STDMETHOD(Stop) (THIS) PURE;
  208809. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  208810. STDMETHOD(Restore) (THIS) PURE;
  208811. };
  208812. typedef struct typeDSCBUFFERDESC
  208813. {
  208814. DWORD dwSize;
  208815. DWORD dwFlags;
  208816. DWORD dwBufferBytes;
  208817. DWORD dwReserved;
  208818. LPWAVEFORMATEX lpwfxFormat;
  208819. } DSCBUFFERDESC;
  208820. struct IDirectSoundCaptureBuffer;
  208821. #undef INTERFACE
  208822. #define INTERFACE IDirectSoundCapture
  208823. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  208824. {
  208825. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  208826. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  208827. STDMETHOD_(ULONG,Release) (THIS) PURE;
  208828. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  208829. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  208830. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  208831. };
  208832. #undef INTERFACE
  208833. #define INTERFACE IDirectSoundCaptureBuffer
  208834. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  208835. {
  208836. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  208837. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  208838. STDMETHOD_(ULONG,Release) (THIS) PURE;
  208839. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  208840. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  208841. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  208842. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  208843. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  208844. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  208845. STDMETHOD(Start) (THIS_ DWORD) PURE;
  208846. STDMETHOD(Stop) (THIS) PURE;
  208847. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  208848. };
  208849. };
  208850. BEGIN_JUCE_NAMESPACE
  208851. static const String getDSErrorMessage (HRESULT hr)
  208852. {
  208853. const char* result = 0;
  208854. switch (hr)
  208855. {
  208856. case MAKE_HRESULT(1, 0x878, 10):
  208857. result = "Device already allocated";
  208858. break;
  208859. case MAKE_HRESULT(1, 0x878, 30):
  208860. result = "Control unavailable";
  208861. break;
  208862. case E_INVALIDARG:
  208863. result = "Invalid parameter";
  208864. break;
  208865. case MAKE_HRESULT(1, 0x878, 50):
  208866. result = "Invalid call";
  208867. break;
  208868. case E_FAIL:
  208869. result = "Generic error";
  208870. break;
  208871. case MAKE_HRESULT(1, 0x878, 70):
  208872. result = "Priority level error";
  208873. break;
  208874. case E_OUTOFMEMORY:
  208875. result = "Out of memory";
  208876. break;
  208877. case MAKE_HRESULT(1, 0x878, 100):
  208878. result = "Bad format";
  208879. break;
  208880. case E_NOTIMPL:
  208881. result = "Unsupported function";
  208882. break;
  208883. case MAKE_HRESULT(1, 0x878, 120):
  208884. result = "No driver";
  208885. break;
  208886. case MAKE_HRESULT(1, 0x878, 130):
  208887. result = "Already initialised";
  208888. break;
  208889. case CLASS_E_NOAGGREGATION:
  208890. result = "No aggregation";
  208891. break;
  208892. case MAKE_HRESULT(1, 0x878, 150):
  208893. result = "Buffer lost";
  208894. break;
  208895. case MAKE_HRESULT(1, 0x878, 160):
  208896. result = "Another app has priority";
  208897. break;
  208898. case MAKE_HRESULT(1, 0x878, 170):
  208899. result = "Uninitialised";
  208900. break;
  208901. case E_NOINTERFACE:
  208902. result = "No interface";
  208903. break;
  208904. case S_OK:
  208905. result = "No error";
  208906. break;
  208907. default:
  208908. return "Unknown error: " + String ((int) hr);
  208909. }
  208910. return result;
  208911. }
  208912. #define DS_DEBUGGING 1
  208913. #ifdef DS_DEBUGGING
  208914. #define CATCH JUCE_CATCH_EXCEPTION
  208915. #undef log
  208916. #define log(a) Logger::writeToLog(a);
  208917. #undef logError
  208918. #define logError(a) logDSError(a, __LINE__);
  208919. static void logDSError (HRESULT hr, int lineNum)
  208920. {
  208921. if (hr != S_OK)
  208922. {
  208923. String error ("DS error at line ");
  208924. error << lineNum << T(" - ") << getDSErrorMessage (hr);
  208925. log (error);
  208926. }
  208927. }
  208928. #else
  208929. #define CATCH JUCE_CATCH_ALL
  208930. #define log(a)
  208931. #define logError(a)
  208932. #endif
  208933. #define DSOUND_FUNCTION(functionName, params) \
  208934. typedef HRESULT (WINAPI *type##functionName) params; \
  208935. static type##functionName ds##functionName = 0;
  208936. #define DSOUND_FUNCTION_LOAD(functionName) \
  208937. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  208938. jassert (ds##functionName != 0);
  208939. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  208940. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  208941. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  208942. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  208943. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  208944. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  208945. static void initialiseDSoundFunctions()
  208946. {
  208947. if (dsDirectSoundCreate == 0)
  208948. {
  208949. HMODULE h = LoadLibraryA ("dsound.dll");
  208950. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  208951. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  208952. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  208953. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  208954. }
  208955. }
  208956. class DSoundInternalOutChannel
  208957. {
  208958. String name;
  208959. LPGUID guid;
  208960. int sampleRate, bufferSizeSamples;
  208961. float* leftBuffer;
  208962. float* rightBuffer;
  208963. IDirectSound* pDirectSound;
  208964. IDirectSoundBuffer* pOutputBuffer;
  208965. DWORD writeOffset;
  208966. int totalBytesPerBuffer;
  208967. int bytesPerBuffer;
  208968. unsigned int lastPlayCursor;
  208969. public:
  208970. int bitDepth;
  208971. bool doneFlag;
  208972. DSoundInternalOutChannel (const String& name_,
  208973. LPGUID guid_,
  208974. int rate,
  208975. int bufferSize,
  208976. float* left,
  208977. float* right)
  208978. : name (name_),
  208979. guid (guid_),
  208980. sampleRate (rate),
  208981. bufferSizeSamples (bufferSize),
  208982. leftBuffer (left),
  208983. rightBuffer (right),
  208984. pDirectSound (0),
  208985. pOutputBuffer (0),
  208986. bitDepth (16)
  208987. {
  208988. }
  208989. ~DSoundInternalOutChannel()
  208990. {
  208991. close();
  208992. }
  208993. void close()
  208994. {
  208995. HRESULT hr;
  208996. if (pOutputBuffer != 0)
  208997. {
  208998. JUCE_TRY
  208999. {
  209000. log (T("closing dsound out: ") + name);
  209001. hr = pOutputBuffer->Stop();
  209002. logError (hr);
  209003. }
  209004. CATCH
  209005. JUCE_TRY
  209006. {
  209007. hr = pOutputBuffer->Release();
  209008. logError (hr);
  209009. }
  209010. CATCH
  209011. pOutputBuffer = 0;
  209012. }
  209013. if (pDirectSound != 0)
  209014. {
  209015. JUCE_TRY
  209016. {
  209017. hr = pDirectSound->Release();
  209018. logError (hr);
  209019. }
  209020. CATCH
  209021. pDirectSound = 0;
  209022. }
  209023. }
  209024. const String open()
  209025. {
  209026. log (T("opening dsound out device: ") + name
  209027. + T(" rate=") + String (sampleRate)
  209028. + T(" bits=") + String (bitDepth)
  209029. + T(" buf=") + String (bufferSizeSamples));
  209030. pDirectSound = 0;
  209031. pOutputBuffer = 0;
  209032. writeOffset = 0;
  209033. String error;
  209034. HRESULT hr = E_NOINTERFACE;
  209035. if (dsDirectSoundCreate != 0)
  209036. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  209037. if (hr == S_OK)
  209038. {
  209039. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  209040. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  209041. const int numChannels = 2;
  209042. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  209043. logError (hr);
  209044. if (hr == S_OK)
  209045. {
  209046. IDirectSoundBuffer* pPrimaryBuffer;
  209047. DSBUFFERDESC primaryDesc;
  209048. zerostruct (primaryDesc);
  209049. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  209050. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  209051. primaryDesc.dwBufferBytes = 0;
  209052. primaryDesc.lpwfxFormat = 0;
  209053. log ("opening dsound out step 2");
  209054. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  209055. logError (hr);
  209056. if (hr == S_OK)
  209057. {
  209058. WAVEFORMATEX wfFormat;
  209059. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  209060. wfFormat.nChannels = (unsigned short) numChannels;
  209061. wfFormat.nSamplesPerSec = sampleRate;
  209062. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  209063. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  209064. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  209065. wfFormat.cbSize = 0;
  209066. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  209067. logError (hr);
  209068. if (hr == S_OK)
  209069. {
  209070. DSBUFFERDESC secondaryDesc;
  209071. zerostruct (secondaryDesc);
  209072. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  209073. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  209074. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  209075. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  209076. secondaryDesc.lpwfxFormat = &wfFormat;
  209077. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  209078. logError (hr);
  209079. if (hr == S_OK)
  209080. {
  209081. log ("opening dsound out step 3");
  209082. DWORD dwDataLen;
  209083. unsigned char* pDSBuffData;
  209084. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  209085. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  209086. logError (hr);
  209087. if (hr == S_OK)
  209088. {
  209089. zeromem (pDSBuffData, dwDataLen);
  209090. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  209091. if (hr == S_OK)
  209092. {
  209093. hr = pOutputBuffer->SetCurrentPosition (0);
  209094. if (hr == S_OK)
  209095. {
  209096. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  209097. if (hr == S_OK)
  209098. return String::empty;
  209099. }
  209100. }
  209101. }
  209102. }
  209103. }
  209104. }
  209105. }
  209106. }
  209107. error = getDSErrorMessage (hr);
  209108. close();
  209109. return error;
  209110. }
  209111. void synchronisePosition()
  209112. {
  209113. if (pOutputBuffer != 0)
  209114. {
  209115. DWORD playCursor;
  209116. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  209117. }
  209118. }
  209119. bool service()
  209120. {
  209121. if (pOutputBuffer == 0)
  209122. return true;
  209123. DWORD playCursor, writeCursor;
  209124. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  209125. if (hr != S_OK)
  209126. {
  209127. logError (hr);
  209128. jassertfalse
  209129. return true;
  209130. }
  209131. int playWriteGap = writeCursor - playCursor;
  209132. if (playWriteGap < 0)
  209133. playWriteGap += totalBytesPerBuffer;
  209134. int bytesEmpty = playCursor - writeOffset;
  209135. if (bytesEmpty < 0)
  209136. bytesEmpty += totalBytesPerBuffer;
  209137. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  209138. {
  209139. writeOffset = writeCursor;
  209140. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  209141. }
  209142. if (bytesEmpty >= bytesPerBuffer)
  209143. {
  209144. LPBYTE lpbuf1 = 0;
  209145. LPBYTE lpbuf2 = 0;
  209146. DWORD dwSize1 = 0;
  209147. DWORD dwSize2 = 0;
  209148. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  209149. bytesPerBuffer,
  209150. (void**) &lpbuf1, &dwSize1,
  209151. (void**) &lpbuf2, &dwSize2, 0);
  209152. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  209153. {
  209154. pOutputBuffer->Restore();
  209155. hr = pOutputBuffer->Lock (writeOffset,
  209156. bytesPerBuffer,
  209157. (void**) &lpbuf1, &dwSize1,
  209158. (void**) &lpbuf2, &dwSize2, 0);
  209159. }
  209160. if (hr == S_OK)
  209161. {
  209162. if (bitDepth == 16)
  209163. {
  209164. const float gainL = 32767.0f;
  209165. const float gainR = 32767.0f;
  209166. int* dest = (int*)lpbuf1;
  209167. const float* left = leftBuffer;
  209168. const float* right = rightBuffer;
  209169. int samples1 = dwSize1 >> 2;
  209170. int samples2 = dwSize2 >> 2;
  209171. if (left == 0)
  209172. {
  209173. while (--samples1 >= 0)
  209174. {
  209175. int r = roundFloatToInt (gainR * *right++);
  209176. if (r < -32768)
  209177. r = -32768;
  209178. else if (r > 32767)
  209179. r = 32767;
  209180. *dest++ = (r << 16);
  209181. }
  209182. dest = (int*)lpbuf2;
  209183. while (--samples2 >= 0)
  209184. {
  209185. int r = roundFloatToInt (gainR * *right++);
  209186. if (r < -32768)
  209187. r = -32768;
  209188. else if (r > 32767)
  209189. r = 32767;
  209190. *dest++ = (r << 16);
  209191. }
  209192. }
  209193. else if (right == 0)
  209194. {
  209195. while (--samples1 >= 0)
  209196. {
  209197. int l = roundFloatToInt (gainL * *left++);
  209198. if (l < -32768)
  209199. l = -32768;
  209200. else if (l > 32767)
  209201. l = 32767;
  209202. l &= 0xffff;
  209203. *dest++ = l;
  209204. }
  209205. dest = (int*)lpbuf2;
  209206. while (--samples2 >= 0)
  209207. {
  209208. int l = roundFloatToInt (gainL * *left++);
  209209. if (l < -32768)
  209210. l = -32768;
  209211. else if (l > 32767)
  209212. l = 32767;
  209213. l &= 0xffff;
  209214. *dest++ = l;
  209215. }
  209216. }
  209217. else
  209218. {
  209219. while (--samples1 >= 0)
  209220. {
  209221. int l = roundFloatToInt (gainL * *left++);
  209222. if (l < -32768)
  209223. l = -32768;
  209224. else if (l > 32767)
  209225. l = 32767;
  209226. l &= 0xffff;
  209227. int r = roundFloatToInt (gainR * *right++);
  209228. if (r < -32768)
  209229. r = -32768;
  209230. else if (r > 32767)
  209231. r = 32767;
  209232. *dest++ = (r << 16) | l;
  209233. }
  209234. dest = (int*)lpbuf2;
  209235. while (--samples2 >= 0)
  209236. {
  209237. int l = roundFloatToInt (gainL * *left++);
  209238. if (l < -32768)
  209239. l = -32768;
  209240. else if (l > 32767)
  209241. l = 32767;
  209242. l &= 0xffff;
  209243. int r = roundFloatToInt (gainR * *right++);
  209244. if (r < -32768)
  209245. r = -32768;
  209246. else if (r > 32767)
  209247. r = 32767;
  209248. *dest++ = (r << 16) | l;
  209249. }
  209250. }
  209251. }
  209252. else
  209253. {
  209254. jassertfalse
  209255. }
  209256. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  209257. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  209258. }
  209259. else
  209260. {
  209261. jassertfalse
  209262. logError (hr);
  209263. }
  209264. bytesEmpty -= bytesPerBuffer;
  209265. return true;
  209266. }
  209267. else
  209268. {
  209269. return false;
  209270. }
  209271. }
  209272. };
  209273. struct DSoundInternalInChannel
  209274. {
  209275. String name;
  209276. LPGUID guid;
  209277. int sampleRate, bufferSizeSamples;
  209278. float* leftBuffer;
  209279. float* rightBuffer;
  209280. IDirectSound* pDirectSound;
  209281. IDirectSoundCapture* pDirectSoundCapture;
  209282. IDirectSoundCaptureBuffer* pInputBuffer;
  209283. public:
  209284. unsigned int readOffset;
  209285. int bytesPerBuffer, totalBytesPerBuffer;
  209286. int bitDepth;
  209287. bool doneFlag;
  209288. DSoundInternalInChannel (const String& name_,
  209289. LPGUID guid_,
  209290. int rate,
  209291. int bufferSize,
  209292. float* left,
  209293. float* right)
  209294. : name (name_),
  209295. guid (guid_),
  209296. sampleRate (rate),
  209297. bufferSizeSamples (bufferSize),
  209298. leftBuffer (left),
  209299. rightBuffer (right),
  209300. pDirectSound (0),
  209301. pDirectSoundCapture (0),
  209302. pInputBuffer (0),
  209303. bitDepth (16)
  209304. {
  209305. }
  209306. ~DSoundInternalInChannel()
  209307. {
  209308. close();
  209309. }
  209310. void close()
  209311. {
  209312. HRESULT hr;
  209313. if (pInputBuffer != 0)
  209314. {
  209315. JUCE_TRY
  209316. {
  209317. log (T("closing dsound in: ") + name);
  209318. hr = pInputBuffer->Stop();
  209319. logError (hr);
  209320. }
  209321. CATCH
  209322. JUCE_TRY
  209323. {
  209324. hr = pInputBuffer->Release();
  209325. logError (hr);
  209326. }
  209327. CATCH
  209328. pInputBuffer = 0;
  209329. }
  209330. if (pDirectSoundCapture != 0)
  209331. {
  209332. JUCE_TRY
  209333. {
  209334. hr = pDirectSoundCapture->Release();
  209335. logError (hr);
  209336. }
  209337. CATCH
  209338. pDirectSoundCapture = 0;
  209339. }
  209340. if (pDirectSound != 0)
  209341. {
  209342. JUCE_TRY
  209343. {
  209344. hr = pDirectSound->Release();
  209345. logError (hr);
  209346. }
  209347. CATCH
  209348. pDirectSound = 0;
  209349. }
  209350. }
  209351. const String open()
  209352. {
  209353. log (T("opening dsound in device: ") + name
  209354. + T(" rate=") + String (sampleRate) + T(" bits=") + String (bitDepth) + T(" buf=") + String (bufferSizeSamples));
  209355. pDirectSound = 0;
  209356. pDirectSoundCapture = 0;
  209357. pInputBuffer = 0;
  209358. readOffset = 0;
  209359. totalBytesPerBuffer = 0;
  209360. String error;
  209361. HRESULT hr = E_NOINTERFACE;
  209362. if (dsDirectSoundCaptureCreate != 0)
  209363. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  209364. logError (hr);
  209365. if (hr == S_OK)
  209366. {
  209367. const int numChannels = 2;
  209368. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  209369. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  209370. WAVEFORMATEX wfFormat;
  209371. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  209372. wfFormat.nChannels = (unsigned short)numChannels;
  209373. wfFormat.nSamplesPerSec = sampleRate;
  209374. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  209375. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  209376. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  209377. wfFormat.cbSize = 0;
  209378. DSCBUFFERDESC captureDesc;
  209379. zerostruct (captureDesc);
  209380. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  209381. captureDesc.dwFlags = 0;
  209382. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  209383. captureDesc.lpwfxFormat = &wfFormat;
  209384. log (T("opening dsound in step 2"));
  209385. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  209386. logError (hr);
  209387. if (hr == S_OK)
  209388. {
  209389. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  209390. logError (hr);
  209391. if (hr == S_OK)
  209392. return String::empty;
  209393. }
  209394. }
  209395. error = getDSErrorMessage (hr);
  209396. close();
  209397. return error;
  209398. }
  209399. void synchronisePosition()
  209400. {
  209401. if (pInputBuffer != 0)
  209402. {
  209403. DWORD capturePos;
  209404. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  209405. }
  209406. }
  209407. bool service()
  209408. {
  209409. if (pInputBuffer == 0)
  209410. return true;
  209411. DWORD capturePos, readPos;
  209412. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  209413. logError (hr);
  209414. if (hr != S_OK)
  209415. return true;
  209416. int bytesFilled = readPos - readOffset;
  209417. if (bytesFilled < 0)
  209418. bytesFilled += totalBytesPerBuffer;
  209419. if (bytesFilled >= bytesPerBuffer)
  209420. {
  209421. LPBYTE lpbuf1 = 0;
  209422. LPBYTE lpbuf2 = 0;
  209423. DWORD dwsize1 = 0;
  209424. DWORD dwsize2 = 0;
  209425. HRESULT hr = pInputBuffer->Lock (readOffset,
  209426. bytesPerBuffer,
  209427. (void**) &lpbuf1, &dwsize1,
  209428. (void**) &lpbuf2, &dwsize2, 0);
  209429. if (hr == S_OK)
  209430. {
  209431. if (bitDepth == 16)
  209432. {
  209433. const float g = 1.0f / 32768.0f;
  209434. float* destL = leftBuffer;
  209435. float* destR = rightBuffer;
  209436. int samples1 = dwsize1 >> 2;
  209437. int samples2 = dwsize2 >> 2;
  209438. const short* src = (const short*)lpbuf1;
  209439. if (destL == 0)
  209440. {
  209441. while (--samples1 >= 0)
  209442. {
  209443. ++src;
  209444. *destR++ = *src++ * g;
  209445. }
  209446. src = (const short*)lpbuf2;
  209447. while (--samples2 >= 0)
  209448. {
  209449. ++src;
  209450. *destR++ = *src++ * g;
  209451. }
  209452. }
  209453. else if (destR == 0)
  209454. {
  209455. while (--samples1 >= 0)
  209456. {
  209457. *destL++ = *src++ * g;
  209458. ++src;
  209459. }
  209460. src = (const short*)lpbuf2;
  209461. while (--samples2 >= 0)
  209462. {
  209463. *destL++ = *src++ * g;
  209464. ++src;
  209465. }
  209466. }
  209467. else
  209468. {
  209469. while (--samples1 >= 0)
  209470. {
  209471. *destL++ = *src++ * g;
  209472. *destR++ = *src++ * g;
  209473. }
  209474. src = (const short*)lpbuf2;
  209475. while (--samples2 >= 0)
  209476. {
  209477. *destL++ = *src++ * g;
  209478. *destR++ = *src++ * g;
  209479. }
  209480. }
  209481. }
  209482. else
  209483. {
  209484. jassertfalse
  209485. }
  209486. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  209487. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  209488. }
  209489. else
  209490. {
  209491. logError (hr);
  209492. jassertfalse
  209493. }
  209494. bytesFilled -= bytesPerBuffer;
  209495. return true;
  209496. }
  209497. else
  209498. {
  209499. return false;
  209500. }
  209501. }
  209502. };
  209503. class DSoundAudioIODevice : public AudioIODevice,
  209504. public Thread
  209505. {
  209506. public:
  209507. DSoundAudioIODevice (const String& deviceName,
  209508. const int outputDeviceIndex_,
  209509. const int inputDeviceIndex_)
  209510. : AudioIODevice (deviceName, "DirectSound"),
  209511. Thread ("Juce DSound"),
  209512. isOpen_ (false),
  209513. isStarted (false),
  209514. outputDeviceIndex (outputDeviceIndex_),
  209515. inputDeviceIndex (inputDeviceIndex_),
  209516. inChans (4),
  209517. outChans (4),
  209518. numInputBuffers (0),
  209519. numOutputBuffers (0),
  209520. totalSamplesOut (0),
  209521. sampleRate (0.0),
  209522. inputBuffers (0),
  209523. outputBuffers (0),
  209524. callback (0),
  209525. bufferSizeSamples (0)
  209526. {
  209527. if (outputDeviceIndex_ >= 0)
  209528. {
  209529. outChannels.add (TRANS("Left"));
  209530. outChannels.add (TRANS("Right"));
  209531. }
  209532. if (inputDeviceIndex_ >= 0)
  209533. {
  209534. inChannels.add (TRANS("Left"));
  209535. inChannels.add (TRANS("Right"));
  209536. }
  209537. }
  209538. ~DSoundAudioIODevice()
  209539. {
  209540. close();
  209541. }
  209542. const StringArray getOutputChannelNames()
  209543. {
  209544. return outChannels;
  209545. }
  209546. const StringArray getInputChannelNames()
  209547. {
  209548. return inChannels;
  209549. }
  209550. int getNumSampleRates()
  209551. {
  209552. return 4;
  209553. }
  209554. double getSampleRate (int index)
  209555. {
  209556. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  209557. return samps [jlimit (0, 3, index)];
  209558. }
  209559. int getNumBufferSizesAvailable()
  209560. {
  209561. return 50;
  209562. }
  209563. int getBufferSizeSamples (int index)
  209564. {
  209565. int n = 64;
  209566. for (int i = 0; i < index; ++i)
  209567. n += (n < 512) ? 32
  209568. : ((n < 1024) ? 64
  209569. : ((n < 2048) ? 128 : 256));
  209570. return n;
  209571. }
  209572. int getDefaultBufferSize()
  209573. {
  209574. return 2560;
  209575. }
  209576. const String open (const BitArray& inputChannels,
  209577. const BitArray& outputChannels,
  209578. double sampleRate,
  209579. int bufferSizeSamples)
  209580. {
  209581. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  209582. isOpen_ = lastError.isEmpty();
  209583. return lastError;
  209584. }
  209585. void close()
  209586. {
  209587. stop();
  209588. if (isOpen_)
  209589. {
  209590. closeDevice();
  209591. isOpen_ = false;
  209592. }
  209593. }
  209594. bool isOpen()
  209595. {
  209596. return isOpen_ && isThreadRunning();
  209597. }
  209598. int getCurrentBufferSizeSamples()
  209599. {
  209600. return bufferSizeSamples;
  209601. }
  209602. double getCurrentSampleRate()
  209603. {
  209604. return sampleRate;
  209605. }
  209606. int getCurrentBitDepth()
  209607. {
  209608. int i, bits = 256;
  209609. for (i = inChans.size(); --i >= 0;)
  209610. bits = jmin (bits, inChans[i]->bitDepth);
  209611. for (i = outChans.size(); --i >= 0;)
  209612. bits = jmin (bits, outChans[i]->bitDepth);
  209613. if (bits > 32)
  209614. bits = 16;
  209615. return bits;
  209616. }
  209617. const BitArray getActiveOutputChannels() const
  209618. {
  209619. return enabledOutputs;
  209620. }
  209621. const BitArray getActiveInputChannels() const
  209622. {
  209623. return enabledInputs;
  209624. }
  209625. int getOutputLatencyInSamples()
  209626. {
  209627. return (int) (getCurrentBufferSizeSamples() * 1.5);
  209628. }
  209629. int getInputLatencyInSamples()
  209630. {
  209631. return getOutputLatencyInSamples();
  209632. }
  209633. void start (AudioIODeviceCallback* call)
  209634. {
  209635. if (isOpen_ && call != 0 && ! isStarted)
  209636. {
  209637. if (! isThreadRunning())
  209638. {
  209639. // something gone wrong and the thread's stopped..
  209640. isOpen_ = false;
  209641. return;
  209642. }
  209643. call->audioDeviceAboutToStart (this);
  209644. const ScopedLock sl (startStopLock);
  209645. callback = call;
  209646. isStarted = true;
  209647. }
  209648. }
  209649. void stop()
  209650. {
  209651. if (isStarted)
  209652. {
  209653. AudioIODeviceCallback* const callbackLocal = callback;
  209654. {
  209655. const ScopedLock sl (startStopLock);
  209656. isStarted = false;
  209657. }
  209658. if (callbackLocal != 0)
  209659. callbackLocal->audioDeviceStopped();
  209660. }
  209661. }
  209662. bool isPlaying()
  209663. {
  209664. return isStarted && isOpen_ && isThreadRunning();
  209665. }
  209666. const String getLastError()
  209667. {
  209668. return lastError;
  209669. }
  209670. juce_UseDebuggingNewOperator
  209671. StringArray inChannels, outChannels;
  209672. int outputDeviceIndex, inputDeviceIndex;
  209673. private:
  209674. bool isOpen_;
  209675. bool isStarted;
  209676. String lastError;
  209677. OwnedArray <DSoundInternalInChannel> inChans;
  209678. OwnedArray <DSoundInternalOutChannel> outChans;
  209679. WaitableEvent startEvent;
  209680. int numInputBuffers, numOutputBuffers, bufferSizeSamples;
  209681. int volatile totalSamplesOut;
  209682. int64 volatile lastBlockTime;
  209683. double sampleRate;
  209684. BitArray enabledInputs, enabledOutputs;
  209685. float** inputBuffers;
  209686. float** outputBuffers;
  209687. AudioIODeviceCallback* callback;
  209688. CriticalSection startStopLock;
  209689. DSoundAudioIODevice (const DSoundAudioIODevice&);
  209690. const DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  209691. const String openDevice (const BitArray& inputChannels,
  209692. const BitArray& outputChannels,
  209693. double sampleRate_,
  209694. int bufferSizeSamples_);
  209695. void closeDevice()
  209696. {
  209697. isStarted = false;
  209698. stopThread (5000);
  209699. inChans.clear();
  209700. outChans.clear();
  209701. int i;
  209702. for (i = 0; i < numInputBuffers; ++i)
  209703. juce_free (inputBuffers[i]);
  209704. delete[] inputBuffers;
  209705. inputBuffers = 0;
  209706. numInputBuffers = 0;
  209707. for (i = 0; i < numOutputBuffers; ++i)
  209708. juce_free (outputBuffers[i]);
  209709. delete[] outputBuffers;
  209710. outputBuffers = 0;
  209711. numOutputBuffers = 0;
  209712. }
  209713. void resync()
  209714. {
  209715. if (! threadShouldExit())
  209716. {
  209717. sleep (5);
  209718. int i;
  209719. for (i = 0; i < outChans.size(); ++i)
  209720. outChans.getUnchecked(i)->synchronisePosition();
  209721. for (i = 0; i < inChans.size(); ++i)
  209722. inChans.getUnchecked(i)->synchronisePosition();
  209723. }
  209724. }
  209725. public:
  209726. void run()
  209727. {
  209728. while (! threadShouldExit())
  209729. {
  209730. if (wait (100))
  209731. break;
  209732. }
  209733. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  209734. const int maxTimeMS = jmax (5, 3 * latencyMs);
  209735. while (! threadShouldExit())
  209736. {
  209737. int numToDo = 0;
  209738. uint32 startTime = Time::getMillisecondCounter();
  209739. int i;
  209740. for (i = inChans.size(); --i >= 0;)
  209741. {
  209742. inChans.getUnchecked(i)->doneFlag = false;
  209743. ++numToDo;
  209744. }
  209745. for (i = outChans.size(); --i >= 0;)
  209746. {
  209747. outChans.getUnchecked(i)->doneFlag = false;
  209748. ++numToDo;
  209749. }
  209750. if (numToDo > 0)
  209751. {
  209752. const int maxCount = 3;
  209753. int count = maxCount;
  209754. for (;;)
  209755. {
  209756. for (i = inChans.size(); --i >= 0;)
  209757. {
  209758. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  209759. if ((! in->doneFlag) && in->service())
  209760. {
  209761. in->doneFlag = true;
  209762. --numToDo;
  209763. }
  209764. }
  209765. for (i = outChans.size(); --i >= 0;)
  209766. {
  209767. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  209768. if ((! out->doneFlag) && out->service())
  209769. {
  209770. out->doneFlag = true;
  209771. --numToDo;
  209772. }
  209773. }
  209774. if (numToDo <= 0)
  209775. break;
  209776. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  209777. {
  209778. resync();
  209779. break;
  209780. }
  209781. if (--count <= 0)
  209782. {
  209783. Sleep (1);
  209784. count = maxCount;
  209785. }
  209786. if (threadShouldExit())
  209787. return;
  209788. }
  209789. }
  209790. else
  209791. {
  209792. sleep (1);
  209793. }
  209794. const ScopedLock sl (startStopLock);
  209795. if (isStarted)
  209796. {
  209797. JUCE_TRY
  209798. {
  209799. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  209800. numInputBuffers,
  209801. outputBuffers,
  209802. numOutputBuffers,
  209803. bufferSizeSamples);
  209804. }
  209805. JUCE_CATCH_EXCEPTION
  209806. totalSamplesOut += bufferSizeSamples;
  209807. }
  209808. else
  209809. {
  209810. for (i = 0; i < numOutputBuffers; ++i)
  209811. if (outputBuffers[i] != 0)
  209812. zeromem (outputBuffers[i], bufferSizeSamples * sizeof (float));
  209813. totalSamplesOut = 0;
  209814. sleep (1);
  209815. }
  209816. }
  209817. }
  209818. };
  209819. class DSoundAudioIODeviceType : public AudioIODeviceType
  209820. {
  209821. public:
  209822. DSoundAudioIODeviceType()
  209823. : AudioIODeviceType (T("DirectSound")),
  209824. hasScanned (false)
  209825. {
  209826. initialiseDSoundFunctions();
  209827. }
  209828. ~DSoundAudioIODeviceType()
  209829. {
  209830. }
  209831. void scanForDevices()
  209832. {
  209833. hasScanned = true;
  209834. outputDeviceNames.clear();
  209835. outputGuids.clear();
  209836. inputDeviceNames.clear();
  209837. inputGuids.clear();
  209838. if (dsDirectSoundEnumerateW != 0)
  209839. {
  209840. dsDirectSoundEnumerateW (outputEnumProcW, this);
  209841. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  209842. }
  209843. }
  209844. const StringArray getDeviceNames (const bool wantInputNames) const
  209845. {
  209846. jassert (hasScanned); // need to call scanForDevices() before doing this
  209847. return wantInputNames ? inputDeviceNames
  209848. : outputDeviceNames;
  209849. }
  209850. int getDefaultDeviceIndex (const bool /*forInput*/) const
  209851. {
  209852. jassert (hasScanned); // need to call scanForDevices() before doing this
  209853. return 0;
  209854. }
  209855. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  209856. {
  209857. jassert (hasScanned); // need to call scanForDevices() before doing this
  209858. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  209859. if (d == 0)
  209860. return -1;
  209861. return asInput ? d->inputDeviceIndex
  209862. : d->outputDeviceIndex;
  209863. }
  209864. bool hasSeparateInputsAndOutputs() const { return true; }
  209865. AudioIODevice* createDevice (const String& outputDeviceName,
  209866. const String& inputDeviceName)
  209867. {
  209868. jassert (hasScanned); // need to call scanForDevices() before doing this
  209869. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  209870. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  209871. if (outputIndex >= 0 || inputIndex >= 0)
  209872. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  209873. : inputDeviceName,
  209874. outputIndex, inputIndex);
  209875. return 0;
  209876. }
  209877. juce_UseDebuggingNewOperator
  209878. StringArray outputDeviceNames;
  209879. OwnedArray <GUID> outputGuids;
  209880. StringArray inputDeviceNames;
  209881. OwnedArray <GUID> inputGuids;
  209882. private:
  209883. bool hasScanned;
  209884. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  209885. {
  209886. desc = desc.trim();
  209887. if (desc.isNotEmpty())
  209888. {
  209889. const String origDesc (desc);
  209890. int n = 2;
  209891. while (outputDeviceNames.contains (desc))
  209892. desc = origDesc + T(" (") + String (n++) + T(")");
  209893. outputDeviceNames.add (desc);
  209894. if (lpGUID != 0)
  209895. outputGuids.add (new GUID (*lpGUID));
  209896. else
  209897. outputGuids.add (0);
  209898. }
  209899. return TRUE;
  209900. }
  209901. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  209902. {
  209903. return ((DSoundAudioIODeviceType*) object)
  209904. ->outputEnumProc (lpGUID, String (description));
  209905. }
  209906. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  209907. {
  209908. return ((DSoundAudioIODeviceType*) object)
  209909. ->outputEnumProc (lpGUID, String (description));
  209910. }
  209911. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  209912. {
  209913. desc = desc.trim();
  209914. if (desc.isNotEmpty())
  209915. {
  209916. const String origDesc (desc);
  209917. int n = 2;
  209918. while (inputDeviceNames.contains (desc))
  209919. desc = origDesc + T(" (") + String (n++) + T(")");
  209920. inputDeviceNames.add (desc);
  209921. if (lpGUID != 0)
  209922. inputGuids.add (new GUID (*lpGUID));
  209923. else
  209924. inputGuids.add (0);
  209925. }
  209926. return TRUE;
  209927. }
  209928. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  209929. {
  209930. return ((DSoundAudioIODeviceType*) object)
  209931. ->inputEnumProc (lpGUID, String (description));
  209932. }
  209933. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  209934. {
  209935. return ((DSoundAudioIODeviceType*) object)
  209936. ->inputEnumProc (lpGUID, String (description));
  209937. }
  209938. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  209939. const DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  209940. };
  209941. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  209942. {
  209943. return new DSoundAudioIODeviceType();
  209944. }
  209945. const String DSoundAudioIODevice::openDevice (const BitArray& inputChannels,
  209946. const BitArray& outputChannels,
  209947. double sampleRate_,
  209948. int bufferSizeSamples_)
  209949. {
  209950. closeDevice();
  209951. totalSamplesOut = 0;
  209952. sampleRate = sampleRate_;
  209953. if (bufferSizeSamples_ <= 0)
  209954. bufferSizeSamples_ = 960; // use as a default size if none is set.
  209955. bufferSizeSamples = bufferSizeSamples_ & ~7;
  209956. DSoundAudioIODeviceType dlh;
  209957. dlh.scanForDevices();
  209958. enabledInputs = inputChannels;
  209959. enabledInputs.setRange (inChannels.size(),
  209960. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  209961. false);
  209962. numInputBuffers = enabledInputs.countNumberOfSetBits();
  209963. inputBuffers = new float* [numInputBuffers + 2];
  209964. zeromem (inputBuffers, sizeof (float*) * numInputBuffers + 2);
  209965. int i, numIns = 0;
  209966. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  209967. {
  209968. float* left = 0;
  209969. float* right = 0;
  209970. if (enabledInputs[i])
  209971. left = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  209972. if (enabledInputs[i + 1])
  209973. right = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  209974. if (left != 0 || right != 0)
  209975. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  209976. dlh.inputGuids [inputDeviceIndex],
  209977. (int) sampleRate, bufferSizeSamples,
  209978. left, right));
  209979. }
  209980. enabledOutputs = outputChannels;
  209981. enabledOutputs.setRange (outChannels.size(),
  209982. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  209983. false);
  209984. numOutputBuffers = enabledOutputs.countNumberOfSetBits();
  209985. outputBuffers = new float* [numOutputBuffers + 2];
  209986. zeromem (outputBuffers, sizeof (float*) * numOutputBuffers + 2);
  209987. int numOuts = 0;
  209988. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  209989. {
  209990. float* left = 0;
  209991. float* right = 0;
  209992. if (enabledOutputs[i])
  209993. left = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  209994. if (enabledOutputs[i + 1])
  209995. right = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  209996. if (left != 0 || right != 0)
  209997. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  209998. dlh.outputGuids [outputDeviceIndex],
  209999. (int) sampleRate, bufferSizeSamples,
  210000. left, right));
  210001. }
  210002. String error;
  210003. // boost our priority while opening the devices to try to get better sync between them
  210004. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  210005. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  210006. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  210007. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  210008. for (i = 0; i < outChans.size(); ++i)
  210009. {
  210010. error = outChans[i]->open();
  210011. if (error.isNotEmpty())
  210012. {
  210013. error = T("Error opening ") + dlh.outputDeviceNames[i]
  210014. + T(": \"") + error + T("\"");
  210015. break;
  210016. }
  210017. }
  210018. if (error.isEmpty())
  210019. {
  210020. for (i = 0; i < inChans.size(); ++i)
  210021. {
  210022. error = inChans[i]->open();
  210023. if (error.isNotEmpty())
  210024. {
  210025. error = T("Error opening ") + dlh.inputDeviceNames[i]
  210026. + T(": \"") + error + T("\"");
  210027. break;
  210028. }
  210029. }
  210030. }
  210031. if (error.isEmpty())
  210032. {
  210033. totalSamplesOut = 0;
  210034. for (i = 0; i < outChans.size(); ++i)
  210035. outChans.getUnchecked(i)->synchronisePosition();
  210036. for (i = 0; i < inChans.size(); ++i)
  210037. inChans.getUnchecked(i)->synchronisePosition();
  210038. startThread (9);
  210039. sleep (10);
  210040. notify();
  210041. }
  210042. else
  210043. {
  210044. log (error);
  210045. }
  210046. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  210047. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  210048. return error;
  210049. }
  210050. #undef log
  210051. #endif
  210052. /********* End of inlined file: juce_win32_DirectSound.cpp *********/
  210053. /********* Start of inlined file: juce_win32_CameraDevice.cpp *********/
  210054. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210055. // compiled on its own).
  210056. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  210057. class DShowCameraDeviceInteral : public ChangeBroadcaster
  210058. {
  210059. public:
  210060. DShowCameraDeviceInteral (CameraDevice* const owner_,
  210061. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  210062. const ComSmartPtr <IBaseFilter>& filter_,
  210063. int minWidth, int minHeight,
  210064. int maxWidth, int maxHeight)
  210065. : owner (owner_),
  210066. captureGraphBuilder (captureGraphBuilder_),
  210067. filter (filter_),
  210068. ok (false),
  210069. imageNeedsFlipping (false),
  210070. width (0),
  210071. height (0),
  210072. activeUsers (0),
  210073. recordNextFrameTime (false)
  210074. {
  210075. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph, CLSCTX_INPROC);
  210076. if (FAILED (hr))
  210077. return;
  210078. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  210079. if (FAILED (hr))
  210080. return;
  210081. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  210082. if (FAILED (hr))
  210083. return;
  210084. {
  210085. ComSmartPtr <IAMStreamConfig> streamConfig;
  210086. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE,
  210087. 0,
  210088. filter,
  210089. IID_IAMStreamConfig,
  210090. (void**) &streamConfig);
  210091. if (streamConfig != 0)
  210092. {
  210093. getVideoSizes (streamConfig);
  210094. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  210095. return;
  210096. }
  210097. }
  210098. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  210099. if (FAILED (hr))
  210100. return;
  210101. hr = smartTee.CoCreateInstance (CLSID_SmartTee, CLSCTX_INPROC_SERVER);
  210102. if (FAILED (hr))
  210103. return;
  210104. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  210105. if (FAILED (hr))
  210106. return;
  210107. if (! connectFilters (filter, smartTee))
  210108. return;
  210109. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  210110. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber, CLSCTX_INPROC_SERVER);
  210111. if (FAILED (hr))
  210112. return;
  210113. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  210114. if (FAILED (hr))
  210115. return;
  210116. AM_MEDIA_TYPE mt;
  210117. zerostruct (mt);
  210118. mt.majortype = MEDIATYPE_Video;
  210119. mt.subtype = MEDIASUBTYPE_RGB24;
  210120. mt.formattype = FORMAT_VideoInfo;
  210121. sampleGrabber->SetMediaType (&mt);
  210122. callback = new GrabberCallback (*this);
  210123. sampleGrabber->SetCallback (callback, 1);
  210124. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  210125. if (FAILED (hr))
  210126. return;
  210127. ComSmartPtr <IPin> grabberInputPin;
  210128. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  210129. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  210130. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  210131. return;
  210132. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  210133. if (FAILED (hr))
  210134. return;
  210135. zerostruct (mt);
  210136. hr = sampleGrabber->GetConnectedMediaType (&mt);
  210137. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  210138. width = pVih->bmiHeader.biWidth;
  210139. height = pVih->bmiHeader.biHeight;
  210140. ComSmartPtr <IBaseFilter> nullFilter;
  210141. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer, CLSCTX_INPROC_SERVER);
  210142. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  210143. if (connectFilters (sampleGrabberBase, nullFilter)
  210144. && addGraphToRot())
  210145. {
  210146. activeImage = new Image (Image::RGB, width, height, true);
  210147. loadingImage = new Image (Image::RGB, width, height, true);
  210148. ok = true;
  210149. }
  210150. }
  210151. ~DShowCameraDeviceInteral()
  210152. {
  210153. mediaControl->Stop();
  210154. removeGraphFromRot();
  210155. for (int i = viewerComps.size(); --i >= 0;)
  210156. ((DShowCaptureViewerComp*) viewerComps.getUnchecked(i))->ownerDeleted();
  210157. callback = 0;
  210158. graphBuilder = 0;
  210159. sampleGrabber = 0;
  210160. mediaControl = 0;
  210161. filter = 0;
  210162. captureGraphBuilder = 0;
  210163. smartTee = 0;
  210164. smartTeePreviewOutputPin = 0;
  210165. smartTeeCaptureOutputPin = 0;
  210166. mux = 0;
  210167. fileWriter = 0;
  210168. delete activeImage;
  210169. delete loadingImage;
  210170. }
  210171. void addUser()
  210172. {
  210173. if (ok && activeUsers++ == 0)
  210174. mediaControl->Run();
  210175. }
  210176. void removeUser()
  210177. {
  210178. if (ok && --activeUsers == 0)
  210179. mediaControl->Stop();
  210180. }
  210181. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  210182. {
  210183. if (recordNextFrameTime)
  210184. {
  210185. firstRecordedTime = Time::getCurrentTime();
  210186. recordNextFrameTime = false;
  210187. }
  210188. imageSwapLock.enter();
  210189. int ls, ps;
  210190. const int lineStride = width * 3;
  210191. uint8* const dest = loadingImage->lockPixelDataReadWrite (0, 0, width, height, ls, ps);
  210192. for (int i = 0; i < height; ++i)
  210193. memcpy (dest + ls * ((height - 1) - i),
  210194. buffer + lineStride * i,
  210195. lineStride);
  210196. loadingImage->releasePixelDataReadWrite (dest);
  210197. imageNeedsFlipping = true;
  210198. imageSwapLock.exit();
  210199. callListeners (*loadingImage);
  210200. sendChangeMessage (this);
  210201. }
  210202. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  210203. {
  210204. if (imageNeedsFlipping)
  210205. {
  210206. imageSwapLock.enter();
  210207. swapVariables (loadingImage, activeImage);
  210208. imageNeedsFlipping = false;
  210209. imageSwapLock.exit();
  210210. }
  210211. RectanglePlacement rp (RectanglePlacement::centred);
  210212. double dx = 0, dy = 0, dw = width, dh = height;
  210213. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  210214. const int rx = roundDoubleToInt (dx), ry = roundDoubleToInt (dy);
  210215. const int rw = roundDoubleToInt (dw), rh = roundDoubleToInt (dh);
  210216. g.saveState();
  210217. g.excludeClipRegion (rx, ry, rw, rh);
  210218. g.fillAll (Colours::black);
  210219. g.restoreState();
  210220. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  210221. }
  210222. bool createFileCaptureFilter (const File& file)
  210223. {
  210224. removeFileCaptureFilter();
  210225. file.deleteFile();
  210226. mediaControl->Stop();
  210227. firstRecordedTime = Time();
  210228. recordNextFrameTime = true;
  210229. HRESULT hr = mux.CoCreateInstance (CLSID_AviDest, CLSCTX_INPROC_SERVER);
  210230. if (SUCCEEDED (hr))
  210231. {
  210232. hr = graphBuilder->AddFilter (mux, _T("AVI Mux"));
  210233. if (SUCCEEDED (hr))
  210234. {
  210235. fileWriter.CoCreateInstance (CLSID_FileWriter, CLSCTX_INPROC_SERVER);
  210236. if (SUCCEEDED (hr))
  210237. {
  210238. ComSmartPtr <IFileSinkFilter> fileSink;
  210239. hr = fileWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  210240. if (SUCCEEDED (hr))
  210241. {
  210242. AM_MEDIA_TYPE mt;
  210243. zerostruct (mt);
  210244. mt.majortype = MEDIATYPE_Stream;
  210245. mt.subtype = MEDIASUBTYPE_Avi;
  210246. mt.formattype = FORMAT_VideoInfo;
  210247. hr = fileSink->SetFileName (file.getFullPathName(), &mt);
  210248. if (SUCCEEDED (hr))
  210249. {
  210250. hr = graphBuilder->AddFilter (fileWriter, _T("File Writer"));
  210251. if (SUCCEEDED (hr))
  210252. {
  210253. ComSmartPtr <IPin> muxInputPin, muxOutputPin, writerInput;
  210254. if (getPin (mux, PINDIR_INPUT, &muxInputPin)
  210255. && getPin (mux, PINDIR_OUTPUT, &muxOutputPin)
  210256. && getPin (fileWriter, PINDIR_INPUT, &writerInput))
  210257. {
  210258. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, muxInputPin);
  210259. if (SUCCEEDED (hr))
  210260. {
  210261. hr = graphBuilder->Connect (muxOutputPin, writerInput);
  210262. if (SUCCEEDED (hr))
  210263. {
  210264. if (ok && activeUsers > 0)
  210265. mediaControl->Run();
  210266. return true;
  210267. }
  210268. }
  210269. }
  210270. }
  210271. }
  210272. }
  210273. }
  210274. }
  210275. }
  210276. removeFileCaptureFilter();
  210277. if (ok && activeUsers > 0)
  210278. mediaControl->Run();
  210279. return false;
  210280. }
  210281. void removeFileCaptureFilter()
  210282. {
  210283. mediaControl->Stop();
  210284. if (mux != 0)
  210285. {
  210286. graphBuilder->RemoveFilter (mux);
  210287. mux = 0;
  210288. }
  210289. if (fileWriter != 0)
  210290. {
  210291. graphBuilder->RemoveFilter (fileWriter);
  210292. fileWriter = 0;
  210293. }
  210294. if (ok && activeUsers > 0)
  210295. mediaControl->Run();
  210296. }
  210297. void addListener (CameraImageListener* listenerToAdd)
  210298. {
  210299. const ScopedLock sl (listenerLock);
  210300. if (listeners.size() == 0)
  210301. addUser();
  210302. listeners.addIfNotAlreadyThere (listenerToAdd);
  210303. }
  210304. void removeListener (CameraImageListener* listenerToRemove)
  210305. {
  210306. const ScopedLock sl (listenerLock);
  210307. listeners.removeValue (listenerToRemove);
  210308. if (listeners.size() == 0)
  210309. removeUser();
  210310. }
  210311. void callListeners (Image& image)
  210312. {
  210313. const ScopedLock sl (listenerLock);
  210314. for (int i = listeners.size(); --i >= 0;)
  210315. {
  210316. CameraImageListener* l = (CameraImageListener*) listeners[i];
  210317. if (l != 0)
  210318. l->imageReceived (image);
  210319. }
  210320. }
  210321. class DShowCaptureViewerComp : public Component,
  210322. public ChangeListener
  210323. {
  210324. public:
  210325. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  210326. : owner (owner_)
  210327. {
  210328. setOpaque (true);
  210329. owner->addChangeListener (this);
  210330. owner->addUser();
  210331. owner->viewerComps.add (this);
  210332. setSize (owner_->width, owner_->height);
  210333. }
  210334. ~DShowCaptureViewerComp()
  210335. {
  210336. if (owner != 0)
  210337. {
  210338. owner->viewerComps.removeValue (this);
  210339. owner->removeUser();
  210340. owner->removeChangeListener (this);
  210341. }
  210342. }
  210343. void ownerDeleted()
  210344. {
  210345. owner = 0;
  210346. }
  210347. void paint (Graphics& g)
  210348. {
  210349. g.setColour (Colours::black);
  210350. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  210351. if (owner != 0)
  210352. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  210353. else
  210354. g.fillAll (Colours::black);
  210355. }
  210356. void changeListenerCallback (void*)
  210357. {
  210358. repaint();
  210359. }
  210360. private:
  210361. DShowCameraDeviceInteral* owner;
  210362. };
  210363. bool ok;
  210364. int width, height;
  210365. Time firstRecordedTime;
  210366. VoidArray viewerComps;
  210367. private:
  210368. CameraDevice* const owner;
  210369. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  210370. ComSmartPtr <IBaseFilter> filter;
  210371. ComSmartPtr <IBaseFilter> smartTee;
  210372. ComSmartPtr <IGraphBuilder> graphBuilder;
  210373. ComSmartPtr <ISampleGrabber> sampleGrabber;
  210374. ComSmartPtr <IMediaControl> mediaControl;
  210375. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  210376. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  210377. ComSmartPtr <IBaseFilter> mux, fileWriter;
  210378. int activeUsers;
  210379. Array <int> widths, heights;
  210380. DWORD graphRegistrationID;
  210381. CriticalSection imageSwapLock;
  210382. bool imageNeedsFlipping;
  210383. Image* loadingImage;
  210384. Image* activeImage;
  210385. bool recordNextFrameTime;
  210386. void getVideoSizes (IAMStreamConfig* const streamConfig)
  210387. {
  210388. widths.clear();
  210389. heights.clear();
  210390. int count = 0, size = 0;
  210391. streamConfig->GetNumberOfCapabilities (&count, &size);
  210392. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  210393. {
  210394. for (int i = 0; i < count; ++i)
  210395. {
  210396. VIDEO_STREAM_CONFIG_CAPS scc;
  210397. AM_MEDIA_TYPE* config;
  210398. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  210399. if (SUCCEEDED (hr))
  210400. {
  210401. const int w = scc.InputSize.cx;
  210402. const int h = scc.InputSize.cy;
  210403. bool duplicate = false;
  210404. for (int j = widths.size(); --j >= 0;)
  210405. {
  210406. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  210407. {
  210408. duplicate = true;
  210409. break;
  210410. }
  210411. }
  210412. if (! duplicate)
  210413. {
  210414. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  210415. widths.add (w);
  210416. heights.add (h);
  210417. }
  210418. deleteMediaType (config);
  210419. }
  210420. }
  210421. }
  210422. }
  210423. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  210424. const int minWidth, const int minHeight,
  210425. const int maxWidth, const int maxHeight)
  210426. {
  210427. int count = 0, size = 0;
  210428. streamConfig->GetNumberOfCapabilities (&count, &size);
  210429. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  210430. {
  210431. for (int i = 0; i < count; ++i)
  210432. {
  210433. VIDEO_STREAM_CONFIG_CAPS scc;
  210434. AM_MEDIA_TYPE* config;
  210435. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  210436. if (SUCCEEDED (hr))
  210437. {
  210438. if (scc.InputSize.cx >= minWidth
  210439. && scc.InputSize.cy >= minHeight
  210440. && scc.InputSize.cx <= maxWidth
  210441. && scc.InputSize.cy <= maxHeight)
  210442. {
  210443. hr = streamConfig->SetFormat (config);
  210444. deleteMediaType (config);
  210445. return SUCCEEDED (hr);
  210446. }
  210447. deleteMediaType (config);
  210448. }
  210449. }
  210450. }
  210451. return false;
  210452. }
  210453. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  210454. {
  210455. ComSmartPtr <IEnumPins> enumerator;
  210456. ComSmartPtr <IPin> pin;
  210457. filter->EnumPins (&enumerator);
  210458. while (enumerator->Next (1, &pin, 0) == S_OK)
  210459. {
  210460. PIN_DIRECTION dir;
  210461. pin->QueryDirection (&dir);
  210462. if (wantedDirection == dir)
  210463. {
  210464. PIN_INFO info;
  210465. zerostruct (info);
  210466. pin->QueryPinInfo (&info);
  210467. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  210468. {
  210469. pin.p->AddRef();
  210470. *result = pin;
  210471. return true;
  210472. }
  210473. }
  210474. }
  210475. return false;
  210476. }
  210477. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  210478. {
  210479. ComSmartPtr <IPin> in, out;
  210480. return getPin (first, PINDIR_OUTPUT, &out)
  210481. && getPin (second, PINDIR_INPUT, &in)
  210482. && SUCCEEDED (graphBuilder->Connect (out, in));
  210483. }
  210484. bool addGraphToRot()
  210485. {
  210486. ComSmartPtr <IRunningObjectTable> rot;
  210487. if (FAILED (GetRunningObjectTable (0, &rot)))
  210488. return false;
  210489. ComSmartPtr <IMoniker> moniker;
  210490. WCHAR buffer[128];
  210491. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  210492. if (FAILED (hr))
  210493. return false;
  210494. graphRegistrationID = 0;
  210495. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  210496. }
  210497. void removeGraphFromRot()
  210498. {
  210499. ComSmartPtr <IRunningObjectTable> rot;
  210500. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  210501. rot->Revoke (graphRegistrationID);
  210502. }
  210503. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  210504. {
  210505. if (pmt->cbFormat != 0)
  210506. CoTaskMemFree ((PVOID) pmt->pbFormat);
  210507. if (pmt->pUnk != 0)
  210508. pmt->pUnk->Release();
  210509. CoTaskMemFree (pmt);
  210510. }
  210511. class GrabberCallback : public ISampleGrabberCB
  210512. {
  210513. public:
  210514. GrabberCallback (DShowCameraDeviceInteral& owner_)
  210515. : owner (owner_)
  210516. {
  210517. }
  210518. HRESULT __stdcall QueryInterface (REFIID id, void** result)
  210519. {
  210520. if (id == IID_IUnknown)
  210521. *result = dynamic_cast <IUnknown*> (this);
  210522. else if (id == IID_ISampleGrabberCB)
  210523. *result = dynamic_cast <ISampleGrabberCB*> (this);
  210524. else
  210525. {
  210526. *result = 0;
  210527. return E_NOINTERFACE;
  210528. }
  210529. AddRef();
  210530. return S_OK;
  210531. }
  210532. ULONG __stdcall AddRef() { return ++refCount; }
  210533. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  210534. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  210535. {
  210536. return E_FAIL;
  210537. }
  210538. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  210539. {
  210540. owner.handleFrame (time, buffer, bufferSize);
  210541. return S_OK;
  210542. }
  210543. private:
  210544. int refCount;
  210545. DShowCameraDeviceInteral& owner;
  210546. GrabberCallback (const GrabberCallback&);
  210547. const GrabberCallback& operator= (const GrabberCallback&);
  210548. };
  210549. ComSmartPtr <GrabberCallback> callback;
  210550. VoidArray listeners;
  210551. CriticalSection listenerLock;
  210552. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  210553. const DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  210554. };
  210555. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  210556. : name (name_)
  210557. {
  210558. isRecording = false;
  210559. }
  210560. CameraDevice::~CameraDevice()
  210561. {
  210562. stopRecording();
  210563. delete (DShowCameraDeviceInteral*) internal;
  210564. internal = 0;
  210565. }
  210566. Component* CameraDevice::createViewerComponent()
  210567. {
  210568. return new DShowCameraDeviceInteral::DShowCaptureViewerComp ((DShowCameraDeviceInteral*) internal);
  210569. }
  210570. const String CameraDevice::getFileExtension()
  210571. {
  210572. return ".avi";
  210573. }
  210574. void CameraDevice::startRecordingToFile (const File& file)
  210575. {
  210576. stopRecording();
  210577. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  210578. d->addUser();
  210579. isRecording = d->createFileCaptureFilter (file);
  210580. }
  210581. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  210582. {
  210583. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  210584. return d->firstRecordedTime;
  210585. }
  210586. void CameraDevice::stopRecording()
  210587. {
  210588. if (isRecording)
  210589. {
  210590. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  210591. d->removeFileCaptureFilter();
  210592. d->removeUser();
  210593. isRecording = false;
  210594. }
  210595. }
  210596. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  210597. {
  210598. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  210599. if (listenerToAdd != 0)
  210600. d->addListener (listenerToAdd);
  210601. }
  210602. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  210603. {
  210604. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  210605. if (listenerToRemove != 0)
  210606. d->removeListener (listenerToRemove);
  210607. }
  210608. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  210609. const int deviceIndexToOpen,
  210610. String& name)
  210611. {
  210612. int index = 0;
  210613. ComSmartPtr <IBaseFilter> result;
  210614. ComSmartPtr <ICreateDevEnum> pDevEnum;
  210615. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum, CLSCTX_INPROC);
  210616. if (SUCCEEDED (hr))
  210617. {
  210618. ComSmartPtr <IEnumMoniker> enumerator;
  210619. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  210620. if (SUCCEEDED (hr) && enumerator != 0)
  210621. {
  210622. ComSmartPtr <IBaseFilter> captureFilter;
  210623. ComSmartPtr <IMoniker> moniker;
  210624. ULONG fetched;
  210625. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  210626. {
  210627. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  210628. if (SUCCEEDED (hr))
  210629. {
  210630. ComSmartPtr <IPropertyBag> propertyBag;
  210631. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  210632. if (SUCCEEDED (hr))
  210633. {
  210634. VARIANT var;
  210635. var.vt = VT_BSTR;
  210636. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  210637. propertyBag = 0;
  210638. if (SUCCEEDED (hr))
  210639. {
  210640. if (names != 0)
  210641. names->add (var.bstrVal);
  210642. if (index == deviceIndexToOpen)
  210643. {
  210644. name = var.bstrVal;
  210645. result = captureFilter;
  210646. captureFilter = 0;
  210647. break;
  210648. }
  210649. ++index;
  210650. }
  210651. moniker = 0;
  210652. }
  210653. captureFilter = 0;
  210654. }
  210655. }
  210656. }
  210657. }
  210658. return result;
  210659. }
  210660. const StringArray CameraDevice::getAvailableDevices()
  210661. {
  210662. StringArray devs;
  210663. String dummy;
  210664. enumerateCameras (&devs, -1, dummy);
  210665. return devs;
  210666. }
  210667. CameraDevice* CameraDevice::openDevice (int index,
  210668. int minWidth, int minHeight,
  210669. int maxWidth, int maxHeight)
  210670. {
  210671. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  210672. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2, CLSCTX_INPROC);
  210673. if (SUCCEEDED (hr))
  210674. {
  210675. String name;
  210676. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  210677. if (filter != 0)
  210678. {
  210679. CameraDevice* const cam = new CameraDevice (name, index);
  210680. DShowCameraDeviceInteral* const intern
  210681. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  210682. minWidth, minHeight, maxWidth, maxHeight);
  210683. cam->internal = intern;
  210684. if (intern->ok)
  210685. return cam;
  210686. else
  210687. delete cam;
  210688. }
  210689. }
  210690. return 0;
  210691. }
  210692. #endif
  210693. /********* End of inlined file: juce_win32_CameraDevice.cpp *********/
  210694. #endif
  210695. // Auto-link the other win32 libs that are needed by library calls..
  210696. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  210697. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  210698. // Auto-links to various win32 libs that are needed by library calls..
  210699. #pragma comment(lib, "kernel32.lib")
  210700. #pragma comment(lib, "user32.lib")
  210701. #pragma comment(lib, "shell32.lib")
  210702. #pragma comment(lib, "gdi32.lib")
  210703. #pragma comment(lib, "vfw32.lib")
  210704. #pragma comment(lib, "comdlg32.lib")
  210705. #pragma comment(lib, "winmm.lib")
  210706. #pragma comment(lib, "wininet.lib")
  210707. #pragma comment(lib, "ole32.lib")
  210708. #pragma comment(lib, "advapi32.lib")
  210709. #pragma comment(lib, "ws2_32.lib")
  210710. #pragma comment(lib, "comsupp.lib")
  210711. #pragma comment(lib, "version.lib")
  210712. #if JUCE_OPENGL
  210713. #pragma comment(lib, "OpenGL32.Lib")
  210714. #pragma comment(lib, "GlU32.Lib")
  210715. #endif
  210716. #if JUCE_QUICKTIME
  210717. #pragma comment (lib, "QTMLClient.lib")
  210718. #endif
  210719. #if JUCE_USE_CAMERA
  210720. #pragma comment (lib, "Strmiids.lib")
  210721. #endif
  210722. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  210723. #endif
  210724. END_JUCE_NAMESPACE
  210725. /********* End of inlined file: juce_win32_NativeCode.cpp *********/
  210726. #endif
  210727. #if JUCE_LINUX
  210728. /********* Start of inlined file: juce_linux_NativeCode.cpp *********/
  210729. /*
  210730. This file wraps together all the mac-specific code, so that
  210731. we can include all the native headers just once, and compile all our
  210732. platform-specific stuff in one big lump, keeping it out of the way of
  210733. the rest of the codebase.
  210734. */
  210735. BEGIN_JUCE_NAMESPACE
  210736. /* Remove this macro if you're having problems compiling the cpu affinity
  210737. calls (the API for these has changed about quite a bit in various Linux
  210738. versions, and a lot of distros seem to ship with obsolete versions)
  210739. */
  210740. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  210741. #define SUPPORT_AFFINITIES 1
  210742. #endif
  210743. #define JUCE_INCLUDED_FILE 1
  210744. // Now include the actual code files..
  210745. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  210746. /*
  210747. This file contains posix routines that are common to both the Linux and Mac builds.
  210748. It gets included directly in the cpp files for these platforms.
  210749. */
  210750. CriticalSection::CriticalSection() throw()
  210751. {
  210752. pthread_mutexattr_t atts;
  210753. pthread_mutexattr_init (&atts);
  210754. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  210755. pthread_mutex_init (&internal, &atts);
  210756. }
  210757. CriticalSection::~CriticalSection() throw()
  210758. {
  210759. pthread_mutex_destroy (&internal);
  210760. }
  210761. void CriticalSection::enter() const throw()
  210762. {
  210763. pthread_mutex_lock (&internal);
  210764. }
  210765. bool CriticalSection::tryEnter() const throw()
  210766. {
  210767. return pthread_mutex_trylock (&internal) == 0;
  210768. }
  210769. void CriticalSection::exit() const throw()
  210770. {
  210771. pthread_mutex_unlock (&internal);
  210772. }
  210773. struct EventStruct
  210774. {
  210775. pthread_cond_t condition;
  210776. pthread_mutex_t mutex;
  210777. bool triggered;
  210778. };
  210779. WaitableEvent::WaitableEvent() throw()
  210780. {
  210781. EventStruct* const es = new EventStruct();
  210782. es->triggered = false;
  210783. pthread_cond_init (&es->condition, 0);
  210784. pthread_mutex_init (&es->mutex, 0);
  210785. internal = es;
  210786. }
  210787. WaitableEvent::~WaitableEvent() throw()
  210788. {
  210789. EventStruct* const es = (EventStruct*) internal;
  210790. pthread_cond_destroy (&es->condition);
  210791. pthread_mutex_destroy (&es->mutex);
  210792. delete es;
  210793. }
  210794. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  210795. {
  210796. EventStruct* const es = (EventStruct*) internal;
  210797. bool ok = true;
  210798. pthread_mutex_lock (&es->mutex);
  210799. if (timeOutMillisecs < 0)
  210800. {
  210801. while (! es->triggered)
  210802. pthread_cond_wait (&es->condition, &es->mutex);
  210803. }
  210804. else
  210805. {
  210806. while (! es->triggered)
  210807. {
  210808. struct timeval t;
  210809. gettimeofday (&t, 0);
  210810. struct timespec time;
  210811. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  210812. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  210813. if (time.tv_nsec >= 1000000000)
  210814. {
  210815. time.tv_nsec -= 1000000000;
  210816. time.tv_sec++;
  210817. }
  210818. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  210819. {
  210820. ok = false;
  210821. break;
  210822. }
  210823. }
  210824. }
  210825. es->triggered = false;
  210826. pthread_mutex_unlock (&es->mutex);
  210827. return ok;
  210828. }
  210829. void WaitableEvent::signal() const throw()
  210830. {
  210831. EventStruct* const es = (EventStruct*) internal;
  210832. pthread_mutex_lock (&es->mutex);
  210833. es->triggered = true;
  210834. pthread_cond_broadcast (&es->condition);
  210835. pthread_mutex_unlock (&es->mutex);
  210836. }
  210837. void WaitableEvent::reset() const throw()
  210838. {
  210839. EventStruct* const es = (EventStruct*) internal;
  210840. pthread_mutex_lock (&es->mutex);
  210841. es->triggered = false;
  210842. pthread_mutex_unlock (&es->mutex);
  210843. }
  210844. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  210845. {
  210846. struct timespec time;
  210847. time.tv_sec = millisecs / 1000;
  210848. time.tv_nsec = (millisecs % 1000) * 1000000;
  210849. nanosleep (&time, 0);
  210850. }
  210851. const tchar File::separator = T('/');
  210852. const tchar* File::separatorString = T("/");
  210853. bool juce_copyFile (const String& s, const String& d) throw();
  210854. static bool juce_stat (const String& fileName, struct stat& info) throw()
  210855. {
  210856. return fileName.isNotEmpty()
  210857. && (stat (fileName.toUTF8(), &info) == 0);
  210858. }
  210859. bool juce_isDirectory (const String& fileName) throw()
  210860. {
  210861. struct stat info;
  210862. return fileName.isEmpty()
  210863. || (juce_stat (fileName, info)
  210864. && ((info.st_mode & S_IFDIR) != 0));
  210865. }
  210866. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  210867. {
  210868. if (fileName.isEmpty())
  210869. return false;
  210870. const char* const fileNameUTF8 = fileName.toUTF8();
  210871. bool exists = access (fileNameUTF8, F_OK) == 0;
  210872. if (exists && dontCountDirectories)
  210873. {
  210874. struct stat info;
  210875. const int res = stat (fileNameUTF8, &info);
  210876. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  210877. exists = false;
  210878. }
  210879. return exists;
  210880. }
  210881. int64 juce_getFileSize (const String& fileName) throw()
  210882. {
  210883. struct stat info;
  210884. return juce_stat (fileName, info) ? info.st_size : 0;
  210885. }
  210886. bool juce_canWriteToFile (const String& fileName) throw()
  210887. {
  210888. return access (fileName.toUTF8(), W_OK) == 0;
  210889. }
  210890. bool juce_deleteFile (const String& fileName) throw()
  210891. {
  210892. if (juce_isDirectory (fileName))
  210893. return rmdir ((const char*) fileName.toUTF8()) == 0;
  210894. else
  210895. return remove ((const char*) fileName.toUTF8()) == 0;
  210896. }
  210897. bool juce_moveFile (const String& source, const String& dest) throw()
  210898. {
  210899. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  210900. return true;
  210901. if (juce_canWriteToFile (source)
  210902. && juce_copyFile (source, dest))
  210903. {
  210904. if (juce_deleteFile (source))
  210905. return true;
  210906. juce_deleteFile (dest);
  210907. }
  210908. return false;
  210909. }
  210910. void juce_createDirectory (const String& fileName) throw()
  210911. {
  210912. mkdir (fileName.toUTF8(), 0777);
  210913. }
  210914. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  210915. {
  210916. int flags = O_RDONLY;
  210917. if (forWriting)
  210918. {
  210919. if (juce_fileExists (fileName, false))
  210920. {
  210921. const int f = open ((const char*) fileName.toUTF8(), O_RDWR, 00644);
  210922. if (f != -1)
  210923. lseek (f, 0, SEEK_END);
  210924. return (void*) f;
  210925. }
  210926. else
  210927. {
  210928. flags = O_RDWR + O_CREAT;
  210929. }
  210930. }
  210931. return (void*) open ((const char*) fileName.toUTF8(), flags, 00644);
  210932. }
  210933. void juce_fileClose (void* handle) throw()
  210934. {
  210935. if (handle != 0)
  210936. close ((int) (pointer_sized_int) handle);
  210937. }
  210938. int juce_fileRead (void* handle, void* buffer, int size) throw()
  210939. {
  210940. if (handle != 0)
  210941. return read ((int) (pointer_sized_int) handle, buffer, size);
  210942. return 0;
  210943. }
  210944. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  210945. {
  210946. if (handle != 0)
  210947. return write ((int) (pointer_sized_int) handle, buffer, size);
  210948. return 0;
  210949. }
  210950. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  210951. {
  210952. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  210953. return pos;
  210954. return -1;
  210955. }
  210956. int64 juce_fileGetPosition (void* handle) throw()
  210957. {
  210958. if (handle != 0)
  210959. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  210960. else
  210961. return -1;
  210962. }
  210963. void juce_fileFlush (void* handle) throw()
  210964. {
  210965. if (handle != 0)
  210966. fsync ((int) (pointer_sized_int) handle);
  210967. }
  210968. const File juce_getExecutableFile()
  210969. {
  210970. Dl_info exeInfo;
  210971. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  210972. return File (exeInfo.dli_fname);
  210973. }
  210974. // if this file doesn't exist, find a parent of it that does..
  210975. static bool doStatFS (const File* file, struct statfs& result) throw()
  210976. {
  210977. File f (*file);
  210978. for (int i = 5; --i >= 0;)
  210979. {
  210980. if (f.exists())
  210981. break;
  210982. f = f.getParentDirectory();
  210983. }
  210984. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  210985. }
  210986. int64 File::getBytesFreeOnVolume() const throw()
  210987. {
  210988. struct statfs buf;
  210989. if (doStatFS (this, buf))
  210990. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  210991. return 0;
  210992. }
  210993. int64 File::getVolumeTotalSize() const throw()
  210994. {
  210995. struct statfs buf;
  210996. if (doStatFS (this, buf))
  210997. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  210998. return 0;
  210999. }
  211000. const String juce_getVolumeLabel (const String& filenameOnVolume,
  211001. int& volumeSerialNumber) throw()
  211002. {
  211003. volumeSerialNumber = 0;
  211004. #if JUCE_MAC
  211005. struct VolAttrBuf
  211006. {
  211007. u_int32_t length;
  211008. attrreference_t mountPointRef;
  211009. char mountPointSpace [MAXPATHLEN];
  211010. } attrBuf;
  211011. struct attrlist attrList;
  211012. zerostruct (attrList);
  211013. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  211014. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  211015. File f (filenameOnVolume);
  211016. for (;;)
  211017. {
  211018. if (getattrlist ((const char*) f.getFullPathName().toUTF8(),
  211019. &attrList, &attrBuf, sizeof(attrBuf), 0) == 0)
  211020. {
  211021. return String::fromUTF8 (((const uint8*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  211022. (int) attrBuf.mountPointRef.attr_length);
  211023. }
  211024. const File parent (f.getParentDirectory());
  211025. if (f == parent)
  211026. break;
  211027. f = parent;
  211028. }
  211029. #endif
  211030. return String::empty;
  211031. }
  211032. void juce_runSystemCommand (const String& command)
  211033. {
  211034. int result = system ((const char*) command.toUTF8());
  211035. (void) result;
  211036. }
  211037. const String juce_getOutputFromCommand (const String& command)
  211038. {
  211039. // slight bodge here, as we just pipe the output into a temp file and read it...
  211040. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  211041. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  211042. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  211043. String result (tempFile.loadFileAsString());
  211044. tempFile.deleteFile();
  211045. return result;
  211046. }
  211047. #if JUCE_64BIT
  211048. #define filedesc ((long long) internal)
  211049. #else
  211050. #define filedesc ((int) internal)
  211051. #endif
  211052. InterProcessLock::InterProcessLock (const String& name_) throw()
  211053. : internal (0),
  211054. name (name_),
  211055. reentrancyLevel (0)
  211056. {
  211057. #if JUCE_MAC
  211058. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  211059. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  211060. #else
  211061. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  211062. #endif
  211063. temp.create();
  211064. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  211065. }
  211066. InterProcessLock::~InterProcessLock() throw()
  211067. {
  211068. while (reentrancyLevel > 0)
  211069. this->exit();
  211070. close (filedesc);
  211071. }
  211072. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  211073. {
  211074. if (internal == 0)
  211075. return false;
  211076. if (reentrancyLevel != 0)
  211077. return true;
  211078. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  211079. struct flock fl;
  211080. zerostruct (fl);
  211081. fl.l_whence = SEEK_SET;
  211082. fl.l_type = F_WRLCK;
  211083. for (;;)
  211084. {
  211085. const int result = fcntl (filedesc, F_SETLK, &fl);
  211086. if (result >= 0)
  211087. {
  211088. ++reentrancyLevel;
  211089. return true;
  211090. }
  211091. if (errno != EINTR)
  211092. {
  211093. if (timeOutMillisecs == 0
  211094. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  211095. break;
  211096. Thread::sleep (10);
  211097. }
  211098. }
  211099. return false;
  211100. }
  211101. void InterProcessLock::exit() throw()
  211102. {
  211103. if (reentrancyLevel > 0 && internal != 0)
  211104. {
  211105. --reentrancyLevel;
  211106. struct flock fl;
  211107. zerostruct (fl);
  211108. fl.l_whence = SEEK_SET;
  211109. fl.l_type = F_UNLCK;
  211110. for (;;)
  211111. {
  211112. const int result = fcntl (filedesc, F_SETLKW, &fl);
  211113. if (result >= 0 || errno != EINTR)
  211114. break;
  211115. }
  211116. }
  211117. }
  211118. /********* End of inlined file: juce_posix_SharedCode.h *********/
  211119. /********* Start of inlined file: juce_linux_Files.cpp *********/
  211120. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  211121. // compiled on its own).
  211122. #ifdef JUCE_INCLUDED_FILE
  211123. #define U_ISOFS_SUPER_MAGIC (short) 0x9660 // linux/iso_fs.h
  211124. #define U_MSDOS_SUPER_MAGIC (short) 0x4d44 // linux/msdos_fs.h
  211125. #define U_NFS_SUPER_MAGIC (short) 0x6969 // linux/nfs_fs.h
  211126. #define U_SMB_SUPER_MAGIC (short) 0x517B // linux/smb_fs.h
  211127. void juce_getFileTimes (const String& fileName,
  211128. int64& modificationTime,
  211129. int64& accessTime,
  211130. int64& creationTime) throw()
  211131. {
  211132. modificationTime = 0;
  211133. accessTime = 0;
  211134. creationTime = 0;
  211135. struct stat info;
  211136. const int res = stat (fileName.toUTF8(), &info);
  211137. if (res == 0)
  211138. {
  211139. modificationTime = (int64) info.st_mtime * 1000;
  211140. accessTime = (int64) info.st_atime * 1000;
  211141. creationTime = (int64) info.st_ctime * 1000;
  211142. }
  211143. }
  211144. bool juce_setFileTimes (const String& fileName,
  211145. int64 modificationTime,
  211146. int64 accessTime,
  211147. int64 creationTime) throw()
  211148. {
  211149. struct utimbuf times;
  211150. times.actime = (time_t) (accessTime / 1000);
  211151. times.modtime = (time_t) (modificationTime / 1000);
  211152. return utime (fileName.toUTF8(), &times) == 0;
  211153. }
  211154. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  211155. {
  211156. struct stat info;
  211157. const int res = stat (fileName.toUTF8(), &info);
  211158. if (res != 0)
  211159. return false;
  211160. info.st_mode &= 0777; // Just permissions
  211161. if( isReadOnly )
  211162. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  211163. else
  211164. // Give everybody write permission?
  211165. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  211166. return chmod (fileName.toUTF8(), info.st_mode) == 0;
  211167. }
  211168. bool juce_copyFile (const String& s, const String& d) throw()
  211169. {
  211170. const File source (s), dest (d);
  211171. FileInputStream* in = source.createInputStream();
  211172. bool ok = false;
  211173. if (in != 0)
  211174. {
  211175. if (dest.deleteFile())
  211176. {
  211177. FileOutputStream* const out = dest.createOutputStream();
  211178. if (out != 0)
  211179. {
  211180. const int bytesCopied = out->writeFromInputStream (*in, -1);
  211181. delete out;
  211182. ok = (bytesCopied == source.getSize());
  211183. if (! ok)
  211184. dest.deleteFile();
  211185. }
  211186. }
  211187. delete in;
  211188. }
  211189. return ok;
  211190. }
  211191. const StringArray juce_getFileSystemRoots() throw()
  211192. {
  211193. StringArray s;
  211194. s.add (T("/"));
  211195. return s;
  211196. }
  211197. bool File::isOnCDRomDrive() const throw()
  211198. {
  211199. struct statfs buf;
  211200. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  211201. return (buf.f_type == U_ISOFS_SUPER_MAGIC);
  211202. // Assume not if this fails for some reason
  211203. return false;
  211204. }
  211205. bool File::isOnHardDisk() const throw()
  211206. {
  211207. struct statfs buf;
  211208. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  211209. {
  211210. switch (buf.f_type)
  211211. {
  211212. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  211213. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  211214. case U_NFS_SUPER_MAGIC: // Network NFS
  211215. case U_SMB_SUPER_MAGIC: // Network Samba
  211216. return false;
  211217. default:
  211218. // Assume anything else is a hard-disk (but note it could
  211219. // be a RAM disk. There isn't a good way of determining
  211220. // this for sure)
  211221. return true;
  211222. }
  211223. }
  211224. // Assume so if this fails for some reason
  211225. return true;
  211226. }
  211227. bool File::isOnRemovableDrive() const throw()
  211228. {
  211229. jassertfalse // xxx not implemented for linux!
  211230. return false;
  211231. }
  211232. bool File::isHidden() const throw()
  211233. {
  211234. return getFileName().startsWithChar (T('.'));
  211235. }
  211236. const File File::getSpecialLocation (const SpecialLocationType type)
  211237. {
  211238. switch (type)
  211239. {
  211240. case userHomeDirectory:
  211241. {
  211242. const char* homeDir = getenv ("HOME");
  211243. if (homeDir == 0)
  211244. {
  211245. struct passwd* const pw = getpwuid (getuid());
  211246. if (pw != 0)
  211247. homeDir = pw->pw_dir;
  211248. }
  211249. return File (String::fromUTF8 ((const uint8*) homeDir));
  211250. }
  211251. case userDocumentsDirectory:
  211252. case userMusicDirectory:
  211253. case userMoviesDirectory:
  211254. case userApplicationDataDirectory:
  211255. return File ("~");
  211256. case userDesktopDirectory:
  211257. return File ("~/Desktop");
  211258. case commonApplicationDataDirectory:
  211259. return File ("/var");
  211260. case globalApplicationsDirectory:
  211261. return File ("/usr");
  211262. case tempDirectory:
  211263. {
  211264. File tmp ("/var/tmp");
  211265. if (! tmp.isDirectory())
  211266. {
  211267. tmp = T("/tmp");
  211268. if (! tmp.isDirectory())
  211269. tmp = File::getCurrentWorkingDirectory();
  211270. }
  211271. return tmp;
  211272. }
  211273. case currentExecutableFile:
  211274. case currentApplicationFile:
  211275. return juce_getExecutableFile();
  211276. default:
  211277. jassertfalse // unknown type?
  211278. break;
  211279. }
  211280. return File::nonexistent;
  211281. }
  211282. const File File::getCurrentWorkingDirectory() throw()
  211283. {
  211284. char buf [2048];
  211285. return File (String::fromUTF8 ((const uint8*) getcwd (buf, sizeof (buf))));
  211286. }
  211287. bool File::setAsCurrentWorkingDirectory() const throw()
  211288. {
  211289. return chdir (getFullPathName().toUTF8()) == 0;
  211290. }
  211291. const String File::getVersion() const throw()
  211292. {
  211293. return String::empty; // xxx not yet implemented
  211294. }
  211295. const File File::getLinkedTarget() const throw()
  211296. {
  211297. char buffer [4096];
  211298. size_t numChars = readlink ((const char*) getFullPathName().toUTF8(),
  211299. buffer, sizeof (buffer));
  211300. if (numChars > 0 && numChars <= sizeof (buffer))
  211301. return File (String::fromUTF8 ((const uint8*) buffer, (int) numChars));
  211302. return *this;
  211303. }
  211304. bool File::moveToTrash() const throw()
  211305. {
  211306. if (! exists())
  211307. return true;
  211308. File trashCan (T("~/.Trash"));
  211309. if (! trashCan.isDirectory())
  211310. trashCan = T("~/.local/share/Trash/files");
  211311. if (! trashCan.isDirectory())
  211312. return false;
  211313. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  211314. getFileExtension()));
  211315. }
  211316. struct FindFileStruct
  211317. {
  211318. String parentDir, wildCard;
  211319. DIR* dir;
  211320. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  211321. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  211322. {
  211323. const char* const wildcardUTF8 = wildCard.toUTF8();
  211324. for (;;)
  211325. {
  211326. struct dirent* const de = readdir (dir);
  211327. if (de == 0)
  211328. break;
  211329. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  211330. {
  211331. result = String::fromUTF8 ((const uint8*) de->d_name);
  211332. const String path (parentDir + result);
  211333. if (isDir != 0 || fileSize != 0)
  211334. {
  211335. struct stat info;
  211336. const bool statOk = (stat (path.toUTF8(), &info) == 0);
  211337. if (isDir != 0)
  211338. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  211339. if (isHidden != 0)
  211340. *isHidden = (de->d_name[0] == '.');
  211341. if (fileSize != 0)
  211342. *fileSize = statOk ? info.st_size : 0;
  211343. }
  211344. if (modTime != 0 || creationTime != 0)
  211345. {
  211346. int64 m, a, c;
  211347. juce_getFileTimes (path, m, a, c);
  211348. if (modTime != 0)
  211349. *modTime = m;
  211350. if (creationTime != 0)
  211351. *creationTime = c;
  211352. }
  211353. if (isReadOnly != 0)
  211354. *isReadOnly = ! juce_canWriteToFile (path);
  211355. return true;
  211356. }
  211357. }
  211358. return false;
  211359. }
  211360. };
  211361. // returns 0 on failure
  211362. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  211363. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  211364. Time* creationTime, bool* isReadOnly) throw()
  211365. {
  211366. DIR* d = opendir (directory.toUTF8());
  211367. if (d != 0)
  211368. {
  211369. FindFileStruct* ff = new FindFileStruct();
  211370. ff->parentDir = directory;
  211371. if (!ff->parentDir.endsWithChar (File::separator))
  211372. ff->parentDir += File::separator;
  211373. ff->wildCard = wildCard;
  211374. if (wildCard == T("*.*"))
  211375. ff->wildCard = T("*");
  211376. ff->dir = d;
  211377. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  211378. {
  211379. return ff;
  211380. }
  211381. else
  211382. {
  211383. firstResultFile = String::empty;
  211384. isDir = false;
  211385. isHidden = false;
  211386. closedir (d);
  211387. delete ff;
  211388. }
  211389. }
  211390. return 0;
  211391. }
  211392. bool juce_findFileNext (void* handle, String& resultFile,
  211393. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  211394. {
  211395. FindFileStruct* const ff = (FindFileStruct*) handle;
  211396. if (ff != 0)
  211397. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  211398. return false;
  211399. }
  211400. void juce_findFileClose (void* handle) throw()
  211401. {
  211402. FindFileStruct* const ff = (FindFileStruct*) handle;
  211403. if (ff != 0)
  211404. {
  211405. closedir (ff->dir);
  211406. delete ff;
  211407. }
  211408. }
  211409. bool juce_launchFile (const String& fileName,
  211410. const String& parameters) throw()
  211411. {
  211412. String cmdString (fileName);
  211413. cmdString << " " << parameters;
  211414. if (URL::isProbablyAWebsiteURL (fileName)
  211415. || URL::isProbablyAnEmailAddress (fileName))
  211416. {
  211417. // create a command that tries to launch a bunch of likely browsers
  211418. const char* const browserNames[] = { "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  211419. StringArray cmdLines;
  211420. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  211421. cmdLines.add (String (browserNames[i]) + T(" ") + cmdString.trim().quoted());
  211422. cmdString = cmdLines.joinIntoString (T(" || "));
  211423. }
  211424. if (cmdString.startsWithIgnoreCase (T("file:")))
  211425. cmdString = cmdString.substring (5);
  211426. const char* const argv[4] = { "/bin/sh", "-c", (const char*) cmdString.toUTF8(), 0 };
  211427. const int cpid = fork();
  211428. if (cpid == 0)
  211429. {
  211430. setsid();
  211431. // Child process
  211432. execve (argv[0], (char**) argv, environ);
  211433. exit (0);
  211434. }
  211435. return cpid >= 0;
  211436. }
  211437. #endif
  211438. /********* End of inlined file: juce_linux_Files.cpp *********/
  211439. /********* Start of inlined file: juce_posix_NamedPipe.cpp *********/
  211440. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  211441. // compiled on its own).
  211442. #if JUCE_INCLUDED_FILE
  211443. struct NamedPipeInternal
  211444. {
  211445. String pipeInName, pipeOutName;
  211446. int pipeIn, pipeOut;
  211447. bool volatile createdPipe, blocked, stopReadOperation;
  211448. static void signalHandler (int) {}
  211449. };
  211450. void NamedPipe::cancelPendingReads()
  211451. {
  211452. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  211453. {
  211454. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  211455. intern->stopReadOperation = true;
  211456. char buffer [1] = { 0 };
  211457. int bytesWritten = ::write (intern->pipeIn, buffer, 1);
  211458. (void) bytesWritten;
  211459. int timeout = 2000;
  211460. while (intern->blocked && --timeout >= 0)
  211461. Thread::sleep (2);
  211462. intern->stopReadOperation = false;
  211463. }
  211464. }
  211465. void NamedPipe::close()
  211466. {
  211467. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  211468. if (intern != 0)
  211469. {
  211470. internal = 0;
  211471. if (intern->pipeIn != -1)
  211472. ::close (intern->pipeIn);
  211473. if (intern->pipeOut != -1)
  211474. ::close (intern->pipeOut);
  211475. if (intern->createdPipe)
  211476. {
  211477. unlink (intern->pipeInName);
  211478. unlink (intern->pipeOutName);
  211479. }
  211480. delete intern;
  211481. }
  211482. }
  211483. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  211484. {
  211485. close();
  211486. NamedPipeInternal* const intern = new NamedPipeInternal();
  211487. internal = intern;
  211488. intern->createdPipe = createPipe;
  211489. intern->blocked = false;
  211490. intern->stopReadOperation = false;
  211491. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  211492. siginterrupt (SIGPIPE, 1);
  211493. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  211494. intern->pipeInName = pipePath + T("_in");
  211495. intern->pipeOutName = pipePath + T("_out");
  211496. intern->pipeIn = -1;
  211497. intern->pipeOut = -1;
  211498. if (createPipe)
  211499. {
  211500. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  211501. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  211502. {
  211503. delete intern;
  211504. internal = 0;
  211505. return false;
  211506. }
  211507. }
  211508. return true;
  211509. }
  211510. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  211511. {
  211512. int bytesRead = -1;
  211513. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  211514. if (intern != 0)
  211515. {
  211516. intern->blocked = true;
  211517. if (intern->pipeIn == -1)
  211518. {
  211519. if (intern->createdPipe)
  211520. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  211521. else
  211522. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  211523. if (intern->pipeIn == -1)
  211524. {
  211525. intern->blocked = false;
  211526. return -1;
  211527. }
  211528. }
  211529. bytesRead = 0;
  211530. char* p = (char*) destBuffer;
  211531. while (bytesRead < maxBytesToRead)
  211532. {
  211533. const int bytesThisTime = maxBytesToRead - bytesRead;
  211534. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  211535. if (numRead <= 0 || intern->stopReadOperation)
  211536. {
  211537. bytesRead = -1;
  211538. break;
  211539. }
  211540. bytesRead += numRead;
  211541. p += bytesRead;
  211542. }
  211543. intern->blocked = false;
  211544. }
  211545. return bytesRead;
  211546. }
  211547. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  211548. {
  211549. int bytesWritten = -1;
  211550. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  211551. if (intern != 0)
  211552. {
  211553. if (intern->pipeOut == -1)
  211554. {
  211555. if (intern->createdPipe)
  211556. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  211557. else
  211558. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  211559. if (intern->pipeOut == -1)
  211560. {
  211561. return -1;
  211562. }
  211563. }
  211564. const char* p = (const char*) sourceBuffer;
  211565. bytesWritten = 0;
  211566. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  211567. while (bytesWritten < numBytesToWrite
  211568. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  211569. {
  211570. const int bytesThisTime = numBytesToWrite - bytesWritten;
  211571. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  211572. if (numWritten <= 0)
  211573. {
  211574. bytesWritten = -1;
  211575. break;
  211576. }
  211577. bytesWritten += numWritten;
  211578. p += bytesWritten;
  211579. }
  211580. }
  211581. return bytesWritten;
  211582. }
  211583. #endif
  211584. /********* End of inlined file: juce_posix_NamedPipe.cpp *********/
  211585. /********* Start of inlined file: juce_linux_Network.cpp *********/
  211586. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  211587. // compiled on its own).
  211588. #ifdef JUCE_INCLUDED_FILE
  211589. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  211590. {
  211591. int numResults = 0;
  211592. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  211593. if (s != -1)
  211594. {
  211595. char buf [1024];
  211596. struct ifconf ifc;
  211597. ifc.ifc_len = sizeof (buf);
  211598. ifc.ifc_buf = buf;
  211599. ioctl (s, SIOCGIFCONF, &ifc);
  211600. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  211601. {
  211602. struct ifreq ifr;
  211603. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  211604. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  211605. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  211606. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  211607. && numResults < maxNum)
  211608. {
  211609. int64 a = 0;
  211610. for (int j = 6; --j >= 0;)
  211611. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data[j];
  211612. *addresses++ = a;
  211613. ++numResults;
  211614. }
  211615. }
  211616. close (s);
  211617. }
  211618. return numResults;
  211619. }
  211620. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  211621. const String& emailSubject,
  211622. const String& bodyText,
  211623. const StringArray& filesToAttach)
  211624. {
  211625. jassertfalse // xxx todo
  211626. return false;
  211627. }
  211628. /** A HTTP input stream that uses sockets.
  211629. */
  211630. class JUCE_HTTPSocketStream
  211631. {
  211632. public:
  211633. JUCE_HTTPSocketStream()
  211634. : readPosition (0),
  211635. socketHandle (-1),
  211636. levelsOfRedirection (0),
  211637. timeoutSeconds (15)
  211638. {
  211639. }
  211640. ~JUCE_HTTPSocketStream()
  211641. {
  211642. closeSocket();
  211643. }
  211644. bool open (const String& url,
  211645. const String& headers,
  211646. const MemoryBlock& postData,
  211647. const bool isPost,
  211648. URL::OpenStreamProgressCallback* callback,
  211649. void* callbackContext,
  211650. int timeOutMs)
  211651. {
  211652. closeSocket();
  211653. uint32 timeOutTime = Time::getMillisecondCounter();
  211654. if (timeOutMs == 0)
  211655. timeOutTime += 60000;
  211656. else if (timeOutMs < 0)
  211657. timeOutTime = 0xffffffff;
  211658. else
  211659. timeOutTime += timeOutMs;
  211660. String hostName, hostPath;
  211661. int hostPort;
  211662. if (! decomposeURL (url, hostName, hostPath, hostPort))
  211663. return false;
  211664. const struct hostent* host = 0;
  211665. int port = 0;
  211666. String proxyName, proxyPath;
  211667. int proxyPort = 0;
  211668. String proxyURL (getenv ("http_proxy"));
  211669. if (proxyURL.startsWithIgnoreCase (T("http://")))
  211670. {
  211671. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  211672. return false;
  211673. host = gethostbyname ((const char*) proxyName.toUTF8());
  211674. port = proxyPort;
  211675. }
  211676. else
  211677. {
  211678. host = gethostbyname ((const char*) hostName.toUTF8());
  211679. port = hostPort;
  211680. }
  211681. if (host == 0)
  211682. return false;
  211683. struct sockaddr_in address;
  211684. zerostruct (address);
  211685. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  211686. address.sin_family = host->h_addrtype;
  211687. address.sin_port = htons (port);
  211688. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  211689. if (socketHandle == -1)
  211690. return false;
  211691. int receiveBufferSize = 16384;
  211692. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  211693. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  211694. #if JUCE_MAC
  211695. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  211696. #endif
  211697. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  211698. {
  211699. closeSocket();
  211700. return false;
  211701. }
  211702. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  211703. proxyName, proxyPort,
  211704. hostPath, url,
  211705. headers, postData,
  211706. isPost));
  211707. int totalHeaderSent = 0;
  211708. while (totalHeaderSent < requestHeader.getSize())
  211709. {
  211710. if (Time::getMillisecondCounter() > timeOutTime)
  211711. {
  211712. closeSocket();
  211713. return false;
  211714. }
  211715. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  211716. if (send (socketHandle,
  211717. ((const char*) requestHeader.getData()) + totalHeaderSent,
  211718. numToSend, 0)
  211719. != numToSend)
  211720. {
  211721. closeSocket();
  211722. return false;
  211723. }
  211724. totalHeaderSent += numToSend;
  211725. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  211726. {
  211727. closeSocket();
  211728. return false;
  211729. }
  211730. }
  211731. const String responseHeader (readResponse (timeOutTime));
  211732. if (responseHeader.isNotEmpty())
  211733. {
  211734. //DBG (responseHeader);
  211735. StringArray lines;
  211736. lines.addLines (responseHeader);
  211737. // NB - using charToString() here instead of just T(" "), because that was
  211738. // causing a mysterious gcc internal compiler error...
  211739. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  211740. .substring (0, 3).getIntValue();
  211741. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  211742. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  211743. String location (findHeaderItem (lines, T("Location:")));
  211744. if (statusCode >= 300 && statusCode < 400
  211745. && location.isNotEmpty())
  211746. {
  211747. if (! location.startsWithIgnoreCase (T("http://")))
  211748. location = T("http://") + location;
  211749. if (levelsOfRedirection++ < 3)
  211750. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  211751. }
  211752. else
  211753. {
  211754. levelsOfRedirection = 0;
  211755. return true;
  211756. }
  211757. }
  211758. closeSocket();
  211759. return false;
  211760. }
  211761. int read (void* buffer, int bytesToRead)
  211762. {
  211763. fd_set readbits;
  211764. FD_ZERO (&readbits);
  211765. FD_SET (socketHandle, &readbits);
  211766. struct timeval tv;
  211767. tv.tv_sec = timeoutSeconds;
  211768. tv.tv_usec = 0;
  211769. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  211770. return 0; // (timeout)
  211771. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  211772. readPosition += bytesRead;
  211773. return bytesRead;
  211774. }
  211775. int readPosition;
  211776. juce_UseDebuggingNewOperator
  211777. private:
  211778. int socketHandle, levelsOfRedirection;
  211779. const int timeoutSeconds;
  211780. void closeSocket()
  211781. {
  211782. if (socketHandle >= 0)
  211783. close (socketHandle);
  211784. socketHandle = -1;
  211785. }
  211786. const MemoryBlock createRequestHeader (const String& hostName,
  211787. const int hostPort,
  211788. const String& proxyName,
  211789. const int proxyPort,
  211790. const String& hostPath,
  211791. const String& originalURL,
  211792. const String& headers,
  211793. const MemoryBlock& postData,
  211794. const bool isPost)
  211795. {
  211796. String header (isPost ? "POST " : "GET ");
  211797. if (proxyName.isEmpty())
  211798. {
  211799. header << hostPath << " HTTP/1.0\r\nHost: "
  211800. << hostName << ':' << hostPort;
  211801. }
  211802. else
  211803. {
  211804. header << originalURL << " HTTP/1.0\r\nHost: "
  211805. << proxyName << ':' << proxyPort;
  211806. }
  211807. header << "\r\nUser-Agent: JUCE/"
  211808. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  211809. << "\r\nConnection: Close\r\nContent-Length: "
  211810. << postData.getSize() << "\r\n"
  211811. << headers << "\r\n";
  211812. MemoryBlock mb;
  211813. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  211814. mb.append (postData.getData(), postData.getSize());
  211815. return mb;
  211816. }
  211817. const String readResponse (const uint32 timeOutTime)
  211818. {
  211819. int bytesRead = 0, numConsecutiveLFs = 0;
  211820. MemoryBlock buffer (1024, true);
  211821. while (numConsecutiveLFs < 2 && bytesRead < 32768
  211822. && Time::getMillisecondCounter() <= timeOutTime)
  211823. {
  211824. fd_set readbits;
  211825. FD_ZERO (&readbits);
  211826. FD_SET (socketHandle, &readbits);
  211827. struct timeval tv;
  211828. tv.tv_sec = timeoutSeconds;
  211829. tv.tv_usec = 0;
  211830. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  211831. return String::empty; // (timeout)
  211832. buffer.ensureSize (bytesRead + 8, true);
  211833. char* const dest = (char*) buffer.getData() + bytesRead;
  211834. if (recv (socketHandle, dest, 1, 0) == -1)
  211835. return String::empty;
  211836. const char lastByte = *dest;
  211837. ++bytesRead;
  211838. if (lastByte == '\n')
  211839. ++numConsecutiveLFs;
  211840. else if (lastByte != '\r')
  211841. numConsecutiveLFs = 0;
  211842. }
  211843. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  211844. if (header.startsWithIgnoreCase (T("HTTP/")))
  211845. return header.trimEnd();
  211846. return String::empty;
  211847. }
  211848. static bool decomposeURL (const String& url,
  211849. String& host, String& path, int& port)
  211850. {
  211851. if (! url.startsWithIgnoreCase (T("http://")))
  211852. return false;
  211853. const int nextSlash = url.indexOfChar (7, '/');
  211854. int nextColon = url.indexOfChar (7, ':');
  211855. if (nextColon > nextSlash && nextSlash > 0)
  211856. nextColon = -1;
  211857. if (nextColon >= 0)
  211858. {
  211859. host = url.substring (7, nextColon);
  211860. if (nextSlash >= 0)
  211861. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  211862. else
  211863. port = url.substring (nextColon + 1).getIntValue();
  211864. }
  211865. else
  211866. {
  211867. port = 80;
  211868. if (nextSlash >= 0)
  211869. host = url.substring (7, nextSlash);
  211870. else
  211871. host = url.substring (7);
  211872. }
  211873. if (nextSlash >= 0)
  211874. path = url.substring (nextSlash);
  211875. else
  211876. path = T("/");
  211877. return true;
  211878. }
  211879. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  211880. {
  211881. for (int i = 0; i < lines.size(); ++i)
  211882. if (lines[i].startsWithIgnoreCase (itemName))
  211883. return lines[i].substring (itemName.length()).trim();
  211884. return String::empty;
  211885. }
  211886. };
  211887. bool juce_isOnLine()
  211888. {
  211889. return true;
  211890. }
  211891. void* juce_openInternetFile (const String& url,
  211892. const String& headers,
  211893. const MemoryBlock& postData,
  211894. const bool isPost,
  211895. URL::OpenStreamProgressCallback* callback,
  211896. void* callbackContext,
  211897. int timeOutMs)
  211898. {
  211899. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  211900. if (s->open (url, headers, postData, isPost,
  211901. callback, callbackContext, timeOutMs))
  211902. return s;
  211903. delete s;
  211904. return 0;
  211905. }
  211906. void juce_closeInternetFile (void* handle)
  211907. {
  211908. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  211909. if (s != 0)
  211910. delete s;
  211911. }
  211912. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  211913. {
  211914. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  211915. if (s != 0)
  211916. return s->read (buffer, bytesToRead);
  211917. return 0;
  211918. }
  211919. int64 juce_getInternetFileContentLength (void* handle)
  211920. {
  211921. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  211922. if (s != 0)
  211923. {
  211924. //xxx todo
  211925. jassertfalse
  211926. }
  211927. return -1;
  211928. }
  211929. int juce_seekInInternetFile (void* handle, int newPosition)
  211930. {
  211931. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  211932. if (s != 0)
  211933. return s->readPosition;
  211934. return 0;
  211935. }
  211936. #endif
  211937. /********* End of inlined file: juce_linux_Network.cpp *********/
  211938. /********* Start of inlined file: juce_linux_SystemStats.cpp *********/
  211939. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  211940. // compiled on its own).
  211941. #ifdef JUCE_INCLUDED_FILE
  211942. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel, int* extFeatures) throw()
  211943. {
  211944. unsigned int cpu = 0;
  211945. unsigned int ext = 0;
  211946. unsigned int family = 0;
  211947. unsigned int dummy = 0;
  211948. #if JUCE_64BIT
  211949. __asm__ ("cpuid"
  211950. : "=a" (family), "=b" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  211951. #else
  211952. __asm__ ("push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
  211953. : "=a" (family), "=D" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  211954. #endif
  211955. if (familyModel != 0)
  211956. *familyModel = family;
  211957. if (extFeatures != 0)
  211958. *extFeatures = ext;
  211959. return cpu;
  211960. }*/
  211961. void Logger::outputDebugString (const String& text) throw()
  211962. {
  211963. fputs (text.toUTF8(), stdout);
  211964. fputs ("\n", stdout);
  211965. }
  211966. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  211967. {
  211968. String text;
  211969. va_list args;
  211970. va_start (args, format);
  211971. text.vprintf(format, args);
  211972. outputDebugString(text);
  211973. }
  211974. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  211975. {
  211976. return Linux;
  211977. }
  211978. const String SystemStats::getOperatingSystemName() throw()
  211979. {
  211980. return T("Linux");
  211981. }
  211982. bool SystemStats::isOperatingSystem64Bit() throw()
  211983. {
  211984. #if JUCE_64BIT
  211985. return true;
  211986. #else
  211987. //xxx not sure how to find this out?..
  211988. return false;
  211989. #endif
  211990. }
  211991. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  211992. {
  211993. String info;
  211994. char buf [256];
  211995. FILE* f = fopen ("/proc/cpuinfo", "r");
  211996. while (f != 0 && fgets (buf, sizeof(buf), f))
  211997. {
  211998. if (strncmp (buf, key, strlen (key)) == 0)
  211999. {
  212000. char* p = buf;
  212001. while (*p && *p != '\n')
  212002. ++p;
  212003. if (*p != 0)
  212004. *p = 0;
  212005. p = buf;
  212006. while (*p != 0 && *p != ':')
  212007. ++p;
  212008. if (*p != 0 && *(p + 1) != 0)
  212009. info = p + 2;
  212010. if (! lastOne)
  212011. break;
  212012. }
  212013. }
  212014. fclose (f);
  212015. return info;
  212016. }
  212017. bool SystemStats::hasMMX() throw()
  212018. {
  212019. return getCpuInfo ("flags").contains (T("mmx"));
  212020. }
  212021. bool SystemStats::hasSSE() throw()
  212022. {
  212023. return getCpuInfo ("flags").contains (T("sse"));
  212024. }
  212025. bool SystemStats::hasSSE2() throw()
  212026. {
  212027. return getCpuInfo ("flags").contains (T("sse2"));
  212028. }
  212029. bool SystemStats::has3DNow() throw()
  212030. {
  212031. return getCpuInfo ("flags").contains (T("3dnow"));
  212032. }
  212033. const String SystemStats::getCpuVendor() throw()
  212034. {
  212035. return getCpuInfo ("vendor_id");
  212036. }
  212037. int SystemStats::getCpuSpeedInMegaherz() throw()
  212038. {
  212039. const String speed (getCpuInfo ("cpu MHz"));
  212040. return (int) (speed.getFloatValue() + 0.5f);
  212041. }
  212042. int SystemStats::getMemorySizeInMegabytes() throw()
  212043. {
  212044. struct sysinfo sysi;
  212045. if (sysinfo (&sysi) == 0)
  212046. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  212047. return 0;
  212048. }
  212049. uint32 juce_millisecondsSinceStartup() throw()
  212050. {
  212051. static unsigned int calibrate = 0;
  212052. static bool calibrated = false;
  212053. timeval t;
  212054. unsigned int ret = 0;
  212055. if (! gettimeofday (&t, 0))
  212056. {
  212057. if (! calibrated)
  212058. {
  212059. struct sysinfo sysi;
  212060. if (sysinfo (&sysi) == 0)
  212061. // Safe to assume system was not brought up earlier than 1970!
  212062. calibrate = t.tv_sec - sysi.uptime;
  212063. calibrated = true;
  212064. }
  212065. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  212066. }
  212067. return ret;
  212068. }
  212069. double Time::getMillisecondCounterHiRes() throw()
  212070. {
  212071. return getHighResolutionTicks() * 0.001;
  212072. }
  212073. int64 Time::getHighResolutionTicks() throw()
  212074. {
  212075. timeval t;
  212076. if (gettimeofday (&t, 0))
  212077. return 0;
  212078. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  212079. }
  212080. int64 Time::getHighResolutionTicksPerSecond() throw()
  212081. {
  212082. // Microseconds
  212083. return 1000000;
  212084. }
  212085. bool Time::setSystemTimeToThisTime() const throw()
  212086. {
  212087. timeval t;
  212088. t.tv_sec = millisSinceEpoch % 1000000;
  212089. t.tv_usec = millisSinceEpoch - t.tv_sec;
  212090. return settimeofday (&t, NULL) ? false : true;
  212091. }
  212092. int SystemStats::getPageSize() throw()
  212093. {
  212094. static int systemPageSize = 0;
  212095. if (systemPageSize == 0)
  212096. systemPageSize = sysconf (_SC_PAGESIZE);
  212097. return systemPageSize;
  212098. }
  212099. int SystemStats::getNumCpus() throw()
  212100. {
  212101. const int lastCpu = getCpuInfo ("processor", true).getIntValue();
  212102. return lastCpu + 1;
  212103. }
  212104. void SystemStats::initialiseStats() throw()
  212105. {
  212106. // Process starts off as root when running suid
  212107. Process::lowerPrivilege();
  212108. String s (SystemStats::getJUCEVersion());
  212109. }
  212110. void PlatformUtilities::fpuReset()
  212111. {
  212112. }
  212113. #endif
  212114. /********* End of inlined file: juce_linux_SystemStats.cpp *********/
  212115. /********* Start of inlined file: juce_linux_Threads.cpp *********/
  212116. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  212117. // compiled on its own).
  212118. #ifdef JUCE_INCLUDED_FILE
  212119. /*
  212120. Note that a lot of methods that you'd expect to find in this file actually
  212121. live in juce_posix_SharedCode.h!
  212122. */
  212123. void JUCE_API juce_threadEntryPoint (void*);
  212124. void* threadEntryProc (void* value) throw()
  212125. {
  212126. // New threads start off as root when running suid
  212127. Process::lowerPrivilege();
  212128. juce_threadEntryPoint (value);
  212129. return 0;
  212130. }
  212131. void* juce_createThread (void* userData) throw()
  212132. {
  212133. pthread_t handle = 0;
  212134. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  212135. {
  212136. pthread_detach (handle);
  212137. return (void*)handle;
  212138. }
  212139. return 0;
  212140. }
  212141. void juce_killThread (void* handle) throw()
  212142. {
  212143. if (handle != 0)
  212144. pthread_cancel ((pthread_t)handle);
  212145. }
  212146. void juce_setCurrentThreadName (const String& /*name*/) throw()
  212147. {
  212148. }
  212149. Thread::ThreadID Thread::getCurrentThreadId() throw()
  212150. {
  212151. return (ThreadID) pthread_self();
  212152. }
  212153. /*
  212154. * This is all a bit non-ideal... the trouble is that on Linux you
  212155. * need to call setpriority to affect the dynamic priority for
  212156. * non-realtime processes, but this requires the pid, which is not
  212157. * accessible from the pthread_t. We could get it by calling getpid
  212158. * once each thread has started, but then we would need a list of
  212159. * running threads etc etc.
  212160. * Also there is no such thing as IDLE priority on Linux.
  212161. * For the moment, map idle, low and normal process priorities to
  212162. * SCHED_OTHER, with the thread priority ignored for these classes.
  212163. * Map high priority processes to the lower half of the SCHED_RR
  212164. * range, and realtime to the upper half
  212165. */
  212166. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  212167. // priority of the current thread
  212168. bool juce_setThreadPriority (void* handle, int priority) throw()
  212169. {
  212170. struct sched_param param;
  212171. int policy, maxp, minp, pri;
  212172. if (handle == 0)
  212173. handle = (void*) pthread_self();
  212174. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  212175. && policy != SCHED_OTHER)
  212176. {
  212177. minp = sched_get_priority_min(policy);
  212178. maxp = sched_get_priority_max(policy);
  212179. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  212180. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  212181. // Realtime process priority
  212182. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  212183. else
  212184. // High process priority
  212185. param.__sched_priority = minp + pri;
  212186. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  212187. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  212188. }
  212189. return false;
  212190. }
  212191. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  212192. {
  212193. #if SUPPORT_AFFINITIES
  212194. cpu_set_t affinity;
  212195. CPU_ZERO (&affinity);
  212196. for (int i = 0; i < 32; ++i)
  212197. if ((affinityMask & (1 << i)) != 0)
  212198. CPU_SET (i, &affinity);
  212199. /*
  212200. N.B. If this line causes a compile error, then you've probably not got the latest
  212201. version of glibc installed.
  212202. If you don't want to update your copy of glibc and don't care about cpu affinities,
  212203. then you can just disable all this stuff by removing the SUPPORT_AFFINITIES macro
  212204. from the linuxincludes.h file.
  212205. */
  212206. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  212207. sched_yield();
  212208. #else
  212209. /* affinities aren't supported because either the appropriate header files weren't found,
  212210. or the SUPPORT_AFFINITIES macro was turned off in linuxheaders.h
  212211. */
  212212. jassertfalse
  212213. #endif
  212214. }
  212215. void Thread::yield() throw()
  212216. {
  212217. sched_yield();
  212218. }
  212219. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  212220. void Process::setPriority (ProcessPriority prior)
  212221. {
  212222. struct sched_param param;
  212223. int policy, maxp, minp;
  212224. const int p = (int) prior;
  212225. if (p <= 1)
  212226. policy = SCHED_OTHER;
  212227. else
  212228. policy = SCHED_RR;
  212229. minp = sched_get_priority_min (policy);
  212230. maxp = sched_get_priority_max (policy);
  212231. if (p < 2)
  212232. param.__sched_priority = 0;
  212233. else if (p == 2 )
  212234. // Set to middle of lower realtime priority range
  212235. param.__sched_priority = minp + (maxp - minp) / 4;
  212236. else
  212237. // Set to middle of higher realtime priority range
  212238. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  212239. pthread_setschedparam (pthread_self(), policy, &param);
  212240. }
  212241. void Process::terminate()
  212242. {
  212243. exit (0);
  212244. }
  212245. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  212246. {
  212247. static char testResult = 0;
  212248. if (testResult == 0)
  212249. {
  212250. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  212251. if (testResult >= 0)
  212252. {
  212253. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  212254. testResult = 1;
  212255. }
  212256. }
  212257. return testResult < 0;
  212258. }
  212259. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  212260. {
  212261. return juce_isRunningUnderDebugger();
  212262. }
  212263. void Process::raisePrivilege()
  212264. {
  212265. // If running suid root, change effective user
  212266. // to root
  212267. if (geteuid() != 0 && getuid() == 0)
  212268. {
  212269. setreuid (geteuid(), getuid());
  212270. setregid (getegid(), getgid());
  212271. }
  212272. }
  212273. void Process::lowerPrivilege()
  212274. {
  212275. // If runing suid root, change effective user
  212276. // back to real user
  212277. if (geteuid() == 0 && getuid() != 0)
  212278. {
  212279. setreuid (geteuid(), getuid());
  212280. setregid (getegid(), getgid());
  212281. }
  212282. }
  212283. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  212284. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  212285. {
  212286. return dlopen ((const char*) name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  212287. }
  212288. void PlatformUtilities::freeDynamicLibrary (void* handle)
  212289. {
  212290. dlclose(handle);
  212291. }
  212292. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  212293. {
  212294. return dlsym (libraryHandle, (const char*) procedureName);
  212295. }
  212296. #endif
  212297. #endif
  212298. /********* End of inlined file: juce_linux_Threads.cpp *********/
  212299. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  212300. /********* Start of inlined file: juce_linux_Messaging.cpp *********/
  212301. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  212302. // compiled on its own).
  212303. #ifdef JUCE_INCLUDED_FILE
  212304. #ifdef JUCE_DEBUG
  212305. #define JUCE_DEBUG_XERRORS 1
  212306. #endif
  212307. Display* display = 0; // This is also referenced from WindowDriver.cpp
  212308. static Window juce_messageWindowHandle = None;
  212309. #define SpecialAtom "JUCESpecialAtom"
  212310. #define BroadcastAtom "JUCEBroadcastAtom"
  212311. #define SpecialCallbackAtom "JUCESpecialCallbackAtom"
  212312. static Atom specialId;
  212313. static Atom broadcastId;
  212314. static Atom specialCallbackId;
  212315. // This is referenced from WindowDriver.cpp
  212316. XContext improbableNumber;
  212317. // Defined in WindowDriver.cpp
  212318. extern void juce_windowMessageReceive (XEvent* event);
  212319. struct MessageThreadFuncCall
  212320. {
  212321. MessageCallbackFunction* func;
  212322. void* parameter;
  212323. void* result;
  212324. CriticalSection lock;
  212325. WaitableEvent event;
  212326. };
  212327. static bool errorCondition = false;
  212328. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  212329. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  212330. // (defined in another file to avoid problems including certain headers in this one)
  212331. extern bool juce_isRunningAsApplication();
  212332. // Usually happens when client-server connection is broken
  212333. static int ioErrorHandler (Display* display)
  212334. {
  212335. DBG (T("ERROR: connection to X server broken.. terminating."));
  212336. errorCondition = true;
  212337. if (juce_isRunningAsApplication())
  212338. Process::terminate();
  212339. return 0;
  212340. }
  212341. // A protocol error has occurred
  212342. static int errorHandler (Display* display, XErrorEvent* event)
  212343. {
  212344. #ifdef JUCE_DEBUG_XERRORS
  212345. char errorStr[64] = { 0 };
  212346. char requestStr[64] = { 0 };
  212347. XGetErrorText (display, event->error_code, errorStr, 64);
  212348. XGetErrorDatabaseText (display,
  212349. "XRequest",
  212350. (const char*) String (event->request_code),
  212351. "Unknown",
  212352. requestStr,
  212353. 64);
  212354. DBG (T("ERROR: X returned ") + String (errorStr) + T(" for operation ") + String (requestStr));
  212355. #endif
  212356. return 0;
  212357. }
  212358. static bool breakIn = false;
  212359. // Breakin from keyboard
  212360. static void sig_handler (int sig)
  212361. {
  212362. if (sig == SIGINT)
  212363. {
  212364. breakIn = true;
  212365. return;
  212366. }
  212367. static bool reentrant = false;
  212368. if (reentrant == false)
  212369. {
  212370. reentrant = true;
  212371. // Illegal instruction
  212372. fflush (stdout);
  212373. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  212374. errorCondition = true;
  212375. if (juce_isRunningAsApplication())
  212376. Process::terminate();
  212377. }
  212378. else
  212379. {
  212380. if (juce_isRunningAsApplication())
  212381. exit(0);
  212382. }
  212383. }
  212384. void MessageManager::doPlatformSpecificInitialisation()
  212385. {
  212386. // Initialise xlib for multiple thread support
  212387. static bool initThreadCalled = false;
  212388. if (! initThreadCalled)
  212389. {
  212390. if (! XInitThreads())
  212391. {
  212392. // This is fatal! Print error and closedown
  212393. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  212394. if (juce_isRunningAsApplication())
  212395. Process::terminate();
  212396. return;
  212397. }
  212398. initThreadCalled = true;
  212399. }
  212400. // This is called if the client/server connection is broken
  212401. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  212402. // This is called if a protocol error occurs
  212403. oldErrorHandler = XSetErrorHandler (errorHandler);
  212404. // Install signal handler for break-in
  212405. struct sigaction saction;
  212406. sigset_t maskSet;
  212407. sigemptyset (&maskSet);
  212408. saction.sa_handler = sig_handler;
  212409. saction.sa_mask = maskSet;
  212410. saction.sa_flags = 0;
  212411. sigaction (SIGINT, &saction, NULL);
  212412. #ifndef _DEBUG
  212413. // Setup signal handlers for various fatal errors
  212414. sigaction (SIGILL, &saction, NULL);
  212415. sigaction (SIGBUS, &saction, NULL);
  212416. sigaction (SIGFPE, &saction, NULL);
  212417. sigaction (SIGSEGV, &saction, NULL);
  212418. sigaction (SIGSYS, &saction, NULL);
  212419. #endif
  212420. String displayName (getenv ("DISPLAY"));
  212421. if (displayName.isEmpty())
  212422. displayName = T(":0.0");
  212423. display = XOpenDisplay (displayName);
  212424. if (display == 0)
  212425. {
  212426. // This is fatal! Print error and closedown
  212427. Logger::outputDebugString ("Failed to open the X display.");
  212428. if (juce_isRunningAsApplication())
  212429. Process::terminate();
  212430. return;
  212431. }
  212432. // Get defaults for various properties
  212433. int screen = DefaultScreen (display);
  212434. Window root = RootWindow (display, screen);
  212435. Visual* visual = DefaultVisual (display, screen);
  212436. // Create atoms for our ClientMessages (these cannot be deleted)
  212437. specialId = XInternAtom (display, SpecialAtom, false);
  212438. broadcastId = XInternAtom (display, BroadcastAtom, false);
  212439. specialCallbackId = XInternAtom (display, SpecialCallbackAtom, false);
  212440. // Create a context to store user data associated with Windows we
  212441. // create in WindowDriver
  212442. improbableNumber = XUniqueContext();
  212443. // We're only interested in client messages for this window
  212444. // which are always sent
  212445. XSetWindowAttributes swa;
  212446. swa.event_mask = NoEventMask;
  212447. // Create our message window (this will never be mapped)
  212448. juce_messageWindowHandle = XCreateWindow (display, root,
  212449. 0, 0, 1, 1, 0, 0, InputOnly,
  212450. visual, CWEventMask, &swa);
  212451. }
  212452. void MessageManager::doPlatformSpecificShutdown()
  212453. {
  212454. if (errorCondition == false)
  212455. {
  212456. XDestroyWindow (display, juce_messageWindowHandle);
  212457. XCloseDisplay (display);
  212458. // reset pointers
  212459. juce_messageWindowHandle = 0;
  212460. display = 0;
  212461. // Restore original error handlers
  212462. XSetIOErrorHandler (oldIOErrorHandler);
  212463. oldIOErrorHandler = 0;
  212464. XSetErrorHandler (oldErrorHandler);
  212465. oldErrorHandler = 0;
  212466. }
  212467. }
  212468. bool juce_postMessageToSystemQueue (void* message)
  212469. {
  212470. if (errorCondition)
  212471. return false;
  212472. XClientMessageEvent clientMsg;
  212473. clientMsg.display = display;
  212474. clientMsg.window = juce_messageWindowHandle;
  212475. clientMsg.type = ClientMessage;
  212476. clientMsg.format = 32;
  212477. clientMsg.message_type = specialId;
  212478. #if JUCE_64BIT
  212479. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) message) >> 32));
  212480. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (long) message);
  212481. #else
  212482. clientMsg.data.l[0] = (long) message;
  212483. #endif
  212484. XSendEvent (display, juce_messageWindowHandle, false,
  212485. NoEventMask, (XEvent*) &clientMsg);
  212486. XFlush (display); // This is necessary to ensure the event is delivered
  212487. return true;
  212488. }
  212489. void MessageManager::broadcastMessage (const String& value) throw()
  212490. {
  212491. }
  212492. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  212493. void* parameter)
  212494. {
  212495. void* retVal = 0;
  212496. if (! errorCondition)
  212497. {
  212498. if (! isThisTheMessageThread())
  212499. {
  212500. static MessageThreadFuncCall messageFuncCallContext;
  212501. const ScopedLock sl (messageFuncCallContext.lock);
  212502. XClientMessageEvent clientMsg;
  212503. clientMsg.display = display;
  212504. clientMsg.window = juce_messageWindowHandle;
  212505. clientMsg.type = ClientMessage;
  212506. clientMsg.format = 32;
  212507. clientMsg.message_type = specialCallbackId;
  212508. #if JUCE_64BIT
  212509. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) &messageFuncCallContext) >> 32));
  212510. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (uint64) &messageFuncCallContext);
  212511. #else
  212512. clientMsg.data.l[0] = (long) &messageFuncCallContext;
  212513. #endif
  212514. messageFuncCallContext.func = func;
  212515. messageFuncCallContext.parameter = parameter;
  212516. if (XSendEvent (display, juce_messageWindowHandle, false, NoEventMask, (XEvent*) &clientMsg) == 0)
  212517. return 0;
  212518. XFlush (display); // This is necessary to ensure the event is delivered
  212519. // Wait for it to complete before continuing
  212520. messageFuncCallContext.event.wait();
  212521. retVal = messageFuncCallContext.result;
  212522. }
  212523. else
  212524. {
  212525. // Just call the function directly
  212526. retVal = func (parameter);
  212527. }
  212528. }
  212529. return retVal;
  212530. }
  212531. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  212532. {
  212533. if (errorCondition)
  212534. return false;
  212535. if (breakIn)
  212536. {
  212537. errorCondition = true;
  212538. if (juce_isRunningAsApplication())
  212539. Process::terminate();
  212540. return false;
  212541. }
  212542. if (returnIfNoPendingMessages && ! XPending (display))
  212543. return false;
  212544. XEvent evt;
  212545. XNextEvent (display, &evt);
  212546. if (evt.type == ClientMessage && evt.xany.window == juce_messageWindowHandle)
  212547. {
  212548. XClientMessageEvent* const clientMsg = (XClientMessageEvent*) &evt;
  212549. if (clientMsg->format != 32)
  212550. {
  212551. jassertfalse
  212552. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received malformed client message.");
  212553. }
  212554. else
  212555. {
  212556. JUCE_TRY
  212557. {
  212558. #if JUCE_64BIT
  212559. void* const messagePtr
  212560. = (void*) ((0xffffffff00000000 & (((uint64) clientMsg->data.l[0]) << 32))
  212561. | (clientMsg->data.l[1] & 0x00000000ffffffff));
  212562. #else
  212563. void* const messagePtr = (void*) (clientMsg->data.l[0]);
  212564. #endif
  212565. if (clientMsg->message_type == specialId)
  212566. {
  212567. MessageManager::getInstance()->deliverMessage (messagePtr);
  212568. }
  212569. else if (clientMsg->message_type == specialCallbackId)
  212570. {
  212571. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) messagePtr;
  212572. MessageCallbackFunction* func = call->func;
  212573. call->result = (*func) (call->parameter);
  212574. call->event.signal();
  212575. }
  212576. else if (clientMsg->message_type == broadcastId)
  212577. {
  212578. #if 0
  212579. TCHAR buffer[8192];
  212580. zeromem (buffer, sizeof (buffer));
  212581. if (GlobalGetAtomName ((ATOM) lParam, buffer, 8192) != 0)
  212582. mq->deliverBroadcastMessage (String (buffer));
  212583. #endif
  212584. }
  212585. else
  212586. {
  212587. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received unknown client message.");
  212588. }
  212589. }
  212590. JUCE_CATCH_ALL
  212591. }
  212592. }
  212593. else if (evt.xany.window != juce_messageWindowHandle)
  212594. {
  212595. juce_windowMessageReceive (&evt);
  212596. }
  212597. return true;
  212598. }
  212599. #endif
  212600. /********* End of inlined file: juce_linux_Messaging.cpp *********/
  212601. /********* Start of inlined file: juce_linux_Fonts.cpp *********/
  212602. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  212603. // compiled on its own).
  212604. #ifdef JUCE_INCLUDED_FILE
  212605. class FreeTypeFontFace
  212606. {
  212607. public:
  212608. enum FontStyle
  212609. {
  212610. Plain = 0,
  212611. Bold = 1,
  212612. Italic = 2
  212613. };
  212614. struct FontNameIndex
  212615. {
  212616. String fileName;
  212617. int faceIndex;
  212618. };
  212619. FreeTypeFontFace (const String& familyName)
  212620. : hasSerif (false),
  212621. monospaced (false)
  212622. {
  212623. family = familyName;
  212624. }
  212625. void setFileName (const String& name,
  212626. const int faceIndex,
  212627. FontStyle style)
  212628. {
  212629. if (names[(int) style].fileName.isEmpty())
  212630. {
  212631. names[(int) style].fileName = name;
  212632. names[(int) style].faceIndex = faceIndex;
  212633. }
  212634. }
  212635. const String& getFamilyName() const throw()
  212636. {
  212637. return family;
  212638. }
  212639. const String& getFileName (int style, int* faceIndex) const throw()
  212640. {
  212641. *faceIndex = names [style].faceIndex;
  212642. return names[style].fileName;
  212643. }
  212644. void setMonospaced (bool mono) { monospaced = mono; }
  212645. bool getMonospaced () const throw() { return monospaced; }
  212646. void setSerif (const bool serif) { hasSerif = serif; }
  212647. bool getSerif () const throw() { return hasSerif; }
  212648. private:
  212649. String family;
  212650. FontNameIndex names[4];
  212651. bool hasSerif, monospaced;
  212652. };
  212653. class FreeTypeInterface : public DeletedAtShutdown
  212654. {
  212655. public:
  212656. FreeTypeInterface() throw()
  212657. : lastFace (0),
  212658. lastBold (false),
  212659. lastItalic (false)
  212660. {
  212661. if (FT_Init_FreeType (&ftLib) != 0)
  212662. {
  212663. ftLib = 0;
  212664. DBG (T("Failed to initialize FreeType"));
  212665. }
  212666. StringArray fontDirs;
  212667. fontDirs.addTokens (String (getenv ("JUCE_FONT_PATH")), T(";,"), 0);
  212668. fontDirs.removeEmptyStrings (true);
  212669. if (fontDirs.size() == 0)
  212670. {
  212671. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  212672. XmlElement* const fontsInfo = fontsConfig.getDocumentElement();
  212673. if (fontsInfo != 0)
  212674. {
  212675. forEachXmlChildElementWithTagName (*fontsInfo, e, T("dir"))
  212676. {
  212677. fontDirs.add (e->getAllSubText().trim());
  212678. }
  212679. delete fontsInfo;
  212680. }
  212681. }
  212682. if (fontDirs.size() == 0)
  212683. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  212684. for (int i = 0; i < fontDirs.size(); ++i)
  212685. enumerateFaces (fontDirs[i]);
  212686. }
  212687. ~FreeTypeInterface() throw()
  212688. {
  212689. if (lastFace != 0)
  212690. FT_Done_Face (lastFace);
  212691. if (ftLib != 0)
  212692. FT_Done_FreeType (ftLib);
  212693. clearSingletonInstance();
  212694. }
  212695. FreeTypeFontFace* findOrCreate (const String& familyName,
  212696. const bool create = false) throw()
  212697. {
  212698. for (int i = 0; i < faces.size(); i++)
  212699. if (faces[i]->getFamilyName() == familyName)
  212700. return faces[i];
  212701. if (! create)
  212702. return NULL;
  212703. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  212704. faces.add (newFace);
  212705. return newFace;
  212706. }
  212707. // Enumerate all font faces available in a given directory
  212708. void enumerateFaces (const String& path) throw()
  212709. {
  212710. File dirPath (path);
  212711. if (path.isEmpty() || ! dirPath.isDirectory())
  212712. return;
  212713. DirectoryIterator di (dirPath, true);
  212714. while (di.next())
  212715. {
  212716. File possible (di.getFile());
  212717. if (possible.hasFileExtension (T("ttf"))
  212718. || possible.hasFileExtension (T("pfb"))
  212719. || possible.hasFileExtension (T("pcf")))
  212720. {
  212721. FT_Face face;
  212722. int faceIndex = 0;
  212723. int numFaces = 0;
  212724. do
  212725. {
  212726. if (FT_New_Face (ftLib,
  212727. possible.getFullPathName(),
  212728. faceIndex,
  212729. &face) == 0)
  212730. {
  212731. if (faceIndex == 0)
  212732. numFaces = face->num_faces;
  212733. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  212734. {
  212735. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  212736. int style = (int) FreeTypeFontFace::Plain;
  212737. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  212738. style |= (int) FreeTypeFontFace::Bold;
  212739. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  212740. style |= (int) FreeTypeFontFace::Italic;
  212741. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  212742. if ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0)
  212743. newFace->setMonospaced (true);
  212744. else
  212745. newFace->setMonospaced (false);
  212746. // Surely there must be a better way to do this?
  212747. if (String (face->family_name).containsIgnoreCase (T("Sans"))
  212748. || String (face->family_name).containsIgnoreCase (T("Verdana"))
  212749. || String (face->family_name).containsIgnoreCase (T("Arial")))
  212750. {
  212751. newFace->setSerif (false);
  212752. }
  212753. else
  212754. {
  212755. newFace->setSerif (true);
  212756. }
  212757. }
  212758. FT_Done_Face (face);
  212759. }
  212760. ++faceIndex;
  212761. }
  212762. while (faceIndex < numFaces);
  212763. }
  212764. }
  212765. }
  212766. // Create a FreeType face object for a given font
  212767. FT_Face createFT_Face (const String& fontName,
  212768. const bool bold,
  212769. const bool italic) throw()
  212770. {
  212771. FT_Face face = NULL;
  212772. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  212773. {
  212774. face = lastFace;
  212775. }
  212776. else
  212777. {
  212778. if (lastFace)
  212779. {
  212780. FT_Done_Face (lastFace);
  212781. lastFace = NULL;
  212782. }
  212783. lastFontName = fontName;
  212784. lastBold = bold;
  212785. lastItalic = italic;
  212786. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  212787. if (ftFace != 0)
  212788. {
  212789. int style = (int) FreeTypeFontFace::Plain;
  212790. if (bold)
  212791. style |= (int) FreeTypeFontFace::Bold;
  212792. if (italic)
  212793. style |= (int) FreeTypeFontFace::Italic;
  212794. int faceIndex;
  212795. String fileName (ftFace->getFileName (style, &faceIndex));
  212796. if (fileName.isEmpty())
  212797. {
  212798. style ^= (int) FreeTypeFontFace::Bold;
  212799. fileName = ftFace->getFileName (style, &faceIndex);
  212800. if (fileName.isEmpty())
  212801. {
  212802. style ^= (int) FreeTypeFontFace::Bold;
  212803. style ^= (int) FreeTypeFontFace::Italic;
  212804. fileName = ftFace->getFileName (style, &faceIndex);
  212805. if (! fileName.length())
  212806. {
  212807. style ^= (int) FreeTypeFontFace::Bold;
  212808. fileName = ftFace->getFileName (style, &faceIndex);
  212809. }
  212810. }
  212811. }
  212812. if (! FT_New_Face (ftLib, (const char*) fileName, faceIndex, &lastFace))
  212813. {
  212814. face = lastFace;
  212815. // If there isn't a unicode charmap then select the first one.
  212816. if (FT_Select_Charmap (face, ft_encoding_unicode))
  212817. FT_Set_Charmap (face, face->charmaps[0]);
  212818. }
  212819. }
  212820. }
  212821. return face;
  212822. }
  212823. bool addGlyph (FT_Face face, Typeface& dest, uint32 character) throw()
  212824. {
  212825. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  212826. const float height = (float) (face->ascender - face->descender);
  212827. const float scaleX = 1.0f / height;
  212828. const float scaleY = -1.0f / height;
  212829. Path destShape;
  212830. #define CONVERTX(val) (scaleX * (val).x)
  212831. #define CONVERTY(val) (scaleY * (val).y)
  212832. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE
  212833. | FT_LOAD_NO_BITMAP
  212834. | FT_LOAD_IGNORE_TRANSFORM) != 0
  212835. || face->glyph->format != ft_glyph_format_outline)
  212836. {
  212837. return false;
  212838. }
  212839. const FT_Outline* const outline = &face->glyph->outline;
  212840. const short* const contours = outline->contours;
  212841. const char* const tags = outline->tags;
  212842. FT_Vector* const points = outline->points;
  212843. for (int c = 0; c < outline->n_contours; c++)
  212844. {
  212845. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  212846. const int endPoint = contours[c];
  212847. for (int p = startPoint; p <= endPoint; p++)
  212848. {
  212849. const float x = CONVERTX (points[p]);
  212850. const float y = CONVERTY (points[p]);
  212851. if (p == startPoint)
  212852. {
  212853. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  212854. {
  212855. float x2 = CONVERTX (points [endPoint]);
  212856. float y2 = CONVERTY (points [endPoint]);
  212857. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  212858. {
  212859. x2 = (x + x2) * 0.5f;
  212860. y2 = (y + y2) * 0.5f;
  212861. }
  212862. destShape.startNewSubPath (x2, y2);
  212863. }
  212864. else
  212865. {
  212866. destShape.startNewSubPath (x, y);
  212867. }
  212868. }
  212869. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  212870. {
  212871. if (p != startPoint)
  212872. destShape.lineTo (x, y);
  212873. }
  212874. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  212875. {
  212876. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  212877. float x2 = CONVERTX (points [nextIndex]);
  212878. float y2 = CONVERTY (points [nextIndex]);
  212879. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  212880. {
  212881. x2 = (x + x2) * 0.5f;
  212882. y2 = (y + y2) * 0.5f;
  212883. }
  212884. else
  212885. {
  212886. ++p;
  212887. }
  212888. destShape.quadraticTo (x, y, x2, y2);
  212889. }
  212890. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  212891. {
  212892. if (p >= endPoint)
  212893. return false;
  212894. const int next1 = p + 1;
  212895. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  212896. const float x2 = CONVERTX (points [next1]);
  212897. const float y2 = CONVERTY (points [next1]);
  212898. const float x3 = CONVERTX (points [next2]);
  212899. const float y3 = CONVERTY (points [next2]);
  212900. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  212901. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  212902. return false;
  212903. destShape.cubicTo (x, y, x2, y2, x3, y3);
  212904. p += 2;
  212905. }
  212906. }
  212907. destShape.closeSubPath();
  212908. }
  212909. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance/height);
  212910. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  212911. addKerning (face, dest, character, glyphIndex);
  212912. return true;
  212913. }
  212914. void addKerning (FT_Face face, Typeface& dest, const uint32 character, const uint32 glyphIndex) throw()
  212915. {
  212916. const float height = (float) (face->ascender - face->descender);
  212917. uint32 rightGlyphIndex;
  212918. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  212919. while (rightGlyphIndex != 0)
  212920. {
  212921. FT_Vector kerning;
  212922. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  212923. {
  212924. if (kerning.x != 0)
  212925. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  212926. }
  212927. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  212928. }
  212929. }
  212930. // Add a glyph to a font
  212931. bool addGlyphToFont (const uint32 character,
  212932. const tchar* fontName, bool bold, bool italic,
  212933. Typeface& dest) throw()
  212934. {
  212935. FT_Face face = createFT_Face (fontName, bold, italic);
  212936. if (face != 0)
  212937. return addGlyph (face, dest, character);
  212938. return false;
  212939. }
  212940. // Create a Typeface object for given name/style
  212941. bool createTypeface (const String& fontName,
  212942. const bool bold, const bool italic,
  212943. Typeface& dest,
  212944. const bool addAllGlyphs) throw()
  212945. {
  212946. dest.clear();
  212947. dest.setName (fontName);
  212948. dest.setBold (bold);
  212949. dest.setItalic (italic);
  212950. FT_Face face = createFT_Face (fontName, bold, italic);
  212951. if (face == 0)
  212952. {
  212953. #ifdef JUCE_DEBUG
  212954. String msg (T("Failed to create typeface: "));
  212955. msg << fontName << " " << (bold ? 'B' : ' ') << (italic ? 'I' : ' ');
  212956. DBG (msg);
  212957. #endif
  212958. return face;
  212959. }
  212960. const float height = (float) (face->ascender - face->descender);
  212961. dest.setAscent (face->ascender / height);
  212962. dest.setDefaultCharacter (L' ');
  212963. if (addAllGlyphs)
  212964. {
  212965. uint32 glyphIndex;
  212966. uint32 charCode = FT_Get_First_Char (face, &glyphIndex);
  212967. while (glyphIndex != 0)
  212968. {
  212969. addGlyph (face, dest, charCode);
  212970. charCode = FT_Get_Next_Char (face, charCode, &glyphIndex);
  212971. }
  212972. }
  212973. return true;
  212974. }
  212975. void getFamilyNames (StringArray& familyNames) const throw()
  212976. {
  212977. for (int i = 0; i < faces.size(); i++)
  212978. familyNames.add (faces[i]->getFamilyName());
  212979. }
  212980. void getMonospacedNames (StringArray& monoSpaced) const throw()
  212981. {
  212982. for (int i = 0; i < faces.size(); i++)
  212983. if (faces[i]->getMonospaced())
  212984. monoSpaced.add (faces[i]->getFamilyName());
  212985. }
  212986. void getSerifNames (StringArray& serif) const throw()
  212987. {
  212988. for (int i = 0; i < faces.size(); i++)
  212989. if (faces[i]->getSerif())
  212990. serif.add (faces[i]->getFamilyName());
  212991. }
  212992. void getSansSerifNames (StringArray& sansSerif) const throw()
  212993. {
  212994. for (int i = 0; i < faces.size(); i++)
  212995. if (! faces[i]->getSerif())
  212996. sansSerif.add (faces[i]->getFamilyName());
  212997. }
  212998. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  212999. private:
  213000. FT_Library ftLib;
  213001. FT_Face lastFace;
  213002. String lastFontName;
  213003. bool lastBold, lastItalic;
  213004. OwnedArray<FreeTypeFontFace> faces;
  213005. };
  213006. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  213007. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  213008. bool bold, bool italic,
  213009. bool addAllGlyphsToFont) throw()
  213010. {
  213011. FreeTypeInterface::getInstance()
  213012. ->createTypeface (fontName, bold, italic, *this, addAllGlyphsToFont);
  213013. }
  213014. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  213015. {
  213016. return FreeTypeInterface::getInstance()
  213017. ->addGlyphToFont (character, getName(), isBold(), isItalic(), *this);
  213018. }
  213019. const StringArray Font::findAllTypefaceNames() throw()
  213020. {
  213021. StringArray s;
  213022. FreeTypeInterface::getInstance()->getFamilyNames (s);
  213023. s.sort (true);
  213024. return s;
  213025. }
  213026. static const String pickBestFont (const StringArray& names,
  213027. const char* const choicesString)
  213028. {
  213029. StringArray choices;
  213030. choices.addTokens (String (choicesString), T(","), 0);
  213031. choices.trim();
  213032. choices.removeEmptyStrings();
  213033. int i, j;
  213034. for (j = 0; j < choices.size(); ++j)
  213035. if (names.contains (choices[j], true))
  213036. return choices[j];
  213037. for (j = 0; j < choices.size(); ++j)
  213038. for (i = 0; i < names.size(); i++)
  213039. if (names[i].startsWithIgnoreCase (choices[j]))
  213040. return names[i];
  213041. for (j = 0; j < choices.size(); ++j)
  213042. for (i = 0; i < names.size(); i++)
  213043. if (names[i].containsIgnoreCase (choices[j]))
  213044. return names[i];
  213045. return names[0];
  213046. }
  213047. static const String linux_getDefaultSansSerifFontName()
  213048. {
  213049. StringArray allFonts;
  213050. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  213051. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  213052. }
  213053. static const String linux_getDefaultSerifFontName()
  213054. {
  213055. StringArray allFonts;
  213056. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  213057. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  213058. }
  213059. static const String linux_getDefaultMonospacedFontName()
  213060. {
  213061. StringArray allFonts;
  213062. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  213063. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  213064. }
  213065. void Typeface::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  213066. {
  213067. defaultSans = linux_getDefaultSansSerifFontName();
  213068. defaultSerif = linux_getDefaultSerifFontName();
  213069. defaultFixed = linux_getDefaultMonospacedFontName();
  213070. }
  213071. #endif
  213072. /********* End of inlined file: juce_linux_Fonts.cpp *********/
  213073. /********* Start of inlined file: juce_linux_Windowing.cpp *********/
  213074. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213075. // compiled on its own).
  213076. #ifdef JUCE_INCLUDED_FILE
  213077. #define TAKE_FOCUS 0
  213078. #define DELETE_WINDOW 1
  213079. #define SYSTEM_TRAY_REQUEST_DOCK 0
  213080. #define SYSTEM_TRAY_BEGIN_MESSAGE 1
  213081. #define SYSTEM_TRAY_CANCEL_MESSAGE 2
  213082. static const int repaintTimerPeriod = 1000 / 100; // 100 fps maximum
  213083. static Atom wm_ChangeState = None;
  213084. static Atom wm_State = None;
  213085. static Atom wm_Protocols = None;
  213086. static Atom wm_ProtocolList [2] = { None, None };
  213087. static Atom wm_ActiveWin = None;
  213088. #define ourDndVersion 3
  213089. static Atom XA_XdndAware = None;
  213090. static Atom XA_XdndEnter = None;
  213091. static Atom XA_XdndLeave = None;
  213092. static Atom XA_XdndPosition = None;
  213093. static Atom XA_XdndStatus = None;
  213094. static Atom XA_XdndDrop = None;
  213095. static Atom XA_XdndFinished = None;
  213096. static Atom XA_XdndSelection = None;
  213097. static Atom XA_XdndProxy = None;
  213098. static Atom XA_XdndTypeList = None;
  213099. static Atom XA_XdndActionList = None;
  213100. static Atom XA_XdndActionDescription = None;
  213101. static Atom XA_XdndActionCopy = None;
  213102. static Atom XA_XdndActionMove = None;
  213103. static Atom XA_XdndActionLink = None;
  213104. static Atom XA_XdndActionAsk = None;
  213105. static Atom XA_XdndActionPrivate = None;
  213106. static Atom XA_JXSelectionWindowProperty = None;
  213107. static Atom XA_MimeTextPlain = None;
  213108. static Atom XA_MimeTextUriList = None;
  213109. static Atom XA_MimeRootDrop = None;
  213110. static XErrorHandler oldHandler = 0;
  213111. static int trappedErrorCode = 0;
  213112. extern "C" int errorTrapHandler (Display* dpy, XErrorEvent* err)
  213113. {
  213114. trappedErrorCode = err->error_code;
  213115. return 0;
  213116. }
  213117. static void trapErrors()
  213118. {
  213119. trappedErrorCode = 0;
  213120. oldHandler = XSetErrorHandler (errorTrapHandler);
  213121. }
  213122. static bool untrapErrors()
  213123. {
  213124. XSetErrorHandler (oldHandler);
  213125. return (trappedErrorCode == 0);
  213126. }
  213127. static bool isActiveApplication = false;
  213128. bool Process::isForegroundProcess() throw()
  213129. {
  213130. return isActiveApplication;
  213131. }
  213132. // (used in the messaging code, declared here for build reasons)
  213133. bool juce_isRunningAsApplication()
  213134. {
  213135. return JUCEApplication::getInstance() != 0;
  213136. }
  213137. // These are defined in juce_linux_Messaging.cpp
  213138. extern Display* display;
  213139. extern XContext improbableNumber;
  213140. static const int eventMask = NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  213141. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  213142. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  213143. static int pointerMap[5];
  213144. static int lastMousePosX = 0, lastMousePosY = 0;
  213145. enum MouseButtons
  213146. {
  213147. NoButton = 0,
  213148. LeftButton = 1,
  213149. MiddleButton = 2,
  213150. RightButton = 3,
  213151. WheelUp = 4,
  213152. WheelDown = 5
  213153. };
  213154. static void getMousePos (int& x, int& y, int& mouseMods) throw()
  213155. {
  213156. Window root, child;
  213157. int winx, winy;
  213158. unsigned int mask;
  213159. mouseMods = 0;
  213160. if (XQueryPointer (display,
  213161. RootWindow (display, DefaultScreen (display)),
  213162. &root, &child,
  213163. &x, &y, &winx, &winy, &mask) == False)
  213164. {
  213165. // Pointer not on the default screen
  213166. x = y = -1;
  213167. }
  213168. else
  213169. {
  213170. if ((mask & Button1Mask) != 0)
  213171. mouseMods |= ModifierKeys::leftButtonModifier;
  213172. if ((mask & Button2Mask) != 0)
  213173. mouseMods |= ModifierKeys::middleButtonModifier;
  213174. if ((mask & Button3Mask) != 0)
  213175. mouseMods |= ModifierKeys::rightButtonModifier;
  213176. }
  213177. }
  213178. static int AltMask = 0;
  213179. static int NumLockMask = 0;
  213180. static bool numLock = 0;
  213181. static bool capsLock = 0;
  213182. static char keyStates [32];
  213183. static void updateKeyStates (const int keycode, const bool press) throw()
  213184. {
  213185. const int keybyte = keycode >> 3;
  213186. const int keybit = (1 << (keycode & 7));
  213187. if (press)
  213188. keyStates [keybyte] |= keybit;
  213189. else
  213190. keyStates [keybyte] &= ~keybit;
  213191. }
  213192. static bool keyDown (const int keycode) throw()
  213193. {
  213194. const int keybyte = keycode >> 3;
  213195. const int keybit = (1 << (keycode & 7));
  213196. return (keyStates [keybyte] & keybit) != 0;
  213197. }
  213198. static const int extendedKeyModifier = 0x10000000;
  213199. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  213200. {
  213201. int keysym;
  213202. if (keyCode & extendedKeyModifier)
  213203. {
  213204. keysym = 0xff00 | (keyCode & 0xff);
  213205. }
  213206. else
  213207. {
  213208. keysym = keyCode;
  213209. if (keysym == (XK_Tab & 0xff)
  213210. || keysym == (XK_Return & 0xff)
  213211. || keysym == (XK_Escape & 0xff)
  213212. || keysym == (XK_BackSpace & 0xff))
  213213. {
  213214. keysym |= 0xff00;
  213215. }
  213216. }
  213217. return keyDown (XKeysymToKeycode (display, keysym));
  213218. }
  213219. // Alt and Num lock are not defined by standard X
  213220. // modifier constants: check what they're mapped to
  213221. static void getModifierMapping() throw()
  213222. {
  213223. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  213224. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  213225. AltMask = 0;
  213226. NumLockMask = 0;
  213227. XModifierKeymap* mapping = XGetModifierMapping (display);
  213228. if (mapping)
  213229. {
  213230. for (int i = 0; i < 8; i++)
  213231. {
  213232. if (mapping->modifiermap [i << 1] == altLeftCode)
  213233. AltMask = 1 << i;
  213234. else if (mapping->modifiermap [i << 1] == numLockCode)
  213235. NumLockMask = 1 << i;
  213236. }
  213237. XFreeModifiermap (mapping);
  213238. }
  213239. }
  213240. static int currentModifiers = 0;
  213241. void ModifierKeys::updateCurrentModifiers() throw()
  213242. {
  213243. currentModifierFlags = currentModifiers;
  213244. }
  213245. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  213246. {
  213247. int x, y, mouseMods;
  213248. getMousePos (x, y, mouseMods);
  213249. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  213250. currentModifiers |= mouseMods;
  213251. return ModifierKeys (currentModifiers);
  213252. }
  213253. static void updateKeyModifiers (const int status) throw()
  213254. {
  213255. currentModifiers &= ~(ModifierKeys::shiftModifier
  213256. | ModifierKeys::ctrlModifier
  213257. | ModifierKeys::altModifier);
  213258. if (status & ShiftMask)
  213259. currentModifiers |= ModifierKeys::shiftModifier;
  213260. if (status & ControlMask)
  213261. currentModifiers |= ModifierKeys::ctrlModifier;
  213262. if (status & AltMask)
  213263. currentModifiers |= ModifierKeys::altModifier;
  213264. numLock = ((status & NumLockMask) != 0);
  213265. capsLock = ((status & LockMask) != 0);
  213266. }
  213267. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  213268. {
  213269. int modifier = 0;
  213270. bool isModifier = true;
  213271. switch (sym)
  213272. {
  213273. case XK_Shift_L:
  213274. case XK_Shift_R:
  213275. modifier = ModifierKeys::shiftModifier;
  213276. break;
  213277. case XK_Control_L:
  213278. case XK_Control_R:
  213279. modifier = ModifierKeys::ctrlModifier;
  213280. break;
  213281. case XK_Alt_L:
  213282. case XK_Alt_R:
  213283. modifier = ModifierKeys::altModifier;
  213284. break;
  213285. case XK_Num_Lock:
  213286. if (press)
  213287. numLock = ! numLock;
  213288. break;
  213289. case XK_Caps_Lock:
  213290. if (press)
  213291. capsLock = ! capsLock;
  213292. break;
  213293. case XK_Scroll_Lock:
  213294. break;
  213295. default:
  213296. isModifier = false;
  213297. break;
  213298. }
  213299. if (modifier != 0)
  213300. {
  213301. if (press)
  213302. currentModifiers |= modifier;
  213303. else
  213304. currentModifiers &= ~modifier;
  213305. }
  213306. return isModifier;
  213307. }
  213308. #if JUCE_USE_XSHM
  213309. static bool isShmAvailable() throw()
  213310. {
  213311. static bool isChecked = false;
  213312. static bool isAvailable = false;
  213313. if (! isChecked)
  213314. {
  213315. isChecked = true;
  213316. int major, minor;
  213317. Bool pixmaps;
  213318. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  213319. {
  213320. trapErrors();
  213321. XShmSegmentInfo segmentInfo;
  213322. zerostruct (segmentInfo);
  213323. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  213324. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  213325. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  213326. xImage->bytes_per_line * xImage->height,
  213327. IPC_CREAT | 0777)) >= 0)
  213328. {
  213329. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  213330. if (segmentInfo.shmaddr != (void*) -1)
  213331. {
  213332. segmentInfo.readOnly = False;
  213333. xImage->data = segmentInfo.shmaddr;
  213334. XSync (display, False);
  213335. if (XShmAttach (display, &segmentInfo) != 0)
  213336. {
  213337. XSync (display, False);
  213338. XShmDetach (display, &segmentInfo);
  213339. isAvailable = true;
  213340. }
  213341. }
  213342. XFlush (display);
  213343. XDestroyImage (xImage);
  213344. shmdt (segmentInfo.shmaddr);
  213345. }
  213346. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  213347. isAvailable &= untrapErrors();
  213348. }
  213349. }
  213350. return isAvailable;
  213351. }
  213352. #endif
  213353. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  213354. {
  213355. const int width = image.getWidth();
  213356. const int height = image.getHeight();
  213357. uint32* const colour = (uint32*) juce_malloc (width * height * sizeof (uint32));
  213358. int index = 0;
  213359. for (int y = 0; y < height; ++y)
  213360. for (int x = 0; x < width; ++x)
  213361. colour[index++] = image.getPixelAt (x, y).getARGB();
  213362. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  213363. 0, (char*) colour, width, height, 32, 0);
  213364. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  213365. width, height, 24);
  213366. GC gc = XCreateGC (display, pixmap, 0, 0);
  213367. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  213368. XFreeGC (display, gc);
  213369. juce_free (colour);
  213370. return pixmap;
  213371. }
  213372. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  213373. {
  213374. const int width = image.getWidth();
  213375. const int height = image.getHeight();
  213376. const int stride = (width + 7) >> 3;
  213377. uint8* const mask = (uint8*) juce_calloc (stride * height);
  213378. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  213379. for (int y = 0; y < height; ++y)
  213380. {
  213381. for (int x = 0; x < width; ++x)
  213382. {
  213383. const uint8 bit = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  213384. const int offset = y * stride + (x >> 3);
  213385. if (image.getPixelAt (x, y).getAlpha() >= 128)
  213386. mask[offset] |= bit;
  213387. }
  213388. }
  213389. Pixmap pixmap = XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  213390. (char*) mask, width, height, 1, 0, 1);
  213391. juce_free (mask);
  213392. return pixmap;
  213393. }
  213394. class XBitmapImage : public Image
  213395. {
  213396. public:
  213397. XBitmapImage (const PixelFormat format_, const int w, const int h,
  213398. const bool clearImage, const bool is16Bit_)
  213399. : Image (format_, w, h),
  213400. is16Bit (is16Bit_)
  213401. {
  213402. jassert (format_ == RGB || format_ == ARGB);
  213403. pixelStride = (format_ == RGB) ? 3 : 4;
  213404. lineStride = ((w * pixelStride + 3) & ~3);
  213405. Visual* const visual = DefaultVisual (display, DefaultScreen (display));
  213406. #if JUCE_USE_XSHM
  213407. usingXShm = false;
  213408. if ((! is16Bit) && isShmAvailable())
  213409. {
  213410. zerostruct (segmentInfo);
  213411. xImage = XShmCreateImage (display, visual, 24, ZPixmap, 0, &segmentInfo, w, h);
  213412. if (xImage != 0)
  213413. {
  213414. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  213415. xImage->bytes_per_line * xImage->height,
  213416. IPC_CREAT | 0777)) >= 0)
  213417. {
  213418. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  213419. if (segmentInfo.shmaddr != (void*) -1)
  213420. {
  213421. segmentInfo.readOnly = False;
  213422. xImage->data = segmentInfo.shmaddr;
  213423. imageData = (uint8*) segmentInfo.shmaddr;
  213424. XSync (display, False);
  213425. if (XShmAttach (display, &segmentInfo) != 0)
  213426. {
  213427. XSync (display, False);
  213428. usingXShm = true;
  213429. }
  213430. else
  213431. {
  213432. jassertfalse
  213433. }
  213434. }
  213435. else
  213436. {
  213437. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  213438. }
  213439. }
  213440. }
  213441. }
  213442. if (! usingXShm)
  213443. #endif
  213444. {
  213445. imageData = (uint8*) juce_malloc (lineStride * h);
  213446. if (format_ == ARGB && clearImage)
  213447. zeromem (imageData, h * lineStride);
  213448. xImage = (XImage*) juce_calloc (sizeof (XImage));
  213449. xImage->width = w;
  213450. xImage->height = h;
  213451. xImage->xoffset = 0;
  213452. xImage->format = ZPixmap;
  213453. xImage->data = (char*) imageData;
  213454. xImage->byte_order = ImageByteOrder (display);
  213455. xImage->bitmap_unit = BitmapUnit (display);
  213456. xImage->bitmap_bit_order = BitmapBitOrder (display);
  213457. xImage->bitmap_pad = 32;
  213458. xImage->depth = pixelStride * 8;
  213459. xImage->bytes_per_line = lineStride;
  213460. xImage->bits_per_pixel = pixelStride * 8;
  213461. xImage->red_mask = 0x00FF0000;
  213462. xImage->green_mask = 0x0000FF00;
  213463. xImage->blue_mask = 0x000000FF;
  213464. if (is16Bit)
  213465. {
  213466. const int pixelStride = 2;
  213467. const int lineStride = ((w * pixelStride + 3) & ~3);
  213468. xImage->data = (char*) juce_malloc (lineStride * h);
  213469. xImage->bitmap_pad = 16;
  213470. xImage->depth = pixelStride * 8;
  213471. xImage->bytes_per_line = lineStride;
  213472. xImage->bits_per_pixel = pixelStride * 8;
  213473. xImage->red_mask = visual->red_mask;
  213474. xImage->green_mask = visual->green_mask;
  213475. xImage->blue_mask = visual->blue_mask;
  213476. }
  213477. if (! XInitImage (xImage))
  213478. {
  213479. jassertfalse
  213480. }
  213481. }
  213482. }
  213483. ~XBitmapImage()
  213484. {
  213485. #if JUCE_USE_XSHM
  213486. if (usingXShm)
  213487. {
  213488. XShmDetach (display, &segmentInfo);
  213489. XFlush (display);
  213490. XDestroyImage (xImage);
  213491. shmdt (segmentInfo.shmaddr);
  213492. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  213493. }
  213494. else
  213495. #endif
  213496. {
  213497. juce_free (xImage->data);
  213498. xImage->data = 0;
  213499. XDestroyImage (xImage);
  213500. }
  213501. if (! is16Bit)
  213502. imageData = 0; // to stop the base class freeing this (for the 16-bit version we want it to free it)
  213503. }
  213504. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  213505. {
  213506. static GC gc = 0;
  213507. if (gc == 0)
  213508. gc = DefaultGC (display, DefaultScreen (display));
  213509. if (is16Bit)
  213510. {
  213511. const uint32 rMask = xImage->red_mask;
  213512. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  213513. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  213514. const uint32 gMask = xImage->green_mask;
  213515. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  213516. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  213517. const uint32 bMask = xImage->blue_mask;
  213518. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  213519. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  213520. int ls, ps;
  213521. const uint8* const pixels = lockPixelDataReadOnly (0, 0, getWidth(), getHeight(), ls, ps);
  213522. for (int y = sy; y < sy + dh; ++y)
  213523. {
  213524. const uint8* p = pixels + y * ls + sx * ps;
  213525. for (int x = sx; x < sx + dw; ++x)
  213526. {
  213527. const PixelRGB* const pixel = (const PixelRGB*) p;
  213528. p += ps;
  213529. XPutPixel (xImage, x, y,
  213530. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  213531. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  213532. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  213533. }
  213534. }
  213535. releasePixelDataReadOnly (pixels);
  213536. }
  213537. // blit results to screen.
  213538. #if JUCE_USE_XSHM
  213539. if (usingXShm)
  213540. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, False);
  213541. else
  213542. #endif
  213543. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  213544. }
  213545. juce_UseDebuggingNewOperator
  213546. private:
  213547. XImage* xImage;
  213548. const bool is16Bit;
  213549. #if JUCE_USE_XSHM
  213550. XShmSegmentInfo segmentInfo;
  213551. bool usingXShm;
  213552. #endif
  213553. static int getShiftNeeded (const uint32 mask) throw()
  213554. {
  213555. for (int i = 32; --i >= 0;)
  213556. if (((mask >> i) & 1) != 0)
  213557. return i - 7;
  213558. jassertfalse
  213559. return 0;
  213560. }
  213561. };
  213562. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  213563. class LinuxComponentPeer : public ComponentPeer
  213564. {
  213565. public:
  213566. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  213567. : ComponentPeer (component, windowStyleFlags),
  213568. windowH (0),
  213569. parentWindow (0),
  213570. wx (0),
  213571. wy (0),
  213572. ww (0),
  213573. wh (0),
  213574. taskbarImage (0),
  213575. fullScreen (false),
  213576. entered (false),
  213577. mapped (false)
  213578. {
  213579. // it's dangerous to create a window on a thread other than the message thread..
  213580. checkMessageManagerIsLocked
  213581. repainter = new LinuxRepaintManager (this);
  213582. createWindow();
  213583. setTitle (component->getName());
  213584. }
  213585. ~LinuxComponentPeer()
  213586. {
  213587. // it's dangerous to delete a window on a thread other than the message thread..
  213588. checkMessageManagerIsLocked
  213589. deleteTaskBarIcon();
  213590. deleteIconPixmaps();
  213591. destroyWindow();
  213592. windowH = 0;
  213593. delete repainter;
  213594. }
  213595. void* getNativeHandle() const
  213596. {
  213597. return (void*) windowH;
  213598. }
  213599. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  213600. {
  213601. XPointer peer = 0;
  213602. if (! XFindContext (display, (XID) windowHandle, improbableNumber, &peer))
  213603. {
  213604. if (peer != 0 && ! ((LinuxComponentPeer*) peer)->isValidMessageListener())
  213605. peer = 0;
  213606. }
  213607. return (LinuxComponentPeer*) peer;
  213608. }
  213609. void setVisible (bool shouldBeVisible)
  213610. {
  213611. if (shouldBeVisible)
  213612. XMapWindow (display, windowH);
  213613. else
  213614. XUnmapWindow (display, windowH);
  213615. }
  213616. void setTitle (const String& title)
  213617. {
  213618. setWindowTitle (windowH, title);
  213619. }
  213620. void setPosition (int x, int y)
  213621. {
  213622. setBounds (x, y, ww, wh, false);
  213623. }
  213624. void setSize (int w, int h)
  213625. {
  213626. setBounds (wx, wy, w, h, false);
  213627. }
  213628. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  213629. {
  213630. fullScreen = isNowFullScreen;
  213631. if (windowH != 0)
  213632. {
  213633. const ComponentDeletionWatcher deletionChecker (component);
  213634. wx = x;
  213635. wy = y;
  213636. ww = jmax (1, w);
  213637. wh = jmax (1, h);
  213638. // Make sure the Window manager does what we want
  213639. XSizeHints* hints = XAllocSizeHints();
  213640. hints->flags = USSize | USPosition;
  213641. hints->width = ww;
  213642. hints->height = wh;
  213643. hints->x = wx;
  213644. hints->y = wy;
  213645. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  213646. {
  213647. hints->min_width = hints->max_width = hints->width;
  213648. hints->min_height = hints->max_height = hints->height;
  213649. hints->flags |= PMinSize | PMaxSize;
  213650. }
  213651. XSetWMNormalHints (display, windowH, hints);
  213652. XFree (hints);
  213653. XMoveResizeWindow (display, windowH,
  213654. wx - windowBorder.getLeft(),
  213655. wy - windowBorder.getTop(), ww, wh);
  213656. if (! deletionChecker.hasBeenDeleted())
  213657. {
  213658. updateBorderSize();
  213659. handleMovedOrResized();
  213660. }
  213661. }
  213662. }
  213663. void getBounds (int& x, int& y, int& w, int& h) const
  213664. {
  213665. x = wx;
  213666. y = wy;
  213667. w = ww;
  213668. h = wh;
  213669. }
  213670. int getScreenX() const
  213671. {
  213672. return wx;
  213673. }
  213674. int getScreenY() const
  213675. {
  213676. return wy;
  213677. }
  213678. void relativePositionToGlobal (int& x, int& y)
  213679. {
  213680. x += wx;
  213681. y += wy;
  213682. }
  213683. void globalPositionToRelative (int& x, int& y)
  213684. {
  213685. x -= wx;
  213686. y -= wy;
  213687. }
  213688. void setMinimised (bool shouldBeMinimised)
  213689. {
  213690. if (shouldBeMinimised)
  213691. {
  213692. Window root = RootWindow (display, DefaultScreen (display));
  213693. XClientMessageEvent clientMsg;
  213694. clientMsg.display = display;
  213695. clientMsg.window = windowH;
  213696. clientMsg.type = ClientMessage;
  213697. clientMsg.format = 32;
  213698. clientMsg.message_type = wm_ChangeState;
  213699. clientMsg.data.l[0] = IconicState;
  213700. XSendEvent (display, root, false,
  213701. SubstructureRedirectMask | SubstructureNotifyMask,
  213702. (XEvent*) &clientMsg);
  213703. }
  213704. else
  213705. {
  213706. setVisible (true);
  213707. }
  213708. }
  213709. bool isMinimised() const
  213710. {
  213711. bool minimised = false;
  213712. unsigned char* stateProp;
  213713. unsigned long nitems, bytesLeft;
  213714. Atom actualType;
  213715. int actualFormat;
  213716. if (XGetWindowProperty (display, windowH, wm_State, 0, 64, False,
  213717. wm_State, &actualType, &actualFormat, &nitems, &bytesLeft,
  213718. &stateProp) == Success
  213719. && actualType == wm_State
  213720. && actualFormat == 32
  213721. && nitems > 0)
  213722. {
  213723. if (((unsigned long*) stateProp)[0] == IconicState)
  213724. minimised = true;
  213725. XFree (stateProp);
  213726. }
  213727. return minimised;
  213728. }
  213729. void setFullScreen (const bool shouldBeFullScreen)
  213730. {
  213731. Rectangle r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  213732. setMinimised (false);
  213733. if (fullScreen != shouldBeFullScreen)
  213734. {
  213735. if (shouldBeFullScreen)
  213736. r = Desktop::getInstance().getMainMonitorArea();
  213737. if (! r.isEmpty())
  213738. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  213739. getComponent()->repaint();
  213740. }
  213741. }
  213742. bool isFullScreen() const
  213743. {
  213744. return fullScreen;
  213745. }
  213746. bool isChildWindowOf (Window possibleParent) const
  213747. {
  213748. Window* windowList = 0;
  213749. uint32 windowListSize = 0;
  213750. Window parent, root;
  213751. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  213752. {
  213753. if (windowList != 0)
  213754. XFree (windowList);
  213755. return parent == possibleParent;
  213756. }
  213757. return false;
  213758. }
  213759. bool isFrontWindow() const
  213760. {
  213761. Window* windowList = 0;
  213762. uint32 windowListSize = 0;
  213763. bool result = false;
  213764. Window parent, root = RootWindow (display, DefaultScreen (display));
  213765. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  213766. {
  213767. for (int i = windowListSize; --i >= 0;)
  213768. {
  213769. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  213770. if (peer != 0)
  213771. {
  213772. result = (peer == this);
  213773. break;
  213774. }
  213775. }
  213776. }
  213777. if (windowList != 0)
  213778. XFree (windowList);
  213779. return result;
  213780. }
  213781. bool contains (int x, int y, bool trueIfInAChildWindow) const
  213782. {
  213783. jassert (x >= 0 && y >= 0 && x < ww && y < wh); // should only be called for points that are actually inside the bounds
  213784. if (((unsigned int) x) >= (unsigned int) ww
  213785. || ((unsigned int) y) >= (unsigned int) wh)
  213786. return false;
  213787. bool inFront = false;
  213788. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  213789. {
  213790. Component* const c = Desktop::getInstance().getComponent (i);
  213791. if (inFront)
  213792. {
  213793. if (c->contains (x + wx - c->getScreenX(),
  213794. y + wy - c->getScreenY()))
  213795. {
  213796. return false;
  213797. }
  213798. }
  213799. else if (c == getComponent())
  213800. {
  213801. inFront = true;
  213802. }
  213803. }
  213804. if (trueIfInAChildWindow)
  213805. return true;
  213806. ::Window root, child;
  213807. unsigned int bw, depth;
  213808. int wx, wy, w, h;
  213809. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  213810. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  213811. &bw, &depth))
  213812. {
  213813. return false;
  213814. }
  213815. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  213816. return false;
  213817. return child == None;
  213818. }
  213819. const BorderSize getFrameSize() const
  213820. {
  213821. return BorderSize();
  213822. }
  213823. bool setAlwaysOnTop (bool alwaysOnTop)
  213824. {
  213825. if (windowH != 0)
  213826. {
  213827. const bool wasVisible = component->isVisible();
  213828. if (wasVisible)
  213829. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  213830. XSetWindowAttributes swa;
  213831. swa.override_redirect = alwaysOnTop ? True : False;
  213832. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  213833. if (wasVisible)
  213834. setVisible (true);
  213835. }
  213836. return true;
  213837. }
  213838. void toFront (bool makeActive)
  213839. {
  213840. if (makeActive)
  213841. {
  213842. setVisible (true);
  213843. grabFocus();
  213844. }
  213845. XEvent ev;
  213846. ev.xclient.type = ClientMessage;
  213847. ev.xclient.serial = 0;
  213848. ev.xclient.send_event = True;
  213849. ev.xclient.message_type = wm_ActiveWin;
  213850. ev.xclient.window = windowH;
  213851. ev.xclient.format = 32;
  213852. ev.xclient.data.l[0] = 2;
  213853. ev.xclient.data.l[1] = CurrentTime;
  213854. ev.xclient.data.l[2] = 0;
  213855. ev.xclient.data.l[3] = 0;
  213856. ev.xclient.data.l[4] = 0;
  213857. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  213858. False,
  213859. SubstructureRedirectMask | SubstructureNotifyMask,
  213860. &ev);
  213861. XWindowAttributes attr;
  213862. XGetWindowAttributes (display, windowH, &attr);
  213863. if (attr.override_redirect)
  213864. XRaiseWindow (display, windowH);
  213865. XSync (display, False);
  213866. handleBroughtToFront();
  213867. }
  213868. void toBehind (ComponentPeer* other)
  213869. {
  213870. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  213871. jassert (otherPeer != 0); // wrong type of window?
  213872. if (otherPeer != 0)
  213873. {
  213874. setMinimised (false);
  213875. Window newStack[] = { otherPeer->windowH, windowH };
  213876. XRestackWindows (display, newStack, 2);
  213877. }
  213878. }
  213879. bool isFocused() const
  213880. {
  213881. int revert;
  213882. Window focusedWindow = 0;
  213883. XGetInputFocus (display, &focusedWindow, &revert);
  213884. return focusedWindow == windowH;
  213885. }
  213886. void grabFocus()
  213887. {
  213888. XWindowAttributes atts;
  213889. if (windowH != 0
  213890. && XGetWindowAttributes (display, windowH, &atts)
  213891. && atts.map_state == IsViewable
  213892. && ! isFocused())
  213893. {
  213894. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  213895. isActiveApplication = true;
  213896. }
  213897. }
  213898. void textInputRequired (int /*x*/, int /*y*/)
  213899. {
  213900. }
  213901. void repaint (int x, int y, int w, int h)
  213902. {
  213903. if (Rectangle::intersectRectangles (x, y, w, h,
  213904. 0, 0,
  213905. getComponent()->getWidth(),
  213906. getComponent()->getHeight()))
  213907. {
  213908. repainter->repaint (x, y, w, h);
  213909. }
  213910. }
  213911. void performAnyPendingRepaintsNow()
  213912. {
  213913. repainter->performAnyPendingRepaintsNow();
  213914. }
  213915. void setIcon (const Image& newIcon)
  213916. {
  213917. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  213918. unsigned long* const data = (unsigned long*) juce_malloc (dataSize * sizeof (uint32));
  213919. int index = 0;
  213920. data[index++] = newIcon.getWidth();
  213921. data[index++] = newIcon.getHeight();
  213922. for (int y = 0; y < newIcon.getHeight(); ++y)
  213923. for (int x = 0; x < newIcon.getWidth(); ++x)
  213924. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  213925. XChangeProperty (display, windowH,
  213926. XInternAtom (display, "_NET_WM_ICON", False),
  213927. XA_CARDINAL, 32, PropModeReplace,
  213928. (unsigned char*) data, dataSize);
  213929. juce_free (data);
  213930. deleteIconPixmaps();
  213931. XWMHints* wmHints = XGetWMHints (display, windowH);
  213932. if (wmHints == 0)
  213933. wmHints = XAllocWMHints();
  213934. wmHints->flags |= IconPixmapHint | IconMaskHint;
  213935. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  213936. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  213937. XSetWMHints (display, windowH, wmHints);
  213938. XFree (wmHints);
  213939. XSync (display, False);
  213940. }
  213941. void deleteIconPixmaps()
  213942. {
  213943. XWMHints* wmHints = XGetWMHints (display, windowH);
  213944. if (wmHints != 0)
  213945. {
  213946. if ((wmHints->flags & IconPixmapHint) != 0)
  213947. {
  213948. wmHints->flags &= ~IconPixmapHint;
  213949. XFreePixmap (display, wmHints->icon_pixmap);
  213950. }
  213951. if ((wmHints->flags & IconMaskHint) != 0)
  213952. {
  213953. wmHints->flags &= ~IconMaskHint;
  213954. XFreePixmap (display, wmHints->icon_mask);
  213955. }
  213956. XSetWMHints (display, windowH, wmHints);
  213957. XFree (wmHints);
  213958. }
  213959. }
  213960. void handleWindowMessage (XEvent* event)
  213961. {
  213962. switch (event->xany.type)
  213963. {
  213964. case 2: // 'KeyPress'
  213965. {
  213966. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  213967. updateKeyStates (keyEvent->keycode, true);
  213968. char utf8 [64];
  213969. zeromem (utf8, sizeof (utf8));
  213970. KeySym sym;
  213971. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  213972. const juce_wchar unicodeChar = *(const juce_wchar*) String::fromUTF8 ((const uint8*) utf8, sizeof (utf8) - 1);
  213973. int keyCode = (int) unicodeChar;
  213974. if (keyCode < 0x20)
  213975. keyCode = XKeycodeToKeysym (display, keyEvent->keycode,
  213976. (currentModifiers & ModifierKeys::shiftModifier) != 0 ? 1 : 0);
  213977. const int oldMods = currentModifiers;
  213978. bool keyPressed = false;
  213979. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  213980. if ((sym & 0xff00) == 0xff00)
  213981. {
  213982. // Translate keypad
  213983. if (sym == XK_KP_Divide)
  213984. keyCode = XK_slash;
  213985. else if (sym == XK_KP_Multiply)
  213986. keyCode = XK_asterisk;
  213987. else if (sym == XK_KP_Subtract)
  213988. keyCode = XK_hyphen;
  213989. else if (sym == XK_KP_Add)
  213990. keyCode = XK_plus;
  213991. else if (sym == XK_KP_Enter)
  213992. keyCode = XK_Return;
  213993. else if (sym == XK_KP_Decimal)
  213994. keyCode = numLock ? XK_period : XK_Delete;
  213995. else if (sym == XK_KP_0)
  213996. keyCode = numLock ? XK_0 : XK_Insert;
  213997. else if (sym == XK_KP_1)
  213998. keyCode = numLock ? XK_1 : XK_End;
  213999. else if (sym == XK_KP_2)
  214000. keyCode = numLock ? XK_2 : XK_Down;
  214001. else if (sym == XK_KP_3)
  214002. keyCode = numLock ? XK_3 : XK_Page_Down;
  214003. else if (sym == XK_KP_4)
  214004. keyCode = numLock ? XK_4 : XK_Left;
  214005. else if (sym == XK_KP_5)
  214006. keyCode = XK_5;
  214007. else if (sym == XK_KP_6)
  214008. keyCode = numLock ? XK_6 : XK_Right;
  214009. else if (sym == XK_KP_7)
  214010. keyCode = numLock ? XK_7 : XK_Home;
  214011. else if (sym == XK_KP_8)
  214012. keyCode = numLock ? XK_8 : XK_Up;
  214013. else if (sym == XK_KP_9)
  214014. keyCode = numLock ? XK_9 : XK_Page_Up;
  214015. switch (sym)
  214016. {
  214017. case XK_Left:
  214018. case XK_Right:
  214019. case XK_Up:
  214020. case XK_Down:
  214021. case XK_Page_Up:
  214022. case XK_Page_Down:
  214023. case XK_End:
  214024. case XK_Home:
  214025. case XK_Delete:
  214026. case XK_Insert:
  214027. keyPressed = true;
  214028. keyCode = (sym & 0xff) | extendedKeyModifier;
  214029. break;
  214030. case XK_Tab:
  214031. case XK_Return:
  214032. case XK_Escape:
  214033. case XK_BackSpace:
  214034. keyPressed = true;
  214035. keyCode &= 0xff;
  214036. break;
  214037. default:
  214038. {
  214039. if (sym >= XK_F1 && sym <= XK_F16)
  214040. {
  214041. keyPressed = true;
  214042. keyCode = (sym & 0xff) | extendedKeyModifier;
  214043. }
  214044. break;
  214045. }
  214046. }
  214047. }
  214048. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  214049. keyPressed = true;
  214050. if (oldMods != currentModifiers)
  214051. handleModifierKeysChange();
  214052. if (keyDownChange)
  214053. handleKeyUpOrDown (true);
  214054. if (keyPressed)
  214055. handleKeyPress (keyCode, unicodeChar);
  214056. break;
  214057. }
  214058. case KeyRelease:
  214059. {
  214060. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  214061. updateKeyStates (keyEvent->keycode, false);
  214062. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  214063. const int oldMods = currentModifiers;
  214064. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  214065. if (oldMods != currentModifiers)
  214066. handleModifierKeysChange();
  214067. if (keyDownChange)
  214068. handleKeyUpOrDown (false);
  214069. break;
  214070. }
  214071. case ButtonPress:
  214072. {
  214073. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  214074. bool buttonMsg = false;
  214075. bool wheelUpMsg = false;
  214076. bool wheelDownMsg = false;
  214077. const int map = pointerMap [buttonPressEvent->button - Button1];
  214078. if (map == LeftButton)
  214079. {
  214080. currentModifiers |= ModifierKeys::leftButtonModifier;
  214081. buttonMsg = true;
  214082. }
  214083. else if (map == RightButton)
  214084. {
  214085. currentModifiers |= ModifierKeys::rightButtonModifier;
  214086. buttonMsg = true;
  214087. }
  214088. else if (map == MiddleButton)
  214089. {
  214090. currentModifiers |= ModifierKeys::middleButtonModifier;
  214091. buttonMsg = true;
  214092. }
  214093. else if (map == WheelUp)
  214094. {
  214095. wheelUpMsg = true;
  214096. }
  214097. else if (map == WheelDown)
  214098. {
  214099. wheelDownMsg = true;
  214100. }
  214101. updateKeyModifiers (buttonPressEvent->state);
  214102. if (buttonMsg)
  214103. {
  214104. toFront (true);
  214105. handleMouseDown (buttonPressEvent->x, buttonPressEvent->y,
  214106. getEventTime (buttonPressEvent->time));
  214107. }
  214108. else if (wheelUpMsg || wheelDownMsg)
  214109. {
  214110. handleMouseWheel (0, wheelDownMsg ? -84 : 84,
  214111. getEventTime (buttonPressEvent->time));
  214112. }
  214113. lastMousePosX = lastMousePosY = 0x100000;
  214114. break;
  214115. }
  214116. case ButtonRelease:
  214117. {
  214118. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  214119. const int oldModifiers = currentModifiers;
  214120. const int map = pointerMap [buttonRelEvent->button - Button1];
  214121. if (map == LeftButton)
  214122. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  214123. else if (map == RightButton)
  214124. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  214125. else if (map == MiddleButton)
  214126. currentModifiers &= ~ModifierKeys::middleButtonModifier;
  214127. updateKeyModifiers (buttonRelEvent->state);
  214128. handleMouseUp (oldModifiers,
  214129. buttonRelEvent->x, buttonRelEvent->y,
  214130. getEventTime (buttonRelEvent->time));
  214131. lastMousePosX = lastMousePosY = 0x100000;
  214132. break;
  214133. }
  214134. case MotionNotify:
  214135. {
  214136. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  214137. updateKeyModifiers (movedEvent->state);
  214138. int x, y, mouseMods;
  214139. getMousePos (x, y, mouseMods);
  214140. if (lastMousePosX != x || lastMousePosY != y)
  214141. {
  214142. lastMousePosX = x;
  214143. lastMousePosY = y;
  214144. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  214145. {
  214146. Window wRoot = 0, wParent = 0;
  214147. Window* wChild = 0;
  214148. unsigned int numChildren;
  214149. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  214150. if (wParent != 0
  214151. && wParent != windowH
  214152. && wParent != wRoot)
  214153. {
  214154. parentWindow = wParent;
  214155. updateBounds();
  214156. x -= getScreenX();
  214157. y -= getScreenY();
  214158. }
  214159. else
  214160. {
  214161. parentWindow = 0;
  214162. x -= getScreenX();
  214163. y -= getScreenY();
  214164. }
  214165. }
  214166. else
  214167. {
  214168. x -= getScreenX();
  214169. y -= getScreenY();
  214170. }
  214171. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0)
  214172. handleMouseMove (x, y, getEventTime (movedEvent->time));
  214173. else
  214174. handleMouseDrag (x, y, getEventTime (movedEvent->time));
  214175. }
  214176. break;
  214177. }
  214178. case EnterNotify:
  214179. {
  214180. lastMousePosX = lastMousePosY = 0x100000;
  214181. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  214182. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  214183. && ! entered)
  214184. {
  214185. updateKeyModifiers (enterEvent->state);
  214186. handleMouseEnter (enterEvent->x, enterEvent->y, getEventTime (enterEvent->time));
  214187. entered = true;
  214188. }
  214189. break;
  214190. }
  214191. case LeaveNotify:
  214192. {
  214193. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  214194. // Suppress the normal leave if we've got a pointer grab, or if
  214195. // it's a bogus one caused by clicking a mouse button when running
  214196. // in a Window manager
  214197. if (((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  214198. && leaveEvent->mode == NotifyNormal)
  214199. || leaveEvent->mode == NotifyUngrab)
  214200. {
  214201. updateKeyModifiers (leaveEvent->state);
  214202. handleMouseExit (leaveEvent->x, leaveEvent->y, getEventTime (leaveEvent->time));
  214203. entered = false;
  214204. }
  214205. break;
  214206. }
  214207. case FocusIn:
  214208. {
  214209. isActiveApplication = true;
  214210. if (isFocused())
  214211. handleFocusGain();
  214212. break;
  214213. }
  214214. case FocusOut:
  214215. {
  214216. isActiveApplication = false;
  214217. if (! isFocused())
  214218. handleFocusLoss();
  214219. break;
  214220. }
  214221. case Expose:
  214222. {
  214223. // Batch together all pending expose events
  214224. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  214225. XEvent nextEvent;
  214226. if (exposeEvent->window != windowH)
  214227. {
  214228. Window child;
  214229. XTranslateCoordinates (display, exposeEvent->window, windowH,
  214230. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  214231. &child);
  214232. }
  214233. repaint (exposeEvent->x, exposeEvent->y,
  214234. exposeEvent->width, exposeEvent->height);
  214235. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  214236. {
  214237. XPeekEvent (display, (XEvent*) &nextEvent);
  214238. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  214239. break;
  214240. XNextEvent (display, (XEvent*) &nextEvent);
  214241. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  214242. repaint (nextExposeEvent->x, nextExposeEvent->y,
  214243. nextExposeEvent->width, nextExposeEvent->height);
  214244. }
  214245. break;
  214246. }
  214247. case CirculateNotify:
  214248. case CreateNotify:
  214249. case DestroyNotify:
  214250. // Think we can ignore these
  214251. break;
  214252. case ConfigureNotify:
  214253. {
  214254. updateBounds();
  214255. updateBorderSize();
  214256. handleMovedOrResized();
  214257. // if the native title bar is dragged, need to tell any active menus, etc.
  214258. if ((styleFlags & windowHasTitleBar) != 0
  214259. && component->isCurrentlyBlockedByAnotherModalComponent())
  214260. {
  214261. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  214262. if (currentModalComp != 0)
  214263. currentModalComp->inputAttemptWhenModal();
  214264. }
  214265. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  214266. if (confEvent->window == windowH
  214267. && confEvent->above != 0
  214268. && isFrontWindow())
  214269. {
  214270. handleBroughtToFront();
  214271. }
  214272. break;
  214273. }
  214274. case ReparentNotify:
  214275. case GravityNotify:
  214276. {
  214277. parentWindow = 0;
  214278. Window wRoot = 0;
  214279. Window* wChild = 0;
  214280. unsigned int numChildren;
  214281. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  214282. if (parentWindow == windowH || parentWindow == wRoot)
  214283. parentWindow = 0;
  214284. updateBounds();
  214285. updateBorderSize();
  214286. handleMovedOrResized();
  214287. break;
  214288. }
  214289. case MapNotify:
  214290. mapped = true;
  214291. handleBroughtToFront();
  214292. break;
  214293. case UnmapNotify:
  214294. mapped = false;
  214295. break;
  214296. case MappingNotify:
  214297. {
  214298. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  214299. if (mappingEvent->request != MappingPointer)
  214300. {
  214301. // Deal with modifier/keyboard mapping
  214302. XRefreshKeyboardMapping (mappingEvent);
  214303. getModifierMapping();
  214304. }
  214305. break;
  214306. }
  214307. case ClientMessage:
  214308. {
  214309. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  214310. if (clientMsg->message_type == wm_Protocols && clientMsg->format == 32)
  214311. {
  214312. const Atom atom = (Atom) clientMsg->data.l[0];
  214313. if (atom == wm_ProtocolList [TAKE_FOCUS])
  214314. {
  214315. XWindowAttributes atts;
  214316. if (clientMsg->window != 0
  214317. && XGetWindowAttributes (display, clientMsg->window, &atts))
  214318. {
  214319. if (atts.map_state == IsViewable)
  214320. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  214321. }
  214322. }
  214323. else if (atom == wm_ProtocolList [DELETE_WINDOW])
  214324. {
  214325. handleUserClosingWindow();
  214326. }
  214327. }
  214328. else if (clientMsg->message_type == XA_XdndEnter)
  214329. {
  214330. handleDragAndDropEnter (clientMsg);
  214331. }
  214332. else if (clientMsg->message_type == XA_XdndLeave)
  214333. {
  214334. resetDragAndDrop();
  214335. }
  214336. else if (clientMsg->message_type == XA_XdndPosition)
  214337. {
  214338. handleDragAndDropPosition (clientMsg);
  214339. }
  214340. else if (clientMsg->message_type == XA_XdndDrop)
  214341. {
  214342. handleDragAndDropDrop (clientMsg);
  214343. }
  214344. else if (clientMsg->message_type == XA_XdndStatus)
  214345. {
  214346. handleDragAndDropStatus (clientMsg);
  214347. }
  214348. else if (clientMsg->message_type == XA_XdndFinished)
  214349. {
  214350. resetDragAndDrop();
  214351. }
  214352. break;
  214353. }
  214354. case SelectionNotify:
  214355. handleDragAndDropSelection (event);
  214356. break;
  214357. case SelectionClear:
  214358. case SelectionRequest:
  214359. break;
  214360. default:
  214361. break;
  214362. }
  214363. }
  214364. void showMouseCursor (Cursor cursor) throw()
  214365. {
  214366. XDefineCursor (display, windowH, cursor);
  214367. }
  214368. void setTaskBarIcon (const Image& image)
  214369. {
  214370. deleteTaskBarIcon();
  214371. taskbarImage = image.createCopy();
  214372. Screen* const screen = XDefaultScreenOfDisplay (display);
  214373. const int screenNumber = XScreenNumberOfScreen (screen);
  214374. char screenAtom[32];
  214375. snprintf (screenAtom, sizeof (screenAtom), "_NET_SYSTEM_TRAY_S%d", screenNumber);
  214376. Atom selectionAtom = XInternAtom (display, screenAtom, false);
  214377. XGrabServer (display);
  214378. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  214379. if (managerWin != None)
  214380. XSelectInput (display, managerWin, StructureNotifyMask);
  214381. XUngrabServer (display);
  214382. XFlush (display);
  214383. if (managerWin != None)
  214384. {
  214385. XEvent ev;
  214386. zerostruct (ev);
  214387. ev.xclient.type = ClientMessage;
  214388. ev.xclient.window = managerWin;
  214389. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  214390. ev.xclient.format = 32;
  214391. ev.xclient.data.l[0] = CurrentTime;
  214392. ev.xclient.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK;
  214393. ev.xclient.data.l[2] = windowH;
  214394. ev.xclient.data.l[3] = 0;
  214395. ev.xclient.data.l[4] = 0;
  214396. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  214397. XSync (display, False);
  214398. }
  214399. // For older KDE's ...
  214400. long atomData = 1;
  214401. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  214402. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  214403. // For more recent KDE's...
  214404. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  214405. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  214406. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  214407. XSizeHints* hints = XAllocSizeHints();
  214408. hints->flags = PMinSize;
  214409. hints->min_width = 22;
  214410. hints->min_height = 22;
  214411. XSetWMNormalHints (display, windowH, hints);
  214412. XFree (hints);
  214413. }
  214414. void deleteTaskBarIcon()
  214415. {
  214416. deleteAndZero (taskbarImage);
  214417. }
  214418. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  214419. juce_UseDebuggingNewOperator
  214420. bool dontRepaint;
  214421. private:
  214422. class LinuxRepaintManager : public Timer
  214423. {
  214424. public:
  214425. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  214426. : peer (peer_),
  214427. image (0),
  214428. lastTimeImageUsed (0)
  214429. {
  214430. #if JUCE_USE_XSHM
  214431. useARGBImagesForRendering = isShmAvailable();
  214432. if (useARGBImagesForRendering)
  214433. {
  214434. XShmSegmentInfo segmentinfo;
  214435. XImage* const testImage
  214436. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  214437. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  214438. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  214439. XDestroyImage (testImage);
  214440. }
  214441. #endif
  214442. }
  214443. ~LinuxRepaintManager()
  214444. {
  214445. delete image;
  214446. }
  214447. void timerCallback()
  214448. {
  214449. if (! regionsNeedingRepaint.isEmpty())
  214450. {
  214451. stopTimer();
  214452. performAnyPendingRepaintsNow();
  214453. }
  214454. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  214455. {
  214456. stopTimer();
  214457. deleteAndZero (image);
  214458. }
  214459. }
  214460. void repaint (int x, int y, int w, int h)
  214461. {
  214462. if (! isTimerRunning())
  214463. startTimer (repaintTimerPeriod);
  214464. regionsNeedingRepaint.add (x, y, w, h);
  214465. }
  214466. void performAnyPendingRepaintsNow()
  214467. {
  214468. peer->clearMaskedRegion();
  214469. const Rectangle totalArea (regionsNeedingRepaint.getBounds());
  214470. if (! totalArea.isEmpty())
  214471. {
  214472. if (image == 0 || image->getWidth() < totalArea.getWidth()
  214473. || image->getHeight() < totalArea.getHeight())
  214474. {
  214475. delete image;
  214476. #if JUCE_USE_XSHM
  214477. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  214478. : Image::RGB,
  214479. #else
  214480. image = new XBitmapImage (Image::RGB,
  214481. #endif
  214482. (totalArea.getWidth() + 31) & ~31,
  214483. (totalArea.getHeight() + 31) & ~31,
  214484. false,
  214485. peer->depthIs16Bit);
  214486. }
  214487. startTimer (repaintTimerPeriod);
  214488. LowLevelGraphicsSoftwareRenderer context (*image);
  214489. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  214490. if (context.reduceClipRegion (regionsNeedingRepaint))
  214491. peer->handlePaint (context);
  214492. if (! peer->maskedRegion.isEmpty())
  214493. regionsNeedingRepaint.subtract (peer->maskedRegion);
  214494. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  214495. {
  214496. const Rectangle& r = *i.getRectangle();
  214497. image->blitToWindow (peer->windowH,
  214498. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  214499. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  214500. }
  214501. }
  214502. regionsNeedingRepaint.clear();
  214503. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  214504. startTimer (repaintTimerPeriod);
  214505. }
  214506. private:
  214507. LinuxComponentPeer* const peer;
  214508. XBitmapImage* image;
  214509. uint32 lastTimeImageUsed;
  214510. RectangleList regionsNeedingRepaint;
  214511. #if JUCE_USE_XSHM
  214512. bool useARGBImagesForRendering;
  214513. #endif
  214514. LinuxRepaintManager (const LinuxRepaintManager&);
  214515. const LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  214516. };
  214517. LinuxRepaintManager* repainter;
  214518. friend class LinuxRepaintManager;
  214519. Window windowH, parentWindow;
  214520. int wx, wy, ww, wh;
  214521. Image* taskbarImage;
  214522. bool fullScreen, entered, mapped, depthIs16Bit;
  214523. BorderSize windowBorder;
  214524. void removeWindowDecorations (Window wndH)
  214525. {
  214526. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  214527. if (hints != None)
  214528. {
  214529. typedef struct
  214530. {
  214531. unsigned long flags;
  214532. unsigned long functions;
  214533. unsigned long decorations;
  214534. long input_mode;
  214535. unsigned long status;
  214536. } MotifWmHints;
  214537. MotifWmHints motifHints;
  214538. zerostruct (motifHints);
  214539. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  214540. motifHints.decorations = 0;
  214541. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  214542. (unsigned char*) &motifHints, 4);
  214543. }
  214544. hints = XInternAtom (display, "_WIN_HINTS", True);
  214545. if (hints != None)
  214546. {
  214547. long gnomeHints = 0;
  214548. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  214549. (unsigned char*) &gnomeHints, 1);
  214550. }
  214551. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  214552. if (hints != None)
  214553. {
  214554. long kwmHints = 2; /*KDE_tinyDecoration*/
  214555. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  214556. (unsigned char*) &kwmHints, 1);
  214557. }
  214558. hints = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  214559. if (hints != None)
  214560. {
  214561. int netHints [2];
  214562. int numHints = 0;
  214563. if ((styleFlags & windowIsTemporary) != 0)
  214564. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_MENU", True);
  214565. else
  214566. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  214567. if (netHints [numHints] != 0)
  214568. ++numHints;
  214569. netHints[numHints] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  214570. if (netHints [numHints] != 0)
  214571. ++numHints;
  214572. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  214573. (unsigned char*) &netHints, numHints);
  214574. }
  214575. }
  214576. void addWindowButtons (Window wndH)
  214577. {
  214578. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  214579. if (hints != None)
  214580. {
  214581. typedef struct
  214582. {
  214583. unsigned long flags;
  214584. unsigned long functions;
  214585. unsigned long decorations;
  214586. long input_mode;
  214587. unsigned long status;
  214588. } MotifWmHints;
  214589. MotifWmHints motifHints;
  214590. zerostruct (motifHints);
  214591. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  214592. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  214593. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  214594. if ((styleFlags & windowHasCloseButton) != 0)
  214595. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  214596. if ((styleFlags & windowHasMinimiseButton) != 0)
  214597. {
  214598. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  214599. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  214600. }
  214601. if ((styleFlags & windowHasMaximiseButton) != 0)
  214602. {
  214603. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  214604. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  214605. }
  214606. if ((styleFlags & windowIsResizable) != 0)
  214607. {
  214608. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  214609. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  214610. }
  214611. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  214612. }
  214613. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  214614. if (hints != None)
  214615. {
  214616. int netHints [6];
  214617. int num = 0;
  214618. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  214619. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  214620. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  214621. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  214622. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  214623. (unsigned char*) &netHints, num);
  214624. }
  214625. }
  214626. void createWindow()
  214627. {
  214628. static bool atomsInitialised = false;
  214629. if (! atomsInitialised)
  214630. {
  214631. atomsInitialised = true;
  214632. wm_Protocols = XInternAtom (display, "WM_PROTOCOLS", 1);
  214633. wm_ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", 1);
  214634. wm_ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", 1);
  214635. wm_ChangeState = XInternAtom (display, "WM_CHANGE_STATE", 1);
  214636. wm_State = XInternAtom (display, "WM_STATE", 1);
  214637. wm_ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  214638. XA_XdndAware = XInternAtom (display, "XdndAware", 0);
  214639. XA_XdndEnter = XInternAtom (display, "XdndEnter", 0);
  214640. XA_XdndLeave = XInternAtom (display, "XdndLeave", 0);
  214641. XA_XdndPosition = XInternAtom (display, "XdndPosition", 0);
  214642. XA_XdndStatus = XInternAtom (display, "XdndStatus", 0);
  214643. XA_XdndDrop = XInternAtom (display, "XdndDrop", 0);
  214644. XA_XdndFinished = XInternAtom (display, "XdndFinished", 0);
  214645. XA_XdndSelection = XInternAtom (display, "XdndSelection", 0);
  214646. XA_XdndProxy = XInternAtom (display, "XdndProxy", 0);
  214647. XA_XdndTypeList = XInternAtom (display, "XdndTypeList", 0);
  214648. XA_XdndActionList = XInternAtom (display, "XdndActionList", 0);
  214649. XA_XdndActionCopy = XInternAtom (display, "XdndActionCopy", 0);
  214650. XA_XdndActionMove = XInternAtom (display, "XdndActionMove", 0);
  214651. XA_XdndActionLink = XInternAtom (display, "XdndActionLink", 0);
  214652. XA_XdndActionAsk = XInternAtom (display, "XdndActionAsk", 0);
  214653. XA_XdndActionPrivate = XInternAtom (display, "XdndActionPrivate", 0);
  214654. XA_XdndActionDescription = XInternAtom (display, "XdndActionDescription", 0);
  214655. XA_JXSelectionWindowProperty = XInternAtom (display, "JXSelectionWindowProperty", 0);
  214656. XA_MimeTextPlain = XInternAtom (display, "text/plain", 0);
  214657. XA_MimeTextUriList = XInternAtom (display, "text/uri-list", 0);
  214658. XA_MimeRootDrop = XInternAtom (display, "application/x-rootwindow-drop", 0);
  214659. }
  214660. resetDragAndDrop();
  214661. XA_OtherMime = XA_MimeTextPlain; // xxx why??
  214662. allowedMimeTypeAtoms [0] = XA_MimeTextPlain;
  214663. allowedMimeTypeAtoms [1] = XA_OtherMime;
  214664. allowedMimeTypeAtoms [2] = XA_MimeTextUriList;
  214665. allowedActions [0] = XA_XdndActionMove;
  214666. allowedActions [1] = XA_XdndActionCopy;
  214667. allowedActions [2] = XA_XdndActionLink;
  214668. allowedActions [3] = XA_XdndActionAsk;
  214669. allowedActions [4] = XA_XdndActionPrivate;
  214670. // Get defaults for various properties
  214671. const int screen = DefaultScreen (display);
  214672. Window root = RootWindow (display, screen);
  214673. // Attempt to create a 24-bit window on the default screen. If this is not
  214674. // possible then exit
  214675. XVisualInfo desiredVisual;
  214676. desiredVisual.screen = screen;
  214677. desiredVisual.depth = 24;
  214678. depthIs16Bit = false;
  214679. int numVisuals;
  214680. XVisualInfo* visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  214681. &desiredVisual, &numVisuals);
  214682. if (numVisuals < 1 || visuals == 0)
  214683. {
  214684. XFree (visuals);
  214685. desiredVisual.depth = 16;
  214686. visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  214687. &desiredVisual, &numVisuals);
  214688. if (numVisuals < 1 || visuals == 0)
  214689. {
  214690. Logger::outputDebugString ("ERROR: System doesn't support 24 or 16 bit RGB display.\n");
  214691. Process::terminate();
  214692. }
  214693. depthIs16Bit = true;
  214694. }
  214695. XFree (visuals);
  214696. // Set up the window attributes
  214697. XSetWindowAttributes swa;
  214698. swa.border_pixel = 0;
  214699. swa.background_pixmap = None;
  214700. swa.colormap = DefaultColormap (display, screen);
  214701. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  214702. swa.event_mask = eventMask;
  214703. Window wndH = XCreateWindow (display, root,
  214704. 0, 0, 1, 1,
  214705. 0, 0, InputOutput, (Visual*) CopyFromParent,
  214706. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  214707. &swa);
  214708. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  214709. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  214710. GrabModeAsync, GrabModeAsync, None, None);
  214711. // Set the window context to identify the window handle object
  214712. if (XSaveContext (display, (XID) wndH, improbableNumber, (XPointer) this))
  214713. {
  214714. // Failed
  214715. jassertfalse
  214716. Logger::outputDebugString ("Failed to create context information for window.\n");
  214717. XDestroyWindow (display, wndH);
  214718. wndH = 0;
  214719. }
  214720. // Set window manager hints
  214721. XWMHints* wmHints = XAllocWMHints();
  214722. wmHints->flags = InputHint | StateHint;
  214723. wmHints->input = True; // Locally active input model
  214724. wmHints->initial_state = NormalState;
  214725. XSetWMHints (display, wndH, wmHints);
  214726. XFree (wmHints);
  214727. if ((styleFlags & windowIsSemiTransparent) != 0)
  214728. {
  214729. //xxx
  214730. }
  214731. if ((styleFlags & windowAppearsOnTaskbar) != 0)
  214732. {
  214733. //xxx
  214734. }
  214735. //XSetTransientForHint (display, wndH, RootWindow (display, DefaultScreen (display)));
  214736. if ((styleFlags & windowHasTitleBar) == 0)
  214737. removeWindowDecorations (wndH);
  214738. else
  214739. addWindowButtons (wndH);
  214740. // Set window manager protocols
  214741. XChangeProperty (display, wndH, wm_Protocols, XA_ATOM, 32, PropModeReplace,
  214742. (unsigned char*) wm_ProtocolList, 2);
  214743. // Set drag and drop flags
  214744. XChangeProperty (display, wndH, XA_XdndTypeList, XA_ATOM, 32, PropModeReplace,
  214745. (const unsigned char*) allowedMimeTypeAtoms, numElementsInArray (allowedMimeTypeAtoms));
  214746. XChangeProperty (display, wndH, XA_XdndActionList, XA_ATOM, 32, PropModeReplace,
  214747. (const unsigned char*) allowedActions, numElementsInArray (allowedActions));
  214748. XChangeProperty (display, wndH, XA_XdndActionDescription, XA_STRING, 8, PropModeReplace,
  214749. (const unsigned char*) "", 0);
  214750. unsigned long dndVersion = ourDndVersion;
  214751. XChangeProperty (display, wndH, XA_XdndAware, XA_ATOM, 32, PropModeReplace,
  214752. (const unsigned char*) &dndVersion, 1);
  214753. // Set window name
  214754. setWindowTitle (wndH, getComponent()->getName());
  214755. // Initialise the pointer and keyboard mapping
  214756. // This is not the same as the logical pointer mapping the X server uses:
  214757. // we don't mess with this.
  214758. static bool mappingInitialised = false;
  214759. if (! mappingInitialised)
  214760. {
  214761. mappingInitialised = true;
  214762. const int numButtons = XGetPointerMapping (display, 0, 0);
  214763. if (numButtons == 2)
  214764. {
  214765. pointerMap[0] = LeftButton;
  214766. pointerMap[1] = RightButton;
  214767. pointerMap[2] = pointerMap[3] = pointerMap[4] = NoButton;
  214768. }
  214769. else if (numButtons >= 3)
  214770. {
  214771. pointerMap[0] = LeftButton;
  214772. pointerMap[1] = MiddleButton;
  214773. pointerMap[2] = RightButton;
  214774. if (numButtons >= 5)
  214775. {
  214776. pointerMap[3] = WheelUp;
  214777. pointerMap[4] = WheelDown;
  214778. }
  214779. }
  214780. getModifierMapping();
  214781. }
  214782. windowH = wndH;
  214783. }
  214784. void destroyWindow()
  214785. {
  214786. XPointer handlePointer;
  214787. if (! XFindContext (display, (XID) windowH, improbableNumber, &handlePointer))
  214788. XDeleteContext (display, (XID) windowH, improbableNumber);
  214789. XDestroyWindow (display, windowH);
  214790. // Wait for it to complete and then remove any events for this
  214791. // window from the event queue.
  214792. XSync (display, false);
  214793. XEvent event;
  214794. while (XCheckWindowEvent (display, windowH, eventMask, &event) == True)
  214795. {}
  214796. }
  214797. static int64 getEventTime (::Time t) throw()
  214798. {
  214799. static int64 eventTimeOffset = 0x12345678;
  214800. const int64 thisMessageTime = t;
  214801. if (eventTimeOffset == 0x12345678)
  214802. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  214803. return eventTimeOffset + thisMessageTime;
  214804. }
  214805. static void setWindowTitle (Window xwin, const char* const title) throw()
  214806. {
  214807. XTextProperty nameProperty;
  214808. char* strings[] = { (char*) title };
  214809. if (XStringListToTextProperty (strings, 1, &nameProperty))
  214810. {
  214811. XSetWMName (display, xwin, &nameProperty);
  214812. XSetWMIconName (display, xwin, &nameProperty);
  214813. XFree (nameProperty.value);
  214814. }
  214815. }
  214816. void updateBorderSize()
  214817. {
  214818. if ((styleFlags & windowHasTitleBar) == 0)
  214819. {
  214820. windowBorder = BorderSize (0);
  214821. }
  214822. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  214823. {
  214824. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  214825. if (hints != None)
  214826. {
  214827. unsigned char* data = 0;
  214828. unsigned long nitems, bytesLeft;
  214829. Atom actualType;
  214830. int actualFormat;
  214831. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  214832. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  214833. &data) == Success)
  214834. {
  214835. const unsigned long* const sizes = (const unsigned long*) data;
  214836. if (actualFormat == 32)
  214837. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  214838. (int) sizes[3], (int) sizes[1]);
  214839. XFree (data);
  214840. }
  214841. }
  214842. }
  214843. }
  214844. void updateBounds()
  214845. {
  214846. jassert (windowH != 0);
  214847. if (windowH != 0)
  214848. {
  214849. Window root, child;
  214850. unsigned int bw, depth;
  214851. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  214852. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  214853. &bw, &depth))
  214854. {
  214855. wx = wy = ww = wh = 0;
  214856. }
  214857. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  214858. {
  214859. wx = wy = 0;
  214860. }
  214861. }
  214862. }
  214863. void resetDragAndDrop()
  214864. {
  214865. dragAndDropFiles.clear();
  214866. lastDropX = lastDropY = -1;
  214867. dragAndDropCurrentMimeType = 0;
  214868. dragAndDropSourceWindow = 0;
  214869. srcMimeTypeAtomList.clear();
  214870. }
  214871. void sendDragAndDropMessage (XClientMessageEvent& msg)
  214872. {
  214873. msg.type = ClientMessage;
  214874. msg.display = display;
  214875. msg.window = dragAndDropSourceWindow;
  214876. msg.format = 32;
  214877. msg.data.l[0] = windowH;
  214878. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  214879. }
  214880. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  214881. {
  214882. XClientMessageEvent msg;
  214883. zerostruct (msg);
  214884. msg.message_type = XA_XdndStatus;
  214885. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  214886. msg.data.l[4] = dropAction;
  214887. sendDragAndDropMessage (msg);
  214888. }
  214889. void sendDragAndDropLeave()
  214890. {
  214891. XClientMessageEvent msg;
  214892. zerostruct (msg);
  214893. msg.message_type = XA_XdndLeave;
  214894. sendDragAndDropMessage (msg);
  214895. }
  214896. void sendDragAndDropFinish()
  214897. {
  214898. XClientMessageEvent msg;
  214899. zerostruct (msg);
  214900. msg.message_type = XA_XdndFinished;
  214901. sendDragAndDropMessage (msg);
  214902. }
  214903. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  214904. {
  214905. if ((clientMsg->data.l[1] & 1) == 0)
  214906. {
  214907. sendDragAndDropLeave();
  214908. if (dragAndDropFiles.size() > 0)
  214909. handleFileDragExit (dragAndDropFiles);
  214910. dragAndDropFiles.clear();
  214911. }
  214912. }
  214913. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  214914. {
  214915. if (dragAndDropSourceWindow == 0)
  214916. return;
  214917. dragAndDropSourceWindow = clientMsg->data.l[0];
  214918. const int dropX = ((int) clientMsg->data.l[2] >> 16) - getScreenX();
  214919. const int dropY = ((int) clientMsg->data.l[2] & 0xffff) - getScreenY();
  214920. if (lastDropX != dropX || lastDropY != dropY)
  214921. {
  214922. lastDropX = dropX;
  214923. lastDropY = dropY;
  214924. dragAndDropTimestamp = clientMsg->data.l[3];
  214925. Atom targetAction = XA_XdndActionCopy;
  214926. for (int i = numElementsInArray (allowedActions); --i >= 0;)
  214927. {
  214928. if ((Atom) clientMsg->data.l[4] == allowedActions[i])
  214929. {
  214930. targetAction = allowedActions[i];
  214931. break;
  214932. }
  214933. }
  214934. sendDragAndDropStatus (true, targetAction);
  214935. if (dragAndDropFiles.size() == 0)
  214936. updateDraggedFileList (clientMsg);
  214937. if (dragAndDropFiles.size() > 0)
  214938. handleFileDragMove (dragAndDropFiles, dropX, dropY);
  214939. }
  214940. }
  214941. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  214942. {
  214943. if (dragAndDropFiles.size() == 0)
  214944. updateDraggedFileList (clientMsg);
  214945. const StringArray files (dragAndDropFiles);
  214946. const int lastX = lastDropX, lastY = lastDropY;
  214947. sendDragAndDropFinish();
  214948. resetDragAndDrop();
  214949. if (files.size() > 0)
  214950. handleFileDragDrop (files, lastX, lastY);
  214951. }
  214952. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  214953. {
  214954. dragAndDropFiles.clear();
  214955. srcMimeTypeAtomList.clear();
  214956. dragAndDropCurrentMimeType = 0;
  214957. const int dndCurrentVersion = (int) (clientMsg->data.l[1] & 0xff000000) >> 24;
  214958. if (dndCurrentVersion < 3 || dndCurrentVersion > ourDndVersion)
  214959. {
  214960. dragAndDropSourceWindow = 0;
  214961. return;
  214962. }
  214963. dragAndDropSourceWindow = clientMsg->data.l[0];
  214964. if ((clientMsg->data.l[1] & 1) != 0)
  214965. {
  214966. Atom actual;
  214967. int format;
  214968. unsigned long count = 0, remaining = 0;
  214969. unsigned char* data = 0;
  214970. XGetWindowProperty (display, dragAndDropSourceWindow, XA_XdndTypeList,
  214971. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  214972. &count, &remaining, &data);
  214973. if (data != 0)
  214974. {
  214975. if (actual == XA_ATOM && format == 32 && count != 0)
  214976. {
  214977. const unsigned long* const types = (const unsigned long*) data;
  214978. for (unsigned int i = 0; i < count; ++i)
  214979. if (types[i] != None)
  214980. srcMimeTypeAtomList.add (types[i]);
  214981. }
  214982. XFree (data);
  214983. }
  214984. }
  214985. if (srcMimeTypeAtomList.size() == 0)
  214986. {
  214987. for (int i = 2; i < 5; ++i)
  214988. if (clientMsg->data.l[i] != None)
  214989. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  214990. if (srcMimeTypeAtomList.size() == 0)
  214991. {
  214992. dragAndDropSourceWindow = 0;
  214993. return;
  214994. }
  214995. }
  214996. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  214997. for (int j = 0; j < numElementsInArray (allowedMimeTypeAtoms); ++j)
  214998. if (srcMimeTypeAtomList[i] == allowedMimeTypeAtoms[j])
  214999. dragAndDropCurrentMimeType = allowedMimeTypeAtoms[j];
  215000. handleDragAndDropPosition (clientMsg);
  215001. }
  215002. void handleDragAndDropSelection (const XEvent* const evt)
  215003. {
  215004. dragAndDropFiles.clear();
  215005. if (evt->xselection.property != 0)
  215006. {
  215007. StringArray lines;
  215008. {
  215009. MemoryBlock dropData;
  215010. for (;;)
  215011. {
  215012. Atom actual;
  215013. uint8* data = 0;
  215014. unsigned long count = 0, remaining = 0;
  215015. int format = 0;
  215016. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  215017. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  215018. &format, &count, &remaining, &data) == Success)
  215019. {
  215020. dropData.append (data, count * format / 8);
  215021. XFree (data);
  215022. if (remaining == 0)
  215023. break;
  215024. }
  215025. else
  215026. {
  215027. XFree (data);
  215028. break;
  215029. }
  215030. }
  215031. lines.addLines (dropData.toString());
  215032. }
  215033. for (int i = 0; i < lines.size(); ++i)
  215034. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf (T("file://"), false, true)));
  215035. dragAndDropFiles.trim();
  215036. dragAndDropFiles.removeEmptyStrings();
  215037. }
  215038. }
  215039. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  215040. {
  215041. dragAndDropFiles.clear();
  215042. if (dragAndDropSourceWindow != None
  215043. && dragAndDropCurrentMimeType != 0)
  215044. {
  215045. dragAndDropTimestamp = clientMsg->data.l[2];
  215046. XConvertSelection (display,
  215047. XA_XdndSelection,
  215048. dragAndDropCurrentMimeType,
  215049. XA_JXSelectionWindowProperty,
  215050. windowH,
  215051. dragAndDropTimestamp);
  215052. }
  215053. }
  215054. StringArray dragAndDropFiles;
  215055. int dragAndDropTimestamp, lastDropX, lastDropY;
  215056. Atom XA_OtherMime, dragAndDropCurrentMimeType;
  215057. Window dragAndDropSourceWindow;
  215058. unsigned int allowedActions [5];
  215059. unsigned int allowedMimeTypeAtoms [3];
  215060. Array <Atom> srcMimeTypeAtomList;
  215061. };
  215062. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  215063. {
  215064. if (enableOrDisable)
  215065. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  215066. }
  215067. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  215068. {
  215069. return new LinuxComponentPeer (this, styleFlags);
  215070. }
  215071. // (this callback is hooked up in the messaging code)
  215072. void juce_windowMessageReceive (XEvent* event)
  215073. {
  215074. if (event->xany.window != None)
  215075. {
  215076. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  215077. if (ComponentPeer::isValidPeer (peer))
  215078. peer->handleWindowMessage (event);
  215079. }
  215080. else
  215081. {
  215082. switch (event->xany.type)
  215083. {
  215084. case KeymapNotify:
  215085. {
  215086. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  215087. memcpy (keyStates, keymapEvent->key_vector, 32);
  215088. break;
  215089. }
  215090. default:
  215091. break;
  215092. }
  215093. }
  215094. }
  215095. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool /*clipToWorkArea*/) throw()
  215096. {
  215097. #if JUCE_USE_XINERAMA
  215098. int major_opcode, first_event, first_error;
  215099. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error)
  215100. && XineramaIsActive (display))
  215101. {
  215102. int numMonitors = 0;
  215103. XineramaScreenInfo* const screens = XineramaQueryScreens (display, &numMonitors);
  215104. if (screens != 0)
  215105. {
  215106. for (int i = numMonitors; --i >= 0;)
  215107. {
  215108. int index = screens[i].screen_number;
  215109. if (index >= 0)
  215110. {
  215111. while (monitorCoords.size() < index)
  215112. monitorCoords.add (Rectangle (0, 0, 0, 0));
  215113. monitorCoords.set (index, Rectangle (screens[i].x_org,
  215114. screens[i].y_org,
  215115. screens[i].width,
  215116. screens[i].height));
  215117. }
  215118. }
  215119. XFree (screens);
  215120. }
  215121. }
  215122. if (monitorCoords.size() == 0)
  215123. #endif
  215124. {
  215125. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  215126. if (hints != None)
  215127. {
  215128. const int numMonitors = ScreenCount (display);
  215129. for (int i = 0; i < numMonitors; ++i)
  215130. {
  215131. Window root = RootWindow (display, i);
  215132. unsigned long nitems, bytesLeft;
  215133. Atom actualType;
  215134. int actualFormat;
  215135. unsigned char* data = 0;
  215136. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  215137. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  215138. &data) == Success)
  215139. {
  215140. const long* const position = (const long*) data;
  215141. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  215142. monitorCoords.add (Rectangle (position[0], position[1],
  215143. position[2], position[3]));
  215144. XFree (data);
  215145. }
  215146. }
  215147. }
  215148. if (monitorCoords.size() == 0)
  215149. {
  215150. monitorCoords.add (Rectangle (0, 0,
  215151. DisplayWidth (display, DefaultScreen (display)),
  215152. DisplayHeight (display, DefaultScreen (display))));
  215153. }
  215154. }
  215155. }
  215156. bool Desktop::canUseSemiTransparentWindows() throw()
  215157. {
  215158. return false;
  215159. }
  215160. void Desktop::getMousePosition (int& x, int& y) throw()
  215161. {
  215162. int mouseMods;
  215163. getMousePos (x, y, mouseMods);
  215164. }
  215165. void Desktop::setMousePosition (int x, int y) throw()
  215166. {
  215167. Window root = RootWindow (display, DefaultScreen (display));
  215168. XWarpPointer (display, None, root, 0, 0, 0, 0, x, y);
  215169. }
  215170. static bool screenSaverAllowed = true;
  215171. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  215172. {
  215173. if (screenSaverAllowed != isEnabled)
  215174. {
  215175. screenSaverAllowed = isEnabled;
  215176. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  215177. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  215178. if (xScreenSaverSuspend == 0)
  215179. {
  215180. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  215181. if (h != 0)
  215182. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  215183. }
  215184. if (xScreenSaverSuspend != 0)
  215185. xScreenSaverSuspend (display, ! isEnabled);
  215186. }
  215187. }
  215188. bool Desktop::isScreenSaverEnabled() throw()
  215189. {
  215190. return screenSaverAllowed;
  215191. }
  215192. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  215193. {
  215194. Window root = RootWindow (display, DefaultScreen (display));
  215195. const unsigned int imageW = image.getWidth();
  215196. const unsigned int imageH = image.getHeight();
  215197. unsigned int cursorW, cursorH;
  215198. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  215199. return 0;
  215200. Image im (Image::ARGB, cursorW, cursorH, true);
  215201. Graphics g (im);
  215202. if (imageW > cursorW || imageH > cursorH)
  215203. {
  215204. hotspotX = (hotspotX * cursorW) / imageW;
  215205. hotspotY = (hotspotY * cursorH) / imageH;
  215206. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  215207. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  215208. false);
  215209. }
  215210. else
  215211. {
  215212. g.drawImageAt (&image, 0, 0);
  215213. }
  215214. const int stride = (cursorW + 7) >> 3;
  215215. uint8* const maskPlane = (uint8*) juce_calloc (stride * cursorH);
  215216. uint8* const sourcePlane = (uint8*) juce_calloc (stride * cursorH);
  215217. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  215218. for (int y = cursorH; --y >= 0;)
  215219. {
  215220. for (int x = cursorW; --x >= 0;)
  215221. {
  215222. const uint8 mask = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  215223. const int offset = y * stride + (x >> 3);
  215224. const Colour c (im.getPixelAt (x, y));
  215225. if (c.getAlpha() >= 128)
  215226. maskPlane[offset] |= mask;
  215227. if (c.getBrightness() >= 0.5f)
  215228. sourcePlane[offset] |= mask;
  215229. }
  215230. }
  215231. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, (char*) sourcePlane, cursorW, cursorH, 0xffff, 0, 1);
  215232. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, (char*) maskPlane, cursorW, cursorH, 0xffff, 0, 1);
  215233. juce_free (maskPlane);
  215234. juce_free (sourcePlane);
  215235. XColor white, black;
  215236. black.red = black.green = black.blue = 0;
  215237. white.red = white.green = white.blue = 0xffff;
  215238. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  215239. XFreePixmap (display, sourcePixmap);
  215240. XFreePixmap (display, maskPixmap);
  215241. return result;
  215242. }
  215243. void juce_deleteMouseCursor (void* const cursorHandle, const bool) throw()
  215244. {
  215245. if (cursorHandle != None)
  215246. XFreeCursor (display, (Cursor) cursorHandle);
  215247. }
  215248. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  215249. {
  215250. unsigned int shape;
  215251. switch (type)
  215252. {
  215253. case MouseCursor::NoCursor:
  215254. {
  215255. const Image im (Image::ARGB, 16, 16, true);
  215256. return juce_createMouseCursorFromImage (im, 0, 0);
  215257. }
  215258. case MouseCursor::NormalCursor:
  215259. return (void*) None; // Use parent cursor
  215260. case MouseCursor::DraggingHandCursor:
  215261. {
  215262. static unsigned char dragHandData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  215263. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  215264. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  215265. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  215266. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  215267. const int dragHandDataSize = 99;
  215268. Image* const im = ImageFileFormat::loadFrom ((const char*) dragHandData, dragHandDataSize);
  215269. void* const dragHandCursor = juce_createMouseCursorFromImage (*im, 8, 7);
  215270. delete im;
  215271. return dragHandCursor;
  215272. }
  215273. case MouseCursor::CopyingCursor:
  215274. {
  215275. static unsigned char copyCursorData[] = {71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  215276. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  215277. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  215278. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174,
  215279. 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  215280. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  215281. const int copyCursorSize = 119;
  215282. Image* const im = ImageFileFormat::loadFrom ((const char*) copyCursorData, copyCursorSize);
  215283. void* const copyCursor = juce_createMouseCursorFromImage (*im, 1, 3);
  215284. delete im;
  215285. return copyCursor;
  215286. }
  215287. case MouseCursor::WaitCursor:
  215288. shape = XC_watch;
  215289. break;
  215290. case MouseCursor::IBeamCursor:
  215291. shape = XC_xterm;
  215292. break;
  215293. case MouseCursor::PointingHandCursor:
  215294. shape = XC_hand2;
  215295. break;
  215296. case MouseCursor::LeftRightResizeCursor:
  215297. shape = XC_sb_h_double_arrow;
  215298. break;
  215299. case MouseCursor::UpDownResizeCursor:
  215300. shape = XC_sb_v_double_arrow;
  215301. break;
  215302. case MouseCursor::UpDownLeftRightResizeCursor:
  215303. shape = XC_fleur;
  215304. break;
  215305. case MouseCursor::TopEdgeResizeCursor:
  215306. shape = XC_top_side;
  215307. break;
  215308. case MouseCursor::BottomEdgeResizeCursor:
  215309. shape = XC_bottom_side;
  215310. break;
  215311. case MouseCursor::LeftEdgeResizeCursor:
  215312. shape = XC_left_side;
  215313. break;
  215314. case MouseCursor::RightEdgeResizeCursor:
  215315. shape = XC_right_side;
  215316. break;
  215317. case MouseCursor::TopLeftCornerResizeCursor:
  215318. shape = XC_top_left_corner;
  215319. break;
  215320. case MouseCursor::TopRightCornerResizeCursor:
  215321. shape = XC_top_right_corner;
  215322. break;
  215323. case MouseCursor::BottomLeftCornerResizeCursor:
  215324. shape = XC_bottom_left_corner;
  215325. break;
  215326. case MouseCursor::BottomRightCornerResizeCursor:
  215327. shape = XC_bottom_right_corner;
  215328. break;
  215329. case MouseCursor::CrosshairCursor:
  215330. shape = XC_crosshair;
  215331. break;
  215332. default:
  215333. return (void*) None; // Use parent cursor
  215334. }
  215335. return (void*) XCreateFontCursor (display, shape);
  215336. }
  215337. void MouseCursor::showInWindow (ComponentPeer* peer) const throw()
  215338. {
  215339. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  215340. if (lp != 0)
  215341. lp->showMouseCursor ((Cursor) getHandle());
  215342. }
  215343. void MouseCursor::showInAllWindows() const throw()
  215344. {
  215345. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  215346. showInWindow (ComponentPeer::getPeer (i));
  215347. }
  215348. Image* juce_createIconForFile (const File& file)
  215349. {
  215350. return 0;
  215351. }
  215352. #if JUCE_OPENGL
  215353. class WindowedGLContext : public OpenGLContext
  215354. {
  215355. public:
  215356. WindowedGLContext (Component* const component,
  215357. const OpenGLPixelFormat& pixelFormat_,
  215358. GLXContext sharedContext)
  215359. : renderContext (0),
  215360. embeddedWindow (0),
  215361. pixelFormat (pixelFormat_)
  215362. {
  215363. jassert (component != 0);
  215364. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  215365. if (peer == 0)
  215366. return;
  215367. XSync (display, False);
  215368. GLint attribs [64];
  215369. int n = 0;
  215370. attribs[n++] = GLX_RGBA;
  215371. attribs[n++] = GLX_DOUBLEBUFFER;
  215372. attribs[n++] = GLX_RED_SIZE;
  215373. attribs[n++] = pixelFormat.redBits;
  215374. attribs[n++] = GLX_GREEN_SIZE;
  215375. attribs[n++] = pixelFormat.greenBits;
  215376. attribs[n++] = GLX_BLUE_SIZE;
  215377. attribs[n++] = pixelFormat.blueBits;
  215378. attribs[n++] = GLX_ALPHA_SIZE;
  215379. attribs[n++] = pixelFormat.alphaBits;
  215380. attribs[n++] = GLX_DEPTH_SIZE;
  215381. attribs[n++] = pixelFormat.depthBufferBits;
  215382. attribs[n++] = GLX_STENCIL_SIZE;
  215383. attribs[n++] = pixelFormat.stencilBufferBits;
  215384. attribs[n++] = GLX_ACCUM_RED_SIZE;
  215385. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  215386. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  215387. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  215388. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  215389. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  215390. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  215391. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  215392. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  215393. attribs[n++] = None;
  215394. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  215395. if (bestVisual == 0)
  215396. return;
  215397. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  215398. Window windowH = (Window) peer->getNativeHandle();
  215399. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  215400. XSetWindowAttributes swa;
  215401. swa.colormap = colourMap;
  215402. swa.border_pixel = 0;
  215403. swa.event_mask = ExposureMask | StructureNotifyMask;
  215404. embeddedWindow = XCreateWindow (display, windowH,
  215405. 0, 0, 1, 1, 0,
  215406. bestVisual->depth,
  215407. InputOutput,
  215408. bestVisual->visual,
  215409. CWBorderPixel | CWColormap | CWEventMask,
  215410. &swa);
  215411. XSaveContext (display, (XID) embeddedWindow, improbableNumber, (XPointer) peer);
  215412. XMapWindow (display, embeddedWindow);
  215413. XFreeColormap (display, colourMap);
  215414. XFree (bestVisual);
  215415. XSync (display, False);
  215416. }
  215417. ~WindowedGLContext()
  215418. {
  215419. makeInactive();
  215420. glXDestroyContext (display, renderContext);
  215421. XUnmapWindow (display, embeddedWindow);
  215422. XDestroyWindow (display, embeddedWindow);
  215423. }
  215424. bool makeActive() const throw()
  215425. {
  215426. jassert (renderContext != 0);
  215427. return glXMakeCurrent (display, embeddedWindow, renderContext)
  215428. && XSync (display, False);
  215429. }
  215430. bool makeInactive() const throw()
  215431. {
  215432. return (! isActive()) || glXMakeCurrent (display, None, 0);
  215433. }
  215434. bool isActive() const throw()
  215435. {
  215436. return glXGetCurrentContext() == renderContext;
  215437. }
  215438. const OpenGLPixelFormat getPixelFormat() const
  215439. {
  215440. return pixelFormat;
  215441. }
  215442. void* getRawContext() const throw()
  215443. {
  215444. return renderContext;
  215445. }
  215446. void updateWindowPosition (int x, int y, int w, int h, int)
  215447. {
  215448. XMoveResizeWindow (display, embeddedWindow,
  215449. x, y, jmax (1, w), jmax (1, h));
  215450. }
  215451. void swapBuffers()
  215452. {
  215453. glXSwapBuffers (display, embeddedWindow);
  215454. }
  215455. bool setSwapInterval (const int numFramesPerSwap)
  215456. {
  215457. // xxx needs doing..
  215458. return false;
  215459. }
  215460. int getSwapInterval() const
  215461. {
  215462. // xxx needs doing..
  215463. return 0;
  215464. }
  215465. void repaint()
  215466. {
  215467. }
  215468. juce_UseDebuggingNewOperator
  215469. GLXContext renderContext;
  215470. private:
  215471. Window embeddedWindow;
  215472. OpenGLPixelFormat pixelFormat;
  215473. WindowedGLContext (const WindowedGLContext&);
  215474. const WindowedGLContext& operator= (const WindowedGLContext&);
  215475. };
  215476. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  215477. const OpenGLPixelFormat& pixelFormat,
  215478. const OpenGLContext* const contextToShareWith)
  215479. {
  215480. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  215481. contextToShareWith != 0 ? (GLXContext) contextToShareWith->getRawContext() : 0);
  215482. if (c->renderContext == 0)
  215483. deleteAndZero (c);
  215484. return c;
  215485. }
  215486. void juce_glViewport (const int w, const int h)
  215487. {
  215488. glViewport (0, 0, w, h);
  215489. }
  215490. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  215491. OwnedArray <OpenGLPixelFormat>& results)
  215492. {
  215493. results.add (new OpenGLPixelFormat()); // xxx
  215494. }
  215495. #endif
  215496. static void initClipboard (Window root, Atom* cutBuffers) throw()
  215497. {
  215498. static bool init = false;
  215499. if (! init)
  215500. {
  215501. init = true;
  215502. // Make sure all cut buffers exist before use
  215503. for (int i = 0; i < 8; i++)
  215504. {
  215505. XChangeProperty (display, root, cutBuffers[i],
  215506. XA_STRING, 8, PropModeAppend, NULL, 0);
  215507. }
  215508. }
  215509. }
  215510. // Clipboard implemented currently using cut buffers
  215511. // rather than the more powerful selection method
  215512. void SystemClipboard::copyTextToClipboard (const String& clipText) throw()
  215513. {
  215514. Window root = RootWindow (display, DefaultScreen (display));
  215515. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  215516. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  215517. initClipboard (root, cutBuffers);
  215518. XRotateWindowProperties (display, root, cutBuffers, 8, 1);
  215519. XChangeProperty (display, root, cutBuffers[0],
  215520. XA_STRING, 8, PropModeReplace, (const unsigned char*) (const char*) clipText,
  215521. clipText.length());
  215522. }
  215523. const String SystemClipboard::getTextFromClipboard() throw()
  215524. {
  215525. const int bufSize = 64; // in words
  215526. String returnData;
  215527. int byteOffset = 0;
  215528. Window root = RootWindow (display, DefaultScreen (display));
  215529. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  215530. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  215531. initClipboard (root, cutBuffers);
  215532. for (;;)
  215533. {
  215534. unsigned long bytesLeft = 0, nitems = 0;
  215535. unsigned char* clipData = 0;
  215536. int actualFormat = 0;
  215537. Atom actualType;
  215538. if (XGetWindowProperty (display, root, cutBuffers[0], byteOffset >> 2, bufSize,
  215539. False, XA_STRING, &actualType, &actualFormat, &nitems, &bytesLeft,
  215540. &clipData) == Success)
  215541. {
  215542. if (actualType == XA_STRING && actualFormat == 8)
  215543. {
  215544. byteOffset += nitems;
  215545. returnData += String ((const char*) clipData, nitems);
  215546. }
  215547. else
  215548. {
  215549. bytesLeft = 0;
  215550. }
  215551. if (clipData != 0)
  215552. XFree (clipData);
  215553. }
  215554. if (bytesLeft == 0)
  215555. break;
  215556. }
  215557. return returnData;
  215558. }
  215559. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  215560. {
  215561. jassertfalse // not implemented!
  215562. return false;
  215563. }
  215564. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  215565. {
  215566. jassertfalse // not implemented!
  215567. return false;
  215568. }
  215569. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  215570. {
  215571. if (! isOnDesktop ())
  215572. addToDesktop (0);
  215573. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  215574. if (wp != 0)
  215575. {
  215576. wp->setTaskBarIcon (newImage);
  215577. setVisible (true);
  215578. toFront (false);
  215579. repaint();
  215580. }
  215581. }
  215582. void SystemTrayIconComponent::paint (Graphics& g)
  215583. {
  215584. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  215585. if (wp != 0)
  215586. {
  215587. const Image* const image = wp->getTaskbarIcon();
  215588. if (image != 0)
  215589. {
  215590. g.drawImageWithin (image, 0, 0, getWidth(), getHeight(),
  215591. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  215592. false);
  215593. }
  215594. }
  215595. }
  215596. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  215597. {
  215598. // xxx not yet implemented!
  215599. }
  215600. void PlatformUtilities::beep()
  215601. {
  215602. fprintf (stdout, "\a");
  215603. fflush (stdout);
  215604. }
  215605. bool AlertWindow::showNativeDialogBox (const String& title,
  215606. const String& bodyText,
  215607. bool isOkCancel)
  215608. {
  215609. // xxx this is supposed to pop up an alert!
  215610. Logger::outputDebugString (title + ": " + bodyText);
  215611. // use a non-native one for the time being..
  215612. if (isOkCancel)
  215613. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  215614. else
  215615. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  215616. return true;
  215617. }
  215618. const int KeyPress::spaceKey = XK_space & 0xff;
  215619. const int KeyPress::returnKey = XK_Return & 0xff;
  215620. const int KeyPress::escapeKey = XK_Escape & 0xff;
  215621. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  215622. const int KeyPress::leftKey = (XK_Left & 0xff) | extendedKeyModifier;
  215623. const int KeyPress::rightKey = (XK_Right & 0xff) | extendedKeyModifier;
  215624. const int KeyPress::upKey = (XK_Up & 0xff) | extendedKeyModifier;
  215625. const int KeyPress::downKey = (XK_Down & 0xff) | extendedKeyModifier;
  215626. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | extendedKeyModifier;
  215627. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | extendedKeyModifier;
  215628. const int KeyPress::endKey = (XK_End & 0xff) | extendedKeyModifier;
  215629. const int KeyPress::homeKey = (XK_Home & 0xff) | extendedKeyModifier;
  215630. const int KeyPress::insertKey = (XK_Insert & 0xff) | extendedKeyModifier;
  215631. const int KeyPress::deleteKey = (XK_Delete & 0xff) | extendedKeyModifier;
  215632. const int KeyPress::tabKey = XK_Tab & 0xff;
  215633. const int KeyPress::F1Key = (XK_F1 & 0xff) | extendedKeyModifier;
  215634. const int KeyPress::F2Key = (XK_F2 & 0xff) | extendedKeyModifier;
  215635. const int KeyPress::F3Key = (XK_F3 & 0xff) | extendedKeyModifier;
  215636. const int KeyPress::F4Key = (XK_F4 & 0xff) | extendedKeyModifier;
  215637. const int KeyPress::F5Key = (XK_F5 & 0xff) | extendedKeyModifier;
  215638. const int KeyPress::F6Key = (XK_F6 & 0xff) | extendedKeyModifier;
  215639. const int KeyPress::F7Key = (XK_F7 & 0xff) | extendedKeyModifier;
  215640. const int KeyPress::F8Key = (XK_F8 & 0xff) | extendedKeyModifier;
  215641. const int KeyPress::F9Key = (XK_F9 & 0xff) | extendedKeyModifier;
  215642. const int KeyPress::F10Key = (XK_F10 & 0xff) | extendedKeyModifier;
  215643. const int KeyPress::F11Key = (XK_F11 & 0xff) | extendedKeyModifier;
  215644. const int KeyPress::F12Key = (XK_F12 & 0xff) | extendedKeyModifier;
  215645. const int KeyPress::F13Key = (XK_F13 & 0xff) | extendedKeyModifier;
  215646. const int KeyPress::F14Key = (XK_F14 & 0xff) | extendedKeyModifier;
  215647. const int KeyPress::F15Key = (XK_F15 & 0xff) | extendedKeyModifier;
  215648. const int KeyPress::F16Key = (XK_F16 & 0xff) | extendedKeyModifier;
  215649. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | extendedKeyModifier;
  215650. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | extendedKeyModifier;
  215651. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | extendedKeyModifier;
  215652. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | extendedKeyModifier;
  215653. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | extendedKeyModifier;
  215654. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | extendedKeyModifier;
  215655. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | extendedKeyModifier;
  215656. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| extendedKeyModifier;
  215657. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| extendedKeyModifier;
  215658. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| extendedKeyModifier;
  215659. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| extendedKeyModifier;
  215660. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| extendedKeyModifier;
  215661. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| extendedKeyModifier;
  215662. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| extendedKeyModifier;
  215663. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| extendedKeyModifier;
  215664. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| extendedKeyModifier;
  215665. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| extendedKeyModifier;
  215666. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| extendedKeyModifier;
  215667. const int KeyPress::playKey = (0xffeeff00) | extendedKeyModifier;
  215668. const int KeyPress::stopKey = (0xffeeff01) | extendedKeyModifier;
  215669. const int KeyPress::fastForwardKey = (0xffeeff02) | extendedKeyModifier;
  215670. const int KeyPress::rewindKey = (0xffeeff03) | extendedKeyModifier;
  215671. #endif
  215672. /********* End of inlined file: juce_linux_Windowing.cpp *********/
  215673. /********* Start of inlined file: juce_linux_Audio.cpp *********/
  215674. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  215675. // compiled on its own).
  215676. #ifdef JUCE_INCLUDED_FILE
  215677. #if JUCE_ALSA
  215678. static const int maxNumChans = 64;
  215679. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  215680. {
  215681. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  215682. snd_pcm_hw_params_t* hwParams;
  215683. snd_pcm_hw_params_alloca (&hwParams);
  215684. for (int i = 0; ratesToTry[i] != 0; ++i)
  215685. {
  215686. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  215687. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  215688. {
  215689. rates.addIfNotAlreadyThere (ratesToTry[i]);
  215690. }
  215691. }
  215692. }
  215693. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  215694. {
  215695. snd_pcm_hw_params_t *params;
  215696. snd_pcm_hw_params_alloca (&params);
  215697. if (snd_pcm_hw_params_any (handle, params) >= 0)
  215698. {
  215699. snd_pcm_hw_params_get_channels_min (params, minChans);
  215700. snd_pcm_hw_params_get_channels_max (params, maxChans);
  215701. }
  215702. }
  215703. static void getDeviceProperties (const String& id,
  215704. unsigned int& minChansOut,
  215705. unsigned int& maxChansOut,
  215706. unsigned int& minChansIn,
  215707. unsigned int& maxChansIn,
  215708. Array <int>& rates)
  215709. {
  215710. if (id.isEmpty())
  215711. return;
  215712. snd_ctl_t* handle;
  215713. if (snd_ctl_open (&handle, id.upToLastOccurrenceOf (T(","), false, false), SND_CTL_NONBLOCK) >= 0)
  215714. {
  215715. snd_pcm_info_t* info;
  215716. snd_pcm_info_alloca (&info);
  215717. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  215718. snd_pcm_info_set_device (info, id.fromLastOccurrenceOf (T(","), false, false).getIntValue());
  215719. snd_pcm_info_set_subdevice (info, 0);
  215720. if (snd_ctl_pcm_info (handle, info) >= 0)
  215721. {
  215722. snd_pcm_t* pcmHandle;
  215723. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  215724. {
  215725. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  215726. getDeviceSampleRates (pcmHandle, rates);
  215727. snd_pcm_close (pcmHandle);
  215728. }
  215729. }
  215730. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  215731. if (snd_ctl_pcm_info (handle, info) >= 0)
  215732. {
  215733. snd_pcm_t* pcmHandle;
  215734. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  215735. {
  215736. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  215737. if (rates.size() == 0)
  215738. getDeviceSampleRates (pcmHandle, rates);
  215739. snd_pcm_close (pcmHandle);
  215740. }
  215741. }
  215742. snd_ctl_close (handle);
  215743. }
  215744. }
  215745. class ALSADevice
  215746. {
  215747. public:
  215748. ALSADevice (const String& id,
  215749. const bool forInput)
  215750. : handle (0),
  215751. bitDepth (16),
  215752. numChannelsRunning (0),
  215753. isInput (forInput),
  215754. sampleFormat (AudioDataConverters::int16LE)
  215755. {
  215756. failed (snd_pcm_open (&handle, id,
  215757. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  215758. SND_PCM_ASYNC));
  215759. }
  215760. ~ALSADevice()
  215761. {
  215762. if (handle != 0)
  215763. snd_pcm_close (handle);
  215764. }
  215765. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  215766. {
  215767. if (handle == 0)
  215768. return false;
  215769. snd_pcm_hw_params_t* hwParams;
  215770. snd_pcm_hw_params_alloca (&hwParams);
  215771. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  215772. return false;
  215773. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  215774. isInterleaved = false;
  215775. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  215776. isInterleaved = true;
  215777. else
  215778. {
  215779. jassertfalse
  215780. return false;
  215781. }
  215782. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  215783. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  215784. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  215785. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  215786. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  215787. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  215788. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  215789. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  215790. bitDepth = 0;
  215791. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  215792. {
  215793. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  215794. {
  215795. bitDepth = formatsToTry [i + 1];
  215796. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  215797. break;
  215798. }
  215799. }
  215800. if (bitDepth == 0)
  215801. {
  215802. error = "device doesn't support a compatible PCM format";
  215803. DBG (T("ALSA error: ") + error + T("\n"));
  215804. return false;
  215805. }
  215806. int dir = 0;
  215807. unsigned int periods = 4;
  215808. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  215809. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  215810. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  215811. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  215812. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  215813. || failed (snd_pcm_hw_params (handle, hwParams)))
  215814. {
  215815. return false;
  215816. }
  215817. snd_pcm_sw_params_t* swParams;
  215818. snd_pcm_sw_params_alloca (&swParams);
  215819. snd_pcm_uframes_t boundary;
  215820. if (failed (snd_pcm_sw_params_current (handle, swParams))
  215821. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  215822. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  215823. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  215824. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  215825. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  215826. || failed (snd_pcm_sw_params (handle, swParams)))
  215827. {
  215828. return false;
  215829. }
  215830. /*
  215831. #ifdef JUCE_DEBUG
  215832. // enable this to dump the config of the devices that get opened
  215833. snd_output_t* out;
  215834. snd_output_stdio_attach (&out, stderr, 0);
  215835. snd_pcm_hw_params_dump (hwParams, out);
  215836. snd_pcm_sw_params_dump (swParams, out);
  215837. #endif
  215838. */
  215839. numChannelsRunning = numChannels;
  215840. return true;
  215841. }
  215842. bool write (float** const data, const int numSamples)
  215843. {
  215844. if (isInterleaved)
  215845. {
  215846. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  215847. float* interleaved = (float*) scratch;
  215848. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  215849. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  215850. snd_pcm_sframes_t num = snd_pcm_writei (handle, (void*) interleaved, numSamples);
  215851. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  215852. return false;
  215853. }
  215854. else
  215855. {
  215856. for (int i = 0; i < numChannelsRunning; ++i)
  215857. if (data[i] != 0)
  215858. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  215859. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  215860. if (failed (num))
  215861. {
  215862. if (num == -EPIPE)
  215863. {
  215864. if (failed (snd_pcm_prepare (handle)))
  215865. return false;
  215866. }
  215867. else if (num != -ESTRPIPE)
  215868. return false;
  215869. }
  215870. }
  215871. return true;
  215872. }
  215873. bool read (float** const data, const int numSamples)
  215874. {
  215875. if (isInterleaved)
  215876. {
  215877. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  215878. float* interleaved = (float*) scratch;
  215879. snd_pcm_sframes_t num = snd_pcm_readi (handle, (void*) interleaved, numSamples);
  215880. if (failed (num))
  215881. {
  215882. if (num == -EPIPE)
  215883. {
  215884. if (failed (snd_pcm_prepare (handle)))
  215885. return false;
  215886. }
  215887. else if (num != -ESTRPIPE)
  215888. return false;
  215889. }
  215890. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  215891. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  215892. }
  215893. else
  215894. {
  215895. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  215896. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  215897. return false;
  215898. for (int i = 0; i < numChannelsRunning; ++i)
  215899. if (data[i] != 0)
  215900. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  215901. }
  215902. return true;
  215903. }
  215904. juce_UseDebuggingNewOperator
  215905. snd_pcm_t* handle;
  215906. String error;
  215907. int bitDepth, numChannelsRunning;
  215908. private:
  215909. const bool isInput;
  215910. bool isInterleaved;
  215911. MemoryBlock scratch;
  215912. AudioDataConverters::DataFormat sampleFormat;
  215913. bool failed (const int errorNum)
  215914. {
  215915. if (errorNum >= 0)
  215916. return false;
  215917. error = snd_strerror (errorNum);
  215918. DBG (T("ALSA error: ") + error + T("\n"));
  215919. return true;
  215920. }
  215921. };
  215922. class ALSAThread : public Thread
  215923. {
  215924. public:
  215925. ALSAThread (const String& inputId_,
  215926. const String& outputId_)
  215927. : Thread ("Juce ALSA"),
  215928. sampleRate (0),
  215929. bufferSize (0),
  215930. callback (0),
  215931. inputId (inputId_),
  215932. outputId (outputId_),
  215933. outputDevice (0),
  215934. inputDevice (0),
  215935. numCallbacks (0),
  215936. totalNumInputChannels (0),
  215937. totalNumOutputChannels (0)
  215938. {
  215939. zeromem (outputChannelData, sizeof (outputChannelData));
  215940. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  215941. zeromem (inputChannelData, sizeof (inputChannelData));
  215942. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  215943. initialiseRatesAndChannels();
  215944. }
  215945. ~ALSAThread()
  215946. {
  215947. close();
  215948. }
  215949. void open (BitArray inputChannels,
  215950. BitArray outputChannels,
  215951. const double sampleRate_,
  215952. const int bufferSize_)
  215953. {
  215954. close();
  215955. error = String::empty;
  215956. sampleRate = sampleRate_;
  215957. bufferSize = bufferSize_;
  215958. currentInputChans.clear();
  215959. currentOutputChans.clear();
  215960. if (inputChannels.getHighestBit() >= 0)
  215961. {
  215962. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), minChansIn); ++i)
  215963. {
  215964. inputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  215965. if (inputChannels[i])
  215966. {
  215967. inputChannelDataForCallback [totalNumInputChannels++] = inputChannelData [i];
  215968. currentInputChans.setBit (i);
  215969. }
  215970. }
  215971. }
  215972. if (outputChannels.getHighestBit() >= 0)
  215973. {
  215974. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), minChansOut); ++i)
  215975. {
  215976. outputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  215977. if (outputChannels[i])
  215978. {
  215979. outputChannelDataForCallback [totalNumOutputChannels++] = outputChannelData [i];
  215980. currentOutputChans.setBit (i);
  215981. }
  215982. }
  215983. }
  215984. if (totalNumOutputChannels > 0 && outputId.isNotEmpty())
  215985. {
  215986. outputDevice = new ALSADevice (outputId, false);
  215987. if (outputDevice->error.isNotEmpty())
  215988. {
  215989. error = outputDevice->error;
  215990. deleteAndZero (outputDevice);
  215991. return;
  215992. }
  215993. currentOutputChans.setRange (0, minChansOut, true);
  215994. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  215995. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  215996. bufferSize))
  215997. {
  215998. error = outputDevice->error;
  215999. deleteAndZero (outputDevice);
  216000. return;
  216001. }
  216002. }
  216003. if (totalNumInputChannels > 0 && inputId.isNotEmpty())
  216004. {
  216005. inputDevice = new ALSADevice (inputId, true);
  216006. if (inputDevice->error.isNotEmpty())
  216007. {
  216008. error = inputDevice->error;
  216009. deleteAndZero (inputDevice);
  216010. return;
  216011. }
  216012. currentInputChans.setRange (0, minChansIn, true);
  216013. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  216014. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  216015. bufferSize))
  216016. {
  216017. error = inputDevice->error;
  216018. deleteAndZero (inputDevice);
  216019. return;
  216020. }
  216021. }
  216022. if (outputDevice == 0 && inputDevice == 0)
  216023. {
  216024. error = "no channels";
  216025. return;
  216026. }
  216027. if (outputDevice != 0 && inputDevice != 0)
  216028. {
  216029. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  216030. }
  216031. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  216032. return;
  216033. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  216034. return;
  216035. startThread (9);
  216036. int count = 1000;
  216037. while (numCallbacks == 0)
  216038. {
  216039. sleep (5);
  216040. if (--count < 0 || ! isThreadRunning())
  216041. {
  216042. error = "device didn't start";
  216043. break;
  216044. }
  216045. }
  216046. }
  216047. void close()
  216048. {
  216049. stopThread (6000);
  216050. deleteAndZero (inputDevice);
  216051. deleteAndZero (outputDevice);
  216052. for (int i = 0; i < maxNumChans; ++i)
  216053. {
  216054. juce_free (inputChannelData [i]);
  216055. juce_free (outputChannelData [i]);
  216056. }
  216057. zeromem (outputChannelData, sizeof (outputChannelData));
  216058. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  216059. zeromem (inputChannelData, sizeof (inputChannelData));
  216060. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  216061. totalNumOutputChannels = 0;
  216062. totalNumInputChannels = 0;
  216063. numCallbacks = 0;
  216064. }
  216065. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  216066. {
  216067. const ScopedLock sl (callbackLock);
  216068. callback = newCallback;
  216069. }
  216070. void run()
  216071. {
  216072. while (! threadShouldExit())
  216073. {
  216074. if (inputDevice != 0)
  216075. {
  216076. if (! inputDevice->read (inputChannelData, bufferSize))
  216077. {
  216078. DBG ("ALSA: read failure");
  216079. break;
  216080. }
  216081. }
  216082. if (threadShouldExit())
  216083. break;
  216084. {
  216085. const ScopedLock sl (callbackLock);
  216086. ++numCallbacks;
  216087. if (callback != 0)
  216088. {
  216089. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback,
  216090. totalNumInputChannels,
  216091. outputChannelDataForCallback,
  216092. totalNumOutputChannels,
  216093. bufferSize);
  216094. }
  216095. else
  216096. {
  216097. for (int i = 0; i < totalNumOutputChannels; ++i)
  216098. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  216099. }
  216100. }
  216101. if (outputDevice != 0)
  216102. {
  216103. failed (snd_pcm_wait (outputDevice->handle, 2000));
  216104. if (threadShouldExit())
  216105. break;
  216106. failed (snd_pcm_avail_update (outputDevice->handle));
  216107. if (! outputDevice->write (outputChannelData, bufferSize))
  216108. {
  216109. DBG ("ALSA: write failure");
  216110. break;
  216111. }
  216112. }
  216113. }
  216114. }
  216115. int getBitDepth() const throw()
  216116. {
  216117. if (outputDevice != 0)
  216118. return outputDevice->bitDepth;
  216119. if (inputDevice != 0)
  216120. return inputDevice->bitDepth;
  216121. return 16;
  216122. }
  216123. juce_UseDebuggingNewOperator
  216124. String error;
  216125. double sampleRate;
  216126. int bufferSize;
  216127. BitArray currentInputChans, currentOutputChans;
  216128. Array <int> sampleRates;
  216129. StringArray channelNamesOut, channelNamesIn;
  216130. AudioIODeviceCallback* callback;
  216131. private:
  216132. const String inputId, outputId;
  216133. ALSADevice* outputDevice;
  216134. ALSADevice* inputDevice;
  216135. int numCallbacks;
  216136. CriticalSection callbackLock;
  216137. float* outputChannelData [maxNumChans];
  216138. float* outputChannelDataForCallback [maxNumChans];
  216139. int totalNumInputChannels;
  216140. float* inputChannelData [maxNumChans];
  216141. float* inputChannelDataForCallback [maxNumChans];
  216142. int totalNumOutputChannels;
  216143. unsigned int minChansOut, maxChansOut;
  216144. unsigned int minChansIn, maxChansIn;
  216145. bool failed (const int errorNum) throw()
  216146. {
  216147. if (errorNum >= 0)
  216148. return false;
  216149. error = snd_strerror (errorNum);
  216150. DBG (T("ALSA error: ") + error + T("\n"));
  216151. return true;
  216152. }
  216153. void initialiseRatesAndChannels() throw()
  216154. {
  216155. sampleRates.clear();
  216156. channelNamesOut.clear();
  216157. channelNamesIn.clear();
  216158. minChansOut = 0;
  216159. maxChansOut = 0;
  216160. minChansIn = 0;
  216161. maxChansIn = 0;
  216162. unsigned int dummy = 0;
  216163. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  216164. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  216165. unsigned int i;
  216166. for (i = 0; i < maxChansOut; ++i)
  216167. channelNamesOut.add (T("channel ") + String ((int) i + 1));
  216168. for (i = 0; i < maxChansIn; ++i)
  216169. channelNamesIn.add (T("channel ") + String ((int) i + 1));
  216170. }
  216171. };
  216172. class ALSAAudioIODevice : public AudioIODevice
  216173. {
  216174. public:
  216175. ALSAAudioIODevice (const String& deviceName,
  216176. const String& inputId_,
  216177. const String& outputId_)
  216178. : AudioIODevice (deviceName, T("ALSA")),
  216179. inputId (inputId_),
  216180. outputId (outputId_),
  216181. isOpen_ (false),
  216182. isStarted (false),
  216183. internal (0)
  216184. {
  216185. internal = new ALSAThread (inputId, outputId);
  216186. }
  216187. ~ALSAAudioIODevice()
  216188. {
  216189. delete internal;
  216190. }
  216191. const StringArray getOutputChannelNames()
  216192. {
  216193. return internal->channelNamesOut;
  216194. }
  216195. const StringArray getInputChannelNames()
  216196. {
  216197. return internal->channelNamesIn;
  216198. }
  216199. int getNumSampleRates()
  216200. {
  216201. return internal->sampleRates.size();
  216202. }
  216203. double getSampleRate (int index)
  216204. {
  216205. return internal->sampleRates [index];
  216206. }
  216207. int getNumBufferSizesAvailable()
  216208. {
  216209. return 50;
  216210. }
  216211. int getBufferSizeSamples (int index)
  216212. {
  216213. int n = 16;
  216214. for (int i = 0; i < index; ++i)
  216215. n += n < 64 ? 16
  216216. : (n < 512 ? 32
  216217. : (n < 1024 ? 64
  216218. : (n < 2048 ? 128 : 256)));
  216219. return n;
  216220. }
  216221. int getDefaultBufferSize()
  216222. {
  216223. return 512;
  216224. }
  216225. const String open (const BitArray& inputChannels,
  216226. const BitArray& outputChannels,
  216227. double sampleRate,
  216228. int bufferSizeSamples)
  216229. {
  216230. close();
  216231. if (bufferSizeSamples <= 0)
  216232. bufferSizeSamples = getDefaultBufferSize();
  216233. if (sampleRate <= 0)
  216234. {
  216235. for (int i = 0; i < getNumSampleRates(); ++i)
  216236. {
  216237. if (getSampleRate (i) >= 44100)
  216238. {
  216239. sampleRate = getSampleRate (i);
  216240. break;
  216241. }
  216242. }
  216243. }
  216244. internal->open (inputChannels, outputChannels,
  216245. sampleRate, bufferSizeSamples);
  216246. isOpen_ = internal->error.isEmpty();
  216247. return internal->error;
  216248. }
  216249. void close()
  216250. {
  216251. stop();
  216252. internal->close();
  216253. isOpen_ = false;
  216254. }
  216255. bool isOpen()
  216256. {
  216257. return isOpen_;
  216258. }
  216259. int getCurrentBufferSizeSamples()
  216260. {
  216261. return internal->bufferSize;
  216262. }
  216263. double getCurrentSampleRate()
  216264. {
  216265. return internal->sampleRate;
  216266. }
  216267. int getCurrentBitDepth()
  216268. {
  216269. return internal->getBitDepth();
  216270. }
  216271. const BitArray getActiveOutputChannels() const
  216272. {
  216273. return internal->currentOutputChans;
  216274. }
  216275. const BitArray getActiveInputChannels() const
  216276. {
  216277. return internal->currentInputChans;
  216278. }
  216279. int getOutputLatencyInSamples()
  216280. {
  216281. return 0;
  216282. }
  216283. int getInputLatencyInSamples()
  216284. {
  216285. return 0;
  216286. }
  216287. void start (AudioIODeviceCallback* callback)
  216288. {
  216289. if (! isOpen_)
  216290. callback = 0;
  216291. internal->setCallback (callback);
  216292. if (callback != 0)
  216293. callback->audioDeviceAboutToStart (this);
  216294. isStarted = (callback != 0);
  216295. }
  216296. void stop()
  216297. {
  216298. AudioIODeviceCallback* const oldCallback = internal->callback;
  216299. start (0);
  216300. if (oldCallback != 0)
  216301. oldCallback->audioDeviceStopped();
  216302. }
  216303. bool isPlaying()
  216304. {
  216305. return isStarted && internal->error.isEmpty();
  216306. }
  216307. const String getLastError()
  216308. {
  216309. return internal->error;
  216310. }
  216311. String inputId, outputId;
  216312. private:
  216313. bool isOpen_, isStarted;
  216314. ALSAThread* internal;
  216315. };
  216316. class ALSAAudioIODeviceType : public AudioIODeviceType
  216317. {
  216318. public:
  216319. ALSAAudioIODeviceType()
  216320. : AudioIODeviceType (T("ALSA")),
  216321. hasScanned (false)
  216322. {
  216323. }
  216324. ~ALSAAudioIODeviceType()
  216325. {
  216326. }
  216327. void scanForDevices()
  216328. {
  216329. if (hasScanned)
  216330. return;
  216331. hasScanned = true;
  216332. inputNames.clear();
  216333. inputIds.clear();
  216334. outputNames.clear();
  216335. outputIds.clear();
  216336. snd_ctl_t* handle;
  216337. snd_ctl_card_info_t* info;
  216338. snd_ctl_card_info_alloca (&info);
  216339. int cardNum = -1;
  216340. while (outputIds.size() + inputIds.size() <= 32)
  216341. {
  216342. snd_card_next (&cardNum);
  216343. if (cardNum < 0)
  216344. break;
  216345. if (snd_ctl_open (&handle, T("hw:") + String (cardNum), SND_CTL_NONBLOCK) >= 0)
  216346. {
  216347. if (snd_ctl_card_info (handle, info) >= 0)
  216348. {
  216349. String cardId (snd_ctl_card_info_get_id (info));
  216350. if (cardId.removeCharacters (T("0123456789")).isEmpty())
  216351. cardId = String (cardNum);
  216352. int device = -1;
  216353. for (;;)
  216354. {
  216355. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  216356. break;
  216357. String id, name;
  216358. id << "hw:" << cardId << ',' << device;
  216359. bool isInput, isOutput;
  216360. if (testDevice (id, isInput, isOutput))
  216361. {
  216362. name << snd_ctl_card_info_get_name (info);
  216363. if (name.isEmpty())
  216364. name = id;
  216365. if (isInput)
  216366. {
  216367. inputNames.add (name);
  216368. inputIds.add (id);
  216369. }
  216370. if (isOutput)
  216371. {
  216372. outputNames.add (name);
  216373. outputIds.add (id);
  216374. }
  216375. }
  216376. }
  216377. }
  216378. snd_ctl_close (handle);
  216379. }
  216380. }
  216381. inputNames.appendNumbersToDuplicates (false, true);
  216382. outputNames.appendNumbersToDuplicates (false, true);
  216383. }
  216384. const StringArray getDeviceNames (const bool wantInputNames) const
  216385. {
  216386. jassert (hasScanned); // need to call scanForDevices() before doing this
  216387. return wantInputNames ? inputNames : outputNames;
  216388. }
  216389. int getDefaultDeviceIndex (const bool forInput) const
  216390. {
  216391. jassert (hasScanned); // need to call scanForDevices() before doing this
  216392. return 0;
  216393. }
  216394. bool hasSeparateInputsAndOutputs() const { return true; }
  216395. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  216396. {
  216397. jassert (hasScanned); // need to call scanForDevices() before doing this
  216398. ALSAAudioIODevice* const d = dynamic_cast <ALSAAudioIODevice*> (device);
  216399. if (d == 0)
  216400. return -1;
  216401. return asInput ? inputIds.indexOf (d->inputId)
  216402. : outputIds.indexOf (d->outputId);
  216403. }
  216404. AudioIODevice* createDevice (const String& outputDeviceName,
  216405. const String& inputDeviceName)
  216406. {
  216407. jassert (hasScanned); // need to call scanForDevices() before doing this
  216408. const int inputIndex = inputNames.indexOf (inputDeviceName);
  216409. const int outputIndex = outputNames.indexOf (outputDeviceName);
  216410. String deviceName (outputDeviceName);
  216411. if (deviceName.isEmpty())
  216412. deviceName = inputDeviceName;
  216413. if (index >= 0)
  216414. return new ALSAAudioIODevice (deviceName,
  216415. inputIds [inputIndex],
  216416. outputIds [outputIndex]);
  216417. return 0;
  216418. }
  216419. juce_UseDebuggingNewOperator
  216420. private:
  216421. StringArray inputNames, outputNames, inputIds, outputIds;
  216422. bool hasScanned;
  216423. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  216424. {
  216425. unsigned int minChansOut = 0, maxChansOut = 0;
  216426. unsigned int minChansIn = 0, maxChansIn = 0;
  216427. Array <int> rates;
  216428. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  216429. DBG (T("ALSA device: ") + id
  216430. + T(" outs=") + String ((int) minChansOut) + T("-") + String ((int) maxChansOut)
  216431. + T(" ins=") + String ((int) minChansIn) + T("-") + String ((int) maxChansIn)
  216432. + T(" rates=") + String (rates.size()));
  216433. isInput = maxChansIn > 0;
  216434. isOutput = maxChansOut > 0;
  216435. return (isInput || isOutput) && rates.size() > 0;
  216436. }
  216437. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  216438. const ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  216439. };
  216440. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  216441. {
  216442. return new ALSAAudioIODeviceType();
  216443. }
  216444. #else // if ALSA is turned off..
  216445. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  216446. {
  216447. return 0;
  216448. }
  216449. #endif
  216450. #endif
  216451. /********* End of inlined file: juce_linux_Audio.cpp *********/
  216452. /********* Start of inlined file: juce_linux_Midi.cpp *********/
  216453. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216454. // compiled on its own).
  216455. #ifdef JUCE_INCLUDED_FILE
  216456. #if JUCE_ALSA
  216457. static snd_seq_t* iterateDevices (const bool forInput,
  216458. StringArray& deviceNamesFound,
  216459. const int deviceIndexToOpen)
  216460. {
  216461. snd_seq_t* returnedHandle = 0;
  216462. snd_seq_t* seqHandle;
  216463. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  216464. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  216465. {
  216466. snd_seq_system_info_t* systemInfo;
  216467. snd_seq_client_info_t* clientInfo;
  216468. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  216469. {
  216470. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  216471. && snd_seq_client_info_malloc (&clientInfo) == 0)
  216472. {
  216473. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  216474. while (--numClients >= 0 && returnedHandle == 0)
  216475. {
  216476. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  216477. {
  216478. snd_seq_port_info_t* portInfo;
  216479. if (snd_seq_port_info_malloc (&portInfo) == 0)
  216480. {
  216481. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  216482. const int client = snd_seq_client_info_get_client (clientInfo);
  216483. snd_seq_port_info_set_client (portInfo, client);
  216484. snd_seq_port_info_set_port (portInfo, -1);
  216485. while (--numPorts >= 0)
  216486. {
  216487. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  216488. && (snd_seq_port_info_get_capability (portInfo)
  216489. & (forInput ? SND_SEQ_PORT_CAP_READ
  216490. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  216491. {
  216492. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  216493. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  216494. {
  216495. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  216496. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  216497. if (sourcePort != -1)
  216498. {
  216499. snd_seq_set_client_name (seqHandle,
  216500. forInput ? "Juce Midi Input"
  216501. : "Juce Midi Output");
  216502. const int portId
  216503. = snd_seq_create_simple_port (seqHandle,
  216504. forInput ? "Juce Midi In Port"
  216505. : "Juce Midi Out Port",
  216506. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  216507. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  216508. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  216509. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  216510. returnedHandle = seqHandle;
  216511. }
  216512. }
  216513. }
  216514. }
  216515. snd_seq_port_info_free (portInfo);
  216516. }
  216517. }
  216518. }
  216519. snd_seq_client_info_free (clientInfo);
  216520. }
  216521. snd_seq_system_info_free (systemInfo);
  216522. }
  216523. if (returnedHandle == 0)
  216524. snd_seq_close (seqHandle);
  216525. }
  216526. deviceNamesFound.appendNumbersToDuplicates (true, true);
  216527. return returnedHandle;
  216528. }
  216529. static snd_seq_t* createDevice (const bool forInput,
  216530. const String& deviceNameToOpen)
  216531. {
  216532. snd_seq_t* seqHandle = 0;
  216533. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  216534. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  216535. {
  216536. snd_seq_set_client_name (seqHandle,
  216537. (const char*) (forInput ? (deviceNameToOpen + T(" Input"))
  216538. : (deviceNameToOpen + T(" Output"))));
  216539. const int portId
  216540. = snd_seq_create_simple_port (seqHandle,
  216541. forInput ? "in"
  216542. : "out",
  216543. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  216544. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  216545. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  216546. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  216547. if (portId < 0)
  216548. {
  216549. snd_seq_close (seqHandle);
  216550. seqHandle = 0;
  216551. }
  216552. }
  216553. return seqHandle;
  216554. }
  216555. class MidiOutputDevice
  216556. {
  216557. public:
  216558. MidiOutputDevice (MidiOutput* const midiOutput_,
  216559. snd_seq_t* const seqHandle_)
  216560. :
  216561. midiOutput (midiOutput_),
  216562. seqHandle (seqHandle_),
  216563. maxEventSize (16 * 1024)
  216564. {
  216565. jassert (seqHandle != 0 && midiOutput != 0);
  216566. snd_midi_event_new (maxEventSize, &midiParser);
  216567. }
  216568. ~MidiOutputDevice()
  216569. {
  216570. snd_midi_event_free (midiParser);
  216571. snd_seq_close (seqHandle);
  216572. }
  216573. void sendMessageNow (const MidiMessage& message)
  216574. {
  216575. if (message.getRawDataSize() > maxEventSize)
  216576. {
  216577. maxEventSize = message.getRawDataSize();
  216578. snd_midi_event_free (midiParser);
  216579. snd_midi_event_new (maxEventSize, &midiParser);
  216580. }
  216581. snd_seq_event_t event;
  216582. snd_seq_ev_clear (&event);
  216583. snd_midi_event_encode (midiParser,
  216584. message.getRawData(),
  216585. message.getRawDataSize(),
  216586. &event);
  216587. snd_midi_event_reset_encode (midiParser);
  216588. snd_seq_ev_set_source (&event, 0);
  216589. snd_seq_ev_set_subs (&event);
  216590. snd_seq_ev_set_direct (&event);
  216591. snd_seq_event_output (seqHandle, &event);
  216592. snd_seq_drain_output (seqHandle);
  216593. }
  216594. juce_UseDebuggingNewOperator
  216595. private:
  216596. MidiOutput* const midiOutput;
  216597. snd_seq_t* const seqHandle;
  216598. snd_midi_event_t* midiParser;
  216599. int maxEventSize;
  216600. };
  216601. const StringArray MidiOutput::getDevices()
  216602. {
  216603. StringArray devices;
  216604. iterateDevices (false, devices, -1);
  216605. return devices;
  216606. }
  216607. int MidiOutput::getDefaultDeviceIndex()
  216608. {
  216609. return 0;
  216610. }
  216611. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  216612. {
  216613. MidiOutput* newDevice = 0;
  216614. StringArray devices;
  216615. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  216616. if (handle != 0)
  216617. {
  216618. newDevice = new MidiOutput();
  216619. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  216620. }
  216621. return newDevice;
  216622. }
  216623. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  216624. {
  216625. MidiOutput* newDevice = 0;
  216626. snd_seq_t* const handle = createDevice (false, deviceName);
  216627. if (handle != 0)
  216628. {
  216629. newDevice = new MidiOutput();
  216630. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  216631. }
  216632. return newDevice;
  216633. }
  216634. MidiOutput::~MidiOutput()
  216635. {
  216636. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  216637. delete device;
  216638. }
  216639. void MidiOutput::reset()
  216640. {
  216641. }
  216642. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  216643. {
  216644. return false;
  216645. }
  216646. void MidiOutput::setVolume (float leftVol, float rightVol)
  216647. {
  216648. }
  216649. void MidiOutput::sendMessageNow (const MidiMessage& message)
  216650. {
  216651. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  216652. }
  216653. class MidiInputThread : public Thread
  216654. {
  216655. public:
  216656. MidiInputThread (MidiInput* const midiInput_,
  216657. snd_seq_t* const seqHandle_,
  216658. MidiInputCallback* const callback_)
  216659. : Thread (T("Juce MIDI Input")),
  216660. midiInput (midiInput_),
  216661. seqHandle (seqHandle_),
  216662. callback (callback_)
  216663. {
  216664. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  216665. }
  216666. ~MidiInputThread()
  216667. {
  216668. snd_seq_close (seqHandle);
  216669. }
  216670. void run()
  216671. {
  216672. const int maxEventSize = 16 * 1024;
  216673. snd_midi_event_t* midiParser;
  216674. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  216675. {
  216676. uint8* const buffer = (uint8*) juce_malloc (maxEventSize);
  216677. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  216678. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  216679. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  216680. while (! threadShouldExit())
  216681. {
  216682. if (poll (pfd, numPfds, 500) > 0)
  216683. {
  216684. snd_seq_event_t* inputEvent = 0;
  216685. snd_seq_nonblock (seqHandle, 1);
  216686. do
  216687. {
  216688. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  216689. {
  216690. // xxx what about SYSEXes that are too big for the buffer?
  216691. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  216692. snd_midi_event_reset_decode (midiParser);
  216693. if (numBytes > 0)
  216694. {
  216695. const MidiMessage message ((const uint8*) buffer,
  216696. numBytes,
  216697. Time::getMillisecondCounter() * 0.001);
  216698. callback->handleIncomingMidiMessage (midiInput, message);
  216699. }
  216700. snd_seq_free_event (inputEvent);
  216701. }
  216702. }
  216703. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  216704. snd_seq_free_event (inputEvent);
  216705. }
  216706. }
  216707. snd_midi_event_free (midiParser);
  216708. juce_free (buffer);
  216709. }
  216710. };
  216711. juce_UseDebuggingNewOperator
  216712. private:
  216713. MidiInput* const midiInput;
  216714. snd_seq_t* const seqHandle;
  216715. MidiInputCallback* const callback;
  216716. };
  216717. MidiInput::MidiInput (const String& name_)
  216718. : name (name_),
  216719. internal (0)
  216720. {
  216721. }
  216722. MidiInput::~MidiInput()
  216723. {
  216724. stop();
  216725. MidiInputThread* const thread = (MidiInputThread*) internal;
  216726. delete thread;
  216727. }
  216728. void MidiInput::start()
  216729. {
  216730. ((MidiInputThread*) internal)->startThread();
  216731. }
  216732. void MidiInput::stop()
  216733. {
  216734. ((MidiInputThread*) internal)->stopThread (3000);
  216735. }
  216736. int MidiInput::getDefaultDeviceIndex()
  216737. {
  216738. return 0;
  216739. }
  216740. const StringArray MidiInput::getDevices()
  216741. {
  216742. StringArray devices;
  216743. iterateDevices (true, devices, -1);
  216744. return devices;
  216745. }
  216746. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  216747. {
  216748. MidiInput* newDevice = 0;
  216749. StringArray devices;
  216750. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  216751. if (handle != 0)
  216752. {
  216753. newDevice = new MidiInput (devices [deviceIndex]);
  216754. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  216755. }
  216756. return newDevice;
  216757. }
  216758. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  216759. {
  216760. MidiInput* newDevice = 0;
  216761. snd_seq_t* const handle = createDevice (true, deviceName);
  216762. if (handle != 0)
  216763. {
  216764. newDevice = new MidiInput (deviceName);
  216765. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  216766. }
  216767. return newDevice;
  216768. }
  216769. #else
  216770. // (These are just stub functions if ALSA is unavailable...)
  216771. const StringArray MidiOutput::getDevices() { return StringArray(); }
  216772. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  216773. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  216774. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  216775. MidiOutput::~MidiOutput() {}
  216776. void MidiOutput::reset() {}
  216777. bool MidiOutput::getVolume (float&, float&) { return false; }
  216778. void MidiOutput::setVolume (float, float) {}
  216779. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  216780. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  216781. MidiInput::~MidiInput() {}
  216782. void MidiInput::start() {}
  216783. void MidiInput::stop() {}
  216784. int MidiInput::getDefaultDeviceIndex() { return 0; }
  216785. const StringArray MidiInput::getDevices() { return StringArray(); }
  216786. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  216787. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  216788. #endif
  216789. #endif
  216790. /********* End of inlined file: juce_linux_Midi.cpp *********/
  216791. /********* Start of inlined file: juce_linux_AudioCDReader.cpp *********/
  216792. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216793. // compiled on its own).
  216794. #ifdef JUCE_INCLUDED_FILE
  216795. AudioCDReader::AudioCDReader()
  216796. : AudioFormatReader (0, T("CD Audio"))
  216797. {
  216798. }
  216799. const StringArray AudioCDReader::getAvailableCDNames()
  216800. {
  216801. StringArray names;
  216802. return names;
  216803. }
  216804. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  216805. {
  216806. return 0;
  216807. }
  216808. AudioCDReader::~AudioCDReader()
  216809. {
  216810. }
  216811. void AudioCDReader::refreshTrackLengths()
  216812. {
  216813. }
  216814. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  216815. int64 startSampleInFile, int numSamples)
  216816. {
  216817. return false;
  216818. }
  216819. bool AudioCDReader::isCDStillPresent() const
  216820. {
  216821. return false;
  216822. }
  216823. int AudioCDReader::getNumTracks() const
  216824. {
  216825. return 0;
  216826. }
  216827. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  216828. {
  216829. return 0;
  216830. }
  216831. bool AudioCDReader::isTrackAudio (int trackNum) const
  216832. {
  216833. return false;
  216834. }
  216835. void AudioCDReader::enableIndexScanning (bool b)
  216836. {
  216837. }
  216838. int AudioCDReader::getLastIndex() const
  216839. {
  216840. return 0;
  216841. }
  216842. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  216843. {
  216844. return Array<int>();
  216845. }
  216846. int AudioCDReader::getCDDBId()
  216847. {
  216848. return 0;
  216849. }
  216850. #endif
  216851. /********* End of inlined file: juce_linux_AudioCDReader.cpp *********/
  216852. /********* Start of inlined file: juce_linux_FileChooser.cpp *********/
  216853. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216854. // compiled on its own).
  216855. #ifdef JUCE_INCLUDED_FILE
  216856. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  216857. const String& title,
  216858. const File& file,
  216859. const String& filters,
  216860. bool isDirectory,
  216861. bool isSave,
  216862. bool warnAboutOverwritingExistingFiles,
  216863. bool selectMultipleFiles,
  216864. FilePreviewComponent* previewComponent)
  216865. {
  216866. //xxx ain't got one!
  216867. jassertfalse
  216868. }
  216869. #endif
  216870. /********* End of inlined file: juce_linux_FileChooser.cpp *********/
  216871. /********* Start of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  216872. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216873. // compiled on its own).
  216874. #ifdef JUCE_INCLUDED_FILE
  216875. #if JUCE_WEB_BROWSER
  216876. /*
  216877. Sorry.. This class isn't implemented on Linux!
  216878. */
  216879. WebBrowserComponent::WebBrowserComponent()
  216880. : browser (0),
  216881. blankPageShown (false)
  216882. {
  216883. setOpaque (true);
  216884. }
  216885. WebBrowserComponent::~WebBrowserComponent()
  216886. {
  216887. }
  216888. void WebBrowserComponent::goToURL (const String& url,
  216889. const StringArray* headers,
  216890. const MemoryBlock* postData)
  216891. {
  216892. lastURL = url;
  216893. lastHeaders.clear();
  216894. if (headers != 0)
  216895. lastHeaders = *headers;
  216896. lastPostData.setSize (0);
  216897. if (postData != 0)
  216898. lastPostData = *postData;
  216899. blankPageShown = false;
  216900. }
  216901. void WebBrowserComponent::stop()
  216902. {
  216903. }
  216904. void WebBrowserComponent::goBack()
  216905. {
  216906. lastURL = String::empty;
  216907. blankPageShown = false;
  216908. }
  216909. void WebBrowserComponent::goForward()
  216910. {
  216911. lastURL = String::empty;
  216912. }
  216913. void WebBrowserComponent::refresh()
  216914. {
  216915. }
  216916. void WebBrowserComponent::paint (Graphics& g)
  216917. {
  216918. g.fillAll (Colours::white);
  216919. }
  216920. void WebBrowserComponent::checkWindowAssociation()
  216921. {
  216922. }
  216923. void WebBrowserComponent::reloadLastURL()
  216924. {
  216925. if (lastURL.isNotEmpty())
  216926. {
  216927. goToURL (lastURL, &lastHeaders, &lastPostData);
  216928. lastURL = String::empty;
  216929. }
  216930. }
  216931. void WebBrowserComponent::parentHierarchyChanged()
  216932. {
  216933. checkWindowAssociation();
  216934. }
  216935. void WebBrowserComponent::resized()
  216936. {
  216937. }
  216938. void WebBrowserComponent::visibilityChanged()
  216939. {
  216940. checkWindowAssociation();
  216941. }
  216942. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  216943. {
  216944. return true;
  216945. }
  216946. #endif
  216947. #endif
  216948. /********* End of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  216949. #endif
  216950. END_JUCE_NAMESPACE
  216951. /********* End of inlined file: juce_linux_NativeCode.cpp *********/
  216952. #endif
  216953. #if JUCE_MAC
  216954. /********* Start of inlined file: juce_mac_NativeCode.mm *********/
  216955. /*
  216956. This file wraps together all the mac-specific code, so that
  216957. we can include all the native headers just once, and compile all our
  216958. platform-specific stuff in one big lump, keeping it out of the way of
  216959. the rest of the codebase.
  216960. */
  216961. BEGIN_JUCE_NAMESPACE
  216962. #undef Point
  216963. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  216964. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  216965. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  216966. cross-linked so that when you make a call to a class that you thought was private, it ends up
  216967. actually calling into a similarly named class in the other module's address space.
  216968. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  216969. have unique names, and should avoid this problem.
  216970. If you're using the amalgamated version, you can just set this macro to something unique before
  216971. you include juce_amalgamated.cpp.
  216972. */
  216973. #ifndef JUCE_ObjCExtraSuffix
  216974. #define JUCE_ObjCExtraSuffix 3
  216975. #endif
  216976. #define appendMacro1(a, b, c, d) a ## _ ## b ## _ ## c ## _ ## d
  216977. #define appendMacro2(a, b, c, d) appendMacro1(a, b, c, d)
  216978. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_ObjCExtraSuffix)
  216979. #define JUCE_INCLUDED_FILE 1
  216980. // Now include the actual code files..
  216981. /********* Start of inlined file: juce_mac_Strings.mm *********/
  216982. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  216983. // compiled on its own).
  216984. #ifdef JUCE_INCLUDED_FILE
  216985. static const String nsStringToJuce (NSString* s)
  216986. {
  216987. return String::fromUTF8 ((uint8*) [s UTF8String]);
  216988. }
  216989. static NSString* juceStringToNS (const String& s)
  216990. {
  216991. return [NSString stringWithUTF8String: (const char*) s.toUTF8()];
  216992. }
  216993. static const String convertUTF16ToString (const UniChar* utf16)
  216994. {
  216995. String s;
  216996. while (*utf16 != 0)
  216997. s += (juce_wchar) *utf16++;
  216998. return s;
  216999. }
  217000. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  217001. {
  217002. String result;
  217003. if (cfString != 0)
  217004. {
  217005. #if JUCE_STRINGS_ARE_UNICODE
  217006. CFRange range = { 0, CFStringGetLength (cfString) };
  217007. UniChar* const u = (UniChar*) juce_malloc (sizeof (UniChar) * (range.length + 1));
  217008. CFStringGetCharacters (cfString, range, u);
  217009. u[range.length] = 0;
  217010. result = convertUTF16ToString (u);
  217011. juce_free (u);
  217012. #else
  217013. const int len = CFStringGetLength (cfString);
  217014. char* buffer = (char*) juce_malloc (len + 1);
  217015. CFStringGetCString (cfString, buffer, len + 1, CFStringGetSystemEncoding());
  217016. result = buffer;
  217017. juce_free (buffer);
  217018. #endif
  217019. }
  217020. return result;
  217021. }
  217022. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  217023. {
  217024. #if JUCE_STRINGS_ARE_UNICODE
  217025. const int len = s.length();
  217026. const juce_wchar* t = (const juce_wchar*) s;
  217027. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  217028. for (int i = 0; i <= len; ++i)
  217029. temp[i] = t[i];
  217030. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  217031. juce_free (temp);
  217032. return result;
  217033. #else
  217034. return CFStringCreateWithCString (kCFAllocatorDefault,
  217035. (const char*) s,
  217036. CFStringGetSystemEncoding());
  217037. #endif
  217038. }
  217039. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  217040. {
  217041. UnicodeMapping map;
  217042. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  217043. kUnicodeNoSubset,
  217044. kTextEncodingDefaultFormat);
  217045. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  217046. kUnicodeCanonicalCompVariant,
  217047. kTextEncodingDefaultFormat);
  217048. map.mappingVersion = kUnicodeUseLatestMapping;
  217049. UnicodeToTextInfo conversionInfo = 0;
  217050. String result;
  217051. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  217052. {
  217053. const int len = s.length();
  217054. UniChar* const tempIn = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  217055. UniChar* const tempOut = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  217056. for (int i = 0; i <= len; ++i)
  217057. tempIn[i] = s[i];
  217058. ByteCount bytesRead = 0;
  217059. ByteCount outputBufferSize = 0;
  217060. if (ConvertFromUnicodeToText (conversionInfo,
  217061. len * sizeof (UniChar), tempIn,
  217062. kUnicodeDefaultDirectionMask,
  217063. 0, 0, 0, 0,
  217064. len * sizeof (UniChar), &bytesRead,
  217065. &outputBufferSize, tempOut) == noErr)
  217066. {
  217067. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  217068. tchar* t = const_cast <tchar*> ((const tchar*) result);
  217069. unsigned int i;
  217070. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  217071. t[i] = (tchar) tempOut[i];
  217072. t[i] = 0;
  217073. }
  217074. juce_free (tempIn);
  217075. juce_free (tempOut);
  217076. DisposeUnicodeToTextInfo (&conversionInfo);
  217077. }
  217078. return result;
  217079. }
  217080. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217081. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  217082. {
  217083. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  217084. owner: nil];
  217085. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  217086. forType: NSStringPboardType];
  217087. }
  217088. const String SystemClipboard::getTextFromClipboard() throw()
  217089. {
  217090. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  217091. return text == 0 ? String::empty
  217092. : nsStringToJuce (text);
  217093. }
  217094. #endif
  217095. #endif
  217096. /********* End of inlined file: juce_mac_Strings.mm *********/
  217097. /********* Start of inlined file: juce_mac_SystemStats.mm *********/
  217098. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217099. // compiled on its own).
  217100. #ifdef JUCE_INCLUDED_FILE
  217101. static int64 highResTimerFrequency;
  217102. #if JUCE_INTEL
  217103. static void juce_getCpuVendor (char* const v) throw()
  217104. {
  217105. int vendor[4];
  217106. zerostruct (vendor);
  217107. int dummy = 0;
  217108. asm ("mov %%ebx, %%esi \n\t"
  217109. "cpuid \n\t"
  217110. "xchg %%esi, %%ebx"
  217111. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  217112. memcpy (v, vendor, 16);
  217113. }
  217114. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures) throw()
  217115. {
  217116. unsigned int cpu = 0;
  217117. unsigned int ext = 0;
  217118. unsigned int family = 0;
  217119. unsigned int dummy = 0;
  217120. asm ("mov %%ebx, %%esi \n\t"
  217121. "cpuid \n\t"
  217122. "xchg %%esi, %%ebx"
  217123. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  217124. familyModel = family;
  217125. extFeatures = ext;
  217126. return cpu;
  217127. }
  217128. struct CPUFlags
  217129. {
  217130. bool hasMMX : 1;
  217131. bool hasSSE : 1;
  217132. bool hasSSE2 : 1;
  217133. bool has3DNow : 1;
  217134. };
  217135. static CPUFlags cpuFlags;
  217136. #endif
  217137. void SystemStats::initialiseStats() throw()
  217138. {
  217139. static bool initialised = false;
  217140. if (! initialised)
  217141. {
  217142. initialised = true;
  217143. // extremely annoying: adding this line stops the apple menu items from working. Of
  217144. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  217145. // any events.
  217146. //NSApplicationLoad();
  217147. [NSApplication sharedApplication];
  217148. #if JUCE_INTEL
  217149. {
  217150. unsigned int familyModel, extFeatures;
  217151. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  217152. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  217153. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  217154. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  217155. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  217156. }
  217157. #endif
  217158. highResTimerFrequency = (int64) AudioGetHostClockFrequency();
  217159. String s (SystemStats::getJUCEVersion());
  217160. rlimit lim;
  217161. getrlimit (RLIMIT_NOFILE, &lim);
  217162. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  217163. setrlimit (RLIMIT_NOFILE, &lim);
  217164. }
  217165. }
  217166. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  217167. {
  217168. return MacOSX;
  217169. }
  217170. const String SystemStats::getOperatingSystemName() throw()
  217171. {
  217172. return T("Mac OS X");
  217173. }
  217174. bool SystemStats::isOperatingSystem64Bit() throw()
  217175. {
  217176. #if JUCE_64BIT
  217177. return true;
  217178. #else
  217179. //xxx not sure how to find this out?..
  217180. return false;
  217181. #endif
  217182. }
  217183. int SystemStats::getMemorySizeInMegabytes() throw()
  217184. {
  217185. uint64 mem = 0;
  217186. size_t memSize = sizeof (mem);
  217187. int mib[] = { CTL_HW, HW_MEMSIZE };
  217188. sysctl (mib, 2, &mem, &memSize, 0, 0);
  217189. return mem / (1024 * 1024);
  217190. }
  217191. bool SystemStats::hasMMX() throw()
  217192. {
  217193. #if JUCE_INTEL
  217194. return cpuFlags.hasMMX;
  217195. #else
  217196. return false;
  217197. #endif
  217198. }
  217199. bool SystemStats::hasSSE() throw()
  217200. {
  217201. #if JUCE_INTEL
  217202. return cpuFlags.hasSSE;
  217203. #else
  217204. return false;
  217205. #endif
  217206. }
  217207. bool SystemStats::hasSSE2() throw()
  217208. {
  217209. #if JUCE_INTEL
  217210. return cpuFlags.hasSSE2;
  217211. #else
  217212. return false;
  217213. #endif
  217214. }
  217215. bool SystemStats::has3DNow() throw()
  217216. {
  217217. #if JUCE_INTEL
  217218. return cpuFlags.has3DNow;
  217219. #else
  217220. return false;
  217221. #endif
  217222. }
  217223. const String SystemStats::getCpuVendor() throw()
  217224. {
  217225. #if JUCE_INTEL
  217226. char v [16];
  217227. juce_getCpuVendor (v);
  217228. return String (v, 16);
  217229. #else
  217230. return String::empty;
  217231. #endif
  217232. }
  217233. int SystemStats::getCpuSpeedInMegaherz() throw()
  217234. {
  217235. uint64 speedHz = 0;
  217236. size_t speedSize = sizeof (speedHz);
  217237. int mib[] = { CTL_HW, HW_CPU_FREQ };
  217238. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  217239. #if JUCE_BIG_ENDIAN
  217240. if (speedSize == 4)
  217241. speedHz >>= 32;
  217242. #endif
  217243. return speedHz / 1000000;
  217244. }
  217245. int SystemStats::getNumCpus() throw()
  217246. {
  217247. #if MACOS_10_4_OR_EARLIER
  217248. return MPProcessors();
  217249. #else
  217250. return [[NSProcessInfo processInfo] activeProcessorCount];
  217251. #endif
  217252. }
  217253. static int64 juce_getMicroseconds() throw()
  217254. {
  217255. UnsignedWide t;
  217256. Microseconds (&t);
  217257. return (((int64) t.hi) << 32) | t.lo;
  217258. }
  217259. uint32 juce_millisecondsSinceStartup() throw()
  217260. {
  217261. return (uint32) (juce_getMicroseconds() / 1000);
  217262. }
  217263. double Time::getMillisecondCounterHiRes() throw()
  217264. {
  217265. // xxx might be more accurate to use a scaled AudioGetCurrentHostTime?
  217266. return juce_getMicroseconds() * 0.001;
  217267. }
  217268. int64 Time::getHighResolutionTicks() throw()
  217269. {
  217270. return (int64) AudioGetCurrentHostTime();
  217271. }
  217272. int64 Time::getHighResolutionTicksPerSecond() throw()
  217273. {
  217274. return highResTimerFrequency;
  217275. }
  217276. int64 SystemStats::getClockCycleCounter() throw()
  217277. {
  217278. return (int64) AudioGetCurrentHostTime();
  217279. }
  217280. bool Time::setSystemTimeToThisTime() const throw()
  217281. {
  217282. jassertfalse
  217283. return false;
  217284. }
  217285. int SystemStats::getPageSize() throw()
  217286. {
  217287. return NSPageSize();
  217288. }
  217289. void PlatformUtilities::fpuReset()
  217290. {
  217291. }
  217292. #endif
  217293. /********* End of inlined file: juce_mac_SystemStats.mm *********/
  217294. /********* Start of inlined file: juce_mac_Network.mm *********/
  217295. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217296. // compiled on its own).
  217297. #if JUCE_INCLUDED_FILE
  217298. static bool getEthernetIterator (io_iterator_t* matchingServices) throw()
  217299. {
  217300. mach_port_t masterPort;
  217301. if (IOMasterPort (MACH_PORT_NULL, &masterPort) == KERN_SUCCESS)
  217302. {
  217303. CFMutableDictionaryRef dict = IOServiceMatching (kIOEthernetInterfaceClass);
  217304. if (dict != 0)
  217305. {
  217306. CFMutableDictionaryRef propDict = CFDictionaryCreateMutable (kCFAllocatorDefault,
  217307. 0,
  217308. &kCFTypeDictionaryKeyCallBacks,
  217309. &kCFTypeDictionaryValueCallBacks);
  217310. if (propDict != 0)
  217311. {
  217312. CFDictionarySetValue (propDict, CFSTR (kIOPrimaryInterface), kCFBooleanTrue);
  217313. CFDictionarySetValue (dict, CFSTR (kIOPropertyMatchKey), propDict);
  217314. CFRelease (propDict);
  217315. }
  217316. }
  217317. return IOServiceGetMatchingServices (masterPort, dict, matchingServices) == KERN_SUCCESS;
  217318. }
  217319. return false;
  217320. }
  217321. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  217322. {
  217323. int numResults = 0;
  217324. io_iterator_t it;
  217325. if (getEthernetIterator (&it))
  217326. {
  217327. io_object_t i;
  217328. while ((i = IOIteratorNext (it)) != 0)
  217329. {
  217330. io_object_t controller;
  217331. if (IORegistryEntryGetParentEntry (i, kIOServicePlane, &controller) == KERN_SUCCESS)
  217332. {
  217333. CFTypeRef data = IORegistryEntryCreateCFProperty (controller,
  217334. CFSTR (kIOMACAddress),
  217335. kCFAllocatorDefault,
  217336. 0);
  217337. if (data != 0)
  217338. {
  217339. UInt8 addr [kIOEthernetAddressSize];
  217340. zeromem (addr, sizeof (addr));
  217341. CFDataGetBytes ((CFDataRef) data, CFRangeMake (0, sizeof (addr)), addr);
  217342. CFRelease (data);
  217343. int64 a = 0;
  217344. for (int i = 6; --i >= 0;)
  217345. a = (a << 8) | addr[i];
  217346. if (! littleEndian)
  217347. a = (int64) swapByteOrder ((uint64) a);
  217348. if (numResults < maxNum)
  217349. {
  217350. *addresses++ = a;
  217351. ++numResults;
  217352. }
  217353. }
  217354. IOObjectRelease (controller);
  217355. }
  217356. IOObjectRelease (i);
  217357. }
  217358. IOObjectRelease (it);
  217359. }
  217360. return numResults;
  217361. }
  217362. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  217363. const String& emailSubject,
  217364. const String& bodyText,
  217365. const StringArray& filesToAttach)
  217366. {
  217367. const ScopedAutoReleasePool pool;
  217368. String script;
  217369. script << "tell application \"Mail\"\r\n"
  217370. "set newMessage to make new outgoing message with properties {subject:\""
  217371. << emailSubject.replace (T("\""), T("\\\""))
  217372. << "\", content:\""
  217373. << bodyText.replace (T("\""), T("\\\""))
  217374. << "\" & return & return}\r\n"
  217375. "tell newMessage\r\n"
  217376. "set visible to true\r\n"
  217377. "set sender to \"sdfsdfsdfewf\"\r\n"
  217378. "make new to recipient at end of to recipients with properties {address:\""
  217379. << targetEmailAddress
  217380. << "\"}\r\n";
  217381. for (int i = 0; i < filesToAttach.size(); ++i)
  217382. {
  217383. script << "tell content\r\n"
  217384. "make new attachment with properties {file name:\""
  217385. << filesToAttach[i].replace (T("\""), T("\\\""))
  217386. << "\"} at after the last paragraph\r\n"
  217387. "end tell\r\n";
  217388. }
  217389. script << "end tell\r\n"
  217390. "end tell\r\n";
  217391. NSAppleScript* s = [[NSAppleScript alloc]
  217392. initWithSource: juceStringToNS (script)];
  217393. NSDictionary* error = 0;
  217394. const bool ok = [s executeAndReturnError: &error] != nil;
  217395. [s release];
  217396. return ok;
  217397. }
  217398. END_JUCE_NAMESPACE
  217399. using namespace JUCE_NAMESPACE;
  217400. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  217401. @interface JuceURLConnection : NSObject
  217402. {
  217403. @public
  217404. NSURLRequest* request;
  217405. NSURLConnection* connection;
  217406. NSMutableData* data;
  217407. Thread* runLoopThread;
  217408. bool initialised, hasFailed, hasFinished;
  217409. int position;
  217410. int64 contentLength;
  217411. NSLock* dataLock;
  217412. }
  217413. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  217414. - (void) dealloc;
  217415. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  217416. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  217417. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  217418. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  217419. - (BOOL) isOpen;
  217420. - (int) read: (char*) dest numBytes: (int) num;
  217421. - (int) readPosition;
  217422. - (void) stop;
  217423. - (void) createConnection;
  217424. @end
  217425. class JuceURLConnectionMessageThread : public Thread
  217426. {
  217427. JuceURLConnection* owner;
  217428. public:
  217429. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  217430. : Thread (T("http connection")),
  217431. owner (owner_)
  217432. {
  217433. }
  217434. ~JuceURLConnectionMessageThread()
  217435. {
  217436. stopThread (10000);
  217437. }
  217438. void run()
  217439. {
  217440. [owner createConnection];
  217441. while (! threadShouldExit())
  217442. {
  217443. const ScopedAutoReleasePool pool;
  217444. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  217445. }
  217446. }
  217447. };
  217448. @implementation JuceURLConnection
  217449. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  217450. withCallback: (URL::OpenStreamProgressCallback*) callback
  217451. withContext: (void*) context;
  217452. {
  217453. [super init];
  217454. request = req;
  217455. [request retain];
  217456. data = [[NSMutableData data] retain];
  217457. dataLock = [[NSLock alloc] init];
  217458. connection = 0;
  217459. initialised = false;
  217460. hasFailed = false;
  217461. hasFinished = false;
  217462. contentLength = -1;
  217463. runLoopThread = new JuceURLConnectionMessageThread (self);
  217464. runLoopThread->startThread();
  217465. while (runLoopThread->isThreadRunning() && ! initialised)
  217466. {
  217467. if (callback != 0)
  217468. callback (context, -1, [[request HTTPBody] length]);
  217469. Thread::sleep (1);
  217470. }
  217471. return self;
  217472. }
  217473. - (void) dealloc
  217474. {
  217475. [self stop];
  217476. delete runLoopThread;
  217477. [connection release];
  217478. [data release];
  217479. [dataLock release];
  217480. [request release];
  217481. [super dealloc];
  217482. }
  217483. - (void) createConnection
  217484. {
  217485. connection = [[NSURLConnection alloc] initWithRequest: request
  217486. delegate: [self retain]];
  217487. if (connection == nil)
  217488. runLoopThread->signalThreadShouldExit();
  217489. }
  217490. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response
  217491. {
  217492. [dataLock lock];
  217493. [data setLength: 0];
  217494. [dataLock unlock];
  217495. initialised = true;
  217496. contentLength = [response expectedContentLength];
  217497. }
  217498. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error
  217499. {
  217500. DBG (nsStringToJuce ([error description]));
  217501. hasFailed = true;
  217502. initialised = true;
  217503. runLoopThread->signalThreadShouldExit();
  217504. }
  217505. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) newData
  217506. {
  217507. [dataLock lock];
  217508. [data appendData: newData];
  217509. [dataLock unlock];
  217510. initialised = true;
  217511. }
  217512. - (void) connectionDidFinishLoading: (NSURLConnection*) connection
  217513. {
  217514. hasFinished = true;
  217515. initialised = true;
  217516. runLoopThread->signalThreadShouldExit();
  217517. }
  217518. - (BOOL) isOpen
  217519. {
  217520. return connection != 0 && ! hasFailed;
  217521. }
  217522. - (int) readPosition
  217523. {
  217524. return position;
  217525. }
  217526. - (int) read: (char*) dest numBytes: (int) numNeeded
  217527. {
  217528. int numDone = 0;
  217529. while (numNeeded > 0)
  217530. {
  217531. int available = jmin (numNeeded, [data length]);
  217532. if (available > 0)
  217533. {
  217534. [dataLock lock];
  217535. [data getBytes: dest length: available];
  217536. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  217537. [dataLock unlock];
  217538. numDone += available;
  217539. numNeeded -= available;
  217540. dest += available;
  217541. }
  217542. else
  217543. {
  217544. if (hasFailed || hasFinished)
  217545. break;
  217546. Thread::sleep (1);
  217547. }
  217548. }
  217549. position += numDone;
  217550. return numDone;
  217551. }
  217552. - (void) stop
  217553. {
  217554. [connection cancel];
  217555. runLoopThread->stopThread (10000);
  217556. }
  217557. @end
  217558. BEGIN_JUCE_NAMESPACE
  217559. bool juce_isOnLine()
  217560. {
  217561. return true;
  217562. }
  217563. void* juce_openInternetFile (const String& url,
  217564. const String& headers,
  217565. const MemoryBlock& postData,
  217566. const bool isPost,
  217567. URL::OpenStreamProgressCallback* callback,
  217568. void* callbackContext,
  217569. int timeOutMs)
  217570. {
  217571. const ScopedAutoReleasePool pool;
  217572. NSMutableURLRequest* req = [NSMutableURLRequest
  217573. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  217574. cachePolicy: NSURLRequestUseProtocolCachePolicy
  217575. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  217576. if (req == nil)
  217577. return 0;
  217578. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  217579. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  217580. StringArray headerLines;
  217581. headerLines.addLines (headers);
  217582. headerLines.removeEmptyStrings (true);
  217583. for (int i = 0; i < headerLines.size(); ++i)
  217584. {
  217585. const String key (headerLines[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  217586. const String value (headerLines[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  217587. if (key.isNotEmpty() && value.isNotEmpty())
  217588. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  217589. }
  217590. if (isPost && postData.getSize() > 0)
  217591. {
  217592. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  217593. length: postData.getSize()]];
  217594. }
  217595. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  217596. withCallback: callback
  217597. withContext: callbackContext];
  217598. if ([s isOpen])
  217599. return s;
  217600. [s release];
  217601. return 0;
  217602. }
  217603. void juce_closeInternetFile (void* handle)
  217604. {
  217605. JuceURLConnection* const s = (JuceURLConnection*) handle;
  217606. if (s != 0)
  217607. {
  217608. const ScopedAutoReleasePool pool;
  217609. [s stop];
  217610. [s release];
  217611. }
  217612. }
  217613. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  217614. {
  217615. JuceURLConnection* const s = (JuceURLConnection*) handle;
  217616. if (s != 0)
  217617. {
  217618. const ScopedAutoReleasePool pool;
  217619. return [s read: (char*) buffer numBytes: bytesToRead];
  217620. }
  217621. return 0;
  217622. }
  217623. int64 juce_getInternetFileContentLength (void* handle)
  217624. {
  217625. JuceURLConnection* const s = (JuceURLConnection*) handle;
  217626. if (s != 0)
  217627. return s->contentLength;
  217628. return -1;
  217629. }
  217630. int juce_seekInInternetFile (void* handle, int newPosition)
  217631. {
  217632. JuceURLConnection* const s = (JuceURLConnection*) handle;
  217633. if (s != 0)
  217634. return [s readPosition];
  217635. return 0;
  217636. }
  217637. #endif
  217638. /********* End of inlined file: juce_mac_Network.mm *********/
  217639. /********* Start of inlined file: juce_posix_NamedPipe.cpp *********/
  217640. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217641. // compiled on its own).
  217642. #if JUCE_INCLUDED_FILE
  217643. struct NamedPipeInternal
  217644. {
  217645. String pipeInName, pipeOutName;
  217646. int pipeIn, pipeOut;
  217647. bool volatile createdPipe, blocked, stopReadOperation;
  217648. static void signalHandler (int) {}
  217649. };
  217650. void NamedPipe::cancelPendingReads()
  217651. {
  217652. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  217653. {
  217654. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  217655. intern->stopReadOperation = true;
  217656. char buffer [1] = { 0 };
  217657. int bytesWritten = ::write (intern->pipeIn, buffer, 1);
  217658. (void) bytesWritten;
  217659. int timeout = 2000;
  217660. while (intern->blocked && --timeout >= 0)
  217661. Thread::sleep (2);
  217662. intern->stopReadOperation = false;
  217663. }
  217664. }
  217665. void NamedPipe::close()
  217666. {
  217667. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  217668. if (intern != 0)
  217669. {
  217670. internal = 0;
  217671. if (intern->pipeIn != -1)
  217672. ::close (intern->pipeIn);
  217673. if (intern->pipeOut != -1)
  217674. ::close (intern->pipeOut);
  217675. if (intern->createdPipe)
  217676. {
  217677. unlink (intern->pipeInName);
  217678. unlink (intern->pipeOutName);
  217679. }
  217680. delete intern;
  217681. }
  217682. }
  217683. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217684. {
  217685. close();
  217686. NamedPipeInternal* const intern = new NamedPipeInternal();
  217687. internal = intern;
  217688. intern->createdPipe = createPipe;
  217689. intern->blocked = false;
  217690. intern->stopReadOperation = false;
  217691. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217692. siginterrupt (SIGPIPE, 1);
  217693. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  217694. intern->pipeInName = pipePath + T("_in");
  217695. intern->pipeOutName = pipePath + T("_out");
  217696. intern->pipeIn = -1;
  217697. intern->pipeOut = -1;
  217698. if (createPipe)
  217699. {
  217700. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  217701. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  217702. {
  217703. delete intern;
  217704. internal = 0;
  217705. return false;
  217706. }
  217707. }
  217708. return true;
  217709. }
  217710. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217711. {
  217712. int bytesRead = -1;
  217713. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  217714. if (intern != 0)
  217715. {
  217716. intern->blocked = true;
  217717. if (intern->pipeIn == -1)
  217718. {
  217719. if (intern->createdPipe)
  217720. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  217721. else
  217722. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  217723. if (intern->pipeIn == -1)
  217724. {
  217725. intern->blocked = false;
  217726. return -1;
  217727. }
  217728. }
  217729. bytesRead = 0;
  217730. char* p = (char*) destBuffer;
  217731. while (bytesRead < maxBytesToRead)
  217732. {
  217733. const int bytesThisTime = maxBytesToRead - bytesRead;
  217734. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  217735. if (numRead <= 0 || intern->stopReadOperation)
  217736. {
  217737. bytesRead = -1;
  217738. break;
  217739. }
  217740. bytesRead += numRead;
  217741. p += bytesRead;
  217742. }
  217743. intern->blocked = false;
  217744. }
  217745. return bytesRead;
  217746. }
  217747. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217748. {
  217749. int bytesWritten = -1;
  217750. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  217751. if (intern != 0)
  217752. {
  217753. if (intern->pipeOut == -1)
  217754. {
  217755. if (intern->createdPipe)
  217756. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  217757. else
  217758. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  217759. if (intern->pipeOut == -1)
  217760. {
  217761. return -1;
  217762. }
  217763. }
  217764. const char* p = (const char*) sourceBuffer;
  217765. bytesWritten = 0;
  217766. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217767. while (bytesWritten < numBytesToWrite
  217768. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217769. {
  217770. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217771. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  217772. if (numWritten <= 0)
  217773. {
  217774. bytesWritten = -1;
  217775. break;
  217776. }
  217777. bytesWritten += numWritten;
  217778. p += bytesWritten;
  217779. }
  217780. }
  217781. return bytesWritten;
  217782. }
  217783. #endif
  217784. /********* End of inlined file: juce_posix_NamedPipe.cpp *********/
  217785. /********* Start of inlined file: juce_mac_Threads.mm *********/
  217786. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217787. // compiled on its own).
  217788. #ifdef JUCE_INCLUDED_FILE
  217789. /*
  217790. Note that a lot of methods that you'd expect to find in this file actually
  217791. live in juce_posix_SharedCode.h!
  217792. */
  217793. void JUCE_API juce_threadEntryPoint (void*);
  217794. void* threadEntryProc (void* userData) throw()
  217795. {
  217796. const ScopedAutoReleasePool pool;
  217797. juce_threadEntryPoint (userData);
  217798. return 0;
  217799. }
  217800. void* juce_createThread (void* userData) throw()
  217801. {
  217802. pthread_t handle = 0;
  217803. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217804. {
  217805. pthread_detach (handle);
  217806. return (void*) handle;
  217807. }
  217808. return 0;
  217809. }
  217810. void juce_killThread (void* handle) throw()
  217811. {
  217812. if (handle != 0)
  217813. pthread_cancel ((pthread_t) handle);
  217814. }
  217815. void juce_setCurrentThreadName (const String& /*name*/) throw()
  217816. {
  217817. }
  217818. Thread::ThreadID Thread::getCurrentThreadId() throw()
  217819. {
  217820. return (ThreadID) pthread_self();
  217821. }
  217822. bool juce_setThreadPriority (void* handle, int priority) throw()
  217823. {
  217824. if (handle == 0)
  217825. handle = (void*) pthread_self();
  217826. struct sched_param param;
  217827. int policy;
  217828. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  217829. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  217830. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217831. }
  217832. void Thread::yield() throw()
  217833. {
  217834. sched_yield();
  217835. }
  217836. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  217837. {
  217838. // xxx
  217839. jassertfalse
  217840. }
  217841. bool Process::isForegroundProcess() throw()
  217842. {
  217843. return [NSApp isActive];
  217844. }
  217845. void Process::raisePrivilege()
  217846. {
  217847. jassertfalse
  217848. }
  217849. void Process::lowerPrivilege()
  217850. {
  217851. jassertfalse
  217852. }
  217853. void Process::terminate()
  217854. {
  217855. exit (0);
  217856. }
  217857. void Process::setPriority (ProcessPriority p)
  217858. {
  217859. // xxx
  217860. }
  217861. #endif
  217862. /********* End of inlined file: juce_mac_Threads.mm *********/
  217863. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  217864. /*
  217865. This file contains posix routines that are common to both the Linux and Mac builds.
  217866. It gets included directly in the cpp files for these platforms.
  217867. */
  217868. CriticalSection::CriticalSection() throw()
  217869. {
  217870. pthread_mutexattr_t atts;
  217871. pthread_mutexattr_init (&atts);
  217872. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  217873. pthread_mutex_init (&internal, &atts);
  217874. }
  217875. CriticalSection::~CriticalSection() throw()
  217876. {
  217877. pthread_mutex_destroy (&internal);
  217878. }
  217879. void CriticalSection::enter() const throw()
  217880. {
  217881. pthread_mutex_lock (&internal);
  217882. }
  217883. bool CriticalSection::tryEnter() const throw()
  217884. {
  217885. return pthread_mutex_trylock (&internal) == 0;
  217886. }
  217887. void CriticalSection::exit() const throw()
  217888. {
  217889. pthread_mutex_unlock (&internal);
  217890. }
  217891. struct EventStruct
  217892. {
  217893. pthread_cond_t condition;
  217894. pthread_mutex_t mutex;
  217895. bool triggered;
  217896. };
  217897. WaitableEvent::WaitableEvent() throw()
  217898. {
  217899. EventStruct* const es = new EventStruct();
  217900. es->triggered = false;
  217901. pthread_cond_init (&es->condition, 0);
  217902. pthread_mutex_init (&es->mutex, 0);
  217903. internal = es;
  217904. }
  217905. WaitableEvent::~WaitableEvent() throw()
  217906. {
  217907. EventStruct* const es = (EventStruct*) internal;
  217908. pthread_cond_destroy (&es->condition);
  217909. pthread_mutex_destroy (&es->mutex);
  217910. delete es;
  217911. }
  217912. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  217913. {
  217914. EventStruct* const es = (EventStruct*) internal;
  217915. bool ok = true;
  217916. pthread_mutex_lock (&es->mutex);
  217917. if (timeOutMillisecs < 0)
  217918. {
  217919. while (! es->triggered)
  217920. pthread_cond_wait (&es->condition, &es->mutex);
  217921. }
  217922. else
  217923. {
  217924. while (! es->triggered)
  217925. {
  217926. struct timeval t;
  217927. gettimeofday (&t, 0);
  217928. struct timespec time;
  217929. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  217930. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  217931. if (time.tv_nsec >= 1000000000)
  217932. {
  217933. time.tv_nsec -= 1000000000;
  217934. time.tv_sec++;
  217935. }
  217936. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  217937. {
  217938. ok = false;
  217939. break;
  217940. }
  217941. }
  217942. }
  217943. es->triggered = false;
  217944. pthread_mutex_unlock (&es->mutex);
  217945. return ok;
  217946. }
  217947. void WaitableEvent::signal() const throw()
  217948. {
  217949. EventStruct* const es = (EventStruct*) internal;
  217950. pthread_mutex_lock (&es->mutex);
  217951. es->triggered = true;
  217952. pthread_cond_broadcast (&es->condition);
  217953. pthread_mutex_unlock (&es->mutex);
  217954. }
  217955. void WaitableEvent::reset() const throw()
  217956. {
  217957. EventStruct* const es = (EventStruct*) internal;
  217958. pthread_mutex_lock (&es->mutex);
  217959. es->triggered = false;
  217960. pthread_mutex_unlock (&es->mutex);
  217961. }
  217962. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  217963. {
  217964. struct timespec time;
  217965. time.tv_sec = millisecs / 1000;
  217966. time.tv_nsec = (millisecs % 1000) * 1000000;
  217967. nanosleep (&time, 0);
  217968. }
  217969. const tchar File::separator = T('/');
  217970. const tchar* File::separatorString = T("/");
  217971. bool juce_copyFile (const String& s, const String& d) throw();
  217972. static bool juce_stat (const String& fileName, struct stat& info) throw()
  217973. {
  217974. return fileName.isNotEmpty()
  217975. && (stat (fileName.toUTF8(), &info) == 0);
  217976. }
  217977. bool juce_isDirectory (const String& fileName) throw()
  217978. {
  217979. struct stat info;
  217980. return fileName.isEmpty()
  217981. || (juce_stat (fileName, info)
  217982. && ((info.st_mode & S_IFDIR) != 0));
  217983. }
  217984. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  217985. {
  217986. if (fileName.isEmpty())
  217987. return false;
  217988. const char* const fileNameUTF8 = fileName.toUTF8();
  217989. bool exists = access (fileNameUTF8, F_OK) == 0;
  217990. if (exists && dontCountDirectories)
  217991. {
  217992. struct stat info;
  217993. const int res = stat (fileNameUTF8, &info);
  217994. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  217995. exists = false;
  217996. }
  217997. return exists;
  217998. }
  217999. int64 juce_getFileSize (const String& fileName) throw()
  218000. {
  218001. struct stat info;
  218002. return juce_stat (fileName, info) ? info.st_size : 0;
  218003. }
  218004. bool juce_canWriteToFile (const String& fileName) throw()
  218005. {
  218006. return access (fileName.toUTF8(), W_OK) == 0;
  218007. }
  218008. bool juce_deleteFile (const String& fileName) throw()
  218009. {
  218010. if (juce_isDirectory (fileName))
  218011. return rmdir ((const char*) fileName.toUTF8()) == 0;
  218012. else
  218013. return remove ((const char*) fileName.toUTF8()) == 0;
  218014. }
  218015. bool juce_moveFile (const String& source, const String& dest) throw()
  218016. {
  218017. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  218018. return true;
  218019. if (juce_canWriteToFile (source)
  218020. && juce_copyFile (source, dest))
  218021. {
  218022. if (juce_deleteFile (source))
  218023. return true;
  218024. juce_deleteFile (dest);
  218025. }
  218026. return false;
  218027. }
  218028. void juce_createDirectory (const String& fileName) throw()
  218029. {
  218030. mkdir (fileName.toUTF8(), 0777);
  218031. }
  218032. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  218033. {
  218034. int flags = O_RDONLY;
  218035. if (forWriting)
  218036. {
  218037. if (juce_fileExists (fileName, false))
  218038. {
  218039. const int f = open ((const char*) fileName.toUTF8(), O_RDWR, 00644);
  218040. if (f != -1)
  218041. lseek (f, 0, SEEK_END);
  218042. return (void*) f;
  218043. }
  218044. else
  218045. {
  218046. flags = O_RDWR + O_CREAT;
  218047. }
  218048. }
  218049. return (void*) open ((const char*) fileName.toUTF8(), flags, 00644);
  218050. }
  218051. void juce_fileClose (void* handle) throw()
  218052. {
  218053. if (handle != 0)
  218054. close ((int) (pointer_sized_int) handle);
  218055. }
  218056. int juce_fileRead (void* handle, void* buffer, int size) throw()
  218057. {
  218058. if (handle != 0)
  218059. return read ((int) (pointer_sized_int) handle, buffer, size);
  218060. return 0;
  218061. }
  218062. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  218063. {
  218064. if (handle != 0)
  218065. return write ((int) (pointer_sized_int) handle, buffer, size);
  218066. return 0;
  218067. }
  218068. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  218069. {
  218070. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  218071. return pos;
  218072. return -1;
  218073. }
  218074. int64 juce_fileGetPosition (void* handle) throw()
  218075. {
  218076. if (handle != 0)
  218077. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  218078. else
  218079. return -1;
  218080. }
  218081. void juce_fileFlush (void* handle) throw()
  218082. {
  218083. if (handle != 0)
  218084. fsync ((int) (pointer_sized_int) handle);
  218085. }
  218086. const File juce_getExecutableFile()
  218087. {
  218088. Dl_info exeInfo;
  218089. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  218090. return File (exeInfo.dli_fname);
  218091. }
  218092. // if this file doesn't exist, find a parent of it that does..
  218093. static bool doStatFS (const File* file, struct statfs& result) throw()
  218094. {
  218095. File f (*file);
  218096. for (int i = 5; --i >= 0;)
  218097. {
  218098. if (f.exists())
  218099. break;
  218100. f = f.getParentDirectory();
  218101. }
  218102. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  218103. }
  218104. int64 File::getBytesFreeOnVolume() const throw()
  218105. {
  218106. struct statfs buf;
  218107. if (doStatFS (this, buf))
  218108. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  218109. return 0;
  218110. }
  218111. int64 File::getVolumeTotalSize() const throw()
  218112. {
  218113. struct statfs buf;
  218114. if (doStatFS (this, buf))
  218115. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  218116. return 0;
  218117. }
  218118. const String juce_getVolumeLabel (const String& filenameOnVolume,
  218119. int& volumeSerialNumber) throw()
  218120. {
  218121. volumeSerialNumber = 0;
  218122. #if JUCE_MAC
  218123. struct VolAttrBuf
  218124. {
  218125. u_int32_t length;
  218126. attrreference_t mountPointRef;
  218127. char mountPointSpace [MAXPATHLEN];
  218128. } attrBuf;
  218129. struct attrlist attrList;
  218130. zerostruct (attrList);
  218131. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  218132. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  218133. File f (filenameOnVolume);
  218134. for (;;)
  218135. {
  218136. if (getattrlist ((const char*) f.getFullPathName().toUTF8(),
  218137. &attrList, &attrBuf, sizeof(attrBuf), 0) == 0)
  218138. {
  218139. return String::fromUTF8 (((const uint8*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  218140. (int) attrBuf.mountPointRef.attr_length);
  218141. }
  218142. const File parent (f.getParentDirectory());
  218143. if (f == parent)
  218144. break;
  218145. f = parent;
  218146. }
  218147. #endif
  218148. return String::empty;
  218149. }
  218150. void juce_runSystemCommand (const String& command)
  218151. {
  218152. int result = system ((const char*) command.toUTF8());
  218153. (void) result;
  218154. }
  218155. const String juce_getOutputFromCommand (const String& command)
  218156. {
  218157. // slight bodge here, as we just pipe the output into a temp file and read it...
  218158. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  218159. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  218160. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  218161. String result (tempFile.loadFileAsString());
  218162. tempFile.deleteFile();
  218163. return result;
  218164. }
  218165. #if JUCE_64BIT
  218166. #define filedesc ((long long) internal)
  218167. #else
  218168. #define filedesc ((int) internal)
  218169. #endif
  218170. InterProcessLock::InterProcessLock (const String& name_) throw()
  218171. : internal (0),
  218172. name (name_),
  218173. reentrancyLevel (0)
  218174. {
  218175. #if JUCE_MAC
  218176. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  218177. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  218178. #else
  218179. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  218180. #endif
  218181. temp.create();
  218182. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  218183. }
  218184. InterProcessLock::~InterProcessLock() throw()
  218185. {
  218186. while (reentrancyLevel > 0)
  218187. this->exit();
  218188. close (filedesc);
  218189. }
  218190. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  218191. {
  218192. if (internal == 0)
  218193. return false;
  218194. if (reentrancyLevel != 0)
  218195. return true;
  218196. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  218197. struct flock fl;
  218198. zerostruct (fl);
  218199. fl.l_whence = SEEK_SET;
  218200. fl.l_type = F_WRLCK;
  218201. for (;;)
  218202. {
  218203. const int result = fcntl (filedesc, F_SETLK, &fl);
  218204. if (result >= 0)
  218205. {
  218206. ++reentrancyLevel;
  218207. return true;
  218208. }
  218209. if (errno != EINTR)
  218210. {
  218211. if (timeOutMillisecs == 0
  218212. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  218213. break;
  218214. Thread::sleep (10);
  218215. }
  218216. }
  218217. return false;
  218218. }
  218219. void InterProcessLock::exit() throw()
  218220. {
  218221. if (reentrancyLevel > 0 && internal != 0)
  218222. {
  218223. --reentrancyLevel;
  218224. struct flock fl;
  218225. zerostruct (fl);
  218226. fl.l_whence = SEEK_SET;
  218227. fl.l_type = F_UNLCK;
  218228. for (;;)
  218229. {
  218230. const int result = fcntl (filedesc, F_SETLKW, &fl);
  218231. if (result >= 0 || errno != EINTR)
  218232. break;
  218233. }
  218234. }
  218235. }
  218236. /********* End of inlined file: juce_posix_SharedCode.h *********/
  218237. /********* Start of inlined file: juce_mac_Files.mm *********/
  218238. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218239. // compiled on its own).
  218240. #ifdef JUCE_INCLUDED_FILE
  218241. /*
  218242. Note that a lot of methods that you'd expect to find in this file actually
  218243. live in juce_posix_SharedCode.h!
  218244. */
  218245. const unsigned int macTimeToUnixTimeDiff = 0x7c25be90;
  218246. static uint64 utcDateTimeToUnixTime (const UTCDateTime& d) throw()
  218247. {
  218248. if (d.highSeconds == 0 && d.lowSeconds == 0 && d.fraction == 0)
  218249. return 0;
  218250. return (((((uint64) d.highSeconds) << 32) | (uint64) d.lowSeconds) * 1000)
  218251. + ((d.fraction * 1000) >> 16)
  218252. - 2082844800000ll;
  218253. }
  218254. static void unixTimeToUtcDateTime (uint64 t, UTCDateTime& d) throw()
  218255. {
  218256. if (t != 0)
  218257. t += 2082844800000ll;
  218258. d.highSeconds = (t / 1000) >> 32;
  218259. d.lowSeconds = (t / 1000) & (uint64) 0xffffffff;
  218260. d.fraction = ((t % 1000) << 16) / 1000;
  218261. }
  218262. void juce_getFileTimes (const String& fileName,
  218263. int64& modificationTime,
  218264. int64& accessTime,
  218265. int64& creationTime) throw()
  218266. {
  218267. modificationTime = 0;
  218268. accessTime = 0;
  218269. creationTime = 0;
  218270. FSRef fileRef;
  218271. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  218272. {
  218273. FSRefParam info;
  218274. zerostruct (info);
  218275. info.ref = &fileRef;
  218276. info.whichInfo = kFSCatInfoAllDates;
  218277. FSCatalogInfo catInfo;
  218278. info.catInfo = &catInfo;
  218279. if (PBGetCatalogInfoSync (&info) == noErr)
  218280. {
  218281. creationTime = utcDateTimeToUnixTime (catInfo.createDate);
  218282. accessTime = utcDateTimeToUnixTime (catInfo.accessDate);
  218283. modificationTime = utcDateTimeToUnixTime (catInfo.contentModDate);
  218284. }
  218285. }
  218286. }
  218287. bool juce_setFileTimes (const String& fileName,
  218288. int64 modificationTime,
  218289. int64 accessTime,
  218290. int64 creationTime) throw()
  218291. {
  218292. FSRef fileRef;
  218293. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  218294. {
  218295. FSRefParam info;
  218296. zerostruct (info);
  218297. info.ref = &fileRef;
  218298. info.whichInfo = kFSCatInfoAllDates;
  218299. FSCatalogInfo catInfo;
  218300. info.catInfo = &catInfo;
  218301. if (PBGetCatalogInfoSync (&info) == noErr)
  218302. {
  218303. if (creationTime != 0)
  218304. unixTimeToUtcDateTime (creationTime, catInfo.createDate);
  218305. if (modificationTime != 0)
  218306. unixTimeToUtcDateTime (modificationTime, catInfo.contentModDate);
  218307. if (accessTime != 0)
  218308. unixTimeToUtcDateTime (accessTime, catInfo.accessDate);
  218309. return PBSetCatalogInfoSync (&info) == noErr;
  218310. }
  218311. }
  218312. return false;
  218313. }
  218314. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  218315. {
  218316. const char* const fileNameUTF8 = fileName.toUTF8();
  218317. struct stat info;
  218318. const int res = stat (fileNameUTF8, &info);
  218319. bool ok = false;
  218320. if (res == 0)
  218321. {
  218322. info.st_mode &= 0777; // Just permissions
  218323. if (isReadOnly)
  218324. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  218325. else
  218326. // Give everybody write permission?
  218327. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  218328. ok = chmod (fileNameUTF8, info.st_mode) == 0;
  218329. }
  218330. return ok;
  218331. }
  218332. bool juce_copyFile (const String& src, const String& dst) throw()
  218333. {
  218334. const ScopedAutoReleasePool pool;
  218335. NSFileManager* fm = [NSFileManager defaultManager];
  218336. return [fm fileExistsAtPath: juceStringToNS (src)]
  218337. && [fm copyPath: juceStringToNS (src)
  218338. toPath: juceStringToNS (dst)
  218339. handler: nil];
  218340. }
  218341. const StringArray juce_getFileSystemRoots() throw()
  218342. {
  218343. StringArray s;
  218344. s.add (T("/"));
  218345. return s;
  218346. }
  218347. static bool isFileOnDriveType (const File* const f, const char** types) throw()
  218348. {
  218349. struct statfs buf;
  218350. if (doStatFS (f, buf))
  218351. {
  218352. const String type (buf.f_fstypename);
  218353. while (*types != 0)
  218354. if (type.equalsIgnoreCase (*types++))
  218355. return true;
  218356. }
  218357. return false;
  218358. }
  218359. bool File::isOnCDRomDrive() const throw()
  218360. {
  218361. static const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  218362. return isFileOnDriveType (this, (const char**) cdTypes);
  218363. }
  218364. bool File::isOnHardDisk() const throw()
  218365. {
  218366. static const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  218367. return ! (isOnCDRomDrive() || isFileOnDriveType (this, (const char**) nonHDTypes));
  218368. }
  218369. bool File::isOnRemovableDrive() const throw()
  218370. {
  218371. const ScopedAutoReleasePool pool;
  218372. BOOL removable = false;
  218373. [[NSWorkspace sharedWorkspace]
  218374. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  218375. isRemovable: &removable
  218376. isWritable: nil
  218377. isUnmountable: nil
  218378. description: nil
  218379. type: nil];
  218380. return removable;
  218381. }
  218382. static bool juce_isHiddenFile (const String& path) throw()
  218383. {
  218384. FSRef ref;
  218385. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  218386. return false;
  218387. FSCatalogInfo info;
  218388. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  218389. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  218390. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  218391. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  218392. }
  218393. bool File::isHidden() const throw()
  218394. {
  218395. return juce_isHiddenFile (getFullPathName());
  218396. }
  218397. const File File::getSpecialLocation (const SpecialLocationType type)
  218398. {
  218399. const ScopedAutoReleasePool pool;
  218400. String resultPath;
  218401. switch (type)
  218402. {
  218403. case userHomeDirectory:
  218404. resultPath = nsStringToJuce (NSHomeDirectory());
  218405. break;
  218406. case userDocumentsDirectory:
  218407. resultPath = "~/Documents";
  218408. break;
  218409. case userDesktopDirectory:
  218410. resultPath = "~/Desktop";
  218411. break;
  218412. case userApplicationDataDirectory:
  218413. resultPath = "~/Library";
  218414. break;
  218415. case commonApplicationDataDirectory:
  218416. resultPath = "/Library";
  218417. break;
  218418. case globalApplicationsDirectory:
  218419. resultPath = "/Applications";
  218420. break;
  218421. case userMusicDirectory:
  218422. resultPath = "~/Music";
  218423. break;
  218424. case userMoviesDirectory:
  218425. resultPath = "~/Movies";
  218426. break;
  218427. case tempDirectory:
  218428. {
  218429. File tmp (T("~/Library/Caches/") + juce_getExecutableFile().getFileNameWithoutExtension());
  218430. tmp.createDirectory();
  218431. return tmp.getFullPathName();
  218432. }
  218433. case currentExecutableFile:
  218434. return juce_getExecutableFile();
  218435. case currentApplicationFile:
  218436. {
  218437. const File exe (juce_getExecutableFile());
  218438. const File parent (exe.getParentDirectory());
  218439. return parent.getFullPathName().endsWithIgnoreCase (T("Contents/MacOS"))
  218440. ? parent.getParentDirectory().getParentDirectory()
  218441. : exe;
  218442. }
  218443. default:
  218444. jassertfalse // unknown type?
  218445. break;
  218446. }
  218447. if (resultPath != 0)
  218448. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  218449. return File::nonexistent;
  218450. }
  218451. const File File::getCurrentWorkingDirectory() throw()
  218452. {
  218453. char buf [2048];
  218454. getcwd (buf, sizeof(buf));
  218455. return File (PlatformUtilities::convertToPrecomposedUnicode (buf));
  218456. }
  218457. bool File::setAsCurrentWorkingDirectory() const throw()
  218458. {
  218459. return chdir (getFullPathName().toUTF8()) == 0;
  218460. }
  218461. const String File::getVersion() const throw()
  218462. {
  218463. const ScopedAutoReleasePool pool;
  218464. String result;
  218465. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  218466. if (bundle != 0)
  218467. {
  218468. NSDictionary* info = [bundle infoDictionary];
  218469. if (info != 0)
  218470. {
  218471. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  218472. if (name != nil)
  218473. result = nsStringToJuce (name);
  218474. }
  218475. }
  218476. return result;
  218477. }
  218478. const File File::getLinkedTarget() const throw()
  218479. {
  218480. FSRef ref;
  218481. Boolean targetIsAFolder, wasAliased;
  218482. if (PlatformUtilities::makeFSRefFromPath (&ref, getFullPathName())
  218483. && (FSResolveAliasFileWithMountFlags (&ref, true, &targetIsAFolder, &wasAliased, 0) == noErr)
  218484. && wasAliased)
  218485. {
  218486. return File (PlatformUtilities::makePathFromFSRef (&ref));
  218487. }
  218488. return *this;
  218489. }
  218490. bool File::moveToTrash() const throw()
  218491. {
  218492. if (! exists())
  218493. return true;
  218494. const ScopedAutoReleasePool pool;
  218495. NSString* p = juceStringToNS (getFullPathName());
  218496. return [[NSWorkspace sharedWorkspace]
  218497. performFileOperation: NSWorkspaceRecycleOperation
  218498. source: [p stringByDeletingLastPathComponent]
  218499. destination: @""
  218500. files: [NSArray arrayWithObject: [p lastPathComponent]]
  218501. tag: nil ];
  218502. }
  218503. struct FindFileStruct
  218504. {
  218505. String parentDir, wildCard;
  218506. DIR* dir;
  218507. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  218508. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  218509. {
  218510. const char* const wildCardUTF8 = wildCard.toUTF8();
  218511. for (;;)
  218512. {
  218513. struct dirent* const de = readdir (dir);
  218514. if (de == 0)
  218515. break;
  218516. if (fnmatch (wildCardUTF8, de->d_name, 0) == 0)
  218517. {
  218518. result = String::fromUTF8 ((const uint8*) de->d_name);
  218519. const String path (parentDir + result);
  218520. if (isDir != 0 || fileSize != 0)
  218521. {
  218522. struct stat info;
  218523. const bool statOk = juce_stat (path, info);
  218524. if (isDir != 0)
  218525. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  218526. if (isHidden != 0)
  218527. *isHidden = (de->d_name[0] == '.')
  218528. || juce_isHiddenFile (path);
  218529. if (fileSize != 0)
  218530. *fileSize = statOk ? info.st_size : 0;
  218531. }
  218532. if (modTime != 0 || creationTime != 0)
  218533. {
  218534. int64 m, a, c;
  218535. juce_getFileTimes (path, m, a, c);
  218536. if (modTime != 0)
  218537. *modTime = m;
  218538. if (creationTime != 0)
  218539. *creationTime = c;
  218540. }
  218541. if (isReadOnly != 0)
  218542. *isReadOnly = ! juce_canWriteToFile (path);
  218543. return true;
  218544. }
  218545. }
  218546. return false;
  218547. }
  218548. };
  218549. // returns 0 on failure
  218550. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  218551. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  218552. Time* creationTime, bool* isReadOnly) throw()
  218553. {
  218554. DIR* const d = opendir (directory.toUTF8());
  218555. if (d != 0)
  218556. {
  218557. FindFileStruct* const ff = new FindFileStruct();
  218558. ff->parentDir = directory;
  218559. if (!ff->parentDir.endsWithChar (File::separator))
  218560. ff->parentDir += File::separator;
  218561. ff->wildCard = wildCard;
  218562. ff->dir = d;
  218563. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  218564. {
  218565. return ff;
  218566. }
  218567. else
  218568. {
  218569. firstResultFile = String::empty;
  218570. isDir = false;
  218571. closedir (d);
  218572. delete ff;
  218573. }
  218574. }
  218575. return 0;
  218576. }
  218577. bool juce_findFileNext (void* handle, String& resultFile,
  218578. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  218579. {
  218580. FindFileStruct* const ff = (FindFileStruct*) handle;
  218581. if (ff != 0)
  218582. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  218583. return false;
  218584. }
  218585. void juce_findFileClose (void* handle) throw()
  218586. {
  218587. FindFileStruct* const ff = (FindFileStruct*)handle;
  218588. if (ff != 0)
  218589. {
  218590. closedir (ff->dir);
  218591. delete ff;
  218592. }
  218593. }
  218594. bool juce_launchExecutable (const String& pathAndArguments) throw()
  218595. {
  218596. char* const argv[4] = { "/bin/sh", "-c", (char*) (const char*) pathAndArguments, 0 };
  218597. const int cpid = fork();
  218598. if (cpid == 0)
  218599. {
  218600. // Child process
  218601. if (execve (argv[0], argv, 0) < 0)
  218602. exit (0);
  218603. }
  218604. else
  218605. {
  218606. if (cpid < 0)
  218607. return false;
  218608. }
  218609. return true;
  218610. }
  218611. bool juce_launchFile (const String& fileName,
  218612. const String& parameters) throw()
  218613. {
  218614. const ScopedAutoReleasePool pool;
  218615. if (parameters.isEmpty())
  218616. {
  218617. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  218618. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  218619. }
  218620. bool ok = false;
  218621. FSRef ref;
  218622. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  218623. {
  218624. if (PlatformUtilities::isBundle (fileName))
  218625. {
  218626. NSMutableArray* urls = [NSMutableArray array];
  218627. StringArray docs;
  218628. docs.addTokens (parameters, true);
  218629. for (int i = 0; i < docs.size(); ++i)
  218630. [urls addObject: juceStringToNS (docs[i])];
  218631. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  218632. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  218633. options: nil
  218634. additionalEventParamDescriptor: nil
  218635. launchIdentifiers: nil];
  218636. }
  218637. else
  218638. {
  218639. ok = juce_launchExecutable (T("\"") + fileName + T("\" ") + parameters);
  218640. }
  218641. }
  218642. return ok;
  218643. }
  218644. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  218645. {
  218646. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  218647. }
  218648. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  218649. {
  218650. uint8 path [2048];
  218651. zeromem (path, sizeof (path));
  218652. String result;
  218653. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  218654. result = String::fromUTF8 (path);
  218655. return PlatformUtilities::convertToPrecomposedUnicode (result);
  218656. }
  218657. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  218658. {
  218659. const ScopedAutoReleasePool pool;
  218660. return NSHFSTypeCodeFromFileType (NSHFSTypeOfFile (juceStringToNS (filename)));
  218661. }
  218662. bool PlatformUtilities::isBundle (const String& filename)
  218663. {
  218664. const ScopedAutoReleasePool pool;
  218665. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  218666. }
  218667. #endif
  218668. /********* End of inlined file: juce_mac_Files.mm *********/
  218669. /********* Start of inlined file: juce_mac_MiscUtilities.mm *********/
  218670. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218671. // compiled on its own).
  218672. #ifdef JUCE_INCLUDED_FILE
  218673. ScopedAutoReleasePool::ScopedAutoReleasePool()
  218674. {
  218675. pool = [[NSAutoreleasePool alloc] init];
  218676. }
  218677. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  218678. {
  218679. [((NSAutoreleasePool*) pool) release];
  218680. }
  218681. void PlatformUtilities::beep()
  218682. {
  218683. NSBeep();
  218684. }
  218685. void PlatformUtilities::addItemToDock (const File& file)
  218686. {
  218687. // check that it's not already there...
  218688. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  218689. .containsIgnoreCase (file.getFullPathName()))
  218690. {
  218691. 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>"
  218692. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  218693. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  218694. }
  218695. }
  218696. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218697. bool AlertWindow::showNativeDialogBox (const String& title,
  218698. const String& bodyText,
  218699. bool isOkCancel)
  218700. {
  218701. const ScopedAutoReleasePool pool;
  218702. return NSRunAlertPanel (juceStringToNS (title),
  218703. juceStringToNS (bodyText),
  218704. @"Ok",
  218705. isOkCancel ? @"Cancel" : nil,
  218706. nil) == NSAlertDefaultReturn;
  218707. }
  218708. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  218709. {
  218710. if (files.size() == 0)
  218711. return false;
  218712. Component* sourceComp = Component::getComponentUnderMouse();
  218713. if (sourceComp == 0)
  218714. {
  218715. jassertfalse // this method must be called in response to a
  218716. // component's mouseDrag event!
  218717. return false;
  218718. }
  218719. const ScopedAutoReleasePool pool;
  218720. NSView* view = (NSView*) sourceComp->getWindowHandle();
  218721. if (view == 0)
  218722. return false;
  218723. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  218724. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  218725. owner: nil];
  218726. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  218727. for (int i = 0; i < files.size(); ++i)
  218728. [filesArray addObject: juceStringToNS (files[i])];
  218729. [pboard setPropertyList: filesArray
  218730. forType: NSFilenamesPboardType];
  218731. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  218732. fromView: nil];
  218733. dragPosition.x -= 16;
  218734. dragPosition.y -= 16;
  218735. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  218736. at: dragPosition
  218737. offset: NSMakeSize (0, 0)
  218738. event: [[view window] currentEvent]
  218739. pasteboard: pboard
  218740. source: view
  218741. slideBack: YES];
  218742. return true;
  218743. }
  218744. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  218745. {
  218746. jassertfalse // not implemented!
  218747. return false;
  218748. }
  218749. bool Desktop::canUseSemiTransparentWindows() throw()
  218750. {
  218751. return true;
  218752. }
  218753. void Desktop::getMousePosition (int& x, int& y) throw()
  218754. {
  218755. const ScopedAutoReleasePool pool;
  218756. const NSPoint p ([NSEvent mouseLocation]);
  218757. x = roundFloatToInt (p.x);
  218758. y = roundFloatToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y);
  218759. }
  218760. void Desktop::setMousePosition (int x, int y) throw()
  218761. {
  218762. // this rubbish needs to be done around the warp call, to avoid causing a
  218763. // bizarre glitch..
  218764. CGAssociateMouseAndMouseCursorPosition (false);
  218765. CGSetLocalEventsSuppressionInterval (0);
  218766. CGPoint pos = { x, y };
  218767. CGWarpMouseCursorPosition (pos);
  218768. CGAssociateMouseAndMouseCursorPosition (true);
  218769. }
  218770. #if MACOS_10_4_OR_EARLIER
  218771. class ScreenSaverDefeater : public Timer,
  218772. public DeletedAtShutdown
  218773. {
  218774. public:
  218775. ScreenSaverDefeater() throw()
  218776. {
  218777. startTimer (10000);
  218778. timerCallback();
  218779. }
  218780. ~ScreenSaverDefeater() {}
  218781. void timerCallback()
  218782. {
  218783. if (Process::isForegroundProcess())
  218784. UpdateSystemActivity (UsrActivity);
  218785. }
  218786. };
  218787. static ScreenSaverDefeater* screenSaverDefeater = 0;
  218788. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  218789. {
  218790. if (isEnabled)
  218791. {
  218792. deleteAndZero (screenSaverDefeater);
  218793. }
  218794. else if (screenSaverDefeater == 0)
  218795. {
  218796. screenSaverDefeater = new ScreenSaverDefeater();
  218797. }
  218798. }
  218799. bool Desktop::isScreenSaverEnabled() throw()
  218800. {
  218801. return screenSaverDefeater == 0;
  218802. }
  218803. #else
  218804. static IOPMAssertionID screenSaverDisablerID = 0;
  218805. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  218806. {
  218807. if (isEnabled)
  218808. {
  218809. if (screenSaverDisablerID != 0)
  218810. {
  218811. IOPMAssertionRelease (screenSaverDisablerID);
  218812. screenSaverDisablerID = 0;
  218813. }
  218814. }
  218815. else
  218816. {
  218817. if (screenSaverDisablerID == 0)
  218818. {
  218819. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep,
  218820. kIOPMAssertionLevelOn, &screenSaverDisablerID);
  218821. }
  218822. }
  218823. }
  218824. bool Desktop::isScreenSaverEnabled() throw()
  218825. {
  218826. return screenSaverDisablerID == 0;
  218827. }
  218828. #endif
  218829. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  218830. {
  218831. const ScopedAutoReleasePool pool;
  218832. monitorCoords.clear();
  218833. NSArray* screens = [NSScreen screens];
  218834. const float mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  218835. for (unsigned int i = 0; i < [screens count]; ++i)
  218836. {
  218837. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  218838. NSRect r = clipToWorkArea ? [s visibleFrame]
  218839. : [s frame];
  218840. monitorCoords.add (Rectangle ((int) r.origin.x,
  218841. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  218842. (int) r.size.width,
  218843. (int) r.size.height));
  218844. }
  218845. jassert (monitorCoords.size() > 0);
  218846. }
  218847. #endif
  218848. #endif
  218849. /********* End of inlined file: juce_mac_MiscUtilities.mm *********/
  218850. /********* Start of inlined file: juce_mac_Debugging.mm *********/
  218851. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218852. // compiled on its own).
  218853. #ifdef JUCE_INCLUDED_FILE
  218854. void Logger::outputDebugString (const String& text) throw()
  218855. {
  218856. fputs (text.toUTF8(), stderr);
  218857. fputs ("\n", stderr);
  218858. }
  218859. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  218860. {
  218861. String text;
  218862. va_list args;
  218863. va_start (args, format);
  218864. text.vprintf (format, args);
  218865. outputDebugString (text);
  218866. }
  218867. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  218868. {
  218869. static char testResult = 0;
  218870. if (testResult == 0)
  218871. {
  218872. struct kinfo_proc info;
  218873. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  218874. size_t sz = sizeof (info);
  218875. sysctl (m, 4, &info, &sz, 0, 0);
  218876. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  218877. }
  218878. return testResult > 0;
  218879. }
  218880. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  218881. {
  218882. return juce_isRunningUnderDebugger();
  218883. }
  218884. #endif
  218885. /********* End of inlined file: juce_mac_Debugging.mm *********/
  218886. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218887. /********* Start of inlined file: juce_mac_NSViewComponentPeer.mm *********/
  218888. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218889. // compiled on its own).
  218890. #ifdef JUCE_INCLUDED_FILE
  218891. class NSViewComponentPeer;
  218892. END_JUCE_NAMESPACE
  218893. #define JuceNSView MakeObjCClassName(JuceNSView)
  218894. @interface JuceNSView : NSView
  218895. {
  218896. @public
  218897. NSViewComponentPeer* owner;
  218898. NSNotificationCenter* notificationCenter;
  218899. }
  218900. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  218901. - (void) dealloc;
  218902. - (BOOL) isOpaque;
  218903. - (void) drawRect: (NSRect) r;
  218904. - (void) mouseDown: (NSEvent*) ev;
  218905. - (void) asyncMouseDown: (NSEvent*) ev;
  218906. - (void) mouseUp: (NSEvent*) ev;
  218907. - (void) asyncMouseUp: (NSEvent*) ev;
  218908. - (void) mouseDragged: (NSEvent*) ev;
  218909. - (void) mouseMoved: (NSEvent*) ev;
  218910. - (void) mouseEntered: (NSEvent*) ev;
  218911. - (void) mouseExited: (NSEvent*) ev;
  218912. - (void) rightMouseDown: (NSEvent*) ev;
  218913. - (void) rightMouseDragged: (NSEvent*) ev;
  218914. - (void) rightMouseUp: (NSEvent*) ev;
  218915. - (void) otherMouseDown: (NSEvent*) ev;
  218916. - (void) otherMouseDragged: (NSEvent*) ev;
  218917. - (void) otherMouseUp: (NSEvent*) ev;
  218918. - (void) scrollWheel: (NSEvent*) ev;
  218919. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  218920. - (void) frameChanged: (NSNotification*) n;
  218921. - (void) keyDown: (NSEvent*) ev;
  218922. - (void) keyUp: (NSEvent*) ev;
  218923. - (void) flagsChanged: (NSEvent*) ev;
  218924. #if MACOS_10_4_OR_EARLIER
  218925. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  218926. #endif
  218927. - (BOOL) becomeFirstResponder;
  218928. - (BOOL) resignFirstResponder;
  218929. - (BOOL) acceptsFirstResponder;
  218930. - (NSArray*) getSupportedDragTypes;
  218931. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  218932. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  218933. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  218934. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  218935. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  218936. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  218937. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  218938. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  218939. @end
  218940. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  218941. @interface JuceNSWindow : NSWindow
  218942. {
  218943. @private
  218944. NSViewComponentPeer* owner;
  218945. bool isZooming;
  218946. }
  218947. - (void) setOwner: (NSViewComponentPeer*) owner;
  218948. - (BOOL) canBecomeKeyWindow;
  218949. - (void) becomeKeyWindow;
  218950. - (BOOL) windowShouldClose: (id) window;
  218951. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  218952. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  218953. - (void) zoom: (id) sender;
  218954. @end
  218955. BEGIN_JUCE_NAMESPACE
  218956. class NSViewComponentPeer : public ComponentPeer
  218957. {
  218958. public:
  218959. NSViewComponentPeer (Component* const component,
  218960. const int windowStyleFlags,
  218961. NSView* viewToAttachTo);
  218962. ~NSViewComponentPeer();
  218963. void* getNativeHandle() const;
  218964. void setVisible (bool shouldBeVisible);
  218965. void setTitle (const String& title);
  218966. void setPosition (int x, int y);
  218967. void setSize (int w, int h);
  218968. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  218969. void getBounds (int& x, int& y, int& w, int& h, const bool global) const;
  218970. void getBounds (int& x, int& y, int& w, int& h) const;
  218971. int getScreenX() const;
  218972. int getScreenY() const;
  218973. void relativePositionToGlobal (int& x, int& y);
  218974. void globalPositionToRelative (int& x, int& y);
  218975. void setMinimised (bool shouldBeMinimised);
  218976. bool isMinimised() const;
  218977. void setFullScreen (bool shouldBeFullScreen);
  218978. bool isFullScreen() const;
  218979. bool contains (int x, int y, bool trueIfInAChildWindow) const;
  218980. const BorderSize getFrameSize() const;
  218981. bool setAlwaysOnTop (bool alwaysOnTop);
  218982. void toFront (bool makeActiveWindow);
  218983. void toBehind (ComponentPeer* other);
  218984. void setIcon (const Image& newIcon);
  218985. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  218986. for example having more than one juce plugin loaded into a host, then when a
  218987. method is called, the actual code that runs might actually be in a different module
  218988. than the one you expect... So any calls to library functions or statics that are
  218989. made inside obj-c methods will probably end up getting executed in a different DLL's
  218990. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  218991. To work around this insanity, I'm only allowing obj-c methods to make calls to
  218992. virtual methods of an object that's known to live inside the right module's space.
  218993. */
  218994. virtual void redirectMouseDown (NSEvent* ev);
  218995. virtual void redirectMouseUp (NSEvent* ev);
  218996. virtual void redirectMouseDrag (NSEvent* ev);
  218997. virtual void redirectMouseMove (NSEvent* ev);
  218998. virtual void redirectMouseEnter (NSEvent* ev);
  218999. virtual void redirectMouseExit (NSEvent* ev);
  219000. virtual void redirectMouseWheel (NSEvent* ev);
  219001. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  219002. virtual bool redirectKeyDown (NSEvent* ev);
  219003. virtual bool redirectKeyUp (NSEvent* ev);
  219004. virtual void redirectModKeyChange (NSEvent* ev);
  219005. #if MACOS_10_4_OR_EARLIER
  219006. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  219007. #endif
  219008. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  219009. virtual bool isOpaque();
  219010. virtual void drawRect (NSRect r);
  219011. virtual bool canBecomeKeyWindow();
  219012. virtual bool windowShouldClose();
  219013. virtual void redirectMovedOrResized();
  219014. virtual NSRect constrainRect (NSRect r);
  219015. static void showArrowCursorIfNeeded();
  219016. virtual void viewFocusGain();
  219017. virtual void viewFocusLoss();
  219018. bool isFocused() const;
  219019. void grabFocus();
  219020. void textInputRequired (int x, int y);
  219021. void repaint (int x, int y, int w, int h);
  219022. void performAnyPendingRepaintsNow();
  219023. juce_UseDebuggingNewOperator
  219024. NSWindow* window;
  219025. JuceNSView* view;
  219026. bool isSharedWindow, fullScreen;
  219027. };
  219028. END_JUCE_NAMESPACE
  219029. @implementation JuceNSView
  219030. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  219031. withFrame: (NSRect) frame
  219032. {
  219033. [super initWithFrame: frame];
  219034. owner = owner_;
  219035. notificationCenter = [NSNotificationCenter defaultCenter];
  219036. [notificationCenter addObserver: self
  219037. selector: @selector (frameChanged:)
  219038. name: NSViewFrameDidChangeNotification
  219039. object: self];
  219040. if (! owner_->isSharedWindow)
  219041. {
  219042. [notificationCenter addObserver: self
  219043. selector: @selector (frameChanged:)
  219044. name: NSWindowDidMoveNotification
  219045. object: owner_->window];
  219046. }
  219047. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  219048. return self;
  219049. }
  219050. - (void) dealloc
  219051. {
  219052. [notificationCenter removeObserver: self];
  219053. [super dealloc];
  219054. }
  219055. - (void) drawRect: (NSRect) r
  219056. {
  219057. if (owner != 0)
  219058. owner->drawRect (r);
  219059. }
  219060. - (BOOL) isOpaque
  219061. {
  219062. return owner == 0 || owner->isOpaque();
  219063. }
  219064. - (void) mouseDown: (NSEvent*) ev
  219065. {
  219066. // In some host situations, the host will stop modal loops from working
  219067. // correctly if they're called from a mouse event, so we'll trigger
  219068. // the event asynchronously..
  219069. if (JUCEApplication::getInstance() == 0)
  219070. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  219071. withObject: ev
  219072. waitUntilDone: NO];
  219073. else
  219074. [self asyncMouseDown: ev];
  219075. }
  219076. - (void) asyncMouseDown: (NSEvent*) ev
  219077. {
  219078. if (owner != 0)
  219079. owner->redirectMouseDown (ev);
  219080. }
  219081. - (void) mouseUp: (NSEvent*) ev
  219082. {
  219083. // In some host situations, the host will stop modal loops from working
  219084. // correctly if they're called from a mouse event, so we'll trigger
  219085. // the event asynchronously..
  219086. if (JUCEApplication::getInstance() == 0)
  219087. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  219088. withObject: ev
  219089. waitUntilDone: NO];
  219090. else
  219091. [self asyncMouseUp: ev];
  219092. }
  219093. - (void) asyncMouseUp: (NSEvent*) ev
  219094. {
  219095. if (owner != 0)
  219096. owner->redirectMouseUp (ev);
  219097. }
  219098. - (void) mouseDragged: (NSEvent*) ev
  219099. {
  219100. if (owner != 0)
  219101. owner->redirectMouseDrag (ev);
  219102. }
  219103. - (void) mouseMoved: (NSEvent*) ev
  219104. {
  219105. if (owner != 0)
  219106. owner->redirectMouseMove (ev);
  219107. }
  219108. - (void) mouseEntered: (NSEvent*) ev
  219109. {
  219110. if (owner != 0)
  219111. owner->redirectMouseEnter (ev);
  219112. }
  219113. - (void) mouseExited: (NSEvent*) ev
  219114. {
  219115. if (owner != 0)
  219116. owner->redirectMouseExit (ev);
  219117. }
  219118. - (void) rightMouseDown: (NSEvent*) ev
  219119. {
  219120. [self mouseDown: ev];
  219121. }
  219122. - (void) rightMouseDragged: (NSEvent*) ev
  219123. {
  219124. [self mouseDragged: ev];
  219125. }
  219126. - (void) rightMouseUp: (NSEvent*) ev
  219127. {
  219128. [self mouseUp: ev];
  219129. }
  219130. - (void) otherMouseDown: (NSEvent*) ev
  219131. {
  219132. [self mouseDown: ev];
  219133. }
  219134. - (void) otherMouseDragged: (NSEvent*) ev
  219135. {
  219136. [self mouseDragged: ev];
  219137. }
  219138. - (void) otherMouseUp: (NSEvent*) ev
  219139. {
  219140. [self mouseUp: ev];
  219141. }
  219142. - (void) scrollWheel: (NSEvent*) ev
  219143. {
  219144. if (owner != 0)
  219145. owner->redirectMouseWheel (ev);
  219146. }
  219147. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  219148. {
  219149. return YES;
  219150. }
  219151. - (void) frameChanged: (NSNotification*) n
  219152. {
  219153. if (owner != 0)
  219154. owner->redirectMovedOrResized();
  219155. }
  219156. - (void) keyDown: (NSEvent*) ev
  219157. {
  219158. if (owner == 0 || ! owner->redirectKeyDown (ev))
  219159. [super keyDown: ev];
  219160. }
  219161. - (void) keyUp: (NSEvent*) ev
  219162. {
  219163. if (owner == 0 || ! owner->redirectKeyUp (ev))
  219164. [super keyUp: ev];
  219165. }
  219166. - (void) flagsChanged: (NSEvent*) ev
  219167. {
  219168. if (owner != 0)
  219169. owner->redirectModKeyChange (ev);
  219170. }
  219171. #if MACOS_10_4_OR_EARLIER
  219172. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  219173. {
  219174. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  219175. return true;
  219176. return [super performKeyEquivalent: ev];
  219177. }
  219178. #endif
  219179. - (BOOL) becomeFirstResponder
  219180. {
  219181. if (owner != 0)
  219182. owner->viewFocusGain();
  219183. return true;
  219184. }
  219185. - (BOOL) resignFirstResponder
  219186. {
  219187. if (owner != 0)
  219188. owner->viewFocusLoss();
  219189. return true;
  219190. }
  219191. - (BOOL) acceptsFirstResponder
  219192. {
  219193. return owner != 0 && owner->canBecomeKeyWindow();
  219194. }
  219195. - (NSArray*) getSupportedDragTypes
  219196. {
  219197. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  219198. }
  219199. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  219200. {
  219201. return owner != 0 && owner->sendDragCallback (type, sender);
  219202. }
  219203. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  219204. {
  219205. if ([self sendDragCallback: 0 sender: sender])
  219206. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  219207. else
  219208. return NSDragOperationNone;
  219209. }
  219210. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  219211. {
  219212. if ([self sendDragCallback: 0 sender: sender])
  219213. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  219214. else
  219215. return NSDragOperationNone;
  219216. }
  219217. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  219218. {
  219219. [self sendDragCallback: 1 sender: sender];
  219220. }
  219221. - (void) draggingExited: (id <NSDraggingInfo>) sender
  219222. {
  219223. [self sendDragCallback: 1 sender: sender];
  219224. }
  219225. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  219226. {
  219227. return YES;
  219228. }
  219229. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  219230. {
  219231. return [self sendDragCallback: 2 sender: sender];
  219232. }
  219233. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  219234. {
  219235. }
  219236. @end
  219237. @implementation JuceNSWindow
  219238. - (void) setOwner: (NSViewComponentPeer*) owner_
  219239. {
  219240. owner = owner_;
  219241. isZooming = false;
  219242. }
  219243. - (BOOL) canBecomeKeyWindow
  219244. {
  219245. return owner != 0 && owner->canBecomeKeyWindow();
  219246. }
  219247. - (void) becomeKeyWindow
  219248. {
  219249. [super becomeKeyWindow];
  219250. if (owner != 0)
  219251. owner->grabFocus();
  219252. }
  219253. - (BOOL) windowShouldClose: (id) window
  219254. {
  219255. return owner == 0 || owner->windowShouldClose();
  219256. }
  219257. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  219258. {
  219259. if (owner != 0)
  219260. frameRect = owner->constrainRect (frameRect);
  219261. return frameRect;
  219262. }
  219263. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  219264. {
  219265. if (isZooming)
  219266. return proposedFrameSize;
  219267. NSRect frameRect = [self frame];
  219268. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  219269. frameRect.size = proposedFrameSize;
  219270. if (owner != 0)
  219271. frameRect = owner->constrainRect (frameRect);
  219272. return frameRect.size;
  219273. }
  219274. - (void) zoom: (id) sender
  219275. {
  219276. isZooming = true;
  219277. [super zoom: sender];
  219278. isZooming = false;
  219279. }
  219280. - (void) windowWillMove: (NSNotification*) notification
  219281. {
  219282. if (juce::Component::getCurrentlyModalComponent() != 0
  219283. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  219284. && (owner->getStyleFlags() & juce::ComponentPeer::windowHasTitleBar) != 0)
  219285. juce::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  219286. }
  219287. @end
  219288. BEGIN_JUCE_NAMESPACE
  219289. class JuceNSImage
  219290. {
  219291. public:
  219292. JuceNSImage (const int width, const int height, const bool hasAlpha)
  219293. : juceImage (hasAlpha ? Image::ARGB : Image::RGB,
  219294. width, height, hasAlpha)
  219295. {
  219296. lineStride = 0;
  219297. pixelStride = 0;
  219298. imageData = juceImage.lockPixelDataReadWrite (0, 0, width, height,
  219299. lineStride, pixelStride);
  219300. imageRep = [[NSBitmapImageRep alloc]
  219301. initWithBitmapDataPlanes: &imageData
  219302. pixelsWide: width
  219303. pixelsHigh: height
  219304. bitsPerSample: 8
  219305. samplesPerPixel: pixelStride
  219306. hasAlpha: hasAlpha
  219307. isPlanar: NO
  219308. colorSpaceName: NSCalibratedRGBColorSpace
  219309. bitmapFormat: /*NSAlphaFirstBitmapFormat*/ (NSBitmapFormat) 0
  219310. bytesPerRow: lineStride
  219311. bitsPerPixel: 8 * pixelStride ];
  219312. juceImage.releasePixelDataReadWrite (imageData);
  219313. }
  219314. ~JuceNSImage()
  219315. {
  219316. [imageRep release];
  219317. }
  219318. Image& getJuceImage() throw() { return juceImage; }
  219319. void draw (const float x, const float y,
  219320. const RectangleList& clip,
  219321. const int originX, const int originY) const
  219322. {
  219323. // Our data is BGRA and the damned image rep only takes RGBA, so
  219324. // we need to byte-swap the active areas if there's an alpha channel...
  219325. if (juceImage.hasAlphaChannel())
  219326. {
  219327. RectangleList::Iterator iter (clip);
  219328. while (iter.next())
  219329. {
  219330. const Rectangle* const r = iter.getRectangle();
  219331. swapRGBOrder (r->getX() + originX,
  219332. r->getY() + originY,
  219333. r->getWidth(),
  219334. r->getHeight());
  219335. }
  219336. }
  219337. NSPoint p;
  219338. p.x = x;
  219339. p.y = y;
  219340. [imageRep drawAtPoint: p];
  219341. }
  219342. void drawNSImage (NSImage* imageToDraw)
  219343. {
  219344. const ScopedAutoReleasePool pool;
  219345. [NSGraphicsContext saveGraphicsState];
  219346. [NSGraphicsContext setCurrentContext:
  219347. [NSGraphicsContext graphicsContextWithBitmapImageRep: imageRep]];
  219348. [imageToDraw drawAtPoint: NSZeroPoint
  219349. fromRect: NSMakeRect (0, 0, [imageToDraw size].width, [imageToDraw size].height)
  219350. operation: NSCompositeSourceOver
  219351. fraction: 1.0f];
  219352. [[NSGraphicsContext currentContext] flushGraphics];
  219353. [NSGraphicsContext restoreGraphicsState];
  219354. if (juceImage.hasAlphaChannel())
  219355. swapRGBOrder (0, 0, juceImage.getWidth(), juceImage.getHeight());
  219356. }
  219357. private:
  219358. Image juceImage;
  219359. NSBitmapImageRep* imageRep;
  219360. uint8* imageData;
  219361. int pixelStride, lineStride;
  219362. void swapRGBOrder (const int x, const int y, const int w, int h) const
  219363. {
  219364. #if JUCE_BIG_ENDIAN
  219365. jassert (pixelStride == 4);
  219366. #endif
  219367. jassert (Rectangle (0, 0, juceImage.getWidth(), juceImage.getHeight())
  219368. .contains (Rectangle (x, y, w, h)));
  219369. uint8* start = imageData + x * pixelStride + y * lineStride;
  219370. while (--h >= 0)
  219371. {
  219372. uint8* p = start;
  219373. start += lineStride;
  219374. for (int i = w; --i >= 0;)
  219375. {
  219376. #if JUCE_BIG_ENDIAN
  219377. const uint8 oldp3 = p[3];
  219378. const uint8 oldp1 = p[1];
  219379. p[3] = p[0];
  219380. p[0] = oldp1;
  219381. p[1] = p[2];
  219382. p[2] = oldp3;
  219383. #else
  219384. const uint8 oldp0 = p[0];
  219385. p[0] = p[2];
  219386. p[2] = oldp0;
  219387. #endif
  219388. p += pixelStride;
  219389. }
  219390. }
  219391. }
  219392. };
  219393. static ComponentPeer* currentlyFocusedPeer = 0;
  219394. static VoidArray keysCurrentlyDown;
  219395. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  219396. {
  219397. if (keysCurrentlyDown.contains ((void*) keyCode))
  219398. return true;
  219399. if (keyCode >= 'A' && keyCode <= 'Z'
  219400. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toLowerCase ((tchar) keyCode)))
  219401. return true;
  219402. if (keyCode >= 'a' && keyCode <= 'z'
  219403. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toUpperCase ((tchar) keyCode)))
  219404. return true;
  219405. return false;
  219406. }
  219407. static int getKeyCodeFromEvent (NSEvent* ev)
  219408. {
  219409. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  219410. int keyCode = unmodified[0];
  219411. if (keyCode == 0x19) // (backwards-tab)
  219412. keyCode = '\t';
  219413. else if (keyCode == 0x03) // (enter)
  219414. keyCode = '\r';
  219415. return keyCode;
  219416. }
  219417. static int currentModifiers = 0;
  219418. static void updateModifiers (NSEvent* e)
  219419. {
  219420. int m = currentModifiers & ~(ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier
  219421. | ModifierKeys::altModifier | ModifierKeys::commandModifier);
  219422. if (([e modifierFlags] & NSShiftKeyMask) != 0)
  219423. m |= ModifierKeys::shiftModifier;
  219424. if (([e modifierFlags] & NSControlKeyMask) != 0)
  219425. m |= ModifierKeys::ctrlModifier;
  219426. if (([e modifierFlags] & NSAlternateKeyMask) != 0)
  219427. m |= ModifierKeys::altModifier;
  219428. if (([e modifierFlags] & NSCommandKeyMask) != 0)
  219429. m |= ModifierKeys::commandModifier;
  219430. currentModifiers = m;
  219431. }
  219432. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  219433. {
  219434. updateModifiers (ev);
  219435. int keyCode = getKeyCodeFromEvent (ev);
  219436. if (keyCode != 0)
  219437. {
  219438. if (isKeyDown)
  219439. keysCurrentlyDown.addIfNotAlreadyThere ((void*) keyCode);
  219440. else
  219441. keysCurrentlyDown.removeValue ((void*) keyCode);
  219442. }
  219443. }
  219444. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  219445. {
  219446. return ModifierKeys (currentModifiers);
  219447. }
  219448. void ModifierKeys::updateCurrentModifiers() throw()
  219449. {
  219450. currentModifierFlags = currentModifiers;
  219451. }
  219452. static int64 getMouseTime (NSEvent* e) { return (int64) [e timestamp] * 1000.0; }
  219453. static void getMousePos (NSEvent* e, NSView* view, int& x, int& y)
  219454. {
  219455. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  219456. x = roundFloatToInt (p.x);
  219457. y = roundFloatToInt ([view frame].size.height - p.y);
  219458. }
  219459. static int getModifierForButtonNumber (const int num) throw()
  219460. {
  219461. return num == 0 ? ModifierKeys::leftButtonModifier
  219462. : (num == 1 ? ModifierKeys::rightButtonModifier
  219463. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  219464. }
  219465. NSViewComponentPeer::NSViewComponentPeer (Component* const component,
  219466. const int windowStyleFlags,
  219467. NSView* viewToAttachTo)
  219468. : ComponentPeer (component, windowStyleFlags),
  219469. window (0),
  219470. view (0)
  219471. {
  219472. NSRect r;
  219473. r.origin.x = 0;
  219474. r.origin.y = 0;
  219475. r.size.width = (float) component->getWidth();
  219476. r.size.height = (float) component->getHeight();
  219477. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  219478. [view setPostsFrameChangedNotifications: YES];
  219479. if (viewToAttachTo != 0)
  219480. {
  219481. window = [viewToAttachTo window];
  219482. [viewToAttachTo addSubview: view];
  219483. isSharedWindow = true;
  219484. setVisible (component->isVisible());
  219485. }
  219486. else
  219487. {
  219488. isSharedWindow = false;
  219489. r.origin.x = (float) component->getX();
  219490. r.origin.y = (float) component->getY();
  219491. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  219492. unsigned int style = 0;
  219493. if ((windowStyleFlags & windowHasTitleBar) == 0)
  219494. style = NSBorderlessWindowMask;
  219495. else
  219496. style = NSTitledWindowMask;
  219497. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  219498. style |= NSMiniaturizableWindowMask;
  219499. if ((windowStyleFlags & windowHasCloseButton) != 0)
  219500. style |= NSClosableWindowMask;
  219501. if ((windowStyleFlags & windowIsResizable) != 0)
  219502. style |= NSResizableWindowMask;
  219503. window = [[JuceNSWindow alloc] initWithContentRect: r
  219504. styleMask: style
  219505. backing: NSBackingStoreBuffered
  219506. defer: YES];
  219507. [((JuceNSWindow*) window) setOwner: this];
  219508. [window orderOut: nil];
  219509. [window setDelegate: window];
  219510. [window setOpaque: component->isOpaque()];
  219511. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  219512. if (component->isAlwaysOnTop())
  219513. [window setLevel: NSFloatingWindowLevel];
  219514. [window setContentView: view];
  219515. [window setAutodisplay: YES];
  219516. [window setAcceptsMouseMovedEvents: YES];
  219517. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  219518. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  219519. [window setReleasedWhenClosed: YES];
  219520. [window retain];
  219521. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  219522. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  219523. }
  219524. setTitle (component->getName());
  219525. }
  219526. NSViewComponentPeer::~NSViewComponentPeer()
  219527. {
  219528. view->owner = 0;
  219529. [view removeFromSuperview];
  219530. [view release];
  219531. if (! isSharedWindow)
  219532. {
  219533. [((JuceNSWindow*) window) setOwner: 0];
  219534. [window close];
  219535. [window release];
  219536. }
  219537. }
  219538. void* NSViewComponentPeer::getNativeHandle() const
  219539. {
  219540. return view;
  219541. }
  219542. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  219543. {
  219544. if (isSharedWindow)
  219545. {
  219546. [view setHidden: ! shouldBeVisible];
  219547. }
  219548. else
  219549. {
  219550. if (shouldBeVisible)
  219551. [window orderFront: nil];
  219552. else
  219553. [window orderOut: nil];
  219554. }
  219555. }
  219556. void NSViewComponentPeer::setTitle (const String& title)
  219557. {
  219558. const ScopedAutoReleasePool pool;
  219559. if (! isSharedWindow)
  219560. [window setTitle: juceStringToNS (title)];
  219561. }
  219562. void NSViewComponentPeer::setPosition (int x, int y)
  219563. {
  219564. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  219565. }
  219566. void NSViewComponentPeer::setSize (int w, int h)
  219567. {
  219568. setBounds (component->getX(), component->getY(), w, h, false);
  219569. }
  219570. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  219571. {
  219572. fullScreen = isNowFullScreen;
  219573. w = jmax (0, w);
  219574. h = jmax (0, h);
  219575. NSRect r;
  219576. r.origin.x = (float) x;
  219577. r.origin.y = (float) y;
  219578. r.size.width = (float) w;
  219579. r.size.height = (float) h;
  219580. if (isSharedWindow)
  219581. {
  219582. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  219583. if ([view frame].size.width != r.size.width
  219584. || [view frame].size.height != r.size.height)
  219585. [view setNeedsDisplay: true];
  219586. [view setFrame: r];
  219587. }
  219588. else
  219589. {
  219590. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  219591. [window setFrame: [window frameRectForContentRect: r]
  219592. display: true];
  219593. }
  219594. }
  219595. void NSViewComponentPeer::getBounds (int& x, int& y, int& w, int& h, const bool global) const
  219596. {
  219597. NSRect r = [view frame];
  219598. if (global && [view window] != 0)
  219599. {
  219600. r = [view convertRect: r toView: nil];
  219601. NSRect wr = [[view window] frame];
  219602. r.origin.x += wr.origin.x;
  219603. r.origin.y += wr.origin.y;
  219604. y = (int) ([[[NSScreen screens] objectAtIndex:0] frame].size.height - r.origin.y - r.size.height);
  219605. }
  219606. else
  219607. {
  219608. y = (int) ([[view superview] frame].size.height - r.origin.y - r.size.height);
  219609. }
  219610. x = (int) r.origin.x;
  219611. w = (int) r.size.width;
  219612. h = (int) r.size.height;
  219613. }
  219614. void NSViewComponentPeer::getBounds (int& x, int& y, int& w, int& h) const
  219615. {
  219616. getBounds (x, y, w, h, ! isSharedWindow);
  219617. }
  219618. int NSViewComponentPeer::getScreenX() const
  219619. {
  219620. int x, y, w, h;
  219621. getBounds (x, y, w, h, true);
  219622. return x;
  219623. }
  219624. int NSViewComponentPeer::getScreenY() const
  219625. {
  219626. int x, y, w, h;
  219627. getBounds (x, y, w, h, true);
  219628. return y;
  219629. }
  219630. void NSViewComponentPeer::relativePositionToGlobal (int& x, int& y)
  219631. {
  219632. int wx, wy, ww, wh;
  219633. getBounds (wx, wy, ww, wh, true);
  219634. x += wx;
  219635. y += wy;
  219636. }
  219637. void NSViewComponentPeer::globalPositionToRelative (int& x, int& y)
  219638. {
  219639. int wx, wy, ww, wh;
  219640. getBounds (wx, wy, ww, wh, true);
  219641. x -= wx;
  219642. y -= wy;
  219643. }
  219644. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  219645. {
  219646. if (constrainer != 0)
  219647. {
  219648. NSRect current = [window frame];
  219649. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  219650. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  219651. int x = (int) r.origin.x;
  219652. int y = (int) r.origin.y;
  219653. int w = (int) r.size.width;
  219654. int h = (int) r.size.height;
  219655. Rectangle original ((int) current.origin.x, (int) current.origin.y,
  219656. (int) current.size.width, (int) current.size.height);
  219657. constrainer->checkBounds (x, y, w, h,
  219658. original,
  219659. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  219660. y != original.getY() && y + h == original.getBottom(),
  219661. x != original.getX() && x + w == original.getRight(),
  219662. y == original.getY() && y + h != original.getBottom(),
  219663. x == original.getX() && x + w != original.getRight());
  219664. r.origin.x = x;
  219665. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - y;
  219666. r.size.width = w;
  219667. r.size.height = h;
  219668. }
  219669. return r;
  219670. }
  219671. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  219672. {
  219673. if (! isSharedWindow)
  219674. {
  219675. if (shouldBeMinimised)
  219676. [window miniaturize: nil];
  219677. else
  219678. [window deminiaturize: nil];
  219679. }
  219680. }
  219681. bool NSViewComponentPeer::isMinimised() const
  219682. {
  219683. return window != 0 && [window isMiniaturized];
  219684. }
  219685. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  219686. {
  219687. if (! isSharedWindow)
  219688. {
  219689. Rectangle r (lastNonFullscreenBounds);
  219690. setMinimised (false);
  219691. if (fullScreen != shouldBeFullScreen)
  219692. {
  219693. if (shouldBeFullScreen)
  219694. r = Desktop::getInstance().getMainMonitorArea();
  219695. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  219696. if (r != getComponent()->getBounds() && ! r.isEmpty())
  219697. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  219698. }
  219699. }
  219700. }
  219701. bool NSViewComponentPeer::isFullScreen() const
  219702. {
  219703. return fullScreen;
  219704. }
  219705. bool NSViewComponentPeer::contains (int x, int y, bool trueIfInAChildWindow) const
  219706. {
  219707. if (((unsigned int) x) >= (unsigned int) component->getWidth()
  219708. || ((unsigned int) y) >= (unsigned int) component->getHeight())
  219709. return false;
  219710. NSPoint p;
  219711. p.x = (float) x;
  219712. p.y = (float) y;
  219713. NSView* v = [view hitTest: p];
  219714. if (trueIfInAChildWindow)
  219715. return v != nil;
  219716. return v == view;
  219717. }
  219718. const BorderSize NSViewComponentPeer::getFrameSize() const
  219719. {
  219720. BorderSize b;
  219721. if (! isSharedWindow)
  219722. {
  219723. NSRect v = [view convertRect: [view frame] toView: nil];
  219724. NSRect w = [window frame];
  219725. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  219726. b.setBottom ((int) v.origin.y);
  219727. b.setLeft ((int) v.origin.x);
  219728. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  219729. }
  219730. return b;
  219731. }
  219732. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  219733. {
  219734. if (! isSharedWindow)
  219735. {
  219736. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  219737. : NSNormalWindowLevel];
  219738. }
  219739. return true;
  219740. }
  219741. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  219742. {
  219743. if (isSharedWindow)
  219744. {
  219745. [[view superview] addSubview: view
  219746. positioned: NSWindowAbove
  219747. relativeTo: nil];
  219748. }
  219749. if (window != 0 && component->isVisible())
  219750. {
  219751. if (makeActiveWindow)
  219752. [window makeKeyAndOrderFront: nil];
  219753. else
  219754. [window orderFront: nil];
  219755. }
  219756. }
  219757. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  219758. {
  219759. NSViewComponentPeer* o = (NSViewComponentPeer*) other;
  219760. if (isSharedWindow)
  219761. {
  219762. [[view superview] addSubview: view
  219763. positioned: NSWindowBelow
  219764. relativeTo: o->view];
  219765. }
  219766. else
  219767. {
  219768. [window orderWindow: NSWindowBelow
  219769. relativeTo: o->window != 0 ? [o->window windowNumber]
  219770. : nil ];
  219771. }
  219772. }
  219773. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  219774. {
  219775. // to do..
  219776. }
  219777. void NSViewComponentPeer::viewFocusGain()
  219778. {
  219779. if (currentlyFocusedPeer != this)
  219780. {
  219781. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  219782. currentlyFocusedPeer->handleFocusLoss();
  219783. currentlyFocusedPeer = this;
  219784. handleFocusGain();
  219785. }
  219786. }
  219787. void NSViewComponentPeer::viewFocusLoss()
  219788. {
  219789. if (currentlyFocusedPeer == this)
  219790. {
  219791. currentlyFocusedPeer = 0;
  219792. handleFocusLoss();
  219793. }
  219794. }
  219795. void juce_HandleProcessFocusChange()
  219796. {
  219797. keysCurrentlyDown.clear();
  219798. if (NSViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  219799. {
  219800. if (Process::isForegroundProcess())
  219801. {
  219802. currentlyFocusedPeer->handleFocusGain();
  219803. ComponentPeer::bringModalComponentToFront();
  219804. }
  219805. else
  219806. {
  219807. currentlyFocusedPeer->handleFocusLoss();
  219808. // turn kiosk mode off if we lose focus..
  219809. Desktop::getInstance().setKioskModeComponent (0);
  219810. }
  219811. }
  219812. }
  219813. bool NSViewComponentPeer::isFocused() const
  219814. {
  219815. return isSharedWindow ? this == currentlyFocusedPeer
  219816. : (window != 0 && [window isKeyWindow]);
  219817. }
  219818. void NSViewComponentPeer::grabFocus()
  219819. {
  219820. if (window != 0)
  219821. {
  219822. [window makeKeyWindow];
  219823. [window makeFirstResponder: view];
  219824. viewFocusGain();
  219825. }
  219826. }
  219827. void NSViewComponentPeer::textInputRequired (int /*x*/, int /*y*/)
  219828. {
  219829. }
  219830. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  219831. {
  219832. String unicode (nsStringToJuce ([ev characters]));
  219833. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  219834. int keyCode = getKeyCodeFromEvent (ev);
  219835. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  219836. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  219837. if (unicode.isNotEmpty() || keyCode != 0)
  219838. {
  219839. if (isKeyDown)
  219840. {
  219841. bool used = false;
  219842. while (unicode.length() > 0)
  219843. {
  219844. juce_wchar textCharacter = unicode[0];
  219845. unicode = unicode.substring (1);
  219846. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  219847. textCharacter = 0;
  219848. used = handleKeyUpOrDown (true) || used;
  219849. used = handleKeyPress (keyCode, textCharacter) || used;
  219850. }
  219851. return used;
  219852. }
  219853. else
  219854. {
  219855. if (handleKeyUpOrDown (false))
  219856. return true;
  219857. }
  219858. }
  219859. return false;
  219860. }
  219861. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  219862. {
  219863. updateKeysDown (ev, true);
  219864. bool used = handleKeyEvent (ev, true);
  219865. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  219866. {
  219867. // for command keys, the key-up event is thrown away, so simulate one..
  219868. updateKeysDown (ev, false);
  219869. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  219870. }
  219871. // (If we're running modally, don't allow unused keystrokes to be passed
  219872. // along to other blocked views..)
  219873. if (Component::getCurrentlyModalComponent() != 0)
  219874. used = true;
  219875. return used;
  219876. }
  219877. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  219878. {
  219879. updateKeysDown (ev, false);
  219880. return handleKeyEvent (ev, false)
  219881. || Component::getCurrentlyModalComponent() != 0;
  219882. }
  219883. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  219884. {
  219885. updateModifiers (ev);
  219886. handleModifierKeysChange();
  219887. }
  219888. #if MACOS_10_4_OR_EARLIER
  219889. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  219890. {
  219891. if ([ev type] == NSKeyDown)
  219892. return redirectKeyDown (ev);
  219893. else if ([ev type] == NSKeyUp)
  219894. return redirectKeyUp (ev);
  219895. return false;
  219896. }
  219897. #endif
  219898. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  219899. {
  219900. updateModifiers (ev);
  219901. currentModifiers |= getModifierForButtonNumber ([ev buttonNumber]);
  219902. int x, y;
  219903. getMousePos (ev, view, x, y);
  219904. handleMouseDown (x, y, getMouseTime (ev));
  219905. }
  219906. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  219907. {
  219908. const int oldMods = currentModifiers;
  219909. updateModifiers (ev);
  219910. currentModifiers &= ~getModifierForButtonNumber ([ev buttonNumber]);
  219911. int x, y;
  219912. getMousePos (ev, view, x, y);
  219913. handleMouseUp (oldMods, x, y, getMouseTime (ev));
  219914. showArrowCursorIfNeeded();
  219915. }
  219916. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  219917. {
  219918. updateModifiers (ev);
  219919. currentModifiers |= getModifierForButtonNumber ([ev buttonNumber]);
  219920. int x, y;
  219921. getMousePos (ev, view, x, y);
  219922. handleMouseDrag (x, y, getMouseTime (ev));
  219923. }
  219924. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  219925. {
  219926. updateModifiers (ev);
  219927. int x, y;
  219928. getMousePos (ev, view, x, y);
  219929. handleMouseMove (x, y, getMouseTime (ev));
  219930. showArrowCursorIfNeeded();
  219931. }
  219932. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  219933. {
  219934. updateModifiers (ev);
  219935. int x, y;
  219936. getMousePos (ev, view, x, y);
  219937. handleMouseEnter (x, y, getMouseTime (ev));
  219938. }
  219939. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  219940. {
  219941. updateModifiers (ev);
  219942. int x, y;
  219943. getMousePos (ev, view, x, y);
  219944. handleMouseExit (x, y, getMouseTime (ev));
  219945. }
  219946. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  219947. {
  219948. updateModifiers (ev);
  219949. handleMouseWheel (roundFloatToInt ([ev deltaX] * 10.0f),
  219950. roundFloatToInt ([ev deltaY] * 10.0f),
  219951. getMouseTime (ev));
  219952. }
  219953. void NSViewComponentPeer::showArrowCursorIfNeeded()
  219954. {
  219955. if (Component::getComponentUnderMouse() == 0)
  219956. {
  219957. int mx, my;
  219958. Desktop::getInstance().getMousePosition (mx, my);
  219959. if (Desktop::getInstance().findComponentAt (mx, my) == 0)
  219960. [[NSCursor arrowCursor] set];
  219961. }
  219962. }
  219963. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  219964. {
  219965. NSString* bestType
  219966. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  219967. if (bestType == nil)
  219968. return false;
  219969. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  219970. int x = (int) p.x;
  219971. int y = (int) ([view frame].size.height - p.y);
  219972. StringArray files;
  219973. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  219974. if (list == nil)
  219975. return false;
  219976. if ([list isKindOfClass: [NSArray class]])
  219977. {
  219978. NSArray* items = (NSArray*) list;
  219979. for (unsigned int i = 0; i < [items count]; ++i)
  219980. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  219981. }
  219982. if (files.size() == 0)
  219983. return false;
  219984. if (type == 0)
  219985. handleFileDragMove (files, x, y);
  219986. else if (type == 1)
  219987. handleFileDragExit (files);
  219988. else if (type == 2)
  219989. handleFileDragDrop (files, x, y);
  219990. return true;
  219991. }
  219992. bool NSViewComponentPeer::isOpaque()
  219993. {
  219994. if (! getComponent()->isValidComponent())
  219995. return true;
  219996. return getComponent()->isOpaque();
  219997. }
  219998. void NSViewComponentPeer::drawRect (NSRect r)
  219999. {
  220000. if (r.size.width < 1.0f || r.size.height < 1.0f)
  220001. return;
  220002. const float y = [view frame].size.height - (r.origin.y + r.size.height);
  220003. JuceNSImage temp ((int) (r.size.width + 0.5f),
  220004. (int) (r.size.height + 0.5f),
  220005. ! getComponent()->isOpaque());
  220006. LowLevelGraphicsSoftwareRenderer context (temp.getJuceImage());
  220007. const int originX = -roundFloatToInt (r.origin.x);
  220008. const int originY = -roundFloatToInt (y);
  220009. context.setOrigin (originX, originY);
  220010. const NSRect* rects = 0;
  220011. NSInteger numRects = 0;
  220012. [view getRectsBeingDrawn: &rects count: &numRects];
  220013. RectangleList clip;
  220014. for (int i = 0; i < numRects; ++i)
  220015. {
  220016. clip.addWithoutMerging (Rectangle (roundFloatToInt (rects[i].origin.x),
  220017. roundFloatToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)),
  220018. roundFloatToInt (rects[i].size.width),
  220019. roundFloatToInt (rects[i].size.height)));
  220020. }
  220021. if (context.reduceClipRegion (clip))
  220022. {
  220023. handlePaint (context);
  220024. temp.draw (r.origin.x, r.origin.y, clip, originX, originY);
  220025. }
  220026. }
  220027. bool NSViewComponentPeer::canBecomeKeyWindow()
  220028. {
  220029. // If running as a plugin, let the component decide whether it's going to allow the window to get focused.
  220030. return ((getStyleFlags() & juce::ComponentPeer::windowIsTemporary) == 0)
  220031. && (JUCEApplication::getInstance() != 0
  220032. || (isValidPeer (this)
  220033. && ! getComponent()->getComponentPropertyBool ("juce_disallowFocus", false, false)));
  220034. }
  220035. bool NSViewComponentPeer::windowShouldClose()
  220036. {
  220037. if (! isValidPeer (this))
  220038. return YES;
  220039. handleUserClosingWindow();
  220040. return NO;
  220041. }
  220042. void NSViewComponentPeer::redirectMovedOrResized()
  220043. {
  220044. handleMovedOrResized();
  220045. }
  220046. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220047. {
  220048. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  220049. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  220050. // is apparently still available in 64-bit apps..
  220051. if (enableOrDisable)
  220052. {
  220053. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  220054. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220055. }
  220056. else
  220057. {
  220058. SetSystemUIMode (kUIModeNormal, 0);
  220059. }
  220060. }
  220061. void NSViewComponentPeer::repaint (int x, int y, int w, int h)
  220062. {
  220063. [view setNeedsDisplayInRect:
  220064. NSMakeRect ((float) x, (float) ([view frame].size.height - (y + h)),
  220065. (float) w, (float) h)];
  220066. }
  220067. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  220068. {
  220069. [view displayIfNeeded];
  220070. }
  220071. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  220072. {
  220073. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  220074. }
  220075. static Image* NSImageToJuceImage (NSImage* image)
  220076. {
  220077. JuceNSImage juceIm ((int) [image size].width,
  220078. (int) [image size].height,
  220079. true);
  220080. juceIm.drawNSImage (image);
  220081. return juceIm.getJuceImage().createCopy();
  220082. }
  220083. Image* juce_createIconForFile (const File& file)
  220084. {
  220085. const ScopedAutoReleasePool pool;
  220086. NSImage* im = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  220087. return NSImageToJuceImage (im);
  220088. }
  220089. const int KeyPress::spaceKey = ' ';
  220090. const int KeyPress::returnKey = 0x0d;
  220091. const int KeyPress::escapeKey = 0x1b;
  220092. const int KeyPress::backspaceKey = 0x7f;
  220093. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  220094. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  220095. const int KeyPress::upKey = NSUpArrowFunctionKey;
  220096. const int KeyPress::downKey = NSDownArrowFunctionKey;
  220097. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  220098. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  220099. const int KeyPress::endKey = NSEndFunctionKey;
  220100. const int KeyPress::homeKey = NSHomeFunctionKey;
  220101. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  220102. const int KeyPress::insertKey = -1;
  220103. const int KeyPress::tabKey = 9;
  220104. const int KeyPress::F1Key = NSF1FunctionKey;
  220105. const int KeyPress::F2Key = NSF2FunctionKey;
  220106. const int KeyPress::F3Key = NSF3FunctionKey;
  220107. const int KeyPress::F4Key = NSF4FunctionKey;
  220108. const int KeyPress::F5Key = NSF5FunctionKey;
  220109. const int KeyPress::F6Key = NSF6FunctionKey;
  220110. const int KeyPress::F7Key = NSF7FunctionKey;
  220111. const int KeyPress::F8Key = NSF8FunctionKey;
  220112. const int KeyPress::F9Key = NSF9FunctionKey;
  220113. const int KeyPress::F10Key = NSF10FunctionKey;
  220114. const int KeyPress::F11Key = NSF1FunctionKey;
  220115. const int KeyPress::F12Key = NSF12FunctionKey;
  220116. const int KeyPress::F13Key = NSF13FunctionKey;
  220117. const int KeyPress::F14Key = NSF14FunctionKey;
  220118. const int KeyPress::F15Key = NSF15FunctionKey;
  220119. const int KeyPress::F16Key = NSF16FunctionKey;
  220120. const int KeyPress::numberPad0 = 0x30020;
  220121. const int KeyPress::numberPad1 = 0x30021;
  220122. const int KeyPress::numberPad2 = 0x30022;
  220123. const int KeyPress::numberPad3 = 0x30023;
  220124. const int KeyPress::numberPad4 = 0x30024;
  220125. const int KeyPress::numberPad5 = 0x30025;
  220126. const int KeyPress::numberPad6 = 0x30026;
  220127. const int KeyPress::numberPad7 = 0x30027;
  220128. const int KeyPress::numberPad8 = 0x30028;
  220129. const int KeyPress::numberPad9 = 0x30029;
  220130. const int KeyPress::numberPadAdd = 0x3002a;
  220131. const int KeyPress::numberPadSubtract = 0x3002b;
  220132. const int KeyPress::numberPadMultiply = 0x3002c;
  220133. const int KeyPress::numberPadDivide = 0x3002d;
  220134. const int KeyPress::numberPadSeparator = 0x3002e;
  220135. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  220136. const int KeyPress::numberPadEquals = 0x30030;
  220137. const int KeyPress::numberPadDelete = 0x30031;
  220138. const int KeyPress::playKey = 0x30000;
  220139. const int KeyPress::stopKey = 0x30001;
  220140. const int KeyPress::fastForwardKey = 0x30002;
  220141. const int KeyPress::rewindKey = 0x30003;
  220142. #endif
  220143. /********* End of inlined file: juce_mac_NSViewComponentPeer.mm *********/
  220144. /********* Start of inlined file: juce_mac_MouseCursor.mm *********/
  220145. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220146. // compiled on its own).
  220147. #ifdef JUCE_INCLUDED_FILE
  220148. static NSImage* juceImageToNSImage (const Image& image)
  220149. {
  220150. const ScopedAutoReleasePool pool;
  220151. int lineStride, pixelStride;
  220152. const uint8* pixels = image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(),
  220153. lineStride, pixelStride);
  220154. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  220155. initWithBitmapDataPlanes: NULL
  220156. pixelsWide: image.getWidth()
  220157. pixelsHigh: image.getHeight()
  220158. bitsPerSample: 8
  220159. samplesPerPixel: image.hasAlphaChannel() ? 4 : 3
  220160. hasAlpha: image.hasAlphaChannel()
  220161. isPlanar: NO
  220162. colorSpaceName: NSCalibratedRGBColorSpace
  220163. bitmapFormat: (NSBitmapFormat) 0
  220164. bytesPerRow: lineStride
  220165. bitsPerPixel: pixelStride * 8];
  220166. unsigned char* newData = [rep bitmapData];
  220167. memcpy (newData, pixels, lineStride * image.getHeight());
  220168. image.releasePixelDataReadOnly (pixels);
  220169. NSImage* im = [[NSImage alloc] init];
  220170. [im addRepresentation: rep];
  220171. [rep release];
  220172. return im;
  220173. }
  220174. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  220175. {
  220176. NSImage* im = juceImageToNSImage (image);
  220177. NSCursor* c = [[NSCursor alloc] initWithImage: im
  220178. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  220179. [im release];
  220180. return (void*) c;
  220181. }
  220182. static void* juce_cursorFromData (const unsigned char* data, const int size, float hx, float hy) throw()
  220183. {
  220184. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  220185. jassert (im != 0);
  220186. if (im == 0)
  220187. return 0;
  220188. void* const curs = juce_createMouseCursorFromImage (*im,
  220189. (int) (hx * im->getWidth()),
  220190. (int) (hy * im->getHeight()));
  220191. delete im;
  220192. return curs;
  220193. }
  220194. static void* juce_cursorFromWebKitFile (const char* filename, float hx, float hy)
  220195. {
  220196. File f ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources");
  220197. MemoryBlock mb;
  220198. if (f.getChildFile (filename).loadFileAsData (mb))
  220199. return juce_cursorFromData ((const unsigned char*) mb.getData(), mb.getSize(), hx, hy);
  220200. return 0;
  220201. }
  220202. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  220203. {
  220204. const ScopedAutoReleasePool pool;
  220205. NSCursor* c = 0;
  220206. switch (type)
  220207. {
  220208. case MouseCursor::NormalCursor:
  220209. c = [NSCursor arrowCursor];
  220210. break;
  220211. case MouseCursor::NoCursor:
  220212. {
  220213. Image blank (Image::ARGB, 8, 8, true);
  220214. return juce_createMouseCursorFromImage (blank, 0, 0);
  220215. }
  220216. case MouseCursor::DraggingHandCursor:
  220217. c = [NSCursor openHandCursor];
  220218. break;
  220219. case MouseCursor::CopyingCursor:
  220220. return juce_cursorFromWebKitFile ("copyCursor.png", 0, 0);
  220221. case MouseCursor::WaitCursor:
  220222. c = [NSCursor arrowCursor]; // avoid this on the mac, let the OS provide the beachball
  220223. break;
  220224. //return juce_cursorFromWebKitFile ("waitCursor.png", 0.5f, 0.5f);
  220225. case MouseCursor::IBeamCursor:
  220226. c = [NSCursor IBeamCursor];
  220227. break;
  220228. case MouseCursor::PointingHandCursor:
  220229. c = [NSCursor pointingHandCursor];
  220230. break;
  220231. case MouseCursor::LeftRightResizeCursor:
  220232. c = [NSCursor resizeLeftRightCursor];
  220233. break;
  220234. case MouseCursor::LeftEdgeResizeCursor:
  220235. c = [NSCursor resizeLeftCursor];
  220236. break;
  220237. case MouseCursor::RightEdgeResizeCursor:
  220238. c = [NSCursor resizeRightCursor];
  220239. break;
  220240. case MouseCursor::UpDownResizeCursor:
  220241. case MouseCursor::TopEdgeResizeCursor:
  220242. case MouseCursor::BottomEdgeResizeCursor:
  220243. return juce_cursorFromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  220244. case MouseCursor::TopLeftCornerResizeCursor:
  220245. case MouseCursor::BottomRightCornerResizeCursor:
  220246. return juce_cursorFromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  220247. case MouseCursor::TopRightCornerResizeCursor:
  220248. case MouseCursor::BottomLeftCornerResizeCursor:
  220249. return juce_cursorFromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  220250. case MouseCursor::UpDownLeftRightResizeCursor:
  220251. return juce_cursorFromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  220252. case MouseCursor::CrosshairCursor:
  220253. c = [NSCursor crosshairCursor];
  220254. break;
  220255. }
  220256. [c retain];
  220257. return (void*) c;
  220258. }
  220259. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  220260. {
  220261. NSCursor* c = (NSCursor*) cursorHandle;
  220262. [c release];
  220263. }
  220264. void MouseCursor::showInAllWindows() const throw()
  220265. {
  220266. showInWindow (0);
  220267. }
  220268. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  220269. {
  220270. NSCursor* const c = (NSCursor*) getHandle();
  220271. [c set];
  220272. }
  220273. #endif
  220274. /********* End of inlined file: juce_mac_MouseCursor.mm *********/
  220275. /********* Start of inlined file: juce_mac_NSViewComponent.mm *********/
  220276. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220277. // compiled on its own).
  220278. #ifdef JUCE_INCLUDED_FILE
  220279. class NSViewComponentInternal : public ComponentMovementWatcher
  220280. {
  220281. Component* const owner;
  220282. NSViewComponentPeer* currentPeer;
  220283. bool wasShowing;
  220284. public:
  220285. NSView* const view;
  220286. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  220287. : ComponentMovementWatcher (owner_),
  220288. owner (owner_),
  220289. currentPeer (0),
  220290. wasShowing (false),
  220291. view (view_)
  220292. {
  220293. [view_ retain];
  220294. if (owner_->isShowing())
  220295. componentPeerChanged();
  220296. }
  220297. ~NSViewComponentInternal()
  220298. {
  220299. [view removeFromSuperview];
  220300. [view release];
  220301. }
  220302. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  220303. {
  220304. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  220305. // The ComponentMovementWatcher version of this method avoids calling
  220306. // us when the top-level comp is resized, but for an NSView we need to know this
  220307. // because with inverted co-ords, we need to update the position even if the
  220308. // top-left pos hasn't changed
  220309. if (comp.isOnDesktop() && wasResized)
  220310. componentMovedOrResized (wasMoved, wasResized);
  220311. }
  220312. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  220313. {
  220314. Component* const topComp = owner->getTopLevelComponent();
  220315. if (topComp->getPeer() != 0)
  220316. {
  220317. int x = 0, y = 0;
  220318. owner->relativePositionToOtherComponent (topComp, x, y);
  220319. NSRect r;
  220320. r.origin.x = (float) x;
  220321. r.origin.y = (float) y;
  220322. r.size.width = (float) owner->getWidth();
  220323. r.size.height = (float) owner->getHeight();
  220324. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  220325. [view setFrame: r];
  220326. }
  220327. }
  220328. void componentPeerChanged()
  220329. {
  220330. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  220331. if (currentPeer != peer)
  220332. {
  220333. [view removeFromSuperview];
  220334. currentPeer = peer;
  220335. if (peer != 0)
  220336. {
  220337. [peer->view addSubview: view];
  220338. componentMovedOrResized (false, false);
  220339. }
  220340. }
  220341. [view setHidden: ! owner->isShowing()];
  220342. }
  220343. void componentVisibilityChanged (Component&)
  220344. {
  220345. componentPeerChanged();
  220346. }
  220347. juce_UseDebuggingNewOperator
  220348. private:
  220349. NSViewComponentInternal (const NSViewComponentInternal&);
  220350. const NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  220351. };
  220352. NSViewComponent::NSViewComponent()
  220353. : info (0)
  220354. {
  220355. }
  220356. NSViewComponent::~NSViewComponent()
  220357. {
  220358. delete info;
  220359. }
  220360. void NSViewComponent::setView (void* view)
  220361. {
  220362. if (view != getView())
  220363. {
  220364. deleteAndZero (info);
  220365. if (view != 0)
  220366. info = new NSViewComponentInternal ((NSView*) view, this);
  220367. }
  220368. }
  220369. void* NSViewComponent::getView() const
  220370. {
  220371. return info == 0 ? 0 : info->view;
  220372. }
  220373. void NSViewComponent::paint (Graphics& g)
  220374. {
  220375. }
  220376. #endif
  220377. /********* End of inlined file: juce_mac_NSViewComponent.mm *********/
  220378. /********* Start of inlined file: juce_mac_AppleRemote.mm *********/
  220379. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220380. // compiled on its own).
  220381. #ifdef JUCE_INCLUDED_FILE
  220382. AppleRemoteDevice::AppleRemoteDevice()
  220383. : device (0),
  220384. queue (0),
  220385. remoteId (0)
  220386. {
  220387. }
  220388. AppleRemoteDevice::~AppleRemoteDevice()
  220389. {
  220390. stop();
  220391. }
  220392. static io_object_t getAppleRemoteDevice() throw()
  220393. {
  220394. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  220395. io_iterator_t iter = 0;
  220396. io_object_t iod = 0;
  220397. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  220398. && iter != 0)
  220399. {
  220400. iod = IOIteratorNext (iter);
  220401. }
  220402. IOObjectRelease (iter);
  220403. return iod;
  220404. }
  220405. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  220406. {
  220407. jassert (*device == 0);
  220408. io_name_t classname;
  220409. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  220410. {
  220411. IOCFPlugInInterface** cfPlugInInterface = 0;
  220412. SInt32 score = 0;
  220413. if (IOCreatePlugInInterfaceForService (iod,
  220414. kIOHIDDeviceUserClientTypeID,
  220415. kIOCFPlugInInterfaceID,
  220416. &cfPlugInInterface,
  220417. &score) == kIOReturnSuccess)
  220418. {
  220419. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  220420. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  220421. device);
  220422. (void) hr;
  220423. (*cfPlugInInterface)->Release (cfPlugInInterface);
  220424. }
  220425. }
  220426. return *device != 0;
  220427. }
  220428. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  220429. {
  220430. if (queue != 0)
  220431. return true;
  220432. stop();
  220433. bool result = false;
  220434. io_object_t iod = getAppleRemoteDevice();
  220435. if (iod != 0)
  220436. {
  220437. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  220438. result = true;
  220439. else
  220440. stop();
  220441. IOObjectRelease (iod);
  220442. }
  220443. return result;
  220444. }
  220445. void AppleRemoteDevice::stop() throw()
  220446. {
  220447. if (queue != 0)
  220448. {
  220449. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  220450. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  220451. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  220452. queue = 0;
  220453. }
  220454. if (device != 0)
  220455. {
  220456. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  220457. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  220458. device = 0;
  220459. }
  220460. }
  220461. bool AppleRemoteDevice::isActive() const throw()
  220462. {
  220463. return queue != 0;
  220464. }
  220465. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  220466. {
  220467. if (result == kIOReturnSuccess)
  220468. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  220469. }
  220470. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  220471. {
  220472. Array <int> cookies;
  220473. CFArrayRef elements;
  220474. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  220475. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  220476. return false;
  220477. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  220478. {
  220479. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  220480. // get the cookie
  220481. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  220482. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  220483. continue;
  220484. long number;
  220485. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  220486. continue;
  220487. cookies.add ((int) number);
  220488. }
  220489. CFRelease (elements);
  220490. if ((*(IOHIDDeviceInterface**) device)
  220491. ->open ((IOHIDDeviceInterface**) device,
  220492. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  220493. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  220494. {
  220495. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  220496. if (queue != 0)
  220497. {
  220498. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  220499. for (int i = 0; i < cookies.size(); ++i)
  220500. {
  220501. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  220502. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  220503. }
  220504. CFRunLoopSourceRef eventSource;
  220505. if ((*(IOHIDQueueInterface**) queue)
  220506. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  220507. {
  220508. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  220509. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  220510. {
  220511. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  220512. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  220513. return true;
  220514. }
  220515. }
  220516. }
  220517. }
  220518. return false;
  220519. }
  220520. void AppleRemoteDevice::handleCallbackInternal()
  220521. {
  220522. int totalValues = 0;
  220523. AbsoluteTime nullTime = { 0, 0 };
  220524. char cookies [12];
  220525. int numCookies = 0;
  220526. while (numCookies < numElementsInArray (cookies))
  220527. {
  220528. IOHIDEventStruct e;
  220529. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  220530. break;
  220531. if ((int) e.elementCookie == 19)
  220532. {
  220533. remoteId = e.value;
  220534. buttonPressed (switched, false);
  220535. }
  220536. else
  220537. {
  220538. totalValues += e.value;
  220539. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  220540. }
  220541. }
  220542. cookies [numCookies++] = 0;
  220543. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  220544. static const char buttonPatterns[] =
  220545. {
  220546. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  220547. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  220548. 0x1f, 0x1d, 0x1c, 0x12, 0,
  220549. 0x1f, 0x1e, 0x1c, 0x12, 0,
  220550. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  220551. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  220552. 0x1f, 0x12, 0x04, 0x02, 0,
  220553. 0x1f, 0x12, 0x03, 0x02, 0,
  220554. 0x1f, 0x12, 0x1f, 0x12, 0,
  220555. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  220556. 19, 0
  220557. };
  220558. int buttonNum = (int) menuButton;
  220559. int i = 0;
  220560. while (i < numElementsInArray (buttonPatterns))
  220561. {
  220562. if (strcmp (cookies, buttonPatterns + i) == 0)
  220563. {
  220564. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  220565. break;
  220566. }
  220567. i += strlen (buttonPatterns + i) + 1;
  220568. ++buttonNum;
  220569. }
  220570. }
  220571. #endif
  220572. /********* End of inlined file: juce_mac_AppleRemote.mm *********/
  220573. /********* Start of inlined file: juce_mac_OpenGLComponent.mm *********/
  220574. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220575. // compiled on its own).
  220576. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  220577. END_JUCE_NAMESPACE
  220578. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  220579. {
  220580. CriticalSection* contextLock;
  220581. bool needsUpdate;
  220582. }
  220583. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  220584. - (bool) makeActive;
  220585. - (void) makeInactive;
  220586. - (void) reshape;
  220587. @end
  220588. @implementation ThreadSafeNSOpenGLView
  220589. - (id) initWithFrame: (NSRect) frameRect
  220590. pixelFormat: (NSOpenGLPixelFormat*) format
  220591. {
  220592. contextLock = new CriticalSection();
  220593. self = [super initWithFrame: frameRect pixelFormat: format];
  220594. if (self != nil)
  220595. [[NSNotificationCenter defaultCenter] addObserver: self
  220596. selector: @selector (_surfaceNeedsUpdate:)
  220597. name: NSViewGlobalFrameDidChangeNotification
  220598. object: self];
  220599. return self;
  220600. }
  220601. - (void) dealloc
  220602. {
  220603. [[NSNotificationCenter defaultCenter] removeObserver: self];
  220604. delete contextLock;
  220605. [super dealloc];
  220606. }
  220607. - (bool) makeActive
  220608. {
  220609. const ScopedLock sl (*contextLock);
  220610. if ([self openGLContext] == 0)
  220611. return false;
  220612. [[self openGLContext] makeCurrentContext];
  220613. if (needsUpdate)
  220614. {
  220615. [super update];
  220616. needsUpdate = false;
  220617. }
  220618. return true;
  220619. }
  220620. - (void) makeInactive
  220621. {
  220622. const ScopedLock sl (*contextLock);
  220623. [NSOpenGLContext clearCurrentContext];
  220624. }
  220625. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  220626. {
  220627. const ScopedLock sl (*contextLock);
  220628. needsUpdate = true;
  220629. }
  220630. - (void) update
  220631. {
  220632. const ScopedLock sl (*contextLock);
  220633. needsUpdate = true;
  220634. }
  220635. - (void) reshape
  220636. {
  220637. const ScopedLock sl (*contextLock);
  220638. needsUpdate = true;
  220639. }
  220640. @end
  220641. BEGIN_JUCE_NAMESPACE
  220642. class WindowedGLContext : public OpenGLContext
  220643. {
  220644. public:
  220645. WindowedGLContext (Component* const component,
  220646. const OpenGLPixelFormat& pixelFormat_,
  220647. NSOpenGLContext* sharedContext)
  220648. : renderContext (0),
  220649. pixelFormat (pixelFormat_)
  220650. {
  220651. jassert (component != 0);
  220652. NSOpenGLPixelFormatAttribute attribs [64];
  220653. int n = 0;
  220654. attribs[n++] = NSOpenGLPFADoubleBuffer;
  220655. attribs[n++] = NSOpenGLPFAAccelerated;
  220656. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  220657. attribs[n++] = NSOpenGLPFAColorSize;
  220658. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  220659. pixelFormat.greenBits,
  220660. pixelFormat.blueBits);
  220661. attribs[n++] = NSOpenGLPFAAlphaSize;
  220662. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  220663. attribs[n++] = NSOpenGLPFADepthSize;
  220664. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  220665. attribs[n++] = NSOpenGLPFAStencilSize;
  220666. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  220667. attribs[n++] = NSOpenGLPFAAccumSize;
  220668. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  220669. pixelFormat.accumulationBufferGreenBits,
  220670. pixelFormat.accumulationBufferBlueBits,
  220671. pixelFormat.accumulationBufferAlphaBits);
  220672. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  220673. attribs[n++] = NSOpenGLPFASampleBuffers;
  220674. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  220675. attribs[n++] = NSOpenGLPFAClosestPolicy;
  220676. attribs[n++] = NSOpenGLPFANoRecovery;
  220677. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  220678. NSOpenGLPixelFormat* format
  220679. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  220680. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  220681. pixelFormat: format];
  220682. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  220683. shareContext: sharedContext] autorelease];
  220684. const GLint swapInterval = 1;
  220685. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  220686. [view setOpenGLContext: renderContext];
  220687. [renderContext setView: view];
  220688. [format release];
  220689. viewHolder = new NSViewComponentInternal (view, component);
  220690. }
  220691. ~WindowedGLContext()
  220692. {
  220693. makeInactive();
  220694. [renderContext setView: nil];
  220695. delete viewHolder;
  220696. }
  220697. bool makeActive() const throw()
  220698. {
  220699. jassert (renderContext != 0);
  220700. [view makeActive];
  220701. return isActive();
  220702. }
  220703. bool makeInactive() const throw()
  220704. {
  220705. [view makeInactive];
  220706. return true;
  220707. }
  220708. bool isActive() const throw()
  220709. {
  220710. return [NSOpenGLContext currentContext] == renderContext;
  220711. }
  220712. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  220713. void* getRawContext() const throw() { return renderContext; }
  220714. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  220715. {
  220716. }
  220717. void swapBuffers()
  220718. {
  220719. [renderContext flushBuffer];
  220720. }
  220721. bool setSwapInterval (const int numFramesPerSwap)
  220722. {
  220723. [renderContext setValues: (const GLint*) &numFramesPerSwap
  220724. forParameter: NSOpenGLCPSwapInterval];
  220725. return true;
  220726. }
  220727. int getSwapInterval() const
  220728. {
  220729. GLint numFrames = 0;
  220730. [renderContext getValues: &numFrames
  220731. forParameter: NSOpenGLCPSwapInterval];
  220732. return numFrames;
  220733. }
  220734. void repaint()
  220735. {
  220736. // we need to invalidate the juce view that holds this gl view, to make it
  220737. // cause a repaint callback
  220738. NSView* v = (NSView*) viewHolder->view;
  220739. NSRect r = [v frame];
  220740. // bit of a bodge here.. if we only invalidate the area of the gl component,
  220741. // it's completely covered by the NSOpenGLView, so the OS throws away the
  220742. // repaint message, thus never causing our paint() callback, and never repainting
  220743. // the comp. So invalidating just a little bit around the edge helps..
  220744. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  220745. }
  220746. void* getNativeWindowHandle() const { return viewHolder->view; }
  220747. juce_UseDebuggingNewOperator
  220748. NSOpenGLContext* renderContext;
  220749. ThreadSafeNSOpenGLView* view;
  220750. private:
  220751. OpenGLPixelFormat pixelFormat;
  220752. NSViewComponentInternal* viewHolder;
  220753. WindowedGLContext (const WindowedGLContext&);
  220754. const WindowedGLContext& operator= (const WindowedGLContext&);
  220755. };
  220756. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  220757. const OpenGLPixelFormat& pixelFormat,
  220758. const OpenGLContext* const contextToShareWith)
  220759. {
  220760. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  220761. contextToShareWith != 0 ? (NSOpenGLContext*) contextToShareWith->getRawContext() : 0);
  220762. if (c->renderContext == 0)
  220763. deleteAndZero (c);
  220764. return c;
  220765. }
  220766. void* OpenGLComponent::getNativeWindowHandle() const
  220767. {
  220768. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle()
  220769. : 0;
  220770. }
  220771. void juce_glViewport (const int w, const int h)
  220772. {
  220773. glViewport (0, 0, w, h);
  220774. }
  220775. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  220776. OwnedArray <OpenGLPixelFormat>& results)
  220777. {
  220778. /* GLint attribs [64];
  220779. int n = 0;
  220780. attribs[n++] = AGL_RGBA;
  220781. attribs[n++] = AGL_DOUBLEBUFFER;
  220782. attribs[n++] = AGL_ACCELERATED;
  220783. attribs[n++] = AGL_NO_RECOVERY;
  220784. attribs[n++] = AGL_NONE;
  220785. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  220786. while (p != 0)
  220787. {
  220788. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  220789. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  220790. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  220791. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  220792. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  220793. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  220794. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  220795. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  220796. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  220797. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  220798. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  220799. results.add (pf);
  220800. p = aglNextPixelFormat (p);
  220801. }*/
  220802. //jassertfalse //xxx can't see how you do this in cocoa!
  220803. }
  220804. #endif
  220805. /********* End of inlined file: juce_mac_OpenGLComponent.mm *********/
  220806. /********* Start of inlined file: juce_mac_MainMenu.mm *********/
  220807. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220808. // compiled on its own).
  220809. #ifdef JUCE_INCLUDED_FILE
  220810. class JuceMainMenuHandler;
  220811. END_JUCE_NAMESPACE
  220812. using namespace JUCE_NAMESPACE;
  220813. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  220814. @interface JuceMenuCallback : NSObject
  220815. {
  220816. JuceMainMenuHandler* owner;
  220817. }
  220818. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  220819. - (void) dealloc;
  220820. - (void) menuItemInvoked: (id) menu;
  220821. - (void) menuNeedsUpdate: (NSMenu*) menu;
  220822. @end
  220823. BEGIN_JUCE_NAMESPACE
  220824. class JuceMainMenuHandler : private MenuBarModelListener,
  220825. private DeletedAtShutdown
  220826. {
  220827. public:
  220828. static JuceMainMenuHandler* instance;
  220829. JuceMainMenuHandler() throw()
  220830. : currentModel (0),
  220831. lastUpdateTime (0)
  220832. {
  220833. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  220834. }
  220835. ~JuceMainMenuHandler() throw()
  220836. {
  220837. setMenu (0);
  220838. jassert (instance == this);
  220839. instance = 0;
  220840. [callback release];
  220841. }
  220842. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  220843. {
  220844. if (currentModel != newMenuBarModel)
  220845. {
  220846. if (currentModel != 0)
  220847. currentModel->removeListener (this);
  220848. currentModel = newMenuBarModel;
  220849. if (currentModel != 0)
  220850. currentModel->addListener (this);
  220851. menuBarItemsChanged (0);
  220852. }
  220853. }
  220854. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  220855. const String& name, const int menuId, const int tag)
  220856. {
  220857. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  220858. action: nil
  220859. keyEquivalent: @""];
  220860. [item setTag: tag];
  220861. NSMenu* sub = createMenu (child, name, menuId, tag);
  220862. [parent setSubmenu: sub forItem: item];
  220863. [sub setAutoenablesItems: false];
  220864. [sub release];
  220865. }
  220866. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  220867. const String& name, const int menuId, const int tag)
  220868. {
  220869. [parentItem setTag: tag];
  220870. NSMenu* menu = [parentItem submenu];
  220871. [menu setTitle: juceStringToNS (name)];
  220872. while ([menu numberOfItems] > 0)
  220873. [menu removeItemAtIndex: 0];
  220874. PopupMenu::MenuItemIterator iter (menuToCopy);
  220875. while (iter.next())
  220876. addMenuItem (iter, menu, menuId, tag);
  220877. [menu setAutoenablesItems: false];
  220878. [menu update];
  220879. }
  220880. void menuBarItemsChanged (MenuBarModel*)
  220881. {
  220882. lastUpdateTime = Time::getMillisecondCounter();
  220883. StringArray menuNames;
  220884. if (currentModel != 0)
  220885. menuNames = currentModel->getMenuBarNames();
  220886. NSMenu* menuBar = [NSApp mainMenu];
  220887. while ([menuBar numberOfItems] > 1 + menuNames.size())
  220888. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  220889. int menuId = 1;
  220890. for (int i = 0; i < menuNames.size(); ++i)
  220891. {
  220892. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  220893. if (i >= [menuBar numberOfItems] - 1)
  220894. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  220895. else
  220896. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  220897. }
  220898. }
  220899. static void flashMenuBar (NSMenu* menu)
  220900. {
  220901. const unichar f35Key = NSF35FunctionKey;
  220902. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  220903. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  220904. action: nil
  220905. keyEquivalent: f35String];
  220906. [item setTarget: nil];
  220907. [menu insertItem: item atIndex: [menu numberOfItems]];
  220908. [item release];
  220909. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  220910. location: NSZeroPoint
  220911. modifierFlags: NSCommandKeyMask
  220912. timestamp: 0
  220913. windowNumber: 0
  220914. context: [NSGraphicsContext currentContext]
  220915. characters: f35String
  220916. charactersIgnoringModifiers: f35String
  220917. isARepeat: NO
  220918. keyCode: 0];
  220919. [menu performKeyEquivalent: f35Event];
  220920. [menu removeItem: item];
  220921. }
  220922. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  220923. {
  220924. for (int i = [menu numberOfItems]; --i >= 0;)
  220925. {
  220926. NSMenuItem* m = [menu itemAtIndex: i];
  220927. if ([m tag] == info.commandID)
  220928. return m;
  220929. if ([m submenu] != 0)
  220930. {
  220931. NSMenuItem* found = findMenuItem ([m submenu], info);
  220932. if (found != 0)
  220933. return found;
  220934. }
  220935. }
  220936. return 0;
  220937. }
  220938. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  220939. {
  220940. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  220941. if (item != 0)
  220942. flashMenuBar ([item menu]);
  220943. }
  220944. void updateMenus()
  220945. {
  220946. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  220947. menuBarItemsChanged (0);
  220948. }
  220949. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  220950. {
  220951. if (currentModel != 0)
  220952. {
  220953. if (commandManager != 0)
  220954. {
  220955. ApplicationCommandTarget::InvocationInfo info (commandId);
  220956. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  220957. commandManager->invoke (info, true);
  220958. }
  220959. currentModel->menuItemSelected (commandId, topLevelIndex);
  220960. }
  220961. }
  220962. MenuBarModel* currentModel;
  220963. uint32 lastUpdateTime;
  220964. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  220965. const int topLevelMenuId, const int topLevelIndex)
  220966. {
  220967. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  220968. if (text == 0)
  220969. text = @"";
  220970. if (iter.isSeparator)
  220971. {
  220972. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  220973. }
  220974. else if (iter.isSectionHeader)
  220975. {
  220976. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  220977. action: nil
  220978. keyEquivalent: @""];
  220979. [item setEnabled: false];
  220980. }
  220981. else if (iter.subMenu != 0)
  220982. {
  220983. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  220984. action: nil
  220985. keyEquivalent: @""];
  220986. [item setTag: iter.itemId];
  220987. [item setEnabled: iter.isEnabled];
  220988. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  220989. [menuToAddTo setSubmenu: sub forItem: item];
  220990. }
  220991. else
  220992. {
  220993. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  220994. action: @selector (menuItemInvoked:)
  220995. keyEquivalent: @""];
  220996. [item setTag: iter.itemId];
  220997. [item setEnabled: iter.isEnabled];
  220998. [item setState: iter.isTicked ? NSOnState : NSOffState];
  220999. [item setTarget: (id) callback];
  221000. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  221001. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  221002. [item setRepresentedObject: info];
  221003. if (iter.commandManager != 0)
  221004. {
  221005. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  221006. ->getKeyPressesAssignedToCommand (iter.itemId));
  221007. if (keyPresses.size() > 0)
  221008. {
  221009. const KeyPress& kp = keyPresses.getReference(0);
  221010. juce_wchar key = kp.getTextCharacter();
  221011. if (kp.getKeyCode() == KeyPress::backspaceKey)
  221012. key = NSBackspaceCharacter;
  221013. else if (kp.getKeyCode() == KeyPress::deleteKey)
  221014. key = NSDeleteCharacter;
  221015. else if (key == 0)
  221016. key = (juce_wchar) kp.getKeyCode();
  221017. unsigned int mods = 0;
  221018. if (kp.getModifiers().isShiftDown())
  221019. mods |= NSShiftKeyMask;
  221020. if (kp.getModifiers().isCtrlDown())
  221021. mods |= NSControlKeyMask;
  221022. if (kp.getModifiers().isAltDown())
  221023. mods |= NSAlternateKeyMask;
  221024. if (kp.getModifiers().isCommandDown())
  221025. mods |= NSCommandKeyMask;
  221026. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  221027. [item setKeyEquivalentModifierMask: mods];
  221028. }
  221029. }
  221030. }
  221031. }
  221032. JuceMenuCallback* callback;
  221033. private:
  221034. NSMenu* createMenu (const PopupMenu menu,
  221035. const String& menuName,
  221036. const int topLevelMenuId,
  221037. const int topLevelIndex)
  221038. {
  221039. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  221040. [m setAutoenablesItems: false];
  221041. [m setDelegate: callback];
  221042. PopupMenu::MenuItemIterator iter (menu);
  221043. while (iter.next())
  221044. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  221045. [m update];
  221046. return m;
  221047. }
  221048. };
  221049. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  221050. END_JUCE_NAMESPACE
  221051. @implementation JuceMenuCallback
  221052. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  221053. {
  221054. [super init];
  221055. owner = owner_;
  221056. return self;
  221057. }
  221058. - (void) dealloc
  221059. {
  221060. [super dealloc];
  221061. }
  221062. - (void) menuItemInvoked: (id) menu
  221063. {
  221064. NSMenuItem* item = (NSMenuItem*) menu;
  221065. if ([[item representedObject] isKindOfClass: [NSArray class]])
  221066. {
  221067. NSArray* info = (NSArray*) [item representedObject];
  221068. owner->invoke ([item tag],
  221069. (ApplicationCommandManager*) (pointer_sized_int)
  221070. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  221071. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  221072. }
  221073. }
  221074. - (void) menuNeedsUpdate: (NSMenu*) menu;
  221075. {
  221076. if (JuceMainMenuHandler::instance != 0)
  221077. JuceMainMenuHandler::instance->updateMenus();
  221078. }
  221079. @end
  221080. BEGIN_JUCE_NAMESPACE
  221081. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  221082. const PopupMenu* extraItems)
  221083. {
  221084. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  221085. {
  221086. PopupMenu::MenuItemIterator iter (*extraItems);
  221087. while (iter.next())
  221088. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  221089. [menu addItem: [NSMenuItem separatorItem]];
  221090. }
  221091. NSMenuItem* item;
  221092. // Services...
  221093. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  221094. action: nil keyEquivalent: @""];
  221095. [menu addItem: item];
  221096. [item release];
  221097. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  221098. [menu setSubmenu: servicesMenu forItem: item];
  221099. [NSApp setServicesMenu: servicesMenu];
  221100. [servicesMenu release];
  221101. [menu addItem: [NSMenuItem separatorItem]];
  221102. // Hide + Show stuff...
  221103. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  221104. action: @selector (hide:) keyEquivalent: @"h"];
  221105. [item setTarget: NSApp];
  221106. [menu addItem: item];
  221107. [item release];
  221108. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  221109. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  221110. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  221111. [item setTarget: NSApp];
  221112. [menu addItem: item];
  221113. [item release];
  221114. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  221115. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  221116. [item setTarget: NSApp];
  221117. [menu addItem: item];
  221118. [item release];
  221119. [menu addItem: [NSMenuItem separatorItem]];
  221120. // Quit item....
  221121. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  221122. action: @selector (terminate:) keyEquivalent: @"q"];
  221123. [item setTarget: NSApp];
  221124. [menu addItem: item];
  221125. [item release];
  221126. return menu;
  221127. }
  221128. // Since our app has no NIB, this initialises a standard app menu...
  221129. static void rebuildMainMenu (const PopupMenu* extraItems)
  221130. {
  221131. // this can't be used in a plugin!
  221132. jassert (JUCEApplication::getInstance() != 0);
  221133. if (JUCEApplication::getInstance() != 0)
  221134. {
  221135. const ScopedAutoReleasePool pool;
  221136. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  221137. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  221138. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  221139. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  221140. [mainMenu setSubmenu: appMenu forItem: item];
  221141. [NSApp setMainMenu: mainMenu];
  221142. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  221143. [appMenu release];
  221144. [mainMenu release];
  221145. }
  221146. }
  221147. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  221148. const PopupMenu* extraAppleMenuItems) throw()
  221149. {
  221150. if (getMacMainMenu() != newMenuBarModel)
  221151. {
  221152. if (newMenuBarModel == 0)
  221153. {
  221154. delete JuceMainMenuHandler::instance;
  221155. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  221156. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  221157. extraAppleMenuItems = 0;
  221158. }
  221159. else
  221160. {
  221161. if (JuceMainMenuHandler::instance == 0)
  221162. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  221163. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  221164. }
  221165. }
  221166. rebuildMainMenu (extraAppleMenuItems);
  221167. if (newMenuBarModel != 0)
  221168. newMenuBarModel->menuItemsChanged();
  221169. }
  221170. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  221171. {
  221172. return JuceMainMenuHandler::instance != 0
  221173. ? JuceMainMenuHandler::instance->currentModel : 0;
  221174. }
  221175. void initialiseMainMenu()
  221176. {
  221177. if (JUCEApplication::getInstance() != 0) // only needed in an app
  221178. rebuildMainMenu (0);
  221179. }
  221180. #endif
  221181. /********* End of inlined file: juce_mac_MainMenu.mm *********/
  221182. /********* Start of inlined file: juce_mac_FileChooser.mm *********/
  221183. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221184. // compiled on its own).
  221185. #ifdef JUCE_INCLUDED_FILE
  221186. END_JUCE_NAMESPACE
  221187. using namespace JUCE_NAMESPACE;
  221188. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  221189. @interface JuceFileChooserDelegate : NSObject
  221190. {
  221191. StringArray* filters;
  221192. }
  221193. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  221194. - (void) dealloc;
  221195. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  221196. @end
  221197. @implementation JuceFileChooserDelegate
  221198. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  221199. {
  221200. [super init];
  221201. filters = filters_;
  221202. return self;
  221203. }
  221204. - (void) dealloc
  221205. {
  221206. delete filters;
  221207. [super dealloc];
  221208. }
  221209. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  221210. {
  221211. const String fname (nsStringToJuce (filename));
  221212. for (int i = filters->size(); --i >= 0;)
  221213. if (fname.matchesWildcard ((*filters)[i], true))
  221214. return true;
  221215. return File (fname).isDirectory();
  221216. }
  221217. @end
  221218. BEGIN_JUCE_NAMESPACE
  221219. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  221220. const String& title,
  221221. const File& currentFileOrDirectory,
  221222. const String& filter,
  221223. bool selectsDirectory,
  221224. bool isSaveDialogue,
  221225. bool warnAboutOverwritingExistingFiles,
  221226. bool selectMultipleFiles,
  221227. FilePreviewComponent* extraInfoComponent)
  221228. {
  221229. const ScopedAutoReleasePool pool;
  221230. StringArray* filters = new StringArray();
  221231. filters->addTokens (filter.replaceCharacters (T(",:"), T(";;")), T(";"), 0);
  221232. filters->trim();
  221233. filters->removeEmptyStrings();
  221234. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  221235. [delegate autorelease];
  221236. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  221237. : [NSOpenPanel openPanel];
  221238. [panel setTitle: juceStringToNS (title)];
  221239. if (! isSaveDialogue)
  221240. {
  221241. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  221242. [openPanel setCanChooseDirectories: selectsDirectory];
  221243. [openPanel setCanChooseFiles: ! selectsDirectory];
  221244. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  221245. }
  221246. [panel setDelegate: delegate];
  221247. String directory, filename;
  221248. if (currentFileOrDirectory.isDirectory())
  221249. {
  221250. directory = currentFileOrDirectory.getFullPathName();
  221251. }
  221252. else
  221253. {
  221254. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  221255. filename = currentFileOrDirectory.getFileName();
  221256. }
  221257. if ([panel runModalForDirectory: juceStringToNS (directory)
  221258. file: juceStringToNS (filename)]
  221259. == NSOKButton)
  221260. {
  221261. if (isSaveDialogue)
  221262. {
  221263. results.add (new File (nsStringToJuce ([panel filename])));
  221264. }
  221265. else
  221266. {
  221267. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  221268. NSArray* urls = [openPanel filenames];
  221269. for (unsigned int i = 0; i < [urls count]; ++i)
  221270. {
  221271. NSString* f = [urls objectAtIndex: i];
  221272. results.add (new File (nsStringToJuce (f)));
  221273. }
  221274. }
  221275. }
  221276. [panel setDelegate: nil];
  221277. }
  221278. #endif
  221279. /********* End of inlined file: juce_mac_FileChooser.mm *********/
  221280. /********* Start of inlined file: juce_mac_QuickTimeMovieComponent.mm *********/
  221281. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221282. // compiled on its own).
  221283. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  221284. #define theMovie ((QTMovie*) movie)
  221285. QuickTimeMovieComponent::QuickTimeMovieComponent()
  221286. : movie (0)
  221287. {
  221288. setOpaque (true);
  221289. setVisible (true);
  221290. QTMovieView* view = [[QTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  221291. setView (view);
  221292. }
  221293. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  221294. {
  221295. closeMovie();
  221296. setView (0);
  221297. }
  221298. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  221299. {
  221300. return true;
  221301. }
  221302. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  221303. {
  221304. // unfortunately, QTMovie objects can only be created on the main thread..
  221305. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  221306. QTMovie* movie = 0;
  221307. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  221308. if (fin != 0)
  221309. {
  221310. movieFile = fin->getFile();
  221311. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  221312. error: nil];
  221313. }
  221314. else
  221315. {
  221316. MemoryBlock temp;
  221317. movieStream->readIntoMemoryBlock (temp);
  221318. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  221319. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  221320. {
  221321. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  221322. length: temp.getSize()]
  221323. name: [NSString stringWithCString: suffixesToTry[i]]
  221324. MIMEType: @""]
  221325. error: nil];
  221326. if (movie != 0)
  221327. break;
  221328. }
  221329. }
  221330. return movie;
  221331. }
  221332. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  221333. const bool controllerVisible)
  221334. {
  221335. closeMovie();
  221336. if (getPeer() == 0)
  221337. {
  221338. // To open a movie, this component must be visible inside a functioning window, so that
  221339. // the QT control can be assigned to the window.
  221340. jassertfalse
  221341. return false;
  221342. }
  221343. movie = openMovieFromStream (movieStream, movieFile);
  221344. [theMovie retain];
  221345. QTMovieView* view = (QTMovieView*) getView();
  221346. [view setMovie: theMovie];
  221347. [view setControllerVisible: controllerVisible];
  221348. setLooping (looping);
  221349. return movie != nil;
  221350. }
  221351. void QuickTimeMovieComponent::closeMovie()
  221352. {
  221353. stop();
  221354. QTMovieView* view = (QTMovieView*) getView();
  221355. [view setMovie: nil];
  221356. [theMovie release];
  221357. movie = 0;
  221358. movieFile = File::nonexistent;
  221359. }
  221360. bool QuickTimeMovieComponent::isMovieOpen() const
  221361. {
  221362. return movie != nil;
  221363. }
  221364. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  221365. {
  221366. return movieFile;
  221367. }
  221368. void QuickTimeMovieComponent::play()
  221369. {
  221370. [theMovie play];
  221371. }
  221372. void QuickTimeMovieComponent::stop()
  221373. {
  221374. [theMovie stop];
  221375. }
  221376. bool QuickTimeMovieComponent::isPlaying() const
  221377. {
  221378. return movie != 0 && [theMovie rate] != 0;
  221379. }
  221380. void QuickTimeMovieComponent::setPosition (const double seconds)
  221381. {
  221382. if (movie != 0)
  221383. {
  221384. QTTime t;
  221385. t.timeValue = (uint64) (100000.0 * seconds);
  221386. t.timeScale = 100000;
  221387. t.flags = 0;
  221388. [theMovie setCurrentTime: t];
  221389. }
  221390. }
  221391. double QuickTimeMovieComponent::getPosition() const
  221392. {
  221393. if (movie == 0)
  221394. return 0.0;
  221395. QTTime t = [theMovie currentTime];
  221396. return t.timeValue / (double) t.timeScale;
  221397. }
  221398. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  221399. {
  221400. [theMovie setRate: newSpeed];
  221401. }
  221402. double QuickTimeMovieComponent::getMovieDuration() const
  221403. {
  221404. if (movie == 0)
  221405. return 0.0;
  221406. QTTime t = [theMovie duration];
  221407. return t.timeValue / (double) t.timeScale;
  221408. }
  221409. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  221410. {
  221411. looping = shouldLoop;
  221412. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  221413. forKey: QTMovieLoopsAttribute];
  221414. }
  221415. bool QuickTimeMovieComponent::isLooping() const
  221416. {
  221417. return looping;
  221418. }
  221419. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  221420. {
  221421. [theMovie setVolume: newVolume];
  221422. }
  221423. float QuickTimeMovieComponent::getMovieVolume() const
  221424. {
  221425. return movie != 0 ? [theMovie volume] : 0.0f;
  221426. }
  221427. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  221428. {
  221429. width = 0;
  221430. height = 0;
  221431. if (movie != 0)
  221432. {
  221433. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  221434. width = s.width;
  221435. height = s.height;
  221436. }
  221437. }
  221438. void QuickTimeMovieComponent::paint (Graphics& g)
  221439. {
  221440. if (movie == 0)
  221441. g.fillAll (Colours::black);
  221442. }
  221443. bool QuickTimeMovieComponent::isControllerVisible() const
  221444. {
  221445. return controllerVisible;
  221446. }
  221447. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  221448. const bool isControllerVisible)
  221449. {
  221450. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  221451. movieFile = movieFile_;
  221452. return ok;
  221453. }
  221454. void QuickTimeMovieComponent::goToStart()
  221455. {
  221456. setPosition (0.0);
  221457. }
  221458. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  221459. const RectanglePlacement& placement)
  221460. {
  221461. int normalWidth, normalHeight;
  221462. getMovieNormalSize (normalWidth, normalHeight);
  221463. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  221464. {
  221465. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  221466. placement.applyTo (x, y, w, h,
  221467. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  221468. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  221469. if (w > 0 && h > 0)
  221470. {
  221471. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  221472. roundDoubleToInt (w), roundDoubleToInt (h));
  221473. }
  221474. }
  221475. else
  221476. {
  221477. setBounds (spaceToFitWithin);
  221478. }
  221479. }
  221480. #if ! (JUCE_MAC && JUCE_64BIT)
  221481. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  221482. {
  221483. if (movieStream == 0)
  221484. return false;
  221485. File file;
  221486. QTMovie* movie = openMovieFromStream (movieStream, file);
  221487. if (movie != nil)
  221488. result = [movie quickTimeMovie];
  221489. return movie != nil;
  221490. }
  221491. #endif
  221492. #endif
  221493. /********* End of inlined file: juce_mac_QuickTimeMovieComponent.mm *********/
  221494. /********* Start of inlined file: juce_mac_AudioCDBurner.mm *********/
  221495. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221496. // compiled on its own).
  221497. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  221498. END_JUCE_NAMESPACE
  221499. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  221500. @interface OpenDiskDevice : NSObject
  221501. {
  221502. DRDevice* device;
  221503. NSMutableArray* tracks;
  221504. }
  221505. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device;
  221506. - (void) dealloc;
  221507. - (bool) isDiskPresent;
  221508. - (int) getNumAvailableAudioBlocks;
  221509. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  221510. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  221511. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting;
  221512. @end
  221513. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  221514. @interface AudioTrackProducer : NSObject
  221515. {
  221516. JUCE_NAMESPACE::AudioSource* source;
  221517. int readPosition, lengthInFrames;
  221518. }
  221519. - (AudioTrackProducer*) init: (int) lengthInFrames;
  221520. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  221521. - (void) dealloc;
  221522. - (void) setupTrackProperties: (DRTrack*) track;
  221523. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  221524. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  221525. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  221526. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  221527. toMedia:(NSDictionary*)mediaInfo;
  221528. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  221529. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  221530. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  221531. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  221532. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  221533. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  221534. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  221535. ioFlags:(uint32_t*)flags;
  221536. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  221537. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  221538. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  221539. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  221540. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  221541. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  221542. ioFlags:(uint32_t*)flags;
  221543. @end
  221544. @implementation OpenDiskDevice
  221545. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device_
  221546. {
  221547. [super init];
  221548. device = device_;
  221549. tracks = [[NSMutableArray alloc] init];
  221550. return self;
  221551. }
  221552. - (void) dealloc
  221553. {
  221554. [tracks release];
  221555. [super dealloc];
  221556. }
  221557. - (bool) isDiskPresent
  221558. {
  221559. return [device isValid]
  221560. && [[[device status] objectForKey: DRDeviceMediaStateKey]
  221561. isEqualTo: DRDeviceMediaStateMediaPresent];
  221562. }
  221563. - (int) getNumAvailableAudioBlocks
  221564. {
  221565. return [[[[device status] objectForKey: DRDeviceMediaInfoKey]
  221566. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  221567. }
  221568. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  221569. {
  221570. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  221571. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  221572. [p setupTrackProperties: t];
  221573. [tracks addObject: t];
  221574. [t release];
  221575. [p release];
  221576. }
  221577. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  221578. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting
  221579. {
  221580. DRBurn* burn = [DRBurn burnForDevice: device];
  221581. if (! [device acquireExclusiveAccess])
  221582. {
  221583. *error = "Couldn't open or write to the CD device";
  221584. return;
  221585. }
  221586. [device acquireMediaReservation];
  221587. NSMutableDictionary* d = [[burn properties] mutableCopy];
  221588. [d autorelease];
  221589. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  221590. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  221591. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount)
  221592. forKey: DRBurnCompletionActionKey];
  221593. [burn setProperties: d];
  221594. [burn writeLayout: tracks];
  221595. for (;;)
  221596. {
  221597. JUCE_NAMESPACE::Thread::sleep (300);
  221598. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  221599. if (listener != 0 && listener->audioCDBurnProgress (progress))
  221600. {
  221601. [burn abort];
  221602. *error = "User cancelled the write operation";
  221603. break;
  221604. }
  221605. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  221606. {
  221607. *error = "Write operation failed";
  221608. break;
  221609. }
  221610. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  221611. {
  221612. break;
  221613. }
  221614. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  221615. objectForKey: DRErrorStatusErrorStringKey];
  221616. if ([err length] > 0)
  221617. {
  221618. *error = JUCE_NAMESPACE::String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [err UTF8String]);
  221619. break;
  221620. }
  221621. }
  221622. [device releaseMediaReservation];
  221623. [device releaseExclusiveAccess];
  221624. }
  221625. @end
  221626. @implementation AudioTrackProducer
  221627. - (AudioTrackProducer*) init: (int) lengthInFrames_
  221628. {
  221629. lengthInFrames = lengthInFrames_;
  221630. readPosition = 0;
  221631. return self;
  221632. }
  221633. - (void) setupTrackProperties: (DRTrack*) track
  221634. {
  221635. NSMutableDictionary* p = [[track properties] mutableCopy];
  221636. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  221637. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  221638. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  221639. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  221640. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  221641. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  221642. [track setProperties: p];
  221643. [p release];
  221644. }
  221645. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  221646. {
  221647. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  221648. if (s != nil)
  221649. s->source = source_;
  221650. return s;
  221651. }
  221652. - (void) dealloc
  221653. {
  221654. if (source != 0)
  221655. {
  221656. source->releaseResources();
  221657. delete source;
  221658. }
  221659. [super dealloc];
  221660. }
  221661. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  221662. {
  221663. }
  221664. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  221665. {
  221666. return true;
  221667. }
  221668. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  221669. {
  221670. return lengthInFrames;
  221671. }
  221672. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  221673. toMedia: (NSDictionary*) mediaInfo
  221674. {
  221675. if (source != 0)
  221676. source->prepareToPlay (44100 / 75, 44100);
  221677. readPosition = 0;
  221678. return true;
  221679. }
  221680. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  221681. {
  221682. if (source != 0)
  221683. source->prepareToPlay (44100 / 75, 44100);
  221684. return true;
  221685. }
  221686. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  221687. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  221688. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  221689. {
  221690. if (source != 0)
  221691. {
  221692. const int numSamples = JUCE_NAMESPACE::jmin (bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  221693. if (numSamples > 0)
  221694. {
  221695. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  221696. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  221697. info.buffer = &tempBuffer;
  221698. info.startSample = 0;
  221699. info.numSamples = numSamples;
  221700. source->getNextAudioBlock (info);
  221701. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  221702. buffer, numSamples, 4);
  221703. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  221704. buffer + 2, numSamples, 4);
  221705. readPosition += numSamples;
  221706. }
  221707. return numSamples * 4;
  221708. }
  221709. return 0;
  221710. }
  221711. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  221712. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  221713. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  221714. ioFlags: (uint32_t*) flags
  221715. {
  221716. zeromem (buffer, bufferLength);
  221717. return bufferLength;
  221718. }
  221719. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  221720. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  221721. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  221722. {
  221723. return true;
  221724. }
  221725. @end
  221726. BEGIN_JUCE_NAMESPACE
  221727. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  221728. : internal (0)
  221729. {
  221730. OpenDiskDevice* dev = [[OpenDiskDevice alloc] initWithDevice: [[DRDevice devices] objectAtIndex: deviceIndex]];
  221731. internal = (void*) dev;
  221732. }
  221733. AudioCDBurner::~AudioCDBurner()
  221734. {
  221735. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  221736. if (dev != 0)
  221737. [dev release];
  221738. }
  221739. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  221740. {
  221741. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  221742. if (b->internal == 0)
  221743. deleteAndZero (b);
  221744. return b;
  221745. }
  221746. static NSArray* findDiskBurnerDevices()
  221747. {
  221748. NSMutableArray* results = [NSMutableArray array];
  221749. NSArray* devs = [DRDevice devices];
  221750. if (devs != 0)
  221751. {
  221752. int num = [devs count];
  221753. int i;
  221754. for (i = 0; i < num; ++i)
  221755. {
  221756. NSDictionary* dic = [[devs objectAtIndex: i] info];
  221757. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  221758. if (name != nil)
  221759. [results addObject: name];
  221760. }
  221761. }
  221762. return results;
  221763. }
  221764. const StringArray AudioCDBurner::findAvailableDevices()
  221765. {
  221766. NSArray* names = findDiskBurnerDevices();
  221767. StringArray s;
  221768. for (unsigned int i = 0; i < [names count]; ++i)
  221769. s.add (String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [[names objectAtIndex: i] UTF8String]));
  221770. return s;
  221771. }
  221772. bool AudioCDBurner::isDiskPresent() const
  221773. {
  221774. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  221775. return dev != 0 && [dev isDiskPresent];
  221776. }
  221777. int AudioCDBurner::getNumAvailableAudioBlocks() const
  221778. {
  221779. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  221780. return [dev getNumAvailableAudioBlocks];
  221781. }
  221782. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  221783. {
  221784. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  221785. if (dev != 0)
  221786. {
  221787. [dev addSourceTrack: source numSamples: numSamps];
  221788. return true;
  221789. }
  221790. return false;
  221791. }
  221792. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  221793. const bool ejectDiscAfterwards,
  221794. const bool peformFakeBurnForTesting)
  221795. {
  221796. String error ("Couldn't open or write to the CD device");
  221797. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  221798. if (dev != 0)
  221799. {
  221800. error = String::empty;
  221801. [dev burn: listener
  221802. errorString: &error
  221803. ejectAfterwards: ejectDiscAfterwards
  221804. isFake: peformFakeBurnForTesting];
  221805. }
  221806. return error;
  221807. }
  221808. void AudioCDReader::ejectDisk()
  221809. {
  221810. const ScopedAutoReleasePool p;
  221811. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  221812. }
  221813. #endif
  221814. /********* End of inlined file: juce_mac_AudioCDBurner.mm *********/
  221815. /********* Start of inlined file: juce_mac_Fonts.mm *********/
  221816. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221817. // compiled on its own).
  221818. #ifdef JUCE_INCLUDED_FILE
  221819. class FontHelper
  221820. {
  221821. NSFont* font;
  221822. public:
  221823. String name;
  221824. bool isBold, isItalic, needsItalicTransform;
  221825. float fontSize, totalSize, ascent;
  221826. int refCount;
  221827. NSMutableDictionary* attributes;
  221828. FontHelper (const String& name_,
  221829. const bool bold_,
  221830. const bool italic_,
  221831. const float size_)
  221832. : font (0),
  221833. name (name_),
  221834. isBold (bold_),
  221835. isItalic (italic_),
  221836. needsItalicTransform (false),
  221837. fontSize (size_),
  221838. refCount (1)
  221839. {
  221840. attributes = [[NSMutableDictionary dictionaryWithObject: [NSNumber numberWithInt: 0]
  221841. forKey: NSLigatureAttributeName] retain];
  221842. font = [NSFont fontWithName: juceStringToNS (name_) size: size_];
  221843. if (italic_)
  221844. {
  221845. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSItalicFontMask];
  221846. if (newFont == font)
  221847. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  221848. font = newFont;
  221849. }
  221850. if (bold_)
  221851. font = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSBoldFontMask];
  221852. [font retain];
  221853. ascent = fabsf ([font ascender]);
  221854. totalSize = ascent + fabsf ([font descender]);
  221855. }
  221856. ~FontHelper()
  221857. {
  221858. [font release];
  221859. [attributes release];
  221860. }
  221861. bool getPathAndKerning (const juce_wchar char1,
  221862. const juce_wchar char2,
  221863. Path* path,
  221864. float& kerning,
  221865. float* ascent,
  221866. float* descent)
  221867. {
  221868. const ScopedAutoReleasePool pool;
  221869. if (font == 0
  221870. || ! [[font coveredCharacterSet] longCharacterIsMember: (UTF32Char) char1])
  221871. return false;
  221872. String chars;
  221873. chars << ' ' << char1 << char2;
  221874. NSTextStorage* textStorage = [[[NSTextStorage alloc] initWithString: juceStringToNS (chars)
  221875. attributes: attributes] autorelease];
  221876. NSLayoutManager* layoutManager = [[[NSLayoutManager alloc] init] autorelease];
  221877. NSTextContainer* textContainer = [[[NSTextContainer alloc] init] autorelease];
  221878. [layoutManager addTextContainer: textContainer];
  221879. [textStorage addLayoutManager: layoutManager];
  221880. [textStorage setFont: font];
  221881. unsigned int glyphIndex = [layoutManager glyphRangeForCharacterRange: NSMakeRange (1, 1)
  221882. actualCharacterRange: 0].location;
  221883. NSPoint p1 = [layoutManager locationForGlyphAtIndex: glyphIndex];
  221884. NSPoint p2 = [layoutManager locationForGlyphAtIndex: glyphIndex + 1];
  221885. kerning = p2.x - p1.x;
  221886. if (ascent != 0)
  221887. *ascent = this->ascent;
  221888. if (descent != 0)
  221889. *descent = fabsf ([font descender]);
  221890. if (path != 0)
  221891. {
  221892. NSBezierPath* bez = [NSBezierPath bezierPath];
  221893. [bez moveToPoint: NSMakePoint (0, 0)];
  221894. [bez appendBezierPathWithGlyph: [layoutManager glyphAtIndex: glyphIndex]
  221895. inFont: font];
  221896. for (int i = 0; i < [bez elementCount]; ++i)
  221897. {
  221898. NSPoint p[3];
  221899. switch ([bez elementAtIndex: i associatedPoints: p])
  221900. {
  221901. case NSMoveToBezierPathElement:
  221902. path->startNewSubPath (p[0].x, -p[0].y);
  221903. break;
  221904. case NSLineToBezierPathElement:
  221905. path->lineTo (p[0].x, -p[0].y);
  221906. break;
  221907. case NSCurveToBezierPathElement:
  221908. path->cubicTo (p[0].x, -p[0].y, p[1].x, -p[1].y, p[2].x, -p[2].y);
  221909. break;
  221910. case NSClosePathBezierPathElement:
  221911. path->closeSubPath();
  221912. break;
  221913. default:
  221914. jassertfalse
  221915. break;
  221916. }
  221917. }
  221918. if (needsItalicTransform)
  221919. path->applyTransform (AffineTransform::identity.sheared (-0.15, 0));
  221920. }
  221921. return kerning != 0;
  221922. }
  221923. juce_wchar getDefaultChar()
  221924. {
  221925. return 0;
  221926. }
  221927. };
  221928. class FontHelperCache : public Timer,
  221929. public DeletedAtShutdown
  221930. {
  221931. VoidArray cache;
  221932. public:
  221933. FontHelperCache()
  221934. {
  221935. }
  221936. ~FontHelperCache()
  221937. {
  221938. for (int i = cache.size(); --i >= 0;)
  221939. {
  221940. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  221941. delete f;
  221942. }
  221943. clearSingletonInstance();
  221944. }
  221945. FontHelper* getFont (const String& name,
  221946. const bool bold,
  221947. const bool italic,
  221948. const float size = 1024)
  221949. {
  221950. for (int i = cache.size(); --i >= 0;)
  221951. {
  221952. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  221953. if (f->name == name
  221954. && f->isBold == bold
  221955. && f->isItalic == italic
  221956. && f->fontSize == size)
  221957. {
  221958. f->refCount++;
  221959. return f;
  221960. }
  221961. }
  221962. FontHelper* const f = new FontHelper (name, bold, italic, size);
  221963. cache.add (f);
  221964. return f;
  221965. }
  221966. void releaseFont (FontHelper* f)
  221967. {
  221968. for (int i = cache.size(); --i >= 0;)
  221969. {
  221970. FontHelper* const f2 = (FontHelper*) cache.getUnchecked(i);
  221971. if (f == f2)
  221972. {
  221973. f->refCount--;
  221974. if (f->refCount == 0)
  221975. startTimer (5000);
  221976. break;
  221977. }
  221978. }
  221979. }
  221980. void timerCallback()
  221981. {
  221982. stopTimer();
  221983. for (int i = cache.size(); --i >= 0;)
  221984. {
  221985. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  221986. if (f->refCount == 0)
  221987. {
  221988. cache.remove (i);
  221989. delete f;
  221990. }
  221991. }
  221992. if (cache.size() == 0)
  221993. delete this;
  221994. }
  221995. juce_DeclareSingleton_SingleThreaded_Minimal (FontHelperCache)
  221996. };
  221997. juce_ImplementSingleton_SingleThreaded (FontHelperCache)
  221998. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  221999. bool bold,
  222000. bool italic,
  222001. bool addAllGlyphsToFont) throw()
  222002. {
  222003. // This method is only safe to be called from the normal UI thread..
  222004. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  222005. FontHelper* const helper = FontHelperCache::getInstance()
  222006. ->getFont (fontName, bold, italic);
  222007. clear();
  222008. setAscent (helper->ascent / helper->totalSize);
  222009. setName (fontName);
  222010. setDefaultCharacter (helper->getDefaultChar());
  222011. setBold (bold);
  222012. setItalic (italic);
  222013. if (addAllGlyphsToFont)
  222014. {
  222015. //xxx
  222016. jassertfalse
  222017. }
  222018. FontHelperCache::getInstance()->releaseFont (helper);
  222019. }
  222020. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  222021. {
  222022. // This method is only safe to be called from the normal UI thread..
  222023. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  222024. if (character == 0)
  222025. return false;
  222026. FontHelper* const helper = FontHelperCache::getInstance()
  222027. ->getFont (getName(), isBold(), isItalic());
  222028. Path path;
  222029. float width;
  222030. bool foundOne = false;
  222031. if (helper->getPathAndKerning (character, T('I'), &path, width, 0, 0))
  222032. {
  222033. path.applyTransform (AffineTransform::scale (1.0f / helper->totalSize,
  222034. 1.0f / helper->totalSize));
  222035. addGlyph (character, path, width / helper->totalSize);
  222036. for (int i = 0; i < glyphs.size(); ++i)
  222037. {
  222038. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  222039. float kerning;
  222040. if (helper->getPathAndKerning (character, g->getCharacter(), 0, kerning, 0, 0))
  222041. {
  222042. kerning = (kerning - width) / helper->totalSize;
  222043. if (kerning != 0)
  222044. addKerningPair (character, g->getCharacter(), kerning);
  222045. }
  222046. if (helper->getPathAndKerning (g->getCharacter(), character, 0, kerning, 0, 0))
  222047. {
  222048. kerning = kerning / helper->totalSize - g->width;
  222049. if (kerning != 0)
  222050. addKerningPair (g->getCharacter(), character, kerning);
  222051. }
  222052. }
  222053. foundOne = true;
  222054. }
  222055. FontHelperCache::getInstance()->releaseFont (helper);
  222056. return foundOne;
  222057. }
  222058. const StringArray Font::findAllTypefaceNames() throw()
  222059. {
  222060. StringArray names;
  222061. const ScopedAutoReleasePool pool;
  222062. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  222063. for (unsigned int i = 0; i < [fonts count]; ++i)
  222064. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  222065. names.sort (true);
  222066. return names;
  222067. }
  222068. void Typeface::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  222069. {
  222070. defaultSans = "Lucida Grande";
  222071. defaultSerif = "Times New Roman";
  222072. defaultFixed = "Monaco";
  222073. }
  222074. #endif
  222075. /********* End of inlined file: juce_mac_Fonts.mm *********/
  222076. /********* Start of inlined file: juce_mac_MessageManager.mm *********/
  222077. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222078. // compiled on its own).
  222079. #ifdef JUCE_INCLUDED_FILE
  222080. struct CallbackMessagePayload
  222081. {
  222082. MessageCallbackFunction* function;
  222083. void* parameter;
  222084. void* volatile result;
  222085. bool volatile hasBeenExecuted;
  222086. };
  222087. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  222088. for example having more than one juce plugin loaded into a host, then when a
  222089. method is called, the actual code that runs might actually be in a different module
  222090. than the one you expect... So any calls to library functions or statics that are
  222091. made inside obj-c methods will probably end up getting executed in a different DLL's
  222092. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  222093. To work around this insanity, I'm only allowing obj-c methods to make calls to
  222094. virtual methods of an object that's known to live inside the right module's space.
  222095. */
  222096. class AppDelegateRedirector
  222097. {
  222098. public:
  222099. AppDelegateRedirector() {}
  222100. virtual ~AppDelegateRedirector() {}
  222101. virtual NSApplicationTerminateReply shouldTerminate()
  222102. {
  222103. if (JUCEApplication::getInstance() != 0)
  222104. {
  222105. JUCEApplication::getInstance()->systemRequestedQuit();
  222106. return NSTerminateCancel;
  222107. }
  222108. return NSTerminateNow;
  222109. }
  222110. virtual BOOL openFile (const NSString* filename)
  222111. {
  222112. if (JUCEApplication::getInstance() != 0)
  222113. {
  222114. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  222115. return YES;
  222116. }
  222117. return NO;
  222118. }
  222119. virtual void openFiles (NSArray* filenames)
  222120. {
  222121. StringArray files;
  222122. for (unsigned int i = 0; i < [filenames count]; ++i)
  222123. files.add (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  222124. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  222125. {
  222126. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (T(" ")));
  222127. }
  222128. }
  222129. virtual void focusChanged()
  222130. {
  222131. juce_HandleProcessFocusChange();
  222132. }
  222133. virtual void deliverMessage (void* message)
  222134. {
  222135. // no need for an mm lock here - deliverMessage locks it
  222136. MessageManager::getInstance()->deliverMessage (message);
  222137. }
  222138. virtual void performCallback (CallbackMessagePayload* pl)
  222139. {
  222140. pl->result = (*pl->function) (pl->parameter);
  222141. pl->hasBeenExecuted = true;
  222142. }
  222143. virtual void deleteSelf()
  222144. {
  222145. delete this;
  222146. }
  222147. };
  222148. END_JUCE_NAMESPACE
  222149. using namespace JUCE_NAMESPACE;
  222150. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  222151. static int numPendingMessages = 0;
  222152. @interface JuceAppDelegate : NSObject
  222153. {
  222154. @private
  222155. id oldDelegate;
  222156. AppDelegateRedirector* redirector;
  222157. @public
  222158. bool flushingMessages;
  222159. }
  222160. - (JuceAppDelegate*) init;
  222161. - (void) dealloc;
  222162. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  222163. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  222164. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  222165. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  222166. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  222167. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  222168. - (void) customEvent: (id) data;
  222169. - (void) performCallback: (id) info;
  222170. - (void) dummyMethod;
  222171. @end
  222172. @implementation JuceAppDelegate
  222173. - (JuceAppDelegate*) init
  222174. {
  222175. [super init];
  222176. redirector = new AppDelegateRedirector();
  222177. numPendingMessages = 0;
  222178. flushingMessages = false;
  222179. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  222180. if (JUCEApplication::getInstance() != 0)
  222181. {
  222182. oldDelegate = [NSApp delegate];
  222183. [NSApp setDelegate: self];
  222184. }
  222185. else
  222186. {
  222187. oldDelegate = 0;
  222188. [center addObserver: self selector: @selector (applicationDidResignActive:)
  222189. name: NSApplicationDidResignActiveNotification object: NSApp];
  222190. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  222191. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  222192. [center addObserver: self selector: @selector (applicationWillUnhide:)
  222193. name: NSApplicationWillUnhideNotification object: NSApp];
  222194. }
  222195. return self;
  222196. }
  222197. - (void) dealloc
  222198. {
  222199. if (oldDelegate != 0)
  222200. [NSApp setDelegate: oldDelegate];
  222201. redirector->deleteSelf();
  222202. [super dealloc];
  222203. }
  222204. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  222205. {
  222206. return redirector->shouldTerminate();
  222207. }
  222208. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  222209. {
  222210. return redirector->openFile (filename);
  222211. }
  222212. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  222213. {
  222214. return redirector->openFiles (filenames);
  222215. }
  222216. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  222217. {
  222218. redirector->focusChanged();
  222219. }
  222220. - (void) applicationDidResignActive: (NSNotification*) aNotification
  222221. {
  222222. redirector->focusChanged();
  222223. }
  222224. - (void) applicationWillUnhide: (NSNotification*) aNotification
  222225. {
  222226. redirector->focusChanged();
  222227. }
  222228. - (void) customEvent: (id) n
  222229. {
  222230. atomicDecrement (numPendingMessages);
  222231. NSData* data = (NSData*) n;
  222232. void* message = 0;
  222233. [data getBytes: &message length: sizeof (message)];
  222234. [data release];
  222235. if (message != 0 && ! flushingMessages)
  222236. redirector->deliverMessage (message);
  222237. }
  222238. - (void) performCallback: (id) info
  222239. {
  222240. if ([info isKindOfClass: [NSData class]])
  222241. {
  222242. CallbackMessagePayload* pl = (CallbackMessagePayload*) [((NSData*) info) bytes];
  222243. if (pl != 0)
  222244. redirector->performCallback (pl);
  222245. }
  222246. else
  222247. {
  222248. jassertfalse // should never get here!
  222249. }
  222250. }
  222251. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  222252. @end
  222253. BEGIN_JUCE_NAMESPACE
  222254. static JuceAppDelegate* juceAppDelegate = 0;
  222255. void MessageManager::runDispatchLoop()
  222256. {
  222257. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  222258. {
  222259. const ScopedAutoReleasePool pool;
  222260. // must only be called by the message thread!
  222261. jassert (isThisTheMessageThread());
  222262. [NSApp run];
  222263. }
  222264. }
  222265. void MessageManager::stopDispatchLoop()
  222266. {
  222267. quitMessagePosted = true;
  222268. [NSApp stop: nil];
  222269. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  222270. }
  222271. static bool isEventBlockedByModalComps (NSEvent* e)
  222272. {
  222273. if (Component::getNumCurrentlyModalComponents() == 0)
  222274. return false;
  222275. NSWindow* const w = [e window];
  222276. if (w == 0 || [w worksWhenModal])
  222277. return false;
  222278. bool isKey = false, isInputAttempt = false;
  222279. switch ([e type])
  222280. {
  222281. case NSKeyDown:
  222282. case NSKeyUp:
  222283. isKey = isInputAttempt = true;
  222284. break;
  222285. case NSLeftMouseDown:
  222286. case NSRightMouseDown:
  222287. case NSOtherMouseDown:
  222288. isInputAttempt = true;
  222289. break;
  222290. case NSLeftMouseDragged:
  222291. case NSRightMouseDragged:
  222292. case NSLeftMouseUp:
  222293. case NSRightMouseUp:
  222294. case NSOtherMouseUp:
  222295. case NSOtherMouseDragged:
  222296. if (Component::getComponentUnderMouse() != 0)
  222297. return false;
  222298. break;
  222299. case NSMouseMoved:
  222300. case NSMouseEntered:
  222301. case NSMouseExited:
  222302. case NSCursorUpdate:
  222303. case NSScrollWheel:
  222304. case NSTabletPoint:
  222305. case NSTabletProximity:
  222306. break;
  222307. default:
  222308. return false;
  222309. }
  222310. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  222311. {
  222312. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  222313. NSView* const compView = (NSView*) peer->getNativeHandle();
  222314. if ([compView window] == w)
  222315. {
  222316. if (isKey)
  222317. {
  222318. if (compView == [w firstResponder])
  222319. return false;
  222320. }
  222321. else
  222322. {
  222323. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  222324. [compView bounds]))
  222325. return false;
  222326. }
  222327. }
  222328. }
  222329. if (isInputAttempt)
  222330. {
  222331. if (! [NSApp isActive])
  222332. [NSApp activateIgnoringOtherApps: YES];
  222333. Component* const modal = Component::getCurrentlyModalComponent (0);
  222334. if (modal != 0)
  222335. modal->inputAttemptWhenModal();
  222336. }
  222337. return true;
  222338. }
  222339. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  222340. {
  222341. const ScopedAutoReleasePool pool;
  222342. jassert (isThisTheMessageThread()); // must only be called by the message thread
  222343. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  222344. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  222345. while (! quitMessagePosted)
  222346. {
  222347. const ScopedAutoReleasePool pool;
  222348. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  222349. beforeDate: endDate];
  222350. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  222351. untilDate: endDate
  222352. inMode: NSDefaultRunLoopMode
  222353. dequeue: YES];
  222354. if (e != 0 && ! isEventBlockedByModalComps (e))
  222355. [NSApp sendEvent: e];
  222356. if (Time::getMillisecondCounter() >= endTime)
  222357. break;
  222358. }
  222359. return ! quitMessagePosted;
  222360. }
  222361. void MessageManager::doPlatformSpecificInitialisation()
  222362. {
  222363. if (juceAppDelegate == 0)
  222364. juceAppDelegate = [[JuceAppDelegate alloc] init];
  222365. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  222366. // correctly (needed prior to 10.5)
  222367. if (! [NSThread isMultiThreaded])
  222368. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  222369. toTarget: juceAppDelegate
  222370. withObject: nil];
  222371. initialiseMainMenu();
  222372. }
  222373. void MessageManager::doPlatformSpecificShutdown()
  222374. {
  222375. if (juceAppDelegate != 0)
  222376. {
  222377. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  222378. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  222379. // Annoyingly, cancelPerformSelectorsWithTarget can't actually cancel the messages
  222380. // sent by performSelectorOnMainThread, so need to manually flush these before quitting..
  222381. juceAppDelegate->flushingMessages = true;
  222382. for (int i = 100; --i >= 0 && numPendingMessages > 0;)
  222383. {
  222384. const ScopedAutoReleasePool pool;
  222385. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  222386. beforeDate: [NSDate dateWithTimeIntervalSinceNow: 5 * 0.001]];
  222387. }
  222388. [juceAppDelegate release];
  222389. juceAppDelegate = 0;
  222390. }
  222391. }
  222392. bool juce_postMessageToSystemQueue (void* message)
  222393. {
  222394. atomicIncrement (numPendingMessages);
  222395. [juceAppDelegate performSelectorOnMainThread: @selector (customEvent:)
  222396. withObject: (id) [[NSData alloc] initWithBytes: &message length: (int) sizeof (message)]
  222397. waitUntilDone: NO];
  222398. return true;
  222399. }
  222400. void MessageManager::broadcastMessage (const String& value) throw()
  222401. {
  222402. }
  222403. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  222404. void* data)
  222405. {
  222406. if (isThisTheMessageThread())
  222407. {
  222408. return (*callback) (data);
  222409. }
  222410. else
  222411. {
  222412. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  222413. // deadlock because the message manager is blocked from running, so can never
  222414. // call your function..
  222415. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  222416. const ScopedAutoReleasePool pool;
  222417. CallbackMessagePayload cmp;
  222418. cmp.function = callback;
  222419. cmp.parameter = data;
  222420. cmp.result = 0;
  222421. cmp.hasBeenExecuted = false;
  222422. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  222423. withObject: [NSData dataWithBytesNoCopy: &cmp
  222424. length: sizeof (cmp)
  222425. freeWhenDone: NO]
  222426. waitUntilDone: YES];
  222427. return cmp.result;
  222428. }
  222429. }
  222430. #endif
  222431. /********* End of inlined file: juce_mac_MessageManager.mm *********/
  222432. /********* Start of inlined file: juce_mac_WebBrowserComponent.mm *********/
  222433. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222434. // compiled on its own).
  222435. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  222436. END_JUCE_NAMESPACE
  222437. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  222438. @interface DownloadClickDetector : NSObject
  222439. {
  222440. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  222441. }
  222442. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  222443. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  222444. request: (NSURLRequest*) request
  222445. frame: (WebFrame*) frame
  222446. decisionListener: (id<WebPolicyDecisionListener>) listener;
  222447. @end
  222448. @implementation DownloadClickDetector
  222449. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  222450. {
  222451. [super init];
  222452. ownerComponent = ownerComponent_;
  222453. return self;
  222454. }
  222455. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  222456. request: (NSURLRequest*) request
  222457. frame: (WebFrame*) frame
  222458. decisionListener: (id <WebPolicyDecisionListener>) listener
  222459. {
  222460. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  222461. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  222462. [listener use];
  222463. else
  222464. [listener ignore];
  222465. }
  222466. @end
  222467. BEGIN_JUCE_NAMESPACE
  222468. class WebBrowserComponentInternal : public NSViewComponent
  222469. {
  222470. public:
  222471. WebBrowserComponentInternal (WebBrowserComponent* owner)
  222472. {
  222473. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  222474. frameName: @""
  222475. groupName: @""];
  222476. setView (webView);
  222477. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  222478. [webView setPolicyDelegate: clickListener];
  222479. }
  222480. ~WebBrowserComponentInternal()
  222481. {
  222482. [webView setPolicyDelegate: nil];
  222483. [clickListener release];
  222484. setView (0);
  222485. }
  222486. void goToURL (const String& url,
  222487. const StringArray* headers,
  222488. const MemoryBlock* postData)
  222489. {
  222490. NSMutableURLRequest* r
  222491. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  222492. cachePolicy: NSURLRequestUseProtocolCachePolicy
  222493. timeoutInterval: 30.0];
  222494. if (postData != 0 && postData->getSize() > 0)
  222495. {
  222496. [r setHTTPMethod: @"POST"];
  222497. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  222498. length: postData->getSize()]];
  222499. }
  222500. if (headers != 0)
  222501. {
  222502. for (int i = 0; i < headers->size(); ++i)
  222503. {
  222504. const String headerName ((*headers)[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  222505. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  222506. [r setValue: juceStringToNS (headerValue)
  222507. forHTTPHeaderField: juceStringToNS (headerName)];
  222508. }
  222509. }
  222510. stop();
  222511. [[webView mainFrame] loadRequest: r];
  222512. }
  222513. void goBack()
  222514. {
  222515. [webView goBack];
  222516. }
  222517. void goForward()
  222518. {
  222519. [webView goForward];
  222520. }
  222521. void stop()
  222522. {
  222523. [webView stopLoading: nil];
  222524. }
  222525. void refresh()
  222526. {
  222527. [webView reload: nil];
  222528. }
  222529. private:
  222530. WebView* webView;
  222531. DownloadClickDetector* clickListener;
  222532. };
  222533. WebBrowserComponent::WebBrowserComponent()
  222534. : browser (0),
  222535. blankPageShown (false)
  222536. {
  222537. setOpaque (true);
  222538. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  222539. }
  222540. WebBrowserComponent::~WebBrowserComponent()
  222541. {
  222542. deleteAndZero (browser);
  222543. }
  222544. void WebBrowserComponent::goToURL (const String& url,
  222545. const StringArray* headers,
  222546. const MemoryBlock* postData)
  222547. {
  222548. lastURL = url;
  222549. lastHeaders.clear();
  222550. if (headers != 0)
  222551. lastHeaders = *headers;
  222552. lastPostData.setSize (0);
  222553. if (postData != 0)
  222554. lastPostData = *postData;
  222555. blankPageShown = false;
  222556. browser->goToURL (url, headers, postData);
  222557. }
  222558. void WebBrowserComponent::stop()
  222559. {
  222560. browser->stop();
  222561. }
  222562. void WebBrowserComponent::goBack()
  222563. {
  222564. lastURL = String::empty;
  222565. blankPageShown = false;
  222566. browser->goBack();
  222567. }
  222568. void WebBrowserComponent::goForward()
  222569. {
  222570. lastURL = String::empty;
  222571. browser->goForward();
  222572. }
  222573. void WebBrowserComponent::refresh()
  222574. {
  222575. browser->refresh();
  222576. }
  222577. void WebBrowserComponent::paint (Graphics& g)
  222578. {
  222579. }
  222580. void WebBrowserComponent::checkWindowAssociation()
  222581. {
  222582. // when the component becomes invisible, some stuff like flash
  222583. // carries on playing audio, so we need to force it onto a blank
  222584. // page to avoid this, (and send it back when it's made visible again).
  222585. if (isShowing())
  222586. {
  222587. if (blankPageShown)
  222588. goBack();
  222589. }
  222590. else
  222591. {
  222592. if (! blankPageShown)
  222593. {
  222594. blankPageShown = true;
  222595. browser->goToURL ("about:blank", 0, 0);
  222596. }
  222597. }
  222598. }
  222599. void WebBrowserComponent::reloadLastURL()
  222600. {
  222601. if (lastURL.isNotEmpty())
  222602. {
  222603. goToURL (lastURL, &lastHeaders, &lastPostData);
  222604. lastURL = String::empty;
  222605. }
  222606. }
  222607. void WebBrowserComponent::parentHierarchyChanged()
  222608. {
  222609. checkWindowAssociation();
  222610. }
  222611. void WebBrowserComponent::resized()
  222612. {
  222613. browser->setSize (getWidth(), getHeight());
  222614. }
  222615. void WebBrowserComponent::visibilityChanged()
  222616. {
  222617. checkWindowAssociation();
  222618. }
  222619. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  222620. {
  222621. return true;
  222622. }
  222623. #endif
  222624. /********* End of inlined file: juce_mac_WebBrowserComponent.mm *********/
  222625. /********* Start of inlined file: juce_mac_CoreAudio.cpp *********/
  222626. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222627. // compiled on its own).
  222628. #ifdef JUCE_INCLUDED_FILE
  222629. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  222630. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  222631. #endif
  222632. #undef log
  222633. #if JUCE_COREAUDIO_LOGGING_ENABLED
  222634. #define log(a) Logger::writeToLog (a)
  222635. #else
  222636. #define log(a)
  222637. #endif
  222638. #undef OK
  222639. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  222640. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  222641. {
  222642. if (err == noErr)
  222643. return true;
  222644. Logger::writeToLog (T("CoreAudio error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  222645. jassertfalse
  222646. return false;
  222647. }
  222648. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  222649. #else
  222650. #define OK(a) (a == noErr)
  222651. #endif
  222652. static const int maxNumChans = 96;
  222653. class CoreAudioInternal : public Timer
  222654. {
  222655. public:
  222656. CoreAudioInternal (AudioDeviceID id)
  222657. : inputLatency (0),
  222658. outputLatency (0),
  222659. callback (0),
  222660. #if ! MACOS_10_4_OR_EARLIER
  222661. audioProcID (0),
  222662. #endif
  222663. inputDevice (0),
  222664. isSlaveDevice (false),
  222665. deviceID (id),
  222666. started (false),
  222667. audioBuffer (0),
  222668. numInputChans (0),
  222669. numOutputChans (0),
  222670. callbacksAllowed (true),
  222671. numInputChannelInfos (0),
  222672. numOutputChannelInfos (0)
  222673. {
  222674. sampleRate = 0;
  222675. bufferSize = 512;
  222676. if (deviceID == 0)
  222677. {
  222678. error = TRANS("can't open device");
  222679. }
  222680. else
  222681. {
  222682. updateDetailsFromDevice();
  222683. AudioDeviceAddPropertyListener (deviceID,
  222684. kAudioPropertyWildcardChannel,
  222685. kAudioPropertyWildcardSection,
  222686. kAudioPropertyWildcardPropertyID,
  222687. deviceListenerProc, this);
  222688. }
  222689. }
  222690. ~CoreAudioInternal()
  222691. {
  222692. AudioDeviceRemovePropertyListener (deviceID,
  222693. kAudioPropertyWildcardChannel,
  222694. kAudioPropertyWildcardSection,
  222695. kAudioPropertyWildcardPropertyID,
  222696. deviceListenerProc);
  222697. stop (false);
  222698. juce_free (audioBuffer);
  222699. delete inputDevice;
  222700. }
  222701. void allocateTempBuffers()
  222702. {
  222703. const int tempBufSize = bufferSize + 4;
  222704. juce_free (audioBuffer);
  222705. audioBuffer = (float*) juce_calloc ((numInputChans + numOutputChans) * tempBufSize * sizeof (float));
  222706. zeromem (tempInputBuffers, sizeof (tempInputBuffers));
  222707. zeromem (tempOutputBuffers, sizeof (tempOutputBuffers));
  222708. int i, count = 0;
  222709. for (i = 0; i < numInputChans; ++i)
  222710. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  222711. for (i = 0; i < numOutputChans; ++i)
  222712. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  222713. }
  222714. // returns the number of actual available channels
  222715. void fillInChannelInfo (bool input)
  222716. {
  222717. int chanNum = 0, activeChans = 0;
  222718. UInt32 size;
  222719. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  222720. {
  222721. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  222722. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  222723. {
  222724. const int numStreams = bufList->mNumberBuffers;
  222725. for (int i = 0; i < numStreams; ++i)
  222726. {
  222727. const AudioBuffer& b = bufList->mBuffers[i];
  222728. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  222729. {
  222730. if (input)
  222731. {
  222732. if (activeInputChans[chanNum])
  222733. {
  222734. inputChannelInfo [activeChans].streamNum = i;
  222735. inputChannelInfo [activeChans].dataOffsetSamples = j;
  222736. inputChannelInfo [activeChans].dataStrideSamples = b.mNumberChannels;
  222737. ++activeChans;
  222738. numInputChannelInfos = activeChans;
  222739. }
  222740. inChanNames.add (T("input ") + String (chanNum + 1));
  222741. }
  222742. else
  222743. {
  222744. if (activeOutputChans[chanNum])
  222745. {
  222746. outputChannelInfo [activeChans].streamNum = i;
  222747. outputChannelInfo [activeChans].dataOffsetSamples = j;
  222748. outputChannelInfo [activeChans].dataStrideSamples = b.mNumberChannels;
  222749. ++activeChans;
  222750. numOutputChannelInfos = activeChans;
  222751. }
  222752. outChanNames.add (T("output ") + String (chanNum + 1));
  222753. }
  222754. ++chanNum;
  222755. }
  222756. }
  222757. }
  222758. juce_free (bufList);
  222759. }
  222760. }
  222761. void updateDetailsFromDevice()
  222762. {
  222763. stopTimer();
  222764. if (deviceID == 0)
  222765. return;
  222766. const ScopedLock sl (callbackLock);
  222767. Float64 sr;
  222768. UInt32 size = sizeof (Float64);
  222769. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyNominalSampleRate, &size, &sr)))
  222770. sampleRate = sr;
  222771. UInt32 framesPerBuf;
  222772. size = sizeof (framesPerBuf);
  222773. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSize, &size, &framesPerBuf)))
  222774. {
  222775. bufferSize = framesPerBuf;
  222776. allocateTempBuffers();
  222777. }
  222778. bufferSizes.clear();
  222779. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, 0)))
  222780. {
  222781. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  222782. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, ranges)))
  222783. {
  222784. bufferSizes.add ((int) ranges[0].mMinimum);
  222785. for (int i = 32; i < 8192; i += 32)
  222786. {
  222787. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  222788. {
  222789. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  222790. {
  222791. bufferSizes.addIfNotAlreadyThere (i);
  222792. break;
  222793. }
  222794. }
  222795. }
  222796. if (bufferSize > 0)
  222797. bufferSizes.addIfNotAlreadyThere (bufferSize);
  222798. }
  222799. juce_free (ranges);
  222800. }
  222801. if (bufferSizes.size() == 0 && bufferSize > 0)
  222802. bufferSizes.add (bufferSize);
  222803. sampleRates.clear();
  222804. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  222805. String rates;
  222806. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, 0)))
  222807. {
  222808. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  222809. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, ranges)))
  222810. {
  222811. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  222812. {
  222813. bool ok = false;
  222814. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  222815. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  222816. ok = true;
  222817. if (ok)
  222818. {
  222819. sampleRates.add (possibleRates[i]);
  222820. rates << possibleRates[i] << T(" ");
  222821. }
  222822. }
  222823. }
  222824. juce_free (ranges);
  222825. }
  222826. if (sampleRates.size() == 0 && sampleRate > 0)
  222827. {
  222828. sampleRates.add (sampleRate);
  222829. rates << sampleRate;
  222830. }
  222831. log (T("sr: ") + rates);
  222832. inputLatency = 0;
  222833. outputLatency = 0;
  222834. UInt32 lat;
  222835. size = sizeof (UInt32);
  222836. if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  222837. inputLatency = (int) lat;
  222838. if (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  222839. outputLatency = (int) lat;
  222840. log (T("lat: ") + String (inputLatency) + T(" ") + String (outputLatency));
  222841. inChanNames.clear();
  222842. outChanNames.clear();
  222843. zeromem (inputChannelInfo, sizeof (inputChannelInfo));
  222844. zeromem (outputChannelInfo, sizeof (outputChannelInfo));
  222845. fillInChannelInfo (true);
  222846. fillInChannelInfo (false);
  222847. }
  222848. const StringArray getSources (bool input)
  222849. {
  222850. StringArray s;
  222851. int num = 0;
  222852. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  222853. if (types != 0)
  222854. {
  222855. for (int i = 0; i < num; ++i)
  222856. {
  222857. AudioValueTranslation avt;
  222858. char buffer[256];
  222859. avt.mInputData = (void*) &(types[i]);
  222860. avt.mInputDataSize = sizeof (UInt32);
  222861. avt.mOutputData = buffer;
  222862. avt.mOutputDataSize = 256;
  222863. UInt32 transSize = sizeof (avt);
  222864. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSourceNameForID, &transSize, &avt)))
  222865. {
  222866. DBG (buffer);
  222867. s.add (buffer);
  222868. }
  222869. }
  222870. juce_free (types);
  222871. }
  222872. return s;
  222873. }
  222874. int getCurrentSourceIndex (bool input) const
  222875. {
  222876. OSType currentSourceID = 0;
  222877. UInt32 size = 0;
  222878. int result = -1;
  222879. if (deviceID != 0
  222880. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, 0)))
  222881. {
  222882. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, &currentSourceID)))
  222883. {
  222884. int num = 0;
  222885. OSType* const types = getAllDataSourcesForDevice (deviceID, input, num);
  222886. if (types != 0)
  222887. {
  222888. for (int i = 0; i < num; ++i)
  222889. {
  222890. if (types[num] == currentSourceID)
  222891. {
  222892. result = i;
  222893. break;
  222894. }
  222895. }
  222896. juce_free (types);
  222897. }
  222898. }
  222899. }
  222900. return result;
  222901. }
  222902. void setCurrentSourceIndex (int index, bool input)
  222903. {
  222904. if (deviceID != 0)
  222905. {
  222906. int num = 0;
  222907. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  222908. if (types != 0)
  222909. {
  222910. if (((unsigned int) index) < (unsigned int) num)
  222911. {
  222912. OSType typeId = types[index];
  222913. AudioDeviceSetProperty (deviceID, 0, 0, input, kAudioDevicePropertyDataSource, sizeof (typeId), &typeId);
  222914. }
  222915. juce_free (types);
  222916. }
  222917. }
  222918. }
  222919. const String reopen (const BitArray& inputChannels,
  222920. const BitArray& outputChannels,
  222921. double newSampleRate,
  222922. int bufferSizeSamples)
  222923. {
  222924. error = String::empty;
  222925. log ("CoreAudio reopen");
  222926. callbacksAllowed = false;
  222927. stopTimer();
  222928. stop (false);
  222929. activeInputChans = inputChannels;
  222930. activeOutputChans = outputChannels;
  222931. activeInputChans.setRange (inChanNames.size(),
  222932. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  222933. false);
  222934. activeOutputChans.setRange (outChanNames.size(),
  222935. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  222936. false);
  222937. numInputChans = activeInputChans.countNumberOfSetBits();
  222938. numOutputChans = activeOutputChans.countNumberOfSetBits();
  222939. // set sample rate
  222940. Float64 sr = newSampleRate;
  222941. UInt32 size = sizeof (sr);
  222942. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyNominalSampleRate, size, &sr));
  222943. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyNominalSampleRate, size, &sr));
  222944. // change buffer size
  222945. UInt32 framesPerBuf = bufferSizeSamples;
  222946. size = sizeof (framesPerBuf);
  222947. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  222948. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  222949. // wait for the changes to happen (on some devices)
  222950. int i = 30;
  222951. while (--i >= 0)
  222952. {
  222953. updateDetailsFromDevice();
  222954. if (sampleRate == newSampleRate && bufferSizeSamples == bufferSize)
  222955. break;
  222956. Thread::sleep (100);
  222957. }
  222958. if (i < 0)
  222959. error = "Couldn't change sample rate/buffer size";
  222960. if (sampleRates.size() == 0)
  222961. error = "Device has no available sample-rates";
  222962. if (bufferSizes.size() == 0)
  222963. error = "Device has no available buffer-sizes";
  222964. if (inputDevice != 0 && error.isEmpty())
  222965. error = inputDevice->reopen (inputChannels,
  222966. outputChannels,
  222967. newSampleRate,
  222968. bufferSizeSamples);
  222969. callbacksAllowed = true;
  222970. return error;
  222971. }
  222972. bool start (AudioIODeviceCallback* cb)
  222973. {
  222974. if (! started)
  222975. {
  222976. callback = 0;
  222977. if (deviceID != 0)
  222978. {
  222979. #if MACOS_10_4_OR_EARLIER
  222980. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, (void*) this)))
  222981. #else
  222982. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, (void*) this, &audioProcID)))
  222983. #endif
  222984. {
  222985. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  222986. {
  222987. started = true;
  222988. }
  222989. else
  222990. {
  222991. #if MACOS_10_4_OR_EARLIER
  222992. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  222993. #else
  222994. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  222995. audioProcID = 0;
  222996. #endif
  222997. }
  222998. }
  222999. }
  223000. }
  223001. if (started)
  223002. {
  223003. const ScopedLock sl (callbackLock);
  223004. callback = cb;
  223005. }
  223006. if (inputDevice != 0)
  223007. return started && inputDevice->start (cb);
  223008. else
  223009. return started;
  223010. }
  223011. void stop (bool leaveInterruptRunning)
  223012. {
  223013. callbackLock.enter();
  223014. callback = 0;
  223015. callbackLock.exit();
  223016. if (started
  223017. && (deviceID != 0)
  223018. && ! leaveInterruptRunning)
  223019. {
  223020. OK (AudioDeviceStop (deviceID, audioIOProc));
  223021. #if MACOS_10_4_OR_EARLIER
  223022. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  223023. #else
  223024. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  223025. audioProcID = 0;
  223026. #endif
  223027. started = false;
  223028. callbackLock.enter();
  223029. callbackLock.exit();
  223030. // wait until it's definately stopped calling back..
  223031. for (int i = 40; --i >= 0;)
  223032. {
  223033. Thread::sleep (50);
  223034. UInt32 running = 0;
  223035. UInt32 size = sizeof (running);
  223036. OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyDeviceIsRunning, &size, &running));
  223037. if (running == 0)
  223038. break;
  223039. }
  223040. callbackLock.enter();
  223041. callbackLock.exit();
  223042. }
  223043. if (inputDevice != 0)
  223044. inputDevice->stop (leaveInterruptRunning);
  223045. }
  223046. double getSampleRate() const
  223047. {
  223048. return sampleRate;
  223049. }
  223050. int getBufferSize() const
  223051. {
  223052. return bufferSize;
  223053. }
  223054. void audioCallback (const AudioBufferList* inInputData,
  223055. AudioBufferList* outOutputData)
  223056. {
  223057. int i;
  223058. const ScopedLock sl (callbackLock);
  223059. if (callback != 0)
  223060. {
  223061. if (inputDevice == 0)
  223062. {
  223063. for (i = numInputChans; --i >= 0;)
  223064. {
  223065. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  223066. float* dest = tempInputBuffers [i];
  223067. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  223068. + info.dataOffsetSamples;
  223069. const int stride = info.dataStrideSamples;
  223070. if (stride != 0) // if this is zero, info is invalid
  223071. {
  223072. for (int j = bufferSize; --j >= 0;)
  223073. {
  223074. *dest++ = *src;
  223075. src += stride;
  223076. }
  223077. }
  223078. }
  223079. }
  223080. if (! isSlaveDevice)
  223081. {
  223082. if (inputDevice == 0)
  223083. {
  223084. callback->audioDeviceIOCallback ((const float**) tempInputBuffers,
  223085. numInputChans,
  223086. tempOutputBuffers,
  223087. numOutputChans,
  223088. bufferSize);
  223089. }
  223090. else
  223091. {
  223092. jassert (inputDevice->bufferSize == bufferSize);
  223093. // Sometimes the two linked devices seem to get their callbacks in
  223094. // parallel, so we need to lock both devices to stop the input data being
  223095. // changed while inside our callback..
  223096. const ScopedLock sl (inputDevice->callbackLock);
  223097. callback->audioDeviceIOCallback ((const float**) inputDevice->tempInputBuffers,
  223098. inputDevice->numInputChans,
  223099. tempOutputBuffers,
  223100. numOutputChans,
  223101. bufferSize);
  223102. }
  223103. for (i = numOutputChans; --i >= 0;)
  223104. {
  223105. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  223106. const float* src = tempOutputBuffers [i];
  223107. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  223108. + info.dataOffsetSamples;
  223109. const int stride = info.dataStrideSamples;
  223110. if (stride != 0) // if this is zero, info is invalid
  223111. {
  223112. for (int j = bufferSize; --j >= 0;)
  223113. {
  223114. *dest = *src++;
  223115. dest += stride;
  223116. }
  223117. }
  223118. }
  223119. }
  223120. }
  223121. else
  223122. {
  223123. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  223124. {
  223125. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  223126. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  223127. + info.dataOffsetSamples;
  223128. const int stride = info.dataStrideSamples;
  223129. if (stride != 0) // if this is zero, info is invalid
  223130. {
  223131. for (int j = bufferSize; --j >= 0;)
  223132. {
  223133. *dest = 0.0f;
  223134. dest += stride;
  223135. }
  223136. }
  223137. }
  223138. }
  223139. }
  223140. // called by callbacks
  223141. void deviceDetailsChanged()
  223142. {
  223143. if (callbacksAllowed)
  223144. startTimer (100);
  223145. }
  223146. void timerCallback()
  223147. {
  223148. stopTimer();
  223149. log ("CoreAudio device changed callback");
  223150. const double oldSampleRate = sampleRate;
  223151. const int oldBufferSize = bufferSize;
  223152. updateDetailsFromDevice();
  223153. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  223154. {
  223155. callbacksAllowed = false;
  223156. stop (false);
  223157. updateDetailsFromDevice();
  223158. callbacksAllowed = true;
  223159. }
  223160. }
  223161. CoreAudioInternal* getRelatedDevice() const
  223162. {
  223163. UInt32 size = 0;
  223164. CoreAudioInternal* result = 0;
  223165. if (deviceID != 0
  223166. && AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, 0) == noErr
  223167. && size > 0)
  223168. {
  223169. AudioDeviceID* devs = (AudioDeviceID*) juce_calloc (size);
  223170. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, devs)))
  223171. {
  223172. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  223173. {
  223174. if (devs[i] != deviceID && devs[i] != 0)
  223175. {
  223176. result = new CoreAudioInternal (devs[i]);
  223177. if (result->error.isEmpty())
  223178. {
  223179. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  223180. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  223181. if (thisIsInput != otherIsInput
  223182. || (inChanNames.size() + outChanNames.size() == 0)
  223183. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  223184. break;
  223185. }
  223186. deleteAndZero (result);
  223187. }
  223188. }
  223189. }
  223190. juce_free (devs);
  223191. }
  223192. return result;
  223193. }
  223194. juce_UseDebuggingNewOperator
  223195. String error;
  223196. int inputLatency, outputLatency;
  223197. BitArray activeInputChans, activeOutputChans;
  223198. StringArray inChanNames, outChanNames;
  223199. Array <double> sampleRates;
  223200. Array <int> bufferSizes;
  223201. AudioIODeviceCallback* callback;
  223202. #if ! MACOS_10_4_OR_EARLIER
  223203. AudioDeviceIOProcID audioProcID;
  223204. #endif
  223205. CoreAudioInternal* inputDevice;
  223206. bool isSlaveDevice;
  223207. private:
  223208. CriticalSection callbackLock;
  223209. AudioDeviceID deviceID;
  223210. bool started;
  223211. double sampleRate;
  223212. int bufferSize;
  223213. float* audioBuffer;
  223214. int numInputChans, numOutputChans;
  223215. bool callbacksAllowed;
  223216. struct CallbackDetailsForChannel
  223217. {
  223218. int streamNum;
  223219. int dataOffsetSamples;
  223220. int dataStrideSamples;
  223221. };
  223222. int numInputChannelInfos, numOutputChannelInfos;
  223223. CallbackDetailsForChannel inputChannelInfo [maxNumChans];
  223224. CallbackDetailsForChannel outputChannelInfo [maxNumChans];
  223225. float* tempInputBuffers [maxNumChans];
  223226. float* tempOutputBuffers [maxNumChans];
  223227. CoreAudioInternal (const CoreAudioInternal&);
  223228. const CoreAudioInternal& operator= (const CoreAudioInternal&);
  223229. static OSStatus audioIOProc (AudioDeviceID inDevice,
  223230. const AudioTimeStamp* inNow,
  223231. const AudioBufferList* inInputData,
  223232. const AudioTimeStamp* inInputTime,
  223233. AudioBufferList* outOutputData,
  223234. const AudioTimeStamp* inOutputTime,
  223235. void* device)
  223236. {
  223237. ((CoreAudioInternal*) device)->audioCallback (inInputData, outOutputData);
  223238. return noErr;
  223239. }
  223240. static OSStatus deviceListenerProc (AudioDeviceID inDevice,
  223241. UInt32 inLine,
  223242. Boolean isInput,
  223243. AudioDevicePropertyID inPropertyID,
  223244. void* inClientData)
  223245. {
  223246. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  223247. switch (inPropertyID)
  223248. {
  223249. case kAudioDevicePropertyBufferSize:
  223250. case kAudioDevicePropertyBufferFrameSize:
  223251. case kAudioDevicePropertyNominalSampleRate:
  223252. case kAudioDevicePropertyStreamFormat:
  223253. case kAudioDevicePropertyDeviceIsAlive:
  223254. intern->deviceDetailsChanged();
  223255. break;
  223256. case kAudioDevicePropertyBufferSizeRange:
  223257. case kAudioDevicePropertyVolumeScalar:
  223258. case kAudioDevicePropertyMute:
  223259. case kAudioDevicePropertyPlayThru:
  223260. case kAudioDevicePropertyDataSource:
  223261. case kAudioDevicePropertyDeviceIsRunning:
  223262. break;
  223263. }
  223264. return noErr;
  223265. }
  223266. static OSType* getAllDataSourcesForDevice (AudioDeviceID deviceID, const bool input, int& num)
  223267. {
  223268. OSType* types = 0;
  223269. UInt32 size = 0;
  223270. num = 0;
  223271. if (deviceID != 0
  223272. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, 0)))
  223273. {
  223274. types = (OSType*) juce_calloc (size);
  223275. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, types)))
  223276. {
  223277. num = size / sizeof (OSType);
  223278. }
  223279. else
  223280. {
  223281. juce_free (types);
  223282. types = 0;
  223283. }
  223284. }
  223285. return types;
  223286. }
  223287. };
  223288. class CoreAudioIODevice : public AudioIODevice
  223289. {
  223290. public:
  223291. CoreAudioIODevice (const String& deviceName,
  223292. AudioDeviceID inputDeviceId,
  223293. const int inputIndex_,
  223294. AudioDeviceID outputDeviceId,
  223295. const int outputIndex_)
  223296. : AudioIODevice (deviceName, "CoreAudio"),
  223297. inputIndex (inputIndex_),
  223298. outputIndex (outputIndex_),
  223299. isOpen_ (false),
  223300. isStarted (false)
  223301. {
  223302. internal = 0;
  223303. CoreAudioInternal* device = 0;
  223304. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  223305. {
  223306. jassert (inputDeviceId != 0);
  223307. device = new CoreAudioInternal (inputDeviceId);
  223308. lastError = device->error;
  223309. if (lastError.isNotEmpty())
  223310. deleteAndZero (device);
  223311. }
  223312. else
  223313. {
  223314. device = new CoreAudioInternal (outputDeviceId);
  223315. lastError = device->error;
  223316. if (lastError.isNotEmpty())
  223317. {
  223318. deleteAndZero (device);
  223319. }
  223320. else if (inputDeviceId != 0)
  223321. {
  223322. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  223323. lastError = device->error;
  223324. if (lastError.isNotEmpty())
  223325. {
  223326. delete secondDevice;
  223327. }
  223328. else
  223329. {
  223330. device->inputDevice = secondDevice;
  223331. secondDevice->isSlaveDevice = true;
  223332. }
  223333. }
  223334. }
  223335. internal = device;
  223336. AudioHardwareAddPropertyListener (kAudioPropertyWildcardPropertyID,
  223337. hardwareListenerProc, internal);
  223338. }
  223339. ~CoreAudioIODevice()
  223340. {
  223341. AudioHardwareRemovePropertyListener (kAudioPropertyWildcardPropertyID,
  223342. hardwareListenerProc);
  223343. delete internal;
  223344. }
  223345. const StringArray getOutputChannelNames()
  223346. {
  223347. return internal->outChanNames;
  223348. }
  223349. const StringArray getInputChannelNames()
  223350. {
  223351. if (internal->inputDevice != 0)
  223352. return internal->inputDevice->inChanNames;
  223353. else
  223354. return internal->inChanNames;
  223355. }
  223356. int getNumSampleRates()
  223357. {
  223358. return internal->sampleRates.size();
  223359. }
  223360. double getSampleRate (int index)
  223361. {
  223362. return internal->sampleRates [index];
  223363. }
  223364. int getNumBufferSizesAvailable()
  223365. {
  223366. return internal->bufferSizes.size();
  223367. }
  223368. int getBufferSizeSamples (int index)
  223369. {
  223370. return internal->bufferSizes [index];
  223371. }
  223372. int getDefaultBufferSize()
  223373. {
  223374. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  223375. if (getBufferSizeSamples(i) >= 512)
  223376. return getBufferSizeSamples(i);
  223377. return 512;
  223378. }
  223379. const String open (const BitArray& inputChannels,
  223380. const BitArray& outputChannels,
  223381. double sampleRate,
  223382. int bufferSizeSamples)
  223383. {
  223384. isOpen_ = true;
  223385. if (bufferSizeSamples <= 0)
  223386. bufferSizeSamples = getDefaultBufferSize();
  223387. internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  223388. lastError = internal->error;
  223389. return lastError;
  223390. }
  223391. void close()
  223392. {
  223393. isOpen_ = false;
  223394. }
  223395. bool isOpen()
  223396. {
  223397. return isOpen_;
  223398. }
  223399. int getCurrentBufferSizeSamples()
  223400. {
  223401. return internal != 0 ? internal->getBufferSize() : 512;
  223402. }
  223403. double getCurrentSampleRate()
  223404. {
  223405. return internal != 0 ? internal->getSampleRate() : 0;
  223406. }
  223407. int getCurrentBitDepth()
  223408. {
  223409. return 32; // no way to find out, so just assume it's high..
  223410. }
  223411. const BitArray getActiveOutputChannels() const
  223412. {
  223413. return internal != 0 ? internal->activeOutputChans : BitArray();
  223414. }
  223415. const BitArray getActiveInputChannels() const
  223416. {
  223417. BitArray chans;
  223418. if (internal != 0)
  223419. {
  223420. chans = internal->activeInputChans;
  223421. if (internal->inputDevice != 0)
  223422. chans.orWith (internal->inputDevice->activeInputChans);
  223423. }
  223424. return chans;
  223425. }
  223426. int getOutputLatencyInSamples()
  223427. {
  223428. if (internal == 0)
  223429. return 0;
  223430. // this seems like a good guess at getting the latency right - comparing
  223431. // this with a round-trip measurement, it gets it to within a few millisecs
  223432. // for the built-in mac soundcard
  223433. return internal->outputLatency + internal->getBufferSize() * 2;
  223434. }
  223435. int getInputLatencyInSamples()
  223436. {
  223437. if (internal == 0)
  223438. return 0;
  223439. return internal->inputLatency + internal->getBufferSize() * 2;
  223440. }
  223441. void start (AudioIODeviceCallback* callback)
  223442. {
  223443. if (internal != 0 && ! isStarted)
  223444. {
  223445. if (callback != 0)
  223446. callback->audioDeviceAboutToStart (this);
  223447. isStarted = true;
  223448. internal->start (callback);
  223449. }
  223450. }
  223451. void stop()
  223452. {
  223453. if (isStarted && internal != 0)
  223454. {
  223455. AudioIODeviceCallback* const lastCallback = internal->callback;
  223456. isStarted = false;
  223457. internal->stop (true);
  223458. if (lastCallback != 0)
  223459. lastCallback->audioDeviceStopped();
  223460. }
  223461. }
  223462. bool isPlaying()
  223463. {
  223464. if (internal->callback == 0)
  223465. isStarted = false;
  223466. return isStarted;
  223467. }
  223468. const String getLastError()
  223469. {
  223470. return lastError;
  223471. }
  223472. int inputIndex, outputIndex;
  223473. juce_UseDebuggingNewOperator
  223474. private:
  223475. CoreAudioInternal* internal;
  223476. bool isOpen_, isStarted;
  223477. String lastError;
  223478. static OSStatus hardwareListenerProc (AudioHardwarePropertyID inPropertyID, void* inClientData)
  223479. {
  223480. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  223481. switch (inPropertyID)
  223482. {
  223483. case kAudioHardwarePropertyDevices:
  223484. intern->deviceDetailsChanged();
  223485. break;
  223486. case kAudioHardwarePropertyDefaultOutputDevice:
  223487. case kAudioHardwarePropertyDefaultInputDevice:
  223488. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  223489. break;
  223490. }
  223491. return noErr;
  223492. }
  223493. CoreAudioIODevice (const CoreAudioIODevice&);
  223494. const CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  223495. };
  223496. class CoreAudioIODeviceType : public AudioIODeviceType
  223497. {
  223498. public:
  223499. CoreAudioIODeviceType()
  223500. : AudioIODeviceType (T("CoreAudio")),
  223501. hasScanned (false)
  223502. {
  223503. }
  223504. ~CoreAudioIODeviceType()
  223505. {
  223506. }
  223507. void scanForDevices()
  223508. {
  223509. hasScanned = true;
  223510. inputDeviceNames.clear();
  223511. outputDeviceNames.clear();
  223512. inputIds.clear();
  223513. outputIds.clear();
  223514. UInt32 size;
  223515. if (OK (AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices, &size, 0)))
  223516. {
  223517. AudioDeviceID* const devs = (AudioDeviceID*) juce_calloc (size);
  223518. if (OK (AudioHardwareGetProperty (kAudioHardwarePropertyDevices, &size, devs)))
  223519. {
  223520. static bool alreadyLogged = false;
  223521. const int num = size / sizeof (AudioDeviceID);
  223522. for (int i = 0; i < num; ++i)
  223523. {
  223524. char name[1024];
  223525. size = sizeof (name);
  223526. if (OK (AudioDeviceGetProperty (devs[i], 0, false, kAudioDevicePropertyDeviceName, &size, name)))
  223527. {
  223528. const String nameString (String::fromUTF8 ((const uint8*) name, strlen (name)));
  223529. if (! alreadyLogged)
  223530. log (T("CoreAudio device: ") + nameString);
  223531. const int numIns = getNumChannels (devs[i], true);
  223532. const int numOuts = getNumChannels (devs[i], false);
  223533. if (numIns > 0)
  223534. {
  223535. inputDeviceNames.add (nameString);
  223536. inputIds.add (devs[i]);
  223537. }
  223538. if (numOuts > 0)
  223539. {
  223540. outputDeviceNames.add (nameString);
  223541. outputIds.add (devs[i]);
  223542. }
  223543. }
  223544. }
  223545. alreadyLogged = true;
  223546. }
  223547. juce_free (devs);
  223548. }
  223549. inputDeviceNames.appendNumbersToDuplicates (false, true);
  223550. outputDeviceNames.appendNumbersToDuplicates (false, true);
  223551. }
  223552. const StringArray getDeviceNames (const bool wantInputNames) const
  223553. {
  223554. jassert (hasScanned); // need to call scanForDevices() before doing this
  223555. if (wantInputNames)
  223556. return inputDeviceNames;
  223557. else
  223558. return outputDeviceNames;
  223559. }
  223560. int getDefaultDeviceIndex (const bool forInput) const
  223561. {
  223562. jassert (hasScanned); // need to call scanForDevices() before doing this
  223563. AudioDeviceID deviceID;
  223564. UInt32 size = sizeof (deviceID);
  223565. // if they're asking for any input channels at all, use the default input, so we
  223566. // get the built-in mic rather than the built-in output with no inputs..
  223567. if (AudioHardwareGetProperty (forInput ? kAudioHardwarePropertyDefaultInputDevice
  223568. : kAudioHardwarePropertyDefaultOutputDevice,
  223569. &size, &deviceID) == noErr)
  223570. {
  223571. if (forInput)
  223572. {
  223573. for (int i = inputIds.size(); --i >= 0;)
  223574. if (inputIds[i] == deviceID)
  223575. return i;
  223576. }
  223577. else
  223578. {
  223579. for (int i = outputIds.size(); --i >= 0;)
  223580. if (outputIds[i] == deviceID)
  223581. return i;
  223582. }
  223583. }
  223584. return 0;
  223585. }
  223586. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  223587. {
  223588. jassert (hasScanned); // need to call scanForDevices() before doing this
  223589. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  223590. if (d == 0)
  223591. return -1;
  223592. return asInput ? d->inputIndex
  223593. : d->outputIndex;
  223594. }
  223595. bool hasSeparateInputsAndOutputs() const { return true; }
  223596. AudioIODevice* createDevice (const String& outputDeviceName,
  223597. const String& inputDeviceName)
  223598. {
  223599. jassert (hasScanned); // need to call scanForDevices() before doing this
  223600. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  223601. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  223602. String deviceName (outputDeviceName);
  223603. if (deviceName.isEmpty())
  223604. deviceName = inputDeviceName;
  223605. if (index >= 0)
  223606. return new CoreAudioIODevice (deviceName,
  223607. inputIds [inputIndex],
  223608. inputIndex,
  223609. outputIds [outputIndex],
  223610. outputIndex);
  223611. return 0;
  223612. }
  223613. juce_UseDebuggingNewOperator
  223614. private:
  223615. StringArray inputDeviceNames, outputDeviceNames;
  223616. Array <AudioDeviceID> inputIds, outputIds;
  223617. bool hasScanned;
  223618. static int getNumChannels (AudioDeviceID deviceID, bool input)
  223619. {
  223620. int total = 0;
  223621. UInt32 size;
  223622. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  223623. {
  223624. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  223625. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  223626. {
  223627. const int numStreams = bufList->mNumberBuffers;
  223628. for (int i = 0; i < numStreams; ++i)
  223629. {
  223630. const AudioBuffer& b = bufList->mBuffers[i];
  223631. total += b.mNumberChannels;
  223632. }
  223633. }
  223634. juce_free (bufList);
  223635. }
  223636. return total;
  223637. }
  223638. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  223639. const CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  223640. };
  223641. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  223642. {
  223643. return new CoreAudioIODeviceType();
  223644. }
  223645. #undef log
  223646. #endif
  223647. /********* End of inlined file: juce_mac_CoreAudio.cpp *********/
  223648. /********* Start of inlined file: juce_mac_CoreMidi.cpp *********/
  223649. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223650. // compiled on its own).
  223651. #ifdef JUCE_INCLUDED_FILE
  223652. #undef log
  223653. #define log(a) Logger::writeToLog(a)
  223654. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  223655. {
  223656. if (err == noErr)
  223657. return true;
  223658. log (T("CoreMidi error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  223659. jassertfalse
  223660. return false;
  223661. }
  223662. #undef OK
  223663. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  223664. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  223665. {
  223666. String result;
  223667. CFStringRef str = 0;
  223668. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  223669. if (str != 0)
  223670. {
  223671. result = PlatformUtilities::cfStringToJuceString (str);
  223672. CFRelease (str);
  223673. str = 0;
  223674. }
  223675. MIDIEntityRef entity = 0;
  223676. MIDIEndpointGetEntity (endpoint, &entity);
  223677. if (entity == 0)
  223678. return result; // probably virtual
  223679. if (result.isEmpty())
  223680. {
  223681. // endpoint name has zero length - try the entity
  223682. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  223683. if (str != 0)
  223684. {
  223685. result += PlatformUtilities::cfStringToJuceString (str);
  223686. CFRelease (str);
  223687. str = 0;
  223688. }
  223689. }
  223690. // now consider the device's name
  223691. MIDIDeviceRef device = 0;
  223692. MIDIEntityGetDevice (entity, &device);
  223693. if (device == 0)
  223694. return result;
  223695. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  223696. if (str != 0)
  223697. {
  223698. const String s (PlatformUtilities::cfStringToJuceString (str));
  223699. CFRelease (str);
  223700. // if an external device has only one entity, throw away
  223701. // the endpoint name and just use the device name
  223702. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  223703. {
  223704. result = s;
  223705. }
  223706. else if (! result.startsWithIgnoreCase (s))
  223707. {
  223708. // prepend the device name to the entity name
  223709. result = (s + T(" ") + result).trimEnd();
  223710. }
  223711. }
  223712. return result;
  223713. }
  223714. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  223715. {
  223716. String result;
  223717. // Does the endpoint have connections?
  223718. CFDataRef connections = 0;
  223719. int numConnections = 0;
  223720. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  223721. if (connections != 0)
  223722. {
  223723. numConnections = CFDataGetLength (connections) / sizeof (MIDIUniqueID);
  223724. if (numConnections > 0)
  223725. {
  223726. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  223727. for (int i = 0; i < numConnections; ++i, ++pid)
  223728. {
  223729. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  223730. MIDIObjectRef connObject;
  223731. MIDIObjectType connObjectType;
  223732. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  223733. if (err == noErr)
  223734. {
  223735. String s;
  223736. if (connObjectType == kMIDIObjectType_ExternalSource
  223737. || connObjectType == kMIDIObjectType_ExternalDestination)
  223738. {
  223739. // Connected to an external device's endpoint (10.3 and later).
  223740. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  223741. }
  223742. else
  223743. {
  223744. // Connected to an external device (10.2) (or something else, catch-all)
  223745. CFStringRef str = 0;
  223746. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  223747. if (str != 0)
  223748. {
  223749. s = PlatformUtilities::cfStringToJuceString (str);
  223750. CFRelease (str);
  223751. }
  223752. }
  223753. if (s.isNotEmpty())
  223754. {
  223755. if (result.isNotEmpty())
  223756. result += (", ");
  223757. result += s;
  223758. }
  223759. }
  223760. }
  223761. }
  223762. CFRelease (connections);
  223763. }
  223764. if (result.isNotEmpty())
  223765. return result;
  223766. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  223767. return getEndpointName (endpoint, false);
  223768. }
  223769. const StringArray MidiOutput::getDevices()
  223770. {
  223771. StringArray s;
  223772. const ItemCount num = MIDIGetNumberOfDestinations();
  223773. for (ItemCount i = 0; i < num; ++i)
  223774. {
  223775. MIDIEndpointRef dest = MIDIGetDestination (i);
  223776. if (dest != 0)
  223777. {
  223778. String name (getConnectedEndpointName (dest));
  223779. if (name.isEmpty())
  223780. name = "<error>";
  223781. s.add (name);
  223782. }
  223783. else
  223784. {
  223785. s.add ("<error>");
  223786. }
  223787. }
  223788. return s;
  223789. }
  223790. int MidiOutput::getDefaultDeviceIndex()
  223791. {
  223792. return 0;
  223793. }
  223794. static MIDIClientRef globalMidiClient;
  223795. static bool hasGlobalClientBeenCreated = false;
  223796. static bool makeSureClientExists()
  223797. {
  223798. if (! hasGlobalClientBeenCreated)
  223799. {
  223800. String name (T("JUCE"));
  223801. if (JUCEApplication::getInstance() != 0)
  223802. name = JUCEApplication::getInstance()->getApplicationName();
  223803. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  223804. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  223805. CFRelease (appName);
  223806. }
  223807. return hasGlobalClientBeenCreated;
  223808. }
  223809. struct MidiPortAndEndpoint
  223810. {
  223811. MIDIPortRef port;
  223812. MIDIEndpointRef endPoint;
  223813. };
  223814. MidiOutput* MidiOutput::openDevice (int index)
  223815. {
  223816. MidiOutput* mo = 0;
  223817. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  223818. {
  223819. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  223820. CFStringRef pname;
  223821. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  223822. {
  223823. log (T("CoreMidi - opening out: ") + PlatformUtilities::cfStringToJuceString (pname));
  223824. if (makeSureClientExists())
  223825. {
  223826. MIDIPortRef port;
  223827. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  223828. {
  223829. MidiPortAndEndpoint* mpe = new MidiPortAndEndpoint();
  223830. mpe->port = port;
  223831. mpe->endPoint = endPoint;
  223832. mo = new MidiOutput();
  223833. mo->internal = (void*)mpe;
  223834. }
  223835. }
  223836. CFRelease (pname);
  223837. }
  223838. }
  223839. return mo;
  223840. }
  223841. MidiOutput::~MidiOutput()
  223842. {
  223843. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  223844. MIDIPortDispose (mpe->port);
  223845. delete mpe;
  223846. }
  223847. void MidiOutput::reset()
  223848. {
  223849. }
  223850. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223851. {
  223852. return false;
  223853. }
  223854. void MidiOutput::setVolume (float leftVol, float rightVol)
  223855. {
  223856. }
  223857. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223858. {
  223859. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  223860. if (message.isSysEx())
  223861. {
  223862. const int maxPacketSize = 256;
  223863. int pos = 0, bytesLeft = message.getRawDataSize();
  223864. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  223865. MIDIPacketList* const packets = (MIDIPacketList*) juce_malloc (32 * numPackets + message.getRawDataSize());
  223866. packets->numPackets = numPackets;
  223867. MIDIPacket* p = packets->packet;
  223868. for (int i = 0; i < numPackets; ++i)
  223869. {
  223870. p->timeStamp = 0;
  223871. p->length = jmin (maxPacketSize, bytesLeft);
  223872. memcpy (p->data, message.getRawData() + pos, p->length);
  223873. pos += p->length;
  223874. bytesLeft -= p->length;
  223875. p = MIDIPacketNext (p);
  223876. }
  223877. MIDISend (mpe->port, mpe->endPoint, packets);
  223878. juce_free (packets);
  223879. }
  223880. else
  223881. {
  223882. MIDIPacketList packets;
  223883. packets.numPackets = 1;
  223884. packets.packet[0].timeStamp = 0;
  223885. packets.packet[0].length = message.getRawDataSize();
  223886. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  223887. MIDISend (mpe->port, mpe->endPoint, &packets);
  223888. }
  223889. }
  223890. const StringArray MidiInput::getDevices()
  223891. {
  223892. StringArray s;
  223893. const ItemCount num = MIDIGetNumberOfSources();
  223894. for (ItemCount i = 0; i < num; ++i)
  223895. {
  223896. MIDIEndpointRef source = MIDIGetSource (i);
  223897. if (source != 0)
  223898. {
  223899. String name (getConnectedEndpointName (source));
  223900. if (name.isEmpty())
  223901. name = "<error>";
  223902. s.add (name);
  223903. }
  223904. else
  223905. {
  223906. s.add ("<error>");
  223907. }
  223908. }
  223909. return s;
  223910. }
  223911. int MidiInput::getDefaultDeviceIndex()
  223912. {
  223913. return 0;
  223914. }
  223915. struct MidiPortAndCallback
  223916. {
  223917. MidiInput* input;
  223918. MIDIPortRef port;
  223919. MIDIEndpointRef endPoint;
  223920. MidiInputCallback* callback;
  223921. MemoryBlock pendingData;
  223922. int pendingBytes;
  223923. double pendingDataTime;
  223924. bool active;
  223925. };
  223926. static CriticalSection callbackLock;
  223927. static VoidArray activeCallbacks;
  223928. static void processSysex (MidiPortAndCallback* const mpe, const uint8*& d, int& size, const double time)
  223929. {
  223930. if (*d == 0xf0)
  223931. {
  223932. mpe->pendingBytes = 0;
  223933. mpe->pendingDataTime = time;
  223934. }
  223935. mpe->pendingData.ensureSize (mpe->pendingBytes + size, false);
  223936. uint8* totalMessage = (uint8*) mpe->pendingData.getData();
  223937. uint8* dest = totalMessage + mpe->pendingBytes;
  223938. while (size > 0)
  223939. {
  223940. if (mpe->pendingBytes > 0 && *d >= 0x80)
  223941. {
  223942. if (*d >= 0xfa || *d == 0xf8)
  223943. {
  223944. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (*d, time));
  223945. ++d;
  223946. --size;
  223947. }
  223948. else
  223949. {
  223950. if (*d == 0xf7)
  223951. {
  223952. *dest++ = *d++;
  223953. mpe->pendingBytes++;
  223954. --size;
  223955. }
  223956. break;
  223957. }
  223958. }
  223959. else
  223960. {
  223961. *dest++ = *d++;
  223962. mpe->pendingBytes++;
  223963. --size;
  223964. }
  223965. }
  223966. if (totalMessage [mpe->pendingBytes - 1] == 0xf7)
  223967. {
  223968. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (totalMessage,
  223969. mpe->pendingBytes,
  223970. mpe->pendingDataTime));
  223971. mpe->pendingBytes = 0;
  223972. }
  223973. else
  223974. {
  223975. mpe->callback->handlePartialSysexMessage (mpe->input,
  223976. totalMessage,
  223977. mpe->pendingBytes,
  223978. mpe->pendingDataTime);
  223979. }
  223980. }
  223981. static void midiInputProc (const MIDIPacketList* pktlist,
  223982. void* readProcRefCon,
  223983. void* srcConnRefCon)
  223984. {
  223985. double time = Time::getMillisecondCounterHiRes() * 0.001;
  223986. const double originalTime = time;
  223987. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) readProcRefCon;
  223988. const ScopedLock sl (callbackLock);
  223989. if (activeCallbacks.contains (mpe) && mpe->active)
  223990. {
  223991. const MIDIPacket* packet = &pktlist->packet[0];
  223992. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  223993. {
  223994. const uint8* d = (const uint8*) (packet->data);
  223995. int size = packet->length;
  223996. while (size > 0)
  223997. {
  223998. time = originalTime;
  223999. if (mpe->pendingBytes > 0 || d[0] == 0xf0)
  224000. {
  224001. processSysex (mpe, d, size, time);
  224002. }
  224003. else
  224004. {
  224005. int used = 0;
  224006. const MidiMessage m (d, size, used, 0, time);
  224007. if (used <= 0)
  224008. {
  224009. jassertfalse // malformed midi message
  224010. break;
  224011. }
  224012. else
  224013. {
  224014. mpe->callback->handleIncomingMidiMessage (mpe->input, m);
  224015. }
  224016. size -= used;
  224017. d += used;
  224018. }
  224019. }
  224020. packet = MIDIPacketNext (packet);
  224021. }
  224022. }
  224023. }
  224024. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  224025. {
  224026. MidiInput* mi = 0;
  224027. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  224028. {
  224029. MIDIEndpointRef endPoint = MIDIGetSource (index);
  224030. if (endPoint != 0)
  224031. {
  224032. CFStringRef pname;
  224033. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  224034. {
  224035. log (T("CoreMidi - opening inp: ") + PlatformUtilities::cfStringToJuceString (pname));
  224036. if (makeSureClientExists())
  224037. {
  224038. MIDIPortRef port;
  224039. MidiPortAndCallback* const mpe = new MidiPortAndCallback();
  224040. mpe->active = false;
  224041. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpe, &port)))
  224042. {
  224043. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  224044. {
  224045. mpe->port = port;
  224046. mpe->endPoint = endPoint;
  224047. mpe->callback = callback;
  224048. mpe->pendingBytes = 0;
  224049. mpe->pendingData.ensureSize (128);
  224050. mi = new MidiInput (getDevices() [index]);
  224051. mpe->input = mi;
  224052. mi->internal = (void*) mpe;
  224053. const ScopedLock sl (callbackLock);
  224054. activeCallbacks.add (mpe);
  224055. }
  224056. else
  224057. {
  224058. OK (MIDIPortDispose (port));
  224059. delete mpe;
  224060. }
  224061. }
  224062. else
  224063. {
  224064. delete mpe;
  224065. }
  224066. }
  224067. }
  224068. CFRelease (pname);
  224069. }
  224070. }
  224071. return mi;
  224072. }
  224073. MidiInput::MidiInput (const String& name_)
  224074. : name (name_)
  224075. {
  224076. }
  224077. MidiInput::~MidiInput()
  224078. {
  224079. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  224080. mpe->active = false;
  224081. callbackLock.enter();
  224082. activeCallbacks.removeValue (mpe);
  224083. callbackLock.exit();
  224084. OK (MIDIPortDisconnectSource (mpe->port, mpe->endPoint));
  224085. OK (MIDIPortDispose (mpe->port));
  224086. delete mpe;
  224087. }
  224088. void MidiInput::start()
  224089. {
  224090. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  224091. const ScopedLock sl (callbackLock);
  224092. mpe->active = true;
  224093. }
  224094. void MidiInput::stop()
  224095. {
  224096. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  224097. const ScopedLock sl (callbackLock);
  224098. mpe->active = false;
  224099. }
  224100. #undef log
  224101. #endif
  224102. /********* End of inlined file: juce_mac_CoreMidi.cpp *********/
  224103. /********* Start of inlined file: juce_mac_CameraDevice.mm *********/
  224104. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224105. // compiled on its own).
  224106. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME && JUCE_USE_CAMERA
  224107. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  224108. class QTCameraDeviceInteral;
  224109. END_JUCE_NAMESPACE
  224110. @interface QTCaptureCallbackDelegate : NSObject
  224111. {
  224112. @public
  224113. CameraDevice* owner;
  224114. QTCameraDeviceInteral* internal;
  224115. Time* firstRecordedTime;
  224116. }
  224117. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  224118. - (void) dealloc;
  224119. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  224120. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  224121. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  224122. fromConnection: (QTCaptureConnection*) connection;
  224123. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  224124. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  224125. fromConnection: (QTCaptureConnection*) connection;
  224126. @end
  224127. BEGIN_JUCE_NAMESPACE
  224128. class QTCameraDeviceInteral
  224129. {
  224130. public:
  224131. QTCameraDeviceInteral (CameraDevice* owner, int index)
  224132. {
  224133. const ScopedAutoReleasePool pool;
  224134. session = [[QTCaptureSession alloc] init];
  224135. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  224136. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  224137. input = 0;
  224138. fileOutput = 0;
  224139. imageOutput = 0;
  224140. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  224141. internalDev: this];
  224142. NSError* err = 0;
  224143. [device retain];
  224144. [device open: &err];
  224145. if (err == 0)
  224146. {
  224147. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  224148. [session addInput: input error: &err];
  224149. if (err == 0)
  224150. {
  224151. resetFile();
  224152. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  224153. [imageOutput setDelegate: callbackDelegate];
  224154. if (err == 0)
  224155. {
  224156. [session startRunning];
  224157. return;
  224158. }
  224159. }
  224160. }
  224161. openingError = nsStringToJuce ([err description]);
  224162. DBG (openingError);
  224163. }
  224164. ~QTCameraDeviceInteral()
  224165. {
  224166. [session stopRunning];
  224167. [session removeOutput: imageOutput];
  224168. [session release];
  224169. [input release];
  224170. [device release];
  224171. [fileOutput release];
  224172. [imageOutput release];
  224173. [callbackDelegate release];
  224174. }
  224175. void resetFile()
  224176. {
  224177. [session removeOutput: fileOutput];
  224178. [fileOutput release];
  224179. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  224180. [fileOutput setDelegate: callbackDelegate];
  224181. }
  224182. void addListener (CameraImageListener* listenerToAdd)
  224183. {
  224184. const ScopedLock sl (listenerLock);
  224185. if (listeners.size() == 0)
  224186. [session addOutput: imageOutput error: nil];
  224187. listeners.addIfNotAlreadyThere (listenerToAdd);
  224188. }
  224189. void removeListener (CameraImageListener* listenerToRemove)
  224190. {
  224191. const ScopedLock sl (listenerLock);
  224192. listeners.removeValue (listenerToRemove);
  224193. if (listeners.size() == 0)
  224194. [session removeOutput: imageOutput];
  224195. }
  224196. static void drawNSBitmapIntoJuceImage (Image& dest, NSBitmapImageRep* source)
  224197. {
  224198. const ScopedAutoReleasePool pool;
  224199. int lineStride, pixelStride;
  224200. uint8* pixels = dest.lockPixelDataReadWrite (0, 0, dest.getWidth(), dest.getHeight(),
  224201. lineStride, pixelStride);
  224202. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  224203. initWithBitmapDataPlanes: &pixels
  224204. pixelsWide: dest.getWidth()
  224205. pixelsHigh: dest.getHeight()
  224206. bitsPerSample: 8
  224207. samplesPerPixel: pixelStride
  224208. hasAlpha: dest.hasAlphaChannel()
  224209. isPlanar: NO
  224210. colorSpaceName: NSCalibratedRGBColorSpace
  224211. bitmapFormat: (NSBitmapFormat) 0
  224212. bytesPerRow: lineStride
  224213. bitsPerPixel: pixelStride * 8];
  224214. [NSGraphicsContext saveGraphicsState];
  224215. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithBitmapImageRep: rep]];
  224216. [source drawAtPoint: NSZeroPoint];
  224217. [[NSGraphicsContext currentContext] flushGraphics];
  224218. [NSGraphicsContext restoreGraphicsState];
  224219. uint8* start = pixels;
  224220. for (int h = dest.getHeight(); --h >= 0;)
  224221. {
  224222. uint8* p = start;
  224223. start += lineStride;
  224224. for (int i = dest.getWidth(); --i >= 0;)
  224225. {
  224226. #if JUCE_BIG_ENDIAN
  224227. const uint8 oldp3 = p[3];
  224228. const uint8 oldp1 = p[1];
  224229. p[3] = p[0];
  224230. p[0] = oldp1;
  224231. p[1] = p[2];
  224232. p[2] = oldp3;
  224233. #else
  224234. const uint8 oldp0 = p[0];
  224235. p[0] = p[2];
  224236. p[2] = oldp0;
  224237. #endif
  224238. p += pixelStride;
  224239. }
  224240. }
  224241. dest.releasePixelDataReadWrite (pixels);
  224242. }
  224243. void callListeners (NSBitmapImageRep* bitmap)
  224244. {
  224245. Image image (Image::ARGB, [bitmap size].width, [bitmap size].height, false);
  224246. drawNSBitmapIntoJuceImage (image, bitmap);
  224247. const ScopedLock sl (listenerLock);
  224248. for (int i = listeners.size(); --i >= 0;)
  224249. {
  224250. CameraImageListener* l = (CameraImageListener*) listeners[i];
  224251. if (l != 0)
  224252. l->imageReceived (image);
  224253. }
  224254. }
  224255. QTCaptureDevice* device;
  224256. QTCaptureDeviceInput* input;
  224257. QTCaptureSession* session;
  224258. QTCaptureMovieFileOutput* fileOutput;
  224259. QTCaptureDecompressedVideoOutput* imageOutput;
  224260. QTCaptureCallbackDelegate* callbackDelegate;
  224261. String openingError;
  224262. VoidArray listeners;
  224263. CriticalSection listenerLock;
  224264. };
  224265. END_JUCE_NAMESPACE
  224266. @implementation QTCaptureCallbackDelegate
  224267. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  224268. internalDev: (QTCameraDeviceInteral*) d
  224269. {
  224270. [super init];
  224271. owner = owner_;
  224272. internal = d;
  224273. firstRecordedTime = 0;
  224274. return self;
  224275. }
  224276. - (void) dealloc
  224277. {
  224278. delete firstRecordedTime;
  224279. [super dealloc];
  224280. }
  224281. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  224282. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  224283. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  224284. fromConnection: (QTCaptureConnection*) connection
  224285. {
  224286. const ScopedAutoReleasePool pool;
  224287. CIImage* image = [CIImage imageWithCVImageBuffer: videoFrame];
  224288. NSBitmapImageRep* bitmap = [[[NSBitmapImageRep alloc] initWithCIImage: image] autorelease];
  224289. internal->callListeners (bitmap);
  224290. }
  224291. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  224292. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  224293. fromConnection: (QTCaptureConnection*) connection
  224294. {
  224295. if (firstRecordedTime == 0)
  224296. firstRecordedTime = new Time (Time::getCurrentTime());
  224297. }
  224298. @end
  224299. BEGIN_JUCE_NAMESPACE
  224300. class QTCaptureViewerComp : public NSViewComponent
  224301. {
  224302. public:
  224303. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  224304. {
  224305. const ScopedAutoReleasePool pool;
  224306. captureView = [[QTCaptureView alloc] init];
  224307. [captureView setCaptureSession: internal->session];
  224308. setSize (640, 480); // xxx need to somehow get the movie size - how?
  224309. setView (captureView);
  224310. }
  224311. ~QTCaptureViewerComp()
  224312. {
  224313. setView (0);
  224314. [captureView setCaptureSession: nil];
  224315. [captureView release];
  224316. }
  224317. QTCaptureView* captureView;
  224318. };
  224319. CameraDevice::CameraDevice (const String& name_, int index)
  224320. : name (name_)
  224321. {
  224322. isRecording = false;
  224323. QTCameraDeviceInteral* d = new QTCameraDeviceInteral (this, index);
  224324. internal = d;
  224325. }
  224326. CameraDevice::~CameraDevice()
  224327. {
  224328. stopRecording();
  224329. delete (QTCameraDeviceInteral*) internal;
  224330. internal = 0;
  224331. }
  224332. Component* CameraDevice::createViewerComponent()
  224333. {
  224334. return new QTCaptureViewerComp (this, (QTCameraDeviceInteral*) internal);
  224335. }
  224336. const String CameraDevice::getFileExtension()
  224337. {
  224338. return ".mov";
  224339. }
  224340. void CameraDevice::startRecordingToFile (const File& file)
  224341. {
  224342. stopRecording();
  224343. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  224344. deleteAndZero (d->callbackDelegate->firstRecordedTime);
  224345. file.deleteFile();
  224346. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  224347. [d->session addOutput: d->fileOutput error: nil];
  224348. isRecording = true;
  224349. }
  224350. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  224351. {
  224352. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  224353. if (d->callbackDelegate->firstRecordedTime != 0)
  224354. return *d->callbackDelegate->firstRecordedTime;
  224355. return Time();
  224356. }
  224357. void CameraDevice::stopRecording()
  224358. {
  224359. if (isRecording)
  224360. {
  224361. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  224362. d->resetFile();
  224363. isRecording = false;
  224364. }
  224365. }
  224366. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  224367. {
  224368. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  224369. if (listenerToAdd != 0)
  224370. d->addListener (listenerToAdd);
  224371. }
  224372. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  224373. {
  224374. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  224375. if (listenerToRemove != 0)
  224376. d->removeListener (listenerToRemove);
  224377. }
  224378. const StringArray CameraDevice::getAvailableDevices()
  224379. {
  224380. const ScopedAutoReleasePool pool;
  224381. StringArray results;
  224382. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  224383. for (int i = 0; i < [devs count]; ++i)
  224384. {
  224385. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  224386. results.add (nsStringToJuce ([dev localizedDisplayName]));
  224387. }
  224388. return results;
  224389. }
  224390. CameraDevice* CameraDevice::openDevice (int index,
  224391. int minWidth, int minHeight,
  224392. int maxWidth, int maxHeight)
  224393. {
  224394. CameraDevice* d = new CameraDevice (getAvailableDevices() [index], index);
  224395. if (((QTCameraDeviceInteral*) (d->internal))->openingError.isEmpty())
  224396. return d;
  224397. delete d;
  224398. return 0;
  224399. }
  224400. #endif
  224401. /********* End of inlined file: juce_mac_CameraDevice.mm *********/
  224402. #endif
  224403. END_JUCE_NAMESPACE
  224404. /********* End of inlined file: juce_mac_NativeCode.mm *********/
  224405. #endif